Solver Module (softpotato.solver)¶
The softpotato.solver subpackage provides numerical solvers for 1D multi-species chemical diffusion and reaction-diffusion problems across planar Cartesian and curvilinear (spherical, cylindrical) geometries.
Architecture and Spatial Operator Delegation¶
Solvers follow the Single Responsibility Principle:
- Time Stepping & Linear Algebra: Managed exclusively by solver classes (ScipyIVPSolver, CrankNicolson, ImplicitFiniteDifference, ExplicitFiniteDifference).
- Spatial Meshes & Discretization: DiffusionProblem natively accepts either structured Mesh1D instances (Uniform1DMesh, GeometricExpandingMesh, ExponentialMesh) from softpotato.grid or raw 1D numpy.ndarray coordinate arrays.
- Spatial Operators & Coordinate Metrics: Discretization stencils (\(\nabla^2 c\)), boundary conditions, interfacial fluxes, and Faradaic current calculations on both uniform and non-uniform meshes are delegated directly to Geometry abstractions (PlanarGeometry, SphericalGeometry, CylindricalGeometry).
Solvers and Supported Options¶
| Solver Class & Aliases | Supported Configuration Options | Description & Defaults |
|---|---|---|
ExplicitFiniteDifference ('explicit', 'ftcs') |
dt (float, optional) |
Explicit Forward-Time Central-Space. If dt=None, automatically defaults to \(0.45 \times \text{CFL limit}\) (\(\Delta t \le \Delta x_{\min}^2 / 2D_{\max}\)). |
ImplicitFiniteDifference ('implicit', 'btcs') |
dt (float, optional) |
Backward-Time Central-Space implicit scheme using banded tridiagonal matrix inversion. If dt=None, defaults to 100 uniform steps: \((t_{\text{end}} - t_{\text{start}}) / 100\). |
CrankNicolson ('crank_nicolson', 'crank-nicolson') |
dt (float, optional) |
Second-order in time and space Crank–Nicolson implicit scheme using banded tridiagonal solve. If dt=None, defaults to 100 uniform steps: \((t_{\text{end}} - t_{\text{start}}) / 100\). |
ScipyIVPSolver ('scipy_ivp', 'solve_ivp') |
method (str, default 'Radau'), rtol (float, default 1e-6), atol (float, default 1e-8) |
Method of Lines ODE integration using scipy.integrate.solve_ivp. Supports stiff ('Radau', 'BDF') and non-stiff ('RK45') integrators. |
Examples¶
1. Planar 1D Diffusion¶
import numpy as np
from softpotato.solver import DiffusionProblem, DirichletBC, get_solver
# Linear domain x in [0, 1]
x = np.linspace(0.0, 1.0, 50)
problem = DiffusionProblem(
grid=x,
diffusivity={"c": 1e-5},
boundary_conditions={"c": (DirichletBC(0.0), DirichletBC(1.0))},
initial_conditions={"c": 1.0},
geometry="planar", # default
)
solver = get_solver("crank_nicolson", dt=0.01)
result = solver.solve(problem, t_span=(0.0, 1.0))
print(result["c"].shape) # (N_t, N_x) concentration profile
print(result.fluxes["c"].shape) # (N_t,) interfacial flux
print(result.currents["c"].shape) # (N_t,) Faradaic current in Amperes
2. Spherical Microelectrode Step Response with Expanding Mesh¶
from softpotato.geometry import SphericalGeometry
from softpotato.grid import GeometricExpandingMesh
from softpotato.solver import DiffusionProblem, DirichletBC, get_solver
r0 = 25e-6 # 25 um radius
r_mesh = GeometricExpandingMesh.from_diffusion_layer(
D=1e-9, t_max=2.0, x_min=r0, n_points=75, gamma=1.06
)
problem = DiffusionProblem(
grid=r_mesh,
diffusivity={"c": 1e-9},
boundary_conditions={"c": (DirichletBC(0.0), DirichletBC(1.0))},
initial_conditions={"c": 1.0},
geometry=SphericalGeometry(r0=r0),
n_electrons=1,
)
solver = get_solver("scipy_ivp")
result = solver.solve(problem, t_span=(0.0, 2.0))
# result.currents['c'] contains exact spherical Cottrell chronoamperometric transient
Module Contents¶
solver
¶
Numerical solvers for chemical species diffusion and reaction-diffusion problems.
This module provides a unified framework for solving 1D multi-species diffusion equations:
Available built-in solvers include:
"scipy_ivp"/"solve_ivp": Method of Lines usingscipy.integrate.solve_ivp(Radau/BDF/RK45)."crank_nicolson": 2nd-order unconditionally stable Crank-Nicolson finite difference."implicit"/"btcs": Unconditionally stable Backward-Time Central-Space."explicit"/"ftcs": Forward-Time Central-Space with CFL stability enforcement.
Examples:
Solving a 1D diffusion problem and comparing two solvers:
>>> import numpy as np
>>> from softpotato.solver import (
... DiffusionProblem,
... DirichletBC,
... NeumannBC,
... get_solver,
... list_solvers,
... )
>>>
>>> list_solvers()
['btcs', 'crank-nicolson', 'crank_nicolson', 'explicit', 'ftcs', 'implicit', 'scipy_ivp', 'solve_ivp']
>>>
>>> grid = np.linspace(0.0, 1.0, 41)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"c": 0.01},
... boundary_conditions={"c": (DirichletBC(0.0), DirichletBC(0.0))},
... initial_conditions={"c": lambda x: np.sin(np.pi * x)},
... )
>>>
>>> t_eval = np.linspace(0.0, 0.5, 6)
>>> solver_mol = get_solver("scipy_ivp")
>>> res_mol = solver_mol.solve(problem, t_span=(0.0, 0.5), t_eval=t_eval)
>>> res_mol.success
True
>>>
>>> solver_cn = get_solver("crank_nicolson", dt=0.01)
>>> res_cn = solver_cn.solve(problem, t_span=(0.0, 0.5), t_eval=t_eval)
>>> res_cn.success
True
BaseSolver
¶
Bases: ABC
Abstract Base Class for all diffusion solvers.
Supports automatic registration of subclasses using name="...":
Examples:
Creating and registering a user-made solver:
>>> import numpy as np
>>> from softpotato.solver import BaseSolver, SolverResult, get_solver, list_solvers
>>>
>>> class CustomSolver(BaseSolver, name="custom_demo"):
... def _run_solver(self, problem, t_span, t_eval, **kwargs):
... t = np.array([t_span[0], t_span[1]]) if t_eval is None else t_eval
... c = {sp: np.zeros((len(t), problem.n_points)) for sp in problem.species}
... return SolverResult(t=t, x=problem.grid, concentrations=c)
>>>
>>> "custom_demo" in list_solvers()
True
>>> my_solver = get_solver("custom_demo")
>>> isinstance(my_solver, CustomSolver)
True
Source code in src/softpotato/solver/base.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
__init__
¶
Initialize solver with optional solver-specific configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**options
|
Any
|
Arbitrary solver configuration options stored in |
{}
|
Source code in src/softpotato/solver/base.py
solve
¶
solve(problem: DiffusionProblem, t_span: tuple[float, float], t_eval: ndarray | None = None, **kwargs: Any) -> SolverResult
Solve the diffusion problem over the specified time span.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
problem
|
DiffusionProblem
|
Problem definition containing grid, species, diffusivity, and boundary conditions. |
required |
t_span
|
tuple[float, float]
|
Time integration interval (t_start, t_end). |
required |
t_eval
|
ndarray
|
Specific time points to evaluate and store the solution. If None, default evaluation time points will be generated by the solver. |
None
|
**kwargs
|
Any
|
Additional run-time options passed to the underlying solver engine,
temporarily overriding any matching configuration options set in |
{}
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
Standardized container holding time, coordinates, and concentration arrays. |
Source code in src/softpotato/solver/base.py
validate
¶
Sanity and physical validity checks before integration.
Source code in src/softpotato/solver/base.py
BoundaryCondition
dataclass
¶
Specification of a 1D boundary condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
btype
|
('dirichlet', 'neumann')
|
Type of boundary condition:
|
'dirichlet'
|
value
|
float or Callable[[float], float]
|
Fixed value or a time-dependent callable \(f(t)\) returning a float. |
required |
Examples:
Constant concentration boundary condition:
>>> from softpotato.solver import BoundaryCondition
>>> bc = BoundaryCondition("dirichlet", 1.0)
>>> bc.evaluate(t=5.0)
1.0
Time-dependent concentration gradient (Neumann flux):
>>> bc_dynamic = BoundaryCondition("neumann", lambda t: -0.1 * t)
>>> bc_dynamic.evaluate(t=2.0)
-0.2
Source code in src/softpotato/solver/base.py
DiffusionProblem
dataclass
¶
Formulation of a 1D multi-species chemical diffusion problem.
Governing equation for each species \(i\):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid
|
ndarray or Mesh1D
|
1D spatial grid points \(x \in [x_{\min}, x_{\max}]\) or a
|
required |
diffusivity
|
dict[str, float]
|
Mapping from chemical species name to its diffusion coefficient \(D_i > 0\). |
required |
boundary_conditions
|
dict[str, tuple[BoundaryCondition, BoundaryCondition]]
|
Mapping from species name to a tuple of |
required |
initial_conditions
|
dict[str, float | ndarray | Callable[[ndarray], ndarray]]
|
Mapping from species name to initial concentration profile (scalar, array, or callable). |
required |
reactions
|
Callable[[dict[str, ndarray], ndarray, float], dict[str, ndarray]]
|
Reaction kinetics term returning |
None
|
species
|
list[str]
|
List of chemical species names. Inferred from diffusivity if not explicitly provided. |
list()
|
geometry
|
Geometry | str
|
Coordinate geometry specifying differential operators (\(\nabla^2\)),
normal surface flux evaluations, and active electrode area. Can be a
registered alias (e.g., |
'planar'
|
n_electrons
|
int | dict[str, int]
|
Number of electrons transferred per reaction (\(n > 0\)) for Faradaic current calculations. Can be an integer or a species-to-integer mapping. |
1
|
electrodes
|
('left', 'right', 'both')
|
Domain boundary or boundaries configured as active electrodes for Faradaic
current evaluation. Defaults to |
'left'
|
electrode_side
|
('left', 'right', 'both')
|
Alias for |
'left'
|
Examples:
Setting up a 1D problem for two species ('A' and 'B'):
>>> import numpy as np
>>> from softpotato.solver import DiffusionProblem, DirichletBC, NeumannBC
>>>
>>> grid = np.linspace(0.0, 1.0, 50)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"A": 1e-4, "B": 2e-4},
... boundary_conditions={
... "A": (DirichletBC(0.0), DirichletBC(1.0)),
... "B": (NeumannBC(0.0), DirichletBC(0.0)),
... },
... initial_conditions={"A": 1.0, "B": 0.0},
... )
>>> problem.species
['A', 'B']
>>> problem.n_points
50
>>> bool(np.isclose(problem.dx, 1.0 / 49.0))
True
Source code in src/softpotato/solver/base.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
get_initial_profile
¶
Evaluate initial concentration profile for a given species.
Source code in src/softpotato/solver/base.py
SolverResult
dataclass
¶
Standardized output container for diffusion simulations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
ndarray
|
1D array of time steps of shape (N_t,). |
required |
x
|
ndarray
|
1D array of spatial coordinates of shape (N_x,). |
required |
concentrations
|
dict[str, ndarray]
|
Dictionary mapping species name to 2D concentration array of shape (N_t, N_x). |
required |
fluxes
|
dict[str, ndarray]
|
Dictionary mapping species name to surface flux at left boundary x=0 of shape (N_t,). |
dict()
|
right_fluxes
|
dict[str, ndarray]
|
Dictionary mapping species name to surface flux at right boundary x=L of shape (N_t,) under the electrode-normal convention (pointing into the solution domain). |
dict()
|
currents
|
dict[str, ndarray]
|
Dictionary mapping species name to Faradaic current at the active electrode(s)
of shape (N_t,) in Amperes. If |
dict()
|
left_currents
|
dict[str, ndarray]
|
Dictionary mapping species name to Faradaic current at the left boundary of shape (N_t,) in Amperes. |
dict()
|
right_currents
|
dict[str, ndarray]
|
Dictionary mapping species name to Faradaic current at the right boundary of shape (N_t,) in Amperes. |
dict()
|
success
|
bool
|
Flag indicating if the numerical solution completed successfully. |
True
|
message
|
str
|
Descriptive status message. |
"Success"
|
raw_output
|
Any
|
Underlying solver output (e.g., OdeResult for SciPy). |
None
|
Examples:
Accessing simulation results:
>>> import numpy as np
>>> from softpotato.solver import SolverResult
>>>
>>> res = SolverResult(
... t=np.linspace(0, 1, 5),
... x=np.linspace(0, 1, 10),
... concentrations={"A": np.ones((5, 10))},
... fluxes={"A": np.zeros(5)},
... right_fluxes={"A": np.zeros(5)},
... )
>>> res.species
['A']
>>> res["A"].shape
(5, 10)
>>> res.fluxes["A"].shape
(5,)
>>> res.left_fluxes["A"].shape
(5,)
>>> res.right_fluxes["A"].shape
(5,)
>>> res.left_currents
{}
>>> res.right_currents
{}
Source code in src/softpotato/solver/base.py
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 | |
CrankNicolson
¶
Bases: BaseSolver
Crank-Nicolson (\(\theta = 0.5\)) finite difference diffusion solver.
Second-order accurate in both time and space: \(\mathcal{O}(\Delta t^2 + \Delta x^2)\). Unconditionally stable. Solves the coupled linear system at each time step:
Employs scipy.linalg.solve_banded to invert the tridiagonal system in \(\mathcal{O}(N)\) time at each step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
Fixed time step size \(\Delta t\). If None (default), automatically selects 100 uniform steps over the integration interval: \(\Delta t = (t_{\text{end}} - t_{\text{start}}) / 100\). |
None
|
**options
|
Any
|
Additional solver options stored in |
{}
|
Examples:
>>> import numpy as np
>>> from softpotato.solver import CrankNicolson, DiffusionProblem, DirichletBC
>>>
>>> grid = np.linspace(0.0, 1.0, 41)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"c": 0.02},
... boundary_conditions={"c": (DirichletBC(0.0), DirichletBC(0.0))},
... initial_conditions={"c": lambda x: np.sin(np.pi * x)},
... )
>>> # 2nd-order accurate time marching
>>> solver = CrankNicolson(dt=0.01)
>>> result = solver.solve(problem, t_span=(0.0, 0.2))
>>> result.success
True
>>> result["c"].shape[1]
41
Source code in src/softpotato/solver/crank_nicolson.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | |
__init__
¶
ExplicitFiniteDifference
¶
Bases: BaseSolver
Explicit Forward-Time Central-Space (FTCS) finite difference diffusion solver.
Numerically solves 1D multi-species diffusion equations:
Enforces the Courant-Friedrichs-Lewy (CFL) stability criterion using the minimum spatial interval \(\Delta x_{\min} = \min_j \Delta x_j\):
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
Fixed time step size \(\Delta t\). Must satisfy the Courant-Friedrichs-Lewy (CFL) stability condition: \[
\Delta t \le \frac{(\Delta x_{\min})^2}{2 \max_i(D_i)}
\]
If None (default), automatically selects a conservative stable step size equal to \(0.45 \times \text{CFL limit}\). |
None
|
**options
|
Any
|
Additional solver options stored in |
{}
|
Examples:
>>> import numpy as np
>>> from softpotato.solver import ExplicitFiniteDifference, DiffusionProblem, DirichletBC
>>>
>>> grid = np.linspace(0.0, 1.0, 21)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"A": 0.01},
... boundary_conditions={"A": (DirichletBC(0.0), DirichletBC(1.0))},
... initial_conditions={"A": 0.0},
... )
>>> # Use automatic CFL-safe time stepping
>>> solver = ExplicitFiniteDifference()
>>> result = solver.solve(problem, t_span=(0.0, 0.1))
>>> result.success
True
>>> result["A"].shape[1]
21
Source code in src/softpotato/solver/explicit.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | |
__init__
¶
ImplicitFiniteDifference
¶
Bases: BaseSolver
Implicit Backward-Time Central-Space (BTCS) finite difference diffusion solver.
Numerically solves 1D multi-species diffusion equations:
Unconditionally stable for arbitrary time steps \(\Delta t\). Solves the resulting
tridiagonal system using scipy.linalg.solve_banded in \(\mathcal{O}(N)\) time per step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
Fixed time step size \(\Delta t\). If None (default), automatically selects 100 uniform steps over the integration interval: \(\Delta t = (t_{\text{end}} - t_{\text{start}}) / 100\). |
None
|
**options
|
Any
|
Additional solver options stored in |
{}
|
Examples:
>>> import numpy as np
>>> from softpotato.solver import ImplicitFiniteDifference, DiffusionProblem, DirichletBC
>>>
>>> grid = np.linspace(0.0, 1.0, 31)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"A": 0.05},
... boundary_conditions={"A": (DirichletBC(0.0), DirichletBC(1.0))},
... initial_conditions={"A": 0.0},
... )
>>> # Implicit schemes remain stable even with large time steps
>>> solver = ImplicitFiniteDifference(dt=0.05)
>>> result = solver.solve(problem, t_span=(0.0, 0.5))
>>> result.success
True
>>> result["A"].shape[1]
31
Source code in src/softpotato/solver/implicit.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | |
__init__
¶
ScipyIVPSolver
¶
Bases: BaseSolver
Diffusion solver using Method of Lines (MOL) and scipy.integrate.solve_ivp.
Discretizes the spatial diffusion operator into a coupled system of ODEs:
Integrates the resulting stiff or non-stiff system using SciPy's ODE suite.
Defaults to the stiff L-stable 'Radau' integrator, suitable for diffusion-reaction systems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
('Radau', 'BDF', 'RK45', 'RK23', 'DOP853', 'LSODA')
|
ODE integration algorithm passed to
|
'Radau'
|
rtol
|
float
|
Relative error tolerance for adaptive time stepping. |
1e-6
|
atol
|
float
|
Absolute error tolerance for adaptive time stepping. |
1e-8
|
**options
|
Any
|
Additional solver options passed to |
{}
|
Examples:
Simulating reaction-diffusion with first-order decay:
>>> import numpy as np
>>> from softpotato.solver import ScipyIVPSolver, DiffusionProblem, NeumannBC
>>>
>>> grid = np.linspace(0.0, 1.0, 31)
>>> problem = DiffusionProblem(
... grid=grid,
... diffusivity={"A": 0.01},
... boundary_conditions={"A": (NeumannBC(0.0), NeumannBC(0.0))},
... initial_conditions={"A": 1.0},
... reactions=lambda c_dict, x, t: {"A": -0.5 * c_dict["A"]},
... )
>>> solver = ScipyIVPSolver(method="Radau", rtol=1e-5)
>>> result = solver.solve(problem, t_span=(0.0, 1.0))
>>> result.success
True
>>> result["A"].shape[1]
31
Source code in src/softpotato/solver/scipy_ivp.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
__init__
¶
Initialize SciPy Method of Lines IVP solver.
Source code in src/softpotato/solver/scipy_ivp.py
DirichletBC
¶
Convenience constructor for a Dirichlet boundary condition \(c = \text{value}\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float or Callable[[float], float]
|
Fixed concentration or time-dependent function \(f(t)\). |
required |
Returns:
| Type | Description |
|---|---|
BoundaryCondition
|
A boundary condition instance configured with |
Examples:
>>> from softpotato.solver import DirichletBC
>>> bc = DirichletBC(0.0)
>>> bc.btype
'dirichlet'
>>> bc.evaluate(10.0)
0.0
Source code in src/softpotato/solver/base.py
NeumannBC
¶
Convenience constructor for a Neumann boundary condition \(\frac{\partial c}{\partial x} = \text{value}\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
float or Callable[[float], float]
|
Fixed gradient \(\partial c / \partial x\) or time-dependent function \(g(t)\). |
required |
Returns:
| Type | Description |
|---|---|
BoundaryCondition
|
A boundary condition instance configured with |
Examples:
>>> from softpotato.solver import NeumannBC
>>> bc = NeumannBC(0.0)
>>> bc.btype
'neumann'
>>> bc.evaluate(0.0)
0.0
Source code in src/softpotato/solver/base.py
get_solver
¶
Instantiate a solver by its registered name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Registered solver identifier (case-insensitive), e.g. 'scipy_ivp', 'crank_nicolson', 'implicit', 'explicit'. |
required |
**kwargs
|
Any
|
Configuration options forwarded to the solver's constructor:
|
{}
|
Returns:
| Type | Description |
|---|---|
BaseSolver
|
An instance of the requested solver. |
Examples:
>>> from softpotato.solver import get_solver
>>> solver = get_solver("scipy_ivp", method="Radau")
>>> solver.options["method"]
'Radau'
>>> solver_cn = get_solver("crank_nicolson", dt=0.01)
>>> solver_cn.options["dt"]
0.01
Source code in src/softpotato/solver/base.py
list_solvers
¶
Return a list of all currently registered solver names.
Returns:
| Type | Description |
|---|---|
list[str]
|
Alphabetically sorted list of registered solver names. |
Examples:
>>> from softpotato.solver import list_solvers
>>> solvers = list_solvers()
>>> "scipy_ivp" in solvers
True
>>> "crank_nicolson" in solvers
True
Source code in src/softpotato/solver/base.py
register_solver
¶
Decorator to register a custom solver class under a given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name identifier to associate with the decorated solver class. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[type[BaseSolver]], type[BaseSolver]]
|
Decorator registering the class into BaseSolver._registry. |
Examples:
>>> import numpy as np
>>> from softpotato.solver import BaseSolver, SolverResult, register_solver, get_solver
>>>
>>> @register_solver("spectral_decorator_demo")
... class SpectralSolver(BaseSolver):
... def _run_solver(self, problem, t_span, t_eval, **kwargs):
... return SolverResult(t=np.array([0, 1]), x=problem.grid, concentrations={})
>>>
>>> solver = get_solver("spectral_decorator_demo")
>>> isinstance(solver, SpectralSolver)
True