biocrnpyler.core.parameter

Parameter processing module.

Parameter Value Defaulting

Not all parameters need to have the required headings. The only two required columns are ‘param_val’ and ‘param_name’. BioCRNpyler uses a form of parameter name defaulting discussed below to find default parameters if no exact match is in the config file. This makes it easy to set default parameters for things like ‘ku’ and ‘ktx’ to quickly build models.

Parameters inside BioCRNpyler

Inside of bioCRNpyler, parameters are stored as a dictionary key value pair: (mechanism_name, part_id, param_name) --> param_val. If that particular parameter key cannot be found, the software will default to the following keys: (mechanism_type, part_id, param_name) >> (part_id, param_name) >> (mechanism_name, param_name) >> (mechanism_type, param_name) >> (param_name) and give a warning. As a note, mechanism_name refers to the name variable of a Mechanism, and mechanism_type refers to the type variable of a Mechanism. Either of these can be used as a mechanism_id. This allows for models to be constructed easily using default parameter values and for parameters to be shared between different mechanisms and/or components.

Units are read directly read from the column labeled “units” in the parameter file.

Initial Conditions are also Parameters

The initial condition of any Species (or Component) will also be looked up as a parameters automatically. Initial conditions can be customized in through the custom_initial_conditions keyword in the Mixture constructor. The custom_initial_conditions keyword will take precedent over parameter initial conditions.

Module Attributes

ParameterKey(mechanism, part_id, name)

Named tuple defining a parameter key.

Classes

ModelParameter(parameter_name, ...[, unit, ...])

Parameter with search and found keys for defaulting behavior.

Parameter(parameter_name, parameter_value[, ...])

Base class for representing parameters in BioCRNpyler.

ParameterDatabase([parameter_dictionary, ...])

Database for storing and retrieving parameters with defaulting.

ParameterEntry(parameter_name, parameter_value)

Parameter with database lookup key and metadata.

ParameterKey(mechanism, part_id, name)

Named tuple defining a parameter key.

class biocrnpyler.core.parameter.ModelParameter(parameter_name: str, parameter_value: str | Real, search_key, found_key, unit=None, parameter_key=None, parameter_info=None, **kwargs)[source]

Parameter with search and found keys for defaulting behavior.

A ModelParameter extends ParameterEntry with information about how the parameter was looked up in the database. It tracks both the original search key and the actual key where the parameter was found, enabling parameter defaulting and debugging.

Parameters:
parameter_namestr

Name of the parameter.

parameter_valuefloat or str

Value of the parameter.

search_keydict, ParameterKey, tuple, or str

The key originally searched for in the database. Usually includes mechanism, part_id, and name.

found_keydict, ParameterKey, tuple, or str

The key where the parameter was actually found after defaulting. May have fewer fields than search_key.

unitstr, optional

Unit of the parameter.

parameter_keydict, ParameterKey, str, or None, optional

Database lookup key (inherited from ParameterEntry).

parameter_infodict, optional

Additional metadata (inherited from ParameterEntry).

**kwargs

Additional keyword arguments passed to ParameterEntry constructor.

Attributes:
search_keyParameterKey

ParameterKey: The key originally searched for in database.

found_keyParameterKey

ParameterKey: The key where parameter was actually found.

See also

Parameter

Base parameter class.

ParameterEntry

Parameter with database key.

ParameterDatabase

Database with parameter defaulting.

Notes

The parameter defaulting hierarchy is:

  1. (mechanism_name, part_id, param_name)

  2. (mechanism_type, part_id, param_name)

  3. (None, part_id, param_name)

  4. (mechanism_name, None, param_name)

  5. (mechanism_type, None, param_name)

  6. (None, None, param_name)

The search_key shows what was requested, while found_key shows which level of defaulting was used. This information is useful for debugging parameter lookups.

Examples

Create a model parameter showing search and found keys:

>>> model_param = bcp.ModelParameter(
...     'kb',
...     100.0,
...     search_key={'mechanism': 'binding', 'part_id': 'prom1'},
...     found_key={'mechanism': 'binding', 'part_id': None},
...     unit='1/s'
... )
>>> # Shows parameter was found using mechanism-level default
__eq__(other)[source]

Test equality between parameters or parameter and number.

Parameters:
otherParameter or float

Object to compare with. Can be another Parameter object or a numerical value.

Returns:
bool

True if values are equal, False otherwise.

Raises:
TypeError

If other cannot be compared (not a Parameter or number).

__hash__()[source]

Return hash value for the parameter.

Returns:
int

Hash value based on parameter name, value, and unit.

static create_parameter_key(new_key: Dict | ParameterKey | str, parameter_name=None) ParameterKey[source]

Convert various input types to a ParameterKey namedtuple.

Parameters:
new_keydict, ParameterKey, tuple, str, or None

Input to convert to ParameterKey:

  • dict: Must have keys matching ParameterKey fields

  • ParameterKey: Returned as-is

  • 3-tuple: Converted to ParameterKey with proper field mapping

  • str: Used as ‘name’, other fields set to None

  • None: All fields set to None (requires parameter_name)

parameter_namestr, optional

Parameter name to use if not specified in new_key. Overrides name field if provided in dict.

Returns:
ParameterKey

Named tuple with fields (mechanism, part_id, name).

Raises:
ValueError

If new_key is not a valid type or format.

Examples

>>> key = bcp.ParameterEntry.create_parameter_key('kb')
>>> key
ParameterKey(mechanism=None, part_id=None, name='kb')
>>> key = bcp.ParameterEntry.create_parameter_key(
...     {'mechanism': 'transcription', 'part_id': 'prom1'},
...     parameter_name='ktx'
... )
>>> key
ParameterKey(mechanism='transcription', part_id='prom1', name='ktx')
property found_key

ParameterKey: The key where parameter was actually found.

get_sbml_id()[source]

Generate SBML-compatible identifier for the parameter.

Constructs an identifier string from the parameter key fields, formatted as: ‘<name>_<part_id>_<mechanism>’.

Returns:
str

SBML-compatible identifier string.

property parameter_info: Dict

dict: Additional metadata about the parameter.

property parameter_key: ParameterKey

ParameterKey: The database lookup key for this parameter.

property parameter_name: str

str: The name of the parameter.

property search_key

ParameterKey: The key originally searched for in database.

property unit: str

str: The unit string for the parameter.

property value: Real

float: The numerical value of the parameter.

class biocrnpyler.core.parameter.Parameter(parameter_name: str, parameter_value: str | Real, unit=None)[source]

Base class for representing parameters in BioCRNpyler.

Parameters represent kinetic constants, initial concentrations, and other numerical values used in chemical reaction networks. This class provides validation for parameter names, values, and units.

Parameters:
parameter_namestr

Name of the parameter. Must start with a letter and contain at least one character.

parameter_valuefloat or str

Value of the parameter. Can be a number or a string in formats: ‘1.00’, ‘1e4’, or ‘2/5’ (rational). Strings are automatically converted to numerical values.

unitstr, optional

Unit of the parameter (e.g., ‘1/s’, ‘nM’, ‘molecules’). If None, defaults to empty string.

Attributes:
parameter_namestr

str: The name of the parameter.

valuefloat

float: The numerical value of the parameter.

unitstr

str: The unit string for the parameter.

See also

ParameterEntry

Parameter with database lookup keys.

ModelParameter

Parameter with search and found keys for defaulting.

ParameterDatabase

Database for storing and retrieving parameters.

Notes

This is the base class for all parameter types in BioCRNpyler. In practice, subclasses ParameterEntry and ModelParameter are more commonly used as they support the parameter lookup and defaulting system.

Parameter values provided as strings are automatically converted:

  • ‘1e4’ –> 10000.0

  • ‘2/5’ –> 0.4

  • ‘1.23’ –> 1.23

Examples

Create a basic parameter:

>>> param = bcp.Parameter('kb', 100.0, unit='1/s')
>>> param.parameter_name
'kb'
>>> param.value
100.0

Create a parameter from a string value:

>>> param = bcp.Parameter('ku', '1e-4', unit='1/s')
>>> param.value
0.0001

Create a parameter from a rational string:

>>> param = bcp.Parameter('ratio', '3/4')
>>> param.value
0.75
__eq__(other)[source]

Test equality between parameters or parameter and number.

Parameters:
otherParameter or float

Object to compare with. Can be another Parameter object or a numerical value.

Returns:
bool

True if values are equal, False otherwise.

Raises:
TypeError

If other cannot be compared (not a Parameter or number).

__hash__()[source]

Return hash value for the parameter.

Returns:
int

Hash value based on parameter name, value, and unit.

property parameter_name: str

str: The name of the parameter.

property unit: str

str: The unit string for the parameter.

property value: Real

float: The numerical value of the parameter.

class biocrnpyler.core.parameter.ParameterDatabase(parameter_dictionary=None, parameter_file=None, overwrite_parameters=False)[source]

Database for storing and retrieving parameters with defaulting.

A ParameterDatabase stores parameters with flexible lookup keys that enable parameter defaulting based on mechanism, part_id, and parameter name. Parameters can be loaded from dictionaries, files, or other databases.

Parameters:
parameter_dictionarydict, optional

Dictionary of parameters to load. Keys should be ParameterKey-like (dict, tuple, or str) and values should be numerical or Parameter objects.

parameter_filestr or list of str, optional

Path(s) to parameter file(s) to load. Files must be tab-separated (.tsv, .txt) or comma-separated (.csv).

overwrite_parametersbool, default=False

If True, allows overwriting existing parameters when loading. If False, raises ValueError if duplicate keys are encountered.

Attributes:
parametersdict

Internal dictionary mapping ParameterKey to ParameterEntry objects. Access via indexing or iteration rather than directly.

See also

Parameter

Base parameter class.

ParameterEntry

Parameter with database key.

ModelParameter

Parameter with search and found keys.

Notes

When searching for a parameter with find_parameter(mechanism, part_id, param_name), the database searches in this order:

  1. (mechanism.name, part_id, param_name)

  2. (mechanism.type, part_id, param_name)

  3. (None, part_id, param_name)

  4. (mechanism.name, None, param_name)

  5. (mechanism.type, None, param_name)

  6. (None, None, param_name)

This enables flexible parameter specification where specific parameters override more general ones.

Parameter files should have these columns (column names are flexible):

  • ‘param_name’ or ‘parameter_name’ (required)

  • ‘param_val’ or ‘value’ (required)

  • ‘mechanism_id’ or ‘mechanism’ (optional)

  • ‘part_id’ or ‘part’ (optional)

  • ‘units’ or ‘unit’ (optional)

Additional columns are stored in parameter_info.

Parameter files are searched for in the following directories:

  1. The current directory

  2. All directories listed in the ‘BCP_PATH’ environment variable

  3. The BioCRNpyler source code directory

The directories are search in this order and the first parameter file that is found is returned. For files in the BioCRNpyler source code directory, common filename patterns are of the form ‘<type>/<name>_parameters.tsv’ where <type> is ‘components’, ‘mechanisms’, or ‘mixtures’.

Examples

Create a parameter database from a dictionary:

>>> params = {
...     'kb': 100.0,
...     'ku': 0.01,
...     ('transcription', None, 'ktx'): 0.05
... }
>>> db = bcp.ParameterDatabase(parameter_dictionary=params)

Load parameters from a file:

>>> db = bcp.ParameterDatabase(
...     parameter_file='mixtures/pure_parameters.tsv')

Look up a parameter with defaulting:

>>> param = db.find_parameter('transcription', 'promoter1', 'ktx')
>>> param.value
0.05

Add a new parameter:

>>> db.add_parameter('kcat', 10.0,
...     parameter_key={'mechanism': 'catalysis', 'part_id': 'enzyme1'})
__contains__(val)[source]

Check if a key or ParameterEntry is in the database.

Parameters:
valParameterEntry, dict, ParameterKey, tuple, or str

Value to check. Can be a ParameterEntry object or any valid parameter key format.

Returns:
bool

True if the key exists in the database (and ParameterEntry values match if val is a ParameterEntry), False otherwise.

__getitem__(key)[source]

Get a parameter by exact key match.

Parameters:
keydict, ParameterKey, tuple, or str

Parameter key to look up. No defaulting is performed.

Returns:
ParameterEntry

The parameter entry with the exact matching key.

Raises:
KeyError

If the exact key is not found in the database.

__iter__()[source]

Initialize iterator over parameter entries.

Returns:
ParameterDatabase

Self with iterator state initialized.

__len__()[source]

Return number of parameters in the database.

Returns:
int

Number of parameter entries stored.

__next__()[source]

Get next parameter entry in iteration.

Returns:
ParameterEntry

Next parameter entry in the database.

Raises:
StopIteration

When all parameters have been iterated.

__setitem__(parameter_key, value)[source]

Set a parameter value by key.

Parameters:
parameter_keydict, ParameterKey, tuple, or str

Key for the parameter.

valuefloat, str, or ParameterEntry

New value or ParameterEntry object. If ParameterEntry, its key must match parameter_key.

Raises:
ValueError

If value is ParameterEntry with mismatched key.

Notes

This method automatically overwrites existing parameters. For more control, use add_parameter instead.

add_parameter(parameter_name: str, parameter_value: str | Real, parameter_origin=None, parameter_key=None, parameter_info=None, overwrite_parameters=False)[source]

Add a parameter to the database.

Parameters:
parameter_namestr

Name of the parameter.

parameter_valuefloat or str

Value of the parameter. Strings are converted to float.

parameter_originstr, optional

Description of where the parameter came from (e.g., filename). Stored in parameter_info.

parameter_keydict, ParameterKey, str, or None, optional

Lookup key for the parameter. If None, creates key with only the parameter name.

parameter_infodict, optional

Additional metadata about the parameter. parameter_origin is added to this dict if provided.

overwrite_parametersbool, default=False

If True, allows overwriting existing parameters. If False, raises ValueError if key already exists.

Raises:
ValueError

If key already exists in database and overwrite_parameters=False.

Examples

>>> db = bcp.ParameterDatabase()
>>> db.add_parameter('kb', 100.0)
>>> db.add_parameter('ku', 0.01,
...     parameter_key={'mechanism': 'binding'})
find_parameter(mechanism, part_id, param_name)[source]

Search for a parameter with automatic defaulting.

Searches the database for the best matching parameter using a hierarchical defaulting system. If an exact match is not found, progressively more general keys are tried.

Parameters:
mechanismstr, Mechanism, or None

Mechanism identifier. Can be a string (used as both name and type), a Mechanism object (uses .name and .mechanism_type), or None.

part_idstr or None

Part/component identifier for the parameter.

param_namestr

Name of the parameter to find.

Returns:
ModelParameter or None

ModelParameter object with search_key and found_key attributes showing how the parameter was found. Returns None if no match found at any defaulting level.

Raises:
ValueError

If mechanism is not a string, Mechanism object, or None.

Notes

The method searches for parameters in this order:

  1. (mechanism.name, part_id, param_name)

  2. (mechanism.type, part_id, param_name)

  3. (None, part_id, param_name)

  4. (mechanism.name, None, param_name)

  5. (mechanism.type, None, param_name)

  6. (None, None, param_name)

This allows setting default parameters at various levels of specificity. For example, a general ‘kb’ parameter can be overridden for specific mechanisms or parts.

Examples

>>> db = bcp.ParameterDatabase()
>>> db.add_parameter('kb', 100.0)
>>> db.add_parameter('kb', 200.0,
...     parameter_key={'mechanism': 'binding'})

General lookup finds the general parameter

>>> param = db.find_parameter(None, None, 'kb')
>>> param.value
100.0

Mechanism-specific lookup finds the specific parameter

>>> param = db.find_parameter('binding', None, 'kb')
>>> param.value
200.0
load_parameters_from_database(parameter_database, overwrite_parameters=False) None[source]

Load parameters from another ParameterDatabase.

Parameters:
parameter_databaseParameterDatabase

Another ParameterDatabase instance to copy parameters from.

overwrite_parametersbool, default=False

If True, allows overwriting existing parameters. If False, raises ValueError if duplicate keys are encountered.

Raises:
TypeError

If parameter_database is not a ParameterDatabase instance.

ValueError

If duplicate keys exist and overwrite_parameters=False.

Examples

>>> db1 = bcp.ParameterDatabase(parameter_dictionary={'kb': 100.0})
>>> db2 = bcp.ParameterDatabase()
>>> db2.load_parameters_from_database(db1)
>>> db2['kb'].value
100.0
load_parameters_from_dictionary(parameter_dictionary: Dict[ParameterKey, str | Real], overwrite_parameters=False) None[source]

Load parameters from a dictionary.

Parameters:
parameter_dictionarydict

Dictionary with keys as ParameterKey-like objects (dict, tuple, or str) and values as numerical values or strings.

overwrite_parametersbool, default=False

If True, allows overwriting existing parameters. If False, raises ValueError if duplicate keys are encountered.

Raises:
ValueError

If duplicate keys exist and overwrite_parameters=False.

Examples

>>> db = bcp.ParameterDatabase()
>>> params = {
...     'kb': 100.0,
...     ('binding', None, 'ku'): 0.01,
... }
>>> db.load_parameters_from_dictionary(params)
load_parameters_from_file(filename: str, overwrite_parameters=False) None[source]

Load parameters from a file.

Reads parameters from a CSV or TSV file and adds them to the database. The file must have ‘param_name’ and ‘param_val’ columns. Optional columns include ‘mechanism’, ‘part_id’, and ‘units’.

Parameters:
filenamestr

Path to parameter file. Must be tab-separated (.tsv, .txt) or comma-separated (.csv). File is searched in current directory and BioCRNpyler package paths.

overwrite_parametersbool, default=False

If True, allows overwriting existing parameters. If False, raises ValueError if duplicate keys are encountered.

Raises:
ValueError

If file cannot be found, has invalid format, or contains duplicate keys when overwrite_parameters=False.

Notes

Accepted column names (case-sensitive, first match used):

  • param_name: ‘parameter_name’, ‘parameter’, ‘param’, ‘param_name’

  • param_val: ‘val’, ‘value’, ‘param_val’, ‘parameter_value’

  • mechanism: ‘mechanism’, ‘mechanism_id’

  • part_id: ‘part_id’, ‘part’

  • unit: ‘units’, ‘unit’

Additional columns are stored in parameter_info dictionary.

File Format Example (CSV):

.. code::

mechanism,part_id,param_name,param_val,unit binding,,kb,100,1/s binding,,ku,0.01,1/s transcription,prom1,ktx,0.05,1/s

Examples

>>> db = bcp.ParameterDatabase(
...    parameter_file='mixtures/pure_parameters.tsv')

Load multiple files:

>>> db = bcp.ParameterDatabase(
...     parameter_file=[
...         'mixtures/pure_parameters.tsv',
...         'components/tetr_parameters.tsv'])
class biocrnpyler.core.parameter.ParameterEntry(parameter_name: str, parameter_value: str | Real, parameter_key=None, parameter_info=None, **kwargs)[source]

Parameter with database lookup key and metadata.

A ParameterEntry extends Parameter with a lookup key for database storage and retrieval, plus additional metadata about the parameter’s origin and context.

Parameters:
parameter_namestr

Name of the parameter.

parameter_valuefloat or str

Value of the parameter.

parameter_keydict, ParameterKey, str, or None, optional

Lookup key for the parameter database.

parameter_infodict, optional

Additional metadata about the parameter (e.g., source file, comments). If dict contains ‘unit’ key, it will update the parameter’s unit.

**kwargs

Additional keyword arguments passed to Parameter constructor, including ‘unit’.

Attributes:
parameter_keyParameterKey

ParameterKey: The database lookup key for this parameter.

parameter_infodict

dict: Additional metadata about the parameter.

See also

Parameter

Base parameter class.

ModelParameter

Parameter with search and found keys.

ParameterDatabase

Database for storing parameter entries.

Notes

The parameter_key value can be any of the following:

  • dict: {‘mechanism’: …, ‘part_id’: …, ‘name’: …}

  • ParameterKey namedtuple: (mechanism, part_id, name)

  • str: parameter name (other fields set to None)

  • None: creates key with all fields None except name

using the following conventions:

  • mechanism: str or None (mechanism name or type)

  • part_id: str or None (component/part identifier)

  • name: str (parameter name)

These keys enable flexible parameter lookup with defaulting behavior in the ParameterDatabase.

Examples

Create a parameter entry with full key:

>>> entry = bcp.ParameterEntry(
...     'kb',
...     100.0,
...     parameter_key={'mechanism': 'binding', 'part_id': 'promoter1'},
...     unit='1/s'
... )

Create a parameter entry with just a name:

>>> entry = bcp.ParameterEntry('ku', 0.01, parameter_key='ku')
>>> entry.parameter_key
ParameterKey(mechanism=None, part_id=None, name='ku')
__eq__(other)[source]

Test equality between parameters or parameter and number.

Parameters:
otherParameter or float

Object to compare with. Can be another Parameter object or a numerical value.

Returns:
bool

True if values are equal, False otherwise.

Raises:
TypeError

If other cannot be compared (not a Parameter or number).

__hash__()[source]

Return hash value for the parameter.

Returns:
int

Hash value based on parameter name, value, and unit.

static create_parameter_key(new_key: Dict | ParameterKey | str, parameter_name=None) ParameterKey[source]

Convert various input types to a ParameterKey namedtuple.

Parameters:
new_keydict, ParameterKey, tuple, str, or None

Input to convert to ParameterKey:

  • dict: Must have keys matching ParameterKey fields

  • ParameterKey: Returned as-is

  • 3-tuple: Converted to ParameterKey with proper field mapping

  • str: Used as ‘name’, other fields set to None

  • None: All fields set to None (requires parameter_name)

parameter_namestr, optional

Parameter name to use if not specified in new_key. Overrides name field if provided in dict.

Returns:
ParameterKey

Named tuple with fields (mechanism, part_id, name).

Raises:
ValueError

If new_key is not a valid type or format.

Examples

>>> key = bcp.ParameterEntry.create_parameter_key('kb')
>>> key
ParameterKey(mechanism=None, part_id=None, name='kb')
>>> key = bcp.ParameterEntry.create_parameter_key(
...     {'mechanism': 'transcription', 'part_id': 'prom1'},
...     parameter_name='ktx'
... )
>>> key
ParameterKey(mechanism='transcription', part_id='prom1', name='ktx')
get_sbml_id()[source]

Generate SBML-compatible identifier for the parameter.

Constructs an identifier string from the parameter key fields, formatted as: ‘<name>_<part_id>_<mechanism>’.

Returns:
str

SBML-compatible identifier string.

property parameter_info: Dict

dict: Additional metadata about the parameter.

property parameter_key: ParameterKey

ParameterKey: The database lookup key for this parameter.

property parameter_name: str

str: The name of the parameter.

property unit: str

str: The unit string for the parameter.

property value: Real

float: The numerical value of the parameter.

class biocrnpyler.core.parameter.ParameterKey(mechanism, part_id, name)[source]

Named tuple defining a parameter key.

Parameters:
mechanismstr, Mechanism, or None

Mechanism identifier. Can be a string (used as both name and type), a Mechanism object (uses .name and .mechanism_type), or None.

part_idstr or None

Part/component identifier for the parameter.

namestr

Name of the parameter. Must start with a letter and contain at least one character.

__add__(value, /)

Return self+value.

__class_getitem__(object, /)

See PEP 585

__contains__(key, /)

Return bool(key in self).

__eq__(value, /)

Return self==value.

__ge__(value, /)

Return self>=value.

__getattribute__(name, /)

Return getattr(self, name).

__getitem__(key, /)

Return self[key].

__getnewargs__()

Return self as a plain tuple. Used by copy and pickle.

__gt__(value, /)

Return self>value.

__hash__(/)

Return hash(self).

__iter__(/)

Implement iter(self).

__le__(value, /)

Return self<=value.

__len__(/)

Return len(self).

__lt__(value, /)

Return self<value.

__mul__(value, /)

Return self*value.

__ne__(value, /)

Return self!=value.

static __new__(_cls, mechanism, part_id, name)

Create new instance of ParameterKey(mechanism, part_id, name)

__replace__(**kwds)

Return a new ParameterKey object replacing specified fields with new values

__rmul__(value, /)

Return value*self.

count(value, /)

Return number of occurrences of value.

index(value, start=0, stop=sys.maxsize, /)

Return first index of value.

Raises ValueError if the value is not present.

mechanism

Alias for field number 0

name

Alias for field number 2

part_id

Alias for field number 1