Bio Module¶
Core biology simulation classes.
alienbio.bio
¶
Bio module: core biology classes for alienbio.
This module defines the fundamental biology abstractions:
Protocols (for type hints) - from alienbio.protocols.bio: - Atom: protocol for atomic elements - Molecule: protocol for molecule entities - Reaction: protocol for reaction entities - Flow: protocol for transport between compartments - Chemistry: protocol for chemistry containers - CompartmentTree: protocol for compartment topology - WorldState: protocol for multi-compartment concentrations - State: protocol for single-compartment concentrations - Simulator: protocol for simulators
Implementations: - AtomImpl: chemical elements with symbol, name, atomic_weight - MoleculeImpl: composed of atoms with bdepth, name, derived symbol/weight - ReactionImpl: transformations between molecules with rates - Flow hierarchy: - Flow: abstract base class for all flows - MembraneFlow: transport across parent-child membrane with stoichiometry - GeneralFlow: arbitrary state modifications (placeholder, needs interpreter) - ChemistryImpl: container for atoms, molecules, and reactions - CompartmentImpl: biological compartment with flows, concentrations, reactions - CompartmentTreeImpl: hierarchical compartment topology (simulation) - WorldStateImpl: multi-compartment concentration storage (simulation) - StateImpl: single-compartment concentrations - ReferenceSimulatorImpl: basic single-compartment simulator - WorldSimulatorImpl: multi-compartment simulator with flows
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
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
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
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).
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
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
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
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)
¶
set(compartment, molecule, value)
¶
get_compartment(compartment)
¶
get_multiplicity(compartment)
¶
set_multiplicity(compartment, value)
¶
total_molecules(compartment, molecule)
¶
copy()
¶
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
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
MockDat
¶
Lightweight mock DAT for hydrating entities without a real DAT.
Used when creating entities from YAML specs that don't have backing DAT files. Provides the minimal interface needed by Entity.
Source code in src/alienbio/infra/entity.py
AtomImpl
¶
Implementation: A chemical element.
Atoms are the building blocks of molecules. They are essentially constants representing chemical elements with their properties.
Attributes:
| Name | Type | Description |
|---|---|---|
symbol |
str
|
Chemical symbol (1-2 letters): 'C', 'H', 'O', 'Na' |
name |
str
|
Human-readable name: 'Carbon', 'Hydrogen' |
atomic_weight |
float
|
Atomic mass in atomic mass units |
Source code in src/alienbio/bio/atom.py
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.
__init__(symbol, name, atomic_weight)
¶
Initialize an atom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Chemical symbol (1-2 letters) |
required |
name
|
str
|
Human-readable English name |
required |
atomic_weight
|
float
|
Atomic mass in atomic mass units |
required |
Source code in src/alienbio/bio/atom.py
__eq__(other)
¶
__hash__()
¶
__repr__()
¶
MoleculeImpl
¶
Bases: Entity
Implementation: A molecule in the biological system.
Molecules are composed of atoms and participate in reactions.
Attributes:
| Name | Type | Description |
|---|---|---|
atoms |
Dict[AtomImpl, int]
|
Atom composition as {AtomImpl: count} |
bdepth |
int
|
Biosynthetic depth (0 = primitive, higher = more complex) |
name |
str
|
Human-readable name (e.g., 'glucose', 'water') |
symbol |
str
|
Chemical formula derived from atoms (e.g., 'C6H12O6', 'H2O') |
molecular_weight |
float
|
Computed from atom weights |
Source code in src/alienbio/bio/molecule.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 | |
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'.
Atoms are ordered by Hill system: C first, then H, then alphabetically.
molecular_weight
property
¶
Molecular mass computed from atom weights.
__init__(local_name, *, parent=None, dat=None, description='', atoms=None, bdepth=0, name=None)
¶
Initialize a molecule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_name
|
str
|
Local name within parent (used as entity identifier) |
required |
parent
|
Optional[Entity]
|
Link to containing entity |
None
|
dat
|
Optional[Dat]
|
DAT anchor for root molecules |
None
|
description
|
str
|
Human-readable description |
''
|
atoms
|
Optional[Dict[AtomImpl, int]]
|
Atom composition as {AtomImpl: count} |
None
|
bdepth
|
int
|
Biosynthetic depth (0 = primitive) |
0
|
name
|
Optional[str]
|
Human-readable name (defaults to local_name) |
None
|
Source code in src/alienbio/bio/molecule.py
hydrate(data, *, dat=None, parent=None, local_name=None)
classmethod
¶
Create a Molecule from a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict with optional keys: name, bdepth, atoms, description |
required |
dat
|
Optional[Dat]
|
DAT anchor (if root entity) |
None
|
parent
|
Optional[Entity]
|
Parent entity (if child) |
None
|
local_name
|
Optional[str]
|
Override name (defaults to data["name"]) |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
New MoleculeImpl instance |
Source code in src/alienbio/bio/molecule.py
attributes()
¶
Semantic content of this molecule.
Source code in src/alienbio/bio/molecule.py
__repr__()
¶
Full representation.
Source code in src/alienbio/bio/molecule.py
ReactionImpl
¶
Bases: Entity
Implementation: A reaction transforming reactants into products.
Reactions define transformations in the biological system. Each reaction has: - reactants: molecules consumed (with stoichiometric coefficients) - products: molecules produced (with stoichiometric coefficients) - rate: constant or function determining reaction speed
Example
A + 2B -> C with rate 0.1¶
reaction = ReactionImpl( "r1", reactants={mol_a: 1, mol_b: 2}, products={mol_c: 1}, rate=0.1, parent=chemistry, )
Source code in src/alienbio/bio/reaction.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
reactants
property
¶
Reactant molecules and their stoichiometric coefficients.
products
property
¶
Product molecules and their stoichiometric coefficients.
rate
property
¶
Reaction rate (constant or function).
name
property
¶
Human-readable name (same as local_name).
symbol
property
¶
Formula string: 'glucose + ATP -> G6P + ADP'.
__init__(name, *, reactants=None, products=None, rate=1.0, parent=None, dat=None, description='')
¶
Initialize a reaction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Local name within parent |
required |
reactants
|
Optional[Dict[Molecule, float]]
|
Dict mapping molecules to stoichiometric coefficients |
None
|
products
|
Optional[Dict[Molecule, float]]
|
Dict mapping molecules to stoichiometric coefficients |
None
|
rate
|
RateValue
|
Reaction rate (constant float or function of State) |
1.0
|
parent
|
Optional[Entity]
|
Link to containing entity |
None
|
dat
|
Optional[Dat]
|
DAT anchor for root reactions |
None
|
description
|
str
|
Human-readable description |
''
|
Source code in src/alienbio/bio/reaction.py
hydrate(data, *, molecules, dat=None, parent=None, local_name=None)
classmethod
¶
Create a Reaction from a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict with keys: reactants, products, rate, name, description |
required |
molecules
|
dict[str, 'MoleculeImpl']
|
Dict mapping molecule names to MoleculeImpl instances |
required |
dat
|
Optional[Dat]
|
DAT anchor (if root entity) |
None
|
parent
|
Optional[Entity]
|
Parent entity (if child) |
None
|
local_name
|
Optional[str]
|
Override name (defaults to data key) |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
New ReactionImpl instance |
Source code in src/alienbio/bio/reaction.py
set_rate(rate)
¶
get_rate(state)
¶
Get the effective rate for a given state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
State
|
Current system state |
required |
Returns:
| Type | Description |
|---|---|
float
|
Rate value (calls rate function if rate is callable) |
Source code in src/alienbio/bio/reaction.py
add_reactant(molecule, coefficient=1.0)
¶
add_product(molecule, coefficient=1.0)
¶
attributes()
¶
Semantic content of this reaction.
Source code in src/alienbio/bio/reaction.py
__repr__()
¶
Full representation.
Source code in src/alienbio/bio/reaction.py
Flow
¶
Bases: ABC
Abstract base class for all flows.
Flows move molecules (or instances) between compartments. Each flow is anchored to an origin compartment.
Subclasses: - MembraneFlow: transport across parent-child membrane with stoichiometry - GeneralFlow: arbitrary state modifications (placeholder)
Common interface: - origin: the compartment where this flow is anchored - name: human-readable identifier - compute_flux(): calculate transfer rate - apply(): modify state based on flux
Source code in src/alienbio/bio/flow.py
origin
property
¶
The origin compartment (where this flow is anchored).
name
property
¶
Human-readable name.
is_membrane_flow
abstractmethod
property
¶
True if this is a membrane flow (origin ↔ parent).
is_general_flow
abstractmethod
property
¶
True if this is a general flow (arbitrary edits).
__init__(origin, name='')
¶
Initialize base flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
CompartmentId
|
The origin compartment (where this flow is anchored) |
required |
name
|
str
|
Human-readable name for this flow |
''
|
Source code in src/alienbio/bio/flow.py
compute_flux(state, tree)
abstractmethod
¶
Compute flux for this flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
Current world state with concentrations |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
Returns:
| Type | Description |
|---|---|
float
|
Flux value (positive = into origin for membrane flows) |
Source code in src/alienbio/bio/flow.py
apply(state, tree, dt=1.0)
abstractmethod
¶
Apply this flow to the state (mutates in place).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
World state to modify |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
dt
|
float
|
Time step |
1.0
|
Source code in src/alienbio/bio/flow.py
MembraneFlow
¶
Bases: Flow
Transport across parent-child membrane with stoichiometry.
A MembraneFlow moves molecules across the membrane between a compartment and its parent. Like reactions, it can specify stoichiometry for multiple molecules moving together.
The rate equation determines how many "events" occur per unit time. Each event moves the specified stoichiometry of molecules.
Direction convention: - Positive stoichiometry = molecules move INTO the origin (from parent) - Negative stoichiometry = molecules move OUT OF origin (into parent)
Example
Sodium-glucose cotransporter (SGLT1)¶
Moves 2 Na+ and 1 glucose into the cell together¶
sglt1 = MembraneFlow( origin=cell_id, stoichiometry={"sodium": 2, "glucose": 1}, rate_constant=10.0, name="sglt1", )
Sodium-potassium pump (Na+/K+-ATPase)¶
Pumps 3 Na+ out, 2 K+ in per ATP hydrolyzed¶
na_k_pump = MembraneFlow( origin=cell_id, stoichiometry={"sodium": -3, "potassium": 2, "atp": -1, "adp": 1}, rate_constant=5.0, name="na_k_atpase", )
Source code in src/alienbio/bio/flow.py
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
stoichiometry
property
¶
Molecules and counts moved per event {molecule: count}.
rate_constant
property
¶
Base rate of events per unit time.
is_membrane_flow
property
¶
True - this is a membrane flow.
is_general_flow
property
¶
False - this is not a general flow.
__init__(origin, stoichiometry, rate_constant=1.0, rate_fn=None, name='')
¶
Initialize a membrane flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
CompartmentId
|
The compartment whose membrane this flow crosses |
required |
stoichiometry
|
Dict[str, float]
|
Molecules and counts moved per event {molecule: count} Positive = into origin, negative = out of origin |
required |
rate_constant
|
float
|
Base rate of events per unit time |
1.0
|
rate_fn
|
Optional[Callable[..., float]]
|
Optional custom rate function |
None
|
name
|
str
|
Human-readable name for this flow |
''
|
Source code in src/alienbio/bio/flow.py
compute_flux(state, tree)
¶
Compute the rate of events (not molecules).
Returns the number of "transport events" per unit time. Multiply by stoichiometry to get actual molecule transfer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
Current world state with concentrations |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
Returns:
| Type | Description |
|---|---|
float
|
Event rate (events per unit time) |
Source code in src/alienbio/bio/flow.py
apply(state, tree, dt=1.0)
¶
Apply this flow to the state (mutates in place).
Computes event rate, then applies stoichiometry to both origin and parent compartments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
World state to modify |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
dt
|
float
|
Time step |
1.0
|
Source code in src/alienbio/bio/flow.py
attributes()
¶
Semantic content for serialization.
Source code in src/alienbio/bio/flow.py
__repr__()
¶
Full representation.
GeneralFlow
¶
Bases: Flow
Arbitrary state modifications (placeholder).
GeneralFlow is a catch-all for flows that don't fit the MembraneFlow pattern. This includes: - Lateral flows between siblings - Instance transfers (RBCs moving between compartments) - Any other arbitrary edits to the system
NOTE: This is currently a placeholder. Full implementation will require a more general interpreter to handle arbitrary state modifications specified via Expr or similar.
For now, GeneralFlow stores an apply_fn that takes state and tree and performs arbitrary modifications.
Source code in src/alienbio/bio/flow.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
description
property
¶
Description of what this flow does.
is_membrane_flow
property
¶
False - this is not a membrane flow.
is_general_flow
property
¶
True - this is a general flow.
__init__(origin, apply_fn=None, name='', description='')
¶
Initialize a general flow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
CompartmentId
|
The compartment where this flow is conceptually anchored |
required |
apply_fn
|
Optional[Callable[[WorldStateImpl, CompartmentTreeImpl, float], None]]
|
Function (state, tree, dt) -> None that modifies state |
None
|
name
|
str
|
Human-readable name for this flow |
''
|
description
|
str
|
Description of what this flow does |
''
|
NOTE: This is a placeholder. Full implementation will need a more general interpreter to support Expr-based specifications.
Source code in src/alienbio/bio/flow.py
compute_flux(state, tree)
¶
General flows don't have a simple flux concept.
Returns 0.0 as placeholder. The actual work happens in apply().
apply(state, tree, dt=1.0)
¶
Apply this flow to the state (mutates in place).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
World state to modify |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
dt
|
float
|
Time step |
1.0
|
Source code in src/alienbio/bio/flow.py
attributes()
¶
Semantic content for serialization.
NOTE: apply_fn cannot be serialized. Full implementation will need Expr-based specification that can be serialized.
Source code in src/alienbio/bio/flow.py
__repr__()
¶
ChemistryImpl
¶
Bases: Entity
Implementation: Container for a chemical system.
Chemistry holds atoms, molecules, and reactions as public dict attributes. These are indexed by: - atoms: by symbol ("C", "H", "O") - molecules: by name ("glucose", "atp") - reactions: by name ("glycolysis_step1", "atp_synthesis")
Chemistry is conceptually immutable - built complete via constructor, though the dicts are technically mutable for flexibility.
Example
chem = ChemistryImpl( "glycolysis", atoms={"C": carbon, "H": hydrogen, "O": oxygen}, molecules={"glucose": glucose_mol, "atp": atp_mol}, reactions={"step1": reaction1, "step2": reaction2}, dat=dat, )
Direct access to contents¶
chem.atoms["C"] # -> carbon atom chem.molecules["glucose"] # -> glucose molecule chem.reactions["step1"] # -> reaction1
Source code in src/alienbio/bio/chemistry.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 | |
__init__(name, *, atoms=None, molecules=None, reactions=None, parent=None, dat=None, description='')
¶
Initialize a chemistry container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Local name within parent |
required |
atoms
|
Optional[Dict[str, AtomImpl]]
|
Dict of atoms by symbol |
None
|
molecules
|
Optional[Dict[str, MoleculeImpl]]
|
Dict of molecules by name |
None
|
reactions
|
Optional[Dict[str, ReactionImpl]]
|
Dict of reactions by name |
None
|
parent
|
Optional[Entity]
|
Link to containing entity |
None
|
dat
|
Optional[Dat]
|
DAT anchor for root chemistry entities |
None
|
description
|
str
|
Human-readable description |
''
|
Source code in src/alienbio/bio/chemistry.py
hydrate(data, *, dat=None, parent=None, local_name=None)
classmethod
¶
Create a Chemistry from a dict.
Recursively hydrates molecules and reactions from nested dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict with keys: molecules, reactions, atoms, description Each molecule/reaction can be a dict that gets hydrated. |
required |
dat
|
Optional[Dat]
|
DAT anchor (if root entity) |
None
|
parent
|
Optional[Entity]
|
Parent entity (if child) |
None
|
local_name
|
Optional[str]
|
Override name |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
New ChemistryImpl with hydrated molecules and reactions |
Source code in src/alienbio/bio/chemistry.py
validate()
¶
Validate the chemistry for consistency.
Checks: - All molecule atoms are atoms in this chemistry - All reaction reactants/products are molecules in this chemistry
Returns:
| Type | Description |
|---|---|
list[str]
|
List of error messages (empty if valid) |
Source code in src/alienbio/bio/chemistry.py
attributes()
¶
Semantic content of this chemistry.
Source code in src/alienbio/bio/chemistry.py
__repr__()
¶
Full representation.
CompartmentImpl
¶
Bases: Entity
Implementation: A compartment in the biological hierarchy.
Compartments represent biological regions: organisms, organs, cells, organelles. Each compartment can contain child compartments, forming a tree structure.
The compartment entity specifies: - Structure: kind and child compartments - Initial state: multiplicity and concentrations - Behavior: membrane flows and active reactions
This entity tree serves as both the initial WorldState specification and the complete simulation configuration.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
Type of compartment ("organism", "organ", "cell", "organelle", etc.) |
multiplicity |
float
|
Number of instances (default 1.0) |
volume |
float
|
Volume of each instance in arbitrary units (default 1.0) |
concentrations |
Dict[str, float]
|
Initial molecule concentrations {molecule_name: value} |
membrane_flows |
List[GeneralFlow]
|
Flows across this compartment's membrane |
active_reactions |
Optional[List[str]]
|
Reactions active here (None = all from chemistry) |
children |
List[CompartmentImpl]
|
Child compartments |
Example
Define an organism with cells¶
organism = CompartmentImpl( "body", volume=70000, # 70 liters in mL kind="organism", concentrations={"glucose": 5.0, "oxygen": 2.0}, )
liver = CompartmentImpl( "liver", volume=1500, # 1.5 liters in mL parent=organism, kind="organ", )
hepatocyte = CompartmentImpl( "hepatocyte", volume=3e-9, # ~3000 cubic microns in mL parent=liver, kind="cell", multiplicity=1e9, # 1 billion liver cells concentrations={"glucose": 1.0}, membrane_flows=[glucose_uptake_flow], active_reactions=["glycolysis", "gluconeogenesis"], )
Source code in src/alienbio/bio/compartment.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
kind
property
¶
Type of compartment: 'organism', 'organ', 'cell', 'organelle'.
multiplicity
property
¶
Number of instances of this compartment.
volume
property
¶
Volume of each instance in arbitrary units.
concentrations
property
¶
Initial molecule concentrations {name: value}.
membrane_flows
property
¶
Flows across this compartment's membrane.
active_reactions
property
¶
Reaction names active in this compartment (None = all).
children
property
¶
Child compartments.
__init__(local_name, *, volume, parent=None, dat=None, description='', kind='compartment', multiplicity=1.0, concentrations=None, membrane_flows=None, active_reactions=None)
¶
Initialize a compartment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
local_name
|
str
|
Local name within parent (used as entity identifier) |
required |
volume
|
float
|
Volume of each instance (required - no default, scale depends on use case) |
required |
parent
|
Optional[Entity]
|
Parent compartment (or None for root) |
None
|
dat
|
Optional[Dat]
|
DAT anchor for root compartments |
None
|
description
|
str
|
Human-readable description |
''
|
kind
|
str
|
Type of compartment ("organism", "organ", "cell", "organelle") |
'compartment'
|
multiplicity
|
float
|
Number of instances of this compartment (default 1.0) |
1.0
|
concentrations
|
Optional[Dict[str, float]]
|
Initial molecule concentrations {name: value} |
None
|
membrane_flows
|
Optional[List[GeneralFlow]]
|
Flows across this compartment's membrane |
None
|
active_reactions
|
Optional[List[str]]
|
Reaction names active here (None = all from chemistry) |
None
|
Source code in src/alienbio/bio/compartment.py
add_child(child)
¶
add_flow(flow)
¶
set_concentration(molecule, value)
¶
set_multiplicity(value)
¶
set_volume(value)
¶
set_active_reactions(reactions)
¶
all_descendants()
¶
Get all descendant compartments (depth-first).
Source code in src/alienbio/bio/compartment.py
all_compartments()
¶
depth()
¶
Get depth in tree (root = 0).
attributes()
¶
Semantic content for serialization.
Source code in src/alienbio/bio/compartment.py
__repr__()
¶
CompartmentTreeImpl
¶
Implementation: Hierarchical structure of compartments.
Represents the tree topology of compartments (organism > organ > cell > organelle). Stored separately from concentrations to allow efficient structure updates.
The tree is represented with: - parents: List[Optional[CompartmentId]] - parent[child] = parent_id or None for root - children: Dict[CompartmentId, List[CompartmentId]] - children by parent
Compartments are identified by integer IDs (0, 1, 2, ...).
Example
Create tree: organism with two organs¶
tree = CompartmentTreeImpl() organism = tree.add_root("organism") # 0 organ_a = tree.add_child(organism, "organ_a") # 1 organ_b = tree.add_child(organism, "organ_b") # 2 cell_1 = tree.add_child(organ_a, "cell_1") # 3
print(tree.parent(cell_1)) # 1 (organ_a) print(tree.children(organism)) # [1, 2]
Source code in src/alienbio/bio/compartment_tree.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
num_compartments
property
¶
Total number of compartments.
__init__()
¶
Initialize empty compartment tree.
Source code in src/alienbio/bio/compartment_tree.py
parent(child)
¶
children(parent)
¶
root()
¶
is_root(compartment)
¶
name(compartment)
¶
add_root(name='root')
¶
Add the root compartment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable name for the root |
'root'
|
Returns:
| Type | Description |
|---|---|
CompartmentId
|
The root compartment ID (always 0) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If root already exists |
Source code in src/alienbio/bio/compartment_tree.py
add_child(parent, name='')
¶
Add a child compartment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent
|
CompartmentId
|
Parent compartment ID |
required |
name
|
str
|
Human-readable name for the child |
''
|
Returns:
| Type | Description |
|---|---|
CompartmentId
|
The new compartment ID |
Source code in src/alienbio/bio/compartment_tree.py
ancestors(compartment)
¶
Get all ancestors from compartment to root (inclusive).
Source code in src/alienbio/bio/compartment_tree.py
descendants(compartment)
¶
Get all descendants of a compartment (not including self).
Source code in src/alienbio/bio/compartment_tree.py
depth(compartment)
¶
Get depth of compartment (root = 0).
to_dict()
¶
from_dict(data)
classmethod
¶
Deserialize tree structure.
Source code in src/alienbio/bio/compartment_tree.py
__repr__()
¶
__str__()
¶
Tree visualization.
Source code in src/alienbio/bio/compartment_tree.py
WorldStateImpl
¶
Implementation: Dense concentration storage for all compartments.
Stores concentrations as a flat array indexed by [compartment, molecule]. Also stores multiplicity (instance count) per compartment. Dense storage is efficient for small to medium molecule counts.
Each WorldState holds a reference to its CompartmentTree. Multiple states share the same tree reference (immutable sharing) until topology changes. When topology changes (e.g., cell division), a new tree is created.
Attributes:
| Name | Type | Description |
|---|---|---|
tree |
CompartmentTreeImpl
|
The CompartmentTree this state belongs to (shared reference) |
num_compartments |
int
|
Number of compartments (derived from tree) |
num_molecules |
int
|
Number of molecules in vocabulary |
concentrations |
int
|
Flat array [num_compartments * num_molecules] |
multiplicities |
int
|
Array [num_compartments] - instance count per compartment |
The concentration array is row-major: concentrations[comp * num_molecules + mol]
Multiplicity represents how many instances of this compartment exist. For example, "arterial red blood cells" might have multiplicity 1e6. Concentrations are per-instance; total molecules = multiplicity * concentration.
Example
tree = CompartmentTreeImpl() root = tree.add_root("organism") cell = tree.add_child(root, "cell") state = WorldStateImpl(tree=tree, num_molecules=50)
Set concentrations¶
state.set(compartment=cell, molecule=5, value=1.0) print(state.get(cell, 5)) # 1.0
Set multiplicity (number of cells)¶
state.set_multiplicity(cell, 1000.0) print(state.get_multiplicity(cell)) # 1000.0
Source code in src/alienbio/bio/world_state.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
tree
property
¶
The compartment tree this state belongs to (shared reference).
num_compartments
property
¶
Number of compartments (from tree).
num_molecules
property
¶
Number of molecules in vocabulary.
__init__(tree, num_molecules, initial_concentrations=None, initial_multiplicities=None)
¶
Initialize world state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
CompartmentTreeImpl
|
CompartmentTree defining the topology (shared reference) |
required |
num_molecules
|
int
|
Number of molecules in vocabulary |
required |
initial_concentrations
|
Optional[List[float]]
|
Optional flat array of initial concentrations |
None
|
initial_multiplicities
|
Optional[List[float]]
|
Optional array of initial multiplicities per compartment |
None
|
Source code in src/alienbio/bio/world_state.py
get(compartment, molecule)
¶
set(compartment, molecule, value)
¶
Set concentration of molecule in compartment.
get_compartment(compartment)
¶
Get all concentrations for a compartment.
set_compartment(compartment, values)
¶
Set all concentrations for a compartment.
Source code in src/alienbio/bio/world_state.py
get_multiplicity(compartment)
¶
set_multiplicity(compartment, value)
¶
get_all_multiplicities()
¶
total_molecules(compartment, molecule)
¶
Get total molecules = multiplicity * concentration.
copy()
¶
Create a copy of this state (shares tree reference).
Source code in src/alienbio/bio/world_state.py
as_array()
¶
Get concentrations as 2D numpy array [compartments x molecules].
Returns a view if numpy is available, otherwise a list of lists.
Source code in src/alienbio/bio/world_state.py
from_array(arr)
¶
Set concentrations from 2D array [compartments x molecules].
Source code in src/alienbio/bio/world_state.py
__repr__()
¶
__str__()
¶
Short representation with summary stats.
Source code in src/alienbio/bio/world_state.py
StateImpl
¶
Implementation: Concentrations of molecules at a point in time.
State is essentially a dict mapping molecules to concentration values. It's tied to a Chemistry which defines the valid molecules.
Attributes:
| Name | Type | Description |
|---|---|---|
chemistry |
ChemistryImpl
|
The Chemistry this state belongs to |
concentrations |
ChemistryImpl
|
Dict mapping molecule names to concentration values |
Example
state = StateImpl(chemistry) state["glucose"] = 1.0 state["atp"] = 0.5 print(state["glucose"]) # 1.0
Source code in src/alienbio/bio/state.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
chemistry
property
¶
The Chemistry this state belongs to.
__init__(chemistry, initial=None)
¶
Initialize state for a chemistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chemistry
|
ChemistryImpl
|
The Chemistry defining valid molecules |
required |
initial
|
Optional[Dict[str, float]]
|
Optional dict of initial concentrations by molecule name |
None
|
Source code in src/alienbio/bio/state.py
__getitem__(key)
¶
__setitem__(key, value)
¶
Set concentration by molecule name.
__contains__(key)
¶
__iter__()
¶
__len__()
¶
get(key, default=0.0)
¶
get_molecule(molecule)
¶
set_molecule(molecule, value)
¶
items()
¶
copy()
¶
to_dict()
¶
from_dict(chemistry, data)
classmethod
¶
__repr__()
¶
__str__()
¶
Short representation.
Source code in src/alienbio/bio/state.py
ReferenceSimulatorImpl
¶
Bases: SimulatorBase
Reference implementation: Basic simulator applying reactions once per step.
This is the reference implementation for testing and validation. For each reaction: - Compute rate (constant or from rate function) - Subtract rate * coefficient from each reactant - Add rate * coefficient to each product
Note: This is a simple Euler-style implementation. For more accurate kinetics, use specialized simulators (JAX, etc.).
Source code in src/alienbio/bio/simulator.py
step(state)
¶
Apply all reactions once.
Source code in src/alienbio/bio/simulator.py
SimulatorBase
¶
Bases: ABC
Abstract base class for simulators.
A Simulator advances the state of a chemical system over time. Subclasses implement the actual simulation algorithm.
The basic interface: - step(state) -> state: advance one time step - run(state, n) -> [states]: run n steps, return timeline
Example
sim = MySimulator(chemistry, dt=0.01) timeline = sim.run(initial_state, steps=100)
Source code in src/alienbio/bio/simulator.py
chemistry
property
¶
The Chemistry being simulated.
dt
property
¶
Time step size.
__init__(chemistry, dt=1.0)
¶
Initialize simulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chemistry
|
ChemistryImpl
|
The Chemistry to simulate |
required |
dt
|
float
|
Time step size (default 1.0) |
1.0
|
step(state)
abstractmethod
¶
run(state, steps)
¶
Run simulation for multiple steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateImpl
|
Initial state |
required |
steps
|
int
|
Number of steps to run |
required |
Returns:
| Type | Description |
|---|---|
List[StateImpl]
|
Timeline of states (length = steps + 1, including initial) |
Source code in src/alienbio/bio/simulator.py
WorldSimulatorImpl
¶
Implementation: Multi-compartment simulator with reactions and flows.
Simulates a world with: - Multiple compartments organized in a tree (organism > organ > cell) - Reactions that occur within compartments - Flows that transport molecules across compartment membranes
Each step: 1. Compute all reaction rates (per compartment) 2. Compute all flow fluxes (between parent-child pairs) 3. Apply reactions (modify concentrations within compartments) 4. Apply flows (transfer molecules across membranes)
Example
Build world¶
tree = CompartmentTreeImpl() organism = tree.add_root("organism") cell = tree.add_child(organism, "cell")
Define reactions and flows¶
reactions = [ReactionSpec("r1", {0: 1}, {1: 1}, rate_constant=0.1)] flows = [GeneralFlow(child=cell, molecule=0, rate_constant=0.05)]
Create simulator¶
sim = WorldSimulatorImpl( tree=tree, reactions=reactions, flows=flows, num_molecules=10, dt=0.1, )
Run simulation¶
state = WorldStateImpl(tree=tree, num_molecules=10) state.set(organism, 0, 100.0) # initial concentration history = sim.run(state, steps=1000, sample_every=100)
All states in history share the same tree reference¶
assert history[0].tree is history[-1].tree
Source code in src/alienbio/bio/world_simulator.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
tree
property
¶
Compartment topology.
reactions
property
¶
Reaction specifications.
flows
property
¶
Flow specifications.
num_molecules
property
¶
Number of molecules in vocabulary.
dt
property
¶
Time step size.
__init__(tree, reactions, flows, num_molecules, dt=1.0)
¶
Initialize world simulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
reactions
|
List[ReactionSpec]
|
List of reaction specifications |
required |
flows
|
List[GeneralFlow]
|
List of flow specifications |
required |
num_molecules
|
int
|
Number of molecules in vocabulary |
required |
dt
|
float
|
Time step size |
1.0
|
Source code in src/alienbio/bio/world_simulator.py
step(state)
¶
Advance simulation by one time step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
Current world state |
required |
Returns:
| Type | Description |
|---|---|
WorldStateImpl
|
New state after applying reactions and flows |
Source code in src/alienbio/bio/world_simulator.py
run(state, steps, sample_every=None)
¶
Run simulation for multiple steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
WorldStateImpl
|
Initial state (not modified) |
required |
steps
|
int
|
Number of steps to run |
required |
sample_every
|
Optional[int]
|
If set, only keep every Nth state (plus final) |
None
|
Returns:
| Type | Description |
|---|---|
List[WorldStateImpl]
|
List of states (timeline) |
Source code in src/alienbio/bio/world_simulator.py
from_chemistry(chemistry, tree, flows=None, dt=1.0)
classmethod
¶
Create simulator from a Chemistry and compartment tree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chemistry
|
ChemistryImpl
|
Chemistry containing molecules and reactions |
required |
tree
|
CompartmentTreeImpl
|
Compartment topology |
required |
flows
|
Optional[List[GeneralFlow]]
|
Optional list of flows (empty if not provided) |
None
|
dt
|
float
|
Time step |
1.0
|
Returns:
| Type | Description |
|---|---|
WorldSimulatorImpl
|
Configured WorldSimulatorImpl |
Source code in src/alienbio/bio/world_simulator.py
__repr__()
¶
Full representation.
Source code in src/alienbio/bio/world_simulator.py
ReactionSpec
¶
Specification for a reaction in the world simulator.
Reactions occur within a single compartment and transform molecules. This is a lightweight spec using molecule IDs for efficient simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
Human-readable name |
|
reactants |
Dict[MoleculeId, stoichiometry] |
|
products |
Dict[MoleculeId, stoichiometry] |
|
rate_constant |
Base reaction rate |
|
compartments |
Which compartments this reaction occurs in (None = all) |
Source code in src/alienbio/bio/world_simulator.py
BioSystem
¶
A complete biological system: chemistry + state + simulator.
BioSystem wraps a Chemistry (molecules and reactions), a State (concentrations), and a Simulator into a single convenient object.
Example
system = BioSystem(chemistry, state) timeline = system.run(steps=100)
With random initial concentrations¶
system = BioSystem.random(chemistry, seed=42)
Source code in src/alienbio/bio/biosystem.py
random(chemistry, *, seed=None, min_conc=0.0, max_conc=10.0, dt=1.0)
classmethod
¶
Create a BioSystem with random initial concentrations.
Source code in src/alienbio/bio/biosystem.py
step()
¶
run(steps)
¶
Run simulation for multiple steps.
Updates internal state to the final state. Returns the full timeline including initial state.
Source code in src/alienbio/bio/biosystem.py
StabilityResult
dataclass
¶
Result of a stability check on a timeline.
Source code in src/alienbio/bio/equilibrium.py
HomeostasisTarget
dataclass
¶
A target concentration range for a molecule.
Source code in src/alienbio/bio/equilibrium.py
AgentInterface
¶
Agent-facing API for interacting with a BioSystem.
Bundles all available measurements and actions with text descriptions. Provides a uniform interface for agents to query and modify the system.
Example
interface = AgentInterface(system) conc = interface.measure("concentration", molecule="A") interface.act("add_molecule", molecule="A", amount=5.0)
Source code in src/alienbio/bio/agent_interface.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
available_measurements()
¶
List all available measurements with descriptions.
Source code in src/alienbio/bio/agent_interface.py
available_actions()
¶
List all available actions with descriptions.
Source code in src/alienbio/bio/agent_interface.py
measure(name, **params)
¶
Take a measurement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Measurement name (e.g., "concentration") |
required |
**params
|
Any
|
Measurement parameters (e.g., molecule="A") |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
Measurement result (type depends on measurement) |
Raises:
| Type | Description |
|---|---|
KeyError
|
If measurement name is unknown |
Source code in src/alienbio/bio/agent_interface.py
act(name, **params)
¶
Execute an action.
For state-modifying actions (add_molecule, remove_molecule, set_concentration), the system's state is updated in place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Action name (e.g., "add_molecule") |
required |
**params
|
Any
|
Action parameters (e.g., molecule="A", amount=5.0) |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The new state after the action |
Raises:
| Type | Description |
|---|---|
KeyError
|
If action name is unknown |
Source code in src/alienbio/bio/agent_interface.py
describe()
¶
Generate a text description of the interface for an agent.
Source code in src/alienbio/bio/agent_interface.py
MeasurementSpec
dataclass
¶
ConcentrationMeasurement
¶
Measure the concentration of a molecule in the current state.
Source code in src/alienbio/bio/measurements.py
AllConcentrationsMeasurement
¶
Measure all concentrations in the current state.
Source code in src/alienbio/bio/measurements.py
RateMeasurement
¶
Measure the effective rate of a reaction at the current state.
Source code in src/alienbio/bio/measurements.py
measure(state, reaction_name)
¶
Return the effective rate of the named reaction.
MoleculeCountMeasurement
¶
Measure the number of molecules in the chemistry.
Source code in src/alienbio/bio/measurements.py
ReactionCountMeasurement
¶
Measure the number of reactions in the chemistry.
Source code in src/alienbio/bio/measurements.py
ActionSpec
dataclass
¶
AddMoleculeAction
¶
Add a specified amount of a molecule to the state.
Source code in src/alienbio/bio/actions.py
apply(state, molecule, amount)
¶
Add amount to the named molecule's concentration.
Returns a new state (does not modify the original).
Source code in src/alienbio/bio/actions.py
RemoveMoleculeAction
¶
Remove a specified amount of a molecule from the state.
Source code in src/alienbio/bio/actions.py
apply(state, molecule, amount)
¶
Remove amount from the named molecule's concentration.
Clamps at zero. Returns a new state.
Source code in src/alienbio/bio/actions.py
SetConcentrationAction
¶
Set a molecule's concentration to a specific value.
Source code in src/alienbio/bio/actions.py
apply(state, molecule, value)
¶
Set the named molecule to the specified concentration.
Returns a new state.
AdjustRateAction
¶
Adjust a reaction's rate constant.
Source code in src/alienbio/bio/actions.py
apply(state, reaction_name, factor)
¶
Scale the named reaction's rate by factor.
Modifies the reaction in-place (rates are shared across states). Returns the same state unchanged (rate is on the reaction, not the state).
Source code in src/alienbio/bio/actions.py
Task
¶
Bases: ABC
Abstract base class for tasks.
A task defines: - A setup (preparing the system) - A goal description (what the agent should do) - Scoring criteria (how to evaluate the result)
Source code in src/alienbio/bio/task.py
name
abstractmethod
property
¶
Short identifier for the task.
description
abstractmethod
property
¶
Human-readable description of the goal.
score(interface, prediction)
abstractmethod
¶
Score the agent's prediction or action.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
'AgentInterface'
|
The agent interface (gives access to system) |
required |
prediction
|
Any
|
The agent's output |
required |
Returns:
| Type | Description |
|---|---|
TaskResult
|
TaskResult with score in [0, 1] and details dict |
Source code in src/alienbio/bio/task.py
PredictTask
¶
Bases: Task
Predict the concentration of a molecule after N simulation steps.
The agent must forecast what the concentration of a target molecule will be after the system runs for a specified number of steps.
Source code in src/alienbio/bio/task.py
score(interface, prediction)
¶
Score a concentration prediction.
Runs the system forward, compares prediction to actual. Score = max(0, 1 - |predicted - actual| / max(actual, tolerance)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
'AgentInterface'
|
Agent interface wrapping the system |
required |
prediction
|
float
|
Predicted concentration value |
required |
Returns:
| Type | Description |
|---|---|
TaskResult
|
TaskResult with score in [0, 1] |
Source code in src/alienbio/bio/task.py
TaskResult
dataclass
¶
ExperimentResult
dataclass
¶
DiagnoseTask
¶
Bases: Task
Identify which perturbation was applied to a diseased system.
The agent receives a diseased system and a list of candidate perturbations. It must identify which perturbation was actually applied.
Source code in src/alienbio/bio/diagnosis.py
score(interface, prediction)
¶
Score a diagnosis prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
'AgentInterface'
|
Agent interface (not used for scoring, but part of protocol) |
required |
prediction
|
int
|
Index into candidates list |
required |
Returns:
| Type | Description |
|---|---|
TaskResult
|
TaskResult with score 1.0 if correct, 0.0 if wrong |
Source code in src/alienbio/bio/diagnosis.py
CureTask
¶
Bases: Task
Restore a diseased system to healthy range.
The agent receives a diseased system and must use actions to bring concentrations back within the healthy baseline ranges.
Source code in src/alienbio/bio/diagnosis.py
score(interface, prediction=None)
¶
Score cure attempt by checking if system is healthy after recovery.
The agent should have already applied actions before score() is called. This method runs the system forward to allow actions to take effect, then checks whether concentrations are within healthy ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
'AgentInterface'
|
Agent interface wrapping the system |
required |
prediction
|
Any
|
Ignored (actions are applied directly) |
None
|
Returns:
| Type | Description |
|---|---|
TaskResult
|
TaskResult with score based on fraction of molecules in range |
Source code in src/alienbio/bio/diagnosis.py
TestSuite
dataclass
¶
A batch of experiments to run.
Pairs tasks with agent interfaces for batch execution.
Source code in src/alienbio/bio/harness.py
TestResults
dataclass
¶
Aggregated results from running a test suite.
Source code in src/alienbio/bio/harness.py
pass_rate
property
¶
Fraction of experiments scoring above threshold.
scores_by_task()
¶
to_dict()
¶
Export results as a serializable dict.
Source code in src/alienbio/bio/harness.py
to_json()
¶
from_dict(data)
classmethod
¶
Import results from a dict.
Source code in src/alienbio/bio/harness.py
AgentStats
dataclass
¶
ComparisonTable
dataclass
¶
Comparison of multiple agents.
Source code in src/alienbio/bio/comparison.py
QuiescenceTimeout
¶
HealthRange
dataclass
¶
Acceptable range for a molecule concentration.
Source code in src/alienbio/bio/disease.py
Baseline
dataclass
¶
Healthy baseline for a biological system.
Defines steady-state concentrations and acceptable ranges.
Source code in src/alienbio/bio/disease.py
is_healthy(concentrations)
¶
Check if all concentrations are within healthy ranges.
Source code in src/alienbio/bio/disease.py
Perturbation
dataclass
¶
A perturbation that creates disease from a healthy system.
Can alter reaction rates or remove reactions entirely.
Source code in src/alienbio/bio/disease.py
apply(system)
¶
Apply perturbation to a system (modifies in-place).
Source code in src/alienbio/bio/disease.py
Symptom
dataclass
¶
An observable symptom — a measurement outside healthy range.
Source code in src/alienbio/bio/disease.py
OrganSpec
dataclass
¶
Specification for an organ (compartment with reactions).
Source code in src/alienbio/bio/organ_generator.py
TransportLink
dataclass
¶
Organism
dataclass
¶
A generated multi-compartment organism.
Source code in src/alienbio/bio/organ_generator.py
PerturbationResult
dataclass
¶
Result of a perturbation experiment.
Source code in src/alienbio/bio/perturbation.py
DriftResult
dataclass
¶
Result of a reaction removal drift experiment.
Source code in src/alienbio/bio/perturbation.py
get_atom(symbol)
¶
Get an atom by its symbol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbol
|
str
|
Chemical symbol (e.g., 'C', 'H', 'Na') |
required |
Returns:
| Type | Description |
|---|---|
AtomImpl
|
The AtomImpl for that element |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the symbol is not in COMMON_ATOMS |
Source code in src/alienbio/bio/atom.py
compute_variance(timeline, window)
¶
Compute variance of each molecule over the last window steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeline
|
List[StateImpl]
|
List of states (length >= window) |
required |
window
|
int
|
Number of trailing steps to analyze |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dict mapping molecule name to variance of concentration |
Source code in src/alienbio/bio/equilibrium.py
check_stability(timeline, window=100, threshold=0.0001)
¶
Check whether a simulation has reached equilibrium.
Computes per-molecule variance over the trailing window. The system is considered stable when all variances are below the threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeline
|
List[StateImpl]
|
Full simulation timeline |
required |
window
|
int
|
Number of trailing steps to check |
100
|
threshold
|
float
|
Maximum allowed variance per molecule |
0.0001
|
Returns:
| Type | Description |
|---|---|
StabilityResult
|
StabilityResult with per-molecule variance and stability flag |
Source code in src/alienbio/bio/equilibrium.py
run_to_equilibrium(system, max_steps=10000, window=100, threshold=0.0001, check_interval=100)
¶
Run a BioSystem until equilibrium is reached or max_steps exceeded.
Runs in chunks of check_interval steps, checking stability after each
chunk. Returns the full timeline and the final stability result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
BioSystem to simulate |
required |
max_steps
|
int
|
Maximum total steps to run |
10000
|
window
|
int
|
Trailing window for variance check |
100
|
threshold
|
float
|
Variance threshold for stability |
0.0001
|
check_interval
|
int
|
Steps between stability checks |
100
|
Returns:
| Type | Description |
|---|---|
tuple[List[StateImpl], StabilityResult]
|
Tuple of (timeline, StabilityResult) |
Source code in src/alienbio/bio/equilibrium.py
find_unstable_rates(system, steps=1000, window=100, threshold=0.0001)
¶
Identify reactions whose rates may cause instability.
Runs the system, then for each reaction, checks if disabling it reduces the maximum variance. Returns reactions that contribute most to instability, mapped to their rate values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
BioSystem to analyze |
required |
steps
|
int
|
Steps to run for each test |
1000
|
window
|
int
|
Trailing window for stability check |
100
|
threshold
|
float
|
Variance threshold |
0.0001
|
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dict mapping reaction name to its rate constant for reactions |
Dict[str, float]
|
that contribute to instability |
Source code in src/alienbio/bio/equilibrium.py
check_homeostasis(state, targets)
¶
Check which homeostasis targets are met in the given state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
StateImpl
|
Current system state |
required |
targets
|
List[HomeostasisTarget]
|
List of homeostasis targets to check |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, bool]
|
Dict mapping molecule name to whether target is met |
Source code in src/alienbio/bio/equilibrium.py
run_experiment(interface, task, agent)
¶
Run an experiment: have the agent attempt the task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
'AgentInterface'
|
Agent-facing API for the system |
required |
task
|
'Task'
|
The task to evaluate |
required |
agent
|
AgentFn
|
A callable (interface, task) -> prediction |
required |
Returns:
| Type | Description |
|---|---|
ExperimentResult
|
ExperimentResult with score and details |
Source code in src/alienbio/bio/experiment.py
generate_diagnosis_task(system, perturbations, *, difficulty=1, seed=None)
¶
Generate a diagnosis task at a given difficulty level.
Difficulty controls the number of candidate perturbations: - difficulty=1: 2 candidates (easy — binary choice) - difficulty=2: 4 candidates - difficulty=N: min(2*N, len(perturbations)) candidates
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
The biological system |
required |
perturbations
|
List['Perturbation']
|
Pool of all possible perturbations |
required |
difficulty
|
int
|
Difficulty level (1 = easiest) |
1
|
seed
|
Optional[int]
|
Random seed for reproducibility |
None
|
Returns:
| Type | Description |
|---|---|
'DiagnoseTask'
|
DiagnoseTask with appropriate number of candidates |
Source code in src/alienbio/bio/difficulty.py
run_suite(suite, agent)
¶
Run all experiments in a test suite.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suite
|
TestSuite
|
The test suite to run |
required |
agent
|
AgentFn
|
Agent function to evaluate |
required |
Returns:
| Type | Description |
|---|---|
TestResults
|
TestResults with all scores |
Source code in src/alienbio/bio/harness.py
compare(results, *, threshold=0.5)
¶
Compare multiple agents' results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
Dict[str, TestResults]
|
Dict mapping agent_name -> TestResults |
required |
threshold
|
float
|
Score threshold for pass/fail (default 0.5) |
0.5
|
Returns:
| Type | Description |
|---|---|
ComparisonTable
|
ComparisonTable with ranked agent statistics |
Source code in src/alienbio/bio/comparison.py
compare_by_task(results, *, threshold=0.5)
¶
Compare agents grouped by task type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results
|
Dict[str, TestResults]
|
Dict mapping agent_name -> TestResults |
required |
threshold
|
float
|
Score threshold for pass/fail |
0.5
|
Returns:
| Type | Description |
|---|---|
Dict[str, ComparisonTable]
|
Dict mapping task_name -> ComparisonTable |
Source code in src/alienbio/bio/comparison.py
run_until_quiet(system, *, measure='all_concentrations', measure_params=None, delta=0.01, span=50, timeout=10000)
¶
Run simulation until a measurement stabilizes.
Runs the system step by step, checking whether the measurement
has changed by less than delta over the last span consecutive steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
The biological system to simulate |
required |
measure
|
str
|
Measurement name (via AgentInterface) |
'all_concentrations'
|
measure_params
|
Optional[Dict[str, Any]]
|
Parameters for the measurement |
None
|
delta
|
float
|
Maximum allowed change for stability |
0.01
|
span
|
int
|
Number of consecutive stable steps required |
50
|
timeout
|
int
|
Maximum steps before raising QuiescenceTimeout |
10000
|
Returns:
| Type | Description |
|---|---|
int
|
Number of steps taken to reach quiescence |
Raises:
| Type | Description |
|---|---|
QuiescenceTimeout
|
If quiescence not reached within timeout |
Source code in src/alienbio/bio/quiescence.py
generate_alien_name(base, *, seed=None)
¶
Generate an opaque alien name from a base string.
The name is deterministic given the same base and seed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
str
|
The original name to obfuscate |
required |
seed
|
Optional[int]
|
Random seed (defaults to hash of base) |
None
|
Returns:
| Type | Description |
|---|---|
str
|
An alien-sounding name |
Source code in src/alienbio/bio/skinning.py
generate_description(system, *, detail_level=2, name_map=None, seed=None)
¶
Generate a natural language description of a biological system.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
The system to describe |
required |
detail_level
|
int
|
1=minimal hints, 2=moderate, 3=full explanation |
2
|
name_map
|
Optional[Dict[str, str]]
|
Optional mapping from real names to alien names |
None
|
seed
|
Optional[int]
|
Random seed for name generation |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Description string using alien terminology |
Source code in src/alienbio/bio/skinning.py
generate_name_map(system, *, seed=None)
¶
Generate a mapping from real names to alien names.
Maps molecules and reactions to opaque alien names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
The system whose names to map |
required |
seed
|
Optional[int]
|
Random seed for deterministic names |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, str]
|
Dict mapping original names to alien names |
Source code in src/alienbio/bio/skinning.py
skin_task_description(task, name_map)
¶
Apply alien naming to a task description.
Replaces any known molecule/reaction names with alien equivalents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
'Task'
|
The task to skin |
required |
name_map
|
Dict[str, str]
|
Mapping from real names to alien names |
required |
Returns:
| Type | Description |
|---|---|
str
|
Task description with alien terminology |
Source code in src/alienbio/bio/skinning.py
check_no_earth_terms(text)
¶
Check that text contains no Earth biology terms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Text to check |
required |
Returns:
| Type | Description |
|---|---|
List[str]
|
List of Earth terms found (empty if clean) |
Source code in src/alienbio/bio/skinning.py
measure_baseline(system, steps=500)
¶
Run system to steady state and measure baseline concentrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
A healthy biological system |
required |
steps
|
int
|
Number of steps to reach steady state |
500
|
Returns:
| Type | Description |
|---|---|
Baseline
|
Baseline with steady-state concentrations and default ranges (±20%) |
Source code in src/alienbio/bio/disease.py
generate_perturbations(system, *, seed=None, kinds=None)
¶
Generate perturbations from a system's reactions.
Creates one perturbation per reaction: either rate_change or reaction_removal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
The healthy system to perturb |
required |
seed
|
Optional[int]
|
Random seed for reproducibility |
None
|
kinds
|
Optional[List[str]]
|
Allowed perturbation kinds (default: both) |
None
|
Returns:
| Type | Description |
|---|---|
List[Perturbation]
|
List of possible perturbations |
Source code in src/alienbio/bio/disease.py
detect_symptoms(concentrations, baseline)
¶
Detect symptoms by comparing concentrations to healthy ranges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
concentrations
|
Dict[str, float]
|
Current molecule concentrations |
required |
baseline
|
Baseline
|
Healthy baseline with ranges |
required |
Returns:
| Type | Description |
|---|---|
List[Symptom]
|
List of symptoms (molecules outside healthy range) |
Source code in src/alienbio/bio/disease.py
generate_organism(chemistry, *, num_organs=3, seed=None, dt=1.0, transport_rate=0.01)
¶
Generate a multi-compartment organism from a chemistry.
Creates an organism with: - A root compartment ("body") - Multiple organ compartments as children - Each organ gets a subset of reactions - Transport links between organs for shared molecules
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chemistry
|
ChemistryImpl
|
Chemistry defining molecules and reactions |
required |
num_organs
|
int
|
Number of organ compartments to create |
3
|
seed
|
Optional[int]
|
Random seed for reproducibility |
None
|
dt
|
float
|
Simulation time step |
1.0
|
transport_rate
|
float
|
Rate for inter-compartment transport |
0.01
|
Returns:
| Type | Description |
|---|---|
Organism
|
Organism with tree, state, simulator, and transport links |
Source code in src/alienbio/bio/organ_generator.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | |
inject_spike(system, molecule, amount, recovery_steps=50, tolerance=0.1)
¶
Inject a concentration spike and observe recovery.
Runs the system for recovery_steps, then injects a spike, then runs for another recovery_steps. Checks if the system returns to within tolerance of the pre-spike concentrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
BioSystem to perturb |
required |
molecule
|
str
|
Molecule to spike |
required |
amount
|
float
|
Amount to add |
required |
recovery_steps
|
int
|
Steps to run before and after spike |
50
|
tolerance
|
float
|
Fraction of pre-spike value considered "recovered" |
0.1
|
Returns:
| Type | Description |
|---|---|
PerturbationResult
|
PerturbationResult with recovery information |
Source code in src/alienbio/bio/perturbation.py
remove_reaction_drift(system, reaction_name, steps=50, drift_threshold=0.01)
¶
Remove a reaction and measure the resulting drift.
Runs the system with and without the named reaction for the same number of steps. Compares final states to measure drift.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
BioSystem to modify |
required |
reaction_name
|
str
|
Name of reaction to remove |
required |
steps
|
int
|
Steps to run |
50
|
drift_threshold
|
float
|
Minimum drift to consider "drifted" |
0.01
|
Returns:
| Type | Description |
|---|---|
DriftResult
|
DriftResult with per-molecule drift measurements |
Source code in src/alienbio/bio/perturbation.py
measure_intervention_response(system, intervention, steps=50)
¶
Apply an intervention (set concentrations) and measure response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
system
|
'BioSystem'
|
BioSystem to perturb |
required |
intervention
|
Dict[str, float]
|
Dict mapping molecule names to new concentrations |
required |
steps
|
int
|
Steps to run after intervention |
50
|
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
Dict mapping molecule names to change from pre-intervention values |