Skip to content

:>> [[ABIO]] → ABIO DocsModules ABIO protocols

Protocols Module

Protocol definitions for the simulation.

alienbio.protocols

Protocol definitions for the alienbio system.

Protocols are organized by subsystem: - infra: Entity base, IO, Expr, Context - bio: Atom, Molecule, Reaction, Chemistry, Pathway, Compartment, Generators

Usage

from alienbio.protocols import Atom, Molecule, Reaction, Chemistry from alienbio.protocols.bio import Atom, Molecule, Reaction from alienbio.protocols.bio import Simulator

Atom

Bases: Protocol

Protocol for atomic elements.

Atoms are the building blocks of molecules. Each atom has: - symbol: 1-2 letter chemical notation (e.g., "C", "H", "Na") - name: Human-readable name (e.g., "Carbon", "Hydrogen") - atomic_weight: Mass in atomic mass units

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class Atom(Protocol):
    """Protocol for atomic elements.

    Atoms are the building blocks of molecules. Each atom has:
    - symbol: 1-2 letter chemical notation (e.g., "C", "H", "Na")
    - name: Human-readable name (e.g., "Carbon", "Hydrogen")
    - atomic_weight: Mass in atomic mass units
    """

    @property
    def symbol(self) -> str:
        """Chemical symbol (1-2 letters): 'C', 'H', 'O', 'Na'."""
        ...

    @property
    def name(self) -> str:
        """Human-readable name: 'Carbon', 'Hydrogen'."""
        ...

    @property
    def atomic_weight(self) -> float:
        """Atomic mass in atomic mass units."""
        ...

symbol property

Chemical symbol (1-2 letters): 'C', 'H', 'O', 'Na'.

name property

Human-readable name: 'Carbon', 'Hydrogen'.

atomic_weight property

Atomic mass in atomic mass units.

Molecule

Bases: Protocol

Protocol for molecule entities.

Molecules are composed of atoms and have: - atoms: Composition as {Atom: count} - bdepth: Biosynthetic depth (0 = primitive, higher = more complex) - name: Human-readable name (e.g., "glucose", "water") - symbol: Chemical formula derived from atoms (e.g., "C6H12O6") - molecular_weight: Computed from atom weights

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class Molecule(Protocol):
    """Protocol for molecule entities.

    Molecules are composed of atoms and have:
    - atoms: Composition as {Atom: count}
    - bdepth: Biosynthetic depth (0 = primitive, higher = more complex)
    - name: Human-readable name (e.g., "glucose", "water")
    - symbol: Chemical formula derived from atoms (e.g., "C6H12O6")
    - molecular_weight: Computed from atom weights
    """

    @property
    def local_name(self) -> str:
        """The molecule's local name within its parent entity."""
        ...

    @property
    def atoms(self) -> Mapping[Any, int]:  # keyed by Atom; Mapping keys are invariant, so the key is open
        """Atom composition: {atom: count}."""
        ...

    @property
    def bdepth(self) -> int:
        """Biosynthetic depth (0 = primitive, 4+ = complex)."""
        ...

    @property
    def name(self) -> str:
        """Human-readable name: 'glucose', 'water'."""
        ...

    @property
    def symbol(self) -> str:
        """Chemical formula derived from atoms: 'C6H12O6', 'H2O'."""
        ...

    @property
    def molecular_weight(self) -> float:
        """Molecular mass computed from atom weights."""
        ...

local_name property

The molecule's local name within its parent entity.

atoms property

Atom composition: {atom: count}.

bdepth property

Biosynthetic depth (0 = primitive, 4+ = complex).

name property

Human-readable name: 'glucose', 'water'.

symbol property

Chemical formula derived from atoms: 'C6H12O6', 'H2O'.

molecular_weight property

Molecular mass computed from atom weights.

Reaction

Bases: Protocol

Protocol for reaction entities.

Reactions define transformations within a single compartment. Each reaction has reactants, products, and a rate.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class Reaction(Protocol):
    """Protocol for reaction entities.

    Reactions define transformations within a single compartment.
    Each reaction has reactants, products, and a rate.
    """

    @property
    def local_name(self) -> str:
        """The reaction's local name."""
        ...

    @property
    def name(self) -> str:
        """Human-readable name."""
        ...

    @property
    def symbol(self) -> str:
        """Formula string: 'A + B -> C + D'."""
        ...

    @property
    def reactants(self) -> Mapping[Any, float]:  # keyed by Molecule (see Molecule.atoms)
        """Reactant molecules and their stoichiometric coefficients."""
        ...

    @property
    def products(self) -> Mapping[Any, float]:
        """Product molecules and their stoichiometric coefficients."""
        ...

    @property
    def modifiers(self) -> Mapping[Any, Any]:
        """Catalyst/regulator molecules acting on the reaction without being
        stoichiometrically consumed, mapped to a modulation value: a bidirectional
        rate-modulation descriptor (``bio.reaction.Modulation`` — kind + params, e.g.
        an activator/inhibitor) or a bare opaque role tag ``str`` (e.g. an enzyme with
        role ``"catalyst"``), which is rate-inert. Empty for an unmodified reaction."""
        ...

    @property
    def rate(self) -> Union[float, Callable]:
        """Reaction rate (constant or function of state)."""
        ...

local_name property

The reaction's local name.

name property

Human-readable name.

symbol property

Formula string: 'A + B -> C + D'.

reactants property

Reactant molecules and their stoichiometric coefficients.

products property

Product molecules and their stoichiometric coefficients.

modifiers property

Catalyst/regulator molecules acting on the reaction without being stoichiometrically consumed, mapped to a modulation value: a bidirectional rate-modulation descriptor (bio.reaction.Modulation — kind + params, e.g. an activator/inhibitor) or a bare opaque role tag str (e.g. an enzyme with role "catalyst"), which is rate-inert. Empty for an unmodified reaction.

rate property

Reaction rate (constant or function of state).

Flow

Bases: Protocol

Protocol for transport between compartments.

Flow hierarchy: - Flow (base): common interface for all flows - TransportFlux (bio.flow): amount-conserving transport between any two compartments - GeneralFlow: arbitrary state modifications (placeholder)

Each flow is anchored to an origin compartment.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class Flow(Protocol):
    """Protocol for transport between compartments.

    Flow hierarchy:
    - Flow (base): common interface for all flows
    - TransportFlux (bio.flow): amount-conserving transport between any two compartments
    - GeneralFlow: arbitrary state modifications (placeholder)

    Each flow is anchored to an origin compartment.
    """

    @property
    def origin(self) -> CompartmentId:
        """The origin compartment (where this flow is anchored)."""
        ...

    @property
    def name(self) -> str:
        """Human-readable name."""
        ...

    @property
    def is_membrane_flow(self) -> bool:
        """True if this is a membrane flow (origin ↔ parent)."""
        ...

    @property
    def is_general_flow(self) -> bool:
        """True if this is a general flow (arbitrary edits)."""
        ...

    def compute_flux(
        self, state: "WorldStateImpl", tree: "CompartmentTreeImpl"
    ) -> float:
        """Compute flux for this flow."""
        ...

    def apply(
        self, state: "WorldStateImpl", tree: "CompartmentTreeImpl", dt: float
    ) -> None:
        """Apply this flow to the state (mutates in place)."""
        ...

    def attributes(self) -> Dict[str, Any]:
        """Semantic content for serialization."""
        ...

origin property

The origin compartment (where this flow is anchored).

name property

Human-readable name.

is_membrane_flow property

True if this is a membrane flow (origin ↔ parent).

is_general_flow property

True if this is a general flow (arbitrary edits).

compute_flux(state, tree)

Compute flux for this flow.

Source code in src/alienbio/protocols/bio.py
def compute_flux(
    self, state: "WorldStateImpl", tree: "CompartmentTreeImpl"
) -> float:
    """Compute flux for this flow."""
    ...

apply(state, tree, dt)

Apply this flow to the state (mutates in place).

Source code in src/alienbio/protocols/bio.py
def apply(
    self, state: "WorldStateImpl", tree: "CompartmentTreeImpl", dt: float
) -> None:
    """Apply this flow to the state (mutates in place)."""
    ...

attributes()

Semantic content for serialization.

Source code in src/alienbio/protocols/bio.py
def attributes(self) -> Dict[str, Any]:
    """Semantic content for serialization."""
    ...

GeneralFlow

Bases: Flow, Protocol

Protocol for general flows (placeholder).

GeneralFlow is a catch-all for flows that don't fit the TransportFlux pattern. This includes lateral flows, instance transfers, and arbitrary state edits.

NOTE: This is a placeholder. Full implementation will require a more general interpreter to handle arbitrary state modifications.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class GeneralFlow(Flow, Protocol):
    """Protocol for general flows (placeholder).

    GeneralFlow is a catch-all for flows that don't fit the TransportFlux pattern.
    This includes lateral flows, instance transfers, and arbitrary state edits.

    NOTE: This is a placeholder. Full implementation will require a more
    general interpreter to handle arbitrary state modifications.
    """

    @property
    def description(self) -> str:
        """Description of what this flow does."""
        ...

description property

Description of what this flow does.

Chemistry

Bases: Protocol

Protocol for chemistry containers.

Chemistry acts as the "world" for a chemical system, holding atoms, molecules, and reactions as public dict attributes.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class Chemistry(Protocol):
    """Protocol for chemistry containers.

    Chemistry acts as the "world" for a chemical system,
    holding atoms, molecules, and reactions as public dict attributes.
    """

    @property
    def local_name(self) -> str:
        """The chemistry's local name."""
        ...

    @property
    def atoms(self) -> Mapping[str, Atom]:
        """All atoms in this chemistry (by symbol)."""
        ...

    @property
    def molecules(self) -> Mapping[str, Molecule]:
        """All molecules in this chemistry (by name)."""
        ...

    @property
    def reactions(self) -> Mapping[str, Reaction]:
        """All reactions in this chemistry (by name)."""
        ...

    def validate(self) -> List[str]:
        """Validate the chemistry for consistency."""
        ...

    # Reaction-network graph queries. The molecules (species nodes) and
    # reactions (reaction nodes) form a bipartite graph; node ids are their
    # ``name``s.

    def neighbors(self, node: str) -> set[str]:
        """Molecule<->reaction adjacency (bipartite), by name."""
        ...

    def paths(self, a: str, b: str, max_len: int = 8) -> List[List[str]]:
        """All simple paths (by name) from ``a`` to ``b`` within ``max_len`` edges."""
        ...

    def subgraph(self, nodes: Iterable[str]) -> "Chemistry":
        """The induced sub-chemistry over ``nodes`` (edges to dropped nodes removed)."""
        ...

    def match(self, pattern: Any) -> List[Dict[str, str]]:
        """All subgraph embeddings of ``pattern`` into this chemistry."""
        ...

local_name property

The chemistry's local name.

atoms property

All atoms in this chemistry (by symbol).

molecules property

All molecules in this chemistry (by name).

reactions property

All reactions in this chemistry (by name).

validate()

Validate the chemistry for consistency.

Source code in src/alienbio/protocols/bio.py
def validate(self) -> List[str]:
    """Validate the chemistry for consistency."""
    ...

neighbors(node)

Molecule<->reaction adjacency (bipartite), by name.

Source code in src/alienbio/protocols/bio.py
def neighbors(self, node: str) -> set[str]:
    """Molecule<->reaction adjacency (bipartite), by name."""
    ...

paths(a, b, max_len=8)

All simple paths (by name) from a to b within max_len edges.

Source code in src/alienbio/protocols/bio.py
def paths(self, a: str, b: str, max_len: int = 8) -> List[List[str]]:
    """All simple paths (by name) from ``a`` to ``b`` within ``max_len`` edges."""
    ...

subgraph(nodes)

The induced sub-chemistry over nodes (edges to dropped nodes removed).

Source code in src/alienbio/protocols/bio.py
def subgraph(self, nodes: Iterable[str]) -> "Chemistry":
    """The induced sub-chemistry over ``nodes`` (edges to dropped nodes removed)."""
    ...

match(pattern)

All subgraph embeddings of pattern into this chemistry.

Source code in src/alienbio/protocols/bio.py
def match(self, pattern: Any) -> List[Dict[str, str]]:
    """All subgraph embeddings of ``pattern`` into this chemistry."""
    ...

CompartmentTree

Bases: Protocol

Protocol for compartment topology.

Represents the hierarchical structure of compartments (organism > organ > cell). Stored separately from concentrations to allow efficient updates.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class CompartmentTree(Protocol):
    """Protocol for compartment topology.

    Represents the hierarchical structure of compartments (organism > organ > cell).
    Stored separately from concentrations to allow efficient updates.
    """

    @property
    def num_compartments(self) -> int:
        """Total number of compartments."""
        ...

    def parent(self, child: CompartmentId) -> Optional[CompartmentId]:
        """Get parent of a compartment (None for root)."""
        ...

    def children(self, parent: CompartmentId) -> List[CompartmentId]:
        """Get children of a compartment."""
        ...

    def root(self) -> CompartmentId:
        """Get the root compartment."""
        ...

    def is_root(self, compartment: CompartmentId) -> bool:
        """Check if compartment is the root."""
        ...

num_compartments property

Total number of compartments.

parent(child)

Get parent of a compartment (None for root).

Source code in src/alienbio/protocols/bio.py
def parent(self, child: CompartmentId) -> Optional[CompartmentId]:
    """Get parent of a compartment (None for root)."""
    ...

children(parent)

Get children of a compartment.

Source code in src/alienbio/protocols/bio.py
def children(self, parent: CompartmentId) -> List[CompartmentId]:
    """Get children of a compartment."""
    ...

root()

Get the root compartment.

Source code in src/alienbio/protocols/bio.py
def root(self) -> CompartmentId:
    """Get the root compartment."""
    ...

is_root(compartment)

Check if compartment is the root.

Source code in src/alienbio/protocols/bio.py
def is_root(self, compartment: CompartmentId) -> bool:
    """Check if compartment is the root."""
    ...

WorldState

Bases: Protocol

Protocol for world concentration state.

Stores concentrations for all compartments and molecules. Dense storage: [num_compartments x num_molecules] array. Can be extended with sparse overflow for large molecule counts.

Each WorldState holds a reference to its CompartmentTree. Multiple states can share the same tree (immutable sharing). When topology changes (e.g., cell division), a new tree is created and new states point to it while historical states keep their original tree reference.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class WorldState(Protocol):
    """Protocol for world concentration state.

    Stores concentrations for all compartments and molecules.
    Dense storage: [num_compartments x num_molecules] array.
    Can be extended with sparse overflow for large molecule counts.

    Each WorldState holds a reference to its CompartmentTree. Multiple
    states can share the same tree (immutable sharing). When topology
    changes (e.g., cell division), a new tree is created and new states
    point to it while historical states keep their original tree reference.
    """

    @property
    def tree(self) -> CompartmentTree:
        """The compartment tree this state belongs to."""
        ...

    @property
    def num_compartments(self) -> int:
        """Number of compartments."""
        ...

    @property
    def num_molecules(self) -> int:
        """Number of molecules in vocabulary."""
        ...

    def get(self, compartment: CompartmentId, molecule: MoleculeId) -> float:
        """Get concentration of molecule in compartment."""
        ...

    def set(self, compartment: CompartmentId, molecule: MoleculeId, value: float) -> None:
        """Set concentration of molecule in compartment."""
        ...

    def get_compartment(self, compartment: CompartmentId) -> List[float]:
        """Get all concentrations for a compartment."""
        ...

    # Multiplicity methods

    def get_multiplicity(self, compartment: CompartmentId) -> float:
        """Get multiplicity (instance count) for a compartment."""
        ...

    def set_multiplicity(self, compartment: CompartmentId, value: float) -> None:
        """Set multiplicity (instance count) for a compartment."""
        ...

    def total_molecules(self, compartment: CompartmentId, molecule: MoleculeId) -> float:
        """Get total molecules = multiplicity * concentration."""
        ...

    # Copy and array methods

    def copy(self) -> WorldState:
        """Create a copy of this state (shares tree reference)."""
        ...

    def as_array(self) -> Any:
        """Get concentrations as 2D array [compartments x molecules]."""
        ...

tree property

The compartment tree this state belongs to.

num_compartments property

Number of compartments.

num_molecules property

Number of molecules in vocabulary.

get(compartment, molecule)

Get concentration of molecule in compartment.

Source code in src/alienbio/protocols/bio.py
def get(self, compartment: CompartmentId, molecule: MoleculeId) -> float:
    """Get concentration of molecule in compartment."""
    ...

set(compartment, molecule, value)

Set concentration of molecule in compartment.

Source code in src/alienbio/protocols/bio.py
def set(self, compartment: CompartmentId, molecule: MoleculeId, value: float) -> None:
    """Set concentration of molecule in compartment."""
    ...

get_compartment(compartment)

Get all concentrations for a compartment.

Source code in src/alienbio/protocols/bio.py
def get_compartment(self, compartment: CompartmentId) -> List[float]:
    """Get all concentrations for a compartment."""
    ...

get_multiplicity(compartment)

Get multiplicity (instance count) for a compartment.

Source code in src/alienbio/protocols/bio.py
def get_multiplicity(self, compartment: CompartmentId) -> float:
    """Get multiplicity (instance count) for a compartment."""
    ...

set_multiplicity(compartment, value)

Set multiplicity (instance count) for a compartment.

Source code in src/alienbio/protocols/bio.py
def set_multiplicity(self, compartment: CompartmentId, value: float) -> None:
    """Set multiplicity (instance count) for a compartment."""
    ...

total_molecules(compartment, molecule)

Get total molecules = multiplicity * concentration.

Source code in src/alienbio/protocols/bio.py
def total_molecules(self, compartment: CompartmentId, molecule: MoleculeId) -> float:
    """Get total molecules = multiplicity * concentration."""
    ...

copy()

Create a copy of this state (shares tree reference).

Source code in src/alienbio/protocols/bio.py
def copy(self) -> WorldState:
    """Create a copy of this state (shares tree reference)."""
    ...

as_array()

Get concentrations as 2D array [compartments x molecules].

Source code in src/alienbio/protocols/bio.py
def as_array(self) -> Any:
    """Get concentrations as 2D array [compartments x molecules]."""
    ...

Simulator

Bases: Protocol

Protocol for simulators.

A Simulator advances the state of a chemical system over time. Applies reactions within compartments and flows across membranes.

Source code in src/alienbio/protocols/bio.py
class Simulator(Protocol):
    """Protocol for simulators.

    A Simulator advances the state of a chemical system over time.
    Applies reactions within compartments and flows across membranes.
    """

    @property
    def tree(self) -> "CompartmentTreeImpl":
        """The compartment topology."""
        ...

    @property
    def dt(self) -> float:
        """Time step size."""
        ...

    @abstractmethod
    def step(self, state: "WorldStateImpl") -> "WorldStateImpl":
        """Advance the simulation by one time step."""
        ...

    def run(
        self,
        state: "WorldStateImpl",
        steps: int,
        sample_every: Optional[int] = None,
    ) -> List["WorldStateImpl"]:
        """Run simulation for multiple steps, optionally sampling history."""
        ...

tree property

The compartment topology.

dt property

Time step size.

step(state) abstractmethod

Advance the simulation by one time step.

Source code in src/alienbio/protocols/bio.py
@abstractmethod
def step(self, state: "WorldStateImpl") -> "WorldStateImpl":
    """Advance the simulation by one time step."""
    ...

run(state, steps, sample_every=None)

Run simulation for multiple steps, optionally sampling history.

Source code in src/alienbio/protocols/bio.py
def run(
    self,
    state: "WorldStateImpl",
    steps: int,
    sample_every: Optional[int] = None,
) -> List["WorldStateImpl"]:
    """Run simulation for multiple steps, optionally sampling history."""
    ...