syntheogenesis / dee /core /plasmid.py
Tengo Gzirishvili
Claude Opus 4.8
Plasmid: accept SnapGene .dna; fix button hover (black fill, both themes)
21dfced
Raw History Blame Contribute Delete
21.9 kB
"""Plasmid Studio core β€” parse, annotate, export, and digest plasmids.
The heavy lifting rides on Biopython (already a dependency): ``Bio.SeqIO`` for
GenBank/FASTA round-tripping and ``Bio.Restriction`` for the full REBASE enzyme
set. This module normalises everything into one plain-dict plasmid model the
rest of the app (endpoints, the SVG map, the virtual gel) consumes:
{
"name": str, "sequence": "ACGT…", "length": int,
"topology": "circular" | "linear", "gc": float,
"features": [ {name, type, start, end, strand, color, notes} ], # 0-based, end-exclusive
"source": "genbank" | "fasta" | "raw",
}
Pure + unit-testable; Bio is imported lazily inside functions (matching the
rest of the codebase) so the server still boots without it loaded eagerly.
"""
from __future__ import annotations
import io
import re
from typing import Any, Dict, List, Optional, Tuple
MAX_LEN = 500_000 # 500 kb β€” covers BACs; bigger is a genome tool's job
MAX_INPUT_TEXT = 2_000_000 # bytes of raw import text (GenBank overhead vs MAX_LEN)
MAX_FEATURES = 5_000 # hard cap on features parsed/stored per plasmid
_COLOR_RE = re.compile(r"^#[0-9A-Fa-f]{3,8}$")
_DNA_RE = re.compile(r"^[ACGTNRYSWKMBDHV]+$") # allow IUPAC ambiguity
_COMP = str.maketrans("ACGTNacgtn", "TGCANtgcan")
# Feature colours by type (hex, tuned for the dark theme map).
_TYPE_COLORS = {
"cds": "#6A89E4", "gene": "#6A89E4",
"promoter": "#5FA98A", "regulatory": "#5FA98A", "rbs": "#5FA98A",
"terminator": "#C77E7E",
"rep_origin": "#E4B45F", "origin": "#E4B45F", "ori": "#E4B45F",
"primer_bind": "#9AA0AA", "misc_feature": "#9AA0AA", "protein_bind": "#9AA0AA",
"resistance": "#D98C5F",
"tag": "#B07ED9", "sig_peptide": "#B07ED9", "cds_tag": "#B07ED9",
}
_DEFAULT_COLOR = "#9AA0AA"
# Short, highly-conserved motifs we can annotate by exact match (both strands).
# Reliable signatures only β€” full gene/ori detection by homology is a later
# milestone; GenBank imports already carry their own curated features.
_MOTIFS: List[Tuple[str, str, str]] = [
# Promoters / regulatory
("T7 promoter", "TAATACGACTCACTATAG", "promoter"),
("T3 promoter", "AATTAACCCTCACTAAAGGG", "promoter"),
("SP6 promoter", "ATTTAGGTGACACTATAGAA", "promoter"),
("lac operator", "TGGAATTGTGAGCGGATAACAATT", "regulatory"),
# Terminators
("T7 terminator", "GCTAGTTATTGCTCAGCGG", "terminator"),
# Sequencing / primer-binding sites
("M13 fwd", "GTAAAACGACGGCCAGT", "primer_bind"),
("M13 rev", "CAGGAAACAGCTATGAC", "primer_bind"),
("CMV-fwd primer", "CGCAAATGGGCGGTAGGCGTG", "primer_bind"),
("BGH-rev primer", "TAGAAGGCACAGTCGAGGCT", "primer_bind"),
# Epitope / purification tags (canonical sequences used in common vectors)
("6Γ—His tag", "CACCACCACCACCACCAC", "tag"),
("6Γ—His tag", "CATCACCATCACCATCAC", "tag"),
("FLAG tag", "GACTACAAGGACGACGACGACAAG", "tag"),
("FLAG tag", "GATTACAAGGATGATGACGATAAG", "tag"),
("HA tag", "TACCCATACGATGTTCCAGATTACGCT", "tag"),
("Myc tag", "GAACAAAAACTTATTTCTGAAGAAGATCTG", "tag"),
("Strep-Tag II", "TGGAGCCACCCGCAGTTCGAAAAA", "tag"),
("V5 tag", "GGTAAGCCTATCCCTAACCCTCTCCTCGGTCTCGATTCTACG", "tag"),
("T7 tag", "ATGGCTAGCATGACTGGTGGACAGCAAATGGGTCGG", "tag"),
# Recombination / binding sites
("loxP", "ATAACTTCGTATAATGTATGCTATACGAAGTTAT", "protein_bind"),
("FRT", "GAAGTTCCTATTCTCTAGAAAGTATAGGAACTTC", "protein_bind"),
("attB1", "ACAAGTTTGTACAAAAAAGCAGGCT", "protein_bind"),
("attB2", "ACCCAGCTTTCTTGTACAAAGTGGT", "protein_bind"),
]
# Curated common cloning enzymes shown by default in restriction analysis.
COMMON_ENZYMES = [
"EcoRI", "BamHI", "HindIII", "XhoI", "NotI", "XbaI", "SpeI", "PstI",
"SalI", "KpnI", "SacI", "SmaI", "NcoI", "NdeI", "NheI", "BglII", "EcoRV",
"ClaI", "ApaI", "AscI", "PacI", "SbfI", "AflII", "MluI", "AgeI", "BsrGI",
"BsaI", "BsmBI", "BbsI", "DraI",
]
# ── helpers ──────────────────────────────────────────────────────────────
def revcomp(seq: str) -> str:
return seq.translate(_COMP)[::-1]
def gc_percent(seq: str) -> float:
s = seq.upper()
n = sum(1 for c in s if c in "ACGT")
return round(100.0 * sum(1 for c in s if c in "GC") / n, 1) if n else 0.0
def _color_for(ftype: str, name: str) -> str:
t = (ftype or "").lower()
n = (name or "").lower()
if re.search(r"\b(amp|kan|neo|cm|chlor|tet|spec|hygro|puro|bla|bsd|zeo)r?\b", n) \
or "resistance" in n:
return _TYPE_COLORS["resistance"]
if any(k in n for k in ("his", "flag", "tag", "myc", "gfp", "rfp", "mcherry", "ha ")):
return _TYPE_COLORS["tag"]
return _TYPE_COLORS.get(t, _DEFAULT_COLOR)
def _clean_dna(text: str) -> str:
return re.sub(r"[^A-Za-z]", "", text or "").upper()
# ── parsing ────────────────────────────────────────────────────────────────
def _label_from_qualifiers(q: Dict[str, Any]) -> str:
for key in ("label", "gene", "product", "standard_name", "note"):
v = q.get(key)
if v:
return str(v[0] if isinstance(v, (list, tuple)) else v)[:60]
return ""
def _record_to_plasmid(rec, source: str, *, default_topology: str = "linear") -> Dict[str, Any]:
"""Normalise a Biopython ``SeqRecord`` (GenBank / SnapGene / EMBL β€” anything
SeqIO hands back with features + a topology annotation) into the plasmid
model. Shared by every structured-format parser so they stay identical."""
seq = str(rec.seq).upper()
topo = (rec.annotations.get("topology") or "").lower()
topology = "circular" if topo == "circular" else ("linear" if topo == "linear" else default_topology)
feats: List[Dict[str, Any]] = []
for f in rec.features:
if f.type in ("source",):
continue
if len(feats) >= MAX_FEATURES:
break
try:
start = int(f.location.start)
end = int(f.location.end)
except Exception: # noqa: BLE001 β€” compound/fuzzy locations
continue
if start < 0 or end <= start or end > len(seq):
continue
name = _label_from_qualifiers(dict(f.qualifiers)) or f.type
strand = getattr(f.location, "strand", None) # Biopython β‰₯1.85: on location
feats.append({
"name": name, "type": f.type,
"start": start, "end": end,
"strand": 1 if (strand or 1) >= 0 else -1,
"color": _color_for(f.type, name),
"notes": "",
})
return {
"name": (rec.name or rec.id or "plasmid")[:80],
"sequence": seq, "length": len(seq),
"topology": topology, "gc": gc_percent(seq),
"features": feats, "source": source,
}
def parse_genbank(text: str) -> Dict[str, Any]:
from Bio import SeqIO
rec = SeqIO.read(io.StringIO(text), "genbank")
return _record_to_plasmid(rec, "genbank", default_topology="linear")
def parse_snapgene(data: bytes) -> Dict[str, Any]:
"""Parse a SnapGene ``.dna`` binary (via Biopython's SnapGene reader). The
format carries its own sequence, topology, and rich feature track."""
from Bio import SeqIO
rec = SeqIO.read(io.BytesIO(data), "snapgene")
# SnapGene maps are circular far more often than not; honour the file's
# own topology annotation when present, else assume circular.
return _record_to_plasmid(rec, "snapgene", default_topology="circular")
def parse_fasta(text: str) -> Dict[str, Any]:
from Bio import SeqIO
rec = SeqIO.read(io.StringIO(text), "fasta")
seq = str(rec.seq).upper()
return {
"name": (rec.id or "sequence")[:80],
"sequence": seq, "length": len(seq),
"topology": "circular", "gc": gc_percent(seq),
"features": [], "source": "fasta",
}
def parse_plasmid(text: str, *, topology: Optional[str] = None) -> Dict[str, Any]:
"""Detect the format (GenBank / FASTA / raw DNA) and normalise. Raises
ValueError with a friendly message on bad input."""
if not text or not text.strip():
raise ValueError("Paste a sequence, GenBank, or FASTA record.")
if len(text) > MAX_INPUT_TEXT:
raise ValueError(f"Input is larger than {MAX_INPUT_TEXT:,} bytes β€” paste just "
"the plasmid, not a whole dataset.")
head = text.lstrip()[:200].upper()
plasmid: Dict[str, Any]
if head.startswith("LOCUS") or "\nORIGIN" in text.upper() or "FEATURES " in text.upper():
try:
plasmid = parse_genbank(text)
except Exception as exc: # noqa: BLE001
raise ValueError(f"Couldn't parse the GenBank record: {exc}") from exc
elif text.lstrip().startswith(">"):
try:
plasmid = parse_fasta(text)
except Exception as exc: # noqa: BLE001
raise ValueError(f"Couldn't parse the FASTA record: {exc}") from exc
else:
seq = _clean_dna(text)
if not seq:
raise ValueError("No DNA found in the input.")
if not _DNA_RE.match(seq):
raise ValueError("Input contains non-DNA characters.")
plasmid = {
"name": "untitled", "sequence": seq, "length": len(seq),
"topology": "circular", "gc": gc_percent(seq),
"features": [], "source": "raw",
}
if plasmid["length"] == 0:
raise ValueError("The record has no sequence.")
if plasmid["length"] > MAX_LEN:
raise ValueError(f"Sequence is longer than {MAX_LEN:,} bp β€” that's a "
"genome-scale tool's job, not a plasmid editor.")
if topology in ("circular", "linear"):
plasmid["topology"] = topology
return plasmid
_SNAPGENE_COOKIE = b"SnapGene"
def parse_binary(data: bytes, *, filename: Optional[str] = None,
topology: Optional[str] = None) -> Dict[str, Any]:
"""Parse a *binary* sequence upload (currently SnapGene ``.dna``) into the
plasmid model. Detects SnapGene by the ``.dna`` extension or its file
signature (first byte 0x09 + a "SnapGene" cookie). Raises ``ValueError``
with a friendly message on unknown / oversize / corrupt input."""
if not data:
raise ValueError("The uploaded file is empty.")
if len(data) > MAX_INPUT_TEXT:
raise ValueError(f"File is larger than {MAX_INPUT_TEXT:,} bytes β€” upload "
"just the plasmid, not a whole dataset.")
name_l = (filename or "").lower()
is_snapgene = (
name_l.endswith(".dna")
or (len(data) > 14 and data[0] == 0x09 and _SNAPGENE_COOKIE in data[:64])
)
if not is_snapgene:
raise ValueError("Unrecognised file. Upload a SnapGene .dna, or paste / "
"upload a GenBank, FASTA, or EMBL text file.")
try:
plasmid = parse_snapgene(data)
except ValueError:
raise
except Exception as exc: # noqa: BLE001 β€” Bio raises a grab-bag on bad bytes
raise ValueError(f"Couldn't read the SnapGene file: {exc}") from exc
# SnapGene records are often unnamed ("Exported", or Biopython's
# "<unknown name>" placeholder) β€” fall back to the filename stem.
cur = (plasmid.get("name") or "").strip().lower()
if filename and (cur in ("", "plasmid", "exported", "untitled", "sequence")
or cur.startswith("<unknown")):
import os
stem = os.path.splitext(os.path.basename(filename))[0][:80]
if stem:
plasmid["name"] = stem
if plasmid["length"] == 0:
raise ValueError("The SnapGene file has no sequence.")
if plasmid["length"] > MAX_LEN:
raise ValueError(f"Sequence is longer than {MAX_LEN:,} bp β€” that's a "
"genome-scale tool's job, not a plasmid editor.")
# An explicit UI topology choice overrides the file's (parity with text imports).
if topology in ("circular", "linear"):
plasmid["topology"] = topology
return plasmid
# ── auto-annotation ──────────────────────────────────────────────────────
def find_orfs(seq: str, min_aa: int = 100, max_orfs: int = 500) -> List[Dict[str, Any]]:
"""ORFs (ATGβ†’stop) β‰₯ ``min_aa`` on both strands. A single LINEAR pass per
frame β€” track the first ATG since the last stop, close the ORF on the next
stop. (The old nested scan was O(nΒ²): a long stop-less, ATG-rich paste would
pin the worker β€” an audit DoS finding.)"""
out: List[Dict[str, Any]] = []
L = len(seq)
stops = {"TAA", "TAG", "TGA"}
for strand, s in ((1, seq), (-1, revcomp(seq))):
for frame in range(3):
orf_start = -1
i = frame
while i + 3 <= L:
cod = s[i:i + 3]
if orf_start < 0:
if cod == "ATG":
orf_start = i
elif cod in stops:
aa = (i - orf_start) // 3
if aa >= min_aa:
if strand == 1:
fs, fe = orf_start, i + 3
else:
fs, fe = L - (i + 3), L - orf_start
out.append({"name": f"ORF ({aa} aa)", "type": "CDS",
"start": fs, "end": fe, "strand": strand,
"color": _TYPE_COLORS["cds"], "notes": "auto-detected ORF"})
if len(out) >= max_orfs:
return out
orf_start = -1
i += 3
return out
def find_motifs(seq: str) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
up = seq.upper()
for name, motif, ftype in _MOTIFS:
for strand, needle in ((1, motif), (-1, revcomp(motif))):
start = up.find(needle)
while start != -1:
out.append({"name": name, "type": ftype, "start": start,
"end": start + len(needle), "strand": strand,
"color": _color_for(ftype, name), "notes": "motif match"})
start = up.find(needle, start + 1)
return out
def auto_annotate(plasmid: Dict[str, Any], *, orfs: bool = True) -> Dict[str, Any]:
"""Add motif + ORF features when the record has none (FASTA / raw). Mutates
and returns ``plasmid``. No-op when GenBank features are already present."""
if plasmid.get("features"):
return plasmid
seq = plasmid["sequence"]
feats = find_motifs(seq)
if orfs:
feats += find_orfs(seq)
# De-overlapping ORFs: keep the longest at each locus (cheap: drop an ORF
# fully contained in a longer one).
cds = sorted([f for f in feats if f["type"] == "CDS"], key=lambda f: f["end"] - f["start"], reverse=True)
kept_cds: List[Dict[str, Any]] = []
for f in cds:
if not any(k["start"] <= f["start"] and f["end"] <= k["end"] and k is not f for k in kept_cds):
kept_cds.append(f)
feats = [f for f in feats if f["type"] != "CDS"] + kept_cds
feats.sort(key=lambda f: (f["start"], f["end"]))
plasmid["features"] = feats
plasmid["auto_annotated"] = True
return plasmid
# ── export ───────────────────────────────────────────────────────────────
def build_genbank(plasmid: Dict[str, Any]) -> str:
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqFeature import SeqFeature, FeatureLocation
from Bio import SeqIO
rec = SeqRecord(Seq(plasmid["sequence"]),
id=(plasmid.get("name") or "plasmid")[:16],
name=(plasmid.get("name") or "plasmid")[:16],
description=plasmid.get("name") or "")
rec.annotations["molecule_type"] = "DNA"
rec.annotations["topology"] = plasmid.get("topology", "linear")
rec.annotations["data_file_division"] = "SYN"
for f in plasmid.get("features", []):
loc = FeatureLocation(int(f["start"]), int(f["end"]),
strand=1 if f.get("strand", 1) >= 0 else -1)
rec.features.append(SeqFeature(loc, type=f.get("type", "misc_feature"),
qualifiers={"label": [f.get("name", "")]}))
out = io.StringIO()
SeqIO.write(rec, out, "genbank")
return out.getvalue()
def sanitize_features(features: Any, seq_len: int) -> List[Dict[str, Any]]:
"""Validate + clamp client-supplied features before we export or store them.
Drops anything malformed; clamps coordinates to [0, seq_len]; forces ``color``
to a safe hex (defends the SVG/style rendering against injection); caps count.
Never raises β€” returns a clean list."""
out: List[Dict[str, Any]] = []
if not isinstance(features, list):
return out
for f in features[:MAX_FEATURES]:
if not isinstance(f, dict):
continue
try:
start = int(f.get("start"))
end = int(f.get("end"))
except (TypeError, ValueError):
continue
start = max(0, min(start, seq_len))
end = max(0, min(end, seq_len))
if end <= start:
continue
color = f.get("color")
if not (isinstance(color, str) and _COLOR_RE.match(color)):
color = _DEFAULT_COLOR
strand = -1 if f.get("strand") in (-1, "-1", "-") else 1
out.append({
"name": str(f.get("name", ""))[:120],
"type": str(f.get("type", "misc_feature"))[:40],
"start": start, "end": end, "strand": strand,
"color": color, "notes": str(f.get("notes", ""))[:200],
})
return out
def build_fasta(plasmid: Dict[str, Any]) -> str:
seq = plasmid["sequence"]
name = (plasmid.get("name") or "sequence").replace(" ", "_")
lines = [f">{name} ({plasmid.get('topology', 'linear')}, {len(seq)} bp)"]
for i in range(0, len(seq), 70):
lines.append(seq[i:i + 70])
return "\n".join(lines) + "\n"
# ── restriction analysis + digest ──────────────────────────────────────────
def _enzyme_batch(names: Optional[List[str]]):
from Bio.Restriction import RestrictionBatch, AllEnzymes
if not names:
names = COMMON_ENZYMES
valid = []
known = {str(e) for e in AllEnzymes}
for n in names:
if n in known:
valid.append(n)
return RestrictionBatch(valid), valid
def restriction_analysis(seq: str, topology: str = "circular",
names: Optional[List[str]] = None) -> Dict[str, Any]:
"""Per-enzyme cut sites over the (default common) enzyme set, classified
into single / double / multi / non-cutters β€” circular-aware."""
from Bio.Seq import Seq
batch, valid = _enzyme_batch(names)
linear = topology != "circular"
s = Seq(seq)
results = batch.search(s, linear=linear) # {enzyme: [positions(1-based)]}
enzymes = []
for enz, sites in results.items():
enzymes.append({
"name": str(enz),
"sites": sorted(sites),
"count": len(sites),
"overhang": _overhang_label(enz),
})
enzymes.sort(key=lambda e: (e["count"], e["name"]))
return {
"enzymes": enzymes,
"single_cutters": [e["name"] for e in enzymes if e["count"] == 1],
"double_cutters": [e["name"] for e in enzymes if e["count"] == 2],
"non_cutters": [e["name"] for e in enzymes if e["count"] == 0],
"topology": topology,
"length": len(seq),
}
def _overhang_label(enz) -> str:
try:
if enz.is_blunt():
return "blunt"
return "5' overhang" if enz.is_5overhang() else "3' overhang"
except Exception: # noqa: BLE001
return ""
def _fragments(positions: List[int], length: int, circular: bool) -> List[int]:
"""Fragment lengths from cut positions (Bio.Restriction 1-based, = first
base of the downstream fragment). Circular wraps the origin-spanning piece."""
bnd = sorted({(p - 1) for p in positions if 1 <= p <= length})
if not bnd:
return [length]
if circular:
if len(bnd) == 1:
return [length] # one cut linearises the circle
frags = [bnd[i] - bnd[i - 1] for i in range(1, len(bnd))]
frags.append(length - bnd[-1] + bnd[0]) # the piece across the origin
else:
frags = [bnd[0]] + [bnd[i] - bnd[i - 1] for i in range(1, len(bnd))] + [length - bnd[-1]]
return sorted((f for f in frags if f > 0), reverse=True)
def digest(seq: str, topology: str, names: List[str]) -> Dict[str, Any]:
"""Cut with the chosen enzymes β†’ fragment sizes (for a virtual gel) + the
combined cut positions (to draw on the map)."""
from Bio.Seq import Seq
batch, valid = _enzyme_batch(names)
linear = topology != "circular"
results = batch.search(Seq(seq), linear=linear)
positions: List[int] = []
per_enzyme = []
for enz, sites in results.items():
positions.extend(sites)
per_enzyme.append({"name": str(enz), "sites": sorted(sites)})
frags = _fragments(positions, len(seq), not linear)
return {
"enzymes": valid,
"per_enzyme": per_enzyme,
"cut_positions": sorted(set(positions)),
"fragments": frags,
"n_fragments": len(frags),
"topology": topology,
"length": len(seq),
}