Skip to content

Latest commit

 

History

History
193 lines (151 loc) · 6.32 KB

python-api.md

File metadata and controls

193 lines (151 loc) · 6.32 KB

Python API

Use the environment installed from the repository's README. For notebook output, include the notebook extra:

uv sync --python 3.13 --all-packages --extra mfe --extra notebook --frozen

Select this environment as your notebook kernel. To register it after activating the virtual environment:

python -m ipykernel install --user --name morse --display-name MORSE

The CPU example notebook runs a small experiment with the bundled sequence-metric scorer. The graphical notebook provides forms for creating YAML and calls this API in its active Python kernel.

Configure and run

import morse

params = morse.load_config("examples/quickstart/experiment.yaml")
result = morse.optimize(
    params=params,
    output_dir="outputs/python_run",
    verbose=2,
    plots=["metrics", "hypervolume", "utrs"],
)

params is an ordinary dictionary using experiment schema 5. Schemas 3/4 remain supported with their previous input semantics. load_config() resolves paths relative to the YAML. You can edit the returned dictionary before running:

params["optimizer"]["population_size"] = 100
params["optimizer"]["generations"] = 200

To supply RNA directly:

result = morse.optimize(
    rna_seq,
    params,
    output_dir="results/my_run",
    verbose=2,
)

The RNA replaces construct.fasta; coordinates and allowed changes stay in the configuration. In schema 5, coordinates.cds selects the body without initiation or stop codons. A body-only input uses coordinates: {cds: [0, length]}. Set construct.start_codon: [AUG] and construct.stop_codon: [UAA]; multiple entries allow the optimizer to choose, with the first defining the reference.

Coordinates are 0-based, end exclusive and refer to the supplied input. MORSE inserts the codons and recalculates coordinates for assembled candidates and scorers. Input can contain RNA U or DNA T. MORSE does not modify the supplied dictionary.

A dictionary read with yaml.safe_load() also works. Set base_dir when its relative input paths belong to a different folder:

result = morse.optimize(rna_seq, params, base_dir="experiments/my_run")

Scorer commands and their parameters work as in the CLI. Prepare the scorer environment before starting the run; see scorer setup.

Check before optimizing

check = morse.validate(params=params)
scores = morse.score(params=params)
trial = morse.pilot(params=params, samples=24)
print(trial["hard_feasible_fraction"], trial["warnings"])

Validation checks configuration and construct structure. Scoring runs the configured scorers once and returns outputs, threshold checks and feasible. The pilot scores the reference plus a random sample using the config seed; samples includes the reference (2–512, capped by the size of the search space). Inspect trial["metrics"] for score ranges and trial["thresholds"] for pass fractions. A pilot does not run generations or initialize the optimization. It returns a dictionary in memory; pass a separate, new or empty output_dir to also save pilot.json and progress.json. All three methods accept an optional RNA string as their first argument.

Progress

verbose Output
0 No progress output
1 Generation, elapsed time, feasibility and optimization progress
2 Progress and plots updated in one notebook display

plots chooses metrics, hypervolume and utrs. Metric plots show population mean and standard deviation; UTR plots show variant shares in each population. The settings affect display only. Results and history are saved in output_dir from the configuration, or the explicit argument. If neither is set, MORSE creates a new directory under outputs/.

Inspect results

result.summary
result.pareto
result.history
result.output_dir

result.plot("metrics")
result.plot("hypervolume")
result.plot("utrs")
result.report()

pareto and history are lists of dictionaries. For a DataFrame, use pandas.DataFrame(result.pareto). plot() returns a Matplotlib figure; report() displays the saved report in a notebook.

Choose a candidate explicitly:

candidate = result.select("hvc")
candidate.id
candidate.sequence
candidate.parts
candidate.metrics

hvc selects the largest exclusive hypervolume contribution in the final feasible Pareto set. For selection by a single metric, use its full name:

candidate = result.select(metric="sequence_metrics.cpg_per_kb")

The configured direction determines whether smaller or larger values win. You can also retrieve a candidate by its ID in the final Pareto table:

selected = result.get_candidate(candidate.id)
selected.to_fasta(result.output_dir / "selected.fasta")

Compare with a baseline

compromise = result.select("hvc")
specialist = result.select(metric="sequence_metrics.cpg_per_kb")
rows = result.compare([compromise, specialist], baseline=result.reference)

result.reference is the scored starting construct. Like a selected candidate, it has an ID, assembled RNA sequence, parts and recorded metrics. Older runs may have only partial annotations for the parts. No scorers are called when reading or comparing saved results.

compare returns one dictionary per candidate and configured metric: candidate_id, baseline_id, metric, direction, baseline, value and delta. Use pandas.DataFrame(rows) if you want a table. delta = value - baseline for numeric measurements. Direction is min or max for objectives and None for logged values and thresholds. Pass percent=True to add 100 * delta / abs(baseline). Percent change from zero is None; nonnumeric and boolean values have no delta or percentage. These are signed changes in the recorded scores, not direction-adjusted gains. If you pass a baseline from another run, check that scorer settings, sequence scopes and units match.

Reopen or continue

result = morse.load_run("results/my_run")
result.plot("metrics")

Interrupting the optimization cell stops the run. Continue from its latest saved generation in the same output directory:

result = morse.resume("results/my_run", verbose=2)

The saved input, resolved configuration and checkpoint are used for continuation.