OneSimulation docs Website Free books Plans on Gumroad

Docs › Worked numerical comparisons › Time integration and continuation lab

9.7 Time integration and continuation lab

9.7.1 Separate temporal error from the physical model

Repeat an RC step with successively smaller time steps. The plotted error is the final voltage error against an exact exponential. A steady mesh-free model isolates the time method.

import numpy as np
import matplotlib.pyplot as plt
import onesimulation_plot_theme as theme
from onesim.cad.geometry import LumpedDomain
from onesim.meshing import LumpedMesh
from onesim.numerics import Numerics
from onesim.numerics.discretization import LumpedParameters
from onesim.numerics.linear import SparseDirect
from onesim.numerics.nonlinear import Newton
from onesim.numerics.time import (
    TimeMethod,
    ForwardEuler,
    ClassicalRungeKutta4,
    BackwardEuler,
    BDF,
)
from onesim.physics.systems import ResistorCapacitor
from onesim.simulation import Problem, Simulation
from onesim.simulation.initial_conditions import InitialValue

domain = LumpedDomain()
rc = ResistorCapacitor(
    domain=domain.system, resistance=2, capacitance=0.5, supply_voltage=3
)
problem = Problem(
    name="RC time convergence",
    geometry=domain,
    physics=(rc,),
    initial_conditions=(InitialValue(rc.voltage, 0.0),),
)
methods = (
    ForwardEuler(),
    TimeMethod("ssprk2"),
    ClassicalRungeKutta4(),
    BackwardEuler(),
    TimeMethod("crank_nicolson"),
    BDF(order=2),
)
steps = (0.1, 0.05, 0.025)
exact = 3 * (1 - np.exp(-1))
theme.use_theme()
fig, ax = plt.subplots(figsize=(6.8, 3.8), layout="constrained")
for method in methods:
    errors = []
    solver = (
        Newton(linear_solver=SparseDirect(), jacobian="analytic")
        if method.implicit
        else None
    )
    sim = Simulation(
        problem=problem,
        mesh=LumpedMesh(domain),
        numerics=Numerics(
            spatial=LumpedParameters(),
            time_integrator=method,
            nonlinear_solver=solver,
        ),
    )
    for dt in steps:
        result = sim.run(start_time=0, end_time=1, time_step=dt)
        y = np.asarray(result.field(rc.voltage).values).item()
        errors.append(abs(y - exact))
    assert errors[-1] < errors[0]
    ax.loglog(steps, errors, "o-", label=method.method_id)
ax.set(xlabel="Time step [s]", ylabel="Final absolute voltage error [V]")
ax.legend(frameon=False, ncol=2)
plt.show()
Figure computed with OneSimulation: recipe time convergence

9.7.2 Adaptive field threshold and BDF continuation

Use a typed event on capacitor voltage to stop an adaptive run at a known threshold. Independently, checkpoint a fixed-step BDF run at an aligned time and compare its restart against a run with the same time history.

import numpy as np
import matplotlib.pyplot as plt
import onesimulation_plot_theme as theme
from onesim.cad.geometry import LumpedDomain
from onesim.meshing import LumpedMesh
from onesim.numerics import Numerics
from onesim.numerics.discretization import LumpedParameters
from onesim.numerics.linear import SparseDirect
from onesim.numerics.nonlinear import Newton
from onesim.numerics.time import AdaptiveTimeStep, ClassicalRungeKutta4, BDF
from onesim.physics.systems import ResistorCapacitor
from onesim.simulation import Problem, Simulation, ExecutionOptions, FieldThreshold
from onesim.simulation.initial_conditions import InitialValue

domain = LumpedDomain()
rc = ResistorCapacitor(
    domain=domain.system, resistance=2, capacitance=0.5, supply_voltage=3
)
problem = Problem(
    name="RC threshold",
    geometry=domain,
    physics=(rc,),
    initial_conditions=(InitialValue(rc.voltage, 0.0),),
)
mesh = LumpedMesh(domain)
explicit = Simulation(
    problem=problem,
    mesh=mesh,
    numerics=Numerics(
        spatial=LumpedParameters(), time_integrator=ClassicalRungeKutta4()
    ),
)
event = FieldThreshold(
    field=rc.voltage,
    value=1.5,
    event_id="half-charge",
    direction=1,
    value_tolerance=1e-10,
)
adaptive = explicit.run(
    start_time=0,
    end_time=1.2,
    time_step=AdaptiveTimeStep(
        initial=0.02, minimum=1e-6, maximum=0.08, relative_tolerance=1e-7
    ),
    execution_options=ExecutionOptions(events=(event,)),
)
assert abs(adaptive.times[-1] - np.log(2)) < 2e-5
implicit = Simulation(
    problem=problem,
    mesh=mesh,
    numerics=Numerics(
        spatial=LumpedParameters(),
        time_integrator=BDF(order=2),
        nonlinear_solver=Newton(linear_solver=SparseDirect(), jacobian="analytic"),
    ),
)
checkpoints = ExecutionOptions(checkpoint_interval=0.4)
first = implicit.run(
    start_time=0, end_time=0.4, time_step=0.02, execution_options=checkpoints
)
resumed = implicit.run(
    start_time=0,
    end_time=0.8,
    time_step=0.02,
    execution_options=ExecutionOptions(restart_checkpoint=first.last_checkpoint),
)
full = implicit.run(
    start_time=0, end_time=0.8, time_step=0.02, execution_options=checkpoints
)
np.testing.assert_allclose(
    resumed.field(rc.voltage).values, full.field(rc.voltage).values, atol=1e-12
)
t = np.asarray(adaptive.times)
y = np.asarray(
    [adaptive.field(rc.voltage).at(float(time)).values.item() for time in t]
)
theme.use_theme()
fig, ax = plt.subplots(figsize=(6.8, 3.5), layout="constrained")
ax.plot(t, y, "o-", label="Accepted adaptive states")
ax.axhline(1.5, color=theme.COPPER, linestyle="--", label="Terminal threshold")
ax.set(xlabel="Accepted time [s]", ylabel="Voltage [V]")
ax.legend(frameon=False)
plt.show()
Figure computed with OneSimulation: recipe adaptive event restart