biocrnpyler.core.species

Classes

Complex(*args, **kwargs)

Metaclass for creating chemical complexes.

ComplexSpecies(species[, name, ...])

Species formed from multiple bound species.

OrderedComplexSpecies(species[, name, ...])

Complex species where species order is significant.

OrderedPolymerSpecies(species[, name, ...])

Ordered polymer that can participate in chemical reactions.

PolymerConformation([complexes, polymer, ...])

Set of polymers and their connections via ComplexSpecies.

Species(name[, material_type, attributes, ...])

A formal species object for a chemical reaction network (CRN).

WeightedSpecies(species[, stoichiometry])

Container for a species with stoichiometric coefficient.

class biocrnpyler.core.species.Complex(*args, **kwargs)[source]

Metaclass for creating chemical complexes.

Complex is not a class that gets instantiated directly - it creates instances of ComplexSpecies, OrderedComplexSpecies, OrderedPolymerSpecies, or PolymerConformation based on the input species and their parent relationships.

Parameters:
specieslist of Species

List of species to combine into a complex. Can include standalone Species, Species with parents (monomers in polymers), or entire OrderedPolymerSpecies.

orderedbool, default=False

If True, creates OrderedComplexSpecies where species order matters. If False, creates ComplexSpecies where order is irrelevant.

**kwargs

Additional keyword arguments passed to the created species class.

Returns:
ComplexSpecies, OrderedComplexSpecies, OrderedPolymerSpecies, or
PolymerConformation

The type of species returned depends on the input structure:

  • Simple species list -> ComplexSpecies or OrderedComplexSpecies

  • Monomers from one polymer -> OrderedPolymerSpecies

  • Monomers from multiple polymers/conformations -> PolymerConformation

See also

ComplexSpecies

Unordered complex of multiple species.

OrderedComplexSpecies

Ordered complex of multiple species.

OrderedPolymerSpecies

Polymer species for reactions.

PolymerConformation

Multiple polymers with connections.

Notes

The __new__ method implements logic for different scenarios:

  1. No parents: Creates ComplexSpecies or OrderedComplexSpecies

  2. Single polymer parent: Creates OrderedPolymerSpecies with complex at binding site

  3. Multiple polymer parents or conformations: Creates PolymerConformation merging all complexes

  4. Error cases: Raises exceptions for invalid combinations

The correct species type is automatically determined from the input, allowing flexible complex formation without explicit type selection.

Examples

Create a simple complex:

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> complex = bcp.Complex([S1, S2])
>>> type(complex)
biocrnpyler.core.species.ComplexSpecies

Create an ordered complex:

>>> ordered = bcp.Complex([S1, S2], ordered=True)
>>> type(ordered)
biocrnpyler.core.species.OrderedComplexSpecies

Create a complex at a polymer binding site:

>>> S3 = bcp.Species('S3')
>>> polymer = bcp.OrderedPolymerSpecies([S1, S2])
>>> # S1 is now inside the polymer at position 0
>>> complex = bcp.Complex([polymer[0], S3])
>>> type(complex.parent)
biocrnpyler.core.species.OrderedPolymerSpecies
static __new__(cls, *args, **kwargs)[source]

Create an instance of the appropriate species type.

This method analyzes the input species and their parent relationships to determine which type of complex to create.

Parameters:
*args

Positional arguments, first should be the species list.

**kwargs

Keyword arguments including ‘species’ and ‘ordered’.

Returns:
ComplexSpecies, OrderedComplexSpecies, OrderedPolymerSpecies, or
PolymerConformation

The appropriate species type based on input structure.

Raises:
TypeError

If species argument is not a list, or if trying to complex entire OrderedPolymerSpecies that are already in PolymerConformations, or if invalid parent types are found.

ValueError

If trying to form complexes between monomers from multiple OrderedPolymerSpecies without PolymerConformations.

Notes

Cases handled:

  1. No Species have parents -> ComplexSpecies or 1OrderedComplexSpecies`

  2. Single Species has parent OrderedPolymerSpecies (no parent) -> OrderedPolymerSpecies with complex at binding site

  3. Multiple Species with OrderedPolymerSpecies1` parents (no parents) -> Error (must use PolymerConformations)

  4. Entire OrderedPolymerSpecies in PolymerConformations -> Error

  5. One or more Species from polymer Conformations -> PolymerConformation merging all complexes

class biocrnpyler.core.species.ComplexSpecies(species: List[Species | str], name: str | None = None, material_type='complex', attributes=None, compartment=None, called_from_complex=False)[source]

Species formed from multiple bound species.

A special kind of species representing a complex of two or more bound species. ComplexSpecies should always be created using the Complex function, not directly. Order of species in the list does not matter: ComplexSpecies([s1, s2]) == ComplexSpecies([s2, s1]).

Parameters:
specieslist of Species or str

List of species forming the complex. Must contain at least 2 species.

namestr or None, optional

Custom name for the complex. If None, generates a name from constituent species.

material_typestr, default=’complex’

Material type identifier for the complex.

attributeslist of str or None, optional

Attributes for the complex species.

compartmentCompartment, str, or None, optional

Compartment containing the complex.

called_from_complexbool, default=False

Internal flag to enforce use of Complex function.

Attributes:
specieslist of Species

Sorted list of constituent species in the complex.

species_setlist of Species

Unique species in the complex, sorted by string representation.

namestr

Name of the complex (auto-generated if not provided).

See also

Complex

Metaclass for creating ComplexSpecies.

OrderedComplexSpecies

Complex where species order matters.

Species

Base class for chemical species.

Notes

ComplexSpecies add an additional ‘_’ at the end of their string representation to differentiate edge cases.

Species order does not affect equality: ComplexSpecies([s1, s2]) == ComplexSpecies([s2, s1])

For ordered complexes, use OrderedComplexSpecies.

If no name is provided, the complex is named by concatenating all constituent species names with counts for duplicates.

Always use the Complex function to create ComplexSpecies:

>>> # Correct
>>> complex_species = bcp.Complex([S1, S2])
>>> # Incorrect (will raise warning)
>>> complex_species = bcp.ComplexSpecies([S1, S2])

Examples

Create a complex (using Complex function):

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> complex_species = bcp.Complex([S1, S2])

Check if a species is in a complex:

>>> S1 in complex_species
True
__contains__(item)[source]

Check if a species is contained in the complex.

Parameters:
itemSpecies

The species to search for.

Returns:
bool

True if the species is found in the complex or any nested complexes, False otherwise.

Raises:
ValueError

If item is not a Species instance.

Notes

This method searches recursively through nested ComplexSpecies to find the target species.

__eq__(other)[source]

Check if two species are equivalent.

Two species are equal if they have the same name, material_type, attributes (as sets), parent, compartment, and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species are equivalent, False otherwise.

Notes

Equality between parents and children can result in loops, so string equality is used for parent comparison.

__gt__(Species2)[source]

Return self>value.

__hash__()[source]

Compute hash value for this monomer.

Returns:
int

Hash value based on position, direction, name (if present), and parent.

__lt__(Species2)[source]

Return self<value.

add_attribute(attribute: str)[source]

Add an attribute to the species.

Parameters:
attributestr

The attribute to add. Must be an alphanumeric string and non-None.

Raises:
AssertionError

If attribute is not an alphanumeric string or is None.

Notes

Duplicate attributes are not added - each attribute appears only once in the attributes list.

Examples

>>> species = bcp.Species('MyProtein')
>>> species.add_attribute('degraded')
>>> species.attributes
['degraded']
contains_species_monomer(s)[source]

Check if the species contains a monomer, ignoring context.

Parameters:
sSpecies

The species monomer to search for.

Returns:
bool

True if the species contains a monomer equal to s (ignoring parent, position, and direction), False otherwise.

Notes

This is a less stringent version of __contains__ that checks without considering Species.parent, Species.position, or direction. Useful for determining if a species is present regardless of its polymer context.

find_polymer_component()[source]

Find the polymer component within this monomer or its species.

Searches this monomer and, if it is a ComplexSpecies, its constituent species to find which one is marked as a polymer component.

Returns:
OrderedMonomer or None

The monomer that is part of a polymer structure, or None if no polymer component is found.

Raises:
ValueError

If multiple species are marked as polymer components in the same location.

Notes

This method is primarily used internally to handle complex species that may contain monomers as part of larger structures.

static flatten_list(in_list) List[source]

Recursively flatten a nested list of species.

Parameters:
in_listlist or Species

A potentially nested list of species, or a single species.

Returns:
list

Flattened list containing all species. None elements are filtered out.

Examples

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> nested = [S1, [S2, None]]
>>> bcp.Species.flatten_list(nested)
[S1, S2]
get_orphan()[source]

Create a copy of this monomer without a parent reference.

Returns a copy that retains position and direction but has no parent polymer. Useful for temporarily working with monomers outside their polymer context.

Returns:
OrderedMonomer

A copy of this monomer with parent set to None but position and direction preserved.

See also

get_removed

Create a fully detached copy.

remove

Remove this monomer from its parent in place.

Notes

This is a shallow copy of the monomer object itself, though the parent reference is explicitly cleared.

get_removed()[source]

Create a fully detached copy of this monomer.

Returns a copy with all polymer-related attributes (parent, position, direction) cleared. Also removes ‘forward’ and ‘reverse’ attributes if present.

Returns:
OrderedMonomer

A copy of this monomer with no parent, position, or direction, and with directional attributes removed.

See also

get_orphan

Create a copy without parent but with position and direction.

remove

Remove this monomer from its parent in place.

Notes

This method is useful for creating completely independent copies of monomers that can be reused in different contexts without any polymer associations.

get_species(recursive=False)[source]

Get all species in the complex.

Parameters:
recursivebool, default=False

If True, returns species inside nested ComplexSpecies recursively. If False, returns only this ComplexSpecies.

Returns:
list of Species

List of species. If recursive=False, returns [self]. If recursive=True, returns [self] plus all constituent species.

monomer_count(m)[source]

Count occurrences of a monomer in the complex.

Parameters:
mSpecies

The monomer to count.

Returns:
int

Number of times the monomer appears in the complex, using monomer_eq for equality comparison.

Notes

This effectively implements self.species.count(m) but uses monomer_eq for equality, which ignores parent and position.

monomer_eq(other)[source]

Check if two monomers are equal, ignoring parent and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species have the same name, material_type, attributes, and compartment, regardless of parent or position.

Notes

This is the same as normal equality but does not check for parents or positions. Useful for comparing species that may be in different polymer contexts.

monomer_insert(parent: OrderedPolymer, position: int, direction=None)[source]

Insert this monomer into a polymer at a specific position.

Sets the monomer’s parent, position, and direction attributes to reflect its insertion into the polymer. Marks the monomer (or its polymer component if it is a complex species) as a polymer component.

Parameters:
parentOrderedPolymer

The polymer to insert this monomer into.

positionint

The position index where this monomer is being inserted.

directionstr, int, or None, optional

The direction for this monomer. If None, uses the monomer’s existing direction.

Raises:
ValueError

If position is None, or if parent is None.

pretty_print(show_material=True, show_compartment=False, show_attributes=True, show_initial_condition=False, **kwargs)[source]

A more powerful printing function.

Useful for understanding CRNs but does not return string identifiers. show_material toggles whether species.material is printed. show_attributes toggles whether species.attributes is printed

remove()[source]

Remove the species from its parent polymer.

Overrides OrderedMonomer.remove to also remove the direction attribute if present.

Returns:
Species

Returns self after removal for method chaining.

remove_attribute(attribute: str)[source]

Remove an attribute from the species.

Parameters:
attributestr

The attribute to remove. Must be an alphanumeric string.

Notes

If the attribute is not present or is None, no action is taken. All occurrences of the attribute are removed from the attributes list.

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

Replace a species throughout the entire complex.

Acts recursively on nested ComplexSpecies. Does not modify in place - returns a new ComplexSpecies.

Parameters:
speciesSpecies

The species to replace.

new_speciesSpecies

The species to replace with.

Returns:
ComplexSpecies

A new ComplexSpecies with the replacement applied.

Raises:
ValueError

If either argument is not a Species instance.

set_dir(direction)[source]

Set the direction of the monomer and return self.

Convenience method for setting direction in a fluent interface style.

Parameters:
directionstr, int, or None

The direction to assign to this monomer.

Returns:
OrderedMonomer

Returns self for method chaining.

Examples

>>> monomer = bcp.OrderedMonomer().set_dir('forward')
>>> monomer.direction
'forward'
subhash()[source]

Compute hash contribution from monomer properties.

Computes a hash value based on the monomer’s position, direction, and name (if present), excluding the parent reference.

Returns:
int

Hash value based on monomer-specific properties.

Notes

This method is used by __hash__ to compute the monomer’s hash contribution. It excludes the parent to avoid circular dependencies in hash computation.

class biocrnpyler.core.species.OrderedComplexSpecies(species, name=None, material_type='ordered_complex', attributes=None, compartment=None, called_from_complex=False)[source]

Complex species where species order is significant.

A special kind of species formed from a complex of two or more species where the order matters. OrderedComplexSpecies should always be created using the Complex function with ordered=True, not directly. Unlike ComplexSpecies, [s1, s2, s3] != [s1, s3, s2].

Parameters:
specieslist of Species or str

Ordered list of species forming the complex. Must contain at least 2 species.

namestr or None, optional

Custom name for the complex. If None, generates a name from constituent species in order.

material_typestr, default=’ordered_complex’

Material type identifier for the ordered complex.

attributeslist of str or None, optional

Attributes for the complex species.

compartmentCompartment, str, or None, optional

Compartment containing the complex.

called_from_complexbool, default=False

Internal flag to enforce use of Complex function.

Attributes:
specieslist of Species

Ordered list of constituent species (NOT sorted).

namestr

Name of the complex (auto-generated if not provided).

See also

Complex

Metaclass for creating ordered complexes.

ComplexSpecies

Complex where species order doesn’t matter.

OrderedPolymerSpecies

Ordered polymer for chemical reactions.

Notes

Unlike ComplexSpecies, the order of species matters: OrderedComplexSpecies([s1, s2]) != OrderedComplexSpecies([s2, s1])

Similar to ComplexSpecies, OrderedComplexSpecies add an additional ‘_’ at the end.

Always use Complex with ordered=True:

>>> # Correct
>>> complex_species = bcp.Complex([S1, S2], ordered=True)
>>> # Incorrect (will raise warning)
>>> complex_species = bcp.OrderedComplexSpecies([S1, S2])

Examples

Create an ordered complex:

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> ordered = bcp.Complex([S1, S2], ordered=True)
>>> reversed = bcp.Complex([S2, S1], ordered=True)
>>> ordered == reversed
False
__contains__(item)[source]

Check if a species is contained in the complex.

Parameters:
itemSpecies

The species to search for.

Returns:
bool

True if the species is found in the complex or any nested complexes, False otherwise.

Raises:
ValueError

If item is not a Species instance.

Notes

This method searches recursively through nested ComplexSpecies to find the target species.

__eq__(other)[source]

Check if two species are equivalent.

Two species are equal if they have the same name, material_type, attributes (as sets), parent, compartment, and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species are equivalent, False otherwise.

Notes

Equality between parents and children can result in loops, so string equality is used for parent comparison.

__gt__(Species2)[source]

Return self>value.

__hash__()[source]

Compute hash value for this monomer.

Returns:
int

Hash value based on position, direction, name (if present), and parent.

__lt__(Species2)[source]

Return self<value.

add_attribute(attribute: str)[source]

Add an attribute to the species.

Parameters:
attributestr

The attribute to add. Must be an alphanumeric string and non-None.

Raises:
AssertionError

If attribute is not an alphanumeric string or is None.

Notes

Duplicate attributes are not added - each attribute appears only once in the attributes list.

Examples

>>> species = bcp.Species('MyProtein')
>>> species.add_attribute('degraded')
>>> species.attributes
['degraded']
contains_species_monomer(s)[source]

Check if the species contains a monomer, ignoring context.

Parameters:
sSpecies

The species monomer to search for.

Returns:
bool

True if the species contains a monomer equal to s (ignoring parent, position, and direction), False otherwise.

Notes

This is a less stringent version of __contains__ that checks without considering Species.parent, Species.position, or direction. Useful for determining if a species is present regardless of its polymer context.

find_polymer_component()[source]

Find the polymer component within this monomer or its species.

Searches this monomer and, if it is a ComplexSpecies, its constituent species to find which one is marked as a polymer component.

Returns:
OrderedMonomer or None

The monomer that is part of a polymer structure, or None if no polymer component is found.

Raises:
ValueError

If multiple species are marked as polymer components in the same location.

Notes

This method is primarily used internally to handle complex species that may contain monomers as part of larger structures.

static flatten_list(in_list) List[source]

Recursively flatten a nested list of species.

Parameters:
in_listlist or Species

A potentially nested list of species, or a single species.

Returns:
list

Flattened list containing all species. None elements are filtered out.

Examples

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> nested = [S1, [S2, None]]
>>> bcp.Species.flatten_list(nested)
[S1, S2]
get_orphan()[source]

Create a copy of this monomer without a parent reference.

Returns a copy that retains position and direction but has no parent polymer. Useful for temporarily working with monomers outside their polymer context.

Returns:
OrderedMonomer

A copy of this monomer with parent set to None but position and direction preserved.

See also

get_removed

Create a fully detached copy.

remove

Remove this monomer from its parent in place.

Notes

This is a shallow copy of the monomer object itself, though the parent reference is explicitly cleared.

get_removed()[source]

Create a fully detached copy of this monomer.

Returns a copy with all polymer-related attributes (parent, position, direction) cleared. Also removes ‘forward’ and ‘reverse’ attributes if present.

Returns:
OrderedMonomer

A copy of this monomer with no parent, position, or direction, and with directional attributes removed.

See also

get_orphan

Create a copy without parent but with position and direction.

remove

Remove this monomer from its parent in place.

Notes

This method is useful for creating completely independent copies of monomers that can be reused in different contexts without any polymer associations.

get_species(recursive=False)[source]

Get all species in the complex.

Parameters:
recursivebool, default=False

If True, returns species inside nested ComplexSpecies recursively. If False, returns only this ComplexSpecies.

Returns:
list of Species

List of species. If recursive=False, returns [self]. If recursive=True, returns [self] plus all constituent species.

monomer_count(m)[source]

Count occurrences of a monomer in the complex.

Parameters:
mSpecies

The monomer to count.

Returns:
int

Number of times the monomer appears in the complex, using monomer_eq for equality comparison.

Notes

This effectively implements self.species.count(m) but uses monomer_eq for equality, which ignores parent and position.

monomer_eq(other)[source]

Check if two monomers are equal, ignoring parent and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species have the same name, material_type, attributes, and compartment, regardless of parent or position.

Notes

This is the same as normal equality but does not check for parents or positions. Useful for comparing species that may be in different polymer contexts.

monomer_insert(parent: OrderedPolymer, position: int, direction=None)[source]

Insert this monomer into a polymer at a specific position.

Sets the monomer’s parent, position, and direction attributes to reflect its insertion into the polymer. Marks the monomer (or its polymer component if it is a complex species) as a polymer component.

Parameters:
parentOrderedPolymer

The polymer to insert this monomer into.

positionint

The position index where this monomer is being inserted.

directionstr, int, or None, optional

The direction for this monomer. If None, uses the monomer’s existing direction.

Raises:
ValueError

If position is None, or if parent is None.

pretty_print(show_material=True, show_compartment=False, show_attributes=True, show_initial_condition=False, **kwargs)[source]

A more powerful printing function.

Useful for understanding CRNs but does not return string identifiers. show_material toggles whether species.material is printed. show_attributes toggles whether species.attributes is printed.

remove()[source]

Remove the species from its parent polymer.

Overrides OrderedMonomer.remove to also remove the direction attribute if present.

Returns:
Species

Returns self after removal for method chaining.

remove_attribute(attribute: str)[source]

Remove an attribute from the species.

Parameters:
attributestr

The attribute to remove. Must be an alphanumeric string.

Notes

If the attribute is not present or is None, no action is taken. All occurrences of the attribute are removed from the attributes list.

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

Replaces species with new_species in the entire Complex Species.

Acts recursively on nested ComplexSpecies.

set_dir(direction)[source]

Set the direction of the monomer and return self.

Convenience method for setting direction in a fluent interface style.

Parameters:
directionstr, int, or None

The direction to assign to this monomer.

Returns:
OrderedMonomer

Returns self for method chaining.

Examples

>>> monomer = bcp.OrderedMonomer().set_dir('forward')
>>> monomer.direction
'forward'
subhash()[source]

Compute hash contribution from monomer properties.

Computes a hash value based on the monomer’s position, direction, and name (if present), excluding the parent reference.

Returns:
int

Hash value based on monomer-specific properties.

Notes

This method is used by __hash__ to compute the monomer’s hash contribution. It excludes the parent to avoid circular dependencies in hash computation.

class biocrnpyler.core.species.OrderedPolymerSpecies(species, name=None, material_type='ordered_polymer', compartment=None, attributes=None, circular=False)[source]

Ordered polymer that can participate in chemical reactions.

A polymer composed of Species (which are also OrderedMonomers) that can act as a reactant or product in chemical reactions. The internal species represent multiple binding sites and/or functional regions.

Parameters:
specieslist of Species or list of [Species, direction]

List of species monomers to form the polymer. Each element can be a Species or a [Species, direction] pair.

namestr or None, optional

Custom name for the polymer. If None, auto-generated from constituent species.

material_typestr, default=’ordered_polymer’

Material type identifier for the polymer.

compartmentCompartment, str, or None, optional

Compartment containing the polymer.

attributeslist of str or None, optional

Attributes for the polymer species.

circularbool, default=False

If True, the polymer has circular topology (e.g., plasmid).

Attributes:
polymertuple of Species

Ordered tuple of species monomers in the polymer.

speciestuple of Species

Alias for polymer (inherited from OrderedPolymer).

circularbool

Flag indicating circular topology.

default_materialstr

Class attribute defining default material type.

See also

OrderedPolymer

Base class for ordered polymers.

OrderedComplexSpecies

Ordered complex base class.

PolymerConformation

Set of polymers with connections.

Notes

When used as a reaction input, either the entire OrderedPolymerSpecies or one of its internal Species (with Species.parent = OrderedPolymerSpecies) can be passed to mechanisms.

Species inside an OrderedPolymerSpecies model multiple binding sites and/or functional regions. ComplexSpecies can be formed at specific locations by passing the internal Species.

The circular attribute indicates circular topology but does not automatically enforce circular constraints in operations.

Examples

Create a linear polymer:

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> polymer = bcp.OrderedPolymerSpecies(
...     species=[S1, S2],
...     name='my_polymer'
... )
>>> len(polymer)
2

Create a circular polymer (plasmid):

>>> plasmid = bcp.OrderedPolymerSpecies(
...     species=[S1, S2],
...     circular=True
... )
>>> plasmid.circular
True
__contains__(item)[source]

Check if a species is contained in the complex.

Parameters:
itemSpecies

The species to search for.

Returns:
bool

True if the species is found in the complex or any nested complexes, False otherwise.

Raises:
ValueError

If item is not a Species instance.

Notes

This method searches recursively through nested ComplexSpecies to find the target species.

__eq__(other)[source]

Check if two species are equivalent.

Two species are equal if they have the same name, material_type, attributes (as sets), parent, compartment, and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species are equivalent, False otherwise.

Notes

Equality between parents and children can result in loops, so string equality is used for parent comparison.

__getitem__(ii)[source]

Get a monomer or slice of monomers from the polymer.

Parameters:
iiint or slice

Index or slice to retrieve from the polymer.

Returns:
OrderedMonomer or tuple

The monomer at the given index, or a tuple of monomers for a slice.

__gt__(Species2)[source]

Return self>value.

__hash__()[source]

Compute hash value for this monomer.

Returns:
int

Hash value based on position, direction, name (if present), and parent.

__len__()[source]

Return the number of monomers in the polymer.

Returns:
int

The number of monomers in the polymer sequence.

__lt__(Species2)[source]

Return self<value.

__setitem__(ii, val)[source]

Replace a monomer at a specific position.

Parameters:
iiint

Index at which to replace the monomer.

valOrderedMonomer

The new monomer to insert at the position.

Notes

Internally calls replace with the monomer’s existing direction.

add_attribute(attribute: str)[source]

Add an attribute to the species.

Parameters:
attributestr

The attribute to add. Must be an alphanumeric string and non-None.

Raises:
AssertionError

If attribute is not an alphanumeric string or is None.

Notes

Duplicate attributes are not added - each attribute appears only once in the attributes list.

Examples

>>> species = bcp.Species('MyProtein')
>>> species.add_attribute('degraded')
>>> species.attributes
['degraded']
append(part, direction=None)[source]

Add a monomer to the end of the polymer.

Appends a copy of the given monomer to the end of the polymer sequence by calling insert at the final position.

Parameters:
partOrderedMonomer

The monomer to append. A copy of this monomer will be added.

directionstr, int, or None, optional

Direction for the appended monomer. If None, uses the monomer’s existing direction if available.

See also

insert

Insert a monomer at a specific position.

Examples

>>> polymer = bcp.OrderedPolymer(parts=[])
>>> mon = bcp.OrderedMonomer()
>>> polymer.append(mon, direction='forward')
>>> len(polymer)
1
changed()[source]

Callback method invoked whenever the polymer structure changes.

This method is called after operations that modify the polymer, such as insert, replace, delpart, or reverse. Subclasses can override this to implement custom behavior when the polymer is modified.

Notes

The base implementation does nothing. Override in subclasses to add functionality like name regeneration, validation, or notifications.

contains_species_monomer(s)[source]

Check if the species contains a monomer, ignoring context.

Parameters:
sSpecies

The species monomer to search for.

Returns:
bool

True if the species contains a monomer equal to s (ignoring parent, position, and direction), False otherwise.

Notes

This is a less stringent version of __contains__ that checks without considering Species.parent, Species.position, or direction. Useful for determining if a species is present regardless of its polymer context.

delpart(position)[source]

Remove a monomer from the polymer at a specific position.

Removes the monomer at the given position, shifts all subsequent monomers to lower positions, and calls the changed callback.

Parameters:
positionint

Index of the monomer to remove. Must be a valid position in the polymer.

See also

replace

Replace a monomer at a specific position.

insert

Insert a monomer at a specific position.

Notes

The removed monomer’s remove method is called to clear its parent, position, and direction. If the polymer has a name attribute and a make_name method, the name is regenerated after deletion.

direction_invert(dirname)[source]

Invert a direction value.

Converts a direction to its opposite orientation. Used during polymer reversal operations.

Parameters:
dirnamestr, int, or None

The direction to invert. Supported values:

  • ‘forward’ <–> ‘reverse’

  • 0 <–> 1

  • None -> None

Returns:
str, int, or None

The inverted direction. Returns the input unchanged if it cannot be inverted.

Warns:
UserWarning

If the direction value is not recognized.

Examples

>>> polymer = bcp.OrderedPolymer(parts=[])
>>> polymer.direction_invert('forward')
'reverse'
>>> polymer.direction_invert(0)
1
find_polymer_component()[source]

Find the polymer component within this monomer or its species.

Searches this monomer and, if it is a ComplexSpecies, its constituent species to find which one is marked as a polymer component.

Returns:
OrderedMonomer or None

The monomer that is part of a polymer structure, or None if no polymer component is found.

Raises:
ValueError

If multiple species are marked as polymer components in the same location.

Notes

This method is primarily used internally to handle complex species that may contain monomers as part of larger structures.

static flatten_list(in_list) List[source]

Recursively flatten a nested list of species.

Parameters:
in_listlist or Species

A potentially nested list of species, or a single species.

Returns:
list

Flattened list containing all species. None elements are filtered out.

Examples

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> nested = [S1, [S2, None]]
>>> bcp.Species.flatten_list(nested)
[S1, S2]
classmethod from_polymer_species(ops, replace_dict, **kwargs)[source]

Create OrderedPolymerSpecies with specific monomers replaced.

Parameters:
opsOrderedPolymerSpecies

The original polymer species to modify.

replace_dictdict

Dictionary mapping monomer indices (int) to new Species to insert at those positions.

**kwargs

Additional keyword arguments for the new OrderedPolymerSpecies. Defaults are inherited from ops if not specified.

Returns:
OrderedPolymerSpecies

New polymer with specified monomers replaced.

Notes

If replace_dict is empty, returns a deep copy of ops.

Examples

Replace monomer at position 1:

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> S3 = bcp.Species('S3')
>>> polymer = bcp.OrderedPolymerSpecies([S1, S2])
>>> new_polymer = bcp.OrderedPolymerSpecies.from_polymer_species(
...     polymer, {1: S3}
... )
get_orphan()[source]

Create a copy of this monomer without a parent reference.

Returns a copy that retains position and direction but has no parent polymer. Useful for temporarily working with monomers outside their polymer context.

Returns:
OrderedMonomer

A copy of this monomer with parent set to None but position and direction preserved.

See also

get_removed

Create a fully detached copy.

remove

Remove this monomer from its parent in place.

Notes

This is a shallow copy of the monomer object itself, though the parent reference is explicitly cleared.

get_removed()[source]

Create a fully detached copy of this monomer.

Returns a copy with all polymer-related attributes (parent, position, direction) cleared. Also removes ‘forward’ and ‘reverse’ attributes if present.

Returns:
OrderedMonomer

A copy of this monomer with no parent, position, or direction, and with directional attributes removed.

See also

get_orphan

Create a copy without parent but with position and direction.

remove

Remove this monomer from its parent in place.

Notes

This method is useful for creating completely independent copies of monomers that can be reused in different contexts without any polymer associations.

get_species(recursive=False)[source]

Get all species in the complex.

Parameters:
recursivebool, default=False

If True, returns species inside nested ComplexSpecies recursively. If False, returns only this ComplexSpecies.

Returns:
list of Species

List of species. If recursive=False, returns [self]. If recursive=True, returns [self] plus all constituent species.

insert(position, part, direction=None)[source]

Insert a monomer at a specific position in the polymer.

Inserts a copy of the given monomer at the specified position, shifting all subsequent monomers to higher positions. Calls the changed callback after insertion.

Parameters:
positionint

Index at which to insert the monomer. Must be between 0 and len(polymer) (inclusive).

partOrderedMonomer

The monomer to insert. A copy of this monomer will be added.

directionstr, int, or None, optional

Direction for the inserted monomer. If None, uses the monomer’s existing direction.

See also

append

Add a monomer to the end of the polymer.

replace

Replace a monomer at a specific position.

Notes

The monomer is deep-copied before insertion to maintain independence from the original object.

monomer_count(m)[source]

Count occurrences of a monomer in the complex.

Parameters:
mSpecies

The monomer to count.

Returns:
int

Number of times the monomer appears in the complex, using monomer_eq for equality comparison.

Notes

This effectively implements self.species.count(m) but uses monomer_eq for equality, which ignores parent and position.

monomer_eq(other)[source]

Check if two monomers are equal, ignoring parent and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species have the same name, material_type, attributes, and compartment, regardless of parent or position.

Notes

This is the same as normal equality but does not check for parents or positions. Useful for comparing species that may be in different polymer contexts.

monomer_insert(parent: OrderedPolymer, position: int, direction=None)[source]

Insert this monomer into a polymer at a specific position.

Sets the monomer’s parent, position, and direction attributes to reflect its insertion into the polymer. Marks the monomer (or its polymer component if it is a complex species) as a polymer component.

Parameters:
parentOrderedPolymer

The polymer to insert this monomer into.

positionint

The position index where this monomer is being inserted.

directionstr, int, or None, optional

The direction for this monomer. If None, uses the monomer’s existing direction.

Raises:
ValueError

If position is None, or if parent is None.

pretty_print(show_material=True, show_compartment=False, show_attributes=True, show_initial_condition=False, **kwargs)[source]

A more powerful printing function.

Useful for understanding CRNs but does not return string identifiers. show_material toggles whether species.material is printed. show_attributes toggles whether species.attributes is printed.

remove()[source]

Remove the species from its parent polymer.

Overrides OrderedMonomer.remove to also remove the direction attribute if present.

Returns:
Species

Returns self after removal for method chaining.

remove_attribute(attribute: str)[source]

Remove an attribute from the species.

Parameters:
attributestr

The attribute to remove. Must be an alphanumeric string.

Notes

If the attribute is not present or is None, no action is taken. All occurrences of the attribute are removed from the attributes list.

replace(position, part, direction=None)[source]

Replace a monomer at a specific position in the polymer.

Removes the monomer at the given position and inserts a copy of the new monomer in its place. Calls the changed callback after replacement.

Parameters:
positionint

Index of the monomer to replace. Must be a valid position in the polymer.

partOrderedMonomer

The monomer to insert. A copy of this monomer will be added.

directionstr, int, or None, optional

Direction for the new monomer. If None, uses the monomer’s existing direction.

See also

insert

Insert a monomer at a specific position.

delpart

Remove a monomer from the polymer.

Notes

The removed monomer’s remove method is called to clear its parent, position, and direction attributes.

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

Replaces species with new_species in the entire Complex Species.

Acts recursively on nested ComplexSpecies.

reverse()[source]

Reverse the order and directions of all monomers in the polymer.

Reverses the polymer sequence and inverts the direction of each monomer. Updates all monomer positions to reflect their new locations. Calls the changed callback after reversal.

Notes

This operation modifies the polymer in place. All monomers have their directions inverted using direction_invert and their positions updated to match the reversed sequence.

Examples

>>> mon1 = bcp.OrderedMonomer()
>>> mon2 = bcp.OrderedMonomer()
>>> polymer = bcp.OrderedPolymer(
...     parts=[[mon1, 'forward'], [mon2, 'reverse']]
... )
>>> polymer.reverse()
>>> polymer[0].direction
'forward'
>>> polymer[1].direction
'reverse'
set_dir(direction)[source]

Set the direction of the monomer and return self.

Convenience method for setting direction in a fluent interface style.

Parameters:
directionstr, int, or None

The direction to assign to this monomer.

Returns:
OrderedMonomer

Returns self for method chaining.

Examples

>>> monomer = bcp.OrderedMonomer().set_dir('forward')
>>> monomer.direction
'forward'
subhash()[source]

Compute hash contribution from monomer properties.

Computes a hash value based on the monomer’s position, direction, and name (if present), excluding the parent reference.

Returns:
int

Hash value based on monomer-specific properties.

Notes

This method is used by __hash__ to compute the monomer’s hash contribution. It excludes the parent to avoid circular dependencies in hash computation.

class biocrnpyler.core.species.PolymerConformation(complexes=None, polymer=None, material_type='conformation', name=None, **kwargs)[source]

Set of polymers and their connections via ComplexSpecies.

Represents a conformation of one or more PolymerSpecies connected by ComplexSpecies containing monomers from the polymers. This class provides unique naming for conformations and serves as a data structure for polymer hypergraphs.

Parameters:
complexeslist of ComplexSpecies, optional

List of ComplexSpecies connecting monomers from OrderedPolymerSpecies. Must contain monomers from the polymers.

polymerOrderedPolymerSpecies or list of Species, optional

Single polymer or list of species to form a polymer. Exactly one of complexes or polymer must be provided.

material_typestr, default=’conformation’

Material type identifier.

namestr or None, optional

Custom name for the conformation. If None, auto-generated.

**kwargs

Additional keyword arguments passed to Species constructor.

Attributes:
polymerslist of OrderedPolymerSpecies

List of polymers in this conformation.

complexeslist of ComplexSpecies

List of complexes connecting monomers in the polymers.

namestr

Auto-generated name encoding polymer and complex structure.

See also

OrderedPolymerSpecies

Polymer species for chemical reactions.

ComplexSpecies

Complex of multiple bound species.

Complex

Metaclass for creating complexes.

Notes

Auto-generated names follow the format: conformation__[Polymer1]_[Polymer2]_[indices]_[Complex1]_[Complex2]__

where indices encode which polymers each complex binds to and the list of PolymerSpecies and ComplexSpecies are in alphabetical order.

A PolymerConformation represents a hypergraph where:

  • Monomers are vertices

  • ComplexSpecies are hyperedges connecting arbitrary numbers of vertices

  • Multiple edges between the same vertices are allowed

Users typically do not create PolymerConformations directly. The Complex function automatically creates them when complexing monomers from OrderedPolymerSpecies.

Examples

Create from a single polymer:

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> polymer = bcp.OrderedPolymerSpecies([S1, S2])
>>> conformation = bcp.PolymerConformation(polymer=polymer)
__eq__(other)[source]

Check if two species are equivalent.

Two species are equal if they have the same name, material_type, attributes (as sets), parent, compartment, and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species are equivalent, False otherwise.

Notes

Equality between parents and children can result in loops, so string equality is used for parent comparison.

__gt__(Species2)[source]

Return self>value.

__hash__()[source]

Compute hash value for this monomer.

Returns:
int

Hash value based on position, direction, name (if present), and parent.

__lt__(Species2)[source]

Return self<value.

add_attribute(attribute: str)[source]

Add an attribute to the species.

Parameters:
attributestr

The attribute to add. Must be an alphanumeric string and non-None.

Raises:
AssertionError

If attribute is not an alphanumeric string or is None.

Notes

Duplicate attributes are not added - each attribute appears only once in the attributes list.

Examples

>>> species = bcp.Species('MyProtein')
>>> species.add_attribute('degraded')
>>> species.attributes
['degraded']
contains_species_monomer(s)[source]

Check if the species contains a monomer, ignoring context.

Parameters:
sSpecies

The species monomer to search for.

Returns:
bool

True if the species contains a monomer equal to s (ignoring parent, position, and direction), False otherwise.

Notes

This is a less stringent version of __contains__ that checks without considering Species.parent, Species.position, or direction. Useful for determining if a species is present regardless of its polymer context.

copy_remove_complexes(complexes)[source]

Returns a new PolymerConformation without these complexes.

find_polymer_component()[source]

Find the polymer component within this monomer or its species.

Searches this monomer and, if it is a ComplexSpecies, its constituent species to find which one is marked as a polymer component.

Returns:
OrderedMonomer or None

The monomer that is part of a polymer structure, or None if no polymer component is found.

Raises:
ValueError

If multiple species are marked as polymer components in the same location.

Notes

This method is primarily used internally to handle complex species that may contain monomers as part of larger structures.

static flatten_list(in_list) List[source]

Recursively flatten a nested list of species.

Parameters:
in_listlist or Species

A potentially nested list of species, or a single species.

Returns:
list

Flattened list containing all species. None elements are filtered out.

Examples

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> nested = [S1, [S2, None]]
>>> bcp.Species.flatten_list(nested)
[S1, S2]
classmethod from_polymer_conformation(pcs, complexes=None, complexes_to_remove=None, **kwargs)[source]

Create PolymerConformation from existing conformations.

Produces a new PolymerConformation by merging complexes from previous PolymerConformations and adding new complexes.

Parameters:
pcslist of PolymerConformation

List of existing PolymerConformations to merge.

complexeslist of ComplexSpecies, optional

Additional complexes to add to the conformation. Default is an empty list.

complexes_to_removelist of ComplexSpecies, optional

Complexes to exclude from the merged conformation. Default is an empty list.

**kwargs

Additional keyword arguments for the new PolymerConformation.

Returns:
PolymerConformation

New conformation merging all input conformations and complexes.

Raises:
TypeError

If pcs is not a list of PolymerConformations.

classmethod from_polymer_replacement(pc, old_polymers, new_polymers, **kwargs)[source]

Create PolymerConformation by replacing polymers.

Produces a PolymerConformation from an existing one by replacing specified polymers with new ones, updating all complexes accordingly.

Parameters:
pcPolymerConformation

The conformation to modify.

old_polymerslist of OrderedPolymerSpecies

Polymers to replace. Must be the same instances (not just equal) as those in pc.polymers.

new_polymerslist of OrderedPolymerSpecies

New polymers to use as replacements. Must be the same length as old_polymers.

**kwargs

Additional keyword arguments for the new PolymerConformation. Defaults are inherited from pc if not specified.

Returns:
PolymerConformation

New conformation with polymers replaced.

Raises:
TypeError

If arguments are not the correct types.

ValueError

If old_polymers are not instances in pc.polymers, or if lists have different lengths.

Notes

This method updates all complexes to reference monomers from the new polymers at the same positions as in the old polymers.

get_orphan()[source]

Create a copy of this monomer without a parent reference.

Returns a copy that retains position and direction but has no parent polymer. Useful for temporarily working with monomers outside their polymer context.

Returns:
OrderedMonomer

A copy of this monomer with parent set to None but position and direction preserved.

See also

get_removed

Create a fully detached copy.

remove

Remove this monomer from its parent in place.

Notes

This is a shallow copy of the monomer object itself, though the parent reference is explicitly cleared.

get_removed()[source]

Create a fully detached copy of this monomer.

Returns a copy with all polymer-related attributes (parent, position, direction) cleared. Also removes ‘forward’ and ‘reverse’ attributes if present.

Returns:
OrderedMonomer

A copy of this monomer with no parent, position, or direction, and with directional attributes removed.

See also

get_orphan

Create a copy without parent but with position and direction.

remove

Remove this monomer from its parent in place.

Notes

This method is useful for creating completely independent copies of monomers that can be reused in different contexts without any polymer associations.

get_species(recursive=None)[source]

Get a list containing this species.

Returns:
list of Species

A list containing only this species: [self].

Notes

This method is used in recursive calls where ComplexSpecies returns a list of constituent species while Species returns just itself in a list. The recursive parameter is accepted for compatibility but not used in the base Species class.

monomer_eq(other)[source]

Check if two monomers are equal, ignoring parent and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species have the same name, material_type, attributes, and compartment, regardless of parent or position.

Notes

This is the same as normal equality but does not check for parents or positions. Useful for comparing species that may be in different polymer contexts.

monomer_insert(parent: OrderedPolymer, position: int, direction=None)[source]

Insert this monomer into a polymer at a specific position.

Sets the monomer’s parent, position, and direction attributes to reflect its insertion into the polymer. Marks the monomer (or its polymer component if it is a complex species) as a polymer component.

Parameters:
parentOrderedPolymer

The polymer to insert this monomer into.

positionint

The position index where this monomer is being inserted.

directionstr, int, or None, optional

The direction for this monomer. If None, uses the monomer’s existing direction.

Raises:
ValueError

If position is None, or if parent is None.

pretty_print(show_material=True, show_compartment=False, show_attributes=True, show_initial_condition=False, **kwargs)[source]

Generate a human-readable string representation of the species.

Parameters:
show_materialbool, default=True

If True, includes material_type in brackets around the species.

show_compartmentbool, default=False

If True, shows the compartment name in the representation.

show_attributesbool, default=True

If True, includes attributes in parentheses after the name.

show_initial_conditionbool, default=False

Placeholder for compatibility with CRN printing.

**kwargs

Additional keyword arguments (currently unused).

Returns:
str

Formatted string representation of the species.

Notes

This method provides more detailed output than __repr__, useful for understanding CRNs but does not return string identifiers compatible with parsers.

Format: material_type[name(attr1, attr2)-direction]

Examples

>>> S = bcp.Species('S', material_type='protein',
...                 attributes=['active'])
>>> S.pretty_print()
'protein[S(active)]'
remove()[source]

Remove the species from its parent polymer.

Overrides OrderedMonomer.remove to also remove the direction attribute if present.

Returns:
Species

Returns self after removal for method chaining.

remove_attribute(attribute: str)[source]

Remove an attribute from the species.

Parameters:
attributestr

The attribute to remove. Must be an alphanumeric string.

Notes

If the attribute is not present or is None, no action is taken. All occurrences of the attribute are removed from the attributes list.

replace_species(species, new_species)[source]

Replace a species with another species.

For a simple Species, returns new_species if this species equals species, otherwise returns self. For complex species, acts recursively.

Parameters:
speciesSpecies

The species to search for and replace.

new_speciesSpecies

The species to replace with.

Returns:
Species

Either new_species (if self == species) or self.

Raises:
ValueError

If either argument is not a Species instance.

set_dir(direction)[source]

Set the direction of the monomer and return self.

Convenience method for setting direction in a fluent interface style.

Parameters:
directionstr, int, or None

The direction to assign to this monomer.

Returns:
OrderedMonomer

Returns self for method chaining.

Examples

>>> monomer = bcp.OrderedMonomer().set_dir('forward')
>>> monomer.direction
'forward'
subhash()[source]

Compute hash contribution from monomer properties.

Computes a hash value based on the monomer’s position, direction, and name (if present), excluding the parent reference.

Returns:
int

Hash value based on monomer-specific properties.

Notes

This method is used by __hash__ to compute the monomer’s hash contribution. It excludes the parent to avoid circular dependencies in hash computation.

class biocrnpyler.core.species.Species(name: str, material_type='', attributes: List | None = None, compartment=None, **kwargs)[source]

A formal species object for a chemical reaction network (CRN).

Represents a chemical species in a CRN with a name, material type, attributes, and compartment. Species inherits from OrderedMonomer, allowing it to be part of polymer structures while also functioning as an independent chemical entity in reactions.

Parameters:
namestr

Name of the species. Must consist of letters, numbers, or underscores, cannot contain double underscores, and cannot begin/end with special characters.

material_typestr, default=’’

Type of material (e.g., ‘dna’, ‘rna’, ‘protein’, ‘complex’). Required if name starts with a number. Must start with a letter.

attributeslist of str or None, optional

List of attribute tags for the species (e.g., ‘degraded’, ‘phosphorylated’). Each attribute must be alphanumeric.

compartmentCompartment, str, or None, optional

The compartment containing this species. If None, uses default compartment. If str, creates a new Compartment with that name.

**kwargs

Additional keyword arguments passed to OrderedMonomer.

Attributes:
namestr

The name of the species.

material_typestr

The material type of the species.

attributeslist of str

List of attribute tags associated with the species.

compartmentCompartment

The compartment containing this species.

directionstr, int, or None

Directional orientation (inherited from OrderedMonomer). When set, the direction is also added as an attribute.

See also

ComplexSpecies

Species formed from multiple bound species.

OrderedPolymerSpecies

Polymer species for chemical reactions.

WeightedSpecies

Species with stoichiometry coefficient.

Notes

Species names must:

  • Contain only letters, numbers, and underscores

  • Not contain double underscores (‘__’)

  • Not end with an underscore

  • Start with a letter or number (if starting with number, requires material_type)

Species are represented as strings in the format:

material_type_name_attribute1_attribute2_compartment

Components are omitted if empty or default values.

Two species are equal if they have the same name, material_type, attributes, compartment, parent, and position.

Examples

Create a simple species:

>>> S = bcp.Species('S')
>>> S.name
'S'

Create a protein with attributes:

>>> GFP = bcp.Species(
...     name='GFP',
...     material_type='protein',
...     attributes=['fluorescent', 'degraded']
... )
>>> repr(GFP)
'protein_GFP_fluorescent_degraded'

Create a species in a compartment:

>>> cytoplasm = bcp.Compartment('cytoplasm')
>>> enzyme = bcp.Species(
...     name='enzyme',
...     material_type='protein',
...     compartment=cytoplasm
... )
__eq__(other)[source]

Check if two species are equivalent.

Two species are equal if they have the same name, material_type, attributes (as sets), parent, compartment, and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species are equivalent, False otherwise.

Notes

Equality between parents and children can result in loops, so string equality is used for parent comparison.

__gt__(Species2)[source]

Return self>value.

__hash__()[source]

Compute hash value for this monomer.

Returns:
int

Hash value based on position, direction, name (if present), and parent.

__lt__(Species2)[source]

Return self<value.

add_attribute(attribute: str)[source]

Add an attribute to the species.

Parameters:
attributestr

The attribute to add. Must be an alphanumeric string and non-None.

Raises:
AssertionError

If attribute is not an alphanumeric string or is None.

Notes

Duplicate attributes are not added - each attribute appears only once in the attributes list.

Examples

>>> species = bcp.Species('MyProtein')
>>> species.add_attribute('degraded')
>>> species.attributes
['degraded']
contains_species_monomer(s)[source]

Check if the species contains a monomer, ignoring context.

Parameters:
sSpecies

The species monomer to search for.

Returns:
bool

True if the species contains a monomer equal to s (ignoring parent, position, and direction), False otherwise.

Notes

This is a less stringent version of __contains__ that checks without considering Species.parent, Species.position, or direction. Useful for determining if a species is present regardless of its polymer context.

find_polymer_component()[source]

Find the polymer component within this monomer or its species.

Searches this monomer and, if it is a ComplexSpecies, its constituent species to find which one is marked as a polymer component.

Returns:
OrderedMonomer or None

The monomer that is part of a polymer structure, or None if no polymer component is found.

Raises:
ValueError

If multiple species are marked as polymer components in the same location.

Notes

This method is primarily used internally to handle complex species that may contain monomers as part of larger structures.

static flatten_list(in_list) List[source]

Recursively flatten a nested list of species.

Parameters:
in_listlist or Species

A potentially nested list of species, or a single species.

Returns:
list

Flattened list containing all species. None elements are filtered out.

Examples

>>> S1 = bcp.Species('S1')
>>> S2 = bcp.Species('S2')
>>> nested = [S1, [S2, None]]
>>> bcp.Species.flatten_list(nested)
[S1, S2]
get_orphan()[source]

Create a copy of this monomer without a parent reference.

Returns a copy that retains position and direction but has no parent polymer. Useful for temporarily working with monomers outside their polymer context.

Returns:
OrderedMonomer

A copy of this monomer with parent set to None but position and direction preserved.

See also

get_removed

Create a fully detached copy.

remove

Remove this monomer from its parent in place.

Notes

This is a shallow copy of the monomer object itself, though the parent reference is explicitly cleared.

get_removed()[source]

Create a fully detached copy of this monomer.

Returns a copy with all polymer-related attributes (parent, position, direction) cleared. Also removes ‘forward’ and ‘reverse’ attributes if present.

Returns:
OrderedMonomer

A copy of this monomer with no parent, position, or direction, and with directional attributes removed.

See also

get_orphan

Create a copy without parent but with position and direction.

remove

Remove this monomer from its parent in place.

Notes

This method is useful for creating completely independent copies of monomers that can be reused in different contexts without any polymer associations.

get_species(recursive=None)[source]

Get a list containing this species.

Returns:
list of Species

A list containing only this species: [self].

Notes

This method is used in recursive calls where ComplexSpecies returns a list of constituent species while Species returns just itself in a list. The recursive parameter is accepted for compatibility but not used in the base Species class.

monomer_eq(other)[source]

Check if two monomers are equal, ignoring parent and position.

Parameters:
otherSpecies

The species to compare with.

Returns:
bool

True if species have the same name, material_type, attributes, and compartment, regardless of parent or position.

Notes

This is the same as normal equality but does not check for parents or positions. Useful for comparing species that may be in different polymer contexts.

monomer_insert(parent: OrderedPolymer, position: int, direction=None)[source]

Insert this monomer into a polymer at a specific position.

Sets the monomer’s parent, position, and direction attributes to reflect its insertion into the polymer. Marks the monomer (or its polymer component if it is a complex species) as a polymer component.

Parameters:
parentOrderedPolymer

The polymer to insert this monomer into.

positionint

The position index where this monomer is being inserted.

directionstr, int, or None, optional

The direction for this monomer. If None, uses the monomer’s existing direction.

Raises:
ValueError

If position is None, or if parent is None.

pretty_print(show_material=True, show_compartment=False, show_attributes=True, show_initial_condition=False, **kwargs)[source]

Generate a human-readable string representation of the species.

Parameters:
show_materialbool, default=True

If True, includes material_type in brackets around the species.

show_compartmentbool, default=False

If True, shows the compartment name in the representation.

show_attributesbool, default=True

If True, includes attributes in parentheses after the name.

show_initial_conditionbool, default=False

Placeholder for compatibility with CRN printing.

**kwargs

Additional keyword arguments (currently unused).

Returns:
str

Formatted string representation of the species.

Notes

This method provides more detailed output than __repr__, useful for understanding CRNs but does not return string identifiers compatible with parsers.

Format: material_type[name(attr1, attr2)-direction]

Examples

>>> S = bcp.Species('S', material_type='protein',
...                 attributes=['active'])
>>> S.pretty_print()
'protein[S(active)]'
remove()[source]

Remove the species from its parent polymer.

Overrides OrderedMonomer.remove to also remove the direction attribute if present.

Returns:
Species

Returns self after removal for method chaining.

remove_attribute(attribute: str)[source]

Remove an attribute from the species.

Parameters:
attributestr

The attribute to remove. Must be an alphanumeric string.

Notes

If the attribute is not present or is None, no action is taken. All occurrences of the attribute are removed from the attributes list.

replace_species(species, new_species)[source]

Replace a species with another species.

For a simple Species, returns new_species if this species equals species, otherwise returns self. For complex species, acts recursively.

Parameters:
speciesSpecies

The species to search for and replace.

new_speciesSpecies

The species to replace with.

Returns:
Species

Either new_species (if self == species) or self.

Raises:
ValueError

If either argument is not a Species instance.

set_dir(direction)[source]

Set the direction of the monomer and return self.

Convenience method for setting direction in a fluent interface style.

Parameters:
directionstr, int, or None

The direction to assign to this monomer.

Returns:
OrderedMonomer

Returns self for method chaining.

Examples

>>> monomer = bcp.OrderedMonomer().set_dir('forward')
>>> monomer.direction
'forward'
subhash()[source]

Compute hash contribution from monomer properties.

Computes a hash value based on the monomer’s position, direction, and name (if present), excluding the parent reference.

Returns:
int

Hash value based on monomer-specific properties.

Notes

This method is used by __hash__ to compute the monomer’s hash contribution. It excludes the parent to avoid circular dependencies in hash computation.

class biocrnpyler.core.species.WeightedSpecies(species: Species, stoichiometry: int = 1)[source]

Container for a species with stoichiometric coefficient.

Wraps a Species object together with its stoichiometry for use in reactions. This class is primarily used internally by the Reaction class to represent reactants and products with their coefficients.

Parameters:
speciesSpecies

The species object.

stoichiometryint, default=1

The stoichiometric coefficient. Must be a positive integer.

Attributes:
speciesSpecies

The wrapped species object.

stoichiometryint

The stoichiometric coefficient (positive integer).

See also

Species

Base class for chemical species.

Reaction

Chemical reaction containing weighted species.

Examples

Create a weighted species:

>>> S = bcp.Species('S')
>>> ws = bcp.WeightedSpecies(species=S, stoichiometry=2)
>>> ws.stoichiometry
2
__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).