syntheogenesis / dee /main.py
WINTER4000's picture
Initial deploy · DEE Flask app via Docker SDK
060bb47 verified
Raw History Blame Contribute Delete
7.23 kB
"""CLI entrypoint for the Digital Evolution Engine.
Example:
python -m dee.main \\
--input my_cds.fasta \\
--output library.csv \\
--model small \\
--percentile 85 \\
--k 100 \\
--host e_coli
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
from typing import Optional, Sequence
from dee.core.codon import (
DEFAULT_FORBIDDEN_SITES,
variants_to_dataframe,
write_library_csv,
)
from dee.core.sequence import (
SequenceValidationError,
list_cds_features,
parse_input,
)
from dee.models.scorer import (
ESM2Scorer,
ScorerConfig,
top_percentile_pool,
)
from dee.optimizer.search import SearchConfig, evolve
logger = logging.getLogger("dee")
def _build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="dee",
description=(
"Digital Evolution Engine — PLM-guided smart-library generator for "
"directed evolution."
),
)
p.add_argument(
"--input",
"-i",
required=True,
help="Path to a FASTA file, an inline FASTA string, or a raw DNA sequence.",
)
p.add_argument(
"--output",
"-o",
required=True,
help="Destination CSV file for the smart library.",
)
p.add_argument(
"--model",
default="small",
help=(
"ESM-2 model: 'small' (35M, default), 'medium' (650M), 'large' (3B), "
"or any Hugging Face model id."
),
)
p.add_argument(
"--device",
default=None,
help="Force a torch device ('cuda'/'mps'/'cpu'); auto-detected if omitted.",
)
p.add_argument(
"--quantization",
default=None,
choices=["8bit", "4bit"],
help="Optional bitsandbytes quantization (CUDA only).",
)
p.add_argument(
"--percentile",
type=float,
default=85.0,
help=(
"Keep mutations above this percentile of ΔLL for the combinatorial "
"search (default 85 = top 15%%)."
),
)
p.add_argument("--k", type=int, default=100, help="Number of variants to output.")
p.add_argument(
"--max-mutations",
type=int,
default=8,
help="Cap on simultaneous substitutions per variant.",
)
p.add_argument(
"--min-mutations",
type=int,
default=2,
help="Floor on simultaneous substitutions per variant.",
)
p.add_argument(
"--restarts",
type=int,
default=12,
help="Independent simulated-annealing restarts.",
)
p.add_argument(
"--steps",
type=int,
default=2000,
help="SA steps per restart.",
)
p.add_argument("--seed", type=int, default=None, help="Random seed.")
p.add_argument(
"--host",
default="e_coli",
help="Expression host for codon optimization: e_coli, yeast, human.",
)
p.add_argument(
"--no-start-check",
action="store_true",
help="Skip start-codon validation (useful for protein-only inputs).",
)
p.add_argument(
"--no-stop-check",
action="store_true",
help="Skip stop-codon validation.",
)
p.add_argument(
"--scores-csv",
default=None,
help="Optional path to also dump the Phase-2 single-site score table.",
)
p.add_argument(
"--cds-feature",
default=None,
help=(
"When reading a GenBank/SnapGene/EMBL file, pick the CDS whose "
"label (gene/product/note) contains this substring "
"(case-insensitive). Use --list-cds to see what's available."
),
)
p.add_argument(
"--list-cds",
action="store_true",
help=(
"List every CDS feature in a structured input file and exit. "
"Output is machine-parseable: '<length_nt>\\t<label>' per line."
),
)
p.add_argument("--verbose", "-v", action="count", default=0)
return p
def _configure_logging(verbose: int) -> None:
level = logging.WARNING
if verbose == 1:
level = logging.INFO
elif verbose >= 2:
level = logging.DEBUG
logging.basicConfig(
level=level, format="%(asctime)s %(levelname)s %(name)s: %(message)s"
)
def run(argv: Optional[Sequence[str]] = None) -> int:
args = _build_parser().parse_args(argv)
_configure_logging(args.verbose)
# --list-cds is a short-circuit: enumerate CDS features and exit before
# touching the PLM (so it's fast and safe to call from the desktop UI).
if args.list_cds:
features = list_cds_features(Path(args.input))
if not features:
print("NO_CDS_FEATURES", file=sys.stderr)
return 3
for label, length in features:
print(f"{length}\t{label}")
return 0
# Phase 1 — parse & translate.
try:
record = parse_input(
args.input,
require_start=not args.no_start_check,
require_stop=not args.no_stop_check,
cds_feature=args.cds_feature,
)
except SequenceValidationError as exc:
msg = (
"INPUT_NOT_RECOGNIZED: " + str(exc) + "\n\n"
"Hint: this tool needs ONE of the following:\n"
" • the protein sequence (amino acids, e.g. MVSKGEEL...),\n"
" • the CDS only (DNA: ATG ... TAA/TAG/TGA, length a multiple of 3), or\n"
" • a FASTA file containing the above.\n"
"If you pasted a plasmid map, copy just the gene of interest — the "
"engine can't guess which ORF you want to evolve."
)
print(msg, file=sys.stderr)
return 2
logger.info(
"Loaded %s: %d aa wild-type protein.", record.identifier, len(record.protein)
)
# Phase 2 — zero-shot scoring.
scorer = ESM2Scorer(
ScorerConfig(
model_name=args.model,
device=args.device,
quantization=args.quantization,
)
)
scores = scorer.score_all_substitutions(record.protein)
if args.scores_csv:
scores.to_csv(args.scores_csv, index=False)
logger.info("Wrote single-site score table to %s.", args.scores_csv)
pool = top_percentile_pool(scores, percentile=args.percentile)
# Phase 3 — combinatorial search.
variants = evolve(
pool,
SearchConfig(
k=args.k,
max_mutations=args.max_mutations,
min_mutations=args.min_mutations,
n_restarts=args.restarts,
steps_per_restart=args.steps,
seed=args.seed,
),
)
# Phase 4 — DNA, codon optimization, scrub restriction sites, write CSV.
df = variants_to_dataframe(
record.protein,
variants,
host=args.host,
forbidden_sites=DEFAULT_FORBIDDEN_SITES,
)
write_library_csv(df, args.output)
print(
f"Done. Wrote {len(df)} variants to {Path(args.output).resolve()}.",
file=sys.stderr,
)
return 0
if __name__ == "__main__":
sys.exit(run())