Skip to content

reaction_library

RL4CRN.iocrns.reaction_library

Reaction library and construction utilities.

This module defines ReactionLibrary, a container for reaction templates used throughout RL4CRN. The library:

  • stores a list of reaction objects and assigns each a unique integer ID,
  • provides fast lookup tables mapping reaction IDs to slices in flattened parameter vectors,
  • exposes masks useful for parameterized policies (continuous/discrete parameter slots and discrete-combination validity in logit space),
  • offers helper constructors for common reaction families (mass-action, degradation, Hill-regulated production).

The library is designed to be used in:

  • actuators (e.g., selecting a reaction by ID),
  • observers/tensorizers (e.g., building multi-hot encodings),
  • policies that need fixed-size parameter layouts.

ReactionLibrary

Container managing a list of registered reaction templates.

Each reaction is assigned a unique integer ID at registration time. The library supports:

  • retrieval by ID (returns a deep copy),
  • computation of flattened parameter layouts,
  • masks describing which parameter slots exist per reaction.

Parameters are often treated in a flattened layout across the entire library. Two related layouts are maintained:

  • a flattened vector of all parameters across reactions (size get_num_parameters),
  • a flattened vector of controllable parameters across reactions (size get_num_controllable_parameters).
ATTRIBUTE DESCRIPTION
reactions

List of registered reaction objects.

last_ID

Next ID to assign (also equals len(reactions) after reindexing).

parameter_lookup_table

List mapping reaction ID -> starting offset in the flattened all-parameters vector.

controllable_parameter_lookup_table

List mapping reaction ID -> starting offset in the flattened controllable-parameters vector.

continuous_parameter_mask

Optional 2D float mask describing continuous parameter slots per reaction.

discrete_parameter_mask

Optional 2D float mask describing discrete parameter slots per reaction.

logit_mask

Optional 2D boolean mask describing valid combinations of discrete categories in a global logit space.

categories_per_discrete_parameter

Optional list with the number of categories for each discrete parameter position (global layout). Required by get_logit_mask.

__init__(reactions=None)

Initialize the library and optionally register initial reactions.

PARAMETER DESCRIPTION
reactions

Optional reaction or list of reactions to register. Each entry must be an instance of RL4CRN.iocrns.reactions.Reaction.

DEFAULT: None

get_reaction(ID)

Retrieve a reaction by its ID (returns a deep copy).

PARAMETER DESCRIPTION
ID

Integer reaction ID.

RETURNS DESCRIPTION

A deep copy of the reaction with the specified ID, or None if the ID is out of range.

add_reactions(reactions)

Register one or more reactions.

PARAMETER DESCRIPTION
reactions

A single Reaction instance, or an iterable of Reaction instances. If None, this method is a no-op.

register_reaction(reaction)

Register a single reaction and assign it a unique ID.

PARAMETER DESCRIPTION
reaction

Reaction instance to add.

Side Effects
  • Appends reaction to reactions.
  • Calls reaction.set_ID(...).
  • Increments last_ID.

__len__()

Returns the number of reactions in the library.

get_num_parameters()

Returns the total number of parameters across all reactions in the library.

get_num_controllable_parameters()

Returns the total number of controllable parameters across all reactions in the library.

prepare_lookup_tables()

Prepare lookup tables for flattened parameter layouts.

This method creates:

  • parameter_lookup_table: reaction ID -> starting offset into a flattened vector of all parameters.
  • controllable_parameter_lookup_table: reaction ID -> starting offset into a flattened vector of controllable parameters.
Notes

Offsets are computed with cumulative sums; for reaction j, the slice of all-parameters is:

  • start = parameter_lookup_table[j]
  • end = start + reactions[j].num_parameters

Similarly for controllable parameters.

__str__()

Return a readable representation listing all registered reactions.

print_reactions(ID_list=None)

Print a subset (or all) reactions in the library.

PARAMETER DESCRIPTION
ID_list

Optional iterable of reaction IDs to print. If None, prints all reactions.

DEFAULT: None

get_parameter_mask(mode='continuous', force=False)

Return a per-reaction mask for parameter-slot existence.

The returned mask is useful when representing reaction parameters in a fixed-size tensor where different reactions have different numbers of parameters.

PARAMETER DESCRIPTION
mode

Which parameter type to consider:

  • 'continuous': uses reaction.num_continuous_parameters and caches to self.continuous_parameter_mask.
  • 'discrete': uses reaction.num_discrete_parameters and caches to self.discrete_parameter_mask.

DEFAULT: 'continuous'

force

If True, recompute even if a cached mask exists.

DEFAULT: False

RETURNS DESCRIPTION

A float32 numpy array of shape (len(self), Pmax), where Pmax is the maximum number of parameters of the selected type across reactions. Entry (i, j) is 1.0 if reaction i has that parameter slot, otherwise 0.0.

If no reactions have parameters of the specified type (Pmax == 0), returns None.

RAISES DESCRIPTION
ValueError

If mode is not 'continuous' or 'discrete'.

get_logit_mask(force=False)

Return a mask of valid discrete-category combinations in logit space.

Discrete parameters are modeled as categorical variables. Let the global discrete parameter layout have D positions, with categories_per_discrete_parameter = [K1, ..., KD]. Consider the full Cartesian grid of category assignments:

\[\{0,\dots,K_1-1\} \times \cdots \times \{0,\dots,K_D-1\}.\]

Not every reaction uses every discrete parameter position. This method constructs a boolean mask indicating which global combinations are valid for each reaction, by enforcing that unused discrete positions take a default category (here: category 0) for that reaction.

PARAMETER DESCRIPTION
force

If True, recompute even if self.logit_mask is already set.

DEFAULT: False

RETURNS DESCRIPTION

Boolean numpy array of shape (len(self), Ncomb) where Ncomb is the

total number of combinations in the Cartesian grid. Entry (r, c) is

True if combination c is valid for reaction r.

Returns None if the library has no discrete parameters

(get_parameter_mask(mode='discrete') returns None).

RAISES DESCRIPTION
ValueError

If categories_per_discrete_parameter is not set but discrete parameters exist.

Notes

This method assumes that unused discrete slots must be fixed to category 0. If your semantics differ (e.g., "don't-care" instead of fixed), you should modify the mask logic accordingly.

clone()

Return a deep copy of the reaction library.

merge(other_library)

Merge another reaction library into this one.

PARAMETER DESCRIPTION
other_library

Another ReactionLibrary whose reactions are registered into this library.

Notes

Merging non-mutually-exclusive libraries may require deduplication. This method currently appends all reactions and re-prepares lookup tables.

find_ID(reactions)

Find reaction IDs by matching reaction instances.

PARAMETER DESCRIPTION
reactions

A single Reaction instance or a list of Reaction instances to match by equality (==) against library entries.

RETURNS DESCRIPTION

A list of integer reaction IDs corresponding to the provided reaction instances. If a reaction instance is not found in the library, None is returned for that instance.

remove_reactions(reactions, remove_by='ID')

Remove reactions from the library.

PARAMETER DESCRIPTION
reactions

Depending on remove_by:

  • 'ID': list/iterable of integer reaction IDs.
  • 'instance': reaction instance or list of instances to match by equality (==) against library entries.
  • 'reactant': not implemented.
  • 'product': not implemented.

remove_by

Removal mode. Supported: 'ID', 'instance'.

DEFAULT: 'ID'

Side Effects
  • Removes matching reactions from reactions.
  • Reassigns reaction IDs to be contiguous starting from 0.
  • Updates last_ID.
  • Recomputes lookup tables.
RAISES DESCRIPTION
NotImplementedError

For 'reactant' and 'product'.

ValueError

If remove_by is not a supported option.

find_zero_reaction()

Find the ID of the zero reaction (∅ → ∅) if it exists.

RETURNS DESCRIPTION

The integer ID of the zero reaction if found, otherwise None.

construct_mass_action_library(species_labels, order=2, order_reactants=None, order_products=None)

Construct a library of mass-action reactions over a species set.

Generates all reactions of the form:

\[\text{reactant complex} \rightarrow \text{product complex}\]

where reactant complexes have size up to order_reactants and product complexes have size up to order_products (multiset combinations with replacement). The pair ([] , []) (∅ → ∅) is included explicitly.

PARAMETER DESCRIPTION
species_labels

List of species labels usable in complexes.

order

If order_reactants and order_products are not provided, both are set to this value.

DEFAULT: 2

order_reactants

Maximum stoichiometric order of reactant complexes.

DEFAULT: None

order_products

Maximum stoichiometric order of product complexes.

DEFAULT: None

RETURNS DESCRIPTION

A ReactionLibrary populated with MassAction reactions.

RAISES DESCRIPTION
AssertionError

If neither order nor both order_reactants and order_products are provided.

Notes

The number of distinct complexes of size up to O from n species is:

\[\sum_{k=0}^{O} \binom{n + k - 1}{k} = \binom{n + O}{O}.\]

This function generates all reactant/product pairs except identical complexes, plus the explicit empty-to-empty reaction.

construct_first_order_degradation_library(species_labels)

Construct a library of first-order degradation reactions.

For each species X in species_labels, constructs a mass-action reaction:

\[X \rightarrow \emptyset.\]
PARAMETER DESCRIPTION
species_labels

List of species labels.

RETURNS DESCRIPTION

A ReactionLibrary containing one degradation reaction per species.

construct_hill_production_library(species_labels, max_product_order=2, max_num_regulators=2)

Construct a library of Hill-regulated production reactions.

Generates reactions of the form:

\[\emptyset \rightarrow \text{product complex},\]

regulated by a set of activators and repressors (disjoint), with total number of regulators between 1 and max_num_regulators.

For each product complex (multiset of size 1..max_product_order) and each split into A activators and R repressors with A+R = t, t ranging over 1..max_num_regulators, this function constructs one HillProduction reaction per distinct choice of activator and repressor sets.

PARAMETER DESCRIPTION
species_labels

List of species labels usable as products or regulators.

max_product_order

Maximum stoichiometric order of the product complex (≥ 1).

DEFAULT: 2

max_num_regulators

Maximum total number of regulators (#activators + #repressors).

DEFAULT: 2

RETURNS DESCRIPTION

A ReactionLibrary populated with HillProduction reactions.

Notes

This constructor uses a parameter layout consistent with the current implementation:

  • parameter vector length: 2 + len(activators) + len(repressors)
  • parameters are initialized to None
  • all parameters are marked controllable (params_controllability=True)

If you switch to a richer Hill parameterization (e.g., separate K and n per regulator), update both the constructor and this docstring.

A rough count of generated reactions is:

\[(\binom{n + P}{P} - 1) \sum_{t=1}^{\min(R, n)} 2^t \binom{n}{t},\]

where n = len(species_labels), P = max_product_order, R = max_num_regulators.

construct_active_degradation_library(species_labels)

Construct a library of active degradation reactions.

Generates reactions of the form:

\[\text{species} \rightarrow \emptyset,\]

regulated by a degradation enzyme.

For each reactant species (substrate), this function constructs one ActiveDegradation reaction per distinct choice of degradation enzyme.

PARAMETER DESCRIPTION
species_labels

List of species labels usable as substrates or degradation enzymes.

RETURNS DESCRIPTION

A ReactionLibrary populated with ActiveDegradation reactions.

Notes

This constructor uses a parameter layout consistent with the current implementation:

  • parameter vector length: 2
  • parameters are initialized to None
  • all parameters are marked controllable (params_controllability=True)

A rough count of generated reactions is:

\[n \cdot (n-1),\]

where n = len(species_labels).