biocrnpyler.core.ChemicalReactionNetwork

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

Bases: object

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:
  • species (list of Species) – List of chemical species in the network.

  • reactions (list of Reaction) – List of reactions between species. Each reaction specifies inputs, outputs, and rate parameters.

  • initial_concentration_dict (dict, optional) – Dictionary mapping Species to their initial concentrations. Values can be numbers or Parameter objects. If None, an empty dictionary is created.

  • show_warnings (bool, default False) – If True, shows warnings about duplicate species/reactions or inconsistencies during CRN validation.

Attributes:
  • species (list of Species) – Deep copy of the species list (use add_species to modify).

  • reactions (list of Reaction) – Deep copy of the reactions list (use add_reactions to modify).

  • initial_concentration_dict (dict) – Dictionary of initial concentrations for species in the CRN.

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))

Methods

add_reactions

Add reactions to the CRN.

add_species

Add species to the CRN.

check_crn_validity

Validate that reactions and species can form a valid CRN.

generate_sbml_model

Generate an SBML model from the CRN.

get_all_species_containing

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

initial_condition_vector

Generate an initial condition vector for simulations.

pretty_print

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

replace_species

Replace a species with another throughout the CRN.

simulate_with_bioscrape

Simulate CRN with bioscrape.

simulate_with_bioscrape_via_sbml

Simulate CRN with bioscrape via SBML export.

simulate_with_roadrunner

Simulate CRN with libRoadRunner.

write_sbml_file

Write the CRN to an SBML file.

add_reactions(reactions: Reaction | List[Reaction], copy_reactions=True, add_species=True, compartment=None) None[source]

Add reactions to the CRN.

Parameters:
  • reactions (Reaction or list of Reaction) – Reaction object(s) to add to the CRN.

  • copy_reactions (bool, default True) – If True, deep-copies reactions before adding them to the CRN. Protects CRN validity at the expense of speed.

  • add_species (bool, default True) – If True, automatically adds any species appearing in the reactions to the CRN. Prevents missing species errors at the expense of speed.

  • compartment (Compartment, 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:
  • species (Species or list of Species) – Species object(s) to add to the CRN. Lists are automatically flattened and binding locations are removed.

  • copy_species (bool, default True) – If True, deep-copies species before adding them to the CRN. Protects CRN validity at the expense of speed.

  • compartment (Compartment, 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:
  • reactions (list of Reaction) – List of reactions to validate.

  • species (list of Species) – List of species to validate.

  • show_warnings (bool, default True) – If True, issues warnings for duplicates or inconsistencies.

Returns:

The input reactions and species lists, unchanged.

Return type:

tuple of (list of Reaction, list of Species)

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_model (bool, default False) – If True, generates an SBML model configured for stochastic simulation.

  • show_warnings (bool, default False) – If True, shows warnings from CRN validity checking.

  • check_validity (bool, default True) – If True, validates the CRN before generating SBML.

  • **kwargs – Additional keyword arguments passed to create_sbml_model and add_all_reactions.

Returns:

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

Return type:

tuple of (libsbml.SBMLDocument, libsbml.Model)

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:
  • species (Species) – The species to search for within other species.

  • return_as_strings (bool, default False) – If True, returns species as string representations. If False, returns actual Species objects.

Returns:

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

Return type:

list

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

Dictionary mapping Species to initial concentrations.

Type:

dict

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

Generate an initial condition vector for simulations.

Parameters:

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

Returns:

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

Return type:

list of float

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_rates (bool, default True) – If True, displays reaction rate functions and parameters.

  • show_material (bool, default True) – If True, displays species material types (e.g., ‘dna’, ‘protein’).

  • show_attributes (bool, default True) – If True, displays species attributes.

  • show_initial_concentration (bool, default True) – If True, displays initial concentrations for each species.

  • show_keys (bool, default True) – If True, shows parameter database keys for initial concentrations (useful for debugging parameter lookup).

  • show_compartment (bool, default False) – If True, displays compartment information for each species.

  • **kwargs – Additional keyword arguments passed to species and reaction pretty_print methods.

Returns:

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

Return type:

str

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

Deep copy of all reactions in the CRN.

Type:

List of Reaction

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:
  • species (Species) – The species to be replaced.

  • new_species (Species) – The species to replace with.

Returns:

New CRN with the species replacement applied.

Return type:

ChemicalReactionNetwork

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:
  • timepoints (array-like) – Time points for simulation.

  • initial_condition_dict (dict, optional) – Dictionary of initial concentrations.

  • stochastic (bool, default False) – If True, runs stochastic simulation.

  • return_dataframe (bool, default True) – If True, returns results as pandas DataFrame.

  • safe (bool, default False) – Safe mode for bioscrape simulation.

Returns:

Simulation results.

Return type:

DataFrame or array

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:
  • timepoints (array-like) – Array of time points at which to record simulation results.

  • filename (str, optional) – Path to save the SBML file. If None, creates a temporary file ‘temp_sbml_file.xml’.

  • initial_condition_dict (dict, optional) – Dictionary mapping species to initial concentrations. Overrides the CRN’s initial_concentration_dict.

  • return_dataframe (bool, default True) – If True, returns results as a pandas DataFrame. If False, returns a numpy array.

  • stochastic (bool, default False) – If True, runs stochastic (Gillespie) simulation. If False, runs deterministic (ODE) simulation.

  • safe (bool, default False) – If True, uses bioscrape’s safe mode which checks for errors.

  • return_model (bool, default False) – If True, returns a tuple of (results, bioscrape_model). If False, returns only results.

  • check_validity (bool, 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:

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

Return type:

DataFrame or array, or tuple

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:
  • timepoints (list of float) – Array of time points at which to record simulation results.

  • initial_condition_dict (dict, optional) – Dictionary mapping species names (strings) to initial concentrations. Overrides the CRN’s initial_concentration_dict.

  • return_roadrunner (bool, default False) – If True, returns the RoadRunner model object instead of simulation results. Useful for advanced control and analysis.

  • check_validity (bool, default True) – If True, validates the CRN before generating SBML.

Returns:

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

Return type:

array or RoadRunner

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

Deep copy of all species in the CRN.

Type:

list

Type:

List of Species

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_name (str) – Path where the SBML file will be written.

  • stochastic_model (bool, default False) – If True, exports an SBML file configured for stochastic simulations.

  • check_validity (bool, default True) – If True, validates the CRN before generating SBML.

  • **kwargs – Additional keyword arguments passed to generate_sbml_model.

Returns:

True if the file was written successfully.

Return type:

bool

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)