File size: 23,808 Bytes
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
genomics_figures.py
===================
Every figure in the suite. Kept separate from the UI so figures can be
regression-tested without a browser, and separate from the maths so a plotting
change can never alter a reported number.

House rules for all panels:
  * 600 dpi raster / true-vector PDF-EPS with Type-42 fonts (journal default).
  * Colourblind-safe palette available and used by default.
  * Every axis carries units. Every heuristic panel says so in the panel itself,
    not only in a caption that may be dropped in review.
  * Empty input produces a labelled blank panel, never a misleading empty axis.
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence, Tuple

import numpy as np
import pandas as pd

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

import genomics_core as gc

__all__ = [
    "fig_composition_overview", "fig_skew_and_ori", "fig_rscu_heatmap",
    "fig_enc_plot", "fig_neutrality_plot", "fig_pr2_plot", "fig_codon_bar",
    "fig_amino_acid_usage", "fig_dinucleotide_oe", "fig_assembly_curve",
    "fig_distance_heatmap", "fig_pangenome_curves", "fig_pangenome_pie",
    "fig_presence_absence", "fig_feature_map", "fig_length_hist",
]

_ANNOT_KW = dict(fontsize=7.5, color="#8a4b08", style="italic")


def _finish(fig, tight=True):
    if tight:
        fig.tight_layout()
    return fig


def _blank(title: str, msg: str, figsize=(7, 4)):
    fig, ax = plt.subplots(figsize=figsize)
    gc.blank_panel(ax, msg)
    ax.set_title(title)
    return _finish(fig)


# ----------------------------------------------------------------------
# Composition
# ----------------------------------------------------------------------

def fig_composition_overview(records: pd.DataFrame, theme: str = "Ocean"):
    """4-panel: base composition, GC per record, length distribution, entropy."""
    if records is None or records.empty:
        return _blank("Composition overview", "No records to display")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, axes = plt.subplots(2, 2, figsize=(11, 7.5))

    ax = axes[0, 0]
    bases = ["A", "T", "G", "C", "N"]
    vals = [records[f"count_{b}"].sum() for b in bases]
    total = sum(vals) or 1
    cols = ["#4C72B0", "#DD8452", "#55A868", "#C44E52", "#999999"]
    bars = ax.bar(bases, [100.0 * v / total for v in vals], color=cols,
                  edgecolor="black", linewidth=0.5)
    for b, v in zip(bars, vals):
        ax.text(b.get_x() + b.get_width() / 2, b.get_height(),
                f"{100.0*v/total:.2f}%", ha="center", va="bottom", fontsize=8)
    ax.set_ylabel("Composition (% of all bases)")
    ax.set_title("Base composition")

    ax = axes[0, 1]
    ax.hist(records["gc_percent"], bins=min(30, max(5, len(records))),
            color=th["primary"], edgecolor="black", linewidth=0.5, alpha=0.85)
    mean_gc = float(records["gc_percent"].mean())
    ax.axvline(mean_gc, color=th["secondary"], ls="--", lw=1.5,
               label=f"mean = {mean_gc:.2f}%")
    ax.set_xlabel("GC content (%)")
    ax.set_ylabel("Number of records")
    ax.set_title("GC distribution across records")
    ax.legend()

    ax = axes[1, 0]
    L = np.sort(records["length_bp"].to_numpy())[::-1]
    ax.plot(np.arange(1, len(L) + 1), L, marker="o" if len(L) < 40 else None,
            color=th["primary"], lw=1.6, ms=3)
    ax.set_yscale("log" if L.max() / max(L.min(), 1) > 100 else "linear")
    ax.set_xlabel("Record rank (longest first)")
    ax.set_ylabel("Length (bp)")
    ax.set_title("Record length profile")

    ax = axes[1, 1]
    if "entropy_bits" in records:
        ax.scatter(records["gc_percent"], records["entropy_bits"], s=22,
                   color=th["primary"], edgecolor="black", linewidth=0.3, alpha=0.85)
        ax.axhline(2.0, color="#888888", ls=":", lw=1.2, label="maximum (2 bits)")
        ax.set_xlabel("GC content (%)")
        ax.set_ylabel("Shannon entropy (bits)")
        ax.set_title("Sequence complexity")
        ax.legend()
    else:
        gc.blank_panel(ax, "Entropy not computed")
    return _finish(fig)


def fig_skew_and_ori(window_df: pd.DataFrame, ori_ter: Dict, record_name: str = "",
                     theme: str = "Ocean"):
    """GC/AT skew and cumulative skew with predicted ori/ter marked."""
    if window_df is None or window_df.empty:
        return _blank("Strand skew", "No windows to display")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, axes = plt.subplots(2, 1, figsize=(11, 6.4), sharex=True)
    x = window_df["midpoint"] / 1000.0

    ax = axes[0]
    ax.plot(x, window_df["GC_skew"], lw=0.9, color=th["primary"], label="GC skew")
    ax.plot(x, window_df["AT_skew"], lw=0.9, color=th["secondary"], alpha=0.75, label="AT skew")
    ax.axhline(0, color="#666666", lw=0.8)
    ax.set_ylabel("Skew per window")
    ax.set_title(f"Strand asymmetry{(' - ' + record_name) if record_name else ''}")
    ax.legend(ncol=2, loc="upper right")

    ax = axes[1]
    ax.plot(x, window_df["cumulative_GC_skew"], lw=1.8, color=th["primary"],
            label="cumulative GC skew")
    conf = str(ori_ter.get("ori_ter_confidence", ""))
    trustworthy = conf.startswith("clear")
    for key, colour, label in [("predicted_origin_bp", "#1a9850", "predicted origin"),
                               ("predicted_terminus_bp", "#d73027", "predicted terminus")]:
        v = ori_ter.get(key)
        if v is not None:
            ax.axvline(v / 1000.0, color=colour, ls="--" if trustworthy else ":",
                       lw=1.6, label=f"{label} ~{v:,} bp")
    ax.set_xlabel("Genome position (kb)")
    ax.set_ylabel("Cumulative GC skew")
    ax.legend(loc="best")
    # The honesty annotation lives inside the figure, so it survives being
    # lifted into a slide deck without its caption.
    ax.annotate(
        "Ori/ter are PREDICTED from cumulative GC skew (Grigoriev 1998), not measured."
        + ("" if trustworthy else "  Signal is weak here - treat as unreliable."),
        xy=(0.005, -0.30), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_dinucleotide_oe(df: pd.DataFrame, theme: str = "Ocean"):
    if df is None or df.empty:
        return _blank("Dinucleotide relative abundance", "No data")
    fig, ax = plt.subplots(figsize=(9, 4.2))
    colours = ["#c0392b" if m else "#4C72B0" for m in df["marked_deviation"]]
    ax.bar(df["dinucleotide"], df["rho"], color=colours, edgecolor="black", linewidth=0.5)
    ax.axhline(1.0, color="#333333", lw=1.0)
    ax.axhspan(0.78, 1.23, color="#999999", alpha=0.14,
               label="Karlin |rho-1| <= 0.23 (unremarkable)")
    ax.set_ylabel(r"$\rho$ = observed / expected")
    ax.set_xlabel("Dinucleotide")
    ax.set_title("Dinucleotide relative abundance (genomic signature)")
    ax.legend(loc="upper right")
    ax.annotate("Red bars mark |rho - 1| > 0.23 (Karlin & Burge 1995).",
                xy=(0.005, -0.22), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


# ----------------------------------------------------------------------
# Codon usage
# ----------------------------------------------------------------------

def fig_rscu_heatmap(usage: pd.DataFrame):
    if usage is None or usage.empty:
        return _blank("RSCU", "No codon usage")
    d = usage[(usage["amino_acid_1"] != "*") & usage["RSCU"].notna()].copy()
    if d.empty:
        return _blank("RSCU", "No sense codons")
    aas = sorted(d["amino_acid_1"].unique())
    maxfam = int(d.groupby("amino_acid_1").size().max())
    M = np.full((len(aas), maxfam), np.nan)
    labels = np.full((len(aas), maxfam), "", dtype=object)
    for i, aa in enumerate(aas):
        sub = d[d["amino_acid_1"] == aa].sort_values("codon").reset_index(drop=True)
        for j, r in sub.iterrows():
            M[i, j] = r["RSCU"]
            labels[i, j] = f"{r['codon']}\n{r['RSCU']:.2f}"
    fig, ax = plt.subplots(figsize=(1.15 * maxfam + 3.2, 0.46 * len(aas) + 2.2))
    im = ax.imshow(M, cmap=gc.RSCU_CMAP, aspect="auto", vmin=0,
                   vmax=float(np.nanmax(M)) if np.isfinite(M).any() else 1)
    for i in range(len(aas)):
        for j in range(maxfam):
            if labels[i, j]:
                v = M[i, j]
                tc = "white" if v > np.nanmax(M) * 0.6 else "#1a1a1a"
                ax.text(j, i, labels[i, j], ha="center", va="center", fontsize=6.8, color=tc)
    ax.set_yticks(range(len(aas)))
    ax.set_yticklabels([f"{a} ({gc.AA_THREE_LETTER.get(a,a)})" for a in aas])
    ax.set_xticks(range(maxfam))
    ax.set_xticklabels([f"codon {i+1}" for i in range(maxfam)])
    ax.set_title("Relative synonymous codon usage (RSCU)")
    ax.grid(False)
    cb = fig.colorbar(im, ax=ax, fraction=0.025, pad=0.02)
    cb.set_label("RSCU  (1.0 = no bias)")
    return _finish(fig)


def fig_codon_bar(usage: pd.DataFrame, theme: str = "Ocean"):
    if usage is None or usage.empty:
        return _blank("Codon usage", "No data")
    d = usage[usage["amino_acid_1"] != "*"].sort_values(["amino_acid_1", "codon"])
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, ax = plt.subplots(figsize=(13, 4.4))
    aas = list(dict.fromkeys(d["amino_acid_1"]))
    cmap = plt.get_cmap("tab20")
    colour = {aa: cmap(i % 20) for i, aa in enumerate(aas)}
    ax.bar(range(len(d)), d["frequency_per_1000"],
           color=[colour[a] for a in d["amino_acid_1"]], edgecolor="black", linewidth=0.3)
    ax.set_xticks(range(len(d)))
    ax.set_xticklabels(d["codon"], rotation=90, fontsize=5.6, family="monospace")
    ax.set_ylabel("Frequency (per 1000 codons)")
    ax.set_title("Genome-wide codon usage")
    ax.margins(x=0.005)
    return _finish(fig)


def fig_enc_plot(per_gene: pd.DataFrame, theme: str = "Ocean"):
    """Wright's ENC vs GC3s with the mutation-drift expectation curve."""
    if per_gene is None or per_gene.empty:
        return _blank("ENC plot", "No genes passed the length filter")
    d = per_gene.dropna(subset=["ENC", "GC3s"])
    if d.empty:
        return _blank("ENC plot", "No genes with computable ENC")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, ax = plt.subplots(figsize=(7.2, 5.6))
    x = d["GC3s"].to_numpy() / 100.0
    ax.scatter(d["GC3s"], d["ENC"], s=16, alpha=0.6, color=th["primary"],
               edgecolor="none", label=f"genes (n = {len(d):,})")
    xs = np.linspace(0.005, 0.995, 400)
    ax.plot(xs * 100, gc.wright_expected_enc(xs), color="#c0392b", lw=2.0,
            label="Wright expectation (mutation drift only)")
    exp = gc.wright_expected_enc(x)
    below = int(np.sum(d["ENC"].to_numpy() < exp - 0.10 * exp))
    ax.set_xlabel("GC3s (%)  - GC at synonymous third positions")
    ax.set_ylabel("ENC  (effective number of codons)")
    ax.set_xlim(0, 100)
    ax.set_ylim(18, 64)
    ax.set_title("ENC plot (Wright 1990)")
    ax.legend(loc="lower center")
    ax.annotate(
        f"{below:,}/{len(d):,} genes lie >10% below the curve, i.e. show codon bias "
        f"beyond what GC mutation pressure alone explains.",
        xy=(0.005, -0.155), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_neutrality_plot(per_gene: pd.DataFrame, reg: Dict, theme: str = "Ocean"):
    if per_gene is None or per_gene.empty:
        return _blank("Neutrality plot", "No genes")
    d = per_gene.dropna(subset=["GC3", "GC12"])
    if len(d) < 3:
        return _blank("Neutrality plot", "Need at least 3 genes")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, ax = plt.subplots(figsize=(7.2, 5.6))
    ax.scatter(d["GC3"], d["GC12"], s=16, alpha=0.6, color=th["primary"], edgecolor="none")
    xs = np.linspace(d["GC3"].min(), d["GC3"].max(), 100)
    if np.isfinite(reg.get("slope", np.nan)):
        ax.plot(xs, reg["slope"] * xs + reg["intercept"], color="#c0392b", lw=2.0,
                label=(f"GC12 = {reg['slope']:.3f}·GC3 + {reg['intercept']:.2f}\n"
                       f"r² = {reg['r_squared']:.3f}, n = {reg['n_genes']:,}"))
    ax.plot(xs, xs, color="#666666", ls="--", lw=1.2, label="slope = 1 (pure mutation pressure)")
    ax.set_xlabel("GC3 (%)")
    ax.set_ylabel("GC12 (%)")
    ax.set_title("Neutrality plot (Sueoka 1988)")
    ax.legend(loc="best")
    s = reg.get("slope", np.nan)
    if np.isfinite(s):
        interp = ("mutation pressure dominates" if s > 0.5 else
                  "selection dominates codon usage" if s < 0.2 else
                  "mixed mutation and selection")
        ax.annotate(f"Slope {s:.3f}: {interp}. Slope approximates the neutral "
                    f"(mutation-driven) fraction of GC variation.",
                    xy=(0.005, -0.155), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_pr2_plot(per_gene: pd.DataFrame, theme: str = "Ocean"):
    if per_gene is None or per_gene.empty:
        return _blank("PR2 plot", "No genes")
    d = per_gene.dropna(subset=["PR2_G3_over_GC3", "PR2_A3_over_AT3"])
    if d.empty:
        return _blank("PR2 plot", "No four-fold degenerate codons found")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, ax = plt.subplots(figsize=(6.4, 6.2))
    ax.scatter(d["PR2_G3_over_GC3"], d["PR2_A3_over_AT3"], s=16, alpha=0.6,
               color=th["primary"], edgecolor="none", label=f"genes (n = {len(d):,})")
    ax.axhline(0.5, color="#666666", lw=1.0)
    ax.axvline(0.5, color="#666666", lw=1.0)
    ax.plot(0.5, 0.5, marker="*", ms=17, color="#c0392b", ls="none",
            label="PR2 centre (no bias)")
    mx, my = float(d["PR2_G3_over_GC3"].mean()), float(d["PR2_A3_over_AT3"].mean())
    ax.plot(mx, my, marker="D", ms=8, color="#1a9850", ls="none",
            label=f"observed mean ({mx:.3f}, {my:.3f})")
    ax.set_xlim(0, 1); ax.set_ylim(0, 1); ax.set_aspect("equal")
    ax.set_xlabel("G3 / (G3 + C3)")
    ax.set_ylabel("A3 / (A3 + T3)")
    ax.set_title("PR2 bias plot, four-fold degenerate sites (Sueoka 1995)")
    ax.legend(loc="upper right", fontsize=7.5)
    ax.annotate("Displacement from the centre indicates strand-asymmetric mutation "
                "or selection at synonymous sites.",
                xy=(0.005, -0.13), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_amino_acid_usage(df: pd.DataFrame, theme: str = "Ocean"):
    if df is None or df.empty:
        return _blank("Amino acid usage", "No data")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    d = df.sort_values("frequency_percent", ascending=False)
    fig, ax = plt.subplots(figsize=(9, 4.2))
    ax.bar(d["amino_acid_3"], d["frequency_percent"], color=th["primary"],
           edgecolor="black", linewidth=0.4)
    ax.set_ylabel("Frequency (% of residues)")
    ax.set_xlabel("Amino acid")
    ax.set_title("Genome-wide amino acid usage")
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
    return _finish(fig)


# ----------------------------------------------------------------------
# Assembly / features
# ----------------------------------------------------------------------

def fig_assembly_curve(lengths: Sequence[int], stats: Dict, theme: str = "Ocean"):
    """Cumulative assembly (Nx) curve with N50/N75/N90 marked."""
    if not len(lengths):
        return _blank("Assembly curve", "No records")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    L = np.sort(np.asarray(lengths, dtype=float))[::-1]
    cum = np.cumsum(L)
    pct = 100.0 * cum / cum[-1]
    fig, ax = plt.subplots(figsize=(7.6, 5.0))
    ax.step(pct, L, where="post", lw=2.0, color=th["primary"])
    for key, colour in [("N50_bp", "#1a9850"), ("N75_bp", "#E69F00"), ("N90_bp", "#d73027")]:
        v = stats.get(key)
        if v:
            ax.axhline(v, color=colour, ls="--", lw=1.3, label=f"{key.replace('_bp','')} = {v:,} bp")
    ax.set_yscale("log" if L.max() / max(L.min(), 1) > 100 else "linear")
    ax.set_xlabel("Cumulative assembly length (%)")
    ax.set_ylabel("Record length (bp)")
    ax.set_title("Assembly contiguity (Nx curve)")
    ax.legend(loc="upper right")
    if stats.get("auN"):
        ax.annotate(f"auN (area under Nx) = {stats['auN']:,.0f} bp - a single-value "
                    f"contiguity summary robust to the N50 threshold artefact.",
                    xy=(0.005, -0.145), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_length_hist(df: pd.DataFrame, col: str, title: str, xlabel: str, theme: str = "Ocean"):
    if df is None or df.empty or col not in df:
        return _blank(title, "No data")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    v = pd.to_numeric(df[col], errors="coerce").dropna()
    if v.empty:
        return _blank(title, "No numeric data")
    fig, ax = plt.subplots(figsize=(7.6, 4.4))
    ax.hist(v, bins=min(60, max(6, int(np.sqrt(len(v))))), color=th["primary"],
            edgecolor="black", linewidth=0.4, alpha=0.88)
    ax.axvline(v.median(), color=th["secondary"], ls="--", lw=1.5,
               label=f"median = {v.median():,.0f}")
    ax.set_xlabel(xlabel); ax.set_ylabel("Count"); ax.set_title(title); ax.legend()
    return _finish(fig)


def fig_feature_map(features: pd.DataFrame, seq_len: int, record_name: str = "",
                    palette: str = "Colourblind safe (Okabe-Ito)", max_features: int = 4000):
    """Linear feature map, strand-separated."""
    if features is None or features.empty:
        return _blank("Feature map", "No features to display", figsize=(12, 3))
    pal = gc.PALETTES.get(palette, gc.PALETTES["Colourblind safe (Okabe-Ito)"])
    d = features.copy()
    if len(d) > max_features:
        d = d.reindex(d["end"].astype(int).sub(d["start"].astype(int)).abs()
                      .sort_values(ascending=False).index[:max_features])
    fig, ax = plt.subplots(figsize=(13, 3.4))
    ax.axhline(0, color="#999999", lw=1.0, zorder=1)
    seen = {}
    for _, r in d.iterrows():
        t = str(r.get("type", "feature"))
        col = pal.get(t, pal["default"])
        seen[t] = col
        s, e = int(r["start"]), int(r["end"])
        strand = int(r.get("strand", 0) or 0)
        y = 0.16 if strand >= 0 else -0.16 - 0.30
        ax.add_patch(plt.Rectangle((s, y), max(e - s, max(1, seq_len // 4000)), 0.30,
                                   facecolor=col, edgecolor="none", alpha=0.9, zorder=2))
    ax.set_xlim(0, seq_len)
    ax.set_ylim(-0.75, 0.65)
    ax.set_yticks([0.31, -0.31])
    ax.set_yticklabels(["+ strand", "− strand"])
    ax.set_xlabel("Position (bp)")
    ax.set_title(f"Feature map{(' - ' + record_name) if record_name else ''}"
                 f"  ({len(d):,} features shown)")
    ax.grid(axis="x")
    if seen:
        ax.legend(handles=[Patch(facecolor=c, label=t) for t, c in sorted(seen.items())],
                  loc="upper center", bbox_to_anchor=(0.5, -0.30), ncol=min(8, len(seen)),
                  fontsize=7)
    return _finish(fig)


# ----------------------------------------------------------------------
# Comparative / pan-genome
# ----------------------------------------------------------------------

def fig_distance_heatmap(mat: pd.DataFrame, title: str, cbar_label: str,
                         cmap: str = "viridis", fmt: str = "{:.3f}"):
    if mat is None or mat.empty:
        return _blank(title, "No matrix")
    n = len(mat)
    fig, ax = plt.subplots(figsize=(max(5.0, 0.68 * n + 3.2), max(4.2, 0.58 * n + 2.6)))
    im = ax.imshow(mat.to_numpy(dtype=float), cmap=cmap, aspect="auto")
    ax.set_xticks(range(n)); ax.set_yticks(range(n))
    ax.set_xticklabels(mat.columns, rotation=45, ha="right", fontsize=7.5)
    ax.set_yticklabels(mat.index, fontsize=7.5)
    if n <= 14:
        A = mat.to_numpy(dtype=float)
        lo, hi = np.nanmin(A), np.nanmax(A)
        for i in range(n):
            for j in range(n):
                v = A[i, j]
                rel = (v - lo) / (hi - lo) if hi > lo else 0.5
                ax.text(j, i, fmt.format(v), ha="center", va="center", fontsize=6.6,
                        color="white" if rel > 0.55 else "#1a1a1a")
    ax.set_title(title)
    ax.grid(False)
    cb = fig.colorbar(im, ax=ax, fraction=0.035, pad=0.02)
    cb.set_label(cbar_label)
    return _finish(fig)


def fig_pangenome_curves(acc: pd.DataFrame, heaps: Dict, theme: str = "Ocean"):
    """Pan/core accumulation curves with the Heaps' law fit overlaid."""
    if acc is None or acc.empty:
        return _blank("Pan-genome accumulation", "No data")
    th = gc.THEMES.get(theme, gc.THEMES["Ocean"])
    fig, ax = plt.subplots(figsize=(7.8, 5.2))
    x = acc["n_genomes"]
    ax.errorbar(x, acc["pan_mean"], yerr=acc["pan_sd"], marker="o", ms=4.5, lw=1.8,
                capsize=3, color=th["primary"], label="pan-genome")
    ax.errorbar(x, acc["core_mean"], yerr=acc["core_sd"], marker="s", ms=4.5, lw=1.8,
                capsize=3, color=th["secondary"], label="core genome")
    g = heaps.get("gamma", np.nan)
    if np.isfinite(g) and np.isfinite(heaps.get("kappa", np.nan)):
        xs = np.linspace(1, x.max(), 200)
        ax.plot(xs, heaps["kappa"] * xs ** g, ls="--", lw=1.6, color="#c0392b",
                label=f"Heaps fit: n = {heaps['kappa']:.0f}·N^{g:.3f}")
    ax.set_xlabel("Number of genomes sampled")
    ax.set_ylabel("Number of gene clusters")
    ax.set_title("Pan-genome and core-genome accumulation")
    ax.legend(loc="center right")
    note = heaps.get("interpretation", "")
    if note:
        ax.annotate(f"Heaps' law (Tettelin 2008): {note}",
                    xy=(0.005, -0.145), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)


def fig_pangenome_pie(counts: Dict[str, int], theme: str = "Ocean"):
    labels = [k for k, v in counts.items() if v > 0]
    vals = [counts[k] for k in labels]
    if not vals:
        return _blank("Pan-genome partition", "No clusters")
    fig, ax = plt.subplots(figsize=(6.6, 5.2))
    cols = {"Core": "#2166ac", "Soft-core": "#67a9cf", "Shell": "#fdae61", "Cloud": "#d73027"}
    total = sum(vals)
    w, *_ = ax.pie(vals, labels=None, colors=[cols.get(l, "#999999") for l in labels],
                   autopct=lambda p: f"{p:.1f}%\n({int(round(p*total/100)):,})",
                   textprops=dict(fontsize=8, color="white"), startangle=90,
                   wedgeprops=dict(edgecolor="white", linewidth=1.6))
    ax.legend(w, [f"{l} (n = {counts[l]:,})" for l in labels],
              loc="center left", bbox_to_anchor=(1.0, 0.5))
    ax.set_title(f"Pan-genome partition  (total {total:,} clusters)")
    return _finish(fig)


def fig_presence_absence(presence: np.ndarray, genome_names: List[str],
                         max_clusters: int = 3000):
    if presence is None or presence.size == 0:
        return _blank("Presence/absence", "No matrix")
    M = presence
    if M.shape[0] > max_clusters:
        # Order by prevalence, then evenly subsample so the core/shell/cloud
        # structure is preserved rather than truncated to the core block.
        order = np.argsort(-M.sum(axis=1))
        M = M[order][np.linspace(0, len(order) - 1, max_clusters).astype(int)]
    else:
        M = M[np.argsort(-M.sum(axis=1))]
    fig, ax = plt.subplots(figsize=(max(5.5, 0.42 * len(genome_names) + 3.0), 6.2))
    ax.imshow(M, cmap="Blues", aspect="auto", interpolation="nearest", vmin=0, vmax=1)
    ax.set_xticks(range(len(genome_names)))
    ax.set_xticklabels(genome_names, rotation=45, ha="right", fontsize=7.5)
    ax.set_ylabel(f"Gene clusters (n = {presence.shape[0]:,}, sorted by prevalence)")
    ax.set_title("Gene presence / absence")
    ax.grid(False)
    if presence.shape[0] > max_clusters:
        ax.annotate(f"Showing {max_clusters:,} of {presence.shape[0]:,} clusters "
                    f"(evenly sampled across prevalence). Full matrix is in the CSV export.",
                    xy=(0.005, -0.12), xycoords="axes fraction", **_ANNOT_KW)
    return _finish(fig)