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
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import matplotlib.patches as patches
|
|
5
|
+
import matplotlib.pyplot as plt
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib import font_manager
|
|
8
|
+
|
|
9
|
+
from alg_painter.plotter_colours import MERIAN_COLOURS
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load_locations_file(location_file: Path) -> pd.DataFrame:
|
|
15
|
+
"""
|
|
16
|
+
Load BUSCO locations from a TSV file.
|
|
17
|
+
"""
|
|
18
|
+
# Read locations
|
|
19
|
+
locations = pd.read_csv(location_file, sep="\t")
|
|
20
|
+
|
|
21
|
+
# Clean chromosome names (remove any :scaffolds)
|
|
22
|
+
locations["query_chr"] = locations["query_chr"].str.replace(
|
|
23
|
+
":.*", "", regex=True
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
return locations
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_data(
|
|
30
|
+
location_file: Path, lengths_file=None
|
|
31
|
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
32
|
+
"""Load BUSCO locations and chromosome lengths"""
|
|
33
|
+
locations = _load_locations_file(location_file)
|
|
34
|
+
|
|
35
|
+
# Read or estimate chromosome lengths
|
|
36
|
+
if lengths_file:
|
|
37
|
+
chrom_lengths = pd.read_csv(
|
|
38
|
+
lengths_file,
|
|
39
|
+
sep="\t",
|
|
40
|
+
header=None,
|
|
41
|
+
names=["query_chr", "length", "offset", "linebases", "linewidth"],
|
|
42
|
+
)
|
|
43
|
+
else:
|
|
44
|
+
# Fallback: estimate from max position + 5% padding
|
|
45
|
+
chrom_lengths = (
|
|
46
|
+
locations.groupby("query_chr")["position"].max().reset_index()
|
|
47
|
+
)
|
|
48
|
+
chrom_lengths["length"] = chrom_lengths["position"] * 1.05
|
|
49
|
+
|
|
50
|
+
return locations, chrom_lengths
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def get_palette(palette_name: str) -> dict:
|
|
54
|
+
return MERIAN_COLOURS[palette_name]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def filter_chromosomes(locations, minimum_buscos=3):
|
|
58
|
+
"""
|
|
59
|
+
Filter chromosomes by minimum BUSCO count
|
|
60
|
+
"""
|
|
61
|
+
busco_counts = (
|
|
62
|
+
locations.groupby("query_chr").size().reset_index(name="n_busco")
|
|
63
|
+
)
|
|
64
|
+
valid_chroms = busco_counts[busco_counts["n_busco"] >= minimum_buscos][
|
|
65
|
+
"query_chr"
|
|
66
|
+
]
|
|
67
|
+
return locations[locations["query_chr"].isin(valid_chroms)]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def setup_font(font_path: Path) -> None:
|
|
71
|
+
"""
|
|
72
|
+
Set up the font for plotting
|
|
73
|
+
"""
|
|
74
|
+
font_manager.fontManager.addfont(str(font_path))
|
|
75
|
+
plt.rcParams["font.family"] = "Open Sans"
|
|
76
|
+
plt.rcParams["font.style"] = "normal"
|
|
77
|
+
plt.rcParams["font.weight"] = "normal"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def calculate_merian_labels(locations, threshold=5):
|
|
81
|
+
"""
|
|
82
|
+
Calculate Merian element labels for each chromosome.
|
|
83
|
+
Returns {chromosome: 'M1; M3; M18'} for elements with >= threshold BUSCOs.
|
|
84
|
+
"""
|
|
85
|
+
# Count BUSCOs per chromosome-Merian combination
|
|
86
|
+
counts = (
|
|
87
|
+
locations.groupby(["query_chr", "assigned_chr"])
|
|
88
|
+
.size()
|
|
89
|
+
.reset_index(name="n")
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
# Filter by threshold
|
|
93
|
+
counts = counts[counts["n"] >= threshold]
|
|
94
|
+
|
|
95
|
+
# Group by chromosome and join Merian elements
|
|
96
|
+
labels = {}
|
|
97
|
+
for chrom in counts["query_chr"].unique():
|
|
98
|
+
chrom_merians = counts[counts["query_chr"] == chrom][
|
|
99
|
+
"assigned_chr"
|
|
100
|
+
].tolist()
|
|
101
|
+
# Sort Merian elements (MZ first, then M1-M31 numerically)
|
|
102
|
+
sorted_merians = sorted(
|
|
103
|
+
chrom_merians,
|
|
104
|
+
key=lambda x: (x != "MZ", int(x[1:]) if x != "MZ" else 0),
|
|
105
|
+
)
|
|
106
|
+
labels[chrom] = "; ".join(sorted_merians)
|
|
107
|
+
|
|
108
|
+
return labels
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def plot_merian_chromosomes(
|
|
112
|
+
locations: pd.DataFrame,
|
|
113
|
+
chrom_lengths: pd.DataFrame,
|
|
114
|
+
output_prefix: str,
|
|
115
|
+
minimum_buscos: int,
|
|
116
|
+
palette: dict,
|
|
117
|
+
label_threshold: int,
|
|
118
|
+
):
|
|
119
|
+
"""
|
|
120
|
+
Create the main Merian plot with chromosome labels
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
# Keep track of placeholder rows in the filtered locations (where buscoID is NA)
|
|
124
|
+
is_placeholder = locations["buscoID"] == "NA"
|
|
125
|
+
|
|
126
|
+
# Filter only valid Merian assignments for actual BUSCOs
|
|
127
|
+
valid_merians = ["MZ"] + [f"M{i}" for i in range(1, 32)]
|
|
128
|
+
locations_filtered = locations[
|
|
129
|
+
is_placeholder
|
|
130
|
+
| locations["assigned_chr"].str.upper().isin(valid_merians)
|
|
131
|
+
]
|
|
132
|
+
locations_filtered["assigned_chr"] = locations_filtered[
|
|
133
|
+
"assigned_chr"
|
|
134
|
+
].str.upper()
|
|
135
|
+
|
|
136
|
+
# Calculate Merian labels for each chromosome
|
|
137
|
+
merian_labels = calculate_merian_labels(
|
|
138
|
+
locations, threshold=label_threshold
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
# Order chromosomes by length (descending) - USE ALL CHROMOSOMES FROM chrom_lengths
|
|
142
|
+
chrom_order = chrom_lengths.sort_values("length", ascending=False)[
|
|
143
|
+
"query_chr"
|
|
144
|
+
].tolist()
|
|
145
|
+
|
|
146
|
+
# DO NOT FILTER - keep all chromosomes even if they have no BUSCOs
|
|
147
|
+
|
|
148
|
+
# Prepare y-positions (reversed so longest is at top)
|
|
149
|
+
n_chroms = len(chrom_order)
|
|
150
|
+
y_positions = {chrom: i for i, chrom in enumerate(reversed(chrom_order))}
|
|
151
|
+
|
|
152
|
+
# Calculate plot height dynamically
|
|
153
|
+
plot_height = max(15, 0.9 * n_chroms)
|
|
154
|
+
|
|
155
|
+
# Create figure with extra space for labels
|
|
156
|
+
fig, ax = plt.subplots(figsize=(30 / 2.54, plot_height / 2.54))
|
|
157
|
+
|
|
158
|
+
# Plot chromosome bars
|
|
159
|
+
for chrom in chrom_order:
|
|
160
|
+
y = y_positions[chrom]
|
|
161
|
+
length = chrom_lengths[chrom_lengths["query_chr"] == chrom][
|
|
162
|
+
"length"
|
|
163
|
+
].values[0]
|
|
164
|
+
# Draw chromosome backbone (white rectangle with black border)
|
|
165
|
+
rect = patches.Rectangle(
|
|
166
|
+
(0, y - 0.4),
|
|
167
|
+
length,
|
|
168
|
+
0.8,
|
|
169
|
+
facecolor="white",
|
|
170
|
+
edgecolor="black",
|
|
171
|
+
linewidth=0.5,
|
|
172
|
+
)
|
|
173
|
+
ax.add_patch(rect)
|
|
174
|
+
|
|
175
|
+
# Plot BUSCO positions
|
|
176
|
+
chrom_buscos = locations[locations["query_chr"] == chrom]
|
|
177
|
+
for _, busco in chrom_buscos.iterrows():
|
|
178
|
+
if pd.notna(busco["position"]):
|
|
179
|
+
color = palette.get(busco["assigned_chr"], (0.85, 0.85, 0.85))
|
|
180
|
+
tile = patches.Rectangle(
|
|
181
|
+
(busco["position"] - 25000, y - 0.4),
|
|
182
|
+
50000,
|
|
183
|
+
0.8,
|
|
184
|
+
facecolor=color,
|
|
185
|
+
edgecolor="none",
|
|
186
|
+
)
|
|
187
|
+
ax.add_patch(tile)
|
|
188
|
+
|
|
189
|
+
# Add Merian label to the right of the chromosome
|
|
190
|
+
if chrom in merian_labels:
|
|
191
|
+
label_text = merian_labels[chrom]
|
|
192
|
+
ax.text(
|
|
193
|
+
length * 1.02,
|
|
194
|
+
y,
|
|
195
|
+
label_text,
|
|
196
|
+
va="center",
|
|
197
|
+
ha="left",
|
|
198
|
+
fontsize=10,
|
|
199
|
+
color="#333333",
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
# Set axis limits and labels
|
|
203
|
+
max_length = chrom_lengths["length"].max()
|
|
204
|
+
ax.set_xlim(0, max_length * 1.25)
|
|
205
|
+
ax.set_ylim(-0.6, n_chroms - 0.4)
|
|
206
|
+
|
|
207
|
+
# X-axis: position in Mb
|
|
208
|
+
ax.set_xlabel("Position (Mb)", fontsize=11)
|
|
209
|
+
ax.xaxis.set_major_formatter(
|
|
210
|
+
plt.FuncFormatter(lambda x, p: f"{x / 1e6:.0f}")
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# Y-axis: chromosome names
|
|
214
|
+
ax.set_yticks([y_positions[c] for c in chrom_order])
|
|
215
|
+
ax.set_yticklabels(chrom_order, fontsize=10)
|
|
216
|
+
ax.set_ylabel("")
|
|
217
|
+
|
|
218
|
+
# Remove top and right spines
|
|
219
|
+
ax.spines["top"].set_visible(False)
|
|
220
|
+
ax.spines["right"].set_visible(False)
|
|
221
|
+
ax.spines["left"].set_visible(False)
|
|
222
|
+
|
|
223
|
+
# Create legend
|
|
224
|
+
legend_elements = []
|
|
225
|
+
for merian in ["MZ"] + [f"M{i}" for i in range(1, 32)]:
|
|
226
|
+
legend_elements.append(
|
|
227
|
+
patches.Patch(facecolor=palette[merian], label=merian)
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
ax.legend(
|
|
231
|
+
handles=legend_elements,
|
|
232
|
+
title="Merian elements",
|
|
233
|
+
loc="center left",
|
|
234
|
+
bbox_to_anchor=(1.01, 0.5),
|
|
235
|
+
frameon=False,
|
|
236
|
+
fontsize=10,
|
|
237
|
+
title_fontsize=11,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
plt.tight_layout(rect=(0, 0, 0.82, 1))
|
|
241
|
+
|
|
242
|
+
# Save outputs
|
|
243
|
+
for ext in ["png", "svg"]:
|
|
244
|
+
output_file = f"{output_prefix}.{ext}"
|
|
245
|
+
dpi = 300 if ext == "png" else None
|
|
246
|
+
plt.savefig(output_file, dpi=dpi, bbox_inches="tight")
|
|
247
|
+
logger.info(f"[Plotter V2] Saved: {output_file}")
|
|
248
|
+
|
|
249
|
+
plt.close()
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def plotter_v2_main(arguments):
|
|
253
|
+
logger.info("[Plotter V2] Loading data from %s", arguments.file)
|
|
254
|
+
locations, chrom_lengths = load_data(
|
|
255
|
+
arguments.file, arguments.lengths_file
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
logger.info(
|
|
259
|
+
f"[Plotter V2] Plotting {len(locations)} BUSCOs across {len(chrom_lengths)} chromosomes"
|
|
260
|
+
)
|
|
261
|
+
setup_font(arguments.font)
|
|
262
|
+
|
|
263
|
+
# Filter by minimum BUSCOs, but keep track of all chromosomes from chrom_lengths
|
|
264
|
+
# This ensures sex chromosomes (like W) are always plotted even if empty
|
|
265
|
+
# all_chromosomes = set(chrom_lengths["query_chr"].tolist())
|
|
266
|
+
locations_filtered = filter_chromosomes(locations, arguments.minimum)
|
|
267
|
+
|
|
268
|
+
final_palette: dict = get_palette(arguments.palette)
|
|
269
|
+
|
|
270
|
+
plot_merian_chromosomes(
|
|
271
|
+
locations_filtered,
|
|
272
|
+
chrom_lengths,
|
|
273
|
+
arguments.prefix,
|
|
274
|
+
arguments.minimum,
|
|
275
|
+
final_palette,
|
|
276
|
+
arguments.label_threshold,
|
|
277
|
+
)
|
alg_painter/cli.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from alg_painter.alg_painter import painting_main as alg_painter
|
|
7
|
+
from alg_painter.alg_plotter_v1 import plotter_v1_main as alg_plotter_v1
|
|
8
|
+
from alg_painter.alg_plotter_v2 import plotter_v2_main as alg_plotter_v2
|
|
9
|
+
|
|
10
|
+
logging.basicConfig(
|
|
11
|
+
level=logging.INFO,
|
|
12
|
+
format="%(asctime)s [%(levelname)s] %(message)s",
|
|
13
|
+
handlers=[
|
|
14
|
+
logging.FileHandler("alg_painter.log"), # logs to file
|
|
15
|
+
logging.StreamHandler(), # logs to console
|
|
16
|
+
],
|
|
17
|
+
)
|
|
18
|
+
logger = logging.getLogger("alg_painter")
|
|
19
|
+
|
|
20
|
+
VERSION = "0.1.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def file_validator(in_file: str, file_type) -> Path | None:
|
|
24
|
+
"""
|
|
25
|
+
Validate files exist and are infact files
|
|
26
|
+
"""
|
|
27
|
+
file_checks = {"font": {"format": [".ttf"], "validated": False}}
|
|
28
|
+
|
|
29
|
+
file_path = Path(in_file)
|
|
30
|
+
|
|
31
|
+
if not file_path.exists() or not file_path.is_file():
|
|
32
|
+
raise argparse.ArgumentTypeError(f"{in_file} is not a valid file")
|
|
33
|
+
|
|
34
|
+
if (
|
|
35
|
+
file_type == "font"
|
|
36
|
+
and file_path.suffix not in file_checks["font"]["format"]
|
|
37
|
+
):
|
|
38
|
+
raise argparse.ArgumentTypeError(
|
|
39
|
+
f"{in_file} has unsupported extension '{file_path.suffix}', expected one of {file_checks['font']['format']}"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
return file_path
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def parse_args() -> argparse.Namespace:
|
|
46
|
+
parser = argparse.ArgumentParser(
|
|
47
|
+
prog="alg_painter", description="Ancestral Linkage Group Painter"
|
|
48
|
+
)
|
|
49
|
+
parser.add_argument(
|
|
50
|
+
"-v",
|
|
51
|
+
"--version",
|
|
52
|
+
action="version",
|
|
53
|
+
version=VERSION,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
subparsers = parser.add_subparsers(
|
|
57
|
+
help="Subcommand help", dest="command", required=True
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
painter = subparsers.add_parser(
|
|
61
|
+
"painter",
|
|
62
|
+
help="Run the Ancestral Linkage Group Painting command",
|
|
63
|
+
description="Paint the BUSCOs colored by their putative ALG assignments",
|
|
64
|
+
)
|
|
65
|
+
painter.add_argument(
|
|
66
|
+
"--alg_table",
|
|
67
|
+
"-a",
|
|
68
|
+
type=Path,
|
|
69
|
+
required=True,
|
|
70
|
+
help="The reference ALG table for mapping",
|
|
71
|
+
)
|
|
72
|
+
painter.add_argument(
|
|
73
|
+
"--query_table",
|
|
74
|
+
"-q",
|
|
75
|
+
type=Path,
|
|
76
|
+
required=True,
|
|
77
|
+
help="The Query table to paint (e.g. your assembly's ALG table)",
|
|
78
|
+
)
|
|
79
|
+
painter.add_argument(
|
|
80
|
+
"--prefix",
|
|
81
|
+
"-p",
|
|
82
|
+
type=str,
|
|
83
|
+
default="alg_painter",
|
|
84
|
+
help="Output prefix of files",
|
|
85
|
+
)
|
|
86
|
+
painter.add_argument("--accession", help="Assembly Accession")
|
|
87
|
+
painter.add_argument(
|
|
88
|
+
"--write_summary",
|
|
89
|
+
action="store_true",
|
|
90
|
+
help="Write a summary of the results",
|
|
91
|
+
)
|
|
92
|
+
painter.add_argument(
|
|
93
|
+
"-v",
|
|
94
|
+
"--version",
|
|
95
|
+
action="version",
|
|
96
|
+
version=f"ALG-{VERSION}-PAINTER-2.1.0",
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
plotter = subparsers.add_parser(
|
|
100
|
+
name="plotter",
|
|
101
|
+
help="Original plotter for generic plotting of BUSCO locations",
|
|
102
|
+
description=(
|
|
103
|
+
"Generate a plot showing locations of putative Merian elements "
|
|
104
|
+
"(or species-level orthologs) in a genomic assembly."
|
|
105
|
+
),
|
|
106
|
+
)
|
|
107
|
+
plotter.add_argument(
|
|
108
|
+
"-f",
|
|
109
|
+
"--file",
|
|
110
|
+
type=Path,
|
|
111
|
+
# required=True,
|
|
112
|
+
help="The output file from the painter command, should be a locations.tsv file",
|
|
113
|
+
)
|
|
114
|
+
plotter.add_argument(
|
|
115
|
+
"-i",
|
|
116
|
+
"--index",
|
|
117
|
+
type=Path,
|
|
118
|
+
default=None,
|
|
119
|
+
help="Genome index file (.fai)",
|
|
120
|
+
)
|
|
121
|
+
plotter.add_argument(
|
|
122
|
+
"-p",
|
|
123
|
+
"--prefix",
|
|
124
|
+
type=str,
|
|
125
|
+
default="alg_plotter_v2",
|
|
126
|
+
help="Output prefix of files",
|
|
127
|
+
)
|
|
128
|
+
plotter.add_argument(
|
|
129
|
+
"-m",
|
|
130
|
+
"--merians",
|
|
131
|
+
action="store_true",
|
|
132
|
+
default=False,
|
|
133
|
+
help="Are you comparing a genome to Merian elements?",
|
|
134
|
+
)
|
|
135
|
+
plotter.add_argument(
|
|
136
|
+
"-d",
|
|
137
|
+
"--differences",
|
|
138
|
+
action="store_true",
|
|
139
|
+
default=False,
|
|
140
|
+
help="Colour only BUSCOs moved from the dominant chromosome",
|
|
141
|
+
)
|
|
142
|
+
plotter.add_argument(
|
|
143
|
+
"-n",
|
|
144
|
+
"--minimum",
|
|
145
|
+
type=int,
|
|
146
|
+
default=3,
|
|
147
|
+
help="Minimum number of BUSCOs per contig to retain (default: 3)",
|
|
148
|
+
)
|
|
149
|
+
plotter.add_argument(
|
|
150
|
+
"--bar_height",
|
|
151
|
+
type=int,
|
|
152
|
+
default=12,
|
|
153
|
+
help="Height of each BUSCO bar in bp (default: 12)",
|
|
154
|
+
)
|
|
155
|
+
plotter.add_argument(
|
|
156
|
+
"--bar_width",
|
|
157
|
+
type=float,
|
|
158
|
+
default=2e4,
|
|
159
|
+
help="Half-width of each BUSCO bar in bp (default: 2e4)",
|
|
160
|
+
)
|
|
161
|
+
plotter.add_argument(
|
|
162
|
+
"-v",
|
|
163
|
+
"--version",
|
|
164
|
+
action="version",
|
|
165
|
+
version=f"ALG-{VERSION}-PLOTTER-2.0.0",
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
plotter_2 = subparsers.add_parser(
|
|
169
|
+
"plotter2",
|
|
170
|
+
help="Newer Plotting process, currently in use for genomenotes, Plot BUSCO locations colored by ALG assignments",
|
|
171
|
+
description="Plot the BUSCO labelled by the ALG painter onto a per chromosome plot",
|
|
172
|
+
)
|
|
173
|
+
plotter_2.add_argument(
|
|
174
|
+
"-f",
|
|
175
|
+
"--file",
|
|
176
|
+
type=Path,
|
|
177
|
+
required=True,
|
|
178
|
+
help="The output file from the painter command, should be a locations.tsv file",
|
|
179
|
+
)
|
|
180
|
+
plotter_2.add_argument(
|
|
181
|
+
"-l",
|
|
182
|
+
"--lengths_file",
|
|
183
|
+
default=None,
|
|
184
|
+
type=Path,
|
|
185
|
+
help="Path to a chromosomes sizes file (an fai file, optional)",
|
|
186
|
+
)
|
|
187
|
+
plotter_2.add_argument(
|
|
188
|
+
"-p",
|
|
189
|
+
"--prefix",
|
|
190
|
+
type=str,
|
|
191
|
+
default="alg_plotter_v2",
|
|
192
|
+
help="Output prefix of files",
|
|
193
|
+
)
|
|
194
|
+
plotter_2.add_argument(
|
|
195
|
+
"-m",
|
|
196
|
+
"--minimum",
|
|
197
|
+
type=int,
|
|
198
|
+
default=3,
|
|
199
|
+
help="Minimum number of BUSCOs to plot per chromosome (default: 3)",
|
|
200
|
+
)
|
|
201
|
+
plotter_2.add_argument(
|
|
202
|
+
"--palette",
|
|
203
|
+
choices=["categorical", "spectrum", "merianbow", "merianbow4"],
|
|
204
|
+
default="categorical",
|
|
205
|
+
help="Palette to use for coloring BUSCOs (default: categorical), spectrum (turbo), merianbow (original for lepidoptera), merianbow4 (CVD-optimised for lepidoptera)",
|
|
206
|
+
)
|
|
207
|
+
plotter_2.add_argument(
|
|
208
|
+
"--label-threshold",
|
|
209
|
+
type=int,
|
|
210
|
+
default=5,
|
|
211
|
+
help="Minimum number of BUSCOs for an ALG unit appear on the plot (default: 5)",
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# Font Arguments
|
|
215
|
+
font_path = os.path.join(
|
|
216
|
+
os.path.dirname(__file__), "fonts", "OpenSans-Regular.ttf"
|
|
217
|
+
)
|
|
218
|
+
plotter_2.add_argument(
|
|
219
|
+
"--font",
|
|
220
|
+
type=lambda s: file_validator(s, "font"),
|
|
221
|
+
default=font_path,
|
|
222
|
+
help="Path to the font file to use for plotting (default: OpenSans-Regular.ttf)",
|
|
223
|
+
)
|
|
224
|
+
plotter_2.add_argument(
|
|
225
|
+
"-v",
|
|
226
|
+
"--version",
|
|
227
|
+
action="version",
|
|
228
|
+
version=f"ALG-{VERSION}-PLOTTER_V2-2.1.0",
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
return parser.parse_args()
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def validate_locations(file_path) -> None:
|
|
235
|
+
with open(file_path, "r") as f:
|
|
236
|
+
first_line = f.readline()
|
|
237
|
+
print(first_line.split("\t"))
|
|
238
|
+
if first_line.split("\t") == [
|
|
239
|
+
"buscoID",
|
|
240
|
+
"query_chr",
|
|
241
|
+
"position",
|
|
242
|
+
"assigned_chr",
|
|
243
|
+
"status\n",
|
|
244
|
+
]:
|
|
245
|
+
raise ValueError(f"File ({file_path}): first line is empty")
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def main():
|
|
249
|
+
args = parse_args()
|
|
250
|
+
|
|
251
|
+
if args.command == "plotter" and args.file:
|
|
252
|
+
validate_locations(args.file)
|
|
253
|
+
|
|
254
|
+
match args.command:
|
|
255
|
+
case "painter":
|
|
256
|
+
alg_painter(args)
|
|
257
|
+
case "plotter":
|
|
258
|
+
alg_plotter_v1(args)
|
|
259
|
+
case "plotter2":
|
|
260
|
+
alg_plotter_v2(args)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
if __name__ == "__main__":
|
|
264
|
+
main()
|
|
Binary file
|
alg_painter/generics.py
ADDED
alg_painter/ncbi_api.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
API_KEY = os.getenv("NCBI_API_KEY")
|
|
7
|
+
|
|
8
|
+
logger = logging.getLogger(__name__)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def fetch_sequence_report(accession: str) -> list[dict]:
|
|
12
|
+
url = f"https://api.ncbi.nlm.nih.gov/datasets/v2/genome/accession/{accession}/sequence_reports"
|
|
13
|
+
headers = {"accept": "application/json", "User-Agent": "buscopainter"}
|
|
14
|
+
params = {}
|
|
15
|
+
if API_KEY:
|
|
16
|
+
params["api_key"] = API_KEY
|
|
17
|
+
logger.info(
|
|
18
|
+
f"[Fetch seq report] Fetching chromosome info from NCBI for {accession}..."
|
|
19
|
+
)
|
|
20
|
+
response = requests.get(url, headers=headers, params=params, timeout=60)
|
|
21
|
+
response.raise_for_status()
|
|
22
|
+
return response.json().get("sequence_report", {}).get(
|
|
23
|
+
"records"
|
|
24
|
+
) or response.json().get("reports", [])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def chrom_lengths_with_unloc(records):
|
|
28
|
+
"""
|
|
29
|
+
Return (accession, total_bp) where accession is the main assembled-molecule
|
|
30
|
+
GenBank accession for each chromosome. Length sums main + its unloc scaffolds.
|
|
31
|
+
"""
|
|
32
|
+
# first map chr_name → main accession
|
|
33
|
+
main_acc = {}
|
|
34
|
+
for rec in records:
|
|
35
|
+
if (
|
|
36
|
+
rec.get("role") == "assembled-molecule"
|
|
37
|
+
and rec.get("assigned_molecule_location_type") == "Chromosome"
|
|
38
|
+
):
|
|
39
|
+
main_acc[rec["chr_name"]] = rec["genbank_accession"]
|
|
40
|
+
|
|
41
|
+
bp_tot: dict[str, int] = {acc: 0 for acc in main_acc.values()}
|
|
42
|
+
|
|
43
|
+
for rec in records:
|
|
44
|
+
role = rec.get("role")
|
|
45
|
+
loc = rec.get("assigned_molecule_location_type", "")
|
|
46
|
+
if role == "assembled-molecule" and loc == "Chromosome":
|
|
47
|
+
acc = rec["genbank_accession"]
|
|
48
|
+
bp_tot[acc] += int(rec.get("length", 0))
|
|
49
|
+
elif role == "unlocalized-scaffold":
|
|
50
|
+
parent = rec.get("chr_name")
|
|
51
|
+
acc = main_acc.get(parent)
|
|
52
|
+
if acc:
|
|
53
|
+
bp_tot[acc] += int(rec.get("length", 0))
|
|
54
|
+
|
|
55
|
+
return sorted(bp_tot.items(), key=lambda x: -x[1])
|