Genome_Visualization_Tool / genomics_parsing.py
GENOMICS-CDDBRG's picture
Upload 7 files
846b701 verified
Raw History Blame Contribute Delete
22.3 kB
"""
genomics_parsing.py
Universal input parsing layer for the Unified Genomics Suite.
Design principle: every format that can be parsed correctly with plain Python
is parsed with plain Python, so the bulk of this module has no dependency
beyond the standard library and pandas. Biopython is used ONLY for GenBank and
EMBL flat files, since those formats have enough real-world edge cases
(joined/complement locations, multi-line qualifiers, multi-record files) that
hand-rolling a parser would be a correctness risk rather than a dependency
saving. If Biopython is unavailable, GenBank/EMBL input fails with a clear
message; every other format still works.
Supported inputs
1. FASTA -> pure Python
2. GenBank / EMBL (single or multi-record) -> Biopython (Bio.SeqIO)
3. GFF3/GTF + matching FASTA -> pure Python
4. BED + matching FASTA -> pandas
5. Annotation table (CSV/TSV) + FASTA -> pandas
6. ZIP bundles containing any combination above, auto-detected
7. Prokka output directory (.gff/.ffn/.faa/.tsv), for the annotation
workbench tool specifically
Every parser returns data in the same shape used throughout the suite:
records: List[GenomeRecord] (id, description, sequence)
tables: Dict[str, pd.DataFrame] keyed by record id, FEATURE_COLUMNS schema
"""
from __future__ import annotations
import gzip
import io
import os
import re
import zipfile
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
import pandas as pd
try:
from Bio import SeqIO # only hard dependency, only used for GenBank/EMBL
_HAVE_BIOPYTHON = True
except Exception:
_HAVE_BIOPYTHON = False
FEATURE_COLUMNS = [
"record_id", "feature_type", "label", "start", "end", "length", "strand",
"gene", "locus_tag", "product", "protein_id", "translation", "note", "source",
]
FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn"}
GB_EXTS = {".gb", ".gbk", ".genbank"}
EMBL_EXTS = {".embl"}
GFF_EXTS = {".gff", ".gff3", ".gtf"}
BED_EXTS = {".bed"}
TABLE_EXTS = {".csv", ".tsv"}
DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan")
def reverse_complement(seq: str) -> str:
return str(seq).translate(DNA_COMPLEMENT)[::-1]
@dataclass
class GenomeRecord:
"""Minimal stand-in for a Bio.SeqRecord, used by the pure-Python parsers
so the rest of the suite never has to care whether Biopython produced the
record or the plain-text FASTA/GFF parser did."""
id: str
description: str
seq: str
def __len__(self):
return len(self.seq)
@dataclass
class ParsedGenome:
records: List[GenomeRecord]
tables: Dict[str, pd.DataFrame]
source_format: str
notes: List[str] = field(default_factory=list)
# ------------------------------------------------------------------
# Low-level helpers
# ------------------------------------------------------------------
def _decode(data: bytes) -> str:
return data.decode("utf-8", errors="replace")
def maybe_gunzip(name: str, data: bytes) -> Tuple[str, bytes]:
if str(name).lower().endswith(".gz"):
return os.path.splitext(name)[0], gzip.decompress(data)
return name, data
def infer_kind(filename: str) -> str:
name = str(filename).lower()
if name.endswith(".gz"):
name = os.path.splitext(name)[0]
if name.endswith(".zip"):
return "zip"
ext = os.path.splitext(name)[1]
if ext in GB_EXTS:
return "genbank"
if ext in EMBL_EXTS:
return "embl"
if ext in FASTA_EXTS:
return "fasta"
if ext in GFF_EXTS:
return "gff"
if ext in BED_EXTS:
return "bed"
if ext in TABLE_EXTS:
return "table"
return "unknown"
def clean_text(value: object) -> str:
return re.sub(r"\s+", " ", str(value if value is not None else "")).strip()
def empty_feature_table() -> pd.DataFrame:
return pd.DataFrame(columns=FEATURE_COLUMNS)
# ------------------------------------------------------------------
# FASTA (pure Python, no Biopython needed)
# ------------------------------------------------------------------
def parse_fasta(data: bytes) -> List[GenomeRecord]:
"""Minimal, well-tested FASTA parser. Handles CRLF/LF, blank lines, and
multi-line sequences. Sequence characters are upper-cased; anything not
a letter is dropped (guards against stray whitespace or '*' terminators
sometimes seen in protein FASTA pasted into the wrong box)."""
text = _decode(data)
records: List[GenomeRecord] = []
header: Optional[str] = None
chunks: List[str] = []
def flush():
if header is not None:
seq = "".join(chunks).upper()
seq = "".join(ch for ch in seq if ch.isalpha())
rec_id = header.split()[0] if header.split() else header
records.append(GenomeRecord(id=rec_id, description=header, seq=seq))
for raw_line in text.splitlines():
line = raw_line.rstrip("\r")
if not line:
continue
if line.startswith(">"):
flush()
header = line[1:].strip()
chunks = []
else:
chunks.append(line)
flush()
return records
# ------------------------------------------------------------------
# GFF3 / GTF (pure Python - no gffutils dependency)
# ------------------------------------------------------------------
def _parse_gff_attributes(attr_field: str, is_gtf: bool) -> Dict[str, str]:
attrs: Dict[str, str] = {}
if not attr_field:
return attrs
if is_gtf:
# GTF: key "value"; key "value"; (space separated, quoted values)
for m in re.finditer(r'(\w+)\s+"([^"]*)"', attr_field):
attrs[m.group(1)] = m.group(2)
else:
# GFF3: key=value;key=value
for part in attr_field.split(";"):
part = part.strip()
if not part or "=" not in part:
continue
k, v = part.split("=", 1)
attrs[k.strip()] = v.strip()
return attrs
def parse_gff_text(gff_text: str, record_lookup: Dict[str, GenomeRecord]) -> Dict[str, pd.DataFrame]:
"""Parse GFF3 or GTF feature lines into the shared FEATURE_COLUMNS schema.
record_lookup maps sequence id -> GenomeRecord, used only to clip
coordinates to the real sequence length and to bucket rows by record.
"""
rows_by_record: Dict[str, list] = {rid: [] for rid in record_lookup}
is_gtf = False
# quick heuristic: GTF attribute fields use `key "value";`, GFF3 uses `key=value`
sample_lines = [l for l in gff_text.splitlines() if l and not l.startswith("#")][:20]
if sample_lines:
sample_attrs = sample_lines[0].split("\t")
if len(sample_attrs) >= 9 and '"' in sample_attrs[8] and "=" not in sample_attrs[8].split(";")[0]:
is_gtf = True
for line in gff_text.splitlines():
if not line or line.startswith("#"):
continue
if line.upper().startswith("##FASTA"):
break
parts = line.rstrip("\n").split("\t")
if len(parts) < 9:
continue
seqid, _source, ftype, start_s, end_s, _score, strand_s, _phase, attr_field = parts[:9]
record = record_lookup.get(seqid) or record_lookup.get(seqid.split()[0])
if record is None:
continue
try:
start = int(start_s) - 1 # GFF/GTF are 1-based inclusive; store 0-based half-open
end = int(end_s)
except ValueError:
continue
attrs = _parse_gff_attributes(attr_field, is_gtf)
label = (attrs.get("Name") or attrs.get("gene") or attrs.get("gene_id")
or attrs.get("locus_tag") or attrs.get("ID") or ftype)
strand = 1 if strand_s == "+" else -1 if strand_s == "-" else 0
rows_by_record[record.id].append({
"record_id": record.id,
"feature_type": clean_text(ftype),
"label": clean_text(label),
"start": max(0, start),
"end": min(len(record.seq), end),
"length": max(0, end - start),
"strand": strand,
"gene": attrs.get("gene", ""),
"locus_tag": attrs.get("locus_tag", ""),
"product": attrs.get("product", ""),
"protein_id": attrs.get("protein_id", ""),
"translation": "",
"note": attrs.get("Note", attrs.get("note", "")),
"source": "GFF/GTF annotation",
})
return {
rid: (pd.DataFrame(rows, columns=FEATURE_COLUMNS)
.sort_values(["start", "end"], kind="stable").reset_index(drop=True))
for rid, rows in rows_by_record.items()
}
# ------------------------------------------------------------------
# BED (pandas)
# ------------------------------------------------------------------
def parse_bed_text(bed_text: str, record_lookup: Dict[str, GenomeRecord]) -> Dict[str, pd.DataFrame]:
lines = [l for l in bed_text.splitlines() if l.strip() and not l.startswith(("#", "track", "browser"))]
if not lines:
return {rid: empty_feature_table() for rid in record_lookup}
bed = pd.read_csv(io.StringIO("\n".join(lines)), sep="\t", header=None)
ncol = min(6, bed.shape[1])
bed = bed.iloc[:, :ncol]
bed.columns = ["seqid", "start", "end", "name", "score", "strand"][:ncol]
tables: Dict[str, pd.DataFrame] = {}
for rid, record in record_lookup.items():
sub = bed[bed["seqid"].astype(str).isin([rid, rid.split()[0]])].copy()
if sub.empty:
tables[rid] = empty_feature_table()
continue
out = pd.DataFrame({
"record_id": rid,
"feature_type": "bed_feature",
"label": sub["name"].astype(str) if "name" in sub else "bed_feature",
"start": sub["start"].astype(int).clip(lower=0),
"end": sub["end"].astype(int).clip(upper=len(record.seq)),
"strand": (sub["strand"].replace({"+": 1, "-": -1}).fillna(0).astype(int)
if "strand" in sub else 0),
"gene": sub["name"].astype(str) if "name" in sub else "",
"locus_tag": "", "product": "", "protein_id": "", "translation": "",
"note": "Imported BED coordinate", "source": "BED annotation",
})
out["length"] = (out["end"] - out["start"]).clip(lower=0)
tables[rid] = out[FEATURE_COLUMNS].sort_values(["start", "end"], kind="stable").reset_index(drop=True)
return tables
# ------------------------------------------------------------------
# Generic annotation table (CSV/TSV with start/end columns)
# ------------------------------------------------------------------
def parse_annotation_table_text(table_text: str, record_lookup: Dict[str, GenomeRecord]) -> Dict[str, pd.DataFrame]:
first_line = table_text.splitlines()[0] if table_text.splitlines() else ""
sep = "," if first_line.count(",") >= first_line.count("\t") else "\t"
df = pd.read_csv(io.StringIO(table_text), sep=sep)
df.columns = [c.strip() for c in df.columns]
lower = {c.lower(): c for c in df.columns}
start_col, end_col = lower.get("start"), lower.get("end")
if start_col is None or end_col is None:
raise ValueError("Annotation table must contain 'start' and 'end' columns.")
record_col = lower.get("record_id") or lower.get("seqid") or lower.get("contig") or lower.get("chrom")
type_col = lower.get("feature_type") or lower.get("type")
label_col = lower.get("label") or lower.get("name") or lower.get("gene")
strand_col = lower.get("strand")
product_col = lower.get("product")
locus_col = lower.get("locus_tag")
tables: Dict[str, pd.DataFrame] = {}
for rid, record in record_lookup.items():
sub = df if record_col is None else df[df[record_col].astype(str).isin([rid, rid.split()[0]])].copy()
if sub.empty:
tables[rid] = empty_feature_table()
continue
out = pd.DataFrame({
"record_id": rid,
"feature_type": sub[type_col].astype(str) if type_col else "misc_feature",
"label": sub[label_col].astype(str) if label_col else "feature",
"start": sub[start_col].astype(int).clip(lower=0),
"end": sub[end_col].astype(int).clip(upper=len(record.seq)),
"strand": (sub[strand_col].replace({"+": 1, "-": -1}).fillna(0).astype(int)
if strand_col else 0),
"gene": sub[label_col].astype(str) if label_col else "",
"locus_tag": sub[locus_col].astype(str) if locus_col else "",
"product": sub[product_col].astype(str) if product_col else "",
"protein_id": "", "translation": "",
"note": "Imported annotation table", "source": "Annotation table",
})
out["length"] = (out["end"] - out["start"]).clip(lower=0)
tables[rid] = out[FEATURE_COLUMNS].sort_values(["start", "end"], kind="stable").reset_index(drop=True)
return tables
# ------------------------------------------------------------------
# GenBank / EMBL (Biopython required)
# ------------------------------------------------------------------
def parse_genbank_or_embl(data: bytes, fmt: str) -> ParsedGenome:
if not _HAVE_BIOPYTHON:
raise RuntimeError(
"Biopython is required to parse GenBank/EMBL files. Install it with: "
"pip install biopython. Every other input format (FASTA, GFF/GTF, "
"BED, annotation table, ZIP bundles of these) works without it."
)
handle = io.StringIO(_decode(data))
bio_records = list(SeqIO.parse(handle, fmt))
if not bio_records:
raise ValueError(f"No {fmt.upper()} records were found in the uploaded file.")
records = [GenomeRecord(id=r.id, description=clean_text(getattr(r, "description", "")), seq=str(r.seq).upper())
for r in bio_records]
tables: Dict[str, pd.DataFrame] = {}
for bio_rec, rec in zip(bio_records, records):
rows = []
for feat in getattr(bio_rec, "features", []):
try:
loc = feat.location
strand = loc.strand if loc.strand in (-1, 1) else 0
start, end = int(loc.start), int(loc.end)
q = getattr(feat, "qualifiers", {}) or {}
label = None
for key in ("gene", "locus_tag", "product", "standard_name", "note", "ID", "Name"):
if q.get(key):
label = clean_text(q[key][0])
break
rows.append({
"record_id": rec.id,
"feature_type": clean_text(getattr(feat, "type", "feature")),
"label": label or clean_text(getattr(feat, "type", "feature")),
"start": max(0, start),
"end": min(len(rec.seq), end),
"length": max(0, end - start),
"strand": int(strand),
"gene": "; ".join(q.get("gene", [])),
"locus_tag": "; ".join(q.get("locus_tag", [])),
"product": "; ".join(q.get("product", [])),
"protein_id": "; ".join(q.get("protein_id", [])),
"translation": "; ".join(q.get("translation", [])),
"note": "; ".join(q.get("note", [])),
"source": f"{fmt.upper()} annotation",
})
except Exception:
continue
tables[rec.id] = (pd.DataFrame(rows, columns=FEATURE_COLUMNS)
.sort_values(["start", "end"], kind="stable").reset_index(drop=True))
return ParsedGenome(records, tables, fmt, [f"Parsed annotated {fmt.upper()} input."])
# ------------------------------------------------------------------
# Top-level dispatch
# ------------------------------------------------------------------
def _record_lookup(records: List[GenomeRecord]) -> Dict[str, GenomeRecord]:
lookup = {r.id: r for r in records}
lookup.update({r.id.split()[0]: r for r in records})
return lookup
def parse_fasta_plus_annotation(primary_bytes: bytes, primary_kind: str, fasta_bytes: bytes) -> ParsedGenome:
records = parse_fasta(fasta_bytes)
if not records:
raise ValueError("No FASTA sequences were found in the matching FASTA file.")
lookup = _record_lookup(records)
text = _decode(primary_bytes)
if primary_kind == "gff":
tables = parse_gff_text(text, lookup)
note = "Parsed GFF/GTF annotation with matching FASTA sequence."
elif primary_kind == "bed":
tables = parse_bed_text(text, lookup)
note = "Parsed BED annotation with matching FASTA sequence."
elif primary_kind == "table":
tables = parse_annotation_table_text(text, lookup)
note = "Parsed annotation table with matching FASTA sequence."
else:
raise ValueError(f"Unsupported paired-annotation kind: {primary_kind}")
for rid in lookup:
tables.setdefault(rid, empty_feature_table())
return ParsedGenome(records, tables, f"{primary_kind}_fasta", [note])
def parse_fasta_only(fasta_bytes: bytes) -> ParsedGenome:
records = parse_fasta(fasta_bytes)
if not records:
raise ValueError("No FASTA sequences were found.")
tables = {r.id: empty_feature_table() for r in records}
return ParsedGenome(records, tables, "fasta",
["Parsed FASTA input. No native annotation; feature tables are empty "
"unless ORF prediction is run separately."])
def parse_zip_bundle(zip_bytes: bytes) -> ParsedGenome:
files: Dict[str, bytes] = {}
with zipfile.ZipFile(io.BytesIO(zip_bytes)) as archive:
for info in archive.infolist():
if info.is_dir():
continue
name = os.path.basename(info.filename)
if not name:
continue
n, b = maybe_gunzip(name, archive.read(info.filename))
files[n] = b
kinds = {name: infer_kind(name) for name in files}
rich = next((n for n, k in kinds.items() if k in {"genbank", "embl"}), None)
if rich:
return parse_genbank_or_embl(files[rich], kinds[rich])
fasta_name = next((n for n, k in kinds.items() if k == "fasta"), None)
gff_name = next((n for n, k in kinds.items() if k == "gff"), None)
bed_name = next((n for n, k in kinds.items() if k == "bed"), None)
table_name = next((n for n, k in kinds.items() if k == "table"), None)
if fasta_name and gff_name:
return parse_fasta_plus_annotation(files[gff_name], "gff", files[fasta_name])
if fasta_name and bed_name:
return parse_fasta_plus_annotation(files[bed_name], "bed", files[fasta_name])
if fasta_name and table_name:
return parse_fasta_plus_annotation(files[table_name], "table", files[fasta_name])
if fasta_name:
return parse_fasta_only(files[fasta_name])
raise ValueError(
"The ZIP archive did not contain a supported combination of files. "
"Supported combinations: GenBank/EMBL alone; FASTA alone; or FASTA "
"paired with one of GFF/GTF, BED, or a CSV/TSV annotation table."
)
def parse_any(primary_name: str, primary_bytes: bytes,
secondary_name: Optional[str] = None, secondary_bytes: Optional[bytes] = None) -> ParsedGenome:
"""Single entry point used by the Streamlit app. Auto-detects format from
the primary file's extension, using the secondary file as the paired
FASTA when the primary file is an annotation-only format."""
primary_name, primary_bytes = maybe_gunzip(primary_name, primary_bytes)
kind = infer_kind(primary_name)
if kind == "zip":
return parse_zip_bundle(primary_bytes)
if kind in {"genbank", "embl"}:
return parse_genbank_or_embl(primary_bytes, kind)
if kind == "fasta":
return parse_fasta_only(primary_bytes)
if kind in {"gff", "bed", "table"}:
if secondary_bytes is None:
raise ValueError(f"A {kind.upper()} file needs a matching FASTA file uploaded alongside it.")
secondary_name, secondary_bytes = maybe_gunzip(secondary_name or "sequence.fasta", secondary_bytes)
return parse_fasta_plus_annotation(primary_bytes, kind, secondary_bytes)
raise ValueError(
f"Could not determine the file type of '{primary_name}'. Supported extensions: "
f"FASTA {sorted(FASTA_EXTS)}, GenBank {sorted(GB_EXTS)}, EMBL {sorted(EMBL_EXTS)}, "
f"GFF/GTF {sorted(GFF_EXTS)}, BED {sorted(BED_EXTS)}, table {sorted(TABLE_EXTS)}, or .zip."
)
# ------------------------------------------------------------------
# Prokka output directory reader (for the annotation workbench tool)
# ------------------------------------------------------------------
def read_prokka_outputs(outdir: str, prefix: str) -> ParsedGenome:
"""Build a ParsedGenome from a completed Prokka run's .fna/.gff outputs,
so the annotation workbench can reuse every downstream metric (codon
usage, ENC, CAI, GC skew, etc.) from genomics_core exactly as the other
tools do, instead of keeping a second, separately-maintained set of
genome statistics functions."""
from pathlib import Path
outdir_p = Path(outdir)
def find(ext):
exact = outdir_p / f"{prefix}.{ext}"
if exact.exists():
return exact
matches = sorted(outdir_p.glob(f"*.{ext}"))
return matches[0] if matches else None
fna_path = find("fna")
gff_path = find("gff")
if fna_path is None:
raise FileNotFoundError(f"No Prokka .fna output found in {outdir}.")
with open(fna_path, "rb") as fh:
records = parse_fasta(fh.read())
if not records:
raise ValueError("Prokka's .fna output contained no sequences.")
lookup = _record_lookup(records)
if gff_path is not None:
with open(gff_path, "r", encoding="utf-8", errors="replace") as fh:
gff_text = fh.read().split("##FASTA")[0]
tables = parse_gff_text(gff_text, lookup)
else:
tables = {}
for rid in lookup:
tables.setdefault(rid, empty_feature_table())
return ParsedGenome(records, tables, "prokka", ["Loaded Prokka annotation output."])