alg-painter 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- alg_painter/__init__.py +3 -0
- alg_painter/alg_painter.py +137 -0
- alg_painter/alg_plotter_v1.py +533 -0
- alg_painter/alg_plotter_v2.py +277 -0
- alg_painter/cli.py +264 -0
- alg_painter/fonts/OpenSans-Regular.ttf +0 -0
- alg_painter/generics.py +8 -0
- alg_painter/ncbi_api.py +55 -0
- alg_painter/plotter_colours.py +137 -0
- alg_painter-0.1.0.dist-info/METADATA +41 -0
- alg_painter-0.1.0.dist-info/RECORD +13 -0
- alg_painter-0.1.0.dist-info/WHEEL +4 -0
- alg_painter-0.1.0.dist-info/entry_points.txt +3 -0
alg_painter/__init__.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import logging
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from alg_painter.generics import write_tsv
|
|
7
|
+
from alg_painter.ncbi_api import (
|
|
8
|
+
chrom_lengths_with_unloc,
|
|
9
|
+
fetch_sequence_report,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def parse_reference_map(ref_path: Path) -> dict[str, str]:
|
|
16
|
+
"""
|
|
17
|
+
Return {BUSCO-ID → ALG element} from the reference full_table.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
# IF LEPIDOPTERAN... SHOULD THIS SIMPLY BE ALG_Z, ALG_1
|
|
21
|
+
alg_set = {"MZ"} | {f"M{i}" for i in range(1, 32)}
|
|
22
|
+
ref_map: dict[str, str] = {}
|
|
23
|
+
with ref_path.open(newline="") as reference_file:
|
|
24
|
+
reader = csv.reader(reference_file, delimiter="\t")
|
|
25
|
+
for row in reader:
|
|
26
|
+
if (
|
|
27
|
+
not row
|
|
28
|
+
or len(row) < 3
|
|
29
|
+
or row[0].startswith("#")
|
|
30
|
+
or row[0].lower().startswith("busco")
|
|
31
|
+
):
|
|
32
|
+
continue
|
|
33
|
+
alg_unit = row[2].upper().strip()
|
|
34
|
+
if alg_unit in alg_set:
|
|
35
|
+
ref_map[row[0]] = alg_unit
|
|
36
|
+
return ref_map
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_busco_table(path: Path) -> tuple[list[tuple], list[str]]:
|
|
40
|
+
"""
|
|
41
|
+
Return list of (busco_id, chr, start, stop) tuples and sorted unique chr list.
|
|
42
|
+
This does not filter out any duplicates
|
|
43
|
+
"""
|
|
44
|
+
tbl: list[tuple] = []
|
|
45
|
+
chroms: set[str] = set()
|
|
46
|
+
keep_status = {"Complete", "Duplicated"}
|
|
47
|
+
|
|
48
|
+
with path.open(newline="") as fh:
|
|
49
|
+
reader = csv.reader(fh, delimiter="\t")
|
|
50
|
+
for row in reader:
|
|
51
|
+
if not row or row[0].startswith("#") or len(row) < 5:
|
|
52
|
+
continue
|
|
53
|
+
bid, status, chrom, start, stop = row[:5]
|
|
54
|
+
if status not in keep_status:
|
|
55
|
+
continue
|
|
56
|
+
try:
|
|
57
|
+
start_coord, end_coord = int(start), int(stop)
|
|
58
|
+
except ValueError:
|
|
59
|
+
continue
|
|
60
|
+
tbl.append((bid, chrom, start_coord, end_coord))
|
|
61
|
+
chroms.add(chrom)
|
|
62
|
+
return tbl, sorted(chroms)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def build_location_rows(
|
|
66
|
+
reference_map: dict[str, str], query_table: list[tuple]
|
|
67
|
+
) -> list[str]:
|
|
68
|
+
rows = ["buscoID\tquery_chr\tposition\tassigned_chr\tstatus"]
|
|
69
|
+
for busco_id, query_chromosome, start, end in query_table:
|
|
70
|
+
position = (start + end) / 2
|
|
71
|
+
assigned = reference_map.get(busco_id, "NA")
|
|
72
|
+
rows.append(
|
|
73
|
+
f"{busco_id}\t{query_chromosome}\t{position}\t{assigned}\t{assigned}"
|
|
74
|
+
)
|
|
75
|
+
return rows
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def painting_main(arguments):
|
|
79
|
+
logger.info(f"Running PAINTER with: {arguments}")
|
|
80
|
+
|
|
81
|
+
prefix_location = Path(arguments.prefix)
|
|
82
|
+
logging.info(f"Making sure output dir exists at: {prefix_location}")
|
|
83
|
+
prefix_location.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
|
|
85
|
+
output_file_dict = {
|
|
86
|
+
"all_locs": Path(
|
|
87
|
+
f"{prefix_location}/{arguments.prefix}_all_locations.tsv"
|
|
88
|
+
),
|
|
89
|
+
"chrom_lengths": Path(
|
|
90
|
+
f"{prefix_location}/{arguments.prefix}_chrom_lengths.tsv"
|
|
91
|
+
),
|
|
92
|
+
"summary": Path(f"{prefix_location}/{arguments.prefix}_summary.tsv"),
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
# Parse the BUSCO tables into the needed formats
|
|
96
|
+
reference_map = parse_reference_map(arguments.alg_table)
|
|
97
|
+
|
|
98
|
+
query_table, query_chromosomes = parse_busco_table(arguments.query_table)
|
|
99
|
+
|
|
100
|
+
# Build the rows of ALL buscos
|
|
101
|
+
all_busco_data = build_location_rows(reference_map, query_table)
|
|
102
|
+
|
|
103
|
+
# If ACCESSION is given then call the NCBI API to get chromosome lenths
|
|
104
|
+
if arguments.accession:
|
|
105
|
+
logger.info(
|
|
106
|
+
f"[Painter] Fetching sequence report for accession: {arguments.accession}"
|
|
107
|
+
)
|
|
108
|
+
seq_report = fetch_sequence_report(arguments.accession)
|
|
109
|
+
pairs = chrom_lengths_with_unloc(seq_report)
|
|
110
|
+
length_lines = ["Chrom\tLength_Mb"] + [
|
|
111
|
+
f"{chromosome}\t{basepairs / 1e6:.3f}"
|
|
112
|
+
for chromosome, basepairs in pairs
|
|
113
|
+
]
|
|
114
|
+
write_tsv(length_lines, output_file_dict["chrom_lengths"])
|
|
115
|
+
chrom_order = [c for c, _ in pairs]
|
|
116
|
+
else:
|
|
117
|
+
chrom_order = query_chromosomes.copy()
|
|
118
|
+
|
|
119
|
+
query_chroms_set = {chrom for _, chrom, _, _ in query_table}
|
|
120
|
+
missing = [c for c in chrom_order if c not in query_chroms_set]
|
|
121
|
+
for c in missing:
|
|
122
|
+
all_busco_data.append(f"NA\t{c}\tNA\tNA\tNA")
|
|
123
|
+
|
|
124
|
+
logger.info(f"[Painter] Writing tsv to: {output_file_dict['all_locs']}")
|
|
125
|
+
write_tsv(all_busco_data, output_file_dict["all_locs"])
|
|
126
|
+
|
|
127
|
+
# Optional summary generation
|
|
128
|
+
if arguments.write_summary:
|
|
129
|
+
logger.info(
|
|
130
|
+
f"[Painter] Writing summary to: {output_file_dict['summary']}"
|
|
131
|
+
)
|
|
132
|
+
counts = Counter(chrom for _, chrom, _, _ in query_table)
|
|
133
|
+
counts.update({c: 0 for c in missing})
|
|
134
|
+
sum_lines = ["query_chr\tbusco_hits"] + [
|
|
135
|
+
f"{c}\t{counts[c]}" for c in chrom_order
|
|
136
|
+
]
|
|
137
|
+
write_tsv(sum_lines, output_file_dict["summary"])
|
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
plotter_v1.py — Python conversion of plot_buscopainter.R
|
|
4
|
+
|
|
5
|
+
CONVERSION WAS AUTOMATICALLY GENERATED BY CLAUDE OPUS 4.6
|
|
6
|
+
AND TESTED AGAINST KNOWN OUTPUT
|
|
7
|
+
|
|
8
|
+
Original R script by : Charlotte Wright
|
|
9
|
+
Original Repo : https://github.com/charlottewright/lep_busco_painter/
|
|
10
|
+
|
|
11
|
+
Converted by : AI assistant
|
|
12
|
+
Date of conversion : 2026-04-14
|
|
13
|
+
|
|
14
|
+
Modified by : Damon-Lee B Pointon
|
|
15
|
+
Modified on : 2026-04-14
|
|
16
|
+
|
|
17
|
+
Description:
|
|
18
|
+
This script generates a plot showing locations of putative
|
|
19
|
+
merian elements (or species-level orthologs) in a genomic assembly.
|
|
20
|
+
It is port of the R/ggplot2 version to Python/matplotlib.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import logging
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
import matplotlib.colors as mcolors
|
|
28
|
+
import matplotlib.patches as mpatches
|
|
29
|
+
import matplotlib.pyplot as plt
|
|
30
|
+
import pandas as pd
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
# Merian element ordering (shared across multiple functions)
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
MERIAN_ORDER = [
|
|
38
|
+
"MZ",
|
|
39
|
+
*[f"M{i}" for i in range(1, 32)],
|
|
40
|
+
"self",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
# ---------------------------------------------------------------------------
|
|
44
|
+
# Colour helpers
|
|
45
|
+
# ---------------------------------------------------------------------------
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def hue_palette(n: int) -> list[str]:
|
|
49
|
+
"""
|
|
50
|
+
Replicate ggplot2's ``hue_pal()`` which generates *n* evenly-spaced
|
|
51
|
+
colours around the HCL colour wheel (approximated here with HSV).
|
|
52
|
+
"""
|
|
53
|
+
colours = []
|
|
54
|
+
for i in range(n):
|
|
55
|
+
hue = (i / n + 0.025) % 1.0 # slight offset matches ggplot2
|
|
56
|
+
colours.append(mcolors.hsv_to_rgb((hue, 0.65, 0.95)))
|
|
57
|
+
return colours
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def set_merian_colour_mapping(location_set: pd.DataFrame) -> dict:
|
|
61
|
+
"""
|
|
62
|
+
Build a mapping of Merian element → colour for elements that are
|
|
63
|
+
actually present in the data. Mirrors R's ``set_merian_colour_mapping``.
|
|
64
|
+
"""
|
|
65
|
+
colour_palette = hue_palette(32)
|
|
66
|
+
colour_palette.append("grey") # colour for "self"
|
|
67
|
+
|
|
68
|
+
status_merians = location_set["status"].unique().tolist()
|
|
69
|
+
mapping: dict = {}
|
|
70
|
+
for merian, colour in zip(MERIAN_ORDER, colour_palette):
|
|
71
|
+
if merian in status_merians:
|
|
72
|
+
mapping[merian] = colour
|
|
73
|
+
return mapping
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---------------------------------------------------------------------------
|
|
77
|
+
# Data loading & filtering
|
|
78
|
+
# ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def prepare_data(location_file: Path) -> pd.DataFrame:
|
|
82
|
+
"""Load a locations TSV and compute chromosome lengths from max position."""
|
|
83
|
+
locations = pd.read_csv(location_file, sep="\t")
|
|
84
|
+
|
|
85
|
+
# Remove rows where query_chr or assigned_chr contain ":"
|
|
86
|
+
locations = locations[~locations["query_chr"].str.contains(":", na=False)]
|
|
87
|
+
locations = locations[
|
|
88
|
+
~locations["assigned_chr"].str.contains(":", na=False)
|
|
89
|
+
]
|
|
90
|
+
|
|
91
|
+
# Compute length per query chromosome as max position
|
|
92
|
+
locations["length"] = locations.groupby("query_chr")["position"].transform(
|
|
93
|
+
"max"
|
|
94
|
+
)
|
|
95
|
+
locations["start"] = 0
|
|
96
|
+
|
|
97
|
+
return locations
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def prepare_data_with_index(
|
|
101
|
+
location_file: Path, index_file: Path
|
|
102
|
+
) -> pd.DataFrame:
|
|
103
|
+
"""Load locations TSV and merge with a genome index (.fai) for lengths."""
|
|
104
|
+
locations = pd.read_csv(location_file, sep="\t")
|
|
105
|
+
contig_lengths = pd.read_csv(
|
|
106
|
+
index_file,
|
|
107
|
+
sep="\t",
|
|
108
|
+
header=None,
|
|
109
|
+
names=["Seq", "length", "offset", "linebases", "linewidth"],
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
# Remove rows where query_chr or assigned_chr contain ":"
|
|
113
|
+
locations = locations[~locations["query_chr"].str.contains(":", na=False)]
|
|
114
|
+
locations = locations[
|
|
115
|
+
~locations["assigned_chr"].str.contains(":", na=False)
|
|
116
|
+
]
|
|
117
|
+
|
|
118
|
+
# Merge to get actual contig lengths
|
|
119
|
+
locations = locations.merge(
|
|
120
|
+
contig_lengths[["Seq", "length"]],
|
|
121
|
+
left_on="query_chr",
|
|
122
|
+
right_on="Seq",
|
|
123
|
+
how="left",
|
|
124
|
+
)
|
|
125
|
+
locations.drop(columns=["Seq"], inplace=True, errors="ignore")
|
|
126
|
+
locations["start"] = 0
|
|
127
|
+
|
|
128
|
+
return locations
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def filter_buscos(locations: pd.DataFrame, minimum: int = 3) -> pd.DataFrame:
|
|
132
|
+
"""Keep only chromosomes with at least *minimum* BUSCOs."""
|
|
133
|
+
filtered_locations = locations.copy()
|
|
134
|
+
filtered_locations["n_busco"] = filtered_locations.groupby("query_chr")[
|
|
135
|
+
"query_chr"
|
|
136
|
+
].transform("count")
|
|
137
|
+
return filtered_locations[filtered_locations["n_busco"] >= minimum]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------------------
|
|
141
|
+
# Shared plotting helpers
|
|
142
|
+
# ---------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _chromosome_order(df: pd.DataFrame) -> list[str]:
|
|
146
|
+
"""Return chromosomes sorted by length descending (unique)."""
|
|
147
|
+
chr_len = df[["query_chr", "length"]].drop_duplicates()
|
|
148
|
+
chr_len = chr_len.sort_values("length", ascending=False)
|
|
149
|
+
return chr_len["query_chr"].tolist()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _apply_busco_paint_theme(ax: plt.Axes) -> None:
|
|
153
|
+
"""Apply the ``busco_paint_theme`` styling to an axes."""
|
|
154
|
+
ax.set_facecolor("white")
|
|
155
|
+
ax.spines["top"].set_visible(False)
|
|
156
|
+
ax.spines["right"].set_visible(False)
|
|
157
|
+
ax.spines["left"].set_visible(False)
|
|
158
|
+
ax.tick_params(left=False, labelleft=True)
|
|
159
|
+
ax.xaxis.set_tick_params(labelsize=11)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _draw_chromosome_row(
|
|
163
|
+
ax: plt.Axes,
|
|
164
|
+
y: float,
|
|
165
|
+
start: float,
|
|
166
|
+
length: float,
|
|
167
|
+
busco_positions,
|
|
168
|
+
busco_colours,
|
|
169
|
+
bar_width: float,
|
|
170
|
+
bar_height: int,
|
|
171
|
+
):
|
|
172
|
+
"""
|
|
173
|
+
Draw one chromosome row: a white backbone + coloured BUSCO ticks.
|
|
174
|
+
"""
|
|
175
|
+
# Backbone rectangle
|
|
176
|
+
rect = mpatches.FancyBboxPatch(
|
|
177
|
+
(start, y),
|
|
178
|
+
length,
|
|
179
|
+
bar_height,
|
|
180
|
+
boxstyle="square,pad=0",
|
|
181
|
+
facecolor="white",
|
|
182
|
+
edgecolor="black",
|
|
183
|
+
linewidth=0.5,
|
|
184
|
+
)
|
|
185
|
+
ax.add_patch(rect)
|
|
186
|
+
|
|
187
|
+
# BUSCO markers
|
|
188
|
+
for pos, col in zip(busco_positions, busco_colours):
|
|
189
|
+
busco_rect = mpatches.FancyBboxPatch(
|
|
190
|
+
(pos - bar_width, y),
|
|
191
|
+
bar_width * 2,
|
|
192
|
+
bar_height,
|
|
193
|
+
boxstyle="square,pad=0",
|
|
194
|
+
facecolor=col,
|
|
195
|
+
edgecolor="none",
|
|
196
|
+
)
|
|
197
|
+
ax.add_patch(busco_rect)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---------------------------------------------------------------------------
|
|
201
|
+
# Core rendering function
|
|
202
|
+
# ---------------------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _render_chromosome_plot(
|
|
206
|
+
spp_df: pd.DataFrame,
|
|
207
|
+
colour_map: dict,
|
|
208
|
+
colour_column: str,
|
|
209
|
+
chr_order: list[str],
|
|
210
|
+
legend_title: str,
|
|
211
|
+
title: str,
|
|
212
|
+
karyotype: str,
|
|
213
|
+
bar_width: float,
|
|
214
|
+
bar_height: int,
|
|
215
|
+
legend_order: list[str] | None = None,
|
|
216
|
+
) -> plt.Figure:
|
|
217
|
+
"""
|
|
218
|
+
Core rendering function for all chromosome paint plots.
|
|
219
|
+
|
|
220
|
+
Parameters
|
|
221
|
+
----------
|
|
222
|
+
spp_df : DataFrame with at least query_chr, position, length,
|
|
223
|
+
and the column named by ``colour_column``.
|
|
224
|
+
colour_map : {value: colour} mapping for the colour_column.
|
|
225
|
+
colour_column : Column name to look up colours from
|
|
226
|
+
(``"status"`` or ``"assigned_chr"``).
|
|
227
|
+
chr_order : Pre-sorted list of chromosomes to plot
|
|
228
|
+
(already filtered if needed).
|
|
229
|
+
legend_title : Title for the legend
|
|
230
|
+
(``"Merian element"`` or ``"Query chromosome"``).
|
|
231
|
+
title : Plot title (species name, rendered italic).
|
|
232
|
+
karyotype : Subtitle string (number of contigs).
|
|
233
|
+
bar_width : Half-width of each BUSCO marker in bp.
|
|
234
|
+
bar_height : Height of each chromosome bar.
|
|
235
|
+
legend_order : If provided, only include these keys (in order) in the
|
|
236
|
+
legend, filtered to values present in the data.
|
|
237
|
+
If ``None``, use all ``colour_map`` keys.
|
|
238
|
+
"""
|
|
239
|
+
spp_df = spp_df.copy()
|
|
240
|
+
sub_title = f"n contigs = {karyotype}"
|
|
241
|
+
|
|
242
|
+
n_chroms = len(chr_order)
|
|
243
|
+
row_height = bar_height + 4
|
|
244
|
+
fig_height = max(8, n_chroms * 0.55)
|
|
245
|
+
fig, ax = plt.subplots(figsize=(15 / 2.54 * 2, fig_height))
|
|
246
|
+
|
|
247
|
+
for idx, chrom in enumerate(chr_order):
|
|
248
|
+
chrom_data = spp_df[spp_df["query_chr"] == chrom]
|
|
249
|
+
y = idx * row_height
|
|
250
|
+
length = chrom_data["length"].iloc[0] if not chrom_data.empty else 0
|
|
251
|
+
|
|
252
|
+
positions = chrom_data["position"].values
|
|
253
|
+
colours = [
|
|
254
|
+
colour_map.get(val, "lightgrey")
|
|
255
|
+
for val in chrom_data[colour_column]
|
|
256
|
+
]
|
|
257
|
+
_draw_chromosome_row(
|
|
258
|
+
ax,
|
|
259
|
+
y,
|
|
260
|
+
0,
|
|
261
|
+
length,
|
|
262
|
+
positions,
|
|
263
|
+
colours,
|
|
264
|
+
bar_width=bar_width,
|
|
265
|
+
bar_height=bar_height,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
ax.text(
|
|
269
|
+
-0.01 * spp_df["length"].max(),
|
|
270
|
+
y + bar_height / 2,
|
|
271
|
+
chrom,
|
|
272
|
+
ha="right",
|
|
273
|
+
va="center",
|
|
274
|
+
fontsize=9,
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
# Axes formatting
|
|
278
|
+
ax.set_xlim(-0.15 * spp_df["length"].max(), spp_df["length"].max() * 1.05)
|
|
279
|
+
ax.set_ylim(-row_height, n_chroms * row_height)
|
|
280
|
+
ax.set_xlabel("Position (Mb)", fontsize=12)
|
|
281
|
+
ax.xaxis.set_major_formatter(
|
|
282
|
+
plt.FuncFormatter(lambda x, _: f"{x / 1e6:.0f}")
|
|
283
|
+
)
|
|
284
|
+
ax.set_yticks([])
|
|
285
|
+
|
|
286
|
+
ax.set_title(f"$\\it{{{title}}}$\n{sub_title}", fontsize=14)
|
|
287
|
+
|
|
288
|
+
# Legend
|
|
289
|
+
if legend_order is not None:
|
|
290
|
+
present = set(spp_df[colour_column].unique())
|
|
291
|
+
legend_keys = [k for k in legend_order if k in present]
|
|
292
|
+
else:
|
|
293
|
+
legend_keys = list(colour_map.keys())
|
|
294
|
+
|
|
295
|
+
legend_handles = [
|
|
296
|
+
mpatches.Patch(facecolor=colour_map.get(k, "lightgrey"), label=k)
|
|
297
|
+
for k in legend_keys
|
|
298
|
+
]
|
|
299
|
+
ax.legend(
|
|
300
|
+
handles=legend_handles,
|
|
301
|
+
title=legend_title,
|
|
302
|
+
loc="center left",
|
|
303
|
+
bbox_to_anchor=(1.01, 0.5),
|
|
304
|
+
frameon=False,
|
|
305
|
+
fontsize=9,
|
|
306
|
+
)
|
|
307
|
+
|
|
308
|
+
_apply_busco_paint_theme(ax)
|
|
309
|
+
fig.tight_layout()
|
|
310
|
+
return fig
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
# ---------------------------------------------------------------------------
|
|
314
|
+
# Four public plot functions (thin wrappers around _render_chromosome_plot)
|
|
315
|
+
# ---------------------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def paint_merians_differences_only(
|
|
319
|
+
spp_df: pd.DataFrame,
|
|
320
|
+
subset_merians: dict,
|
|
321
|
+
num_col: int,
|
|
322
|
+
title: str,
|
|
323
|
+
karyotype: str,
|
|
324
|
+
bar_width: float,
|
|
325
|
+
bar_height: int,
|
|
326
|
+
) -> plt.Figure:
|
|
327
|
+
"""Plot only BUSCOs that have moved — coloured by Merian element."""
|
|
328
|
+
chr_order = _chromosome_order(spp_df)
|
|
329
|
+
return _render_chromosome_plot(
|
|
330
|
+
spp_df,
|
|
331
|
+
subset_merians,
|
|
332
|
+
"status",
|
|
333
|
+
chr_order,
|
|
334
|
+
"Merian element",
|
|
335
|
+
title,
|
|
336
|
+
karyotype,
|
|
337
|
+
bar_width,
|
|
338
|
+
bar_height,
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def paint_species_differences_only(
|
|
343
|
+
spp_df: pd.DataFrame,
|
|
344
|
+
num_col: int,
|
|
345
|
+
title: str,
|
|
346
|
+
karyotype: str,
|
|
347
|
+
bar_width: float,
|
|
348
|
+
bar_height: int,
|
|
349
|
+
) -> plt.Figure:
|
|
350
|
+
"""Plot only BUSCOs that have moved — coloured by species/query chromosome."""
|
|
351
|
+
chr_order = _chromosome_order(spp_df)
|
|
352
|
+
chr_order = [c for c in chr_order if c != "self"]
|
|
353
|
+
|
|
354
|
+
legend_levels = spp_df["status"].unique().tolist()
|
|
355
|
+
legend_levels = [level for level in legend_levels if level != "self"]
|
|
356
|
+
legend_levels = ["self"] + legend_levels
|
|
357
|
+
|
|
358
|
+
col_palette_raw = hue_palette(len(legend_levels))
|
|
359
|
+
col_palette_raw[0] = "grey" # "self" → grey
|
|
360
|
+
col_palette = dict(zip(legend_levels, col_palette_raw))
|
|
361
|
+
|
|
362
|
+
return _render_chromosome_plot(
|
|
363
|
+
spp_df,
|
|
364
|
+
col_palette,
|
|
365
|
+
"status",
|
|
366
|
+
chr_order,
|
|
367
|
+
"Query chromosome",
|
|
368
|
+
title,
|
|
369
|
+
karyotype,
|
|
370
|
+
bar_width,
|
|
371
|
+
bar_height,
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def paint_merians_all(
|
|
376
|
+
spp_df: pd.DataFrame,
|
|
377
|
+
num_col: int,
|
|
378
|
+
title: str,
|
|
379
|
+
karyotype: str,
|
|
380
|
+
bar_width: float,
|
|
381
|
+
bar_height: int,
|
|
382
|
+
) -> plt.Figure:
|
|
383
|
+
"""Plot ALL BUSCOs — coloured by Merian element (assigned_chr)."""
|
|
384
|
+
colour_palette_raw = hue_palette(
|
|
385
|
+
32
|
|
386
|
+
) # THIS COULD BE UPDATED FOR ALG UNIT COUNT
|
|
387
|
+
colour_palette_raw.append("grey") # for "self"
|
|
388
|
+
colour_palette = dict(zip(MERIAN_ORDER, colour_palette_raw))
|
|
389
|
+
chr_order = _chromosome_order(spp_df)
|
|
390
|
+
|
|
391
|
+
return _render_chromosome_plot(
|
|
392
|
+
spp_df,
|
|
393
|
+
colour_palette,
|
|
394
|
+
"assigned_chr",
|
|
395
|
+
chr_order,
|
|
396
|
+
"Merian element",
|
|
397
|
+
title,
|
|
398
|
+
karyotype,
|
|
399
|
+
bar_width,
|
|
400
|
+
bar_height,
|
|
401
|
+
legend_order=MERIAN_ORDER,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def paint_species_all(
|
|
406
|
+
spp_df: pd.DataFrame,
|
|
407
|
+
num_col: int,
|
|
408
|
+
title: str,
|
|
409
|
+
karyotype: str,
|
|
410
|
+
bar_width: float,
|
|
411
|
+
bar_height: int,
|
|
412
|
+
) -> plt.Figure:
|
|
413
|
+
"""Plot ALL BUSCOs — coloured by species/assigned chromosome."""
|
|
414
|
+
chr_order = _chromosome_order(spp_df)
|
|
415
|
+
chr_order = [c for c in chr_order if c != "self"]
|
|
416
|
+
|
|
417
|
+
legend_levels = spp_df["assigned_chr"].unique().tolist()
|
|
418
|
+
col_palette = dict(zip(legend_levels, hue_palette(len(legend_levels))))
|
|
419
|
+
|
|
420
|
+
return _render_chromosome_plot(
|
|
421
|
+
spp_df,
|
|
422
|
+
col_palette,
|
|
423
|
+
"assigned_chr",
|
|
424
|
+
chr_order,
|
|
425
|
+
"Query chromosome",
|
|
426
|
+
title,
|
|
427
|
+
karyotype,
|
|
428
|
+
bar_width,
|
|
429
|
+
bar_height,
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
# ---------------------------------------------------------------------------
|
|
434
|
+
# Save helper
|
|
435
|
+
# ---------------------------------------------------------------------------
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def save_plot(fig: plt.Figure, base_path: str) -> None:
|
|
439
|
+
"""Save figure as both PNG and PDF (mirrors R script's ggsave calls)."""
|
|
440
|
+
for ext in ("png", "pdf"):
|
|
441
|
+
out = f"{base_path}_buscopainter.{ext}"
|
|
442
|
+
fig.savefig(out, dpi=300, bbox_inches="tight")
|
|
443
|
+
logger.info("[Plotter V1] Saved: %s", out)
|
|
444
|
+
plt.close(fig)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
# ---------------------------------------------------------------------------
|
|
448
|
+
# Main entry point
|
|
449
|
+
# ---------------------------------------------------------------------------
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def plotter_v1_main(args: argparse.Namespace) -> None:
|
|
453
|
+
"""
|
|
454
|
+
Main orchestration — mirrors the bottom half of the R script.
|
|
455
|
+
Can be called from the CLI or imported and called with an args namespace.
|
|
456
|
+
"""
|
|
457
|
+
if args.index is None:
|
|
458
|
+
location_set = prepare_data(args.file)
|
|
459
|
+
else:
|
|
460
|
+
location_set = prepare_data_with_index(args.file, args.index)
|
|
461
|
+
|
|
462
|
+
locations_filt = filter_buscos(location_set, args.minimum)
|
|
463
|
+
|
|
464
|
+
# ---- Reporting --------------------------------------------------------
|
|
465
|
+
total_contigs = location_set["query_chr"].nunique()
|
|
466
|
+
num_contigs = locations_filt["query_chr"].nunique()
|
|
467
|
+
num_removed = total_contigs - num_contigs
|
|
468
|
+
|
|
469
|
+
logger.info(
|
|
470
|
+
f"[Plotter V1] Number of contigs before filtering by number of BUSCOs: {total_contigs}"
|
|
471
|
+
)
|
|
472
|
+
logger.info(
|
|
473
|
+
f"[Plotter V1] Number of contigs removed by filtering : {num_removed}"
|
|
474
|
+
)
|
|
475
|
+
logger.info(
|
|
476
|
+
f"[Plotter V1] Number of contigs post-filtering: {num_contigs}"
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
num_contigs_str = str(num_contigs)
|
|
480
|
+
bw = args.bar_width
|
|
481
|
+
bh = args.bar_height
|
|
482
|
+
|
|
483
|
+
# ---- Select plot function based on flags ------------------------------
|
|
484
|
+
if args.merians:
|
|
485
|
+
subset_merians: dict[str, str] = set_merian_colour_mapping(
|
|
486
|
+
locations_filt
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
if not args.differences:
|
|
490
|
+
fig = paint_merians_all(
|
|
491
|
+
locations_filt,
|
|
492
|
+
1,
|
|
493
|
+
args.prefix,
|
|
494
|
+
num_contigs_str,
|
|
495
|
+
bar_width=bw,
|
|
496
|
+
bar_height=bh,
|
|
497
|
+
)
|
|
498
|
+
else:
|
|
499
|
+
num_col = (
|
|
500
|
+
1 if len(locations_filt["query_chr"].unique()) < 100 else 3
|
|
501
|
+
)
|
|
502
|
+
fig = paint_merians_differences_only(
|
|
503
|
+
locations_filt,
|
|
504
|
+
subset_merians,
|
|
505
|
+
num_col,
|
|
506
|
+
args.prefix,
|
|
507
|
+
num_contigs_str,
|
|
508
|
+
bar_width=bw,
|
|
509
|
+
bar_height=bh,
|
|
510
|
+
)
|
|
511
|
+
else:
|
|
512
|
+
if not args.differences:
|
|
513
|
+
fig = paint_species_all(
|
|
514
|
+
locations_filt,
|
|
515
|
+
1,
|
|
516
|
+
args.prefix,
|
|
517
|
+
num_contigs_str,
|
|
518
|
+
bar_width=bw,
|
|
519
|
+
bar_height=bh,
|
|
520
|
+
)
|
|
521
|
+
else:
|
|
522
|
+
fig = paint_species_differences_only(
|
|
523
|
+
locations_filt,
|
|
524
|
+
1,
|
|
525
|
+
args.prefix,
|
|
526
|
+
num_contigs_str,
|
|
527
|
+
bar_width=bw,
|
|
528
|
+
bar_height=bh,
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
# ---- Save outputs -----------------------------------------------------
|
|
532
|
+
logger.info(f"[Plotter V1] Saving plot to: {str(args.file)}")
|
|
533
|
+
save_plot(fig, str(args.file))
|