biocrnpyler.core.chemical_reaction_network

Classes

ChemicalReactionNetwork(species, reactions)

Container for chemical species and their reactions.

class biocrnpyler.core.chemical_reaction_network.ChemicalReactionNetwork(species: List[Species], reactions: List[Reaction], initial_concentration_dict: Dict[Species, Real | Parameter] = None, show_warnings=False)[source]

Container for chemical species and their reactions.

A ChemicalReactionNetwork (CRN) represents a biochemical system as a set of species and reactions between them. CRNs can be compiled to SBML format for simulation with various tools, or simulated directly with bioscrape or roadrunner.

Parameters:
specieslist of Species

List of chemical species in the network.

reactionslist of Reaction

List of reactions between species. Each reaction specifies inputs, outputs, and rate parameters.

initial_concentration_dictdict, optional

Dictionary mapping Species to their initial concentrations. Values can be numbers or Parameter objects. If None, an empty dictionary is created.

show_warningsbool, default=False

If True, shows warnings about duplicate species/reactions or inconsistencies during CRN validation.

Attributes:
specieslist of Species

list: List of Species : Deep copy of all species in the CRN.

reactionslist of Reaction

List of Reaction: Deep copy of all reactions in the CRN.

initial_concentration_dictdict

dict: Dictionary mapping Species to initial concentrations.

See also

Species

Chemical species in a CRN.

Reaction

Chemical reaction between species.

Mixture

High-level interface for building CRNs from components.

Notes

Mass action reactions follow standard mass action kinetics:

  • Deterministic propensity: \(k \prod_{i} [S_i]^{a_i}\)

  • Stochastic propensity: \(k \prod_{i} \frac{S_i!}{(S_i - a_i)!}\)

where \(a_i\) is the stoichiometric coefficient of species \(i\).

A valid CRN requires:

  • All species in reactions must be in the species list

  • All species and reactions must be unique (duplicates trigger warnings)

  • Initial concentrations must be non-negative

Once created, species and reactions cannot be removed, only added. This ensures CRN validity is maintained throughout its lifetime.

Chemical reaction networks can be simulated by writing the output as SMBL using write_sbml_file and then loading into an external simulator, or by using the bioscrape package, which can be called directly using simulate_with_bioscrape_via_sbml.

Examples

Create a simple CRN manually:

>>> # Define species
>>> S = bcp.Species('S')
>>> P = bcp.Species('P')
>>> E = bcp.Species('protein_E')
>>> C = bcp.Species('C')
>>> # Define reactions
>>> rxn1 = bcp.Reaction.from_massaction(
...     [S, E], [C], k_forward=0.1, k_reverse=1e-4)
>>> rxn2 = bcp.Reaction.from_massaction([C], [E, P], k_forward=0.01)
>>> # Create CRN
>>> crn = bcp.ChemicalReactionNetwork(
...     species=[S, E, C, P],
...     reactions=[rxn1, rxn2]
... )

Compile a CRN from a mixture:

>>> enzyme = bcp.Enzyme('E', 'S', 'P')
>>> mixture = bcp.Mixture(
...     components=[enzyme],
...     mechanisms={'catalysis': bcp.MichaelisMenten()},
...     parameters={'kb': 0.1, 'ku': 1e-4, 'kcat': 0.01})
>>> crn = mixture.compile_crn()
>>> print(
...     f"CRN has {len(crn.species)} species and "
...     f"{len(crn.reactions)} reactions")
CRN has 4 species and 2 reactions

Export to SBML and simulate:

>>> crn.write_sbml_file('model.xml')
>>> result = crn.simulate_with_bioscrape_via_sbml(
...     initial_condition_dict={S: 100, 'protein_E': 50, P: 0},
...     timepoints=np.linspace(0, 5))
add_reactions(reactions: Reaction | List[Reaction], copy_reactions=True, add_species=True, compartment=None) None[source]

Add reactions to the CRN.

Parameters:
reactionsReaction or list of Reaction

Reaction object(s) to add to the CRN.

copy_reactionsbool, default=True

If True, deep-copies reactions before adding them to the CRN. Protects CRN validity at the expense of speed.

add_speciesbool, default=True

If True, automatically adds any species appearing in the reactions to the CRN. Prevents missing species errors at the expense of speed.

compartmentCompartment, optional

If provided, assigns this compartment to any species with default compartments found in the reactions.

Raises:
ValueError

If any element is not a Reaction object.

Notes

Unlike species, reactions are not checked for duplicates when added. It is recommended to keep copy_reactions=True to protect the CRN from external modifications.

add_species(species, copy_species=True, compartment=None)[source]

Add species to the CRN.

Parameters:
speciesSpecies or list of Species

Species object(s) to add to the CRN. Lists are automatically flattened and binding locations are removed.

copy_speciesbool, default=True

If True, deep-copies species before adding them to the CRN. Protects CRN validity at the expense of speed.

compartmentCompartment, optional

If provided, assigns this compartment to any species with default compartments.

Raises:
ValueError

If any element is not a Species object.

Notes

Duplicate species (based on equality) are automatically filtered out. Species are stored in both a list (_species) and a set (_species_set) for efficient duplicate checking.

static check_crn_validity(reactions: List[Reaction], species: List[Species], show_warnings=True) Tuple[List[Reaction], List[Species]][source]

Validate that reactions and species can form a valid CRN.

Checks for duplicate species/reactions and verifies that all species in reactions are present in the species list.

Parameters:
reactionslist of Reaction

List of reactions to validate.

specieslist of Species

List of species to validate.

show_warningsbool, default=True

If True, issues warnings for duplicates or inconsistencies.

Returns:
tuple of (list of Reaction, list of Species)

The input reactions and species lists, unchanged.

Raises:
ValueError

If any reaction is not a Reaction object, or any species is not a Species object.

Warns:
UserWarning
  • Duplicate reactions or species are found

  • Species exist without reactions

  • Reactions contain unlisted species

generate_sbml_model(stochastic_model=False, show_warnings=False, check_validity=True, **kwargs)[source]

Generate an SBML model from the CRN.

Creates SBML document and model objects containing all species, reactions, compartments, and parameters from the CRN.

Parameters:
stochastic_modelbool, default=False

If True, generates an SBML model configured for stochastic simulation.

show_warningsbool, default=False

If True, shows warnings from CRN validity checking.

check_validitybool, default=True

If True, validates the CRN before generating SBML.

**kwargs

Additional keyword arguments passed to create_sbml_model and add_all_reactions.

Returns:
tuple of (libsbml.SBMLDocument, libsbml.Model)

The SBML document and model objects. The document can be written to a file or further manipulated.

Warns:
UserWarning

Issues a warning if the generated SBML model contains errors.

See also

write_sbml_file

Write the SBML model directly to a file.

get_all_species_containing(species: Species, return_as_strings=False)[source]

Find all species (complexes) that contain a given species.

Searches recursively through all species in the CRN to find those that contain the target species as a component.

Parameters:
speciesSpecies

The species to search for within other species.

return_as_stringsbool, default=False

If True, returns species as string representations. If False, returns actual Species objects.

Returns:
list

List of Species objects (or strings if return_as_strings=True) that contain the target species.

Raises:
ValueError

If species is not a Species object.

Examples

>>> substrate = bcp.Species('S')
>>> enzyme = bcp.Enzyme('E', substrate, 'P')
>>> mixture = bcp.Mixture(
...     components=[enzyme],
...     mechanisms={'catalysis': bcp.MichaelisMenten()},
...     parameters={'kb': 0.1, 'ku': 1e-4, 'kcat': 0.01})
>>> crn = mixture.compile_crn()
>>> # Find all complexes containing S
>>> crn.get_all_species_containing(substrate)
[S, complex_S_protein_E_]
property initial_concentration_dict

dict: Dictionary mapping Species to initial concentrations.

initial_condition_vector(init_cond_dict: Dict[str, float] | Dict[Species, float])[source]

Generate an initial condition vector for simulations.

Parameters:
init_cond_dictdict

Dictionary mapping species (or species names as strings) to their initial concentrations.

Returns:
list of float

Vector of initial concentrations matching the order of species in self._species. Species not in init_cond_dict are set to 0.0.

pretty_print(show_rates=True, show_material=True, show_attributes=True, show_initial_concentration=True, show_keys=True, show_compartment=False, **kwargs)[source]

Generate detailed, human-readable string representation of the CRN.

Parameters:
show_ratesbool, default=True

If True, displays reaction rate functions and parameters.

show_materialbool, default=True

If True, displays species material types (e.g., ‘dna’, ‘protein’).

show_attributesbool, default=True

If True, displays species attributes.

show_initial_concentrationbool, default=True

If True, displays initial concentrations for each species.

show_keysbool, default=True

If True, shows parameter database keys for initial concentrations (useful for debugging parameter lookup).

show_compartmentbool, default=False

If True, displays compartment information for each species.

**kwargs

Additional keyword arguments passed to species and reaction pretty_print methods.

Returns:
str

Formatted string with species (sorted by initial concentration) and reactions with detailed information.

Notes

This method provides much more detailed output than __repr__, making it useful for debugging and understanding CRN structure. Species are sorted by initial concentration (highest first) for easier analysis.

property reactions

List of Reaction: Deep copy of all reactions in the CRN.

replace_species(species: Species, new_species: Species)[source]

Replace a species with another throughout the CRN.

Creates a new CRN where all occurrences of a target species are replaced with a new species. The original CRN is not modified.

Parameters:
speciesSpecies

The species to be replaced.

new_speciesSpecies

The species to replace with.

Returns:
ChemicalReactionNetwork

New CRN with the species replacement applied.

Raises:
ValueError

If either argument is not a Species object.

Notes

This method does not modify the original CRN. It creates and returns a new CRN with the replacement applied throughout all species and reactions.

simulate_with_bioscrape(timepoints, initial_condition_dict=None, stochastic=False, return_dataframe=True, safe=False)[source]

Simulate CRN with bioscrape.

Deprecated since version 1.0.0: This method is deprecated. Use simulate_with_bioscrape_via_sbml instead.

Parameters:
timepointsarray-like

Time points for simulation.

initial_condition_dictdict, optional

Dictionary of initial concentrations.

stochasticbool, default=False

If True, runs stochastic simulation.

return_dataframebool, default=True

If True, returns results as pandas DataFrame.

safebool, default=False

Safe mode for bioscrape simulation.

Returns:
DataFrame or array

Simulation results.

See also

simulate_with_bioscrape_via_sbml

Recommended simulation method.

simulate_with_bioscrape_via_sbml(timepoints, filename=None, initial_condition_dict=None, return_dataframe=True, stochastic=False, safe=False, return_model=False, check_validity=True, **kwargs)[source]

Simulate CRN with bioscrape via SBML export.

Exports the CRN to an SBML file and simulates it using the bioscrape simulator. Bioscrape is a stochastic and deterministic simulator for biological circuits.

Parameters:
timepointsarray-like

Array of time points at which to record simulation results.

filenamestr, optional

Path to save the SBML file. If None, creates a temporary file ‘temp_sbml_file.xml’.

initial_condition_dictdict, optional

Dictionary mapping species to initial concentrations. Overrides the CRN’s initial_concentration_dict.

return_dataframebool, default=True

If True, returns results as a pandas DataFrame. If False, returns a numpy array.

stochasticbool, default=False

If True, runs stochastic (Gillespie) simulation. If False, runs deterministic (ODE) simulation.

safebool, default=False

If True, uses bioscrape’s safe mode which checks for errors.

return_modelbool, default=False

If True, returns a tuple of (results, bioscrape_model). If False, returns only results.

check_validitybool, default=True

If True, validates the CRN before generating SBML.

**kwargs

Additional keyword arguments. ‘sbml_warnings’ can be set to True to show SBML parsing warnings.

Returns:
DataFrame or array, or tuple

Simulation results as DataFrame or array. If return_model=True, returns tuple of (results, bioscrape Model object).

Warns:
UserWarning

Issues a warning if bioscrape is not installed.

Notes

Requires bioscrape to be installed: pip install bioscrape

Bioscrape GitHub: https://github.com/biocircuits/bioscrape

Examples

>>> result = crn.simulate_with_bioscrape_via_sbml(
...     timepoints=np.linspace(0, 10, 100)
... )
>>> # Stochastic simulation
>>> result = crn.simulate_with_bioscrape_via_sbml(
...     timepoints=np.linspace(0, 10, 100),
...     stochastic=True
... )
simulate_with_roadrunner(timepoints: List[float], initial_condition_dict: Dict[str, float] = None, return_roadrunner=False, check_validity=True)[source]

Simulate CRN with libRoadRunner.

Converts the CRN to SBML in memory and simulates it using the libRoadRunner deterministic simulator. libRoadRunner is a fast SBML simulator for deterministic (ODE) simulation.

Parameters:
timepointslist of float

Array of time points at which to record simulation results.

initial_condition_dictdict, optional

Dictionary mapping species names (strings) to initial concentrations. Overrides the CRN’s initial_concentration_dict.

return_roadrunnerbool, default=False

If True, returns the RoadRunner model object instead of simulation results. Useful for advanced control and analysis.

check_validitybool, default=True

If True, validates the CRN before generating SBML.

Returns:
array or RoadRunner

If return_roadrunner=False, returns simulation results as a numpy array. If return_roadrunner=True, returns the RoadRunner model object.

Warns:
UserWarning

Issues a warning if libroadrunner is not installed.

Notes

Requires libroadrunner to be installed: pip install libroadrunner

libRoadRunner documentation: https://libroadrunner.org/

Examples

>>> result = crn.simulate_with_roadrunner(
...     timepoints=np.linspace(0, 10, 100)
... )
>>> # Get RoadRunner object for advanced control
>>> rr = crn.simulate_with_roadrunner(
...     timepoints=np.linspace(0, 10, 100),
...     return_roadrunner=True
... )
>>> # Run parameter scan with RoadRunner
>>> result = rr.simulate(0, 10, 100)
property species

list: List of Species : Deep copy of all species in the CRN.

write_sbml_file(file_name=None, stochastic_model=False, check_validity=True, **kwargs) bool[source]

Write the CRN to an SBML file.

Generates an SBML model from the CRN and writes it to a file for use with simulators like COPASI, VCell, or bioscrape.

Parameters:
file_namestr

Path where the SBML file will be written.

stochastic_modelbool, default=False

If True, exports an SBML file configured for stochastic simulations.

check_validitybool, default=True

If True, validates the CRN before generating SBML.

**kwargs

Additional keyword arguments passed to generate_sbml_model.

Returns:
bool

True if the file was written successfully.

See also

generate_sbml_model

Generate SBML objects without writing to file.

Examples

>>> crn.write_sbml_file('my_model.xml')
>>> crn.write_sbml_file('stochastic_model.xml', stochastic_model=True)