demathpy 0.0.2__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,207 @@
1
+ Metadata-Version: 2.4
2
+ Name: demathpy
3
+ Version: 0.1.1
4
+ Summary: PDE/ODE math backend
5
+ Author: Misekai
6
+ Author-email: Misekai <mcore-us@misekai.net>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy>=1.24.0
10
+ Requires-Dist: sympy>=1.12.0
11
+ Requires-Dist: typing>=3.10.0.0
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+
15
+ # Demathpy
16
+
17
+ A Python library for parsing and safely evaluating symbolic Ordinary and Partial Differential Equations (ODEs/PDEs) on numerical grids.
18
+
19
+ This repository provides:
20
+ - A class-based `PDE` solver (`from demathpy import PDE`) for running simulations.
21
+ - A lightweight **symbol normalizer** that converts human-readable mathematical notation into valid Python expressions.
22
+ - Equation-based Boundary Conditions and Initial Conditions.
23
+ - Built-in support for common differential operators and vector calculus notation using Finite Differences.
24
+
25
+ ### Key Features
26
+
27
+ #### 1. The PDE Class
28
+
29
+ The core of the library is the `PDE` class. It manages the grid state, parsing, and time-stepping.
30
+
31
+ ```python
32
+ from demathpy import PDE
33
+ import numpy as np
34
+
35
+ # Define a Heat Equation: du/dt = Laplacian(u)
36
+ p = PDE("du/dt = lap(u)", space_axis=["x", "y"])
37
+
38
+ # Configure the grid
39
+ p.init_grid(width=100, height=100, dx=0.5)
40
+
41
+ # Set Initial Conditions using equations
42
+ p.initial = ["u = exp(-(x-25)**2 - (y-25)**2)"]
43
+ p.set_initial_state()
44
+
45
+ # Set Boundary Conditions using equations
46
+ # Format: "axis(coord) = value" or "axis=coord = value"
47
+ p.boundry = [
48
+ "x=0 = 1.0", # Left boundary (x=0) is fixed at 1.0
49
+ "x=100 = 0.0", # Right boundary (x=100) is fixed at 0.0
50
+ "y=0 = 0.0", # Bottom boundary is 0.0
51
+ "periodic" # Other unset boundaries (y=100) default to periodic or 0
52
+ ]
53
+
54
+ # Run simulation
55
+ for _ in range(100):
56
+ p.step(dt=0.01)
57
+
58
+ print(p.u.mean())
59
+ ```
60
+
61
+ #### 2. Equation-Based Configuration
62
+
63
+ You can configure boundaries and initial states using string equations instead of manual array manipulation.
64
+
65
+ **Boundary Conditions (`p.boundry` list):**
66
+ - **Dirichlet:** `x=0 = 1.0` (Fixes value at boundary)
67
+ - **Neumann:** `dx(u) = 0` (Not fully exposed yet, currently defaults to Dirichlet logic if value provided).
68
+ - **Periodic:** Use `periodic` keyword or leave empty for default periodic behavior (if implemented).
69
+
70
+ **Initial Conditions (`p.initial` list):**
71
+ - **Scalar:** `u = sin(x) * cos(y)`
72
+ - **Vector Components:** `ux = 1.0`, `uy = 0.0` (if `p.u_shape = ["ux", "uy"]`)
73
+
74
+ #### 3. Vector Fields
75
+
76
+ The solver supports vector-valued PDEs (e.g., Navier-Stokes, Reaction-Diffusion systems).
77
+
78
+ ```python
79
+ # 2D Advection: du/dt = - (u · ∇) u
80
+ p = PDE("du/dt = -advect(u, u)", space_axis=["x", "y"])
81
+ p.u_shape = ["ux", "uy"] # Define component names
82
+ p.init_grid(width=50, height=50, dx=1.0)
83
+
84
+ # Initialize Vortex
85
+ p.initial = [
86
+ "ux = -sin(y)",
87
+ "uy = sin(x)"
88
+ ]
89
+ p.set_initial_state()
90
+ ```
91
+
92
+ ### Supported Operators
93
+
94
+ The parser recognizes and maps these to NumPy finite difference functions:
95
+
96
+ - **Derivatives:** `du/dt`, `dx(u)`, `dy(u)`, `dz(u)`
97
+ - **Second Derivatives:** `dxx(u)`, `dzz(u)`
98
+ - **Laplacian:** `lap(u)` or `∇²u`
99
+ - **Gradient:** `grad(u)` or `∇u` (Returns vector)
100
+ - **Divergence:** `div(u)` or `∇·u` (Expects vector input)
101
+ - **Advection:** `advect(velocity, field)` -> `(velocity · ∇) field`
102
+ - **Math Functions:** `sin, cos, exp, log, abs, sqrt, tanh` ...
103
+
104
+ ### Symbol Normalization
105
+
106
+ The parser supports Unicode and mathematical shorthand:
107
+ - `α, β, γ` → `alpha, beta, gamma`
108
+ - `u²` → `u**2`
109
+ - `|u|` → `abs(u)`
110
+
111
+ ### Workflow & Visualization
112
+
113
+ To integrate `Demathpy` into visualization software or interactive notebooks, you can use the `get_grid()` method to probe the field dynamics without advancing the simulation time.
114
+
115
+ #### Visualization Step-by-Step
116
+
117
+ 1. **Initialize**:
118
+ ```python
119
+ p = PDE("du/dt = lap(u) - u**3 + u", space_axis=["x", "y"])
120
+ p.init_grid(width=20, height=20, dx=0.5)
121
+ p.initial = ["u = 0.1 * sin(x)"]
122
+ p.boundry = ["periodic"]
123
+ p.set_initial_state()
124
+ ```
125
+
126
+ 2. **Probe the Vector Field (du/dt)**:
127
+ Use `get_grid(dt=0)` to get the instantaneous rate of change. This is useful for visualizing flow fields or phase plots.
128
+ ```python
129
+ # Get Rate of Change (RHS of PDE)
130
+ du_dt = p.get_grid(dt=0)
131
+
132
+ # Or calculate the hypothetical next step delta
133
+ delta_u = p.get_grid(dt=0.01)
134
+ ```
135
+
136
+ 3. **Predict on Arbitrary States**:
137
+ You can evaluate the PDE on a hypothetical state `u_test` without updating the solver's internal state. This is useful for drawing vector fields in phase space.
138
+ ```python
139
+ # Create a test state
140
+ test_u = np.sin(p.u)
141
+
142
+ # Calculate how the PDE would evolve this state
143
+ # Returns the rate of change for the test state
144
+ response = p.get_grid(u_state=test_u, dt=0)
145
+ ```
146
+
147
+ 4. **Run Simulation Loops**:
148
+ ```python
149
+ import matplotlib.pyplot as plt
150
+
151
+ for i in range(100):
152
+ p.step(dt=0.01)
153
+ if i % 10 == 0:
154
+ plt.imshow(p.u) # Visualization logic
155
+ # plt.show()
156
+ ```
157
+
158
+ ### The ODE Class
159
+
160
+ Demathpy also efficiently solves Ordinary Differential Equations (ODEs) where the state depends only on time $t$. The API is identical to the PDE class.
161
+
162
+ ```python
163
+ from demathpy import ODE
164
+
165
+ # 1. EXPONENTIAL DECAY
166
+ # dy/dt = -y
167
+ o = ODE("dy/dt = -y", u_shape=["y"])
168
+ o.initial = ["y = 1.0"]
169
+ o.init_state(shape=(1,)) # scalar system
170
+ o.set_initial_state()
171
+
172
+ for _ in range(100):
173
+ o.step(dt=0.01)
174
+ print(o.u) # Should be close to exp(-1)
175
+
176
+ # 2. VECTOR SYSTEMS (Predator-Prey)
177
+ # du/dt = u - u*v
178
+ # dv/dt = u*v - v
179
+ pp = ODE("du/dt = [u[0] - u[0]*u[1], u[0]*u[1] - u[1]]", u_shape=["u", "v"])
180
+ pp.initial = ["u = 1.1", "v = 1.0"]
181
+ pp.init_state(shape=(1,)) # Single ecosystem
182
+ pp.set_initial_state()
183
+
184
+ pp.step(dt=0.1)
185
+
186
+ # 3. BATCHED EXECUTION
187
+ # Simulating 1000 identical particles with different initial conditions
188
+ particles = ODE("dx/dt = -x + noise") # noise not impl by default but external vars work
189
+ # Or just decay
190
+ batch = ODE("dy/dt = -y")
191
+ batch.init_state(shape=(1000,)) # 1000 systems
192
+ # Set random initial states directly (or use equation if supported)
193
+ import numpy as np
194
+ batch.u[:] = np.random.rand(1000)
195
+
196
+ batch.step(0.1)
197
+ ```
198
+
199
+ **Key ODE Features:**
200
+ - **Equation Parsing:** Supports `dy/dt`, `d^2y/dt^2`, vector syntax `[a, b]`.
201
+ - **Initialization:** Use `init_state(shape=...)` where shape defines the batch size (independent systems).
202
+ - **Probing:** `get_grid(u_state=..., dt=0)` works exactly like PDE for generating phase portraits (return vector field at state).
203
+ - **Functions:** Includes `sin, cos, exp, step, heaviside, sign, abs` ...
204
+
205
+ ### License
206
+
207
+ MIT
@@ -0,0 +1,193 @@
1
+ # Demathpy
2
+
3
+ A Python library for parsing and safely evaluating symbolic Ordinary and Partial Differential Equations (ODEs/PDEs) on numerical grids.
4
+
5
+ This repository provides:
6
+ - A class-based `PDE` solver (`from demathpy import PDE`) for running simulations.
7
+ - A lightweight **symbol normalizer** that converts human-readable mathematical notation into valid Python expressions.
8
+ - Equation-based Boundary Conditions and Initial Conditions.
9
+ - Built-in support for common differential operators and vector calculus notation using Finite Differences.
10
+
11
+ ### Key Features
12
+
13
+ #### 1. The PDE Class
14
+
15
+ The core of the library is the `PDE` class. It manages the grid state, parsing, and time-stepping.
16
+
17
+ ```python
18
+ from demathpy import PDE
19
+ import numpy as np
20
+
21
+ # Define a Heat Equation: du/dt = Laplacian(u)
22
+ p = PDE("du/dt = lap(u)", space_axis=["x", "y"])
23
+
24
+ # Configure the grid
25
+ p.init_grid(width=100, height=100, dx=0.5)
26
+
27
+ # Set Initial Conditions using equations
28
+ p.initial = ["u = exp(-(x-25)**2 - (y-25)**2)"]
29
+ p.set_initial_state()
30
+
31
+ # Set Boundary Conditions using equations
32
+ # Format: "axis(coord) = value" or "axis=coord = value"
33
+ p.boundry = [
34
+ "x=0 = 1.0", # Left boundary (x=0) is fixed at 1.0
35
+ "x=100 = 0.0", # Right boundary (x=100) is fixed at 0.0
36
+ "y=0 = 0.0", # Bottom boundary is 0.0
37
+ "periodic" # Other unset boundaries (y=100) default to periodic or 0
38
+ ]
39
+
40
+ # Run simulation
41
+ for _ in range(100):
42
+ p.step(dt=0.01)
43
+
44
+ print(p.u.mean())
45
+ ```
46
+
47
+ #### 2. Equation-Based Configuration
48
+
49
+ You can configure boundaries and initial states using string equations instead of manual array manipulation.
50
+
51
+ **Boundary Conditions (`p.boundry` list):**
52
+ - **Dirichlet:** `x=0 = 1.0` (Fixes value at boundary)
53
+ - **Neumann:** `dx(u) = 0` (Not fully exposed yet, currently defaults to Dirichlet logic if value provided).
54
+ - **Periodic:** Use `periodic` keyword or leave empty for default periodic behavior (if implemented).
55
+
56
+ **Initial Conditions (`p.initial` list):**
57
+ - **Scalar:** `u = sin(x) * cos(y)`
58
+ - **Vector Components:** `ux = 1.0`, `uy = 0.0` (if `p.u_shape = ["ux", "uy"]`)
59
+
60
+ #### 3. Vector Fields
61
+
62
+ The solver supports vector-valued PDEs (e.g., Navier-Stokes, Reaction-Diffusion systems).
63
+
64
+ ```python
65
+ # 2D Advection: du/dt = - (u · ∇) u
66
+ p = PDE("du/dt = -advect(u, u)", space_axis=["x", "y"])
67
+ p.u_shape = ["ux", "uy"] # Define component names
68
+ p.init_grid(width=50, height=50, dx=1.0)
69
+
70
+ # Initialize Vortex
71
+ p.initial = [
72
+ "ux = -sin(y)",
73
+ "uy = sin(x)"
74
+ ]
75
+ p.set_initial_state()
76
+ ```
77
+
78
+ ### Supported Operators
79
+
80
+ The parser recognizes and maps these to NumPy finite difference functions:
81
+
82
+ - **Derivatives:** `du/dt`, `dx(u)`, `dy(u)`, `dz(u)`
83
+ - **Second Derivatives:** `dxx(u)`, `dzz(u)`
84
+ - **Laplacian:** `lap(u)` or `∇²u`
85
+ - **Gradient:** `grad(u)` or `∇u` (Returns vector)
86
+ - **Divergence:** `div(u)` or `∇·u` (Expects vector input)
87
+ - **Advection:** `advect(velocity, field)` -> `(velocity · ∇) field`
88
+ - **Math Functions:** `sin, cos, exp, log, abs, sqrt, tanh` ...
89
+
90
+ ### Symbol Normalization
91
+
92
+ The parser supports Unicode and mathematical shorthand:
93
+ - `α, β, γ` → `alpha, beta, gamma`
94
+ - `u²` → `u**2`
95
+ - `|u|` → `abs(u)`
96
+
97
+ ### Workflow & Visualization
98
+
99
+ To integrate `Demathpy` into visualization software or interactive notebooks, you can use the `get_grid()` method to probe the field dynamics without advancing the simulation time.
100
+
101
+ #### Visualization Step-by-Step
102
+
103
+ 1. **Initialize**:
104
+ ```python
105
+ p = PDE("du/dt = lap(u) - u**3 + u", space_axis=["x", "y"])
106
+ p.init_grid(width=20, height=20, dx=0.5)
107
+ p.initial = ["u = 0.1 * sin(x)"]
108
+ p.boundry = ["periodic"]
109
+ p.set_initial_state()
110
+ ```
111
+
112
+ 2. **Probe the Vector Field (du/dt)**:
113
+ Use `get_grid(dt=0)` to get the instantaneous rate of change. This is useful for visualizing flow fields or phase plots.
114
+ ```python
115
+ # Get Rate of Change (RHS of PDE)
116
+ du_dt = p.get_grid(dt=0)
117
+
118
+ # Or calculate the hypothetical next step delta
119
+ delta_u = p.get_grid(dt=0.01)
120
+ ```
121
+
122
+ 3. **Predict on Arbitrary States**:
123
+ You can evaluate the PDE on a hypothetical state `u_test` without updating the solver's internal state. This is useful for drawing vector fields in phase space.
124
+ ```python
125
+ # Create a test state
126
+ test_u = np.sin(p.u)
127
+
128
+ # Calculate how the PDE would evolve this state
129
+ # Returns the rate of change for the test state
130
+ response = p.get_grid(u_state=test_u, dt=0)
131
+ ```
132
+
133
+ 4. **Run Simulation Loops**:
134
+ ```python
135
+ import matplotlib.pyplot as plt
136
+
137
+ for i in range(100):
138
+ p.step(dt=0.01)
139
+ if i % 10 == 0:
140
+ plt.imshow(p.u) # Visualization logic
141
+ # plt.show()
142
+ ```
143
+
144
+ ### The ODE Class
145
+
146
+ Demathpy also efficiently solves Ordinary Differential Equations (ODEs) where the state depends only on time $t$. The API is identical to the PDE class.
147
+
148
+ ```python
149
+ from demathpy import ODE
150
+
151
+ # 1. EXPONENTIAL DECAY
152
+ # dy/dt = -y
153
+ o = ODE("dy/dt = -y", u_shape=["y"])
154
+ o.initial = ["y = 1.0"]
155
+ o.init_state(shape=(1,)) # scalar system
156
+ o.set_initial_state()
157
+
158
+ for _ in range(100):
159
+ o.step(dt=0.01)
160
+ print(o.u) # Should be close to exp(-1)
161
+
162
+ # 2. VECTOR SYSTEMS (Predator-Prey)
163
+ # du/dt = u - u*v
164
+ # dv/dt = u*v - v
165
+ pp = ODE("du/dt = [u[0] - u[0]*u[1], u[0]*u[1] - u[1]]", u_shape=["u", "v"])
166
+ pp.initial = ["u = 1.1", "v = 1.0"]
167
+ pp.init_state(shape=(1,)) # Single ecosystem
168
+ pp.set_initial_state()
169
+
170
+ pp.step(dt=0.1)
171
+
172
+ # 3. BATCHED EXECUTION
173
+ # Simulating 1000 identical particles with different initial conditions
174
+ particles = ODE("dx/dt = -x + noise") # noise not impl by default but external vars work
175
+ # Or just decay
176
+ batch = ODE("dy/dt = -y")
177
+ batch.init_state(shape=(1000,)) # 1000 systems
178
+ # Set random initial states directly (or use equation if supported)
179
+ import numpy as np
180
+ batch.u[:] = np.random.rand(1000)
181
+
182
+ batch.step(0.1)
183
+ ```
184
+
185
+ **Key ODE Features:**
186
+ - **Equation Parsing:** Supports `dy/dt`, `d^2y/dt^2`, vector syntax `[a, b]`.
187
+ - **Initialization:** Use `init_state(shape=...)` where shape defines the batch size (independent systems).
188
+ - **Probing:** `get_grid(u_state=..., dt=0)` works exactly like PDE for generating phase portraits (return vector field at state).
189
+ - **Functions:** Includes `sin, cos, exp, step, heaviside, sign, abs` ...
190
+
191
+ ### License
192
+
193
+ MIT
@@ -1,7 +1,7 @@
1
1
 
2
2
  [project]
3
3
  name = "demathpy"
4
- version = "0.0.2"
4
+ version = "0.1.1"
5
5
  authors = [
6
6
  { name="Misekai", email="mcore-us@misekai.net" },
7
7
  ]
@@ -0,0 +1,23 @@
1
+ """demathpy: PDE/ODE math backend for rde-core."""
2
+
3
+ from .symbols import normalize_symbols, normalize_lhs
4
+ from .pde import (
5
+ PDE,
6
+ normalize_pde,
7
+ init_grid,
8
+ parse_pde,
9
+ step_pdes,
10
+ )
11
+ from .ode import ODE, parse_ode
12
+
13
+ __all__ = [
14
+ "PDE",
15
+ "ODE",
16
+ "normalize_symbols",
17
+ "normalize_lhs",
18
+ "normalize_pde",
19
+ "init_grid",
20
+ "parse_pde",
21
+ "step_pdes",
22
+ "parse_ode",
23
+ ]