File size: 5,153 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
"""
genome_figures_extra.py

High-impact-journal style figures:
  - Circular genome map with a GC content ring and a GC skew ring, the classic
    CGView-style overview that genome papers use.
  - Refined nucleotide composition donut.

Uses only numpy, pandas, and matplotlib.
"""

import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap


PALETTE = {
    "primary": "#2c5f8a", "secondary": "#c45a3b", "accent": "#3b8c6e",
    "warm": "#d9a23b", "purple": "#7a5ba6", "neutral": "#6b6b6b",
    "light": "#d9e2ec",
}


def fig_nucleotide_donut(genome_df):
    """Refined donut of A, T, G, C, N proportions."""
    totals = genome_df[["A", "T", "G", "C", "N"]].sum()
    values = totals.values.astype(float)
    labels = list(totals.index)
    colors = ["#2c5f8a", "#5a8fc4", "#c45a3b", "#d9a23b", "#9aa0a6"]

    fig, ax = plt.subplots(figsize=(6, 6))
    wedges, _ = ax.pie(
        values, colors=colors, startangle=90, counterclock=False,
        wedgeprops={"width": 0.42, "edgecolor": "white", "linewidth": 2},
    )
    total = values.sum()
    legend_labels = [f"{l}  {v / total * 100:.1f}%" for l, v in zip(labels, values)]
    ax.legend(wedges, legend_labels, loc="center", frameon=False, fontsize=11)
    ax.set_title("Genome nucleotide composition", fontsize=13, weight="bold")
    return fig


def _smooth(values, k=3):
    if k <= 1 or len(values) < k:
        return values
    kernel = np.ones(k) / k
    return np.convolve(values, kernel, mode="same")


def fig_circular_genome(window_df, isolate, genome_gc_mean=None, title=None):
    """Circular genome map for the longest contig of one isolate.

    Outer ring: GC content deviation from the mean (windowed).
    Inner ring: GC skew (windowed), green for positive, purple for negative.
    """
    sub = window_df[window_df["input_file"] == isolate]
    if sub.empty:
        return None
    longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0]
    sub = sub[sub["contig_id"] == longest].sort_values("midpoint").copy()
    if len(sub) < 6:
        return None

    n = len(sub)
    theta = np.linspace(0, 2 * np.pi, n, endpoint=False)
    width = 2 * np.pi / n

    gc = sub["GC_percent"].values.astype(float)
    gc_mean = genome_gc_mean if genome_gc_mean is not None else float(np.mean(gc))
    gc_dev = _smooth(gc - gc_mean)
    skew = _smooth(sub["GC_skew"].values.astype(float))

    fig = plt.figure(figsize=(7.6, 7.6))
    ax = fig.add_subplot(111, projection="polar")
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    ax.axis("off")

    # Ring radii
    gc_inner, gc_outer = 2.4, 3.4
    skew_inner, skew_outer = 1.3, 2.2

    # GC content ring: bars above mean in blue, below mean in orange
    max_dev = max(1e-6, np.max(np.abs(gc_dev)))
    for t, d in zip(theta, gc_dev):
        h = (abs(d) / max_dev) * (gc_outer - gc_inner) / 2
        base = (gc_inner + gc_outer) / 2
        if d >= 0:
            ax.bar(t, h, width=width, bottom=base, color=PALETTE["primary"],
                   edgecolor="none", alpha=0.9)
        else:
            ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["warm"],
                   edgecolor="none", alpha=0.9)

    # GC skew ring
    max_skew = max(1e-6, np.max(np.abs(skew)))
    for t, s in zip(theta, skew):
        h = (abs(s) / max_skew) * (skew_outer - skew_inner) / 2
        base = (skew_inner + skew_outer) / 2
        if s >= 0:
            ax.bar(t, h, width=width, bottom=base, color=PALETTE["accent"],
                   edgecolor="none", alpha=0.9)
        else:
            ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["purple"],
                   edgecolor="none", alpha=0.9)

    # Guide circles
    for r in [(gc_inner + gc_outer) / 2, (skew_inner + skew_outer) / 2]:
        ax.plot(np.linspace(0, 2 * np.pi, 200), [r] * 200,
                color="#bbbbbb", linewidth=0.6, linestyle="--")

    ax.set_ylim(0, gc_outer + 0.3)

    # Position ticks every quarter, labelled in kb
    contig_len = int(sub["end"].max())
    for frac in [0, 0.25, 0.5, 0.75]:
        ang = frac * 2 * np.pi
        ax.plot([ang, ang], [0.9, gc_outer + 0.1], color="#dddddd", linewidth=0.6)
        ax.text(ang, gc_outer + 0.25, f"{int(contig_len * frac / 1000)} kb",
                ha="center", va="center", fontsize=8, color="#555555")

    ax.text(0, 0, f"{isolate}\n{contig_len/1e6:.2f} Mb\nGC {gc_mean:.1f}%",
            ha="center", va="center", fontsize=10, weight="bold")

    fig.suptitle(title or f"Circular genome map: {longest}",
                 fontsize=13, weight="bold", y=0.98)

    # Legend
    from matplotlib.patches import Patch
    handles = [
        Patch(color=PALETTE["primary"], label="GC above mean"),
        Patch(color=PALETTE["warm"], label="GC below mean"),
        Patch(color=PALETTE["accent"], label="GC skew +"),
        Patch(color=PALETTE["purple"], label="GC skew -"),
    ]
    ax.legend(handles=handles, loc="upper right", bbox_to_anchor=(1.18, 1.12),
              frameon=False, fontsize=8.5)
    return fig