numODEsolver 2.0.2__py3-none-any.whl → 3.0__py3-none-any.whl

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.
numODEsolver/solver.py CHANGED
@@ -1,4 +1,5 @@
1
1
  from scipy.interpolate import interp1d
2
+ import re
2
3
  import numpy as np
3
4
  from asteval import Interpreter
4
5
 
@@ -8,20 +9,30 @@ from asteval import Interpreter
8
9
  class Solver:
9
10
  def __init__(self):
10
11
  self.aeval = Interpreter()
12
+ self.aeval.symtable.pop("open", None)
11
13
  def get_function(self, func):
12
- func = func.lower()
13
- if not "y'" in func:
14
- f = self.aeval(f"lambda x,y: {func}")
15
- return f
16
- else:
17
- func = func.replace("y'","dy")
18
- f = self.aeval(f"lambda x,y,dy: {func}")
19
- return f
20
-
21
- def euler_2order(self,f,x0,y0,dy0,n,bound):
14
+ expr = func.lower().replace("y'", "dy")
15
+ f = self.aeval(f"lambda x, y, dy=0: {expr}")
16
+ if self.aeval.error or not callable(f):
17
+ msg = self.aeval.error[0].get_error() if self.aeval.error else "error"
18
+ self.aeval.error = []
19
+ raise ValueError(f"Could not parse function {func!r}: {msg}")
20
+
21
+ def wrapped(x, y, dy=0):
22
+ return f(x, y, dy)
23
+ # order 2 if the expression depends on y' (dy), otherwise order 1
24
+ wrapped.order = 2 if re.search(r"\bdy\b", expr) else 1
25
+ return wrapped
26
+
27
+ @staticmethod
28
+ def _check_first_order(f):
29
+ if getattr(f, "order", 1) == 2:
30
+ raise ValueError("Function contains y' – use euler_2order or rk4_2order instead.")
31
+
32
+ def euler_2order(self,f,x0,y0,dy0,n,bound): # euler cromer
22
33
  if n <= 0:
23
34
  raise ValueError("n must be greater than zero.")
24
- elif x0 > bound:
35
+ elif x0 >= bound:
25
36
  raise ValueError("initial condition must be < than the input bound!")
26
37
  vals = np.zeros((n+1,3))
27
38
  vals[0] = [x0,y0,dy0]
@@ -31,16 +42,17 @@ class Solver:
31
42
 
32
43
  dy_d = dy + h*f(x,y,dy)
33
44
  y_d = y + h * dy_d
34
- x_d = x + h
45
+ x_d = x0 + (i+1)*h
35
46
  vals[i+1] = [x_d,y_d,dy_d]
36
47
 
37
48
  return vals
38
49
 
39
50
  def euler_1order(self,f,x0,y0,n,bound):
51
+ self._check_first_order(f)
40
52
  if n <= 0:
41
53
  raise ValueError("n must be greater than zero.")
42
- elif x0 > bound:
43
- raise ValueError("initial condition must be < than the inpunt bound!")
54
+ elif x0 >= bound:
55
+ raise ValueError("initial condition must be < than the input bound!")
44
56
  vals = np.zeros((n+1, 2))
45
57
  vals[0] = [x0,y0]
46
58
  h = (bound-x0)/n
@@ -53,10 +65,11 @@ class Solver:
53
65
  return vals
54
66
 
55
67
  def rk4_1order(self,f,x0,y0,n,bound):
68
+ self._check_first_order(f)
56
69
  if n <= 0:
57
70
  raise ValueError("n must be greater than zero.")
58
- elif x0 > bound:
59
- raise ValueError("initial condition must be < than the inpunt bound!")
71
+ elif x0 >= bound:
72
+ raise ValueError("initial condition must be < than the input bound!")
60
73
  vals = np.zeros((n+1,2))
61
74
  vals[0] = [x0,y0]
62
75
  h = (bound-x0) / n
@@ -71,9 +84,40 @@ class Solver:
71
84
  x_d = x0 + (i+1)*h
72
85
  y_d = y + h * (k1+2*k2+2*k3+k4)/6
73
86
  vals[i+1] = [x_d,y_d]
74
-
87
+
88
+ return vals
89
+
90
+ # y'' = f(x,y,y') is rewritten as a system of two first-order ODEs:
91
+ # y' = v, v' = f(x,y,v)
92
+ # and both equations are advanced together with classical RK4.
93
+ def rk4_2order(self,f,x0,y0,dy0,n,bound):
94
+ if n <= 0:
95
+ raise ValueError("n must be greater than zero.")
96
+ elif x0 >= bound:
97
+ raise ValueError("initial condition must be < than the input bound!")
98
+ vals = np.zeros((n+1,3))
99
+ vals[0] = [x0,y0,dy0]
100
+ h = (bound-x0) / n
101
+ for i in range(n):
102
+ x,y,v = vals[i]
103
+
104
+ # k = slope of y (= v), l = slope of v (= f)
105
+ k1 = v
106
+ l1 = f(x, y, v)
107
+ k2 = v + h/2*l1
108
+ l2 = f(x+h/2, y+h/2*k1, v+h/2*l1)
109
+ k3 = v + h/2*l2
110
+ l3 = f(x+h/2, y+h/2*k2, v+h/2*l2)
111
+ k4 = v + h*l3
112
+ l4 = f(x+h, y+h*k3, v+h*l3)
113
+
114
+ x_d = x0 + (i+1)*h
115
+ y_d = y + h * (k1+2*k2+2*k3+k4)/6
116
+ v_d = v + h * (l1+2*l2+2*l3+l4)/6
117
+ vals[i+1] = [x_d,y_d,v_d]
118
+
75
119
  return vals
76
-
120
+
77
121
  # You can adjust the decimal places, note that rk4 is more accurate
78
122
  def get_value(self,data,val,dec):
79
123
  x_vals = data[:,0]
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.4
2
+ Name: numODEsolver
3
+ Version: 3.0
4
+ Summary: Tool that solves ODE's numerically. Written in Python.
5
+ Home-page: https://github.com/lukasnf/Numerical-ODE-Solver
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Operating System :: OS Independent
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: numpy
13
+ Requires-Dist: asteval
14
+ Requires-Dist: scipy
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: home-page
19
+ Dynamic: license-file
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # numODEsolver
25
+
26
+ ![PyPI](https://img.shields.io/pypi/v/numODEsolver)
27
+ ![Python](https://img.shields.io/pypi/pyversions/numODEsolver)
28
+
29
+ A lightweight Python package for solving first- and second-order ordinary differential equations (ODEs) numerically, using Euler-type methods or the classical fourth-order Runge–Kutta method (RK4).
30
+
31
+ ## Methods
32
+
33
+ | Solver | ODE | Method | Global error |
34
+ | :--- | :--- | :--- | :--- |
35
+ | `euler_1order` | y' = f(x, y) | Explicit Euler | ∝ h |
36
+ | `rk4_1order` | y' = f(x, y) | Classical RK4 | ∝ h⁴ |
37
+ | `euler_2order` | y'' = f(x, y, y') | Semi-implicit Euler (Euler–Cromer) | ∝ h |
38
+ | `rk4_2order` | y'' = f(x, y, y') | Classical RK4 | ∝ h⁴ |
39
+
40
+ Halving the step size *h* reduces the error roughly by a factor of 2 for Euler and by a factor of 16 for RK4.
41
+
42
+ ![Error convergence of Euler and RK4](https://raw.githubusercontent.com/lukasnf/Numerical-ODE-Solver/main/docs/convergence.png)
43
+
44
+ `euler_2order` updates y' first and then uses the *new* y' to update y. This keeps the energy of oscillating systems (e.g. y'' = −y) bounded, while the plain explicit Euler method lets it grow without limit.
45
+
46
+ The second-order solvers rewrite y'' = f(x, y, y') as a system of two first-order ODEs, y' = v and v' = f(x, y, v), and advance y and v together.
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install numODEsolver
52
+ ```
53
+
54
+ Requires Python 3.8 or newer. The dependencies [NumPy](https://numpy.org), [SciPy](https://scipy.org) and [asteval](https://github.com/lmfit/asteval) are installed automatically.
55
+
56
+ ## Usage
57
+
58
+ ### First-order ODE
59
+
60
+ Solve y' = y with y(0) = 1 (exact solution: y = eˣ):
61
+
62
+ ```python
63
+ import numODEsolver as ns
64
+ import matplotlib.pyplot as plt # optional, only for plotting
65
+
66
+ solver = ns.Solver()
67
+ f = solver.get_function("y") # right-hand side of y' = y
68
+ values = solver.rk4_1order(f, x0=0, y0=1, n=10000, bound=10)
69
+
70
+ print(solver.get_value(values, val=10, dec=5)) # y(10) ≈ e^10 = 22026.46579
71
+
72
+ plt.plot(values[:, 0], values[:, 1])
73
+ plt.show()
74
+ ```
75
+
76
+ ### Second-order ODE
77
+
78
+ Solve y'' = y' + y with y(0) = 1 and y'(0) = 1:
79
+
80
+ ```python
81
+ import numODEsolver as ns
82
+
83
+ solver = ns.Solver()
84
+ f = solver.get_function("y'+y") # right-hand side of y'' = y' + y; use y' for the first derivative
85
+ values = solver.rk4_2order(f, x0=0, y0=1, dy0=1, n=10000, bound=5)
86
+
87
+ print(solver.get_value(values, val=3, dec=2)) # y(3) ≈ 92.86
88
+ ```
89
+
90
+ `euler_2order` takes the same arguments.
91
+
92
+ ### Parameters
93
+
94
+ | Parameter | Meaning |
95
+ | :--- | :--- |
96
+ | `x0`, `y0` | Initial point and initial value |
97
+ | `dy0` | Initial value of y' (second-order solvers only) |
98
+ | `n` | Number of steps (step size h = (bound − x0) / n) |
99
+ | `bound` | End of the integration interval, must be greater than `x0` |
100
+ | `val`, `dec` | x-value to evaluate and number of decimal places (`get_value`) |
101
+
102
+ ### Return value
103
+
104
+ Every solver returns a NumPy array with one row per step:
105
+
106
+ - first-order solvers: columns `[x, y]`
107
+ - second-order solvers: columns `[x, y, y']`
108
+
109
+ `get_value` interpolates y between the steps with a cubic spline. `val` must lie between `x0` and `bound`.
110
+
111
+ ## How Functions Are Parsed
112
+
113
+ `get_function` turns a string such as `"y'+y"` into a callable function:
114
+
115
+ 1. The string is converted to lower case and every `y'` is replaced by a variable `dy`.
116
+ 2. The expression is evaluated with [asteval](https://github.com/lmfit/asteval) as `lambda x, y, dy=0: <expression>`.
117
+ 3. If the expression contains `y'`, the function is marked as second-order.
118
+
119
+ Allowed are the variables `x`, `y` and `y'`, normal Python operators (`+ - * / **`) and the NumPy math functions and constants without a prefix, e.g. `sin`, `cos`, `exp`, `log`, `sqrt`, `abs`, `pi`:
120
+
121
+ ```python
122
+ solver.get_function("sin(x) - y**2")
123
+ solver.get_function("-0.5*y' - 4*y")
124
+ ```
125
+
126
+ asteval does not allow imports or access to Python internals (like `__import__`), and numODEsolver also removes asteval's `open()`, so expressions cannot read files. This makes it much safer than Python's `eval`, but it is not a complete sandbox, so do not pass untrusted input.
127
+
128
+ An expression that cannot be parsed raises a `ValueError`. Passing a function with `y'` to a first-order solver also raises a `ValueError`.
129
+
130
+ ## Known Limitations
131
+
132
+ - Fixed step size only (no adaptive step-size control)
133
+ - Explicit methods: stiff ODEs may require very small step sizes
134
+ - Integration only forwards (`bound` must be greater than `x0`)
135
+ - Only single equations, no systems of several ODEs and no third or higher order
136
+ - `get_value` needs at least 4 points (`n >= 3`) for the cubic interpolation
137
+ - Functions are evaluated through asteval, which is slower than plain Python; very large `n` can take a while
138
+ ## Contributing
139
+
140
+ Bug reports and suggestions are welcome. Please open an [issue](https://github.com/lukasnf/Numerical-ODE-Solver/issues).
141
+
142
+ ## Author
143
+
144
+ Lukas Filipon, B.Sc. Physics student at KIT
@@ -0,0 +1,7 @@
1
+ numODEsolver/__init__.py,sha256=DhJ68tBHDDwR8f_PIYsP5mI_y_4q4pdoKYVrGaYnlaI,26
2
+ numODEsolver/solver.py,sha256=LgsqnTLqZv4L73i9E-cxooPW8Ddw5RofIhj1oXeBOEg,4622
3
+ numodesolver-3.0.dist-info/licenses/LICENSE,sha256=B1LP4xi1JhMSHUlkccB-_2VoeKE8r2jbuvGFUzqJ70Y,1065
4
+ numodesolver-3.0.dist-info/METADATA,sha256=roEu05Nc84drerngiF_vaTfQq79TgOBIQaCa9_LsynA,5458
5
+ numodesolver-3.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ numodesolver-3.0.dist-info/top_level.txt,sha256=G-8gaHtECVQ5G30bl_5w1UUSZ7L380bwmNo-6_r74hc,13
7
+ numodesolver-3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,75 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: numODEsolver
3
- Version: 2.0.2
4
- Summary: Tool that solves ODE's numerically. Written in Python.
5
- Home-page: https://github.com/lukasnf/Numerical-ODE-Solver
6
- Classifier: Programming Language :: Python :: 3
7
- Classifier: License :: OSI Approved :: MIT License
8
- Classifier: Operating System :: OS Independent
9
- Requires-Python: >=3.8
10
- Description-Content-Type: text/markdown
11
- License-File: LICENSE
12
- Requires-Dist: numpy
13
- Requires-Dist: asteval
14
- Requires-Dist: scipy
15
- Dynamic: classifier
16
- Dynamic: description
17
- Dynamic: description-content-type
18
- Dynamic: home-page
19
- Dynamic: license-file
20
- Dynamic: requires-dist
21
- Dynamic: requires-python
22
- Dynamic: summary
23
-
24
- # Numerical ODE Solver
25
-
26
- This project is a Python implementation for solving ordinary differential equations (ODEs) numerically. The script allows users to choose between two methods: Euler's Method and Runge-Kutta 4th Order Method (RK4), providing a visual representation of the solution (optional). Note: Euler's Method is more inaccurate than RK4.
27
-
28
- ## Requirements
29
- Python version >= 3.8
30
-
31
- Ensure the following Python libraries are installed:
32
-
33
- Install it using `pip`:
34
- ```bash
35
- pip install numODEsolver
36
- ```
37
- ## Example
38
- ```bash
39
- import numODEsolver as ns
40
- import matplotlib.pyplot as plt #optional for plot
41
-
42
- solver = ns.Solver()
43
- f = solver.get_function("y")
44
- values = solver.rk4_1order(f,x0=0,y0=1,n=10000,bound=10.1)
45
- n = solver.get_value(values,val=10,dec=5)
46
- print(n)
47
- plt.plot(values[:,0],values[:,1])
48
- plt.show()
49
- ```
50
- ```bash
51
- import numODEsolver as solver
52
-
53
- solver = ns.Solver()
54
- f = solver.get_function("y'+y") #y' = for 1st derivative. The ode would be y'' = y'+y
55
- x,y,dy = solver.euler_2order(f,x0=0,y0=1,dy0=1,n=10000,bound=5)
56
- n = solver.get_value(values,val=3,dec=2)
57
- print(n)
58
- ```
59
-
60
- # Version History
61
-
62
- - 8.12.2024 - v0.1 -> only 1st order ODE's are solvable, more features coming soon
63
- - 15.12.2024 - v0.2 -> removed plot function
64
- - 26.1.2025 - v0.3 -> included 2nd order methods, see more on GitHub
65
- - 18.03.2025 - v2.0 -> more secure function handeling, more stable numerical methods.
66
-
67
- ---
68
- For more documentation take a look at the source code on my GitHub.
69
-
70
- You can modify the script to add more methods, or change visualization settings.
71
-
72
- Contributions and suggestions are welcome!
73
-
74
- Lukas
75
-
@@ -1,7 +0,0 @@
1
- numODEsolver/__init__.py,sha256=DhJ68tBHDDwR8f_PIYsP5mI_y_4q4pdoKYVrGaYnlaI,26
2
- numODEsolver/solver.py,sha256=pStGfhx2Bmw21zzU_wL0_7GCUWt3v1Hvb52w37tNQWk,2840
3
- numodesolver-2.0.2.dist-info/licenses/LICENSE,sha256=B1LP4xi1JhMSHUlkccB-_2VoeKE8r2jbuvGFUzqJ70Y,1065
4
- numodesolver-2.0.2.dist-info/METADATA,sha256=iyJWhdB6DeBHWS-_eiTOCLwPQ0Dr5JE9uTGM8fZlBE8,2244
5
- numodesolver-2.0.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
- numodesolver-2.0.2.dist-info/top_level.txt,sha256=G-8gaHtECVQ5G30bl_5w1UUSZ7L380bwmNo-6_r74hc,13
7
- numodesolver-2.0.2.dist-info/RECORD,,