Spaces:
Build error
Build error
Update app.py
Browse files1223456789101191011121213141516171819202122232425263 unmodified lines3031323322343536373839404142434422 unmodified lines67686957707172738 unmodified lines828384858687888914 unmodified lines10410510610710810992939495969798991001011021031041051061071081091101101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591605 unmodified lines1661671681221231241251261271691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182191 unmodified line22122222313522422522622763 unmodified lines29129229329429529629729829930021 unmodified lines32232332423223332532632732847 unmodified lines3763773782872883793803813823 unmodified lines38638738829838939039139230339339439539611 unmodified lines40840941032141141241341417 unmodified lines43243343434543543643743835043944044144211 unmodified lines4544554563684574584594603724614624634644654664674683794694704711 unmodified line47347447538747647747847922 unmodified lines50250350441641750550650750810 unmodified lines51952052143452252352452524 unmodified lines55055155246555355455555618 unmodified lines57557657749057857958058119 unmodified lines6016026035165176046056066071 unmodified line60961061152561261361461561653061761861962062162262353762462562662740 unmodified lines66866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472558772672772872973059159273173273373473573673773873959859974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482520 unmodified lines8468478486316326338498508518528538548558568578588598608618628638648656356366376386396406418668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099106446459119129136479149159166499179186516529199209219229236569249259269279289296629309319329336669349359369372 unmodified lines940941942675676677678679680681682683684685686687688689690691692693694695696697698699700943944945946947948949950951703952953705954955707956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041709710711712713714104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108171710821083108410856 unmodified lines10921093109473010951096109710981 unmodified line1100110111027387397407417427431103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136745746747748749750751752753754755756757758113711381139114011411142114311441145114611471148114911501151115211531154115511561157760761762763764765766767115811591160116111621163116411651166769770116711681169117011711172117311741175117677511771178117911809 unmodified lines1190119111927917927931193119411951196119711982 unmodified lines12011202120312041205120680212071208120980512101211121280812131214121512168121217121812198151220122181712221223122412251226822122712281229123012311232123312341235828123612371238123983212401241124212431244124512461247124883912491250125112521253844125412551256125712581259850126012611262126312648558561265126612671268126986012701271127212731274865127512768678681277127812798708718728738741280128112821283128412851286128712881289129012918778781292129312941295129688212971298129913002 unmodified lines13031304130589113061307130813093 unmodified lines13131314131590113161317903131813191320132113229081323132413251326132713289149151329133013311332133313341 unmodified line1336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813899231390139192513921393139413951396139713981399932933140014011402140314042 unmodified lines14071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115424 unmodified lines15471548154995215501551155215531554957155515569591557155815591560156115621563156415651566156715681569967968969970971972973974975157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616073 unmodified lines16111612161398816141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716387 unmodified lines164616471648101510161649165016511652165312 unmodified lines166616671668166916701671167216731674167516761677167810411679168016811682168316841685168616871688168916905 unmodified lines1696169716981057169917001701170217031704105917051706170717081709106410651710171117121713171417151069107010711072107310741075171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175210791080108110821083108410851086108710881089109010911092109310941095109610971098109911001753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821102178317841785178617871788178917901791179217931 unmodified line179517961797111017981799180018011802180318041805180611141807180818091810181118121813112118141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718388 unmodified lines184718481849185018511852185318541855185618571858185918601151115211531154115511561861186218631864186518661867186818691870116118711872187318741875116318761877187811661167116811691879188018811882188318841885188611751176117711781179188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192611831184192719281929193019311932193319341935193619371938193919401941118911901191194219431944194511931946194711951948194919501951119719521953195419551956120012011202195719581959196019611962196319641965196619671205196819691970"""GenomeScope Pro: publication grade genome visualization and genome composition analytics.GenomeScope Pro 2.0: publication grade genome visualization and genome composition analytics.
This version extends the original tool to support a methodological paper. It adds manygenome parameters, a wider set of publication quality figures, and several analysis tables.
Supported inputs:1. GenBank, EMBL, FASTA, GFF3 plus FASTA, BED plus FASTA, CSV/TSV annotation plus FASTA2. ZIP archives containing one of the above supported combinations
Main outputs:1. Linear and circular genome maps with distinct colours for feature classes2. GC content, GC skew, cumulative GC skew, nucleotide composition, CpG observed/expected3. CDS based codon usage, RSCU, ENC, codon adaptation index when a reference codon table is supplied4. Annotation tables, genome summary tables, and downloadable figure package1. Linear and circular genome maps with curated colour palettes for feature classes2. Genome composition: GC content, AT content, GC skew, AT skew, cumulative skews, nucleotide and dinucleotide composition, dinucleotide relative abundance (genomic signature), tetranucleotide frequency, CpG observed/expected, Shannon entropy, predicted origin and terminus of replication, and assembly statistics (N50, L50, N90)3. Codon analysis: codon usage, RSCU, RSCU heatmap, effective number of codons (ENC), codon adaptation index (CAI), amino acid usage, GC at codon positions, GC3s, neutrality plot, ENC plot against Wright expected curve, and PR2 bias plot4. Per CDS metrics table, annotation tables, genome summary tables, and a downloadable figure and data package suitable for a manuscript
References for the methods are listed in the sidebar so the output can be cited."""
import io3 unmodified linesimport mathimport zipfileimport tempfilefrom collections import Counterfrom dataclasses import dataclassfrom dataclasses import dataclass, fieldfrom typing import Dict, List, Optional, Tuple
import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dfrom matplotlib.colors import LinearSegmentedColormapimport numpy as npimport pandas as pdimport streamlit as st22 unmodified lines# Page and figure configuration# -----------------------------st.set_page_config( page_title="GenomeScope Pro", page_title="GenomeScope Pro 2.0", page_icon="🧬", layout="wide", initial_sidebar_state="expanded",8 unmodified lines "xtick.labelsize": 8, "ytick.labelsize": 8, "legend.fontsize": 8, "axes.edgecolor": "#333333", "axes.linewidth": 0.8, "figure.dpi": 160, "savefig.dpi": 600, "pdf.fonttype": 42,14 unmodified lines unsafe_allow_html=True,)
# Two curated feature palettes. The default is a tuned set. The colourblind safe set# uses the Okabe and Ito colours, which print well and read clearly for most readers.FEATURE_PALETTES = {FEATURE_COLORS = { "CDS": "#2166ac", "gene": "#1a9850", "tRNA": "#fdae61", "rRNA": "#d73027", "ncRNA": "#762a83", "misc_RNA": "#9970ab", "repeat_region": "#636363", "mobile_element": "#bf812d", "source": "#bdbdbd", "exon": "#66bd63", "mRNA": "#3288bd", "promoter": "#e78ac3", "terminator": "#8da0cb", "ORF": "#00a6a6", "bed_feature": "#4d4d4d", "misc_feature": "#8c510a", "default": "#4575b4", "highlight": "#ffd92f", "Default": { "CDS": "#2166ac", "gene": "#1a9850", "tRNA": "#fdae61", "rRNA": "#d73027", "ncRNA": "#762a83", "misc_RNA": "#9970ab", "repeat_region": "#636363", "mobile_element": "#bf812d", "source": "#bdbdbd", "exon": "#66bd63", "mRNA": "#3288bd", "promoter": "#e78ac3", "terminator": "#8da0cb", "ORF": "#00a6a6", "bed_feature": "#4d4d4d", "misc_feature": "#8c510a", "default": "#4575b4", "highlight": "#ffd92f", }, "Colourblind safe": { "CDS": "#0072B2", "gene": "#009E73", "tRNA": "#E69F00", "rRNA": "#D55E00", "ncRNA": "#CC79A7", "misc_RNA": "#56B4E9", "repeat_region": "#5b5b5b", "mobile_element": "#8c6d31", "source": "#bdbdbd", "exon": "#34a853", "mRNA": "#56B4E9", "promoter": "#CC79A7", "terminator": "#999999", "ORF": "#117733", "bed_feature": "#4d4d4d", "misc_feature": "#8c510a", "default": "#0072B2", "highlight": "#F0E442", },}
# Line and accent themes for the composition and codon figures.LINE_THEMES = { "Ocean": {"primary": "#1f6f8b", "secondary": "#e8915b", "cmap": "viridis"}, "Ember": {"primary": "#b5341f", "secondary": "#2b6f6f", "cmap": "magma"}, "Forest": {"primary": "#2f7d4f", "secondary": "#8a5a2b", "cmap": "cividis"}, "Royal": {"primary": "#3a3a8c", "secondary": "#c97b1e", "cmap": "plasma"},}
FASTA_EXTS = {".fa", ".fasta", ".fna", ".fas", ".ffn"}5 unmodified linesTABLE_EXTS = {".csv", ".tsv", ".txt"}DEFAULT_FEATURES = ["CDS", "gene", "tRNA", "rRNA", "ncRNA", "repeat_region", "mobile_element", "misc_feature", "ORF"]DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan")STANDARD_TABLE = CodonTable.unambiguous_dna_by_id[11]STOP_CODONS = set(STANDARD_TABLE.stop_codons)SENSE_CODONS = sorted([c for c in STANDARD_TABLE.forward_table.keys()])AA_TO_CODONS: Dict[str, List[str]] = {}for codon, aa in STANDARD_TABLE.forward_table.items(): AA_TO_CODONS.setdefault(aa, []).append(codon)
# Kyte and Doolittle hydropathy values for GRAVY.KD_HYDRO = { "A": 1.8, "R": -4.5, "N": -3.5, "D": -3.5, "C": 2.5, "Q": -3.5, "E": -3.5, "G": -0.4, "H": -3.2, "I": 4.5, "L": 3.8, "K": -3.9, "M": 1.9, "F": 2.8, "P": -1.6, "S": -0.8, "T": -0.7, "W": -0.9, "Y": -1.3, "V": 4.2,}AROMATIC_AA = set("FWY")
# Common NCBI genetic code tables. The user can pick the right one for the organism.GENETIC_CODE_OPTIONS = { "11 Bacterial, Archaeal and Plant Plastid": 11, "1 Standard": 1, "2 Vertebrate Mitochondrial": 2, "4 Mold, Protozoan and Coelenterate Mitochondrial": 4, "5 Invertebrate Mitochondrial": 5, "9 Echinoderm and Flatworm Mitochondrial": 9, "23 Thraustochytrium Mitochondrial": 23,}
@dataclassclass CodonContext: table_id: int forward_table: Dict[str, str] stop_codons: set sense_codons: List[str] sense_set: set aa_to_codons: Dict[str, List[str]] fourfold_boxes: List[Tuple[str, str]]
def build_codon_context(table_id: int) -> CodonContext: table = CodonTable.unambiguous_dna_by_id[table_id] forward = dict(table.forward_table) stop = set(table.stop_codons) sense = sorted(forward.keys()) aa_to_codons: Dict[str, List[str]] = {} for codon, aa in forward.items(): aa_to_codons.setdefault(aa, []).append(codon) boxes = [] for first in "ACGT": for second in "ACGT": quad = [first + second + t for t in "ACGT"] aas = {forward.get(c) for c in quad} if len(aas) == 1 and None not in aas: boxes.append((first, second)) return CodonContext(table_id, forward, stop, sense, set(sense), aa_to_codons, boxes)
@dataclass1 unmodified line records: List feature_tables: Dict[str, pd.DataFrame] source_mode: str notes: List[str] notes: List[str] = field(default_factory=list)
# -----------------------------63 unmodified lines return clean_text(getattr(feature, "type", "feature"))
FEATURE_COLUMNS = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"]
# -----------------------------# Parsing and annotation handling# -----------------------------21 unmodified lines }) except Exception: continue columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] return pd.DataFrame(rows, columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) return pd.DataFrame(rows, columns=FEATURE_COLUMNS).sort_values(["start", "end"], kind="stable").reset_index(drop=True)
def build_gff_db(gff_text: str, workdir: str):47 unmodified lines "note": "; ".join(attrs.get("Note", [])), "source": "GFF/GTF annotation", }) columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] return records, {r.id: pd.DataFrame(rows_by_record[r.id], columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) for r in records} return records, {r.id: pd.DataFrame(rows_by_record[r.id], columns=FEATURE_COLUMNS).sort_values(["start", "end"], kind="stable").reset_index(drop=True) for r in records}
def bed_and_fasta_to_tables(bed_bytes: bytes, fasta_bytes: bytes) -> Tuple[List, Dict[str, pd.DataFrame]]:3 unmodified lines bed = pd.read_csv(io.StringIO(bed_bytes.decode("utf-8", errors="replace")), sep="\t", header=None, comment="#") bed = bed.iloc[:, :min(6, bed.shape[1])] bed.columns = ["seqid", "start", "end", "name", "score", "strand"][:bed.shape[1]] columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] tables = {} for record in records: sdf = bed[bed["seqid"].astype(str).isin([record.id, record.id.split()[0]])].copy() if sdf.empty: tables[record.id] = pd.DataFrame(columns=columns) tables[record.id] = pd.DataFrame(columns=FEATURE_COLUMNS) continue out = pd.DataFrame({ "record_id": record.id,11 unmodified lines "source": "BED annotation", }) out["length"] = (out["end"] - out["start"]).clip(lower=0) tables[record.id] = out[columns].sort_values(["start", "end"], kind="stable").reset_index(drop=True) tables[record.id] = out[FEATURE_COLUMNS].sort_values(["start", "end"], kind="stable").reset_index(drop=True) return records, tables
17 unmodified lines strand_col = lower.get("strand") product_col = lower.get("product") locus_col = lower.get("locus_tag") columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] tables = {} for record in records: sdf = df if record_col is None else df[df[record_col].astype(str).isin([record.id, record.id.split()[0]])].copy() if sdf.empty: tables[record.id] = pd.DataFrame(columns=columns) tables[record.id] = pd.DataFrame(columns=FEATURE_COLUMNS) continue out = pd.DataFrame({ "record_id": record.id,11 unmodified lines "source": "Annotation table", }) out["length"] = (out["end"] - out["start"]).clip(lower=0) tables[record.id] = out[columns].sort_values(["start", "end"], kind="stable").reset_index(drop=True) tables[record.id] = out[FEATURE_COLUMNS].sort_values(["start", "end"], kind="stable").reset_index(drop=True) return records, tables
def predict_orfs(sequence: str, min_aa: int = 90, max_orfs: int = 5000) -> pd.DataFrame:def predict_orfs(sequence: str, ctx: CodonContext, min_aa: int = 90, max_orfs: int = 5000) -> pd.DataFrame: seq = str(sequence).upper() seq_len = len(seq) starts = {"ATG", "GTG", "TTG"} stop_codons = ctx.stop_codons rows = []
def scan(s: str, strand: int): nonlocal rows for frame in range(3): pos = frame while pos <= len(s) - 3 and len(rows) < max_orfs:1 unmodified line if codon in starts: stop = pos + 3 while stop <= len(s) - 3: if s[stop:stop + 3] in STOP_CODONS: if s[stop:stop + 3] in stop_codons: nt_len = stop + 3 - pos if nt_len // 3 >= min_aa: if strand == 1:22 unmodified lines pos += 3 scan(seq, 1) scan(reverse_complement(seq), -1) columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"] return pd.DataFrame(rows, columns=columns).sort_values(["start", "end"], kind="stable").reset_index(drop=True) return pd.DataFrame(rows, columns=FEATURE_COLUMNS).sort_values(["start", "end"], kind="stable").reset_index(drop=True)
def parse_zip(uploaded_file) -> Dict[str, bytes]:10 unmodified lines return files
def parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int) -> ParsedGenome:def parse_input_bundle(primary_upload, secondary_upload, input_mode: str, infer_orfs: bool, min_orf_aa: int, ctx: CodonContext) -> ParsedGenome: notes: List[str] = []
if input_mode == "ZIP auto detect":24 unmodified lines return ParsedGenome(records, tables, "table_fasta", notes) if fasta: records = parse_text_records(files[fasta], "fasta") tables = fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, notes) tables = fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, ctx, notes) notes.append(f"ZIP detected FASTA only: {fasta}") return ParsedGenome(records, tables, "fasta", notes) raise ValueError("The ZIP archive did not contain a supported genome input combination.")18 unmodified lines if not records: raise ValueError("No FASTA records were detected.") notes.append("Parsed FASTA input. Native feature annotation is not available unless ORF prediction is enabled.") return ParsedGenome(records, fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, notes), "fasta", notes) return ParsedGenome(records, fasta_tables_with_optional_orfs(records, infer_orfs, min_orf_aa, ctx, notes), "fasta", notes)
if input_mode in {"Universal auto detect", "GFF/GTF plus FASTA"} and kind == "gff": if secondary_upload is None:19 unmodified lines raise ValueError("Unsupported input type or missing paired FASTA file.")
def fasta_tables_with_optional_orfs(records, infer_orfs: bool, min_orf_aa: int, notes: List[str]) -> Dict[str, pd.DataFrame]: columns = ["record_id", "feature_type", "label", "start", "end", "length", "strand", "gene", "locus_tag", "product", "protein_id", "translation", "note", "source"]def fasta_tables_with_optional_orfs(records, infer_orfs: bool, min_orf_aa: int, ctx: CodonContext, notes: List[str]) -> Dict[str, pd.DataFrame]: total_len = sum(len(r.seq) for r in records) if infer_orfs and total_len > 10_000_000: notes.append("ORF prediction was disabled because the input is larger than 10 Mb. Use annotated GenBank/GFF for large genomes.")1 unmodified line tables = {} for record in records: if infer_orfs: df = predict_orfs(str(record.seq), min_aa=min_orf_aa) df = predict_orfs(str(record.seq), ctx, min_aa=min_orf_aa) if not df.empty: df["record_id"] = record.id tables[record.id] = df else: tables[record.id] = pd.DataFrame(columns=columns) tables[record.id] = pd.DataFrame(columns=FEATURE_COLUMNS) if infer_orfs: notes.append("ORF prediction was performed for FASTA only input using bacterial start codons ATG, GTG and TTG.") return tables
# -----------------------------# Genome composition and codon bias# Genome composition# -----------------------------def nucleotide_counts(sequence: str) -> Dict[str, int]: seq = str(sequence).upper()40 unmodified lines return (cg * len(seq)) / (c * g)
def shannon_entropy(sequence: str) -> float: seq = str(sequence).upper() counts = [seq.count(b) for b in "ACGT"] total = sum(counts) if total == 0: return 0.0 return -sum((c / total) * math.log2(c / total) for c in counts if c > 0)
def estimate_tm(sequence: str) -> float: """Rough whole sequence melting temperature using the basic GC fraction rule.""" seq = str(sequence).upper() valid = sum(seq.count(x) for x in "ATGC") if valid == 0: return 0.0 a = seq.count("A") t = seq.count("T") g = seq.count("G") c = seq.count("C") return round(64.9 + 41.0 * (g + c - 16.4) / valid, 2) if valid else 0.0
def dinucleotide_relative_abundance(sequence: str) -> pd.DataFrame: seq = re.sub("[^ACGT]", "", str(sequence).upper()) n = len(seq) rows = [] if n < 2: return pd.DataFrame(columns=["dinucleotide", "observed_freq", "expected_freq", "rho"]) mono = {b: seq.count(b) / n for b in "ACGT"} pairs = Counter(seq[i:i + 2] for i in range(n - 1)) total_pairs = sum(pairs.values()) for x in "ACGT": for y in "ACGT": obs = pairs.get(x + y, 0) / total_pairs if total_pairs else 0.0 exp = mono[x] * mono[y] rho = obs / exp if exp > 0 else 0.0 rows.append({"dinucleotide": x + y, "observed_freq": round(obs, 6), "expected_freq": round(exp, 6), "rho": round(rho, 4)}) return pd.DataFrame(rows)
def tetranucleotide_frequency(sequence: str, top: int = 25) -> pd.DataFrame: seq = re.sub("[^ACGT]", "", str(sequence).upper()) if len(seq) < 4: return pd.DataFrame(columns=["tetranucleotide", "count", "frequency_per_1000"]) counts = Counter(seq[i:i + 4] for i in range(len(seq) - 3)) total = sum(counts.values()) rows = [{"tetranucleotide": k, "count": v, "frequency_per_1000": round(1000.0 * v / total, 4)} for k, v in counts.most_common(top)] return pd.DataFrame(rows)
def window_dataframe(sequence: str, window_size: int = 1000) -> pd.DataFrame: seq = str(sequence).upper() rows = [] cumulative = 0.0 cum_gc = 0.0 cum_at = 0.0 for start in range(0, len(seq), window_size): end = min(len(seq), start + window_size) w = seq[start:end] skew = gc_skew_value(w) cumulative += skew gc_skew = gc_skew_value(w) at_skew = at_skew_value(w) cum_gc += gc_skew cum_at += at_skew rows.append({ "start": start, "end": end, "midpoint": (start + end) // 2, "GC_percent": compute_gc_percent(w), "GC_skew": skew, "cumulative_GC_skew": cumulative, "AT_percent": compute_at_percent(w), "GC_skew": gc_skew, "AT_skew": at_skew, "cumulative_GC_skew": cum_gc, "cumulative_AT_skew": cum_at, "Shannon_entropy_bits": round(shannon_entropy(w), 4), "N_count": w.count("N"), }) return pd.DataFrame(rows)
def predict_origin_terminus(window_df: pd.DataFrame) -> Dict[str, object]: """Predict origin and terminus of replication from the cumulative GC skew. For many bacterial genomes the global minimum of the cumulative GC skew marks the origin and the global maximum marks the terminus. This is a prediction and should be confirmed with dedicated tools for a final assembly.""" if window_df.empty: return {"origin_bp": None, "terminus_bp": None} cum = window_df["cumulative_GC_skew"].values mids = window_df["midpoint"].values return { "origin_bp": int(mids[int(np.argmin(cum))]), "terminus_bp": int(mids[int(np.argmax(cum))]), }
def assembly_statistics(records) -> Dict[str, object]: lengths = sorted([len(r.seq) for r in records], reverse=True) total = sum(lengths) if total == 0: return {}
def n_x(fraction): threshold = total * fraction acc = 0 for i, length in enumerate(lengths, 1): acc += length if acc >= threshold: return length, i return lengths[-1], len(lengths)
n50, l50 = n_x(0.5) n90, l90 = n_x(0.9) return { "num_records": len(records), "total_length_bp": total, "longest_record_bp": lengths[0], "shortest_record_bp": lengths[-1], "mean_record_length_bp": round(total / len(lengths), 1), "N50_bp": n50, "L50": l50, "N90_bp": n90, "L90": l90, }
def genome_composition(records) -> Dict[str, object]: """Aggregate nucleotide composition across all records.""" combined = {"A": 0, "T": 0, "G": 0, "C": 0, "N": 0} total = 0 for r in records: c = nucleotide_counts(str(r.seq)) for k in combined: combined[k] += c[k] total += len(r.seq) valid = combined["A"] + combined["T"] + combined["G"] + combined["C"] gc = 100.0 * (combined["G"] + combined["C"]) / valid if valid else 0.0 at = 100.0 * (combined["A"] + combined["T"]) / valid if valid else 0.0 g, c = combined["G"], combined["C"] a, t = combined["A"], combined["T"] return { "total_length_bp": total, "A": combined["A"], "T": combined["T"], "G": combined["G"], "C": combined["C"], "N": combined["N"], "GC_percent": round(gc, 3), "AT_percent": round(at, 3), "GC_skew": round((g - c) / (g + c), 5) if (g + c) else 0.0, "AT_skew": round((a - t) / (a + t), 5) if (a + t) else 0.0, }
# -----------------------------# Codon and protein analysis# -----------------------------def extract_feature_sequence(record, row: pd.Series) -> str: start, end = int(row["start"]), int(row["end"]) seq = str(record.seq[start:end]).upper()20 unmodified lines return seqs
def codon_usage_table(cds_sequences: List[str], reference_weights: Optional[Dict[str, float]] = None) -> pd.DataFrame: counts = {codon: 0 for codon in SENSE_CODONS} stop_counts = {codon: 0 for codon in STOP_CODONS}def iterate_codons(seq: str): for i in range(0, len(seq) - 2, 3): yield seq[i:i + 3]
def codon_counts_single(seq: str, ctx: CodonContext) -> Dict[str, int]: seq = valid_cds_sequence(seq) counts: Dict[str, int] = {} for codon in iterate_codons(seq): if codon in ctx.sense_set: counts[codon] = counts.get(codon, 0) + 1 return counts
def aggregate_codon_counts(cds_sequences: List[str], ctx: CodonContext) -> Dict[str, int]: total: Dict[str, int] = {c: 0 for c in ctx.sense_codons} for seq in cds_sequences: seq = valid_cds_sequence(seq) for i in range(0, len(seq) - 2, 3): codon = seq[i:i + 3] if codon in counts: counts[codon] += 1 elif codon in stop_counts: stop_counts[codon] += 1 for codon, n in codon_counts_single(seq, ctx).items(): total[codon] += n return total
def enc_from_counts(counts: Dict[str, int], ctx: CodonContext) -> float: """Wright effective number of codons from synonymous family homozygosity.""" if not counts or sum(counts.values()) == 0: return float("nan") f_by_k: Dict[int, List[float]] = {} for aa, codons in ctx.aa_to_codons.items(): k = len(codons) if k == 1: continue cvals = np.array([counts.get(c, 0) for c in codons], dtype=float) n = cvals.sum() if n <= 1: continue p = cvals / n f = (n * np.sum(p ** 2) - 1) / (n - 1) if f <= 0: continue f_by_k.setdefault(k, []).append(f) means = {k: float(np.mean(v)) for k, v in f_by_k.items() if v} f2, f3, f4, f6 = means.get(2), means.get(3), means.get(4), means.get(6) if f3 is None and f2 and f4: f3 = (f2 + f4) / 2.0 enc = 2.0 if f2: enc += 9.0 / f2 if f3: enc += 1.0 / f3 if f4: enc += 5.0 / f4 if f6: enc += 3.0 / f6 if enc <= 2.0: return float("nan") return round(float(min(max(enc, 20.0), 61.0)), 3)
def codon_usage_table(counts: Dict[str, int], ctx: CodonContext, stop_counts: Optional[Dict[str, int]] = None, reference_weights: Optional[Dict[str, float]] = None) -> pd.DataFrame: stop_counts = stop_counts or {c: 0 for c in ctx.stop_codons} total_sense = sum(counts.values()) rows = [] for aa, codons in sorted(AA_TO_CODONS.items()): aa_total = sum(counts[c] for c in codons) for aa, codons in sorted(ctx.aa_to_codons.items()): aa_total = sum(counts.get(c, 0) for c in codons) n_syn = len(codons) max_count = max([counts[c] for c in codons]) if codons else 0 max_count = max([counts.get(c, 0) for c in codons]) if codons else 0 for codon in sorted(codons): count = counts.get(codon, 0) freq_per_thousand = (counts[codon] / total_sense * 1000.0) if total_sense else 0.0 freq_per_thousand = (count / total_sense * 1000.0) if total_sense else 0.0 expected = aa_total / n_syn if n_syn else 0 rscu = counts[codon] / expected if expected else 0.0 rel_adapt = (counts[codon] / max_count) if max_count else 0.0 rscu = count / expected if expected else 0.0 rel_adapt = (count / max_count) if max_count else 0.0 rows.append({ "amino_acid": aa, "codon": codon, "count": counts[codon], "count": count, "frequency_per_1000": round(freq_per_thousand, 4), "RSCU": round(rscu, 4), "relative_adaptiveness_w": round(rel_adapt, 4), "reference_weight": reference_weights.get(codon, np.nan) if reference_weights else np.nan, }) for codon in sorted(STOP_CODONS): for codon in sorted(ctx.stop_codons): rows.append({ "amino_acid": "Stop", "codon": codon, "count": stop_counts[codon], "count": stop_counts.get(codon, 0), "frequency_per_1000": 0.0, "RSCU": 0.0, "relative_adaptiveness_w": 0.0,2 unmodified lines return pd.DataFrame(rows)
def effective_number_of_codons(codon_df: pd.DataFrame) -> float: """Approximate Wright ENC from homozygosity of synonymous codon families.""" if codon_df.empty or codon_df["count"].sum() == 0: return 0.0 f_by_k: Dict[int, List[float]] = {2: [], 3: [], 4: [], 6: []} sense = codon_df[codon_df["amino_acid"] != "Stop"].copy() for aa, group in sense.groupby("amino_acid"): k = len(group) if k == 1: continue counts = group["count"].astype(float).values n = counts.sum() if n <= 1: continue homozygosity = ((counts ** 2).sum() - n) / (n * (n - 1)) if k in f_by_k: f_by_k[k].append(max(homozygosity, 1e-9)) def mean_or_nan(vals): return float(np.mean(vals)) if vals else np.nan f2, f3, f4, f6 = [mean_or_nan(f_by_k[k]) for k in [2, 3, 4, 6]] enc = 2 enc += 9 / f2 if not np.isnan(f2) else 0 enc += 1 / f3 if not np.isnan(f3) else 0 enc += 5 / f4 if not np.isnan(f4) else 0 enc += 3 / f6 if not np.isnan(f6) else 0 return round(float(min(max(enc, 20.0), 61.0)), 3)def derive_weights_from_counts(counts: Dict[str, int], ctx: CodonContext) -> Dict[str, float]: weights: Dict[str, float] = {} for aa, codons in ctx.aa_to_codons.items(): max_count = max([counts.get(c, 0) for c in codons]) if codons else 0 for codon in codons: weights[codon] = (counts.get(codon, 0) / max_count) if max_count else 0.0 return weights
def codon_adaptation_index(cds_sequences: List[str], weights: Optional[Dict[str, float]]) -> float:def cai_single(seq: str, ctx: CodonContext, weights: Optional[Dict[str, float]]) -> float: if not weights: return 0.0 return float("nan") logs = [] for seq in cds_sequences: for codon in iterate_codons(valid_cds_sequence(seq)): if codon in ctx.sense_set: w = max(float(weights.get(codon, 0.0)), 1e-8) logs.append(math.log(w)) return round(float(math.exp(np.mean(logs))), 4) if logs else float("nan")
def codon_position_gc(seq: str) -> Tuple[float, float, float]: seq = valid_cds_sequence(seq) gc = [0, 0, 0] tot = [0, 0, 0] for codon in iterate_codons(seq): for j in range(3): base = codon[j] if base in "ACGT": tot[j] += 1 if base in "GC": gc[j] += 1 return tuple(100.0 * gc[j] / tot[j] if tot[j] else 0.0 for j in range(3))
def gc3s_value(seq: str, ctx: CodonContext) -> float: seq = valid_cds_sequence(seq) gc = 0 tot = 0 for codon in iterate_codons(seq): aa = ctx.forward_table.get(codon) if aa is None: continue if len(ctx.aa_to_codons.get(aa, [])) <= 1: continue third = codon[2] if third in "ACGT": tot += 1 if third in "GC": gc += 1 return 100.0 * gc / tot if tot else 0.0
def pr2_components(seq: str, ctx: CodonContext) -> Tuple[float, float, int]: """Return G3/(G3+C3) and A3/(A3+T3) over four-fold degenerate codon boxes.""" seq = valid_cds_sequence(seq) box_set = set(ctx.fourfold_boxes) a3 = t3 = g3 = c3 = 0 for codon in iterate_codons(seq): if (codon[0], codon[1]) in box_set: third = codon[2] if third == "A": a3 += 1 elif third == "T": t3 += 1 elif third == "G": g3 += 1 elif third == "C": c3 += 1 gc = g3 + c3 at = a3 + t3 x = g3 / gc if gc else np.nan y = a3 / at if at else np.nan return x, y, at + gc
def translate_cds(seq: str, ctx: CodonContext) -> str: seq = valid_cds_sequence(seq) if not seq: return "" try: protein = str(Seq(seq).translate(table=ctx.table_id)) except Exception: return "" return protein.split("*")[0]
def protein_metrics(protein: str) -> Tuple[float, float]: protein = re.sub("[^ACDEFGHIKLMNPQRSTVWY]", "", str(protein).upper()) if not protein: return float("nan"), float("nan") gravy = sum(KD_HYDRO.get(a, 0.0) for a in protein) / len(protein) aromaticity = sum(1 for a in protein if a in AROMATIC_AA) / len(protein) return round(gravy, 4), round(aromaticity, 4)
def per_cds_metrics(cds_sequences: List[str], ctx: CodonContext, weights: Optional[Dict[str, float]]) -> pd.DataFrame: rows = [] for idx, seq in enumerate(cds_sequences, 1): seq = valid_cds_sequence(seq) for i in range(0, len(seq) - 2, 3): codon = seq[i:i + 3] if codon in SENSE_CODONS: w = max(float(weights.get(codon, 0.0)), 1e-8) logs.append(math.log(w)) return round(float(math.exp(np.mean(logs))), 4) if logs else 0.0 if len(seq) < 90: continue counts = codon_counts_single(seq, ctx) enc = enc_from_counts(counts, ctx) gc1, gc2, gc3 = codon_position_gc(seq) x_pr2, y_pr2, pr2_n = pr2_components(seq, ctx) protein = translate_cds(seq, ctx) gravy, aromaticity = protein_metrics(protein) rows.append({ "cds_index": idx, "length_bp": len(seq), "length_aa": len(protein), "GC_percent": round(compute_gc_percent(seq), 3), "GC1": round(gc1, 3), "GC2": round(gc2, 3), "GC3": round(gc3, 3), "GC12": round((gc1 + gc2) / 2.0, 3), "GC3s": round(gc3s_value(seq, ctx), 3), "ENC": enc, "CAI": cai_single(seq, ctx, weights), "GRAVY": gravy, "aromaticity": aromaticity, "PR2_G3_over_GC3": round(x_pr2, 4) if not np.isnan(x_pr2) else np.nan, "PR2_A3_over_AT3": round(y_pr2, 4) if not np.isnan(y_pr2) else np.nan, }) return pd.DataFrame(rows)
def amino_acid_usage(cds_sequences: List[str], ctx: CodonContext) -> pd.DataFrame: counter: Counter = Counter() for seq in cds_sequences: counter.update(translate_cds(seq, ctx)) total = sum(counter.values()) order = "ACDEFGHIKLMNPQRSTVWY" rows = [{"amino_acid": aa, "count": counter.get(aa, 0), "frequency_percent": round(100.0 * counter.get(aa, 0) / total, 4) if total else 0.0} for aa in order] return pd.DataFrame(rows)
def parse_reference_codon_weights(uploaded_ref) -> Optional[Dict[str, float]]:def parse_reference_codon_weights(uploaded_ref, ctx: CodonContext) -> Optional[Dict[str, float]]: if uploaded_ref is None: return None text = uploaded_ref.getvalue().decode("utf-8", errors="replace")6 unmodified lines weights = {} for _, row in df.iterrows(): codon = str(row[codon_col]).upper().replace("U", "T") if codon in SENSE_CODONS: if codon in ctx.sense_set: try: weights[codon] = float(row[weight_col]) except Exception:1 unmodified line return weights or None
def build_summary_statistics(record, full_df: pd.DataFrame, filtered_df: pd.DataFrame, cds_sequences: List[str], codon_df: pd.DataFrame, cai: float) -> Dict[str, object]: seq = str(record.seq).upper() counts = nucleotide_counts(seq) feature_counts = full_df["feature_type"].value_counts().to_dict() if not full_df.empty else {} coding_bp = int(full_df.loc[full_df["feature_type"].str.lower().eq("cds"), "length"].sum()) if not full_df.empty else 0 total_codons = int(codon_df.loc[codon_df["amino_acid"] != "Stop", "count"].sum()) if not codon_df.empty else 0def neutrality_regression(per_cds: pd.DataFrame) -> Dict[str, float]: if per_cds.empty or len(per_cds) < 3: return {"slope": np.nan, "intercept": np.nan, "r": np.nan, "n": int(len(per_cds))} x = per_cds["GC3"].astype(float).values y = per_cds["GC12"].astype(float).values mask = np.isfinite(x) & np.isfinite(y) x, y = x[mask], y[mask] if len(x) < 3: return {"slope": np.nan, "intercept": np.nan, "r": np.nan, "n": int(len(x))} slope, intercept = np.polyfit(x, y, 1) r = float(np.corrcoef(x, y)[0, 1]) return {"slope": round(float(slope), 4), "intercept": round(float(intercept), 4), "r": round(r, 4), "n": int(len(x))}
def enc_expected_curve(gc3s_fraction: np.ndarray) -> np.ndarray: s = np.clip(gc3s_fraction, 1e-6, 1 - 1e-6) return 2 + s + 29.0 / (s ** 2 + (1 - s) ** 2)
# -----------------------------# Summary statistics# -----------------------------def build_summary_statistics(records, main_record, composition, assembly, origin_terminus, full_df_main, filtered_df, all_cds, codon_df, codon_counts, ctx, cai_mean, per_cds, neutrality) -> Dict[str, object]: main_seq = str(main_record.seq).upper() feature_counts = full_df_main["feature_type"].value_counts().to_dict() if not full_df_main.empty else {} coding_bp = int(full_df_main.loc[full_df_main["feature_type"].str.lower().eq("cds"), "length"].sum()) if not full_df_main.empty else 0 total_codons = int(sum(codon_counts.values())) enc_genome = enc_from_counts(codon_counts, ctx) mean_enc = round(float(per_cds["ENC"].dropna().mean()), 3) if not per_cds.empty else np.nan mean_gravy = round(float(per_cds["GRAVY"].dropna().mean()), 4) if not per_cds.empty else np.nan return { "record_id": record.id, "description": clean_text(getattr(record, "description", "")), "genome_length_bp": len(seq), "A": counts["A"], "T": counts["T"], "G": counts["G"], "C": counts["C"], "N": counts["N"], "GC_percent": round(compute_gc_percent(seq), 3), "AT_percent": round(compute_at_percent(seq), 3), "GC_skew": round(gc_skew_value(seq), 5), "AT_skew": round(at_skew_value(seq), 5), "CpG_observed_expected": round(cpg_observed_expected(seq), 5), "total_features": int(len(full_df)), "main_record_id": main_record.id, "main_record_description": clean_text(getattr(main_record, "description", "")), "num_records": len(records), "total_genome_length_bp": composition["total_length_bp"], "main_record_length_bp": len(main_seq), "A": composition["A"], "T": composition["T"], "G": composition["G"], "C": composition["C"], "N": composition["N"], "GC_percent": composition["GC_percent"], "AT_percent": composition["AT_percent"], "GC_skew": composition["GC_skew"], "AT_skew": composition["AT_skew"], "CpG_observed_expected": round(cpg_observed_expected(main_seq), 5), "Shannon_entropy_bits": round(shannon_entropy(main_seq), 4), "estimated_Tm_C": estimate_tm(main_seq), "N50_bp": assembly.get("N50_bp"), "L50": assembly.get("L50"), "N90_bp": assembly.get("N90_bp"), "predicted_origin_bp": origin_terminus.get("origin_bp"), "predicted_terminus_bp": origin_terminus.get("terminus_bp"), "total_features_main_record": int(len(full_df_main)), "displayed_features": int(len(filtered_df)), "CDS_count": int(feature_counts.get("CDS", 0)), "gene_count": int(feature_counts.get("gene", 0)), "tRNA_count": int(feature_counts.get("tRNA", 0)), "rRNA_count": int(feature_counts.get("rRNA", 0)), "ORF_count": int(feature_counts.get("ORF", 0)), "coding_bp": coding_bp, "coding_density_percent": round(100.0 * coding_bp / len(seq), 3) if len(seq) else 0.0, "CDS_used_for_codon_analysis": len(cds_sequences), "CDS_count_main_record": int(feature_counts.get("CDS", 0)), "gene_count_main_record": int(feature_counts.get("gene", 0)), "tRNA_count_main_record": int(feature_counts.get("tRNA", 0)), "rRNA_count_main_record": int(feature_counts.get("rRNA", 0)), "ORF_count_main_record": int(feature_counts.get("ORF", 0)), "coding_bp_main_record": coding_bp, "coding_density_percent_main_record": round(100.0 * coding_bp / len(main_seq), 3) if len(main_seq) else 0.0, "CDS_used_for_codon_analysis": len(all_cds), "total_sense_codons": total_codons, "effective_number_of_codons_ENC": effective_number_of_codons(codon_df), "codon_adaptation_index_CAI": cai, "effective_number_of_codons_ENC_genome": enc_genome, "mean_ENC_per_CDS": mean_enc, "mean_GRAVY_per_CDS": mean_gravy, "codon_adaptation_index_CAI_mean": cai_mean, "neutrality_slope_GC12_vs_GC3": neutrality.get("slope"), "neutrality_correlation_r": neutrality.get("r"), }
# -----------------------------# Filtering and visualization# Filtering# -----------------------------def filter_features(df: pd.DataFrame, selected_types: List[str], query: str, min_len: int, max_features: int) -> pd.DataFrame: if df.empty:9 unmodified lines if q: fields = ["label", "gene", "locus_tag", "product", "protein_id", "note"] mask = pd.Series(False, index=out.index) for field in fields: if field in out.columns: mask = mask | out[field].fillna("").str.lower().str.contains(re.escape(q), na=False) for field_name in fields: if field_name in out.columns: mask = mask | out[field_name].fillna("").str.lower().str.contains(re.escape(q), na=False) out["highlight"] = mask else: out["highlight"] = False2 unmodified lines return out.sort_values(["start", "end"], kind="stable").reset_index(drop=True)
# -----------------------------# Legends# -----------------------------def feature_legend_html(feature_types: List[str], highlight: bool) -> str:def feature_legend_html(feature_types: List[str], highlight: bool, palette: Dict[str, str]) -> str: parts = [] for ft in feature_types: color = FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]) color = palette.get(ft, palette["default"]) parts.append(f'<span class="legend-item"><span class="legend-swatch" style="background:{color}"></span>{ft}</span>') if highlight: parts.append(f'<span class="legend-item"><span class="legend-swatch" style="background:{FEATURE_COLORS["highlight"]}"></span>highlighted match</span>') parts.append(f'<span class="legend-item"><span class="legend-swatch" style="background:{palette["highlight"]}"></span>highlighted match</span>') return "".join(parts)
def add_matplotlib_legend(ax, feature_types: List[str], highlight: bool):def add_matplotlib_legend(ax, feature_types: List[str], highlight: bool, palette: Dict[str, str]): handles = [] for ft in feature_types: handles.append(Line2D([0], [0], color=FEATURE_COLORS.get(ft, FEATURE_COLORS["default"]), lw=5, label=ft)) handles.append(Line2D([0], [0], color=palette.get(ft, palette["default"]), lw=5, label=ft)) if highlight: handles.append(Line2D([0], [0], color=FEATURE_COLORS["highlight"], lw=5, label="highlighted match")) handles.append(Line2D([0], [0], color=palette["highlight"], lw=5, label="highlighted match")) if handles: ax.legend(handles=handles, frameon=False, ncol=2, loc="upper right")
def draw_linear_map(record, filtered_df: pd.DataFrame, feature_types: List[str], publication: bool):# -----------------------------# Figures# -----------------------------def draw_linear_map(record, filtered_df, feature_types, publication, palette): if GraphicFeature is None or GraphicRecord is None: raise RuntimeError("dna_features_viewer is required. Install it with: pip install dna_features_viewer") features = [] label_limit = 160 if publication else 80 for _, row in filtered_df.iterrows(): color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"]) color = palette["highlight"] if bool(row.get("highlight", False)) else palette.get(row["feature_type"], palette["default"]) label = clean_text(row.get("label", row["feature_type"])) if len(filtered_df) <= label_limit else None if label and len(label) > 34: label = label[:31] + "..." features.append(GraphicFeature(start=int(row["start"]), end=int(row["end"]), strand=int(row["strand"]) if int(row["strand"]) in [-1, 1] else 0, color=color, label=label)) features.append(GraphicFeature(start=int(row["start"]), end=int(row["end"]), strand=int(row["strand"]) if int(row["strand"]) in [-1, 1] else 0, color=color, label=label)) graphic = GraphicRecord(sequence_length=len(record.seq), features=features) height = 4.8 if len(filtered_df) < 100 else 6.2 if len(filtered_df) < 300 else 7.5 fig, ax = plt.subplots(figsize=(16, height)) graphic.plot(ax=ax, with_ruler=True, annotate_inline=(len(filtered_df) <= label_limit)) ax.set_title("A. Linear genome map", loc="left", fontweight="bold") ax.set_xlabel(f"{record.id} | {len(record.seq):,} bp") add_matplotlib_legend(ax, feature_types, bool(filtered_df.get("highlight", pd.Series(dtype=bool)).any()) if not filtered_df.empty else False) add_matplotlib_legend(ax, feature_types, bool(filtered_df.get("highlight", pd.Series(dtype=bool)).any()) if not filtered_df.empty else False, palette) plt.tight_layout() return fig
def draw_circular_map(record, filtered_df: pd.DataFrame, window_df: pd.DataFrame, feature_types: List[str]):def draw_circular_map(record, filtered_df, window_df, feature_types, palette, theme): if Circos is None: raise RuntimeError("pycirclize is required for circular maps. Install it with: pip install pycirclize") seq_len = len(record.seq) circos = Circos({record.id: seq_len}, space=2) sector = circos.sectors[0] axis = sector.add_track((88, 100)) axis = sector.add_track((92, 100)) axis.axis(fc="#f8f9fa", ec="#222222", lw=0.4) tick_interval = max(1000, seq_len // 12) axis.xticks_by_interval(tick_interval, label_formatter=lambda v: f"{int(v / 1000)} kb" if v >= 1000 else str(int(v)), label_size=8, label_orientation="vertical")
forward = sector.add_track((66, 84)) reverse = sector.add_track((46, 64)) forward = sector.add_track((74, 90)) reverse = sector.add_track((58, 73)) forward.axis(fc="#ffffff", ec="#555555", lw=0.25) reverse.axis(fc="#ffffff", ec="#555555", lw=0.25) for _, row in filtered_df.iterrows(): color = FEATURE_COLORS["highlight"] if bool(row.get("highlight", False)) else FEATURE_COLORS.get(row["feature_type"], FEATURE_COLORS["default"]) color = palette["highlight"] if bool(row.get("highlight", False)) else palette.get(row["feature_type"], palette["default"]) track = reverse if int(row.get("strand", 0)) == -1 else forward track.rect(int(row["start"]), int(row["end"]), fc=color, ec=color, lw=0.1)
if not window_df.empty: gc_track = sector.add_track((28, 42)) gc_track = sector.add_track((42, 56)) gc_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) gc_track.line(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), vmin=0, vmax=100, lw=0.8) gc_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), y2=[50.0] * len(window_df), vmin=0, vmax=100, alpha=0.25) gc_track.line(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), vmin=0, vmax=100, lw=0.8, color=theme["primary"]) gc_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_percent"].tolist(), y2=[float(window_df["GC_percent"].mean())] * len(window_df), vmin=0, vmax=100, alpha=0.25, color=theme["primary"])
skew_track = sector.add_track((12, 26)) skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) max_skew = max(0.05, float(np.nanmax(np.abs(window_df["GC_skew"])))) skew_track.line(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), vmin=-max_skew, vmax=max_skew, lw=0.8) skew_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), y2=0, vmin=-max_skew, vmax=max_skew, alpha=0.30) max_gc_skew = max(0.05, float(np.nanmax(np.abs(window_df["GC_skew"])))) gc_skew_track = sector.add_track((28, 41)) gc_skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) gc_skew_track.line(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), vmin=-max_gc_skew, vmax=max_gc_skew, lw=0.8, color=theme["secondary"]) gc_skew_track.fill_between(window_df["midpoint"].tolist(), window_df["GC_skew"].tolist(), y2=0, vmin=-max_gc_skew, vmax=max_gc_skew, alpha=0.30, color=theme["secondary"])
max_at_skew = max(0.05, float(np.nanmax(np.abs(window_df["AT_skew"])))) at_skew_track = sector.add_track((14, 27)) at_skew_track.axis(fc="#fbfbfb", ec="#555555", lw=0.2) at_skew_track.line(window_df["midpoint"].tolist(), window_df["AT_skew"].tolist(), vmin=-max_at_skew, vmax=max_at_skew, lw=0.8, color="#7d7d7d")
fig = circos.plotfig() fig.set_size_inches(9.2, 9.2) fig.suptitle("B. Circular genome map with GC tracks", x=0.08, y=0.98, ha="left", fontweight="bold") fig.set_size_inches(9.4, 9.4) fig.suptitle("B. Circular genome map with GC content, GC skew and AT skew tracks", x=0.06, y=0.99, ha="left", fontweight="bold") return fig
def draw_feature_distribution(feature_df: pd.DataFrame):def draw_feature_distribution(feature_df, palette): dist = feature_df["feature_type"].value_counts().rename_axis("feature_type").reset_index(name="count") if not feature_df.empty else pd.DataFrame(columns=["feature_type", "count"]) fig, ax = plt.subplots(figsize=(9, 4.8)) ax.set_title("C. Feature class distribution", loc="left", fontweight="bold")2 unmodified lines ax.axis("off") else: show = dist.head(15) colors = [FEATURE_COLORS.get(x, FEATURE_COLORS["default"]) for x in show["feature_type"]] colors = [palette.get(x, palette["default"]) for x in show["feature_type"]] ax.bar(show["feature_type"], show["count"], color=colors, edgecolor="#222222", linewidth=0.35) ax.set_xlabel("Feature class") ax.set_ylabel("Count")3 unmodified lines return fig, dist
def draw_gc_profile(window_df: pd.DataFrame, seq_len: int):def draw_gc_profile(window_df, seq_len, theme): fig, ax = plt.subplots(figsize=(10, 4.8)) ax.set_title("D. GC content and GC skew profile", loc="left", fontweight="bold") ax.set_title("D. GC content with GC skew and AT skew", loc="left", fontweight="bold") if window_df.empty: ax.text(0.5, 0.5, "No sequence windows available", ha="center", va="center") ax.axis("off") else: ax.plot(window_df["midpoint"], window_df["GC_percent"], label="GC percent", lw=1.8) ax.plot(window_df["midpoint"], window_df["GC_percent"], label="GC percent", lw=1.8, color=theme["primary"]) ax.set_xlabel("Genome position (bp)") ax.set_ylabel("GC percent") ax.set_xlim(0, seq_len) ax.grid(alpha=0.25) ax2 = ax.twinx() ax2.plot(window_df["midpoint"], window_df["GC_skew"], label="GC skew", lw=1.2, linestyle="--") ax2.set_ylabel("GC skew") ax2.plot(window_df["midpoint"], window_df["GC_skew"], label="GC skew", lw=1.1, linestyle="--", color=theme["secondary"]) ax2.plot(window_df["midpoint"], window_df["AT_skew"], label="AT skew", lw=1.0, linestyle=":", color="#7d7d7d") ax2.set_ylabel("Skew") lines, labels = ax.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax.legend(lines + lines2, labels + labels2, frameon=False, loc="upper right")1 unmodified line return fig
def draw_cumulative_skew(window_df, origin_terminus, seq_len, theme): fig, ax = plt.subplots(figsize=(10, 4.8)) ax.set_title("E. Cumulative GC skew with predicted origin and terminus", loc="left", fontweight="bold") if window_df.empty: ax.text(0.5, 0.5, "No sequence windows available", ha="center", va="center") ax.axis("off") else: ax.plot(window_df["midpoint"], window_df["cumulative_GC_skew"], lw=1.8, color=theme["primary"], label="Cumulative GC skew") ax.plot(window_df["midpoint"], window_df["cumulative_AT_skew"], lw=1.2, linestyle="--", color=theme["secondary"], label="Cumulative AT skew") ori = origin_terminus.get("origin_bp") ter = origin_terminus.get("terminus_bp") if ori is not None: ax.axvline(ori, color="#1a9850", lw=1.2, linestyle="-.", label=f"Predicted origin ~{ori:,} bp") if ter is not None: ax.axvline(ter, color="#d73027", lw=1.2, linestyle="-.", label=f"Predicted terminus ~{ter:,} bp") ax.set_xlabel("Genome position (bp)") ax.set_ylabel("Cumulative skew") ax.set_xlim(0, seq_len) ax.grid(alpha=0.25) ax.legend(frameon=False, loc="best") plt.tight_layout() return fig
def draw_composition(nuc_counts, dinuc_df, theme): fig, axes = plt.subplots(1, 2, figsize=(13, 4.8)) axes[0].set_title("F1. Nucleotide composition", loc="left", fontweight="bold") bases = ["A", "T", "G", "C", "N"] base_colors = ["#4575b4", "#91bfdb", "#fc8d59", "#d73027", "#999999"] values = [nuc_counts.get(b, 0) for b in bases] axes[0].bar(bases, values, color=base_colors, edgecolor="#222222", linewidth=0.35) axes[0].set_ylabel("Count") axes[0].grid(axis="y", alpha=0.25)
axes[1].set_title("F2. Dinucleotide relative abundance", loc="left", fontweight="bold") if dinuc_df.empty: axes[1].text(0.5, 0.5, "No data", ha="center", va="center") axes[1].axis("off") else: colors = [theme["secondary"] if (r > 1.23 or r < 0.78) else theme["primary"] for r in dinuc_df["rho"]] axes[1].bar(dinuc_df["dinucleotide"], dinuc_df["rho"], color=colors, edgecolor="#222222", linewidth=0.3) axes[1].axhline(1.0, color="#444444", lw=1.0) axes[1].axhline(1.23, color="#999999", lw=0.8, linestyle="--") axes[1].axhline(0.78, color="#999999", lw=0.8, linestyle="--") axes[1].set_ylabel("rho (observed / expected)") axes[1].tick_params(axis="x", rotation=90) axes[1].grid(axis="y", alpha=0.25) plt.tight_layout() return fig
def draw_codon_rscu(codon_df: pd.DataFrame):def draw_codon_rscu(codon_df, theme): fig, ax = plt.subplots(figsize=(13, 5.2)) ax.set_title("E. Relative synonymous codon usage", loc="left", fontweight="bold") ax.set_title("G. Relative synonymous codon usage", loc="left", fontweight="bold") sense = codon_df[codon_df["amino_acid"] != "Stop"].copy() if not codon_df.empty else pd.DataFrame() if sense.empty or sense["count"].sum() == 0: ax.text(0.5, 0.5, "No CDS codon data available", ha="center", va="center") ax.axis("off") else: sense["label"] = sense["codon"] + "\n" + sense["amino_acid"] colors = [theme["primary"] if v >= 1 else theme["secondary"] for v in sense["RSCU"]] ax.bar(sense["label"], sense["RSCU"], edgecolor="#222222", linewidth=0.25) ax.axhline(1.0, lw=1.0, linestyle="--") ax.bar(sense["label"], sense["RSCU"], color=colors, edgecolor="#222222", linewidth=0.25) ax.axhline(1.0, lw=1.0, linestyle="--", color="#444444") ax.set_ylabel("RSCU") ax.set_xlabel("Codon and amino acid") ax.tick_params(axis="x", rotation=90)2 unmodified lines return fig
def draw_rscu_heatmap(codon_df, ctx, cmap_name): fig, ax = plt.subplots(figsize=(7.5, 9)) ax.set_title("H. RSCU codon table heatmap", loc="left", fontweight="bold") if codon_df.empty or codon_df["count"].sum() == 0: ax.text(0.5, 0.5, "No CDS codon data available", ha="center", va="center") ax.axis("off") plt.tight_layout() return fig bases = "TCAG" rscu_map = dict(zip(codon_df["codon"], codon_df["RSCU"])) aa_map = dict(zip(codon_df["codon"], codon_df["amino_acid"])) matrix = np.full((16, 4), np.nan) labels = [["" for _ in range(4)] for _ in range(16)] for i, first in enumerate(bases): for j, second in enumerate(bases): row = i * 4 + j for k, third in enumerate(bases): codon = first + second + third matrix[row, k] = rscu_map.get(codon, np.nan) aa = aa_map.get(codon, "*") labels[row][k] = f"{codon}\n{aa}" im = ax.imshow(matrix, cmap=cmap_name, aspect="auto", vmin=0, vmax=max(2.0, np.nanmax(matrix))) ax.set_xticks(range(4)) ax.set_xticklabels(list(bases)) ax.set_yticks(range(16)) ax.set_yticklabels([first + second for first in bases for second in bases]) ax.set_xlabel("Third position") ax.set_ylabel("First and second position") for r in range(16): for c in range(4): if not np.isnan(matrix[r, c]): ax.text(c, r, labels[r][c], ha="center", va="center", fontsize=6, color="#111111") fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="RSCU") plt.tight_layout() return fig
def draw_amino_acid_usage(aa_df, theme): fig, ax = plt.subplots(figsize=(11, 4.6)) ax.set_title("I. Amino acid usage", loc="left", fontweight="bold") if aa_df.empty or aa_df["count"].sum() == 0: ax.text(0.5, 0.5, "No protein data available", ha="center", va="center") ax.axis("off") else: ordered = aa_df.sort_values("frequency_percent", ascending=False) ax.bar(ordered["amino_acid"], ordered["frequency_percent"], color=theme["primary"], edgecolor="#222222", linewidth=0.3) ax.set_ylabel("Frequency (%)") ax.set_xlabel("Amino acid") ax.grid(axis="y", alpha=0.25) plt.tight_layout() return fig
def draw_neutrality(per_cds, neutrality, theme): fig, ax = plt.subplots(figsize=(6.6, 6)) ax.set_title("J. Neutrality plot (GC12 vs GC3)", loc="left", fontweight="bold") if per_cds.empty: ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") ax.axis("off") else: ax.scatter(per_cds["GC3"], per_cds["GC12"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none") slope = neutrality.get("slope") intercept = neutrality.get("intercept") if slope is not None and not (isinstance(slope, float) and np.isnan(slope)): xs = np.linspace(per_cds["GC3"].min(), per_cds["GC3"].max(), 50) ax.plot(xs, slope * xs + intercept, color=theme["secondary"], lw=1.8, label=f"slope = {slope:.3f}, r = {neutrality.get('r')}") ax.legend(frameon=False, loc="best") ax.set_xlabel("GC3 (%)") ax.set_ylabel("GC12 (%)") ax.grid(alpha=0.25) plt.tight_layout() return fig
def draw_enc_plot(per_cds, theme): fig, ax = plt.subplots(figsize=(6.6, 6)) ax.set_title("K. ENC plot against expected curve", loc="left", fontweight="bold") if per_cds.empty: ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") ax.axis("off") else: ax.scatter(per_cds["GC3s"], per_cds["ENC"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none", label="CDS") xs = np.linspace(0.0, 1.0, 200) ax.plot(xs * 100, enc_expected_curve(xs), color=theme["secondary"], lw=1.8, label="Wright expected curve") ax.set_xlim(0, 100) ax.set_ylim(20, 62) ax.set_xlabel("GC3s (%)") ax.set_ylabel("ENC") ax.grid(alpha=0.25) ax.legend(frameon=False, loc="best") plt.tight_layout() return fig
def draw_pr2_plot(per_cds, theme): fig, ax = plt.subplots(figsize=(6.4, 6.2)) ax.set_title("L. PR2 bias plot", loc="left", fontweight="bold") sub = per_cds.dropna(subset=["PR2_G3_over_GC3", "PR2_A3_over_AT3"]) if not per_cds.empty else pd.DataFrame() if sub.empty: ax.text(0.5, 0.5, "No four-fold codon data available", ha="center", va="center") ax.axis("off") else: ax.scatter(sub["PR2_G3_over_GC3"], sub["PR2_A3_over_AT3"], s=12, alpha=0.55, color=theme["primary"], edgecolor="none") ax.axvline(0.5, color="#444444", lw=1.0, linestyle="--") ax.axhline(0.5, color="#444444", lw=1.0, linestyle="--") ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_xlabel("G3 / (G3 + C3)") ax.set_ylabel("A3 / (A3 + T3)") ax.grid(alpha=0.25) plt.tight_layout() return fig
def draw_feature_length_distribution(per_cds, theme): fig, ax = plt.subplots(figsize=(8.5, 4.6)) ax.set_title("M. CDS length distribution", loc="left", fontweight="bold") if per_cds.empty: ax.text(0.5, 0.5, "No CDS data available", ha="center", va="center") ax.axis("off") else: ax.hist(per_cds["length_bp"], bins=40, color=theme["primary"], edgecolor="#222222", linewidth=0.3) ax.set_xlabel("CDS length (bp)") ax.set_ylabel("Number of CDS") ax.grid(axis="y", alpha=0.25) plt.tight_layout() return fig
def fig_bytes(fig, fmt: str = "png", dpi: int = 600) -> bytes: buffer = io.BytesIO() kwargs = {"bbox_inches": "tight"}4 unmodified lines return buffer.getvalue()
def build_bundle(figures: Dict[str, bytes], tables: Dict[str, pd.DataFrame], summary_text: str) -> bytes:def build_bundle(figures, tables, summary_text, methods_text) -> bytes: mem = io.BytesIO() with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as zf: for name, data in figures.items(): if data is not None: zf.writestr(name, data) zf.writestr(os.path.join("figures", name), data) for name, df in tables.items(): zf.writestr(name, df.to_csv(index=False)) zf.writestr(os.path.join("tables", name), df.to_csv(index=False)) zf.writestr("manuscript_summary.txt", summary_text) zf.writestr("methods.txt", methods_text) mem.seek(0) return mem.getvalue()
def manuscript_summary(stats: Dict[str, object]) -> str: def fmt(value, spec=""): if value is None or (isinstance(value, float) and np.isnan(value)): return "not available" return format(value, spec) if spec else str(value) return ( f"The genome record {stats['record_id']} had a length of {stats['genome_length_bp']:,} bp, " f"with GC content of {stats['GC_percent']:.2f}%, AT content of {stats['AT_percent']:.2f}%, " f"GC skew of {stats['GC_skew']:.5f}, and CpG observed/expected ratio of {stats['CpG_observed_expected']:.5f}. " f"A total of {stats['total_features']:,} annotated features were parsed, including {stats['CDS_count']:,} CDS, " f"{stats['tRNA_count']:,} tRNA and {stats['rRNA_count']:,} rRNA features. The estimated coding density was " f"{stats['coding_density_percent']:.2f}%. Codon usage analysis was performed using {stats['CDS_used_for_codon_analysis']:,} CDS, " f"covering {stats['total_sense_codons']:,} sense codons. The effective number of codons was " f"{stats['effective_number_of_codons_ENC']:.2f}, while the codon adaptation index was " f"{stats['codon_adaptation_index_CAI']:.4f} when a reference weight table was supplied." f"The dataset {stats['main_record_id']} contained {fmt(stats['num_records'])} sequence record(s) " f"with a total length of {fmt(stats['total_genome_length_bp'], ',')} bp. The assembly had an N50 of " f"{fmt(stats['N50_bp'], ',')} bp and an L50 of {fmt(stats['L50'])}. The overall GC content was " f"{fmt(stats['GC_percent'], '.2f')}%, AT content was {fmt(stats['AT_percent'], '.2f')}%, GC skew was " f"{fmt(stats['GC_skew'], '.5f')}, AT skew was {fmt(stats['AT_skew'], '.5f')}, and the CpG observed to " f"expected ratio was {fmt(stats['CpG_observed_expected'], '.5f')}. The predicted origin and terminus of " f"replication were near {fmt(stats['predicted_origin_bp'], ',')} bp and {fmt(stats['predicted_terminus_bp'], ',')} bp. " f"In the longest record, {fmt(stats['total_features_main_record'], ',')} features were parsed, including " f"{fmt(stats['CDS_count_main_record'], ',')} CDS, {fmt(stats['tRNA_count_main_record'], ',')} tRNA and " f"{fmt(stats['rRNA_count_main_record'], ',')} rRNA features, which is a coding density of " f"{fmt(stats['coding_density_percent_main_record'], '.2f')}%. Codon usage was analysed using " f"{fmt(stats['CDS_used_for_codon_analysis'], ',')} CDS that covered {fmt(stats['total_sense_codons'], ',')} sense codons. " f"The genome wide effective number of codons was {fmt(stats['effective_number_of_codons_ENC_genome'], '.2f')}, " f"as well as a mean per CDS value of {fmt(stats['mean_ENC_per_CDS'], '.2f')}. The neutrality plot of GC12 against " f"GC3 gave a regression slope of {fmt(stats['neutrality_slope_GC12_vs_GC3'], '.3f')} and a correlation of " f"{fmt(stats['neutrality_correlation_r'], '.3f')}, which describes the balance between mutation and selection " f"pressure on codon usage. The mean codon adaptation index was {fmt(stats['codon_adaptation_index_CAI_mean'], '.4f')}." )
METHODS_TEXT = ( "Methods. Sequence composition was computed from nucleotide counts. GC content and AT content were the " "percentage of G plus C and A plus T over valid bases. GC skew was (G minus C) over (G plus C) and AT skew " "was (A minus T) over (A plus T), computed in sliding windows and cumulatively. The predicted origin and " "terminus of replication were taken as the minimum and maximum of the cumulative GC skew (Lobry 1996; " "Grigoriev 1998). CpG observed over expected followed Gardiner-Garden and Frommer (1987). Dinucleotide " "relative abundance (genomic signature) followed Karlin and Burge (1995). Codon usage and relative " "synonymous codon usage followed Sharp and Li (1986). The effective number of codons followed Wright (1990). " "The codon adaptation index followed Sharp and Li (1987). The neutrality plot followed Sueoka (1988), the " "ENC plot followed Wright (1990), and the PR2 bias plot followed Sueoka (1995). GRAVY followed Kyte and " "Doolittle (1982). Users should confirm the genetic code table and confirm predictions with dedicated tools " "before final reporting.")
# -----------------------------# Session state and Streamlit UI# -----------------------------3 unmodified lines "error": "", "records": [], "tables": {}, "record_id": None, "main_record_id": None, "stats": {}, "stats_df": pd.DataFrame(), "feature_df": pd.DataFrame(), "filtered_df": pd.DataFrame(), "window_df": pd.DataFrame(), "codon_df": pd.DataFrame(), "per_cds_df": pd.DataFrame(), "aa_df": pd.DataFrame(), "dinuc_df": pd.DataFrame(), "tetra_df": pd.DataFrame(), "dist_df": pd.DataFrame(), "assembly": {}, "origin_terminus": {}, "neutrality": {}, "summary": "", "figures": {}, "bundle": None, "notes": [], "available_types": [], "selected_types": [], "palette_name": "Default", } for k, v in defaults.items(): st.session_state.setdefault(k, v)7 unmodified lines
initialise_state()
st.markdown('<div class="main-title">GenomeScope Pro: Whole Genome Visualization and Composition Analytics</div>', unsafe_allow_html=True)st.markdown('<div class="sub-title">A Streamlit tool for annotated genome maps, GC analysis, codon usage, codon bias indices and publication grade image export.</div>', unsafe_allow_html=True)st.markdown('<div class="main-title">GenomeScope Pro 2.0: Whole Genome Visualization and Composition Analytics</div>', unsafe_allow_html=True)st.markdown('<div class="sub-title">A Streamlit tool for annotated genome maps, GC and skew analysis, codon usage, codon bias indices, replication origin prediction, and publication grade figure export.</div>', unsafe_allow_html=True)
with st.sidebar: st.header("Input")12 unmodified lines reference_upload = st.file_uploader("Optional reference codon weights for CAI, CSV/TSV with codon and weight columns", accept_multiple_files=False)
st.header("Analysis settings") genetic_code_label = st.selectbox("Genetic code table", list(GENETIC_CODE_OPTIONS.keys()), index=0) palette_name = st.selectbox("Feature colour palette", list(FEATURE_PALETTES.keys()), index=0) theme_name = st.selectbox("Figure colour theme", list(LINE_THEMES.keys()), index=0) run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1) derive_weights = st.checkbox("Derive codon weights from this genome when no reference is given", value=True) infer_orfs = st.checkbox("Predict ORFs for FASTA only input", value=False) min_orf_aa = st.slider("Minimum ORF length, amino acids", 30, 500, 90, 10) query = st.text_input("Search and highlight feature", value="") min_feature_length = st.number_input("Minimum feature length to display, bp", min_value=0, max_value=500000, value=0, step=50) max_features = st.number_input("Maximum displayed features", min_value=100, max_value=100000, value=25000, step=100) window_size = st.number_input("GC window size, bp", min_value=100, max_value=500000, value=1000, step=100) window_size = st.number_input("Window size for GC and skew, bp", min_value=100, max_value=500000, value=1000, step=100)
run_button = st.button("Run genome analysis", type="primary", use_container_width=True) clear_button = st.button("Clear results", use_container_width=True)
st.markdown('<div class="note">Methods references: Lobry 1996, Grigoriev 1998, Karlin and Burge 1995, ' 'Gardiner-Garden and Frommer 1987, Sharp and Li 1986 and 1987, Wright 1990, Sueoka 1988 and 1995, ' 'Kyte and Doolittle 1982.</div>', unsafe_allow_html=True)
if clear_button: reset_state() st.rerun()5 unmodified lines if input_mode in {"GFF/GTF plus FASTA", "BED plus FASTA", "Annotation table plus FASTA"} and secondary_upload is None: st.error("Please upload both the annotation file and the matching FASTA file.") st.stop() with st.spinner("Parsing genome, calculating composition metrics and rendering figures..."): with st.spinner("Parsing genome, computing composition and codon metrics, and rendering figures..."): try: ctx = build_codon_context(GENETIC_CODE_OPTIONS[genetic_code_label]) palette = FEATURE_PALETTES[palette_name] theme = LINE_THEMES[theme_name]
parsed = parse_input_bundle(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa) parsed = parse_input_bundle(primary_upload, secondary_upload, input_mode, infer_orfs, min_orf_aa, ctx) records = parsed.records tables = parsed.feature_tables if not records: raise ValueError("No sequence records were parsed.") record = records[0] feature_df = tables.get(record.id, pd.DataFrame()).copy()
main_record = max(records, key=lambda r: len(r.seq)) feature_df = tables.get(main_record.id, pd.DataFrame()).copy() available_types = sorted(feature_df["feature_type"].dropna().unique().tolist()) if not feature_df.empty else [] selected_types = [x for x in DEFAULT_FEATURES if x in available_types] or available_types filtered_df = filter_features(feature_df, selected_types, query, int(min_feature_length), int(max_features)) window_df = window_dataframe(str(record.seq), int(window_size)) cds_sequences = collect_cds_sequences(record, feature_df) ref_weights = parse_reference_codon_weights(reference_upload) codon_df = codon_usage_table(cds_sequences, ref_weights) cai = codon_adaptation_index(cds_sequences, ref_weights) stats = build_summary_statistics(record, feature_df, filtered_df, cds_sequences, codon_df, cai) stats_df = pd.DataFrame([stats])
window_df = window_dataframe(str(main_record.seq), int(window_size)) origin_terminus = predict_origin_terminus(window_df) assembly = assembly_statistics(records) composition = genome_composition(records) nuc_counts = nucleotide_counts(str(main_record.seq)) dinuc_df = dinucleotide_relative_abundance(str(main_record.seq)) tetra_df = tetranucleotide_frequency(str(main_record.seq))
all_cds = [] for r in records: all_cds.extend(collect_cds_sequences(r, tables.get(r.id, pd.DataFrame())))
codon_counts = aggregate_codon_counts(all_cds, ctx) stop_counts = {c: 0 for c in ctx.stop_codons} for seq in all_cds: seq = valid_cds_sequence(seq) for codon in iterate_codons(seq): if codon in stop_counts: stop_counts[codon] += 1
ref_weights = parse_reference_codon_weights(reference_upload, ctx) weights = ref_weights if ref_weights else (derive_weights_from_counts(codon_counts, ctx) if derive_weights else None) codon_df = codon_usage_table(codon_counts, ctx, stop_counts, ref_weights) per_cds_df = per_cds_metrics(all_cds, ctx, weights) aa_df = amino_acid_usage(all_cds, ctx) cai_mean = round(float(per_cds_df["CAI"].dropna().mean()), 4) if not per_cds_df.empty and per_cds_df["CAI"].notna().any() else float("nan") neutrality = neutrality_regression(per_cds_df)
stats = build_summary_statistics(records, main_record, composition, assembly, origin_terminus, feature_df, filtered_df, all_cds, codon_df, codon_counts, ctx, cai_mean, per_cds_df, neutrality) stats_df = pd.DataFrame([stats]).T.reset_index() stats_df.columns = ["parameter", "value"]
publication = run_mode == "Publication quality" dpi = 600 if publication else 300 linear_fig = draw_linear_map(record, filtered_df, selected_types, publication) circular_fig = draw_circular_map(record, filtered_df, window_df, selected_types) distribution_fig, dist_df = draw_feature_distribution(feature_df) gc_fig = draw_gc_profile(window_df, len(record.seq)) codon_fig = draw_codon_rscu(codon_df)
figures = { "A_linear_genome_map.png": fig_bytes(linear_fig, "png", dpi), "B_circular_genome_map.png": fig_bytes(circular_fig, "png", dpi), "C_feature_distribution.png": fig_bytes(distribution_fig, "png", dpi), "D_GC_profile.png": fig_bytes(gc_fig, "png", dpi), "E_codon_RSCU.png": fig_bytes(codon_fig, "png", dpi), "A_linear_genome_map.svg": fig_bytes(linear_fig, "svg") if publication else None, "B_circular_genome_map.svg": fig_bytes(circular_fig, "svg") if publication else None, "C_feature_distribution.svg": fig_bytes(distribution_fig, "svg") if publication else None, "D_GC_profile.svg": fig_bytes(gc_fig, "svg") if publication else None, "E_codon_RSCU.svg": fig_bytes(codon_fig, "svg") if publication else None, "A_linear_genome_map.pdf": fig_bytes(linear_fig, "pdf") if publication else None, "B_circular_genome_map.pdf": fig_bytes(circular_fig, "pdf") if publication else None, "C_feature_distribution.pdf": fig_bytes(distribution_fig, "pdf") if publication else None, "D_GC_profile.pdf": fig_bytes(gc_fig, "pdf") if publication else None, "E_codon_RSCU.pdf": fig_bytes(codon_fig, "pdf") if publication else None,
linear_fig = draw_linear_map(main_record, filtered_df, selected_types, publication, palette) circular_fig = draw_circular_map(main_record, filtered_df, window_df, selected_types, palette, theme) distribution_fig, dist_df = draw_feature_distribution(feature_df, palette) gc_fig = draw_gc_profile(window_df, len(main_record.seq), theme) cumulative_fig = draw_cumulative_skew(window_df, origin_terminus, len(main_record.seq), theme) composition_fig = draw_composition(nuc_counts, dinuc_df, theme) rscu_fig = draw_codon_rscu(codon_df, theme) heatmap_fig = draw_rscu_heatmap(codon_df, ctx, theme["cmap"]) aa_fig = draw_amino_acid_usage(aa_df, theme) neutrality_fig = draw_neutrality(per_cds_df, neutrality, theme) enc_fig = draw_enc_plot(per_cds_df, theme) pr2_fig = draw_pr2_plot(per_cds_df, theme) length_fig = draw_feature_length_distribution(per_cds_df, theme)
fig_objects = { "A_linear_genome_map": linear_fig, "B_circular_genome_map": circular_fig, "C_feature_distribution": distribution_fig, "D_GC_profile": gc_fig, "E_cumulative_skew": cumulative_fig, "F_composition": composition_fig, "G_codon_RSCU": rscu_fig, "H_RSCU_heatmap": heatmap_fig, "I_amino_acid_usage": aa_fig, "J_neutrality_plot": neutrality_fig, "K_ENC_plot": enc_fig, "L_PR2_plot": pr2_fig, "M_CDS_length_distribution": length_fig, } for fig in [linear_fig, circular_fig, distribution_fig, gc_fig, codon_fig]:
figures = {} for name, fig in fig_objects.items(): figures[f"{name}.png"] = fig_bytes(fig, "png", dpi) if publication: figures[f"{name}.svg"] = fig_bytes(fig, "svg") figures[f"{name}.pdf"] = fig_bytes(fig, "pdf") for fig in fig_objects.values(): plt.close(fig)
summary = manuscript_summary(stats)1 unmodified line "summary_statistics.csv": stats_df, "feature_annotations.csv": feature_df, "displayed_features.csv": filtered_df, "window_GC_statistics.csv": window_df, "window_composition.csv": window_df, "codon_usage_RSCU.csv": codon_df, "per_cds_metrics.csv": per_cds_df, "amino_acid_usage.csv": aa_df, "dinucleotide_relative_abundance.csv": dinuc_df, "tetranucleotide_frequency.csv": tetra_df, "feature_distribution.csv": dist_df, "assembly_statistics.csv": pd.DataFrame([assembly]) if assembly else pd.DataFrame(), } bundle = build_bundle(figures, tables_for_zip, summary) bundle = build_bundle(figures, tables_for_zip, summary, METHODS_TEXT)
st.session_state.update({ "done": True, "error": "", "records": records, "tables": tables, "record_id": record.id, "main_record_id": main_record.id, "stats": stats, "stats_df": stats_df, "feature_df": feature_df, "filtered_df": filtered_df, "window_df": window_df, "codon_df": codon_df, "per_cds_df": per_cds_df, "aa_df": aa_df, "dinuc_df": dinuc_df, "tetra_df": tetra_df, "dist_df": dist_df, "assembly": assembly, "origin_terminus": origin_terminus, "neutrality": neutrality, "summary": summary, "figures": figures, "bundle": bundle, "notes": parsed.notes, "available_types": available_types, "selected_types": selected_types, "palette_name": palette_name, }) except Exception as exc: st.session_state["done"] = False8 unmodified lines
stats = st.session_state["stats"]figures = st.session_state["figures"]palette = FEATURE_PALETTES[st.session_state["palette_name"]]
def metric_value(key, spec, suffix=""): value = stats.get(key) if value is None or (isinstance(value, float) and np.isnan(value)): return "n/a" return f"{format(value, spec)}{suffix}"
m1, m2, m3, m4, m5, m6 = st.columns(6)m1.metric("Genome length", f"{stats['genome_length_bp']:,} bp")m2.metric("GC", f"{stats['GC_percent']:.2f}%")m3.metric("Coding density", f"{stats['coding_density_percent']:.2f}%")m4.metric("CDS", f"{stats['CDS_count']:,}")m5.metric("ENC", f"{stats['effective_number_of_codons_ENC']:.2f}")m6.metric("CAI", f"{stats['codon_adaptation_index_CAI']:.4f}")m1.metric("Total length", metric_value("total_genome_length_bp", ",", " bp"))m2.metric("GC", metric_value("GC_percent", ".2f", "%"))m3.metric("N50", metric_value("N50_bp", ",", " bp"))m4.metric("CDS analysed", metric_value("CDS_used_for_codon_analysis", ","))m5.metric("ENC genome", metric_value("effective_number_of_codons_ENC_genome", ".2f"))m6.metric("CAI mean", metric_value("codon_adaptation_index_CAI_mean", ".4f"))
if st.session_state["notes"]: st.markdown('<div class="box"><b>Run notes</b><br>' + "<br>".join(st.session_state["notes"]) + "</div>", unsafe_allow_html=True)
st.markdown('<div class="box"><b>Feature colour legend</b><br>' + feature_legend_html(st.session_state["selected_types"], bool(st.session_state["filtered_df"].get("highlight", pd.Series(dtype=bool)).any()) if not st.session_state["filtered_df"].empty else False) + "</div>", unsafe_allow_html=True)st.markdown('<div class="box"><b>Feature colour legend</b><br>' + feature_legend_html(st.session_state["selected_types"], bool(st.session_state["filtered_df"].get("highlight", pd.Series(dtype=bool)).any()) if not st.session_state["filtered_df"].empty else False, palette) + "</div>", unsafe_allow_html=True)
tabs = st.tabs(["Genome images", "Genome statistics", "Codon bias", "Annotation table", "Manuscript text", "Downloads"])tabs = st.tabs(["Genome maps", "Composition", "Codon bias", "Per CDS metrics", "Annotation table", "Manuscript text", "Downloads"])
with tabs[0]: st.subheader("Publication grade genome images") image_tabs = st.tabs(["Linear map", "Circular map", "Feature distribution", "GC profile", "Codon RSCU"]) keys = ["A_linear_genome_map.png", "B_circular_genome_map.png", "C_feature_distribution.png", "D_GC_profile.png", "E_codon_RSCU.png"] for tab, key in zip(image_tabs, keys): st.subheader("Publication grade genome maps") image_tabs = st.tabs(["Linear map", "Circular map", "Feature distribution"]) for tab, key in zip(image_tabs, ["A_linear_genome_map.png", "B_circular_genome_map.png", "C_feature_distribution.png"]): with tab: st.image(figures[key], use_container_width=True)
with tabs[1]: st.subheader("Genome composition and structure") st.dataframe(st.session_state["stats_df"], use_container_width=True, height=180) st.markdown("**Window based GC statistics**") st.dataframe(st.session_state["window_df"], use_container_width=True, height=300) st.markdown("**Feature distribution**") st.dataframe(st.session_state["dist_df"], use_container_width=True, height=250) comp_tabs = st.tabs(["GC profile", "Cumulative skew", "Composition", "Window table", "Dinucleotide", "Tetranucleotide"]) with comp_tabs[0]: st.image(figures["D_GC_profile.png"], use_container_width=True) with comp_tabs[1]: st.image(figures["E_cumulative_skew.png"], use_container_width=True) ori = st.session_state["origin_terminus"].get("origin_bp") ter = st.session_state["origin_terminus"].get("terminus_bp") st.markdown(f'<div class="note">Predicted origin near {ori:,} bp and terminus near {ter:,} bp. ' f'These are predictions from cumulative GC skew and should be confirmed for a final assembly.</div>' if ori is not None and ter is not None else '<div class="note">No origin prediction available.</div>', unsafe_allow_html=True) with comp_tabs[2]: st.image(figures["F_composition.png"], use_container_width=True) with comp_tabs[3]: st.dataframe(st.session_state["window_df"], use_container_width=True, height=320) with comp_tabs[4]: st.dataframe(st.session_state["dinuc_df"], use_container_width=True, height=320) with comp_tabs[5]: st.dataframe(st.session_state["tetra_df"], use_container_width=True, height=320)
with tabs[2]: st.subheader("Codon usage and codon bias") codon_tabs = st.tabs(["RSCU bars", "RSCU heatmap", "Amino acid usage", "Neutrality", "ENC plot", "PR2 plot", "Codon table"]) with codon_tabs[0]: st.image(figures["G_codon_RSCU.png"], use_container_width=True) with codon_tabs[1]: st.image(figures["H_RSCU_heatmap.png"], use_container_width=True) with codon_tabs[2]: st.image(figures["I_amino_acid_usage.png"], use_container_width=True) with codon_tabs[3]: st.image(figures["J_neutrality_plot.png"], use_container_width=True) n = st.session_state["neutrality"] st.markdown(f'<div class="note">Neutrality slope of GC12 on GC3 was {n.get("slope")} with correlation {n.get("r")} ' f'over {n.get("n")} CDS. A slope near 1 suggests weak selection and a low slope suggests stronger selection on codon usage.</div>', unsafe_allow_html=True) with codon_tabs[4]: st.image(figures["K_ENC_plot.png"], use_container_width=True) with codon_tabs[5]: st.image(figures["L_PR2_plot.png"], use_container_width=True) with codon_tabs[6]: st.dataframe(st.session_state["codon_df"], use_container_width=True, height=420) st.markdown('<div class="note">ENC ranges from about 20 to 61. Lower values indicate stronger codon usage bias. CAI is calculated only when a valid reference codon weight table is uploaded.</div>', unsafe_allow_html=True) st.dataframe(st.session_state["codon_df"], use_container_width=True, height=420) st.markdown('<div class="note">ENC ranges from about 20 to 61. Lower values indicate stronger codon usage bias. ' 'CAI uses the uploaded reference weights, or weights derived from this genome when that option is selected.</div>', unsafe_allow_html=True)
with tabs[3]: st.subheader("Per CDS metrics") st.image(figures["M_CDS_length_distribution.png"], use_container_width=True) st.dataframe(st.session_state["per_cds_df"], use_container_width=True, height=380)
with tabs[4]: st.subheader("Parsed and displayed annotation") st.markdown("**Genome summary parameters**") st.dataframe(st.session_state["stats_df"], use_container_width=True, height=300) st.markdown("**Displayed features**") st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=350) st.markdown("**All parsed features**") st.dataframe(st.session_state["feature_df"], use_container_width=True, height=350) st.dataframe(st.session_state["filtered_df"], use_container_width=True, height=300) st.markdown("**All parsed features in the longest record**") st.dataframe(st.session_state["feature_df"], use_container_width=True, height=300)
with tabs[4]:with tabs[5]: st.subheader("Manuscript ready result statement") st.text_area("Generated text", value=st.session_state["summary"], height=180) st.text_area("Generated result text", value=st.session_state["summary"], height=220) st.markdown("**Methods paragraph**") st.text_area("Methods text", value=METHODS_TEXT, height=220)
with tabs[5]:with tabs[6]: st.subheader("Download results") st.download_button("Download complete results package", data=st.session_state["bundle"], file_name="GenomeScope_Pro_results.zip", mime="application/zip", use_container_width=True) cols = st.columns(2) with cols[0]: st.download_button("Download linear genome map", data=figures["A_linear_genome_map.png"], file_name="A_linear_genome_map.png", mime="image/png") st.download_button("Download circular genome map", data=figures["B_circular_genome_map.png"], file_name="B_circular_genome_map.png", mime="image/png") st.download_button("Download codon usage table", data=st.session_state["codon_df"].to_csv(index=False).encode("utf-8"), file_name="codon_usage_RSCU.csv", mime="text/csv") st.download_button("Linear genome map (PNG)", data=figures["A_linear_genome_map.png"], file_name="A_linear_genome_map.png", mime="image/png") st.download_button("Circular genome map (PNG)", data=figures["B_circular_genome_map.png"], file_name="B_circular_genome_map.png", mime="image/png") st.download_button("Cumulative skew (PNG)", data=figures["E_cumulative_skew.png"], file_name="E_cumulative_skew.png", mime="image/png") st.download_button("RSCU heatmap (PNG)", data=figures["H_RSCU_heatmap.png"], file_name="H_RSCU_heatmap.png", mime="image/png") with cols[1]: st.download_button("Per CDS metrics (CSV)", data=st.session_state["per_cds_df"].to_csv(index=False).encode("utf-8"), file_name="per_cds_metrics.csv", mime="text/csv") st.download_button("Codon usage table (CSV)", data=st.session_state["codon_df"].to_csv(index=False).encode("utf-8"), file_name="codon_usage_RSCU.csv", mime="text/csv") st.download_button("Summary parameters (CSV)", data=st.session_state["stats_df"].to_csv(index=False).encode("utf-8"), file_name="summary_statistics.csv", mime="text/csv") st.download_button("Window composition (CSV)", data=st.session_state["window_df"].to_csv(index=False).encode("utf-8"), file_name="window_composition.csv", mime="text/csv")
st.markdown("---")st.markdown("GenomeScope Pro calculates sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. For FASTA only inputs, feature maps depend on optional ORF prediction and should be interpreted as predicted rather than curated annotation.")st.markdown("GenomeScope Pro 2.0 computes sequence composition from the nucleotide sequence and codon statistics from CDS coordinates. " "Detailed maps and GC profiles use the longest record, while codon analysis pools CDS across all records. " "For FASTA only inputs, feature maps depend on optional ORF prediction and should be read as predicted rather than curated annotation.")app.py+1034-269