Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Python API

The public names of crn_craft 0.10.1: everything in crn_craft.__all__, the methods of Model, PreparedEnsemble, Result, FspResult and CompiledLoop, and the modules crn_craft.importers, crn_craft.likelihood and crn_craft.sensitivities. The page is generated from the signatures and docstrings of the installed package, so it lists what the package does. Examples are in the guide; this page has none.

Import the package as import crn_craft as crn. crn_craft.rules is the API of release 0.6.0 under its old name. It has the same names with the defaults and document versions of 0.6.0; the migration page lists the differences. Code written for it keeps running.

crn_craft.rules.ensemble takes the arguments of ensemble below. Its quantiles defaults to None (no quantiles), and an absent selector means the linear scan.

Contents: Models, Running, Experiments and probability laws, Likelihoods and sensitivities, Results, Files and archives, Analysis and import/export, Compiled loops.

Models

Build a model in Python, or take a packaged one. Model writes crn-craft.model/1.0. The language of the document is in the model reference; chapter 2 of the guide teaches the builder, and chapter 12 species with attributes.

Model

class Model(name='model')

A model built call by call, written as crn-craft.model/1.0.

ArgumentDefaultMeaning
name'model'The model’s name.

The builder of crn_craft.rules.Model (the same methods: add_species, add_initial, add_parameter, add_reaction, add_observable, set_initial, set_stop, add_ode, to_dict, to_json, from_dict, fsp, analyze, to_gillespy2), whose documents are always crn-craft.model/1.0. Species are plain counts, or carry attributes (add_species(name, attributes=[...])), whose molecules reactions match with pattern and create with copy and new. add_reaction accepts any number of reactant molecules of attribute-free species; ["A", "A", "A"] is a third-order reaction.

Model.add_species

Model.add_species(name, initial=0, attributes=None)

Declare species with initial counts (default 0), or with attributes.

ArgumentDefaultMeaning
namerequiredA species name, or a mapping from names to initial counts.
initial0Initial count. Not allowed with a mapping; 0 for a species with attributes.
attributesNoneAttribute names, for example ["clone"], or None for a plain count.

add_species("S", 999) declares one; add_species({"S": 999, "I": 1}) declares every entry of a mapping, in its order, as one call each would. A mapping takes no other argument (TypeError). If an entry is invalid, nothing is declared. A species that a reaction already introduced keeps its position and takes the count.

attributes, a list of attribute names, declares a species whose molecules carry numeric attributes, for example add_species("mtDNA", attributes=["clone"]): each attribute vector is an instance with its own count, and the run creates and removes instances. Its molecules at time 0 come from add_initial, so initial must stay 0, and each such species is declared in its own call (a mapping with attributes raises TypeError). Declare it before the reactions that use it. Every species, with attributes or not, has an observable under its own name: its total count of molecules.

Model.add_initial

Model.add_initial(name, count, /, **attributes)

Add count molecules of species name at time 0.

ArgumentDefaultMeaning
namerequiredA declared species.
countrequiredA nonnegative integer, or a parameter expression for a species with attributes.
**attributesnoneEvery attribute of the species, as a number or a parameter expression.

For a species with attributes every attribute is a keyword, for example add_initial("mtDNA", 1000, clone=0): the molecules of one instance. Values are numbers or parameter expressions, and count is a nonnegative integer or a parameter expression such as "K". Call it once per attribute vector; a second call with the same values adds to the count. For a species without attributes it adds count, an integer, to the initial count.

Model.add_parameter

Model.add_parameter(name, value=<required>)

Declare parameters that string rates may read.

ArgumentDefaultMeaning
namerequiredA parameter name, or a mapping from names to values.
valuerequiredThe value. Not allowed with a mapping.

add_parameter("gamma", 0.01) declares one; add_parameter({"gamma": 0.01, "beta": 2e-4}) declares every entry of a mapping, in its order, as one call each would. A mapping takes no other argument (TypeError). If an entry is invalid, nothing is declared. add_parameters is the same method.

Model.add_parameters

Model.add_parameters(name, value=<required>)

Declare parameters that string rates may read.

ArgumentDefaultMeaning
namerequiredA parameter name, or a mapping from names to values.
valuerequiredThe value. Not allowed with a mapping.

add_parameter("gamma", 0.01) declares one; add_parameter({"gamma": 0.01, "beta": 2e-4}) declares every entry of a mapping, in its order, as one call each would. A mapping takes no other argument (TypeError). If an entry is invalid, nothing is declared. add_parameters is the same method.

Model.add_reaction

Model.add_reaction(rate, reactants, products, name=None)

Add a reaction reactants -> products.

ArgumentDefaultMeaning
raterequiredA number (a mass-action constant), mass_action(expression) (the same, as an expression) or a string (the whole propensity).
reactantsrequiredSpecies names, repeated for multiplicity: ["A", "A"]; pattern(...) or pattern dictionaries.
productsrequiredSpecies names, repeated for multiplicity; copy(...), new(...) or product dictionaries.
nameNoneThe rule’s name. Default r<index>.

rate is a number (a mass-action constant k: the reaction fires at k times the number of distinct combinations of reactant molecules, so ["A", "A"] fires at k·A(A−1)/2), a string (the whole propensity) or mass_action (an expression that a reaction multiplies by the number of combinations, like a number). Species are lists of names, repeated for multiplicity, for example ["A", "A"]. Three or more reactant molecules, such as ["A", "A", "A"] or ["A", "A", "B"], are written with the pattern field count of crn-craft.model/1.0 (a numeric k fires at k·C(A, 2)·B for ["A", "A", "B"]; a string propensity applies while each species has its count). Species not yet declared are declared with count 0, as in rebop. name defaults to r<index>.

For species with attributes, a reactant is a species name (any molecule; the first is labeled x, the second y) or a pattern with a where condition or factor; a product is copy (copy("x") keeps the attributes of reactant x) or new (every attribute given), never a bare name. The pattern and product dictionaries of the model document are accepted too. A reaction with where or factor takes a number or mass_action as its rate. A plain string stays the whole propensity: for a species with attributes the reaction fires at that rate and takes a molecule uniformly, whatever its attributes, and only the tree method (method=None) runs it unless the species has a single instance. Reactions over species with attributes take at most two reactant molecules.

pattern

pattern(species, where=None, factor=None, label=None)

A reactant of add_reaction: the molecules of species that match.

ArgumentDefaultMeaning
speciesrequiredA species name.
whereNoneA condition over parameters and the molecule’s attributes, or None.
factorNoneA weight per molecule (a number or an expression), or None for 1.
labelNoneThe molecule’s label; None means x for the first reactant and y for the second.

where is a condition over parameters and the molecule’s attributes, for example "x.clone > 0"; factor is a weight h ≥ 0 per molecule over the same names (a number or an expression), so the reaction fires at its rate times the sum of h over the matching molecules. label names the molecule in where, factor, product attributes and copy; it defaults to x for the first reactant and y for the second, so a condition on the second reactant reads y.clone (or give label). A plain species name is the pattern without where and factor. A reaction with a where or factor takes a rate per combination of molecules, a number or mass_action, not a whole-propensity string. The model document writes it as {"label", "type", "where", "factor"}; such a dictionary is accepted as a reactant too.

copy

copy(label, /, **attributes)

A product of add_reaction: a copy of the reactant labeled label.

ArgumentDefaultMeaning
labelrequiredThe label of the reactant to copy.
**attributesnoneAttributes to override, as numbers or expressions.

The product has the reactant’s species and attribute values, except the attributes given as keywords, which it overrides: for example copy("x", size="x.size + 1"). Values are numbers or expressions over parameters, the reactants’ attributes (x.clone) and random draws (new_id(), bernoulli(p), choice(p, a, b), uniform(a, b), normal(m, s)). Reactants are consumed, so ["mtDNA"] -> [copy("x"), copy("x")] is a replication that keeps the clone (one molecule more), and [copy("x")] alone gives the molecule back. The model document writes {"type": ..., "copy": label, "attributes": {...}}; such a dictionary is accepted as a product too.

new

new(species, /, **attributes)

A product of add_reaction: a molecule of species with the given attributes.

ArgumentDefaultMeaning
speciesrequiredA species name.
**attributesnoneEvery attribute of the species, as numbers or expressions.

Every attribute of the species is given as a keyword; values are numbers or expressions over parameters, the reactants’ attributes and random draws, for example new("mtDNA", clone="new_id()"), which founds a new clone, or new("Cluster", size="x.size + y.size"). A species without attributes takes none: new("A") is the same as "A". The model document writes {"type": species, "attributes": {...}}; such a dictionary is accepted as a product too.

mass_action

mass_action(expression)

A rate for add_reaction: expression per combination of molecules.

ArgumentDefaultMeaning
expressionrequiredAn expression over parameters and observables, or a number.

The reaction fires at the expression’s value g times the number of distinct combinations of reactant molecules, as a numeric rate does: one reactant x of a species with N molecules fires at g·N, and with a pattern at g times the sum of factor over the matching molecules. The expression reads parameters and observables, for example mass_action("r * max(0, K - N) / N"), and is written as the rule’s rate. A plain string rate is different: it is the reaction’s whole propensity (the rule’s propensity), and a firing then takes reactant molecules uniformly. For one reactant without where or factor the two describe the same process: mass_action("delta") and "delta * N" (with N the count) on ["mtDNA"] both fire at δN and take a molecule uniformly. A whole propensity cannot be combined with where or factor, and the static methods run it only over a species with a single instance, so a per-molecule rate on a species with attributes is mass_action. A number is accepted too and means what it means as a rate.

Model.add_observable

Model.add_observable(
    name,
    species,
    where=None,
    weight=None,
    reduce='sum',
    label=None,
)

Declare an observable: a number reduced from the molecules of species.

ArgumentDefaultMeaning
namerequiredThe observable’s name; it shares a namespace with parameters and species.
speciesrequiredA declared species.
whereNoneA condition over parameters and the instance’s attributes, or None for every instance.
weightNoneA number or an expression per instance; None means 1.
reduce'sum'"sum", "distinct", "max", "min" or "max_count".
labelNoneThe instance’s name in where and weight; None means x.

Over the present instances of species that satisfy where (a condition over parameters and the instance’s attributes, for example "x.clone > 0"), with weight per instance (a number or an expression over the same names, default 1), reduce gives:

  • "sum" (default): the sum of weight × count, so without weight the number of matching molecules;
  • "distinct": the sum of the weights, each instance once, so without weight the number of distinct matching instances (for example clones);
  • "max", "min": the largest or smallest weight, 0 when no instance matches;
  • "max_count": the largest copy number among the matching instances, times the weight, 0 when none matches (for example the size of the largest clone); it exists only in crn-craft.model/1.0.

A model with an observable of this call is written as crn-craft.model/1.0, also by crn_craft.rules.Model.

label names the instance in where and weight (default x). Rates (strings and mass_action), the stop condition and trackers read observables by name, and results have a column for each. The name shares one namespace with parameters, species and continuous variables; every species already has an observable under its own name, its count.

Model.set_initial

Model.set_initial(counts=None, /, **kwargs)

Set initial counts of declared species, from a mapping or keywords.

ArgumentDefaultMeaning
countsNoneA mapping from species names to counts.
**kwargsnoneThe same, as keywords: set_initial(S=990, I=10).

model.set_initial({"S": 990, "I": 10}) and model.set_initial(S=990, I=10) are equivalent. A species with attributes takes its molecules from add_initial instead.

Model.set_stop

Model.set_stop(condition)

Set the stop condition, or remove it with None.

ArgumentDefaultMeaning
conditionrequiredAn expression over parameters and species counts, or None to remove the stop.

condition is an expression over parameters and species counts, for example "I == 0" or "N > 0 && mutants >= 0.9 * N". Once it is true (it is checked at time 0 and after every event), a replicate keeps its state to the end of the report grid and is recorded as "stopped", with its stop_time. It cannot read continuous variables; a bound of add_ode stops on those.

Model.add_ode

Model.add_ode(
    name,
    initial,
    derivative,
    independent=False,
    lower_bound=None,
    on_bound='stop',
)

Declare a continuous variable dx/dt = derivative between events.

ArgumentDefaultMeaning
namerequiredThe variable’s name.
initialrequiredA number or a parameter expression.
derivativerequiredAn expression over parameters, species counts and continuous variables.
independent (keyword only)FalseTrue if initial and derivative read only parameters and other independent variables.
lower_bound (keyword only)NoneA number or a parameter expression, or None.
on_bound (keyword only)'stop'"stop" ends the replicate at the bound, "clamp" holds the variable there.

initial and lower_bound are numbers or parameter expressions; derivative is an expression over parameters, species counts and continuous variables. String rates may read the variable. With a lower_bound, on_bound is "stop" (end the replicate when the variable reaches the bound) or "clamp" (hold it there). Run such a model with method="hybrid".

independent=True declares that initial and derivative read only parameters and other independent variables, never species counts, so the ODE can be solved once for the whole run instead of per replicate. It writes "independent": true on the variable and makes to_dict write crn-craft.rules-model/0.4; the engine refuses an independent variable that reads anything else. Without independent variables the document is rules-model/0.3, as before. add_ODE is the same method.

Model.add_ODE

Model.add_ODE(
    name,
    initial,
    derivative,
    independent=False,
    lower_bound=None,
    on_bound='stop',
)

Declare a continuous variable dx/dt = derivative between events.

ArgumentDefaultMeaning
namerequiredThe variable’s name.
initialrequiredA number or a parameter expression.
derivativerequiredAn expression over parameters, species counts and continuous variables.
independent (keyword only)FalseTrue if initial and derivative read only parameters and other independent variables.
lower_bound (keyword only)NoneA number or a parameter expression, or None.
on_bound (keyword only)'stop'"stop" ends the replicate at the bound, "clamp" holds the variable there.

initial and lower_bound are numbers or parameter expressions; derivative is an expression over parameters, species counts and continuous variables. String rates may read the variable. With a lower_bound, on_bound is "stop" (end the replicate when the variable reaches the bound) or "clamp" (hold it there). Run such a model with method="hybrid".

independent=True declares that initial and derivative read only parameters and other independent variables, never species counts, so the ODE can be solved once for the whole run instead of per replicate. It writes "independent": true on the variable and makes to_dict write crn-craft.rules-model/0.4; the engine refuses an independent variable that reads anything else. Without independent variables the document is rules-model/0.3, as before. add_ODE is the same method.

Model.add_continuous

Model.add_continuous(
    name,
    initial,
    derivative,
    lower_bound=None,
    on_bound='stop',
)

Deprecated since 0.5.0: use add_ode, which takes the same arguments and independent=. Writes the same document as before.

ArgumentDefaultMeaning
namerequiredThe variable’s name.
initialrequiredA number or a parameter expression.
derivativerequiredAn expression over parameters, species counts and continuous variables.
lower_bound (keyword only)NoneA number or a parameter expression, or None.
on_bound (keyword only)'stop'"stop" ends the replicate at the bound, "clamp" holds the variable there.

Model.from_dict

Model.from_dict(document)

A model of a complete model document.

ArgumentDefaultMeaning
documentrequiredA model document: crn-craft.model/1.0, a rules-model or a network model/0.1.

document is a dictionary, JSON text or bytes: any rules-model version, crn-craft.model/1.0 or a network crn-craft.model/0.1, which is converted first (crn_craft.convert). The engine checks it (CrnError with its diagnostics if invalid). to_dict returns the document as given, key order included, so its hash is that of the document; crn_craft.Model.from_dict writes it as crn-craft.model/1.0, changing only the schema string of a rules-model.

A document the builder could have written stays editable: the add_* and set_* methods work, and after the first edit to_dict writes the builder’s document (explicit default values such as "attributes": [] are then left out, and the entries of initial and observables are grouped by species, which changes the bytes but not the meaning). That is a rules-model/0.3, 0.4 or model/1.0 document (for crn_craft.Model also rules-model/0.1 and 0.2 without an ATP block) whose types, initial entries and observables have the fields of add_species, add_initial and add_observable, with one numeric initial count per species without attributes; every converted network model, the packaged examples and documents that to_dict wrote are such documents. A species whose count observable (an observable named after it, over all its molecules) is missing in the document keeps it missing. Any other document (an ATP block, two initial entries of one species without attributes, …) is kept whole and cannot be edited: those methods raise ValueError; edit the dictionary and call from_dict again.

Model.to_dict

Model.to_dict()

Return the document as a new dictionary.

It is rules-model/0.3, or rules-model/0.4 if a continuous variable is independent (see add_ode), or crn-craft.model/1.0 if a reaction takes three or more molecules or a call of release 0.8.0 (a species with attributes, add_observable, pattern, copy, new) changed the model; a rules-model document of from_dict keeps its version unless such a call edits it. crn_craft.Model writes crn-craft.model/1.0 always. A model from from_dict returns its document until it is edited.

Model.to_json

Model.to_json(*, indent=2)

Return the document as JSON text with a trailing newline.

ArgumentDefaultMeaning
indent (keyword only)2JSON indentation.

Model.name

Model.name

Read-only property.

The model’s name.

Model.species

Model.species

Read-only property.

Species (type) names in declaration order.

Model.parameters

Model.parameters

Read-only property.

A copy of the parameter values by name.

Model.reaction_names

Model.reaction_names

Read-only property.

Reaction (rule) names in declaration order.

load_example

load_example(name)

One of the packaged example models as a Model.

ArgumentDefaultMeaning
namerequired"enzyme-mechanism", "immigration-death", "michaelis-menten", "repressilator" or "vilar-noise".

name is one of "enzyme-mechanism", "immigration-death", "michaelis-menten", "repressilator" and "vilar-noise". The packaged files are the converted crn-craft.model/1.0 documents of models/examples/ in the repository (crn_craft.convert of each); to_dict() returns that document until the model is edited.

Running

Prepare a request and simulate it, check documents without running them, ask for the finite state projection, and read the discovery document. ensemble builds the request from keyword arguments; prepare takes a request you wrote. Both return a PreparedEnsemble. The guide teaches this in chapters 3 and 5.

ensemble

ensemble(
    model,
    end,
    report_times,
    replicates=1,
    seed=0,
    threads=1,
    keep_paths=0,
    keep_instances=0,
    max_events=100000000,
    max_sampling_steps=None,
    max_instances=100000,
    max_output_bytes=67108864,
    wall_time_s=None,
    trackers=(),
    event_log=None,
    method=None,
    compiled=None,
    quantiles=(0.025, 0.5, 0.975),
    selector=None,
    strict=False,
    protocol=None,
)

Build and prepare a crn-craft.run/1.0 request; simulate() runs it.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
end (keyword only)requiredHorizon of the run. Report times lie in [0, end].
report_times (keyword only)requiredIncreasing report times in [0, end].
replicates (keyword only)1Number of replicates.
seed (keyword only)0Root seed. Replicate i draws from its own stream, so results do not depend on threads.
threads (keyword only)1Native worker threads, 1 to 64.
keep_paths (keyword only)0How many replicates, from replicate 0, keep their full observable series (result.paths). "all" or True keeps every replicate.
keep_instances (keyword only)0How many replicates keep their final instances (metadata["final_instances"]).
max_events (keyword only)100000000Event budget per replicate. None means no limit (the request records 2**64 - 1).
max_sampling_steps (keyword only)NoneBudget per replicate for random words and leap iterations. None means 16 × max_events (2**64 - 1 when max_events is None).
max_instances (keyword only)100000Most instances alive at once, per replicate.
max_output_bytes (keyword only)67108864Budget for the size of the result. Event logs reserve space for every replicate before the run.
wall_time_s (keyword only)NoneWall-clock limit of the whole run in seconds, or None.
trackers (keyword only)()A list of {"observable", "first_passage"?, "keep_episodes"?}.
event_log (keyword only)None{"max_entries": n, "rules": [...]}, or None.
method (keyword only)NoneA method name or a dictionary such as {"kind": "tau", "epsilon": 0.03}; None runs the tree method. See methods.
compiled (keyword only)NoneA loop from compile_loop for this model. Checked at preparation and used by every simulate().
quantiles (keyword only)(0.025, 0.5, 0.975)Probabilities for statistics["quantiles"] and statistics["median"]. () or None asks for none.
selector (keyword only)NoneThe event selector of static_direct: "linear", "composition_rejection", "sorting", "rssa_cr" or "auto". See methods.
strict (keyword only)FalseTrue: replicates that end early raise IncompleteEnsembleError in simulate() instead of warning with IncompleteEnsembleWarning.
protocol (keyword only)NoneAn ordered Protocol describing count operations and delays.

The arguments are those of crn_craft.rules.ensemble, with two differences: the documents are always crn-craft.model/1.0 (a rules-model gets that schema string, a network crn-craft.model/0.1 is converted) and crn-craft.run/1.0, and quantiles defaults to (0.025, 0.5, 0.975), so result.statistics has "median" and "quantiles"; quantiles=() or None asks for none. selector chooses the event selector of method="static_direct" (absent means "auto"). method=None runs the exact tree method; higher-order reactions (count) need "static_direct", "next_reaction", "tau" or "hybrid".

A Protocol selects the run/1.1 count scheduler. Supply linear Static Direct (the default with a protocol) or Next Reaction.

Budgets: max_events defaults to 108 events per replicate, and max_sampling_steps=None follows it (16 random words per event), so a long run needs only max_events raised. max_events=None means no event and sampling limit (the request records 264 - 1); guard such a run with wall_time_s. If replicates end early (a budget, or failed), simulate() warns with IncompleteEnsembleWarning, naming the count per termination and the keyword to raise; strict=True raises IncompleteEnsembleError instead.

prepare

prepare(
    model,
    request,
    compiled=None,
    quantiles=<unset>,
    selector=None,
    strict=False,
)

Prepare a request you wrote, as crn-craft.run/1.0.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
requestrequiredA request you wrote: bytes, a JSON string or a dictionary.
compiled (keyword only)NoneA loop from compile_loop for this model. Checked at preparation and used by every simulate().
quantiles (keyword only)unsetUnset: (0.025, 0.5, 0.975) unless the request states outputs.quantiles itself. () asks for none.
selector (keyword only)NoneThe event selector of static_direct: "linear", "composition_rejection", "sorting", "rssa_cr" or "auto". See methods.
strict (keyword only)FalseTrue: replicates that end early raise IncompleteEnsembleError in simulate() instead of warning with IncompleteEnsembleWarning.

As crn_craft.rules.prepare, but the documents are always the 1.0 contracts: a rules-run request is rewritten as crn-craft.run/1.0 with the defaults of its version written out (so it runs the same paths), a rules-model gets the schema crn-craft.model/1.0 and a network crn-craft.model/0.1 is converted; the request’s model hash follows when it was the hash of the supplied model. quantiles defaults to (0.025, 0.5, 0.975) unless the request states outputs.quantiles itself; quantiles=() asks for none. A crn-craft.run/1.0 request for crn-craft.model/1.0 bytes that needs no change keeps its exact bytes. strict is that of ensemble; the request’s budgets are used as written.

PreparedEnsemble

class PreparedEnsemble

Created by the functions of this page, not by calling it.

A prepared request, returned by ensemble and prepare.

simulate() runs it, bind_parameters makes a candidate with other parameter values, and archive seals a run. It can be simulated again with independent execution state. strict (from ensemble or prepare) decides whether a run with replicates that ended early warns (IncompleteEnsembleWarning) or raises (IncompleteEnsembleError); candidates keep it.

PreparedEnsemble.simulate

PreparedEnsemble.simulate(
    cancel_file=None,
    callback=None,
    batch_callback=None,
    batch_size=256,
    compiled=None,
)

Run native workers.

ArgumentDefaultMeaning
cancel_file (keyword only)NonePath of a file; the run is cancelled when the file exists.
callback (keyword only)Nonecallback(id, event) on the native workers; returning False stops that replicate. Needs the interpreter.
batch_callback (keyword only)Nonebatch_callback(id, events) receives the retained log after the run.
batch_size (keyword only)256Entries per call of batch_callback.
compiled (keyword only)NoneA CompiledLoop for this call only. None uses the loop attached at preparation, if any.

A live callback(id, event) returning False stops that replicate; any other return value continues. event is a log entry: time, rule (an index into rule_names, None for a leap), reactants, products, observables (in the result’s column order) and firings. Workers preserve per-replicate order, and calls from different replicates interleave. An exception in the callback cancels the run and is raised here; partial results are discarded. A callback that blocks also blocks Ctrl-C. A batch_callback(id, events) replays the retained log after execution and cannot affect the run.

compiled, a CompiledLoop for this model, runs this call in the compiled program instead of the interpreter, with byte-identical results. The request must select static_direct (CrnError CRN-R020 at /method otherwise) and use this loop’s model bytes (CRN-R020 at /model); the first call checks this. None, the default, means the loop attached with compiled= on ensemble or prepare, and the interpreter if none was attached. So a run prepared without a loop can be simulated either way, call by call, while a run with an attached loop always runs compiled. Callbacks need the interpreter and are refused with ValueError whenever a loop runs the call.

PreparedEnsemble.bind_parameters

PreparedEnsemble.bind_parameters(overrides)

Prepare an independent candidate with the same ensemble settings.

ArgumentDefaultMeaning
overridesrequiredA mapping from parameter names to new finite values.

The candidate’s model and run hashes cover the re-serialized bound model and request, not the original file. It runs interpreted: a compiled loop serves only the model bytes it was compiled for.

Its results’ model is this run’s model with the bound values, and their request this run’s request bound to it (see Result.model).

PreparedEnsemble.rule_names

PreparedEnsemble.rule_names

Read-only property.

Rule names in declaration order.

Callback events and log entries carry a rule index into this tuple, so run.rule_names[event["rule"]] names the rule that fired.

Model.fsp

Model.fsp(end, report_times, bounds, *, max_states=None, tolerance=None)

The exact distribution of the counts by finite state projection.

ArgumentDefaultMeaning
endrequiredHorizon of the run. Report times lie in [0, end].
report_timesrequiredIncreasing report times in [0, end].
boundsrequiredA mapping from every species label to its largest count.
max_states (keyword only)NoneCap on the enumerated states. None means 100,000.
tolerance (keyword only)NoneTruncation budget of the series. None means 1e-12.

bounds maps every species label to its largest count (a type name for a type without attributes, for example {"S": 999, "I": 1000, "R": 1000}); end and report_times are as in ensemble. max_states (default 100,000) caps the enumerated states and tolerance (default 1e-12) is the truncation budget of the series. The model must be closed (CrnError CRN-R017 otherwise). Returns an FspResult; see crn_craft.rules.fsp for the method and its error terms.

check

check(model, request=None)

Check a model, and optionally a request for it, without running anything.

ArgumentDefaultMeaning
modelrequiredA model: bytes, text, a dictionary or a Model.
requestNoneA request for the model, or None to check the model alone.

model and request are bytes, text, dictionaries or a Model. Returns the report crn-craft check MODEL [REQUEST] prints, as a dictionary; read valid and diagnostics:

  • a crn-craft.model/1.0 model, with or without a request, and a rules-model with a request: crn-craft.check/1.0; with a request, the report says whether run would accept the two documents (simulation and fsp requests) and adds run_sha256;
  • a rules-model alone: crn-craft.rules-check/0.1, as release 0.6.0;
  • a network crn-craft.model/0.1 alone: crn-craft.check/1.0 of the conversion (CRN-R016 and validation diagnostics if it cannot be converted).

describe

describe(kind=None)

The discovery document, or the JSON Schema of one contract.

ArgumentDefaultMeaning
kindNoneA contract name such as "model-1.0" or "run-1.0". None returns the discovery document.

Without kind: crn-craft.describe/1.0, as crn-craft describe prints it, with the commands, the 1.0 contracts, methods, selectors, quantiles and limits first and the older contracts that are still read under legacy. With kind (for example "model-1.0" or "run-1.0"), the schema crn-craft describe KIND prints; ValueError for an unknown kind.

CrnError

class CrnError(diagnostics)

A request the native core rejected.

ArgumentDefaultMeaning
diagnosticsrequiredThe list of diagnostics.

diagnostics is the list of CRN-craft diagnostics (dictionaries with code, path, message and hint). It is a ValueError, so existing except ValueError handlers keep working.

IncompleteEnsembleWarning

class IncompleteEnsembleWarning(message, counts=None)

Some replicates of a run ended early, on a budget or by failing.

ArgumentDefaultMeaning
messagerequiredThe message.
countsNoneReplicates per termination.

simulate() warns with it when a replicate’s termination is neither completed nor stopped (a cancelled run is not reported: it was stopped on purpose). The message gives the count per termination and the keyword that raises each budget. counts maps each such termination to its number of replicates. strict=True raises IncompleteEnsembleError instead. The package registers the filter "always" for this category at import, after any other filter, so every run that ends early is reported, also in a loop; warnings.simplefilter("ignore", IncompleteEnsembleWarning) silences it.

IncompleteEnsembleError

class IncompleteEnsembleError(message, counts=None, result=None)

The error of strict=True for an ensemble that did not complete.

ArgumentDefaultMeaning
messagerequiredThe message.
countsNoneReplicates per termination.
resultNoneThe result of the run.

It carries the message and counts of IncompleteEnsembleWarning, and result, the crn_craft.rules.Result of the run, so the records can still be read.

Experiments and probability laws

Declare scheduled experiments, prepare a probability projection, build spatial compartments and import an experiment bundle.

Protocol

class Protocol(*, time_unit=None, max_pending=4096)

An ordered calendar in the time unit of the model’s rates.

ArgumentDefaultMeaning
time_unit (keyword only)NoneA label for the time unit of the model and the protocol.
max_pending (keyword only)4096Per-replicate cap on pending reaction completions.

Use at for external interventions and delay to attach completions to the firings of a reaction. Equal times preserve insertion order. Reports see the state after actions and due completions.

Protocol.at

Protocol.at(
    time,
    parameters=None,
    change=None,
    set_counts=None,
    partition=None,
)

Add an atomic group of rate edits and count operations.

ArgumentDefaultMeaning
timerequiredTimestamp in the same time unit as the model.
parameters (keyword only)NoneNamed kinetic parameters to replace at this time.
change (keyword only)NoneMap species names to signed count increments.
set_counts (keyword only)NoneMap species names to absolute counts.
partition (keyword only)NoneMap species names to independent retention probabilities.

Count increments may be negative. Counts assigned or partitioned in the same group use their pre-group values. Give at most one count operation per species. Return the protocol for chaining.

Protocol.delay

Protocol.delay(reaction, duration, *, products=None, owner=None)

Add fixed delayed products to a named initiation reaction.

ArgumentDefaultMeaning
reactionrequiredName of the reaction.
durationrequiredPositive time from initiation to completion.
products (keyword only)NoneCount increments made by a successful completion.
owner (keyword only)NoneOptional busy species whose removal cancels the completion.

When supplied, the owner is a busy species created once per initiation. Its loss cancels the completion; a completion consumes one surviving owner.

Protocol.to_dict

Protocol.to_dict()

Return a detached copy of the protocol payload for run/1.1.

Signal

class Signal(function, *, change_times=())

A real-time rate input. Tables use linear or right-continuous steps.

ArgumentDefaultMeaning
functionrequiredPrescribed time-dependent rate function.
change_times (keyword only)()Times where the rate can change discontinuously.

Tables are evaluated natively by both forced-segment solvers. Callables are a Python-only option, called from the native step loop. Provide their change points and a reproducible description of their parameters in the calling experiment.

Signal.table

Signal.table(times, values, *, interpolation='linear')

Create a table with held endpoint values outside its range.

ArgumentDefaultMeaning
timesrequiredIncreasing times at which the rate is tabulated.
valuesrequiredValues in the same order as times.
interpolation (keyword only)'linear'Linear interpolation or a right-continuous step curve.

prepare_fsp

prepare_fsp(
    model,
    bounds,
    protocol=None,
    initial=None,
    retained=None,
    max_states=100000,
    max_edges=2000000,
)

Prepare a reusable projection for a closed model.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
boundsrequiredMapping of species labels to inclusive upper counts.
protocol (keyword only)NoneAn ordered Protocol describing count operations and delays.
initial (keyword only)NoneOptional mapping of count tuples to probabilities.
retained (keyword only)NoneOptional iterable of count tuples, in lowered species order, that restrict the state space; transitions that leave the set flow to the absorbing sink. Not available with scheduled interventions.
max_states (keyword only)100000Reachable-state limit.
max_edges (keyword only)2000000Sparse edge limit.

The native engine lowers the model, enumerates the states, builds the generator and propagates the law; no solve needs SciPy. Existing Model.fsp is the native uniformization for one fixed model without protocols, signals or initial mixtures. A prepared projection holds no per-solve state, so threads can share it. It cannot be pickled; prepare one per process.

retained optionally restricts the projection to a finite set of count tuples in the order of the projection’s species, inside bounds (for example a hyperbolic cut (x - 4) (y - 4) < c). Only retained states reachable from the initial law are enumerated; a transition to any other state flows to the absorbing sink, so the sink probability measures the truncation. The initial law must lie in the set; duplicates count once; an empty set, negative counts, tuples of another length and more than max_states tuples are refused. A retained set cannot be combined with scheduled count interventions.

stationary_fsp

stationary_fsp(
    model,
    bounds,
    return_state=None,
    class_state=None,
    parameters=None,
    expansions=0,
    tolerance=1e-06,
    flux_tolerance=1e-06,
    max_states=100000,
    max_factor_bytes=2147483648,
)

Solve a finite stationary law or an outward-flux-redirected FSP.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
boundsrequiredMapping of species labels to inclusive upper counts.
return_state (keyword only)NoneRetained count tuple to which stationary FSP redirects escaping rates.
class_state (keyword only)NoneState identifying the selected finite closed class.
parameters (keyword only)NoneNumeric model parameter overrides.
expansions (keyword only)0Maximum number of additional projection enlargements.
tolerance (keyword only)1e-06Target maximum marginal CDF change after refinement.
flux_tolerance (keyword only)1e-06Target outward rate after projection refinement.
max_states (keyword only)100000Reachable-state limit.
max_factor_bytes (keyword only)2147483648Memory budget, in bytes, of the sparse LU factorization and its workspace; a larger bound is refused (CRN-E070).

With a return state, expand faces according to boundary flux exposure and compare marginal CDFs across successive bounds. The resulting convergence indication is empirical for an infinite network. A finite generator with several closed classes needs an explicit class state. The native engine builds the generator, finds the closed communicating classes and solves the anchored balance equations of one class with a sparse LU, refused when its bound exceeds max_factor_bytes. Without a return state, every transition must stay inside the bounds.

SpatialModel

class SpatialModel(name, volumes)

Build an ordinary reaction network from named well-mixed compartments.

ArgumentDefaultMeaning
namerequiredA name.
volumesrequiredMapping of compartment names to their positive fixed volumes.

The graph uses directed per-molecule transport hazards. Compartment volumes are fixed. Rate templates can interpolate local species names and the fixed volume.

SpatialModel.add_species

SpatialModel.add_species(name, initial=0, *, reservoirs=())

Add a species in every compartment, with optional fixed counts.

ArgumentDefaultMeaning
namerequiredA name.
initial0Initial count or a mapping from compartments to counts.
reservoirs (keyword only)()Compartments that keep this species at its initial count.

SpatialModel.label

SpatialModel.label(species, region)

Return the species label used by the lowered model.

ArgumentDefaultMeaning
speciesrequiredA species name.
regionrequiredCompartment name.

SpatialModel.local

SpatialModel.local(
    name,
    rate,
    reactants,
    products,
    combinatorial=False,
    regions=None,
)

Instantiate a local reaction template in the selected regions.

ArgumentDefaultMeaning
namerequiredA name.
raterequiredNumeric rate or expression with local substitution fields.
reactantsrequiredSpecies consumed by the local reaction.
productsrequiredSpecies produced by the local reaction.
combinatorial (keyword only)FalseMultiply an expression by the available reactant combinations.
regions (keyword only)NoneCompartments receiving the local reaction template.

SpatialModel.transport

SpatialModel.transport(species, origin, target, rate)

Add a directed, per-copy first-order hop.

ArgumentDefaultMeaning
speciesrequiredA species name.
originrequiredSource compartment of a directed hop.
targetrequiredDestination compartment or reference copy count, depending on the model.
raterequiredFirst-order hop rate per copy.

SpatialModel.diffusion

SpatialModel.diffusion(species, first, second, diffusivity, spacing)

Add both directions on a uniform lattice at rate D / spacing².

ArgumentDefaultMeaning
speciesrequiredA species name.
firstrequiredOne region of the lattice pair.
secondrequiredThe other region of the lattice pair.
diffusivityrequiredDiffusion coefficient per distance unit squared per time unit.
spacingrequiredDistance between lattice neighbors.

SpatialModel.profile

SpatialModel.profile(values, species)

Select region columns from a trajectory/report array.

ArgumentDefaultMeaning
valuesrequiredA trajectory array with a variable axis.
speciesrequiredA species name.

spatial_turnover

spatial_turnover(
    initial,
    end,
    target,
    feedback,
    mutant_weight,
    death,
    hop,
    seed=0,
    mutation=0.0,
    fixed_left=False,
    labels=False,
    max_events=3000000000,
)

Sample the endpoint of a two-genotype nearest-neighbor turnover chain.

ArgumentDefaultMeaning
initialrequiredPer-region sequence of initial wild and mutant count pairs.
end (keyword only)requiredHorizon of the run. Report times lie in [0, end].
target (keyword only)requiredDestination compartment or reference copy count, depending on the model.
feedback (keyword only)requiredCoefficient of linear birth feedback.
mutant_weight (keyword only)requiredRelative contribution of a mutant to copy-count feedback.
death (keyword only)requiredLoss rate per molecule.
hop (keyword only)requiredHopping rate per molecule in each available direction.
seed (keyword only)0Root seed. Replicate i draws from its own stream, so results do not depend on threads.
mutation (keyword only)0.0Probability of a new mutant clone at birth.
fixed_left (keyword only)FalseUse the first compartment as a fixed reservoir.
labels (keyword only)FalseReturn clone labels by region.
max_events (keyword only)3000000000Event budget per replicate. None means no limit (the request records 2**64 - 1).

Each copy has birth rate max(0, death + feedback * (target - W - weight*M)). Death and migration have constant per-copy rates. New mutations are marked at birth, and labels have no effect on subsequent hazards.

read_experiment

read_experiment(path, *, convention)

Read an OMEX or SED-ML path and resolve its local stochastic experiment.

ArgumentDefaultMeaning
pathrequiredA file path.
convention (keyword only)requiredThe rate convention. The importer refuses an absent or other value.

The caller explicitly confirms stochastic count propensity semantics. Exact polynomial conversion verifies the falling-factorial reactants.

Likelihoods and sensitivities

Turn the law of a prepared projection into the probability of what was measured, score it against counted cells, and differentiate it with respect to parameters. crn_craft.likelihood and crn_craft.sensitivities are modules: call their names as crn.likelihood.histogram_score(...). Binomial detection and fluorescence bins need SciPy (pip install "crn-craft[likelihood]"); everything else runs without it. Tutorial O3 and optimization lesson C8 use these names.

likelihood.measured_counts

likelihood.measured_counts(states, species, observable)

Map projected states to one count, a species sum, or a joint readout.

ArgumentDefaultMeaning
statesrequiredCount states, one row per state, as PreparedFsp.states gives them.
speciesrequiredThe species labels of the columns of states.
observablerequiredA species name, or a tuple with one entry per measured axis: a name or a list of names to sum.

A string names one species. Each entry in a tuple is one measured axis. An axis can be a string or a list of species to sum.

likelihood.count_probability

likelihood.count_probability(states, probabilities, values, *, detection=1.0)

Compute the probability of each requested count or joint count.

ArgumentDefaultMeaning
statesrequiredMeasured counts of every state: one column per measured axis, or a vector for one axis.
probabilitiesrequiredOne probability per state, without the sink.
valuesrequiredThe counts or joint counts whose probabilities are wanted, in the layout of states.
detection (keyword only)1.0Probability that one molecule is detected, a number or one per axis; below 1 each count is thinned binomially (needs SciPy).

likelihood.binned_probability

likelihood.binned_probability(
    counts,
    probabilities,
    edges,
    gain=None,
    background=0.0,
    sigma=None,
)

Map one count to intervals or to Gaussian fluorescence bins.

ArgumentDefaultMeaning
countsrequiredThe measured count of every state, one axis.
probabilitiesrequiredOne probability per state, without the sink.
edgesrequiredStrictly increasing bin edges; -inf and inf are allowed.
gain (keyword only)NoneFluorescence per molecule. With sigma, the bins are of fluorescence, not of counts (needs SciPy).
background (keyword only)0.0Fluorescence of a cell without molecules.
sigma (keyword only)NoneStandard deviation of the Gaussian measurement noise.

Edges are increasing and bins are left-closed, right-open. Infinite edges represent underflow or overflow. Fluorescence has mean background + gain * count and standard deviation sigma.

likelihood.HistogramGroup

class likelihood.HistogramGroup(
    condition,
    replicate,
    time,
    counts,
    probabilities,
    missing_mass=0.0,
    time_unit='',
    readout='',
)

Counts and predicted observed bin probabilities for one sample group.

ArgumentDefaultMeaning
conditionrequiredLabel of the experimental condition.
replicaterequiredLabel of the replicate.
timerequiredObservation time, a finite number.
countsrequiredObserved cells per bin, nonnegative integers.
probabilitiesrequiredPredicted probability of every bin, in the order of counts.
missing_mass0.0Probability that the prediction does not capture (sink and truncated bins), in [0, 1].
time_unit''Unit of time, kept as a label.
readout''Name of the readout, kept as a label.

likelihood.histogram_score

likelihood.histogram_score(groups)

Score grouped histograms and expose the cost uncertainty due to leakage.

ArgumentDefaultMeaning
groupsrequiredAn iterable of HistogramGroup.

likelihood.HistogramScore

class likelihood.HistogramScore

Created by the functions of this page, not by calling it.

Negative log likelihood and a bound allowing for uncaptured mass.

impossible_bins counts occupied bins with zero retained probability. nats_per_cell is infinite exactly when it is positive. Each entry of groups is (condition, replicate, time, cells, nats, optimistic nats).

likelihood.mean_score

likelihood.mean_score(observed, predicted, covariance)

Return the quadratic mean objective for a group covariance.

ArgumentDefaultMeaning
observedrequiredObserved means, a number or a vector.
predictedrequiredPredicted means of the same shape.
covariancerequiredCovariance of the observed means, symmetric positive definite.

The value is delta’ V^-1 delta / 2 without the log-determinant term. The covariance must be symmetric positive definite.

sensitivities.forward_sensitivities

sensitivities.forward_sensitivities(
    graph,
    segments,
    times,
    parameters,
    initial=None,
    initial_derivatives=None,
    logarithmic=False,
    difference=0.0001,
    tolerance=1e-06,
    max_work=300000,
    max_factor_bytes=536870912,
)

Solve p’=Qp and s’=Qs+(dQ/dtheta)p over piecewise-constant bindings.

ArgumentDefaultMeaning
graphrequiredA prepared projection from prepare_fsp.
segmentsrequiredSequence of (end_time, bindings) with increasing ends.
timesrequiredStrictly increasing report times in [0, last end].
parametersrequiredNames of the parameters to differentiate, at most 16.
initial (keyword only)NoneInitial law; by default the one given to prepare_fsp.
initial_derivatives (keyword only)NoneDerivatives of the initial law, one row per parameter; by default zero.
logarithmic (keyword only)FalseDifferentiate with respect to the natural logarithm of each parameter.
difference (keyword only)0.0001Relative step of the centered difference of the generator.
tolerance (keyword only)1e-06Relative tolerance of the integration; the absolute one is 1e-4 tolerance.
max_work (keyword only)300000Largest number of augmented implicit solves.
max_factor_bytes (keyword only)536870912Largest memory of one sparse factorization, in bytes.

segments is a sequence of (end_time, bindings), measured from time zero, with strictly increasing ends; each binding maps parameter names to values for that segment and must bind every name in parameters (at most 16 names). times increase strictly, lie in [0, last end]; time zero returns the initial state. The law and its derivatives pass continuously across segment ends, where the integrator restarts.

dQ/dtheta is the centered difference of the generator at theta (1 +- difference) (or theta exp(+-difference) with logarithmic=True, which differentiates in natural-log coordinates) on the same state graph. It is exact up to roundoff for rates linear in the parameter and second-order accurate otherwise, so parameters inside any rate expression, Hill functions included, can be differentiated; the time integration is the implicit variable-order BDF of the prepared projection with the derivatives inside its error norm (relative tolerance, absolute 1e-4 tolerance), and one sparse factorization serves the law and every direction.

initial is a law as in PreparedFsp.solve; by default the initial law given to crn_craft.prepare_fsp. It does not depend on the parameters unless initial_derivatives (one row per parameter, one column per state in graph order, no sink column, rows summing to zero) says so. Scheduled count interventions, stop states and continuously varying signals are outside this interface.

Raises ValueError for invalid arguments, a lost probability or derivative mass above 1e-7 or a negative probability beyond the integration tolerance, and the errors of the prepared projection for budgets (max_work augmented solves, max_factor_bytes) and interruption. The caller chooses the truncation: read the sink.

sensitivities.ProjectionSensitivities

class sensitivities.ProjectionSensitivities

Created by the functions of this page, not by calling it.

Laws and their parameter derivatives at the requested times.

probabilities has shape (times, states + 1) and derivatives (times, parameters, states + 1), in the order of states; the last column is the absorbing sink. Each row of probabilities sums to one and each derivative row to zero, sink included. work counts the augmented implicit solves.

sensitivities.ProjectionSensitivities.observed

sensitivities.ProjectionSensitivities.observed(axes)

Sum states and derivatives into the bins of the measured counts.

ArgumentDefaultMeaning
axesrequiredThe measured species, as the observable of likelihood.measured_counts.

axes names the measured species. Returns the distinct measured count tuples, their probabilities (times, bins) and derivatives (times, parameters, bins); the sink is not a bin.

sensitivities.fisher_information

sensitivities.fisher_information(
    probabilities,
    derivatives,
    cells,
    probability_floor=0.0,
)

Fisher information of independent snapshots of measured bins.

ArgumentDefaultMeaning
probabilitiesrequiredProbabilities of the measured bins, shape (times, bins).
derivativesrequiredTheir derivatives, shape (times, parameters, bins).
cellsrequiredCells measured at each time: a number or one per time.
probability_floor (keyword only)0.0Bins with a smaller probability are left out.

probabilities (times, bins) and derivatives (times, parameters, bins) describe MEASURED bins (aggregate hidden states first). cells is the number of cells measured at each time, a number or one per time. Returns (matrix, excluded): the symmetric positive semidefinite matrix sum_t n_t sum_b g g^T / p over bins with p > 0 and p >= probability_floor, and per time the probability of the excluded bins. A bin with p = 0 is unreachable or has underflowed and carries no information; a positive floor reproduces a published convention that drops rare bins and lowers the information.

Results

What simulate() and Model.fsp return. The fields of the result document and the terminations are in the results reference. Result.save is under files and archives. Chapter 4 of the guide teaches the data frames.

Result

class Result

Created by the functions of this page, not by calling it.

The result of a rules ensemble.

  • records: one row per replicate, indexed by replicate id. Columns started, termination (categorical over the values of crn_craft.rules.TERMINATIONS: completed, stopped and the reasons a replicate ended early), stop_time, events, rng_words, peak_instances, created_instances and saved_points.
  • rule_events: events per replicate (rows) and rule (columns, in declaration order).
  • statistics: None if withheld, else a dict with samples (the number of replicates included) and one DataFrame per statistic (mean, sample_variance, mean_standard_error), indexed by report time with one column per observable. A statistic that was not computed is None. A run with quantiles= also has quantiles, a dict from each requested probability to a DataFrame of that shape, and, when 0.5 was requested, median, the DataFrame of quantiles[0.5] (see ensemble).
  • paths: the kept series as an xarray DataArray with dimensions (replicate, time, variable); paths_frame() gives the DataFrame of release 0.4.0, to_xarray() a Dataset.
  • event_columns(): event logs as a DataArray with dimensions (replicate, entry, variable); event_frame() gives the DataFrame of release 0.4.0.
  • tracker_columns(i): a tracker’s fields as a DataFrame.
  • metadata: the full result document; observations its trackers and logs; record_diagnostics replicate errors by id.
  • model and request: the model and request documents that ran, and save(path), which writes them with the results to one markdown or JSON report.

Observables are in result order: sorted by name, then any continuous variable such as ATP. Use .to_numpy() on any frame, column or array for NumPy arrays.

Result.paths

Result.paths

Kept series as a DataArray: replicates x report times x variables.

Dimensions are ("replicate", "time", "variable"), the order of event_columns(), with the coordinates replicate (the kept replicate ids, int64), time (the report times) and variable (the observables in result order: sorted names, then continuous variables). Values are float64. attrs holds the result’s sampler, method (the method object of rules-result/0.3 as JSON text, "null" for older results), root_seed, model_sha256 and run_sha256; netCDF can store all of them.

keep_paths decides which replicates are kept ("all" keeps every one). A replicate that ended on a budget has values only up to its last saved report time and NaN after it. For example paths.sel(variable="mutants") is a replicate x time array and paths.sel(replicate=3) one replicate’s series. Release 0.5.0 ordered the dimensions ("time", "variable", "replicate"); paths.transpose("time", "variable", "replicate") gives that order. paths_frame() returns the DataFrame of release 0.4.0.

Result.paths_frame

Result.paths_frame()

Kept series as a DataFrame: (replicate, time) rows.

One column per observable, in result order; this is paths of release 0.4.0. A replicate that ended on a budget has rows only up to its last saved report time.

Result.to_xarray

Result.to_xarray()

Return the kept paths as an xarray Dataset.

Dimensions are replicate and time (the report times), with one variable per observable; rows a replicate did not save are NaN. It holds the values of paths: paths.to_dataset("variable"). attrs holds sampler, model_sha256, run_sha256 and root_seed, all of which netCDF can store.

Result.tracker_columns

Result.tracker_columns(index=0)

Return a tracker’s scalar fields, one row per observed replicate.

ArgumentDefaultMeaning
index0The index of the tracker in the request’s trackers.

Indexed by replicate id. Counts (appearances, extinctions, omitted_episodes) are unsigned integers; times and values are floats, NaN where absent (for example first_passage of a replicate that never met the predicate). Replicates that failed before tracking began carry no observation. Episodes are in observations.

Result.event_columns

Result.event_columns(replicate=None)

Return retained event logs as a DataArray.

ArgumentDefaultMeaning
replicateNoneA replicate id, or None for every log.

Without a replicate id the dimensions are ("replicate", "entry", "variable"): one row per observed replicate (int64 ids), entries 0, 1, … in event order, and the observables after each event (result order), NaN past a replicate’s last entry. Coordinates over (replicate, entry): time (float64, NaN as padding), rule (the rule index, -1 for a leap, -2 as padding) and rule_name (the name; NaN for a leap and as padding); over replicate: length, the number of logged entries. With a replicate id the dimensions are ("entry", "variable"), exactly length entries, with scalar replicate and length coordinates. attrs is that of paths.

A replicate without logged events has length 0. Participant instances and leap firings are in the observation entries. event_frame() returns the DataFrame of release 0.4.0.

Result.event_frame

Result.event_frame(replicate=None)

Return retained event logs as a DataFrame (release 0.4.0’s form).

ArgumentDefaultMeaning
replicateNoneA replicate id, or None for every logged event.

With a replicate id, that replicate’s log, indexed by entry; without one, every logged event, indexed by (replicate, entry). Rows are in event order: time, rule (the rule index, -1 for a leap), rule_name (categorical, missing for a leap), then one column per observable after the event. Participant instances and leap firings are in the observation entries.

Result.model

Result.model

Read-only property.

The model document that ran, as a new dictionary.

For a run from ensemble or prepare (also with a compiled loop) it is the parsed model bytes whose SHA-256 is metadata["model_sha256"]. For a bind_parameters candidate it is the template’s model with the bound parameter values, all parameters as floats in name order: the document the engine re-serialized and ran, apart from fields that serialization adds with their default values. None for a Result built directly from a metadata document and columns.

Result.request

Result.request

Read-only property.

The request document that ran, as a new dictionary.

For a bind_parameters candidate it is the template’s request bound to the candidate’s model: model.sha256 is metadata["model_sha256"]. None for a Result built directly from a metadata document and columns.

FspResult

class FspResult

Created by the functions of this page, not by calling it.

A finite state projection as pandas and xarray objects.

Model.fsp returns it; crn_craft.rules.fsp returns the document it wraps.

  • states: the projected states, a DataFrame indexed by state (0 is the initial state) with one int64 column per species label.
  • probabilities: a DataArray with dimensions ("time", "state"), the probability of each state at each report time (the mass that left the bounds is not in it; see truncation).
  • mean: the projected first moment of each species at each report time, a DataFrame indexed by time: Σ p(x)·x over the retained states, not renormalized, so it is the mean of the full process only up to the leaked mass.
  • truncation: the error terms per report time, a DataFrame with the columns physical_leakage_estimate (mass that left the bounds), series_tail_upper_bound, discarded_weight_estimate, mass_defect and roundoff_mass_residual.
  • species: the species labels; metadata: the crn-craft.fsp-result/1.0 document.

Files and archives

Read model and report files, write reports, and seal a run in an archive directory that can be verified later. The formats are in the archive reference and the contracts.

load

load(path)

Read a model file and check it; return its exact bytes.

ArgumentDefaultMeaning
pathrequiredA model file.

Every model version is read: crn-craft.model/1.0, the rules-model versions and the network crn-craft.model/0.1. An invalid model raises CrnError with the diagnostics of check. Pass the bytes to ensemble or prepare, or to Model.from_dict.

load_report

load_report(path)

Read a JSON report written by Result.save.

ArgumentDefaultMeaning
pathrequiredA JSON file written by Result.save.

Returns the parsed crn-craft.report/1.0 document as a dictionary: schema, crn_craft_version, model and request (the documents that ran) and result. Non-finite numbers in it are the strings "nan", "inf" and "-inf". Raises ValueError for a file that is not strict JSON (including duplicate keys) or whose schema is not crn-craft.report/1.0.

Result.save

Result.save(path, *, paths=True)

Write the model, the request and the results to one report file.

ArgumentDefaultMeaning
pathrequiredThe file. .md or .markdown writes markdown, .json writes crn-craft.report/1.0.
paths (keyword only)TrueFalse leaves the single trajectories out.

The extension of path decides the format: .md or .markdown for markdown, .json for JSON (schema crn-craft.report/1.0, read back with load_report), in any case; another extension raises ValueError. paths=False leaves the single trajectories out. An existing file is replaced; the report is written to a temporary file in the same directory and renamed, so a failed write (OSError) leaves no partial file. Returns path as a pathlib.Path.

The same result always gives the same bytes: there is no timestamp, host name or timing. The markdown report lists the model (reactions, start values, parameters, stop condition, continuous variables), the simulation settings with the sampler, the package version and both hashes, and the results: terminations, mean events per rule, the kept trajectories and the summary statistics (quantiles, when the result has them, in ascending order). Observables follow the model’s species declaration order when every observable is named after a species type, then continuous variables; otherwise result order. Each section’s lines are in a fenced text block, so a markdown renderer keeps one line per entry. Numbers are written in shortest round-trip form, integral values without .0.

A report is a readable record of a run; an archive is the sealed, verifiable record of a run for replay. save changes nothing about the result.

archive

archive(model, request, directory, *, cancel_file=None)

Run a request and seal the run in a new archive directory.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
requestrequiredA request: bytes, a JSON string or a dictionary.
directoryrequiredThe new archive directory. It must not exist; its parent must.
cancel_file (keyword only)NonePath of a file; the run is cancelled when the file exists.

model is model bytes, a JSON string, a dictionary or a Model; request is request bytes, a JSON string or a dictionary: any rules-run version, or crn-craft.run/1.0 with any method, fsp included. The request must bind the exact model bytes (model.sha256); its model.path is kept but not resolved. directory must not exist; its parent must.

The directory gets model.json and request.json (the exact bytes), result.json (the result as crn-craft rules prints it), manifest.json (crn-craft.archive/1.0: length and SHA-256 of the three) and, written last, COMPLETE. This is crn-craft rules MODEL REQUEST --archive NEW_DIRECTORY without files for the inputs; PreparedEnsemble.archive archives a prepared run.

Returns the crn-craft.archive-check/1.0 report as a dictionary, also when the run or the write failed: read valid (the archive was written), simulation_complete (the run completed) and termination together, and diagnostics for the reason of a failure. Input errors create no directory. Check an archive later with verify_archive. Ctrl-C cancels the run, which is archived as cancelled before KeyboardInterrupt is raised.

An archive is the sealed, verifiable record of a run for replay; a report written by Result.save is a readable record.

PreparedEnsemble.archive

PreparedEnsemble.archive(directory, *, cancel_file=None)

Run this request once more and seal the run in directory.

ArgumentDefaultMeaning
directoryrequiredThe new archive directory. Its parent must exist.
cancel_file (keyword only)NonePath of a file; the run is cancelled when the file exists.

As archive with the exact model and request bytes this run was prepared from: the archived result equals the result of simulate() (completed runs replay byte for byte; a compiled loop gives the interpreter’s result, which the archive holds). Returns the crn-craft.archive-check/1.0 report. A bind_parameters candidate has no original bytes and raises ValueError: archive its model with the bound values and a request bound to it with archive.

verify_archive

verify_archive(directory)

Check an archive directory without running anything.

ArgumentDefaultMeaning
directoryrequiredThe archive directory to check.

Reads crn-craft.archive/1.0 directories (written by archive and crn-craft run ... --archive) and returns the report of crn-craft verify DIRECTORY as a dictionary (crn-craft.archive-check/1.0): valid is true for an intact, consistent archive, also of an incomplete run (simulation_complete false); diagnostics names the first inconsistency otherwise. The network engine’s crn-craft.archive/0.1 directories are no longer read (release 0.7.0).

Analysis and import/export

Analyze the structure of a network, export it, and import SBML and BioNetGen files. The reports are described in the analysis reference and the GillesPy2 export. Chapter 11 of the guide teaches this.

Model.analyze

Model.analyze()

The network analysis of this model (crn-craft.analysis/1.0).

Returns the report as a dictionary, as crn-craft analyze MODEL prints it: species and reactions of the lowered network, their dependencies, conservation laws, the cone of reachable directions, the complex graph and warnings. Read success first: a model without a flat view (continuous variables, ATP, products that create new attribute tuples) gives success false with CRN-R017.

Model.to_gillespy2

Model.to_gillespy2()

This model as a gillespy2.Model.

GillesPy2 must be installed, in the version the export names (crn-craft describe lists it; another version raises RuntimeError). A rule with a constant rate and at most two molecules becomes a mass-action reaction, any other rule a custom propensity, as crn-craft export MODEL gillespy2 writes them. A model the export refuses raises CrnError (CRN-E050 for what GillesPy2 cannot evaluate, such as a stop condition or exp).

convert

convert(model)

Convert a network model (crn-craft.model/0.1) into crn-craft.model/1.0.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.

model is bytes, text or a dictionary. Returns the converted model’s exact bytes (pretty-printed JSON with a trailing newline), the same bytes crn-craft convert MODEL prints. Every species becomes a type and an observable of the same name, every reaction a rule with the same propensity; reactions of any order use the pattern field count. A model the converter cannot hold (a population limit, a network without reactions, …) raises CrnError with CRN-R016; an invalid network model raises CrnError with its validation diagnostics. Model.from_dict(json.loads(convert(m))) gives a Model.

read_sbml

read_sbml(path, *, convention)

Import an SBML file as a Model.

ArgumentDefaultMeaning
pathrequiredAn SBML file.
convention (keyword only)requiredMust be "stochastic_count_propensity".

The SBML subset and the required convention ("stochastic_count_propensity") are those of crn_craft.importers.import_sbml. The network is converted to crn-craft.model/1.0; model.import_report keeps the import report’s provenance (source_format, source_sha256, the convention and parameter policy) without the model. Unsupported input raises crn_craft.importers.ImportFailure (a ValueError).

read_bngl

read_bngl(path, *, convention)

Import an expanded BioNetGen network (.net) as a Model.

ArgumentDefaultMeaning
pathrequiredAn expanded .net file.
convention (keyword only)required"binomial" or "falling_factorial".

convention is the rate convention of crn_craft.importers.import_bng_net ("binomial" or "falling_factorial"). The network is converted to crn-craft.model/1.0; model.import_report keeps the import report’s provenance (species patterns, groups, the convention) without the model. Unsupported input raises crn_craft.importers.ImportFailure (a ValueError).

importers.import_sbml

importers.import_sbml(raw, *, convention)

L3V2 Core, one fixed unit compartment, integer item amounts, polynomial jumps.

ArgumentDefaultMeaning
rawrequiredThe SBML document’s bytes.
convention (keyword only)requiredMust be "stochastic_count_propensity".

convention must be explicitly ‘stochastic_count_propensity’. Parameters are folded into reaction coefficients; the report names that import-time choice. Returns a crn-craft.import/1.0 report as a dictionary: report["model"] is the converted crn-craft.model/1.0 model, beside the source format and its SHA-256. Unsupported input raises crn_craft.importers.ImportFailure.

The document is read by the package’s one XML guard: at most 16 MiB of well-formed UTF-8 (UTF-16 and UTF-32 are refused, and so is a declared encoding other than UTF-8) without a document type or entity declaration anywhere in its bytes, so nothing is expanded or fetched, and with elements nested at most 256 levels deep.

importers.import_bng_net

importers.import_bng_net(raw, *, rate_convention)

Expanded numeric .net only; explicit binomial or falling_factorial convention.

ArgumentDefaultMeaning
rawrequiredThe .net file’s bytes.
rate_convention (keyword only)required"binomial" or "falling_factorial".

Returns a crn-craft.import/1.0 report as a dictionary: report["model"] is the converted crn-craft.model/1.0 model, beside the source format and its SHA-256. Unsupported input raises crn_craft.importers.ImportFailure.

importers.ImportFailure

class importers.ImportFailure

Raised by an importer for input it does not support.

A ValueError with the attribute code "CRN-E090".

Compiled loops

Build the Static Direct event loop of a model into a program and run requests with it. This needs a Rust toolchain; the requirements, the cache and the limits are in the methods reference. Chapter 5 of the guide teaches when to use it.

compile_loop

compile_loop(
    model,
    cache_dir=None,
    cargo='cargo',
    source=None,
    progress=True,
)

Compile the Static Direct event loop of a model; opt-in, needs Rust.

ArgumentDefaultMeaning
modelrequiredA model: bytes from load, a JSON string, a dictionary or a Model.
cache_dir (keyword only)NoneWhere to keep builds. Default: the user cache directory, or CRN_CRAFT_CACHE_DIR.
cargo (keyword only)'cargo'The cargo executable.
source (keyword only)NoneA CRN-craft checkout of the installed version, for an offline build or a version that is not on crates.io. Default: CRN_CRAFT_SOURCE.
progress (keyword only)TrueFalse silences cargo’s progress on stderr.

As crn_craft.rules.compile_loop, for the document that ensemble runs: a rules-model gets the schema string crn-craft.model/1.0 and a network crn-craft.model/0.1 is converted. So ensemble(model, ..., compiled=compile_loop(model)) works for the same model argument. Generated loops run the linear scan: pass selector="linear" to ensemble unless "auto" picks it for the model.

loop_source

loop_source(model)

Return the generated Static Direct event loop of a model as Rust.

ArgumentDefaultMeaning
modelrequiredA model: bytes, text, a dictionary or a Model.

As crn_craft.rules.loop_source, for the document that ensemble runs: a rules-model gets the schema string crn-craft.model/1.0 and a network crn-craft.model/0.1 is converted, so the loop’s fingerprint is that of the model/1.0 bytes.

CompiledLoop

class CompiledLoop

Created by the functions of this page, not by calling it.

A compiled Static Direct event loop for one model and parameter set.

Returned by compile_loop. Pass it as compiled= to rules.ensemble, rules.prepare or PreparedEnsemble.simulate to run Static Direct requests for exactly this model with it.

  • fingerprint: the generated loop’s fingerprint, which covers the emitted source and the model bytes;
  • model_sha256: SHA-256 of the model bytes it was compiled for;
  • version: the crn-craft version it was built against;
  • path: the program; directory its cache entry with the Cargo project and log the build log;
  • cached: whether a cached build was reused; build_seconds the cargo time of a new build, else None.

CompiledLoop.execute

CompiledLoop.execute(request, *, cancel_file=None)

Run a rules-run request for this loop’s model in its program.

ArgumentDefaultMeaning
requestrequiredA rules-run request for this loop’s model.
cancel_file (keyword only)NonePath of a file; the run is cancelled when the file exists.

Returns the metadata text and the record columns, as the extension does. A rejected request raises CrnError.

CompiledLoop.verify

CompiledLoop.verify(run)

Run a prepared ensemble interpreted and compiled, and compare.

ArgumentDefaultMeaning
runrequiredA PreparedEnsemble for this loop’s model.

Raises CompiledLoopError (reason "mismatch") unless the metadata and every record column are byte-identical. Returns the result; replicates that ended early warn or raise as in run.simulate().

CompiledLoopError

class CompiledLoopError(message, reason, log=None)

A compiled event loop could not be built, or it disagreed with the interpreter.

ArgumentDefaultMeaning
messagerequiredThe message.
reasonrequired"cargo_missing", "build_failed" or "mismatch".
logNoneThe path of the build log, if a build started.

reason is "cargo_missing", "build_failed" or "mismatch"; log is the path of the build log, if a build started.

The importers module

Explicit finite-network import subsets. No silent SBML/rule expansion.

The importers build a network model (crn-craft.model/0.1) exactly as in 0.6.0, validate it, and return it converted to crn-craft.model/1.0 by crn_craft.convert, inside a crn-craft.import/1.0 report that keeps the source’s provenance. report["model"] is the converted model as a dictionary, ready for the unified API (a later read_sbml/read_bngl wraps it in a Model).