# Demathpy

A Python library for parsing and safely evaluating symbolic Ordinary and Partial Differential Equations (ODEs/PDEs) on numerical grids.

This repository provides:

- A lightweight **symbol normalizer** that converts human-readable mathematical notation into valid Python expressions.
- A **secure evaluation engine** that evaluates PDE/ODE right-hand sides on NumPy grids without using raw `eval` on untrusted input.
- Built-in support for common differential operators and vector calculus notation.

### Key Features

#### 1. Symbol Normalization

The parser supports Unicode and mathematical shorthand, including:

- Greek letters: `α, β, γ, λ, ε, φ, θ` → `alpha, beta, gamma, lam, epsilon, phi, theta`
- Powers: `u², v³` → `u**2, v**3`
- Implicit multiplication:  
  - `αu` → `alpha*u`  
  - `2u` → `2*u`  
  - `(u+1)(v+1)` → `(u+1)*(v+1)`
- Absolute values: `|u|` → `abs(u)`
- Common functions:  
  `sin, cos, tan, exp, log, tanh, sech, sign, sqrt`

#### 2. Differential Operator Support

The parser recognizes and evaluates:

- First derivatives:
  - `du/dt`, `u_t`
- Second derivatives:
  - `dxx(u)`, `dzz(u)`
- Laplacian:
  - `∇²u`, `lap(u)`
- Gradient:
  - `∇u`, `grad(u)`
- Divergence:
  - `∇·(A)`, `div(A)`

These are mapped to finite-difference operators implemented in NumPy.

#### 3. PDE / ODE Parsing

The library provides:

- `parse_pde(equation: str)`  
  Parses a PDE string and returns `(lhs_variable, rhs_expression)`.

- `evaluate_rhs(rhs: str, grids: dict, constants: dict, grid_dx: float)`  
  Safely evaluates the right-hand side on NumPy arrays representing fields and parameters.

Supports equations such as:

```text
∂T/∂t = α ∇²T - σ T
u_t = D dxx(u) + f(u)
∂φ/∂t = ∇·((1 + T²) ∇φ)
```
#### 4. Secure Evaluation Environment
Only a restricted set of functions and operators are exposed.
No access to Python builtins, file I/O, or unsafe functions.
All variables must come from:
grids: NumPy arrays for fields (u, T, phi, etc.)
constants: scalar parameters (alpha, beta, lambda, etc.)
#### 5. Coordinate-Aware PDEs
The evaluator automatically provides spatial coordinate grids:
x, z as NumPy arrays derived from grid shape and spacing.
This enables anisotropic and spatially varying coefficients such as:
``` α x dxx(T) + α z dzz(T)```
Typical Use:

```text 
from pde import parse_pde, evaluate_rhs

lhs, rhs = parse_pde("∂T/∂t = α ∇²T - σ T")

result = evaluate_rhs(
    rhs,
    grids={"T": T_grid},
    constants={"alpha": 0.1, "sigma": 0.01},
    grid_dx=0.01
)
```

#### 6. Purpose
This project is intended as a safe mathematical expression parser for:
Scientific computing
PDE/ODE solvers
Physics and engineering simulations
Educational or sandboxed equation evaluation