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:
objectContainer 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 (
listofSpecies) – List of chemical species in the network.reactions (
listofReaction) – 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 orParameterobjects. If None, an empty dictionary is created.show_warnings (
bool, defaultFalse) – If True, shows warnings about duplicate species/reactions or inconsistencies during CRN validation.
- Attributes:
species (
listofSpecies) – Deep copy of the species list (useadd_speciesto modify).reactions (
listofReaction) – Deep copy of the reactions list (useadd_reactionsto modify).initial_concentration_dict (
dict) – Dictionary of initial concentrations for species in the CRN.
See also
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_fileand then loading into an external simulator, or by using the bioscrape package, which can be called directly usingsimulate_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 to the CRN.
Add species to the CRN.
Validate that reactions and species can form a valid CRN.
Generate an SBML model from the CRN.
Find all species (complexes) that contain a given species.
Generate an initial condition vector for simulations.
Generate detailed, human-readable string representation of the CRN.
Replace a species with another throughout the CRN.
Simulate CRN with bioscrape.
Simulate CRN with bioscrape via SBML export.
Simulate CRN with libRoadRunner.
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 (
ReactionorlistofReaction) – Reaction object(s) to add to the CRN.copy_reactions (
bool, defaultTrue) – If True, deep-copies reactions before adding them to the CRN. Protects CRN validity at the expense of speed.add_species (
bool, defaultTrue) – 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=Trueto protect the CRN from external modifications.
- add_species(species, copy_species=True, compartment=None)[source]
Add species to the CRN.
- Parameters:
species (
SpeciesorlistofSpecies) – Species object(s) to add to the CRN. Lists are automatically flattened and binding locations are removed.copy_species (
bool, defaultTrue) – 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:
- Returns:
The input reactions and species lists, unchanged.
- Return type:
tupleof(listofReaction,listofSpecies)- 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, defaultFalse) – If True, generates an SBML model configured for stochastic simulation.show_warnings (
bool, defaultFalse) – If True, shows warnings from CRN validity checking.check_validity (
bool, defaultTrue) – If True, validates the CRN before generating SBML.**kwargs – Additional keyword arguments passed to
create_sbml_modelandadd_all_reactions.
- Returns:
The SBML document and model objects. The document can be written to a file or further manipulated.
- Return type:
tupleof(libsbml.SBMLDocument,libsbml.Model)- Warns:
UserWarning – Issues a warning if the generated SBML model contains errors.
See also
write_sbml_fileWrite 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, defaultFalse) – 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
speciesis 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 ininit_cond_dictare set to 0.0.- Return type:
listoffloat
- 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, defaultTrue) – If True, displays reaction rate functions and parameters.show_material (
bool, defaultTrue) – If True, displays species material types (e.g., ‘dna’, ‘protein’).show_attributes (
bool, defaultTrue) – If True, displays species attributes.show_initial_concentration (
bool, defaultTrue) – If True, displays initial concentrations for each species.show_keys (
bool, defaultTrue) – If True, shows parameter database keys for initial concentrations (useful for debugging parameter lookup).show_compartment (
bool, defaultFalse) – If True, displays compartment information for each species.**kwargs – Additional keyword arguments passed to species and reaction
pretty_printmethods.
- 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.
- 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:
- Returns:
New CRN with the species replacement applied.
- Return type:
- 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_sbmlinstead.- Parameters:
timepoints (
array-like) – Time points for simulation.initial_condition_dict (
dict, optional) – Dictionary of initial concentrations.stochastic (
bool, defaultFalse) – If True, runs stochastic simulation.return_dataframe (
bool, defaultTrue) – If True, returns results as pandas DataFrame.safe (
bool, defaultFalse) – Safe mode for bioscrape simulation.
- Returns:
Simulation results.
- Return type:
DataFrameorarray
See also
simulate_with_bioscrape_via_sbmlRecommended 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’sinitial_concentration_dict.return_dataframe (
bool, defaultTrue) – If True, returns results as a pandas DataFrame. If False, returns a numpy array.stochastic (
bool, defaultFalse) – If True, runs stochastic (Gillespie) simulation. If False, runs deterministic (ODE) simulation.safe (
bool, defaultFalse) – If True, uses bioscrape’s safe mode which checks for errors.return_model (
bool, defaultFalse) – If True, returns a tuple of (results, bioscrape_model). If False, returns only results.check_validity (
bool, defaultTrue) – 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:
DataFrameorarray, ortuple- Warns:
UserWarning – Issues a warning if bioscrape is not installed.
Notes
Requires bioscrape to be installed:
pip install bioscrapeBioscrape 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 (
listoffloat) – 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’sinitial_concentration_dict.return_roadrunner (
bool, defaultFalse) – If True, returns the RoadRunner model object instead of simulation results. Useful for advanced control and analysis.check_validity (
bool, defaultTrue) – If True, validates the CRN before generating SBML.
- Returns:
If
return_roadrunner=False, returns simulation results as a numpy array. Ifreturn_roadrunner=True, returns the RoadRunner model object.- Return type:
arrayorRoadRunner- Warns:
UserWarning – Issues a warning if libroadrunner is not installed.
Notes
Requires libroadrunner to be installed:
pip install libroadrunnerlibRoadRunner 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)
- 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, defaultFalse) – If True, exports an SBML file configured for stochastic simulations.check_validity (
bool, defaultTrue) – 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_modelGenerate SBML objects without writing to file.
Examples
>>> crn.write_sbml_file('my_model.xml') >>> crn.write_sbml_file('stochastic_model.xml', stochastic_model=True)