Specification Language Module¶
Parser and interpreter for the specification language.
alienbio.spec_lang
¶
Spec Language Module.
YAML tags, decorators, and Bio class for loading/saving biology specifications. See docs: [[Spec Language]], [[Decorators]], [[Bio]]
Bio
¶
Top-level API for Alien Biology operations.
Bio acts as a "pegboard" holding references to implementation classes.
The module singleton bio is used by default; create new instances
for sandboxing or customization.
Usage
from alienbio import Bio, bio
bio.fetch(...) # Use the module singleton bio.sim(scenario) # Create simulator using default Simulator class
Customize for sandboxing:¶
my_bio = Bio() my_bio._simulator_factory = JaxSimulator my_bio.sim(scenario) # Uses JaxSimulator
Configure source roots:¶
bio.add_source_root("./catalog", module="myproject.catalog")
Create Bio bound to a specific DAT:¶
sandbox = Bio(dat="experiments/baseline")
ORM Pattern
- DATs are cached: same DAT name returns the same object
- First fetch loads DAT into memory; subsequent fetches return cached instance
Source code in src/alienbio/spec_lang/bio.py
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 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 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 | |
io
property
writable
¶
Active IO instance for entity I/O.
Lazily creates a default IO instance on first access.
sim
property
writable
¶
Active Simulator instance.
agent
property
writable
¶
Active Agent instance.
chem
property
writable
¶
Active Chemistry instance.
dat
property
¶
Get this Bio's bound DAT, creating an anonymous one if needed.
__init__(*, dat=None)
¶
Initialize Bio with default implementations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dat
|
str | Any | None
|
Optional DAT to bind this Bio to (string path or DAT object) |
None
|
Source code in src/alienbio/spec_lang/bio.py
create(protocol, name=None, spec=None)
¶
Create component instance via factory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
protocol
|
type
|
Protocol class (Simulator, IO, Agent, Chemistry, etc.) |
required |
name
|
str | None
|
Implementation name. If None, uses default for protocol. |
None
|
spec
|
Any
|
Data/configuration for the instance. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
New instance of the specified implementation. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no implementation found for protocol/name. |
Source code in src/alienbio/spec_lang/bio.py
compile_sim(scenario, dt=1.0)
¶
Create a compiled simulator from a scenario spec.
Compiles rate expressions (Quoted strings) into efficient callables, returning a CompiledSimulator with step/run/action/measure methods.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
Any
|
ScenarioSpec, dict, or any object with molecules, reactions, initial_state, scope attributes |
required |
dt
|
float
|
Timestep size (default 1.0) |
1.0
|
Returns:
| Type | Description |
|---|---|
Any
|
CompiledSimulator instance |
Source code in src/alienbio/spec_lang/bio.py
add_source_root(path, module=None)
¶
Add a source root for spec resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Filesystem path to search for YAML files |
required |
module
|
str | None
|
Optional Python module prefix for Python global lookups |
None
|
Source code in src/alienbio/spec_lang/bio.py
cd(path=_UNSET)
¶
Get, set, or reset the current working DAT.
cd()— return current DAT pathcd(path)— set current DAT to pathcd(None)— reset (clear current DAT)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Any
|
DAT path to set, None to reset, or omit to get current |
_UNSET
|
Returns:
| Type | Description |
|---|---|
Path | None
|
Current DAT path (or None if reset/unset) |
Source code in src/alienbio/spec_lang/bio.py
clear_cache()
classmethod
¶
fetch(specifier, *, raw=False, hydrate=True)
¶
Fetch a typed object from a specifier path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
specifier
|
str
|
Path like "catalog/scenarios/mutualism" or "mute.mol.energy" |
required |
raw
|
bool
|
If True, return raw YAML without processing |
False
|
hydrate
|
bool
|
If False, resolve tags but don't convert to typed objects |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Processed data (or typed object when hydration implemented) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If specifier not found |
Source code in src/alienbio/spec_lang/bio.py
store(specifier, obj, *, raw=False)
¶
Store a typed object to a specifier path.
Dehydration pipeline (inverse of fetch): 1. Convert typed objects to dicts (via to_dict() if available) 2. Convert placeholders back to tag form: - Evaluable → {"!ev": source} - Quoted → {"!_": source} - Reference → {"!ref": name} 3. Write YAML
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
specifier
|
str
|
Path or file like "output.yaml", "dat_dir/", or "./relative" |
required |
obj
|
Any
|
Object to store (dict, typed object, or hydrated data) |
required |
raw
|
bool
|
If True, write obj directly without any dehydration |
False
|
Source code in src/alienbio/spec_lang/bio.py
expand(specifier)
¶
Expand a spec: resolve includes, refs, defaults without hydrating.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
specifier
|
str
|
Path like "catalog/scenarios/mutualism" |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Fully expanded dict with _type fields |
Source code in src/alienbio/spec_lang/bio.py
load_spec(specifier)
¶
Load a spec file with placeholders for deferred evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
specifier
|
str
|
Path to spec |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Hydrated spec with placeholders (not yet evaluated) |
Source code in src/alienbio/spec_lang/bio.py
eval_spec(spec, *, seed=None, bindings=None, ctx=None)
¶
Evaluate a hydrated spec, resolving all placeholders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
Any
|
Hydrated spec from load_spec() |
required |
seed
|
int | None
|
Random seed for reproducibility |
None
|
bindings
|
dict[str, Any] | None
|
Variables available to expressions |
None
|
ctx
|
EvalContext | None
|
Full evaluation context (overrides seed/bindings) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Fully evaluated spec with concrete values |
Source code in src/alienbio/spec_lang/bio.py
build(spec, seed=0, registry=None, params=None)
¶
Build a scenario from a spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spec
|
str | dict[str, Any]
|
Spec dict or specifier string |
required |
seed
|
int
|
Random seed for reproducibility |
0
|
registry
|
Any
|
Template registry |
None
|
params
|
dict[str, Any] | None
|
Parameter overrides |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Scenario with visible and ground truth data |
Source code in src/alienbio/spec_lang/bio.py
run(target, seed=0, registry=None, params=None, steps=None, dt=None)
¶
Run a target: build if needed, then execute simulation.
This is the main entry point for M3.1 Scenario Execution.
Pipeline: 1. If target is a string or dict spec, build it into a Scenario 2. Extract sim settings (steps, dt) from scenario or use defaults 3. Build Chemistry from scenario ground truth 4. Initialize State from scenario regions/containers 5. Create simulator and run for N steps 6. Return SimulationResult with timeline
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
str | dict[str, Any]
|
Specifier string, dict spec, Scenario, or DAT |
required |
seed
|
int
|
Random seed for reproducibility |
0
|
registry
|
Any
|
Template registry for building |
None
|
params
|
dict[str, Any] | None
|
Parameter overrides for building |
None
|
steps
|
int | None
|
Override number of simulation steps (default: from scenario or 100) |
None
|
dt
|
float | None
|
Override time step (default: from scenario or 1.0) |
None
|
Returns:
| Type | Description |
|---|---|
SimulationResult
|
SimulationResult with timeline of states |
Source code in src/alienbio/spec_lang/bio.py
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 | |
SimulationResult
dataclass
¶
Result of running a simulation.
Contains the timeline of states and metadata about the run.
Attributes:
| Name | Type | Description |
|---|---|---|
timeline |
List[Any]
|
List of states from simulation (StateImpl or dict) |
final_state |
Any
|
The final state after simulation |
steps |
int
|
Number of steps executed |
dt |
float
|
Time step used |
seed |
int
|
Random seed used for the run |
scenario_name |
str
|
Name of the scenario that was run |
Source code in src/alienbio/spec_lang/bio.py
final
property
¶
Return the final state as a dict of concentrations.
Compatible with scoring functions that expect a dict.
CompiledSimulator
¶
Simulator created from a scenario spec with compiled rate expressions.
Rate expressions are compiled once at construction time. The simulator operates on dict-based state (molecule name -> concentration).
Source code in src/alienbio/spec_lang/compiled_sim.py
initial_state()
¶
step(state)
¶
Advance state by one timestep using Euler integration.
Source code in src/alienbio/spec_lang/compiled_sim.py
run(state, steps)
¶
Run simulation for N steps, returning full history.
Returns:
| Type | Description |
|---|---|
list[dict[str, float]]
|
List of length steps+1 (initial state + N stepped states) |
Source code in src/alienbio/spec_lang/compiled_sim.py
action(name, *args)
¶
Execute a named action on the internal state.
Supported actions
add_feedstock(molecule, amount) — increase concentration
Source code in src/alienbio/spec_lang/compiled_sim.py
measure(name, *args)
¶
Take a named measurement from the internal state.
Source code in src/alienbio/spec_lang/compiled_sim.py
ScenarioSpec
dataclass
¶
Lightweight scenario specification for compiled simulation.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Scenario identifier |
molecules |
dict[str, Any]
|
Molecule names to properties |
reactions |
dict[str, Any]
|
Reaction name to dict with substrates, products, rate |
initial_state |
dict[str, float]
|
Molecule name to initial concentration |
scope |
dict[str, Any]
|
Named constants for rate compilation |
Source code in src/alienbio/spec_lang/compiled_sim.py
Include
¶
Placeholder for !include tag - file to include.
Resolved during hydration (phase 1).
Source code in src/alienbio/spec_lang/tags.py
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 | |
load(base_dir=None, _seen=None)
¶
Load the included file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir
|
str | None
|
Base directory for relative paths |
None
|
_seen
|
set[str] | None
|
Internal set tracking files in current include chain |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
File contents (string for .md, parsed for .yaml, executed for .py) |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file doesn't exist |
RecursionError
|
If circular include detected |
Source code in src/alienbio/spec_lang/tags.py
Evaluable
dataclass
¶
Placeholder for !ev expressions - evaluated at instantiation time.
Created during hydration when a !ev tag is encountered. Evaluated by eval_node() to produce a concrete value.
Use !ev for values that should be computed when the spec is instantiated, such as random samples, computed parameters, etc.
Example
YAML: count: !ev normal(50, 10) After hydrate: {"count": Evaluable(source="normal(50, 10)")} After eval: {"count": 47.3} # sampled value
Source code in src/alienbio/spec_lang/eval.py
evaluate(namespace=None)
¶
Evaluate the expression in a sandboxed namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
namespace
|
dict[str, Any] | None
|
Dict of names available during evaluation |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Result of evaluating the expression |
Source code in src/alienbio/spec_lang/eval.py
Quoted
dataclass
¶
Placeholder for !_ expressions - preserved as expression strings.
Created during hydration when a !_ or !quote tag is encountered. Preserved through evaluation - returns the source string unchanged. Used for rate equations, scoring functions, and other "code" that gets compiled or called later (not at instantiation time).
The !_ tag is the common case - most expressions in specs are lambdas.
Example
YAML: rate: !_ k * S After hydrate: {"rate": Quoted(source="k * S")} After eval: {"rate": "k * S"} # preserved for later compilation
Source code in src/alienbio/spec_lang/eval.py
Reference
dataclass
¶
Placeholder for !ref expressions.
Created during hydration when a !ref tag is encountered. Resolved during evaluation by looking up the name in ctx.bindings.
Example
YAML: permeability: !ref high_permeability After hydrate: {"permeability": Reference(name="high_permeability")} After eval: {"permeability": 0.8} # looked up from bindings
Source code in src/alienbio/spec_lang/eval.py
resolve(constants)
¶
Resolve the reference from a constants dict.
Supports dotted paths like "settings.threshold".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
constants
|
dict[str, Any]
|
Dict of named values to look up in |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The resolved value |
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not found in constants |
Source code in src/alienbio/spec_lang/eval.py
EvalContext
dataclass
¶
Evaluation context for spec evaluation.
Carries state through the recursive evaluation process: - rng: Random number generator for reproducible sampling - bindings: Named values for !ref resolution - functions: Callable functions available to !_ expressions - path: Current location in the tree for error messages
Example
ctx = EvalContext( rng=np.random.default_rng(42), bindings={"k": 0.5, "permeability": 0.8}, functions={"normal": normal, "uniform": uniform} ) result = eval_node(hydrated_spec, ctx)
Source code in src/alienbio/spec_lang/eval.py
child(key)
¶
Create child context with extended path.
Source code in src/alienbio/spec_lang/eval.py
EvalError
¶
Bases: Exception
Error during spec evaluation.
Source code in src/alienbio/spec_lang/eval.py
Scope
¶
Bases: dict
A dict with lexical scoping (parent chain lookup).
Variables are inherited through the scope chain. Lookups check the current scope first, then climb to parent scopes until found.
The scope hierarchy is built at load time (via extends: in YAML),
but variable lookups are dynamic - they climb the hierarchy at
access time.
Attributes:
| Name | Type | Description |
|---|---|---|
parent |
Optional parent Scope for inheritance chain |
|
name |
Optional name for this scope (for debugging) |
Source code in src/alienbio/spec_lang/scope.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 | |
__init__(data=None, parent=None, name=None)
¶
Create a new Scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any] | None
|
Initial dict content |
None
|
parent
|
Scope | None
|
Parent scope for inheritance |
None
|
name
|
str | None
|
Optional name for debugging |
None
|
Source code in src/alienbio/spec_lang/scope.py
__getitem__(key)
¶
Get item, climbing parent chain if not found locally.
get(key, default=None)
¶
__contains__(key)
¶
Check if key exists in this scope or any parent.
local_keys()
¶
all_keys()
¶
child(data=None, name=None)
¶
Create a child scope that inherits from this one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any] | None
|
Initial content for child scope |
None
|
name
|
str | None
|
Optional name for the child scope |
None
|
Returns:
| Type | Description |
|---|---|
Scope
|
New Scope with this scope as parent |
Source code in src/alienbio/spec_lang/scope.py
resolve(key)
¶
Resolve a key and return (value, defining_scope).
Useful for debugging to see where a value comes from.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to look up |
required |
Returns:
| Type | Description |
|---|---|
tuple[Any, Scope | None]
|
Tuple of (value, scope_that_defined_it) |
Raises:
| Type | Description |
|---|---|
KeyError
|
If key not found in any scope |
Source code in src/alienbio/spec_lang/scope.py
compile_rate_expression(source, constants)
¶
Compile a rate expression string into a callable function.
Constants are baked in at compile time (copied, not referenced). Variables (S, S1, S2, P, P1, P2, or molecule names) are looked up from the state dict passed at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Rate expression string, e.g. |
required |
constants
|
dict[str, float]
|
Named constants to bake in, e.g. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[dict[str, float]], float]
|
A function |
Source code in src/alienbio/spec_lang/rate_compiler.py
compile_sim(scenario, dt=1.0)
¶
Create a CompiledSimulator from a scenario spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scenario
|
ScenarioSpec | dict[str, Any]
|
ScenarioSpec or dict with keys name, molecules, reactions, initial_state, scope |
required |
dt
|
float
|
Timestep size (default 1.0) |
1.0
|
Returns:
| Type | Description |
|---|---|
CompiledSimulator
|
CompiledSimulator ready to run |
Source code in src/alienbio/spec_lang/compiled_sim.py
biotype(arg=None)
¶
Register a class for hydration from YAML.
Usage
@biotype class Chemistry: ...
@biotype("custom_name") class World: ...
Source code in src/alienbio/spec_lang/decorators.py
fn(summary=None, range=None, **kwargs)
¶
Base decorator for all functions. Stores metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
summary
|
str | None
|
Short description for plots/tables |
None
|
range
|
tuple[float, float] | None
|
Expected output range |
None
|
**kwargs
|
Any
|
Additional metadata |
{}
|
Source code in src/alienbio/spec_lang/decorators.py
scoring(summary=None, range=(0.0, 1.0), higher_is_better=True, **kwargs)
¶
Decorator for scoring functions.
Registers function in scoring_registry.
Source code in src/alienbio/spec_lang/decorators.py
action(summary=None, targets=None, reversible=False, cost=1.0, **kwargs)
¶
Decorator for action functions.
Registers function in action_registry.
Source code in src/alienbio/spec_lang/decorators.py
measurement(summary=None, targets=None, cost='none', **kwargs)
¶
Decorator for measurement functions.
Registers function in measurement_registry.
Source code in src/alienbio/spec_lang/decorators.py
rate(summary=None, range=(0.0, float('inf')), **kwargs)
¶
Decorator for rate functions.
Registers function in rate_registry.
Source code in src/alienbio/spec_lang/decorators.py
get_biotype(name)
¶
Get a biotype class by name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not registered |
get_action(name)
¶
Get an action by name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not registered |
get_measurement(name)
¶
Get a measurement by name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not registered |
Source code in src/alienbio/spec_lang/decorators.py
get_scoring(name)
¶
Get a scoring function by name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not registered |
Source code in src/alienbio/spec_lang/decorators.py
get_rate(name)
¶
Get a rate function by name.
Raises:
| Type | Description |
|---|---|
KeyError
|
If name not registered |
Source code in src/alienbio/spec_lang/decorators.py
hydrate(data, base_path=None)
¶
Convert dict structure to Python objects with placeholders.
Transforms
{"!_": source} → Quoted(source) (preserve expression) {"!ev": source} → Evaluable(source) (evaluate at instantiation) {"!ref": name} → Reference(name) (lookup in bindings) {"!include": path} → file contents (recursively hydrated)
Also handles
- Recursive descent into dicts and lists
- YAML tag objects (Evaluable, Quoted, Reference, Include) pass through
- Include objects are loaded and their contents hydrated
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data structure to hydrate |
required |
base_path
|
str | None
|
Base directory for resolving !include paths |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Hydrated data with placeholders |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If !include file doesn't exist |
Source code in src/alienbio/spec_lang/eval.py
dehydrate(data)
¶
Convert Python objects back to serializable dict structure.
Inverse of hydrate() - converts placeholder objects back to their dict representation for YAML serialization.
Transforms
Evaluable(source) → {"!ev": source} (evaluate at instantiation) Quoted(source) → {"!_": source} (preserve expression) Reference(name) → {"!ref": name}
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
The data structure to dehydrate |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Dehydrated data suitable for YAML serialization |
Source code in src/alienbio/spec_lang/eval.py
eval_node(node, ctx, *, strict=True)
¶
Recursively evaluate a hydrated spec node.
Processes placeholder objects
Evaluable → execute expression and return result Quoted → return source string unchanged Reference → look up in ctx.bindings
Recursively evaluates
dict → evaluate all values list → evaluate all elements
Passes through
Scalar values (int, float, str, bool, None)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Any
|
The hydrated node to evaluate |
required |
ctx
|
EvalContext
|
Evaluation context |
required |
strict
|
bool
|
If True, missing references raise EvalError. If False, missing references return the Reference unchanged. |
True
|
Returns:
| Type | Description |
|---|---|
Any
|
Fully evaluated value |
Raises:
| Type | Description |
|---|---|
EvalError
|
If evaluation fails (undefined reference, syntax error, etc.) |
Source code in src/alienbio/spec_lang/eval.py
make_context(seed=None, bindings=None, functions=None)
¶
Create an evaluation context with default functions.
Convenience function that sets up a Context with: - Seeded RNG for reproducibility - Optional custom bindings - DEFAULT_FUNCTIONS plus any custom functions
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int | None
|
Random seed for reproducibility (None for random) |
None
|
bindings
|
dict[str, Any] | None
|
Named values for !ref resolution |
None
|
functions
|
dict[str, Callable[..., Any]] | None
|
Additional functions (merged with defaults) |
None
|
Returns:
| Type | Description |
|---|---|
EvalContext
|
Configured EvalContext ready for evaluation |
Source code in src/alienbio/spec_lang/eval.py
normal(mean, std, *, ctx)
¶
uniform(low, high, *, ctx)
¶
lognormal(mean, sigma, *, ctx)
¶
poisson(lam, *, ctx)
¶
exponential(scale, *, ctx)
¶
choice(options, *, ctx)
¶
discrete(weights, *, ctx)
¶
Sample index from discrete distribution with given weights.
Source code in src/alienbio/spec_lang/builtins.py
transform_typed_keys(data, type_registry=None)
¶
Transform type.name keys to nested structure with _type field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict with keys like "world.foo", "suite.bar" |
required |
type_registry
|
set[str] | None
|
Set of known type names (default: built-in types) |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Transformed dict with _type fields |
Example
{"world.foo": {"molecules": {}}} becomes: {"foo": {"_type": "world", "molecules": {}}}
Source code in src/alienbio/spec_lang/loader.py
expand_defaults(data, inherited_defaults=None)
¶
Expand defaults through suite/scenario hierarchy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Dict with suite/scenario structure and defaults |
required |
inherited_defaults
|
dict[str, Any] | None
|
Defaults inherited from parent suites |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Data with defaults expanded into each scenario |