Docs › Worked physics and service recipes › Shared cell for lumped histories
6.1 Shared cell for lumped histories
Use this cell for a single lumped model with scalar field references. Output snapshots contain accepted model state and derived values. Each plotted ordinate inherits its unit from the field definition. Supply the named initial states before choosing observables.
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.time import ClassicalRungeKutta4
from onesim.results.storage import MemoryOutputSink, Output
from onesim.simulation import Problem, Simulation
from onesim.simulation.initial_conditions import InitialValue
def history_case(
domain, model, initial, observe, *, end, dt, spatial=None, linear_solver=None
):
refs = tuple(model.field(name) for name in observe)
problem = Problem(
name=type(model).__name__,
geometry=domain,
physics=(model,),
initial_conditions=tuple(
InitialValue(model.field(name), value) for name, value in initial.items()
),
)
sim = Simulation(
problem=problem,
mesh=LumpedMesh(domain),
numerics=Numerics(
spatial=LumpedParameters() if spatial is None else spatial,
time_integrator=ClassicalRungeKutta4(),
linear_solver=linear_solver,
),
)
sim.validate().require_valid()
sink = MemoryOutputSink()
sim.run(
start_time=0,
end_time=end,
time_step=dt,
output=Output(fields=refs, interval=4 * dt, sink=sink),
)
t = np.array([float(s.time) for s in sink.snapshots])
assert np.isclose(t[-1], end)
data = {
ref.name: np.array(
[np.asarray(s.fields[ref.field_id].values).item() for s in sink.snapshots]
)
for ref in refs
}
assert all(np.isfinite(y).all() for y in data.values())
return t, data
def history_plot(title, model, t, data):
theme.use_theme()
fig, axes = plt.subplots(
len(data),
1,
sharex=True,
squeeze=False,
figsize=(7.2, 1.22 * len(data) + 0.85),
layout="constrained",
)
for ax, (name, y) in zip(axes[:, 0], data.items()):
ref = model.field(name)
ax.plot(t, y)
ax.set_ylabel(ref.unit)
ax.set_title(name.replace("_", " ").capitalize(), loc="left", fontsize=9)
ax.grid(alpha=0.25)
axes[-1, 0].set_xlabel("Time [s]")
fig.suptitle(title, color=theme.INK, fontweight="bold")
return fig