βοΈ YAML user guideο
Phyloom parses structured YAML configuration files to simulate complex evolutionary and epidemiological dynamics. To set up a simulation, you specify key parametersβincluding model specifics and execution settingsβin a human-readable YAML text file, which Phyloom executes using the following command:
phyloom path/to/config.yaml
This guide details how to define and run a Phyloom simulation using a YAML configuration file. For building and executing models programmatically in Python, refer to the Python user guide. Complete, runnable configuration walkthroughs are available in the examples section.
π YAML syntaxο
A Phyloom configuration file relies on nested structures to establish relationships between simulation settings. YAML enforces this hierarchy through its indentation-based syntax, allowing you to define complex, human-readable data structures such as key-value pairings (mappings), ordered lists (sequences), and primitive data values (strings, numbers, booleans).
context: # Mapping: named context variables
rate: # Key within the context mapping
type: uniform # Nested mapping specifying a uniform distribution for the `rate` variable
low: 0.1
high: 0.3
model:
spec: bdsh
init_state: A
events: # A sequence of event configurations
- rule: {spec: birth} # First sequence item; inline mapping using { }
hazard: {spec: constant, rate: rate}
- rule: {spec: sampling, removal: false} # Second sequence item
hazard: {spec: skyline, rates: [0.1, 0.2], break_times: [5.0]} # Square brackets [ ] define an inline list
schedule:
- times: [10.0]
action: | # A vertical bar | keeps the following indented lines together as one multi-line text value
model.rho_sample(0.5, "A", removal=True)
model.rho_sample(0.5, "B", removal=False)
ποΈ Dataset generation settingsο
Dataset generation settings govern run-level options such as output locations, parallel processing, and reproducibility seeds.
output_dir: "phyloom-outputs" # Target directory for all generated simulation artifacts
# Option 1: Scalar value (generates a single flat dataset)
# n_samples: 100
# Option 2: Split mapping (generates separate train/val/test directories)
n_samples:
train: 800
val: 100
test: 100
n_jobs: 4 # Number of parallel worker processes
seed: 42 # Master random seed for reproducibility
The output directory layout depends on whether n_samples is defined as a scalar value or as a dataset split mapping.
When n_samples is set to a single integer (e.g., n_samples: 100), Phyloom writes all generated samples directly into a root data/ folder alongside a single metadata.csv file:
phyloom-outputs/
βββ metadata.csv
βββ data/
βββ 1/
β βββ sampled.nwk
β βββ history.nwk
βββ 2/
βββ ...
metadata.csv: A summary table containing one row per sample, logging the sample ID alongside its full materialized context values and optional log entries (see below).data/: Subdirectories indexed by sample ID, starting at 1 (1/,2/, etc.), containing sample-specific simulation artifacts.
When n_samples is defined as a mapping (e.g., n_samples: {train: 800, val: 100, test: 100}), Phyloom creates separate subdirectories for each split, each containing its own metadata.csv and data/ folder:
output_dir/
βββ train/
β βββ metadata.csv
β βββ data/
β βββ 1/
β β βββ sampled.nwk
β β βββ history.nwk
β βββ ...
βββ val/
β βββ metadata.csv
β βββ data/
β βββ ...
βββ test/
βββ metadata.csv
βββ data/
βββ ...
ποΈ Contextο
Sample-specific parameters are defined in the top-level context mapping. Each key in this mapping is a context variable that can be a fixed scalar, a random draw from a prior distribution, or an expression derived from earlier context entries. Phyloom supports all NumPy random-generator distributions, including uniform, lognormal, and integer draws. For a full list of supported distributions and their arguments, see the NumPy documentation. The evaluated values for these variables form the materialized context, which Phyloom uses to configure the model and execution settings for each sample. Materialized context values are also recorded in the sampleβs metadata.csv row.
context:
# Fixed scalar
generation_time: 2.5
# Derived scalar expression
birth_rate: 1 / generation_time
# NumPy array manipulation
base_rates: np.array([0.1, 0.2])
scaled_rates: base_rates * birth_rate
min_rate: np.min(scaled_rates)
# Random integer draw from [low, high)
initial_size:
type: integers
low: 20
high: 50
# Distribution draw with dynamic parameters
mean_rate: 0.1
rate:
type: lognormal
mean: mean_rate
sigma: 0.2
# Choice distribution with dynamic probabilities
super_spreader_fraction:
type: uniform
low: 0.1
high: 0.3
initial_state:
type: choice
a: "['I_N', 'I_S']"
p: "[1 - super_spreader_fraction, super_spreader_fraction]"
# Derived rate calculations based on other context values
removal_rate: {type: uniform, low: 0.25, high: 0.6}
sampling_probability: {type: uniform, low: 0.05, high: 0.2}
sampling_rate: removal_rate * sampling_probability
unsampled_exit_rate: removal_rate - sampling_rate
𧬠Model configurationsο
A model configuration defines initial conditions alongside event-driven, dynamic behaviors. Phyloom supports three model families:
BDSHmodels forward-time lineage evolution with birth, death, sampling, and hybridization dynamics.Coalescentmodels backward-time lineage ancestry.Epidemicmodels compartment-based epidemic dynamics.
Each family includes its own initial-condition fields, while sharing support for two core sequence blocks:
events: Defines stochastic events, each pairing one of the modelβs rules, listed below for each family, with a hazard (see stochastic events).schedule: Defines deterministic actions to run at specific simulation times. These are composed of atimeslist and anactionblock. Thetimeslist specifies one or more simulation timestamps for execution, while the action block consists of executable Python statements run directly against the currentmodel, allowing for dynamic lineage manipulations, state changes, and other model-specific operations.
π± BDSHο
The BDSH model requires init_state to set the starting lineage state and supports the following stochastic event rules:
birth: Replaces one eligible lineage with two descendants. An optionalparent_statefilters the parent lineage, whilechild_states: [state1, state2]defines the resulting descendant states. Omitted ornullchild entries inherit the parent state.death: Terminates a lineage without sampling. An optionalstatefilters eligible lineages.migration: Transitions an active lineage to a new state. Requiressource_stateandtarget_stateto specify the origin and destination states.sampling: Records a lineage observation. When the requiredremovalflag istrue, the lineage terminates upon sampling; whenfalse, the lineage branchesβone descendant is sampled while the other remains active. An optionalstatefilters eligible lineages.ldh: Merges two parent lineages into a single hybrid lineage (lineage-degenerative hybridization). Optionalparent_states: [state1, state2]filters parent lineages, andhybrid_statespecifies the hybrid state. Ifhybrid_stateis omitted, both parents must share the same state, which the hybrid inherits.lnh: Generates a hybrid descendant from two lineages where one parent continues and the second terminates (lineage-neutral hybridization). Optionalcontinuing_parent_stateandterminating_parent_statefilter the parent lineages (must be provided together). An optionalnew_parent_stateupdates the continuing parentβs state (defaults to its existing state if omitted). The optionalhybrid_statesets the hybrid state; if omitted, both parents must share the same state.lgh: Produces a hybrid descendant while allowing both parent lineages to continue (lineage-generative hybridization). Optionalparent_states: [state1, state2]filters the parents, whilenew_parent_states: [state1, state2]assigns updated states to the continuing parents. Omitted ornullentries inherit their respective parent states. An optionalhybrid_stateassigns the hybrid state; if omitted, both parents must share the same state.
context:
schedule_time:
type: uniform
low: 5.0
high: 15.0
sample_probability:
type: uniform
low: 0.1
high: 0.5
init_state:
type: choice
a: "['A', 'B']"
p: "[0.5, 0.5]"
model:
spec: bdsh
init_state: "{init_state}" # Placeholder interpolation for context-dependent string value
events:
- rule: {spec: birth, parent_state: A, child_states: [A, B]}
hazard: # ...
- rule: {spec: death, state: B}
hazard: # ...
- rule: {spec: migration, source_state: B, target_state: A}
hazard: # ...
- rule: {spec: sampling, state: A, removal: true}
hazard: # ...
- rule: {spec: ldh, parent_states: [A, A], hybrid_state: H}
hazard: # ...
- rule:
spec: lnh
continuing_parent_state: A
terminating_parent_state: A
new_parent_state: A
hybrid_state: H
hazard: # ...
- rule:
spec: lgh
parent_states: [A, A]
hybrid_state: H
new_parent_states: [A, A]
hazard: # ...
schedule:
# Sample lineages in state "A" with probability sample_probability at schedule_time
- times: [schedule_time]
action: model.rho_sample(sample_probability, "A", removal=True)
π Coalescentο
The Coalescent model requires init_population, a mapping from state names to positive initial lineage counts, and supports the following stochastic event rules:
retrace: Replaces a current lineage with an ancestor in the requiredancestral_state. An optionalcurrent_statefilters eligible lineages.coalesce: Merges two lineages into a single common ancestor. An optionalcurrent_states: [state1, state2]list filters eligible pairs. The optionalancestral_statesets the resulting ancestorβs state; if omitted, both lineages must share the same state, which the ancestor inherits.
context:
schedule_times:
type: uniform
low: 5.0
high: 15.0
size: 50
model:
spec: coalescent
init_population: {A: 1, B: 2}
events:
- rule: {spec: retrace, current_state: A, ancestral_state: B}
hazard: # ...
- rule: {spec: coalesce, current_states: [B, B], ancestral_state: A}
hazard: # ...
schedule:
# Add a new lineage in state "B" at each time in schedule_times
- times: np.sort(schedule_times)
action: model.spawn("B")
π¦ Epidemicο
The Epidemic model requires two primary initializations: init_state defines the state of the initial infectious lineage, while init_pools maps pool names to their non-negative initial population counts. Pools omitted from init_pools start at zero. The model supports the following stochastic event rules:
infection: Consumes one member from the requiredrecipient_pooland produces two descendants from an eligible source lineage. An optionalsource_statefilters source lineages, whilechild_states: [state1, state2]assigns descendant states (nullentries inherit the source state).recovery: Terminates an eligible lineage and adds one member to the requireddestination_pool. An optionalsource_statefilters lineages, andsamplecontrols whether the lineage is recorded as an observationmigration: Transitions an active lineage to a new state. Requiressource_stateandtarget_stateto specify the origin and destination states.flow: Transfers one member from the requiredsource_poolto the requireddestination_poolwithout altering lineages.
context:
schedule_time:
type: uniform
low: 5.0
high: 15.0
init_S:
type: integers
low: 100
high: 200
flow_probability:
type: uniform
low: 0.1
high: 0.5
model:
spec: epidemic
init_state: I
init_pools: {S: init_S}
events:
- rule:
spec: infection
recipient_pool: S
source_state: I
child_states: [I, E]
hazard: # ...
- rule: {spec: recovery, source_state: I, destination_pool: R, sample: true}
hazard: # ...
- rule: {spec: migration, source_state: E, target_state: I}
hazard: # ...
- rule: {spec: flow, source_pool: S, destination_pool: R}
hazard: # ...
schedule:
# Move a fraction of the S pool to R at the scheduled time
- times: [schedule_time]
action: |
for _ in range(int(flow_probability * model.pools["S"])):
model.flow("S", "R")
π² Configuring stochastic eventsο
A stochastic event configuration specifies which transition can occur and when it is eligible to fire. Each event pairs a rule of its model, from those listed above, with a per-opportunity, time-dependent instantaneous rate function (hazard). The firing rate of an event can also be scaled dynamically by an optional model state-dependent rate_multiplier.
Phyloom supports five built-in hazard shapes:
constant: Fires at a fixed positiverateover time.delta: Fires immediately upon becoming eligible; requires no additional parameters.exponential: Defined by a positiverateat time \(t=0\) and an exponentialdecayparameter. Positivedecaymakes the rate fall, negativedecaymakes it grow with simulation time, and zero keeps it constant.skyline(piecewise-constant): Defined by non-negativeratesand strictly increasing, positivebreak_times. Must provide exactly one more rate than the number of break times; each break time marks the start of the next rate interval.numeric: Uses a custom-defined expressionrate_fnto compute a non-negative rate as a function of simulation timet.
To dynamically scale hazard rates based on the model state, specify the optional rate_multiplier field. Defined as an expression of model, it provides direct access to real-time simulation properties and methods, such as the current clock time or active lineage counts. The expression must evaluate to a non-negative scalar that directly scales the hazard rate, where a value of \(0\) temporarily disables the event.
context:
event_rate: 0.1
decay: 0.05
change_time:
type: uniform
low: 0.1
high: 10.0
rate_before: 0.1
rate_after: 0.2
base_rate: 0.1
skyline_rates:
type: uniform
low: 0.1
high: 0.5
size: 10
break_times:
type: uniform
low: 0.1
high: 10.0
size: 9
model:
# ...
events:
- rule: # ...
hazard: {spec: constant, rate: event_rate}
rate_multiplier: 1 / model.count_current_lineages("A") # Inversely scales rate by the count of lineages in state "A"
- rule: # ...
hazard: {spec: delta}
- rule: # ...
hazard: {spec: exponential, rate: event_rate, decay: decay}
rate_multiplier: float(model.current_time < 2.0) # Disables the event after time 2.0
- rule: # ...
hazard:
spec: skyline
rates: [rate_before, rate_after, 0.3]
break_times: [change_time, 15.0]
- rule: # ...
hazard:
spec: skyline
rates: skyline_rates
break_times: break_times
- rule: # ...
hazard:
spec: numeric
rate_fn: base_rate * np.exp(-decay * t)
π Execution settingsο
Execution settings control when a trial ends, whether it is accepted, and what is recorded in the output.
max_timeoptionally sets a positive upper bound on simulated time. Stochastic events and scheduled actions due exactly at this bound are applied before the trial ends.stop_criterionis an optional Python expression evaluated against the currentmodelafter each simulation step; returningTrueends the trial.acceptance_criterionis an optional Python expression evaluated against themodelwhen a trial ends; returningFalserejects the trial and retries with the same materialized context.stop_hookis an optional block of Python statements run on the acceptedmodelafter the trial ends and before logs and output hooks are evaluated.max_rejectionslimits rejected trials for one context. Once the count exceeds it, that context is written tomax_rejections_exceeded_contexts.csvin the runβs output directory (output_dirfor an unsplit run oroutput_dir/<split>for a split run), then replaced with a newly sampled context.timeoutis an optional wall-clock limit in seconds for one trial. Timed-out contexts are written totimed_out_contexts.csvin the runβs output directory (output_dirfor an unsplit run oroutput_dir/<split>for a split run), then replaced with newly sampled contexts.logsmaps metadata column names to Python expressions evaluated on the acceptedmodel, afterstop_hookruns. Their results are written tometadata.csv.output_hooksis a required list of Python statement blocks run for each accepted sample, after logs are evaluated. Each block receives the acceptedmodelandoutput_dir, which is the sample-specific output directory where it can write files.post_commandsis an optional list of shell commands run last for each accepted sample, after the output hooks, with{name}placeholders filled from the materialized context and the sample-specificoutput_dir.
context:
target_samples: {type: integers, low: 10, high: 21}
birth_rate: 0.4
sampling_rate: 0.2
clock_rate: {type: uniform, low: 0.001, high: 0.01}
seq_length: {type: integers, low: 500, high: 1001}
model:
spec: bdsh
# ...
# Stop when the number of sampled lineages reaches the target sample size
stop_criterion: model.count_sampled_lineages() >= target_samples
# Accept only trials that finish with at least one active lineage (i.e., the model is not extinct)
acceptance_criterion: model.count_current_lineages() > 0
# On accepted trials, sample each active I lineage with probability 0.5
# and remove sampled lineages
stop_hook: model.rho_sample(0.5, "I", removal=True)
max_time: 100.0 # Execution stops if the simulated clock reaches 100.0 time units
max_rejections: 100 # Abandon a context after the rejection count exceeds 100
timeout: 60 # Abandon a trial if it runs longer than 60 seconds of wall-clock time
# Store the accepted model's sampled-lineage count as metadata
logs:
sampled_lineages: model.count_sampled_lineages()
# Write the full lineage history and the sampled lineage history to
# newick files in the sample-specific output directory
output_hooks:
- model.history().dump(output_dir / "history.nwk")
- model.history(model.get_sampled_lineages()).dump(output_dir / "sampled.nwk")
# Run AliSim on the sampled tree to simulate a DNA alignment along it
# (requires IQ-TREE 3 installed with its `iqtree3` command on your PATH)
post_commands:
- iqtree3 --alisim {output_dir}/alignment -t {output_dir}/sampled.nwk
-m JC --length {seq_length} --branch-scale {clock_rate}
-af fasta