piconum 0.1.0__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.
- piconum-0.1.0/PKG-INFO +211 -0
- piconum-0.1.0/README.md +195 -0
- piconum-0.1.0/pyproject.toml +36 -0
- piconum-0.1.0/src/piconum/__init__.py +14 -0
- piconum-0.1.0/src/piconum/integration/__init__.py +17 -0
- piconum-0.1.0/src/piconum/integration/integrator.py +44 -0
- piconum-0.1.0/src/piconum/interpolation/__init__.py +8 -0
- piconum-0.1.0/src/piconum/interpolation/interpolation.py +102 -0
- piconum-0.1.0/src/piconum/ivp/__init__.py +15 -0
- piconum-0.1.0/src/piconum/ivp/ivp.py +40 -0
- piconum-0.1.0/src/piconum/ivp/solver.py +196 -0
- piconum-0.1.0/src/piconum/py.typed +0 -0
piconum-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: piconum
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modular, readable and easy to use library for numerical methods
|
|
5
|
+
Author: XMT23
|
|
6
|
+
Author-email: XMT23 <martintapiaxavier@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
10
|
+
Classifier: Typing :: Typed
|
|
11
|
+
Requires-Dist: numpy>=2.2.6
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Project-URL: Homepage, https://github.com/XMT23/piconum
|
|
14
|
+
Project-URL: Issues, https://github.com/XMT23/piconum/issues
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# numlib
|
|
18
|
+
|
|
19
|
+
A Python library implementing numerical methods for integration, interpolation,
|
|
20
|
+
and solving initial value problems (IVPs).
|
|
21
|
+
Developed as part of the *Numerical and Probabilistic Methods*
|
|
22
|
+
course at the Universitat Autònoma de Barcelona (UAB),
|
|
23
|
+
within the degree in Computational Mathematics and Data Analysis.
|
|
24
|
+
|
|
25
|
+
The library aims to be modular, readable, and easy to use. Each module is self-contained and exposes
|
|
26
|
+
a clean interface.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Structure
|
|
31
|
+
|
|
32
|
+
```
|
|
33
|
+
.
|
|
34
|
+
├── main.py
|
|
35
|
+
└── numlib/
|
|
36
|
+
├── integration/
|
|
37
|
+
│ ├── functions.py # Example functions and epsilon presets
|
|
38
|
+
│ ├── integrator.py # Integration methods
|
|
39
|
+
│ └── integration_benchmarks.py # Convergence and comparision utilities
|
|
40
|
+
├── interpolation/
|
|
41
|
+
│ └── interpolation.py # Polynomial interpolation (Lagrange Polynomials) via Gaussian elimination
|
|
42
|
+
└── ivp/
|
|
43
|
+
├── ivp.py # IVP problem definition class
|
|
44
|
+
└── solver.py # All IVP solvers
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**`numlib/ivp`** — Defines the `IVP` class for specifying ODE systems and
|
|
48
|
+
implements 8 solvers ranging from Euler to a predictor-corrector scheme.
|
|
49
|
+
All solvers are Python generators, which allows step-by-step iteration
|
|
50
|
+
and dynamic step size control via `.send()`.
|
|
51
|
+
|
|
52
|
+
**`numlib/interpolation`** — Polynomial interpolation from a function and a set of nodes.
|
|
53
|
+
The system is solved using a custom Gaussian elimination implementation.
|
|
54
|
+
The result is an `InterpolationPoly` object that is callable and human-readable.
|
|
55
|
+
|
|
56
|
+
**`numlib/integration`** — Numerical integration using Trapezoidal and Simpson,
|
|
57
|
+
with utilities to generate convergence tables across increasing subdivisions.
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Installation and requirements
|
|
62
|
+
|
|
63
|
+
It is recommended to create a virtual environment before installing dependencies:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
python -m venv .venv
|
|
67
|
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
|
68
|
+
pip install -r requirements.txt
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Examples
|
|
74
|
+
|
|
75
|
+
### Solving an IVP
|
|
76
|
+
|
|
77
|
+
Define the system using the `IVP` class.
|
|
78
|
+
Variables and parameters are accessed by name inside the function:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
from numlib.ivp import IVP, rk4
|
|
82
|
+
|
|
83
|
+
system = IVP(
|
|
84
|
+
f=lambda t, v, p: -v.y,
|
|
85
|
+
vars=["y"],
|
|
86
|
+
t0=0.0,
|
|
87
|
+
y0=1.0,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
for t, y in rk4(system, tf=5.0, h=0.1):
|
|
91
|
+
print(f"t={t:.2f} y={y[0]:.6f}")
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Parameters can be passed as keyword arguments and accessed via `p` inside the function:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
system = IVP(
|
|
98
|
+
f=lambda t, v, p: p.r * v.y * (1 - v.y / p.K),
|
|
99
|
+
vars=["y"],
|
|
100
|
+
t0=0.0,
|
|
101
|
+
y0=1.0,
|
|
102
|
+
r=1.0,
|
|
103
|
+
K=10.0,
|
|
104
|
+
)
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Multi-variable systems work the same way.
|
|
108
|
+
Just provide a list of variable names and initial values:
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
# Harmonic oscillator: x'' + x = 0 → x' = vx, vx' = -x
|
|
112
|
+
system = IVP(
|
|
113
|
+
f=lambda t, v, p: [v.vx, -v.x],
|
|
114
|
+
vars=["x", "vx"],
|
|
115
|
+
t0=0.0,
|
|
116
|
+
y0=[1.0, 0.0],
|
|
117
|
+
)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
---
|
|
121
|
+
|
|
122
|
+
### Variable step size with `.send()`
|
|
123
|
+
|
|
124
|
+
All solvers are generators.
|
|
125
|
+
You can send a new value of `h` at any step.
|
|
126
|
+
This might be useful for changing at runtime the stepsize.
|
|
127
|
+
|
|
128
|
+
```python
|
|
129
|
+
from numlib.ivp import IVP, rk4
|
|
130
|
+
|
|
131
|
+
system = IVP(f=lambda t, v, p: -v.y, vars=["y"], t0=0.0, y0=1.0)
|
|
132
|
+
|
|
133
|
+
gen = rk4(system, tf=5.0, h=0.1)
|
|
134
|
+
t, y = next(gen)
|
|
135
|
+
|
|
136
|
+
while True:
|
|
137
|
+
new_h = 0.01 if abs(y[0]) > 0.5 else 0.2 # fine steps where y changes fast
|
|
138
|
+
try:
|
|
139
|
+
t, y = gen.send(new_h)
|
|
140
|
+
except StopIteration:
|
|
141
|
+
break
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
If no new step size is needed,
|
|
145
|
+
just iterate normally with `next()` or a `for` loop.
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
### Polynomial interpolation
|
|
150
|
+
|
|
151
|
+
Pass any callable and a list of interpolation nodes.
|
|
152
|
+
The result is an object you can call directly or print:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from numlib.interpolation import interpolation_poly
|
|
156
|
+
import numpy as np
|
|
157
|
+
|
|
158
|
+
p = interpolation_poly(np.sin, [-1.0, 0.0, 1.0, 2.0])
|
|
159
|
+
|
|
160
|
+
print(p) # → -0.1782x^3 + 0.0076x^2 + 0.8719x
|
|
161
|
+
print(p(0.5)) # → 0.4769...
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The polynomial is solved internally via Gaussian elimination.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
### Numerical integration
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
from numlib.integration import simpson_composite
|
|
172
|
+
|
|
173
|
+
result = simpson_composite(lambda x: np.exp(-(x**2)), a=0.0, b=2.0, n=100)
|
|
174
|
+
print(result) # → 0.8821...
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## Implemented methods
|
|
180
|
+
|
|
181
|
+
### IVP Solvers (`numlib/ivp`)
|
|
182
|
+
|
|
183
|
+
| Method | Type | Order | Notes |
|
|
184
|
+
|--------|------|-------|-------|
|
|
185
|
+
| `euler` | Single-step | 1 | — |
|
|
186
|
+
| `taylor2` | Single-step | 2 | Jacobian estimated numerically if not provided |
|
|
187
|
+
| `rk2` | Single-step | 2 | Parameterizable via `alpha` |
|
|
188
|
+
| `rk4` | Single-step | 4 | — |
|
|
189
|
+
| `ab2` | Multi-step | 2 | Adams-Bashforth, starts with RK4 |
|
|
190
|
+
| `ab4` | Multi-step | 4 | Adams-Bashforth, starts with RK4 |
|
|
191
|
+
| `am` | Multi-step | 4 | Adams-Moulton (implicit) |
|
|
192
|
+
| `pc` | Multi-step | 4 | Predictor-corrector (AB4 + AM) |
|
|
193
|
+
|
|
194
|
+
### Integration methods (`numlib/integration`)
|
|
195
|
+
|
|
196
|
+
| Method | Type |
|
|
197
|
+
|--------|------|
|
|
198
|
+
| `trapezoidal_simple` | Simple rule |
|
|
199
|
+
| `trapezoidal_composite` | Composite rule |
|
|
200
|
+
| `simpson_simple` | Simple rule |
|
|
201
|
+
| `simpson_composite` | Composite rule |
|
|
202
|
+
|
|
203
|
+
### Interpolation (`numlib/interpolation`)
|
|
204
|
+
|
|
205
|
+
| Function | Description |
|
|
206
|
+
|----------|-------------|
|
|
207
|
+
| `interpolation_poly` | Builds interpolating polynomial from a callable and node list |
|
|
208
|
+
| `gauss` | Gaussian elimination for square linear systems |
|
|
209
|
+
| `triangular_sup` | Row reduction to upper triangular form |
|
|
210
|
+
|
|
211
|
+
---
|
piconum-0.1.0/README.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# numlib
|
|
2
|
+
|
|
3
|
+
A Python library implementing numerical methods for integration, interpolation,
|
|
4
|
+
and solving initial value problems (IVPs).
|
|
5
|
+
Developed as part of the *Numerical and Probabilistic Methods*
|
|
6
|
+
course at the Universitat Autònoma de Barcelona (UAB),
|
|
7
|
+
within the degree in Computational Mathematics and Data Analysis.
|
|
8
|
+
|
|
9
|
+
The library aims to be modular, readable, and easy to use. Each module is self-contained and exposes
|
|
10
|
+
a clean interface.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Structure
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
.
|
|
18
|
+
├── main.py
|
|
19
|
+
└── numlib/
|
|
20
|
+
├── integration/
|
|
21
|
+
│ ├── functions.py # Example functions and epsilon presets
|
|
22
|
+
│ ├── integrator.py # Integration methods
|
|
23
|
+
│ └── integration_benchmarks.py # Convergence and comparision utilities
|
|
24
|
+
├── interpolation/
|
|
25
|
+
│ └── interpolation.py # Polynomial interpolation (Lagrange Polynomials) via Gaussian elimination
|
|
26
|
+
└── ivp/
|
|
27
|
+
├── ivp.py # IVP problem definition class
|
|
28
|
+
└── solver.py # All IVP solvers
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
**`numlib/ivp`** — Defines the `IVP` class for specifying ODE systems and
|
|
32
|
+
implements 8 solvers ranging from Euler to a predictor-corrector scheme.
|
|
33
|
+
All solvers are Python generators, which allows step-by-step iteration
|
|
34
|
+
and dynamic step size control via `.send()`.
|
|
35
|
+
|
|
36
|
+
**`numlib/interpolation`** — Polynomial interpolation from a function and a set of nodes.
|
|
37
|
+
The system is solved using a custom Gaussian elimination implementation.
|
|
38
|
+
The result is an `InterpolationPoly` object that is callable and human-readable.
|
|
39
|
+
|
|
40
|
+
**`numlib/integration`** — Numerical integration using Trapezoidal and Simpson,
|
|
41
|
+
with utilities to generate convergence tables across increasing subdivisions.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Installation and requirements
|
|
46
|
+
|
|
47
|
+
It is recommended to create a virtual environment before installing dependencies:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
python -m venv .venv
|
|
51
|
+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
|
|
52
|
+
pip install -r requirements.txt
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Examples
|
|
58
|
+
|
|
59
|
+
### Solving an IVP
|
|
60
|
+
|
|
61
|
+
Define the system using the `IVP` class.
|
|
62
|
+
Variables and parameters are accessed by name inside the function:
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from numlib.ivp import IVP, rk4
|
|
66
|
+
|
|
67
|
+
system = IVP(
|
|
68
|
+
f=lambda t, v, p: -v.y,
|
|
69
|
+
vars=["y"],
|
|
70
|
+
t0=0.0,
|
|
71
|
+
y0=1.0,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
for t, y in rk4(system, tf=5.0, h=0.1):
|
|
75
|
+
print(f"t={t:.2f} y={y[0]:.6f}")
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Parameters can be passed as keyword arguments and accessed via `p` inside the function:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
system = IVP(
|
|
82
|
+
f=lambda t, v, p: p.r * v.y * (1 - v.y / p.K),
|
|
83
|
+
vars=["y"],
|
|
84
|
+
t0=0.0,
|
|
85
|
+
y0=1.0,
|
|
86
|
+
r=1.0,
|
|
87
|
+
K=10.0,
|
|
88
|
+
)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Multi-variable systems work the same way.
|
|
92
|
+
Just provide a list of variable names and initial values:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
# Harmonic oscillator: x'' + x = 0 → x' = vx, vx' = -x
|
|
96
|
+
system = IVP(
|
|
97
|
+
f=lambda t, v, p: [v.vx, -v.x],
|
|
98
|
+
vars=["x", "vx"],
|
|
99
|
+
t0=0.0,
|
|
100
|
+
y0=[1.0, 0.0],
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
### Variable step size with `.send()`
|
|
107
|
+
|
|
108
|
+
All solvers are generators.
|
|
109
|
+
You can send a new value of `h` at any step.
|
|
110
|
+
This might be useful for changing at runtime the stepsize.
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from numlib.ivp import IVP, rk4
|
|
114
|
+
|
|
115
|
+
system = IVP(f=lambda t, v, p: -v.y, vars=["y"], t0=0.0, y0=1.0)
|
|
116
|
+
|
|
117
|
+
gen = rk4(system, tf=5.0, h=0.1)
|
|
118
|
+
t, y = next(gen)
|
|
119
|
+
|
|
120
|
+
while True:
|
|
121
|
+
new_h = 0.01 if abs(y[0]) > 0.5 else 0.2 # fine steps where y changes fast
|
|
122
|
+
try:
|
|
123
|
+
t, y = gen.send(new_h)
|
|
124
|
+
except StopIteration:
|
|
125
|
+
break
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
If no new step size is needed,
|
|
129
|
+
just iterate normally with `next()` or a `for` loop.
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
### Polynomial interpolation
|
|
134
|
+
|
|
135
|
+
Pass any callable and a list of interpolation nodes.
|
|
136
|
+
The result is an object you can call directly or print:
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from numlib.interpolation import interpolation_poly
|
|
140
|
+
import numpy as np
|
|
141
|
+
|
|
142
|
+
p = interpolation_poly(np.sin, [-1.0, 0.0, 1.0, 2.0])
|
|
143
|
+
|
|
144
|
+
print(p) # → -0.1782x^3 + 0.0076x^2 + 0.8719x
|
|
145
|
+
print(p(0.5)) # → 0.4769...
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
The polynomial is solved internally via Gaussian elimination.
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
### Numerical integration
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
from numlib.integration import simpson_composite
|
|
156
|
+
|
|
157
|
+
result = simpson_composite(lambda x: np.exp(-(x**2)), a=0.0, b=2.0, n=100)
|
|
158
|
+
print(result) # → 0.8821...
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Implemented methods
|
|
164
|
+
|
|
165
|
+
### IVP Solvers (`numlib/ivp`)
|
|
166
|
+
|
|
167
|
+
| Method | Type | Order | Notes |
|
|
168
|
+
|--------|------|-------|-------|
|
|
169
|
+
| `euler` | Single-step | 1 | — |
|
|
170
|
+
| `taylor2` | Single-step | 2 | Jacobian estimated numerically if not provided |
|
|
171
|
+
| `rk2` | Single-step | 2 | Parameterizable via `alpha` |
|
|
172
|
+
| `rk4` | Single-step | 4 | — |
|
|
173
|
+
| `ab2` | Multi-step | 2 | Adams-Bashforth, starts with RK4 |
|
|
174
|
+
| `ab4` | Multi-step | 4 | Adams-Bashforth, starts with RK4 |
|
|
175
|
+
| `am` | Multi-step | 4 | Adams-Moulton (implicit) |
|
|
176
|
+
| `pc` | Multi-step | 4 | Predictor-corrector (AB4 + AM) |
|
|
177
|
+
|
|
178
|
+
### Integration methods (`numlib/integration`)
|
|
179
|
+
|
|
180
|
+
| Method | Type |
|
|
181
|
+
|--------|------|
|
|
182
|
+
| `trapezoidal_simple` | Simple rule |
|
|
183
|
+
| `trapezoidal_composite` | Composite rule |
|
|
184
|
+
| `simpson_simple` | Simple rule |
|
|
185
|
+
| `simpson_composite` | Composite rule |
|
|
186
|
+
|
|
187
|
+
### Interpolation (`numlib/interpolation`)
|
|
188
|
+
|
|
189
|
+
| Function | Description |
|
|
190
|
+
|----------|-------------|
|
|
191
|
+
| `interpolation_poly` | Builds interpolating polynomial from a callable and node list |
|
|
192
|
+
| `gauss` | Gaussian elimination for square linear systems |
|
|
193
|
+
| `triangular_sup` | Row reduction to upper triangular form |
|
|
194
|
+
|
|
195
|
+
---
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "piconum"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A modular, readable and easy to use library for numerical methods"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "XMT23", email = "martintapiaxavier@gmail.com" }
|
|
10
|
+
]
|
|
11
|
+
dependencies = [
|
|
12
|
+
"numpy>=2.2.6",
|
|
13
|
+
]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
[project.urls]
|
|
21
|
+
Homepage = "https://github.com/XMT23/piconum"
|
|
22
|
+
Issues = "https://github.com/XMT23/piconum/issues"
|
|
23
|
+
|
|
24
|
+
[tool.ruff]
|
|
25
|
+
extend-exclude = ["sandbox"]
|
|
26
|
+
|
|
27
|
+
[build-system]
|
|
28
|
+
requires = ["uv_build>=0.11.26,<0.12.0"]
|
|
29
|
+
build-backend = "uv_build"
|
|
30
|
+
|
|
31
|
+
[dependency-groups]
|
|
32
|
+
dev = [
|
|
33
|
+
"mypy>=2.4.1",
|
|
34
|
+
"pandas>=2.3.3",
|
|
35
|
+
"ruff>=0.17.6",
|
|
36
|
+
]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""
|
|
2
|
+
piconum: modular, readable and easy to use numerical methods
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
from . import integration, interpolation, ivp
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
__version__ = version("piconum")
|
|
11
|
+
except PackageNotFoundError:
|
|
12
|
+
__version__ = "0.0.0+unknown"
|
|
13
|
+
|
|
14
|
+
__all__ = ["__version__", "integration", "interpolation", "ivp"]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from .integrator import (
|
|
2
|
+
IntegrationMethod,
|
|
3
|
+
MathFunction,
|
|
4
|
+
simpson_composite,
|
|
5
|
+
simpson_simple,
|
|
6
|
+
trapezoidal_composite,
|
|
7
|
+
trapezoidal_simple,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"IntegrationMethod",
|
|
12
|
+
"MathFunction",
|
|
13
|
+
"simpson_composite",
|
|
14
|
+
"simpson_simple",
|
|
15
|
+
"trapezoidal_composite",
|
|
16
|
+
"trapezoidal_simple",
|
|
17
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
MathFunction = Callable[[float], float]
|
|
4
|
+
IntegrationMethod = Callable[[MathFunction, float, float, int], float]
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def trapezoidal_simple(f: MathFunction, a: float, b: float, _: int) -> float:
|
|
8
|
+
return (b - a) / 2 * (f(a) + f(b))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def trapezoidal_composite(f: MathFunction, a: float, b: float, n: int) -> float:
|
|
12
|
+
if n < 1:
|
|
13
|
+
raise ValueError("N must be >= 1 for Trapezoidal Composite")
|
|
14
|
+
|
|
15
|
+
h = (b - a) / n
|
|
16
|
+
s = f(a) + f(b)
|
|
17
|
+
|
|
18
|
+
for i in range(1, n):
|
|
19
|
+
xi = a + i * h
|
|
20
|
+
s += 2 * f(xi)
|
|
21
|
+
|
|
22
|
+
return (h / 2) * s
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def simpson_simple(f: MathFunction, a: float, b: float, _: int) -> float:
|
|
26
|
+
m = (a + b) / 2
|
|
27
|
+
return (b - a) / 6 * (f(a) + 4 * f(m) + f(b))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def simpson_composite(f: MathFunction, a: float, b: float, n: int) -> float:
|
|
31
|
+
if n < 2 or (n % 2) != 0:
|
|
32
|
+
raise ValueError("N must be even and >= 2 for Simpson Composite")
|
|
33
|
+
|
|
34
|
+
h = (b - a) / n
|
|
35
|
+
s = f(a) + f(b)
|
|
36
|
+
|
|
37
|
+
for i in range(1, n):
|
|
38
|
+
xi = a + i * h
|
|
39
|
+
if i % 2 == 1:
|
|
40
|
+
s += 4 * f(xi)
|
|
41
|
+
else:
|
|
42
|
+
s += 2 * f(xi)
|
|
43
|
+
|
|
44
|
+
return (h / 3) * s
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class InterpolationPoly:
|
|
7
|
+
def __init__(self, coefficients: np.ndarray) -> None:
|
|
8
|
+
self.coefficients = coefficients
|
|
9
|
+
|
|
10
|
+
def __str__(self) -> str:
|
|
11
|
+
terms = []
|
|
12
|
+
for i, a in enumerate(self.coefficients):
|
|
13
|
+
if abs(a) < 1e-8:
|
|
14
|
+
continue
|
|
15
|
+
coef = f"{a:.4g}"
|
|
16
|
+
if i == 0:
|
|
17
|
+
terms.append(coef)
|
|
18
|
+
elif i == 1:
|
|
19
|
+
if str(coef) == "1":
|
|
20
|
+
coef = ""
|
|
21
|
+
terms.append(f"{coef}x")
|
|
22
|
+
else:
|
|
23
|
+
if str(coef) == "1":
|
|
24
|
+
coef = ""
|
|
25
|
+
terms.append(f"{coef}x^{i}")
|
|
26
|
+
|
|
27
|
+
return " + ".join(list(reversed(terms))) if terms else "0"
|
|
28
|
+
|
|
29
|
+
def __call__(self, x: float) -> float:
|
|
30
|
+
return self.evaluate(x)
|
|
31
|
+
|
|
32
|
+
def evaluate(self, x: float) -> float:
|
|
33
|
+
return np.sum([a * x**i for i, a in enumerate(self.coefficients)])
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _regressive_sustitution(sup_matrix: np.ndarray) -> np.ndarray:
|
|
37
|
+
assert sup_matrix.shape[1] == sup_matrix.shape[0] + 1, (
|
|
38
|
+
"'sup_matrix' does not represent a linear system of equations, "
|
|
39
|
+
f"it must have n rows and n + 1 columns. Actual shape given: {sup_matrix.shape}"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
coefficients = np.zeros_like(sup_matrix[0][:-1])
|
|
43
|
+
|
|
44
|
+
for i in range(sup_matrix.shape[0] + 1):
|
|
45
|
+
if sup_matrix[-i][-(i + 1)] == 0:
|
|
46
|
+
coefficients[-i] = 0
|
|
47
|
+
else:
|
|
48
|
+
coefficients[-i] = (
|
|
49
|
+
sup_matrix[-i][-1] - np.sum(coefficients * sup_matrix[-i][:-1])
|
|
50
|
+
) / sup_matrix[-i][-(i + 1)]
|
|
51
|
+
|
|
52
|
+
return coefficients
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def triangular_sup(matrix: np.ndarray) -> np.ndarray:
|
|
56
|
+
if len(matrix.shape) != 2:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
f"'matrix' must be a 2D array, got a {len(matrix.shape)}D object"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
M = matrix.astype(float).copy()
|
|
62
|
+
n_rows = M.shape[0]
|
|
63
|
+
n_cols = M.shape[1]
|
|
64
|
+
|
|
65
|
+
for i in range(n_rows):
|
|
66
|
+
pivot = M[i][i]
|
|
67
|
+
for k in range(i + 1, n_rows):
|
|
68
|
+
m = M[k][i] / pivot
|
|
69
|
+
for j in range(i, n_cols):
|
|
70
|
+
M[k][j] = M[k][j] - M[i][j] * m
|
|
71
|
+
|
|
72
|
+
return M
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def gauss(M: np.ndarray) -> np.ndarray:
|
|
76
|
+
if M.shape[0] > M.shape[1] - 1:
|
|
77
|
+
raise ValueError("given system of equations doesn't have an unique solution")
|
|
78
|
+
|
|
79
|
+
M = triangular_sup(M)
|
|
80
|
+
|
|
81
|
+
return _regressive_sustitution(M)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _coefficients(f: Callable, x: np.ndarray) -> np.ndarray:
|
|
85
|
+
y = np.array([f(xi) for xi in x], dtype=float)
|
|
86
|
+
m = len(x)
|
|
87
|
+
|
|
88
|
+
A = np.array([[x[i] ** j for j in range(m)] for i in range(m)], dtype=float)
|
|
89
|
+
M = np.hstack([A, y.reshape(-1, 1)])
|
|
90
|
+
|
|
91
|
+
return gauss(M)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def interpolation_poly(
|
|
95
|
+
f: Callable, x: list[float] | list[int] | np.ndarray
|
|
96
|
+
) -> InterpolationPoly:
|
|
97
|
+
x_vec: np.ndarray = np.array(x, dtype=float)
|
|
98
|
+
if len(x_vec) != len(np.unique(x_vec)):
|
|
99
|
+
raise ValueError(f"vector 'x' must consist of unique elements. Got {x_vec}")
|
|
100
|
+
|
|
101
|
+
coefficients: np.ndarray = _coefficients(f, x_vec)
|
|
102
|
+
return InterpolationPoly(coefficients)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from collections.abc import Callable
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class IVP:
|
|
7
|
+
def __init__(
|
|
8
|
+
self, f, fvars, *, t0=0.0, y0: float | list[float] = 0.0, **params
|
|
9
|
+
) -> None:
|
|
10
|
+
self.f: Callable = f
|
|
11
|
+
self.t0: float = t0
|
|
12
|
+
self.y0: np.ndarray = np.atleast_1d(y0)
|
|
13
|
+
|
|
14
|
+
self._var_names: np.ndarray = np.array(fvars)
|
|
15
|
+
|
|
16
|
+
if len(self.y0) != len(self._var_names):
|
|
17
|
+
raise ValueError(
|
|
18
|
+
f"{len(self.y0)} expected variables, got {len(self._var_names)}"
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# Create and instantiate a "Params" empty class
|
|
22
|
+
self.params = type("Params", (), {})()
|
|
23
|
+
for name, value in params.items():
|
|
24
|
+
setattr(self.params, name, value)
|
|
25
|
+
|
|
26
|
+
def evaluate(self, t: float, y: float | list[float] | np.ndarray):
|
|
27
|
+
y_values = np.atleast_1d(y)
|
|
28
|
+
|
|
29
|
+
if len(y_values) != len(self._var_names):
|
|
30
|
+
raise ValueError(
|
|
31
|
+
f"{len(self._var_names)} expected variables, got {len(y_values)}"
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# Create and instantiate a "Vars" empty class
|
|
35
|
+
v = type("Vars", (), {})()
|
|
36
|
+
for name, value in zip(self._var_names, y_values):
|
|
37
|
+
setattr(v, name, value)
|
|
38
|
+
|
|
39
|
+
result = self.f(t, v, self.params)
|
|
40
|
+
return np.atleast_1d(result)
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
from collections.abc import Callable, Generator
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .ivp import IVP
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def euler_step(
|
|
9
|
+
system: IVP, t: float, y: np.ndarray, h: float
|
|
10
|
+
) -> tuple[float, np.ndarray]:
|
|
11
|
+
dy = system.evaluate(t, y)
|
|
12
|
+
return t + h, y + h * dy
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def taylor2_step(
|
|
16
|
+
system: IVP,
|
|
17
|
+
t: float,
|
|
18
|
+
y: np.ndarray,
|
|
19
|
+
h: float,
|
|
20
|
+
df_dy: Callable | None = None,
|
|
21
|
+
df_dt: Callable | None = None,
|
|
22
|
+
eps: float = 1e-6,
|
|
23
|
+
) -> tuple[float, np.ndarray]:
|
|
24
|
+
f = system.evaluate(t, y)
|
|
25
|
+
|
|
26
|
+
if df_dy is not None:
|
|
27
|
+
d1 = df_dy(t, y)
|
|
28
|
+
else:
|
|
29
|
+
n = len(y)
|
|
30
|
+
d1 = np.zeros((n, n))
|
|
31
|
+
for i in range(n):
|
|
32
|
+
e = np.zeros(n)
|
|
33
|
+
e[i] = eps
|
|
34
|
+
d1[:, i] = (system.evaluate(t, y + e) - system.evaluate(t, y - e)) / (
|
|
35
|
+
2 * eps
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
if df_dt is not None:
|
|
39
|
+
d2 = df_dt(t, y)
|
|
40
|
+
else:
|
|
41
|
+
d2 = (system.evaluate(t + eps, y) - system.evaluate(t - eps, y)) / (2 * eps)
|
|
42
|
+
|
|
43
|
+
return t + h, y + h * f + (h**2 / 2) * (d1 @ f + d2)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def rk2_step(
|
|
47
|
+
system: IVP, t: float, y: np.ndarray, h: float, alpha: float = 0.5
|
|
48
|
+
) -> tuple[float, np.ndarray]:
|
|
49
|
+
c1, c2 = 1 - alpha, alpha
|
|
50
|
+
a2 = 1 / (2 * alpha)
|
|
51
|
+
b21 = 1 / (2 * alpha)
|
|
52
|
+
|
|
53
|
+
k1 = system.evaluate(t, y)
|
|
54
|
+
k2 = system.evaluate(t + h * a2, y + h * b21 * k1)
|
|
55
|
+
|
|
56
|
+
return t + h, y + h * (c1 * k1 + c2 * k2)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def rk4_step(
|
|
60
|
+
system: IVP, t: float, y: np.ndarray, h: float
|
|
61
|
+
) -> tuple[float, np.ndarray]:
|
|
62
|
+
k1 = system.evaluate(t, y)
|
|
63
|
+
k2 = system.evaluate(t + h / 2, y + (h / 2) * k1)
|
|
64
|
+
k3 = system.evaluate(t + h / 2, y + (h / 2) * k2)
|
|
65
|
+
k4 = system.evaluate(t + h, y + h * k3)
|
|
66
|
+
|
|
67
|
+
return t + h, y + (h / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def ab2_step(system: IVP, history: list, h: float) -> tuple[float, np.ndarray]:
|
|
71
|
+
f = [system.evaluate(t, y) for t, y in history[-2:]]
|
|
72
|
+
t, y = history[-1]
|
|
73
|
+
return t + h, y + h * ((3 / 2) * f[1] - (1 / 2) * f[0])
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def ab4_step(system: IVP, history: list, h: float) -> tuple[float, np.ndarray]:
|
|
77
|
+
f = [system.evaluate(t, y) for t, y in history[-4:]]
|
|
78
|
+
t, y = history[-1]
|
|
79
|
+
return t + h, y + (h / 24) * (55 * f[3] - 59 * f[2] + 37 * f[1] - 9 * f[0])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def am_step(
|
|
83
|
+
system: IVP,
|
|
84
|
+
history: list,
|
|
85
|
+
h: float,
|
|
86
|
+
tol: float = 1e-10,
|
|
87
|
+
max_iter: int = 50,
|
|
88
|
+
) -> tuple[float, np.ndarray]:
|
|
89
|
+
t, y = history[-1]
|
|
90
|
+
f = [system.evaluate(ti, yi) for ti, yi in history[-3:]]
|
|
91
|
+
|
|
92
|
+
t_new = t + h
|
|
93
|
+
y_new = y.copy()
|
|
94
|
+
|
|
95
|
+
for _ in range(max_iter):
|
|
96
|
+
f_new = system.evaluate(t_new, y_new)
|
|
97
|
+
y_next = y + (h / 24) * (9 * f_new + 19 * f[2] - 5 * f[1] + f[0])
|
|
98
|
+
if np.max(np.abs(y_next - y_new)) < tol:
|
|
99
|
+
return t_new, y_next
|
|
100
|
+
y_new = y_next
|
|
101
|
+
|
|
102
|
+
return t_new, y_new
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
# predictor-correcto
|
|
106
|
+
def pc_step(system: IVP, history: list, h: float) -> tuple[float, np.ndarray]:
|
|
107
|
+
t, y = history[-1]
|
|
108
|
+
f = [system.evaluate(ti, yi) for ti, yi in history[-4:]]
|
|
109
|
+
|
|
110
|
+
y_pred = y + (h / 24) * (55 * f[3] - 59 * f[2] + 37 * f[1] - 9 * f[0])
|
|
111
|
+
|
|
112
|
+
f_pred = system.evaluate(t + h, y_pred)
|
|
113
|
+
y_new = y + (h / 24) * (9 * f_pred + 19 * f[3] - 5 * f[2] + f[1])
|
|
114
|
+
|
|
115
|
+
return t + h, y_new
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _solver(step_fn: Callable, system: IVP, tf: float, h: float, **kwargs):
|
|
119
|
+
t, y = system.t0, system.y0.copy()
|
|
120
|
+
while t < tf:
|
|
121
|
+
h_current = min(h, tf - t)
|
|
122
|
+
h_new = yield t, y
|
|
123
|
+
if h_new is not None:
|
|
124
|
+
h = h_new
|
|
125
|
+
t, y = step_fn(system, t, y, h_current, **kwargs)
|
|
126
|
+
yield t, y
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _multipass_solver(
|
|
130
|
+
step_fn: Callable, n_steps: int, system: IVP, tf: float, h: float, **kwargs
|
|
131
|
+
):
|
|
132
|
+
history = [(system.t0, system.y0.copy())]
|
|
133
|
+
for _ in range(n_steps - 1):
|
|
134
|
+
t, y = history[-1]
|
|
135
|
+
if t >= tf:
|
|
136
|
+
break
|
|
137
|
+
t_new, y_new = rk4_step(system, t, y, min(h, tf - t))
|
|
138
|
+
history.append((t_new, y_new))
|
|
139
|
+
|
|
140
|
+
for t, y in history[:-1]:
|
|
141
|
+
yield t, y
|
|
142
|
+
|
|
143
|
+
while history[-1][0] < tf:
|
|
144
|
+
t, y = history[-1]
|
|
145
|
+
h_current = min(h, tf - t)
|
|
146
|
+
h_new = yield t, y
|
|
147
|
+
if h_new is not None:
|
|
148
|
+
h = h_new
|
|
149
|
+
t_new, y_new = step_fn(system, history, h_current, **kwargs)
|
|
150
|
+
history.append((t_new, y_new))
|
|
151
|
+
history = history[-n_steps:]
|
|
152
|
+
|
|
153
|
+
yield history[-1]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def euler(system: IVP, tf: float, h: float) -> Generator:
|
|
157
|
+
return _solver(euler_step, system, tf, h)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def taylor2(
|
|
161
|
+
system: IVP,
|
|
162
|
+
tf: float,
|
|
163
|
+
h: float,
|
|
164
|
+
df_dy: Callable | None = None,
|
|
165
|
+
df_dt: Callable | None = None,
|
|
166
|
+
eps: float = 1e-6,
|
|
167
|
+
) -> Generator:
|
|
168
|
+
return _solver(taylor2_step, system, tf, h, df_dy=df_dy, df_dt=df_dt, eps=eps)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def euler2(system: IVP, tf: float, h: float):
|
|
172
|
+
return _solver(rk2_step, system, tf, h, alpha=1.0)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def rk2(system: IVP, tf: float, h: float, alpha: float = 0.5) -> Generator:
|
|
176
|
+
return _solver(rk2_step, system, tf, h, alpha=alpha)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def rk4(system: IVP, tf: float, h: float) -> Generator:
|
|
180
|
+
return _solver(rk4_step, system, tf, h)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def ab2(system: IVP, tf: float, h: float) -> Generator:
|
|
184
|
+
return _multipass_solver(ab2_step, 2, system, tf, h)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def ab4(system: IVP, tf: float, h: float) -> Generator:
|
|
188
|
+
return _multipass_solver(ab4_step, 4, system, tf, h)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def am(system: IVP, tf: float, h: float) -> Generator:
|
|
192
|
+
return _multipass_solver(am_step, 3, system, tf, h)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def pc(system: IVP, tf: float, h: float) -> Generator:
|
|
196
|
+
return _multipass_solver(pc_step, 4, system, tf, h)
|
|
File without changes
|