molfoundry.MultiPhaseStochsim#
- class molfoundry.MultiPhaseStochsim(*, labelSettings=None, retainHistory=True, onStep=None, seed=42)[source]#
Bases:
TSObjectExact multiphase (multi-compartment) stochastic simulation.
nphases each run the rule-based Gillespie SSA with lazy network expansion; the whole system is evolved as one combined continuous-time Markov chain by a single shared simulator (one clock, one RNG, one global propensity) – the exact Direct-Method realization.Stage A: phases only, no interphase channels yet. A phase may still exchange with the implicit outside via its own
inputRate/outputRateflows, and a single channel-free phase reproducesStochsimfor the same seed. All phases share oneLabelSettingsso species identity is comparable across phases by canonical key.Create a multiphase stochastic simulation.
retainHistoryandonStephave the same meaning as forStochsim: withretainHistory=Falsethe engine holds only O(species) state and the full trajectory is streamed to a history file under./outsoprint()can still rebuild the playback (whiletrajectory()/series()/times(), which need the in-memory log, are unavailable).onStepfires once per step with aStepInfo.- Parameters:
labelSettings (LabelSettings | None)
retainHistory (bool)
onStep (Callable[[Stochsim.StepInfo], Any] | None)
seed (int)
- setOnStep(onStep)[source]#
Set a per-step callback, or
Noneto clear it.See
Stochsim.setOnStep(). The callback receives aStepInfoonce for the start step and then for every step across the whole (shared-clock) system.
- addPhase(name, *, graphDatabase, expandStrategy, volume=1.0, initialState=None, reactionRate=None, inputRate=None, outputRate=None, labelSettings=None)[source]#
Add a phase (compartment) with its own chemistry, volume, and rates.
graphDatabase,expandStrategy, and the rate arguments have the same meaning as forStochsim;volumeis stored for later partition channels.labelSettingsoverrides the constructor’sLabelSettingsfor this phase only. Species identity stays comparable across phases (they are matched by the graph’s intrinsic canonical key), so, e.g., a wildcard-free phase can use cheap string/isomorphism matching while a phase with_X-style term rules uses term/specialisation.- Parameters:
name (str)
expandStrategy (Any)
volume (float)
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)
labelSettings (LabelSettings | None)
- Return type:
- addChannel(*, source, target, rate, species=None, select=None)[source]#
Add a constant first-order transport channel
source -> target.Selectivity (which species may cross) is one of:
species(a single graph),select(a predicateGraph -> boolor an iterable of graphs), or neither (all species).rateis the per-molecule transfer rate constant (the engine applies mass action,rate * count(species in source), on top), either a number or a callback(Graph) -> float | (float, bool)re-evaluated each step for saturable / gated / state-dependent transport. Bidirectional exchange is two channels (seeaddPartitionfor the thermodynamically-consistent pair).
- addCoupledChannel(*, reactants, products, rate)[source]#
Add a coupled cross-phase reaction (symport / antiport / reactive transport).
reactantsandproductsare lists of(species_graph, phase)pairs (phasea Phase or index). Mass action requires all reactants present, so e.g. a symport fires only when every co-transported species is available.rateis a constant or a no-argument callback() -> float | (float, bool). All named species must be representable in their phases (in thegraphDatabaseor derivable there).
- addPartition(*, source, target, Kd, rate, species=None, select=None)[source]#
Add a thermodynamically-consistent partition (a bidirectional pair).
Kdis the equilibrium distribution coefficient[target]/[source];rateis the forward (source -> target) per-molecule rate constant. The backward constant is derived to enforce detailed balance across the (possibly unequal) phase volumes:k_f/k_b = Kd * (V_target/V_source), so the pair on its own relaxes to[target]/[source] = Kd. Selectivity is specified as foraddChannel(). Returns(forward, backward).
- setDrawTime(drawTime)[source]#
Set the global waiting-time strategy; see
Stochsim.setDrawTime().
- simulate(time=None, iterations=None, advanceToEndTime=False)[source]#
Advance the whole system up to a time and/or iteration bound.
Both bounds are relative to the current state, so repeated calls continue; with neither bound the system runs until a global deadlock.
With a
timebound,advanceToEndTimeparks the shared clock at exactly that time when no reaction fires before it (the drawn event overshot, or the whole system is momentarily dead), so a subsequent segment re-evaluates time-dependent rates there (reviving a dead system) or a scheduledtransfer()lands at exactly that time. Off by default.
- transfer(source, target, *, species=None, fraction=None, amount=None)[source]#
Discrete scheduled transfer between two phases, applied at the current time.
This is an operator step between
simulate()segments – serial passage / dilution, pipetting an aliquot, decanting a layer, or a deterministic spike-in – not an intrinsic reaction, so it does not advance the iteration count. It is applied atomically (one injection) and the target phase’s network is expanded around any species new to it, so the transferred molecules react and flow onward on subsequent steps. Provide exactly one of:fraction– move a binomially-sampled aliquot (each molecule crosses independently with probabilityfraction, drawn on the shared RNG). Withspecies=Noneevery species currently present insourceis aliquoted (a whole-compartment dilution); with aspeciesgraph, only that one.amount– move exactly that many molecules of a specificspecies(a deterministic spike-in / decant); raises if fewer are present.
Returns the total number of molecules moved (
sourceandtargetare a Phase or an index).
- print(printer=None, *, name=None, dark='dynamic')[source]#
Write an interactive HTML playback of this multiphase run to the summary folder.
Produces one standalone, seekable page (
<name>.htmlnext tosummary.html) with one box per phase (name at the top-left), the final per-phase derivation graphs as oval-framed molecule depictions with live counts below them, dotted bent arrows for the inter-phase channels, and input/output flows drawn to the outside of each box. Nodes and hyperedges are revealed 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 (across all phases) so itsdrawMode/collapseHydrogenssettings control how the molecules are drawn.namesets the filename (defaultmultiphase). Flushed at process exit; 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 Phase(parent, index, ref)[source]#
Bases:
objectA single phase (compartment). Obtained from
addPhase().- Parameters:
parent (MultiPhaseStochsim)
index (int)
ref (Any)
- index#
Index of this phase within its owning simulation.
- setReactionRate(rate)[source]#
See
Stochsim.setReactionRate()(scoped to this phase).
- setInputRate(rate)[source]#
See
Stochsim.setInputRate()(this phase’s flow to the outside).
- setOutputRate(rate)[source]#
See
Stochsim.setOutputRate()(this phase’s flow to the outside).
- class Channel(parent, ref)[source]#
Bases:
objectA transport channel. Obtained from
addChannel().- Parameters:
parent (MultiPhaseStochsim)
ref (Any)
- class Trajectory(times, columnPhases, columnVertexIds, counts)[source]#
Bases:
object- Parameters:
- times#
Time stamp of each recorded step.
- columnPhases#
Phase index of each column of
counts.
- columnVertexIds#
DG vertex index (within its phase) of each column of
counts.
- counts#
counts[step][column]molecule counts.