molfoundry.Stochsim#
- class molfoundry.Stochsim(*, graphDatabase, expandStrategy, initialState, labelSettings=None, reactionRate=None, inputRate=None, outputRate=None, drawTime=None, retainHistory=True, onStep=None, seed=42)[source]#
Bases:
TSObjectRule-based Gillespie stochastic simulation with on-demand network expansion.
Implements Herrera Machado et al., “Rule-Based Gillespie Simulation of Chemical Systems” (2025): the reaction network is not enumerated up front but grown lazily as new species appear, while an exact SSA evolves the species counts.
Rates may be constants (evaluated once) or callbacks. Following MØD’s
DrawMassAction, a callback returns either a rate or a(rate, cache)pair and – unless it caches – is re-evaluated every step, so rates may depend on the currenttimeorstate(). The underlying simulator applies the Law of Mass Action on top of the returned rate constant. The waiting-time distribution is customizable viadrawTime(default: exponential), mirroring MØD’sDrawTimeExponential.Create a rule-based Gillespie simulation.
retainHistory(defaultTrue) keeps the whole trajectory in memory, sotrajectory()/series()andprint()work directly. Set it toFalsefor long / large runs to bound memory to O(species): the engine then holds only the start and current step. The full trajectory is instead streamed to a history file under./out(adjacent to./summary) soprint()can still rebuild the interactive playback;trajectory()/series(), which need the in-memory log, are unavailable in that mode.onStepis an optional callback invoked once for the start step and then for every step as it is produced, receiving aStepInfo(index,time,reaction). It fires synchronously as the step is recorded, so it may read the live state via this simulation (e.g.state()) — the streaming hook that pairs withretainHistory=False.- Parameters:
expandStrategy (Any)
labelSettings (LabelSettings | None)
reactionRate (float | int | Tuple[float, bool] | Callable[[...], Any] | None)
inputRate (float | int | Tuple[float, bool] | Callable[[...], Any] | None)
outputRate (float | int | Tuple[float, bool] | Callable[[...], Any] | None)
drawTime (Callable[[float, Callable[[], float]], float] | None)
retainHistory (bool)
onStep (Callable[[Stochsim.StepInfo], Any] | None)
seed (int)
- setReactionRate(rate)[source]#
Set the rate for each reaction (default: 1 per hyperedge).
rateis a constant (float, or a(rate, cache)pair) or a callback(DG.HyperEdge) -> float | (float, bool). A callback is re-evaluated every step unless it returnscache=True, so reaction rates may depend ontimeorstate(). The engine applies the Law of Mass Action on top of the returned rate constant.
- setInputRate(rate)[source]#
Set the input-flow (∅ -> species) rate (default: 0, closed system).
rateis a constant or a callback(DG.Vertex) -> float | (float, bool)with the same re-evaluation semantics assetReactionRate().
- setOutputRate(rate)[source]#
Set the output-flow (species -> ∅) rate (default: 0, closed system).
rateis a constant or a callback(DG.Vertex) -> float | (float, bool)with the same re-evaluation semantics assetReactionRate().
- setDrawTime(drawTime)[source]#
Set the waiting-time strategy, or
Noneto restore the default Gillespie exponential drawln(1 / uniform()) / totalPropensity.drawTimeis called asdrawTime(totalPropensity, uniform), whereuniform()yields independent draws in [0, 1) from the simulator’s own seeded RNG, and must return the time increment until the next reaction. Must be set before the simulation starts.
- setOnStep(onStep)[source]#
Set a per-step callback, or
Noneto clear it.onStepreceives aStepInfoonce for the start step and then for every step produced. Set it beforesimulate()so the start step is seen; the callback runs synchronously as the step is recorded and may read the live state through this simulation.
- simulate(time=None, iterations=None, advanceToEndTime=False)[source]#
Advance the simulation up to a time bound and/or iteration bound.
Both bounds are relative to the current state, so repeated calls continue. With neither bound the simulation runs until it deadlocks.
With a
timebound,advanceToEndTimeparks the clock at exactly that time when no reaction fires before it (the drawn event overshot, or the system is momentarily dead), appending a no-reaction marker step at the bound. This lets a latersimulatesegment re-evaluate a time-dependent rate at that instant – reviving an otherwise dead system – or a scheduled intervention (e.g.state()-dependent rate, or a follow-up action) land at exactly that time. Off by default, so the clock otherwise stops at the last event.
- print(printer=None, *, name=None, dark='dynamic')[source]#
Write an interactive HTML playback of this simulation to the summary folder.
Produces one standalone, seekable page (
<name>.htmlnext tosummary.html) that lays out the final derivation graph as oval-framed molecule depictions, shows each molecule’s current count below it, and reveals nodes/hyperedges at the step they were first expanded. Play / pause / stop and a speed control step through the whole simulation.printeris an optionalGraphPrinter– exactly as forDG.print()– threaded to every molecule depiction so itsdrawMode/collapseHydrogenssettings control how the molecules are drawn.namesets the filename (defaultstochsim). Like the rest of the summary the file is flushed when the process exits; returns the target filename.With
retainHistory=Falsethe trajectory is rebuilt from the streamed./outhistory file rather than the (absent) in-memory log.- Parameters:
printer (GraphPrinter | None)
name (str | None)
dark (Any)
- Return type:
- class StepInfo(index, time, reaction)[source]#
Bases:
objectOne step handed to an
onStepcallback.- index#
Absolute step index in the trajectory (0 is the start step).
- time#
Simulation time at this step.
- reaction#
Name of the reaction that fired, or
Nonefor the start step and no-reaction time markers.