GENOME_ANNOTATION / genome_analysis.py
GENOMICS-CDDBRG's picture
Upload 2 files
1295dcf verified
Raw History Blame Contribute Delete
22.5 kB
"""
genome_analysis.py
Computes genome parameters and produces publication-quality figures and tables
from a genome FASTA file and standard Prokka output files (.gff, .ffn, .faa, .tsv).
All functions use only pandas, numpy, and matplotlib, so the module runs without
Biopython or other heavy dependencies.
Author tool: Genome Annotation and Analysis Workbench
"""
import os
import math
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg") # headless backend for servers such as Hugging Face Spaces
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
# ----------------------------------------------------------------------------
# Publication style
# ----------------------------------------------------------------------------
PALETTE = {
"primary": "#2c5f8a",
"secondary": "#c45a3b",
"accent": "#3b8c6e",
"neutral": "#6b6b6b",
"light": "#d9e2ec",
"warm": "#d9a23b",
}
CATEGORY_COLORS = [
"#2c5f8a", "#c45a3b", "#3b8c6e", "#d9a23b", "#7a5ba6",
"#5a8fc4", "#b04a6a", "#4a9d8e", "#c98f3b", "#8a6bbf",
]
def set_publication_style():
"""Apply a clean style suitable for journal figures."""
plt.rcParams.update({
"figure.dpi": 120,
"savefig.dpi": 300,
"font.family": "sans-serif",
"font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"],
"font.size": 11,
"axes.titlesize": 13,
"axes.titleweight": "bold",
"axes.labelsize": 11,
"axes.edgecolor": "#444444",
"axes.linewidth": 0.9,
"axes.spines.top": False,
"axes.spines.right": False,
"xtick.labelsize": 9.5,
"ytick.labelsize": 9.5,
"legend.fontsize": 9.5,
"legend.frameon": False,
"figure.facecolor": "white",
"axes.facecolor": "white",
"axes.grid": True,
"grid.color": "#e6e6e6",
"grid.linewidth": 0.7,
})
# ----------------------------------------------------------------------------
# Genetic code and helpers
# ----------------------------------------------------------------------------
CODON_TABLE = {
"TTT": "F", "TTC": "F", "TTA": "L", "TTG": "L",
"CTT": "L", "CTC": "L", "CTA": "L", "CTG": "L",
"ATT": "I", "ATC": "I", "ATA": "I", "ATG": "M",
"GTT": "V", "GTC": "V", "GTA": "V", "GTG": "V",
"TCT": "S", "TCC": "S", "TCA": "S", "TCG": "S",
"CCT": "P", "CCC": "P", "CCA": "P", "CCG": "P",
"ACT": "T", "ACC": "T", "ACA": "T", "ACG": "T",
"GCT": "A", "GCC": "A", "GCA": "A", "GCG": "A",
"TAT": "Y", "TAC": "Y", "TAA": "*", "TAG": "*",
"CAT": "H", "CAC": "H", "CAA": "Q", "CAG": "Q",
"AAT": "N", "AAC": "N", "AAA": "K", "AAG": "K",
"GAT": "D", "GAC": "D", "GAA": "E", "GAG": "E",
"TGT": "C", "TGC": "C", "TGA": "*", "TGG": "W",
"CGT": "R", "CGC": "R", "CGA": "R", "CGG": "R",
"AGT": "S", "AGC": "S", "AGA": "R", "AGG": "R",
"GGT": "G", "GGC": "G", "GGA": "G", "GGG": "G",
}
AA_NAMES = {
"A": "Ala", "R": "Arg", "N": "Asn", "D": "Asp", "C": "Cys",
"Q": "Gln", "E": "Glu", "G": "Gly", "H": "His", "I": "Ile",
"L": "Leu", "K": "Lys", "M": "Met", "F": "Phe", "P": "Pro",
"S": "Ser", "T": "Thr", "W": "Trp", "Y": "Tyr", "V": "Val",
}
def synonymous_codon_map():
"""Return amino acid -> list of codons (stop codons grouped under '*')."""
syn = defaultdict(list)
for codon, aa in CODON_TABLE.items():
syn[aa].append(codon)
return syn
# ----------------------------------------------------------------------------
# FASTA parsing
# ----------------------------------------------------------------------------
def read_fasta(path):
"""Read a FASTA file into a dict {header: sequence}. Header is first token."""
sequences = {}
header = None
chunks = []
with open(path, "r") as fh:
for line in fh:
line = line.rstrip("\n")
if not line:
continue
if line.startswith(">"):
if header is not None:
sequences[header] = "".join(chunks).upper()
header = line[1:].split()[0]
chunks = []
else:
chunks.append(line)
if header is not None:
sequences[header] = "".join(chunks).upper()
return sequences
def read_fasta_records(path):
"""Read a FASTA file into a list of (header, sequence). Keeps full header."""
records = []
header = None
chunks = []
with open(path, "r") as fh:
for line in fh:
line = line.rstrip("\n")
if not line:
continue
if line.startswith(">"):
if header is not None:
records.append((header, "".join(chunks).upper()))
header = line[1:]
chunks = []
else:
chunks.append(line)
if header is not None:
records.append((header, "".join(chunks).upper()))
return records
# ----------------------------------------------------------------------------
# Assembly statistics
# ----------------------------------------------------------------------------
def gc_content(seq):
if not seq:
return 0.0
g = seq.count("G")
c = seq.count("C")
return 100.0 * (g + c) / len(seq)
def n_content(seq):
if not seq:
return 0.0
return 100.0 * seq.count("N") / len(seq)
def _nx_lx(lengths, fraction):
"""Return (Nx, Lx) for a given fraction such as 0.5 for N50."""
if not lengths:
return 0, 0
sorted_lengths = sorted(lengths, reverse=True)
total = sum(sorted_lengths)
target = total * fraction
cumulative = 0
for i, length in enumerate(sorted_lengths, start=1):
cumulative += length
if cumulative >= target:
return length, i
return sorted_lengths[-1], len(sorted_lengths)
def assembly_stats(contigs):
"""Return a dict of assembly metrics from a {header: seq} dict."""
lengths = [len(s) for s in contigs.values()]
total = sum(lengths)
full_seq = "".join(contigs.values())
n50, l50 = _nx_lx(lengths, 0.5)
n75, l75 = _nx_lx(lengths, 0.75)
n90, l90 = _nx_lx(lengths, 0.90)
gc_values = [gc_content(s) for s in contigs.values()]
return {
"total_length_bp": total,
"num_contigs": len(lengths),
"gc_percent": gc_content(full_seq),
"n_percent": n_content(full_seq),
"largest_contig_bp": max(lengths) if lengths else 0,
"smallest_contig_bp": min(lengths) if lengths else 0,
"mean_contig_bp": float(np.mean(lengths)) if lengths else 0.0,
"median_contig_bp": float(np.median(lengths)) if lengths else 0.0,
"N50": n50, "L50": l50,
"N75": n75, "L75": l75,
"N90": n90, "L90": l90,
"gc_min_percent": min(gc_values) if gc_values else 0.0,
"gc_max_percent": max(gc_values) if gc_values else 0.0,
"gc_std_percent": float(np.std(gc_values)) if gc_values else 0.0,
}
def per_contig_table(contigs):
"""Per-contig DataFrame: name, length, GC%, N%."""
rows = []
for name, seq in contigs.items():
rows.append({
"contig": name,
"length_bp": len(seq),
"gc_percent": round(gc_content(seq), 3),
"n_percent": round(n_content(seq), 3),
})
df = pd.DataFrame(rows).sort_values("length_bp", ascending=False).reset_index(drop=True)
return df
def assembly_stats_table(stats):
"""Format the assembly stats dict as a tidy two-column table."""
order = [
("Total length (bp)", stats["total_length_bp"]),
("Number of contigs", stats["num_contigs"]),
("GC content (%)", round(stats["gc_percent"], 3)),
("N content (%)", round(stats["n_percent"], 4)),
("Largest contig (bp)", stats["largest_contig_bp"]),
("Smallest contig (bp)", stats["smallest_contig_bp"]),
("Mean contig (bp)", round(stats["mean_contig_bp"], 1)),
("Median contig (bp)", round(stats["median_contig_bp"], 1)),
("N50 (bp)", stats["N50"]),
("L50", stats["L50"]),
("N75 (bp)", stats["N75"]),
("L75", stats["L75"]),
("N90 (bp)", stats["N90"]),
("L90", stats["L90"]),
("GC range across contigs (%)",
f"{round(stats['gc_min_percent'],2)} to {round(stats['gc_max_percent'],2)}"),
("GC std across contigs (%)", round(stats["gc_std_percent"], 3)),
]
return pd.DataFrame(order, columns=["Metric", "Value"])
# ----------------------------------------------------------------------------
# GC skew
# ----------------------------------------------------------------------------
def gc_skew_windows(seq, window=10000, step=5000):
"""Compute windowed GC skew (G-C)/(G+C) and cumulative skew."""
positions = []
skew = []
cumulative = []
running = 0.0
for start in range(0, max(1, len(seq) - window + 1), step):
sub = seq[start:start + window]
g = sub.count("G")
c = sub.count("C")
denom = g + c
value = (g - c) / denom if denom else 0.0
running += value
positions.append(start + window // 2)
skew.append(value)
cumulative.append(running)
return np.array(positions), np.array(skew), np.array(cumulative)
# ----------------------------------------------------------------------------
# GFF parsing and coding metrics
# ----------------------------------------------------------------------------
def parse_gff(path):
"""Parse a Prokka GFF3 file into a DataFrame of features (before FASTA section)."""
rows = []
with open(path, "r") as fh:
for line in fh:
if line.startswith("##FASTA"):
break
if line.startswith("#") or not line.strip():
continue
parts = line.rstrip("\n").split("\t")
if len(parts) < 9:
continue
seqid, source, ftype, start, end, score, strand, phase, attrs = parts[:9]
try:
start_i = int(start)
end_i = int(end)
except ValueError:
continue
attr_dict = {}
for field in attrs.split(";"):
if "=" in field:
k, v = field.split("=", 1)
attr_dict[k] = v
rows.append({
"seqid": seqid,
"type": ftype,
"start": start_i,
"end": end_i,
"length_bp": end_i - start_i + 1,
"strand": strand,
"product": attr_dict.get("product", ""),
"gene": attr_dict.get("gene", ""),
})
return pd.DataFrame(rows)
def coding_density(total_length_bp, gff_df):
"""Percent of genome covered by CDS features."""
if gff_df.empty or total_length_bp == 0:
return 0.0
cds = gff_df[gff_df["type"] == "CDS"]
coding_bp = int(cds["length_bp"].sum())
return 100.0 * coding_bp / total_length_bp
def feature_type_counts(gff_df):
"""Counts of each feature type."""
if gff_df.empty:
return pd.DataFrame(columns=["Feature", "Count"])
counts = gff_df["type"].value_counts().reset_index()
counts.columns = ["Feature", "Count"]
return counts
def strand_distribution(gff_df):
"""Counts of CDS on plus and minus strand."""
if gff_df.empty:
return {"+": 0, "-": 0}
cds = gff_df[gff_df["type"] == "CDS"]
plus = int((cds["strand"] == "+").sum())
minus = int((cds["strand"] == "-").sum())
return {"+": plus, "-": minus}
def hypothetical_fraction(gff_df):
"""Fraction of CDS annotated as hypothetical protein."""
cds = gff_df[gff_df["type"] == "CDS"]
if cds.empty:
return 0.0, 0, 0
hyp = cds["product"].str.contains("hypothetical", case=False, na=False).sum()
total = len(cds)
return 100.0 * hyp / total, int(hyp), int(total)
# ----------------------------------------------------------------------------
# Codon usage and RSCU
# ----------------------------------------------------------------------------
def codon_counts_from_ffn(ffn_path):
"""Count codons across all CDS nucleotide sequences in a Prokka .ffn file."""
counts = Counter()
for _, seq in read_fasta_records(ffn_path):
seq = seq.replace("U", "T")
for i in range(0, len(seq) - 2, 3):
codon = seq[i:i + 3]
if codon in CODON_TABLE and set(codon) <= set("ACGT"):
counts[codon] += 1
return counts
def compute_rscu(codon_counts):
"""Compute RSCU for each codon. RSCU = observed / mean over synonymous codons."""
syn = synonymous_codon_map()
rscu = {}
for aa, codons in syn.items():
if aa == "*":
continue
total = sum(codon_counts.get(c, 0) for c in codons)
n = len(codons)
if total == 0:
for c in codons:
rscu[c] = 0.0
continue
mean_count = total / n
for c in codons:
rscu[c] = codon_counts.get(c, 0) / mean_count if mean_count else 0.0
return rscu
def codon_usage_table(codon_counts, rscu):
"""Build a codon usage table with counts, fraction per amino acid, and RSCU."""
syn = synonymous_codon_map()
rows = []
for aa, codons in sorted(syn.items()):
if aa == "*":
continue
aa_total = sum(codon_counts.get(c, 0) for c in codons)
for c in sorted(codons):
count = codon_counts.get(c, 0)
frac = count / aa_total if aa_total else 0.0
rows.append({
"Amino acid": AA_NAMES.get(aa, aa),
"AA": aa,
"Codon": c,
"Count": count,
"Fraction": round(frac, 4),
"RSCU": round(rscu.get(c, 0.0), 3),
})
return pd.DataFrame(rows)
# ----------------------------------------------------------------------------
# Amino acid composition
# ----------------------------------------------------------------------------
def amino_acid_composition(faa_path):
"""Compute amino acid composition across all proteins in a Prokka .faa file."""
counts = Counter()
total = 0
for _, seq in read_fasta_records(faa_path):
seq = seq.replace("*", "")
for aa in seq:
if aa in AA_NAMES:
counts[aa] += 1
total += 1
rows = []
for aa, name in AA_NAMES.items():
c = counts.get(aa, 0)
rows.append({
"Amino acid": name,
"AA": aa,
"Count": c,
"Percent": round(100.0 * c / total, 3) if total else 0.0,
})
df = pd.DataFrame(rows).sort_values("Percent", ascending=False).reset_index(drop=True)
return df
def gene_length_series(gff_df):
"""Return a Series of CDS lengths in base pairs."""
cds = gff_df[gff_df["type"] == "CDS"]
return cds["length_bp"]
# ----------------------------------------------------------------------------
# Figures
# ----------------------------------------------------------------------------
def _save(fig, outdir, name):
"""Save a figure as PNG and PDF at 300 dpi. Return the PNG path."""
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
png = outdir / f"{name}.png"
pdf = outdir / f"{name}.pdf"
fig.savefig(png, bbox_inches="tight", dpi=300)
fig.savefig(pdf, bbox_inches="tight")
return str(png)
def fig_contig_length_distribution(contigs, outdir):
lengths = sorted([len(s) for s in contigs.values()], reverse=True)
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.bar(range(1, len(lengths) + 1), [l / 1000.0 for l in lengths],
color=PALETTE["primary"], edgecolor="white", linewidth=0.5)
ax.set_xlabel("Contig rank (largest to smallest)")
ax.set_ylabel("Length (kb)")
ax.set_title("Contig length distribution")
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
return _save(fig, outdir, "fig_contig_length_distribution"), fig
def fig_cumulative_length(contigs, stats, outdir):
lengths = sorted([len(s) for s in contigs.values()], reverse=True)
cumulative = np.cumsum(lengths) / 1e6
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.plot(range(1, len(lengths) + 1), cumulative,
color=PALETTE["primary"], linewidth=2, marker="o", markersize=3)
ax.axhline(stats["total_length_bp"] / 2e6, color=PALETTE["secondary"],
linestyle="--", linewidth=1.2, label="50% of assembly")
ax.axvline(stats["L50"], color=PALETTE["accent"], linestyle=":",
linewidth=1.2, label=f"L50 = {stats['L50']}")
ax.set_xlabel("Number of contigs")
ax.set_ylabel("Cumulative length (Mb)")
ax.set_title("Cumulative assembly length and N50")
ax.legend()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
return _save(fig, outdir, "fig_cumulative_length"), fig
def fig_gc_per_contig(contigs, stats, outdir):
gc_values = [gc_content(s) for s in contigs.values()]
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.hist(gc_values, bins=min(20, max(5, len(gc_values))),
color=PALETTE["accent"], edgecolor="white", linewidth=0.6)
ax.axvline(stats["gc_percent"], color=PALETTE["secondary"], linestyle="--",
linewidth=1.3, label=f"Genome GC = {stats['gc_percent']:.2f}%")
ax.set_xlabel("GC content per contig (%)")
ax.set_ylabel("Number of contigs")
ax.set_title("GC content distribution across contigs")
ax.legend()
return _save(fig, outdir, "fig_gc_per_contig"), fig
def fig_gc_skew(contigs, outdir, window=10000, step=5000):
# Use the longest contig for a clean skew profile
longest = max(contigs.values(), key=len)
positions, skew, cumulative = gc_skew_windows(longest, window=window, step=step)
fig, axes = plt.subplots(2, 1, figsize=(6.5, 5.5), sharex=True)
axes[0].plot(positions / 1000.0, skew, color=PALETTE["primary"], linewidth=1.2)
axes[0].axhline(0, color=PALETTE["neutral"], linewidth=0.8)
axes[0].set_ylabel("GC skew")
axes[0].set_title("GC skew along the longest contig")
axes[1].plot(positions / 1000.0, cumulative, color=PALETTE["secondary"], linewidth=1.6)
axes[1].set_ylabel("Cumulative GC skew")
axes[1].set_xlabel("Position (kb)")
return _save(fig, outdir, "fig_gc_skew"), fig
def fig_feature_counts(gff_df, outdir):
counts = feature_type_counts(gff_df)
fig, ax = plt.subplots(figsize=(6.5, 4))
colors = [CATEGORY_COLORS[i % len(CATEGORY_COLORS)] for i in range(len(counts))]
ax.bar(counts["Feature"], counts["Count"], color=colors,
edgecolor="white", linewidth=0.6)
ax.set_xlabel("Feature type")
ax.set_ylabel("Count")
ax.set_title("Annotated feature counts")
for i, v in enumerate(counts["Count"]):
ax.text(i, v, str(int(v)), ha="center", va="bottom", fontsize=8.5)
plt.setp(ax.get_xticklabels(), rotation=30, ha="right")
return _save(fig, outdir, "fig_feature_counts"), fig
def fig_gene_length_hist(gff_df, outdir):
lengths = gene_length_series(gff_df)
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.hist(lengths, bins=40, color=PALETTE["primary"],
edgecolor="white", linewidth=0.5)
median = float(np.median(lengths)) if len(lengths) else 0
ax.axvline(median, color=PALETTE["secondary"], linestyle="--",
linewidth=1.3, label=f"Median = {median:.0f} bp")
ax.set_xlabel("CDS length (bp)")
ax.set_ylabel("Number of CDS")
ax.set_title("CDS length distribution")
ax.legend()
return _save(fig, outdir, "fig_gene_length_hist"), fig
def fig_strand_pie(gff_df, outdir):
sd = strand_distribution(gff_df)
fig, ax = plt.subplots(figsize=(5, 5))
values = [sd["+"], sd["-"]]
labels = [f"Plus strand\n({sd['+']})", f"Minus strand\n({sd['-']})"]
ax.pie(values, labels=labels, colors=[PALETTE["primary"], PALETTE["secondary"]],
autopct="%1.1f%%", startangle=90, counterclock=False,
wedgeprops={"edgecolor": "white", "linewidth": 1.5},
textprops={"fontsize": 10})
ax.set_title("CDS strand distribution")
return _save(fig, outdir, "fig_strand_distribution"), fig
def fig_rscu(rscu, outdir):
syn = synonymous_codon_map()
codons = []
values = []
aa_for_codon = []
for aa in sorted(syn.keys()):
if aa == "*":
continue
for c in sorted(syn[aa]):
codons.append(c)
values.append(rscu.get(c, 0.0))
aa_for_codon.append(aa)
fig, ax = plt.subplots(figsize=(11, 4))
# color by amino acid group
unique_aa = sorted(set(aa_for_codon))
color_map = {aa: CATEGORY_COLORS[i % len(CATEGORY_COLORS)]
for i, aa in enumerate(unique_aa)}
bar_colors = [color_map[aa] for aa in aa_for_codon]
ax.bar(range(len(codons)), values, color=bar_colors,
edgecolor="white", linewidth=0.4)
ax.axhline(1.0, color=PALETTE["neutral"], linestyle="--", linewidth=1)
ax.set_xticks(range(len(codons)))
ax.set_xticklabels(codons, rotation=90, fontsize=7)
ax.set_ylabel("RSCU")
ax.set_title("Relative synonymous codon usage (RSCU)")
return _save(fig, outdir, "fig_rscu"), fig
def fig_aa_composition(aa_df, outdir):
fig, ax = plt.subplots(figsize=(7.5, 4))
ax.bar(aa_df["Amino acid"], aa_df["Percent"], color=PALETTE["accent"],
edgecolor="white", linewidth=0.6)
ax.set_xlabel("Amino acid")
ax.set_ylabel("Percent of residues (%)")
ax.set_title("Amino acid composition of the proteome")
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
return _save(fig, outdir, "fig_aa_composition"), fig
def fig_coding_density(density_percent, outdir):
fig, ax = plt.subplots(figsize=(5, 5))
values = [density_percent, max(0.0, 100 - density_percent)]
ax.pie(values, labels=[f"Coding\n{density_percent:.1f}%",
f"Non-coding\n{100 - density_percent:.1f}%"],
colors=[PALETTE["primary"], PALETTE["light"]],
startangle=90, counterclock=False,
wedgeprops={"edgecolor": "white", "linewidth": 1.5},
textprops={"fontsize": 10})
centre = plt.Circle((0, 0), 0.6, color="white")
ax.add_artist(centre)
ax.set_title("Coding density")
return _save(fig, outdir, "fig_coding_density"), fig