File size: 22,499 Bytes
1295dcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
"""
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