Skip to content

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 - execution: State, Simulator, Timeline, World, Task, etc.

Usage

from alienbio.protocols import Atom, Molecule, Reaction, Chemistry from alienbio.protocols.bio import Atom, Molecule, Reaction from alienbio.protocols.execution import State, 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) -> Dict[Atom, int]:
        """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) -> Dict[Molecule, float]:
        """Reactant molecules and their stoichiometric coefficients."""
        ...

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

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

    def get_rate(self, state: WorldState, compartment: CompartmentId) -> float:
        """Get the effective rate for a given compartment's 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.

rate property

Reaction rate (constant or function of state).

get_rate(state, compartment)

Get the effective rate for a given compartment's state.

Source code in src/alienbio/protocols/bio.py
def get_rate(self, state: WorldState, compartment: CompartmentId) -> float:
    """Get the effective rate for a given compartment's state."""
    ...

Flow

Bases: Protocol

Protocol for transport between compartments.

Flow hierarchy: - Flow (base): common interface for all flows - MembraneFlow: transport across parent-child membrane with stoichiometry - 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
    - MembraneFlow: transport across parent-child membrane with stoichiometry
    - 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: WorldState, tree: CompartmentTree
    ) -> float:
        """Compute flux for this flow."""
        ...

    def apply(
        self, state: WorldState, tree: CompartmentTree, 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: WorldState, tree: CompartmentTree
) -> 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: WorldState, tree: CompartmentTree, 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."""
    ...

MembraneFlow

Bases: Flow, Protocol

Protocol for membrane flows with stoichiometry.

Membrane flows transport molecules across the parent-child boundary. Like reactions, they specify stoichiometry for multiple molecules moving together per event.

Direction convention: - Positive stoichiometry = molecules move INTO origin (from parent) - Negative stoichiometry = molecules move OUT OF origin (into parent)

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class MembraneFlow(Flow, Protocol):
    """Protocol for membrane flows with stoichiometry.

    Membrane flows transport molecules across the parent-child boundary.
    Like reactions, they specify stoichiometry for multiple molecules
    moving together per event.

    Direction convention:
    - Positive stoichiometry = molecules move INTO origin (from parent)
    - Negative stoichiometry = molecules move OUT OF origin (into parent)
    """

    @property
    def stoichiometry(self) -> Dict[str, float]:
        """Molecules and counts moved per event {molecule: count}."""
        ...

    @property
    def rate_constant(self) -> float:
        """Base rate of events per unit time."""
        ...

stoichiometry property

Molecules and counts moved per event {molecule: count}.

rate_constant property

Base rate of events per unit time.

GeneralFlow

Bases: Flow, Protocol

Protocol for general flows (placeholder).

GeneralFlow is a catch-all for flows that don't fit the MembraneFlow 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 MembraneFlow 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) -> Dict[str, Atom]:
        """All atoms in this chemistry (by symbol)."""
        ...

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

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

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

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."""
    ...

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]."""
    ...

State

Bases: Protocol

Protocol for single-compartment molecule concentration state.

Simple interface for simulations with one compartment. For multi-compartment simulations, use WorldState instead.

Source code in src/alienbio/protocols/bio.py
@runtime_checkable
class State(Protocol):
    """Protocol for single-compartment molecule concentration state.

    Simple interface for simulations with one compartment.
    For multi-compartment simulations, use WorldState instead.
    """

    @property
    def chemistry(self) -> Chemistry:
        """The Chemistry this state belongs to."""
        ...

    def __getitem__(self, key: str) -> float:
        """Get concentration by molecule name."""
        ...

    def __setitem__(self, key: str, value: float) -> None:
        """Set concentration by molecule name."""
        ...

    def __contains__(self, key: str) -> bool:
        """Check if molecule exists in state."""
        ...

    def __iter__(self) -> Iterator[str]:
        """Iterate over molecule names."""
        ...

    def __len__(self) -> int:
        """Number of molecules in state."""
        ...

    def get(self, key: str, default: float = 0.0) -> float:
        """Get concentration with default."""
        ...

    def get_molecule(self, molecule: Molecule) -> float:
        """Get concentration by molecule object."""
        ...

    def set_molecule(self, molecule: Molecule, value: float) -> None:
        """Set concentration by molecule object."""
        ...

    def copy(self) -> State:
        """Create a copy of this state."""
        ...

chemistry property

The Chemistry this state belongs to.

__getitem__(key)

Get concentration by molecule name.

Source code in src/alienbio/protocols/bio.py
def __getitem__(self, key: str) -> float:
    """Get concentration by molecule name."""
    ...

__setitem__(key, value)

Set concentration by molecule name.

Source code in src/alienbio/protocols/bio.py
def __setitem__(self, key: str, value: float) -> None:
    """Set concentration by molecule name."""
    ...

__contains__(key)

Check if molecule exists in state.

Source code in src/alienbio/protocols/bio.py
def __contains__(self, key: str) -> bool:
    """Check if molecule exists in state."""
    ...

__iter__()

Iterate over molecule names.

Source code in src/alienbio/protocols/bio.py
def __iter__(self) -> Iterator[str]:
    """Iterate over molecule names."""
    ...

__len__()

Number of molecules in state.

Source code in src/alienbio/protocols/bio.py
def __len__(self) -> int:
    """Number of molecules in state."""
    ...

get(key, default=0.0)

Get concentration with default.

Source code in src/alienbio/protocols/bio.py
def get(self, key: str, default: float = 0.0) -> float:
    """Get concentration with default."""
    ...

get_molecule(molecule)

Get concentration by molecule object.

Source code in src/alienbio/protocols/bio.py
def get_molecule(self, molecule: Molecule) -> float:
    """Get concentration by molecule object."""
    ...

set_molecule(molecule, value)

Set concentration by molecule object.

Source code in src/alienbio/protocols/bio.py
def set_molecule(self, molecule: Molecule, value: float) -> None:
    """Set concentration by molecule object."""
    ...

copy()

Create a copy of this state.

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

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 chemistry(self) -> Chemistry:
        """The Chemistry being simulated."""
        ...

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

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

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

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

chemistry property

The Chemistry being simulated.

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: WorldState) -> WorldState:
    """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: WorldState,
    steps: int,
    sample_every: Optional[int] = None,
) -> List[WorldState]:
    """Run simulation for multiple steps, optionally sampling history."""
    ...

Scenario dataclass

Result of template instantiation (build phase).

Contains the visible scenario (with opaque names) plus ground truth and visibility mapping for debugging/scoring.

Attributes:

Name Type Description
molecules dict[str, Any]

Visible molecules (opaque names)

reactions dict[str, Any]

Visible reactions (opaque names)

regions list[Region]

List of spatial regions with organisms

_ground_truth_ dict[str, Any]

Full scenario with internal names

_visibility_mapping_ dict[str, Any]

Map from internal to opaque names

_seed int

Random seed used for instantiation

_metadata_ dict[str, Any]

Optional metadata from spec

Source code in src/alienbio/protocols/execution.py
@biotype
@dataclass
class Scenario:
    """Result of template instantiation (build phase).

    Contains the visible scenario (with opaque names) plus
    ground truth and visibility mapping for debugging/scoring.

    Attributes:
        molecules: Visible molecules (opaque names)
        reactions: Visible reactions (opaque names)
        regions: List of spatial regions with organisms
        _ground_truth_: Full scenario with internal names
        _visibility_mapping_: Map from internal to opaque names
        _seed: Random seed used for instantiation
        _metadata_: Optional metadata from spec
    """

    molecules: dict[str, Any] = field(default_factory=dict)
    reactions: dict[str, Any] = field(default_factory=dict)
    regions: list[Region] = field(default_factory=list)
    _ground_truth_: dict[str, Any] = field(default_factory=dict)
    _visibility_mapping_: dict[str, Any] = field(default_factory=dict)
    _seed: int = 0
    _metadata_: dict[str, Any] = field(default_factory=dict)

Region dataclass

A spatial region containing organisms and substrates.

Attributes:

Name Type Description
id str

Unique identifier for this region

substrates dict[str, float]

Dict of substrate concentrations

organisms list[Organism]

List of organisms in this region

Source code in src/alienbio/protocols/execution.py
@dataclass
class Region:
    """A spatial region containing organisms and substrates.

    Attributes:
        id: Unique identifier for this region
        substrates: Dict of substrate concentrations
        organisms: List of organisms in this region
    """

    id: str = ""
    substrates: dict[str, float] = field(default_factory=dict)
    organisms: list[Organism] = field(default_factory=list)

Organism dataclass

An organism instance within a region.

Attributes:

Name Type Description
id str

Unique identifier for this organism

species str

Name of the species this organism belongs to

Source code in src/alienbio/protocols/execution.py
@dataclass
class Organism:
    """An organism instance within a region.

    Attributes:
        id: Unique identifier for this organism
        species: Name of the species this organism belongs to
    """

    id: str = ""
    species: str = ""