pflex 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.
- pflex/__init__.py +44 -0
- pflex/analysis.py +1647 -0
- pflex/data/__init__.py +0 -0
- pflex/data/dataset/__init__.py +0 -0
- pflex/data/dataset/liver_cell_lines_500_genes.csv +501 -0
- pflex/data/dataset/melanoma_cell_lines_500_genes.csv +501 -0
- pflex/data/dataset/neuroblastoma_cell_lines_500_genes.csv +501 -0
- pflex/data/gold_standard/CORUM.parquet +0 -0
- pflex/data/gold_standard/GOBP.parquet +0 -0
- pflex/data/gold_standard/PATHWAY.parquet +0 -0
- pflex/data/gold_standard/__init__.py +0 -0
- pflex/data/gold_standard/corum.csv +2917 -0
- pflex/data/gold_standard/gobp.csv +4829 -0
- pflex/data/gold_standard/pathway.csv +1330 -0
- pflex/examples/basic_usage.py +95 -0
- pflex/logging_config.py +56 -0
- pflex/old_functions.py +422 -0
- pflex/plotting.py +2234 -0
- pflex/preprocessing.py +290 -0
- pflex/utils.py +128 -0
- pflex-1.0.dist-info/METADATA +167 -0
- pflex-1.0.dist-info/RECORD +25 -0
- pflex-1.0.dist-info/WHEEL +4 -0
- pflex-1.0.dist-info/entry_points.txt +2 -0
- pflex-1.0.dist-info/licenses/LICENSE +7 -0
pflex/plotting.py
ADDED
|
@@ -0,0 +1,2234 @@
|
|
|
1
|
+
# Standard library
|
|
2
|
+
from itertools import combinations
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
# Third-party libraries
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import matplotlib.pyplot as plt
|
|
10
|
+
from matplotlib import patches
|
|
11
|
+
from matplotlib.cm import get_cmap
|
|
12
|
+
from matplotlib.lines import Line2D
|
|
13
|
+
from matplotlib.ticker import NullFormatter, NullLocator
|
|
14
|
+
|
|
15
|
+
# Completely disable LaTeX and clear all font cache/references
|
|
16
|
+
import matplotlib as mpl
|
|
17
|
+
import matplotlib.font_manager as fm
|
|
18
|
+
|
|
19
|
+
# Disable LaTeX rendering completely
|
|
20
|
+
mpl.rcParams['text.usetex'] = False
|
|
21
|
+
|
|
22
|
+
# Reset all font-related parameters to system defaults
|
|
23
|
+
mpl.rcParams['font.family'] = 'sans-serif'
|
|
24
|
+
mpl.rcParams['font.serif'] = ['DejaVu Serif', 'Times New Roman', 'Bitstream Vera Serif', 'serif']
|
|
25
|
+
mpl.rcParams['font.sans-serif'] = ['DejaVu Sans', 'Arial', 'Bitstream Vera Sans', 'sans-serif']
|
|
26
|
+
mpl.rcParams['font.cursive'] = ['Apple Chancery', 'Textile', 'Zapf Chancery', 'Sand', 'Script MT', 'Felipa', 'cursive']
|
|
27
|
+
mpl.rcParams['font.fantasy'] = ['Comic Sans MS', 'Chicago', 'Charcoal', 'Impact', 'Western', 'Humor Sans', 'fantasy']
|
|
28
|
+
mpl.rcParams['font.monospace'] = ['DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Computer Modern Typewriter', 'Andale Mono', 'Nimbus Mono L', 'Courier New', 'Courier', 'Fixed', 'Terminal', 'monospace']
|
|
29
|
+
|
|
30
|
+
# Remove any LaTeX-specific math font settings
|
|
31
|
+
mpl.rcParams['mathtext.fontset'] = 'dejavusans'
|
|
32
|
+
mpl.rcParams['mathtext.default'] = 'regular'
|
|
33
|
+
|
|
34
|
+
# Force font manager to rebuild with system fonts only
|
|
35
|
+
try:
|
|
36
|
+
fm.fontManager.__init__()
|
|
37
|
+
except Exception:
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
# Local modules
|
|
41
|
+
from .utils import dload, _sanitize
|
|
42
|
+
from .logging_config import log
|
|
43
|
+
|
|
44
|
+
def plot_precision_recall_curve(line_width=2.0, hide_minor_ticks=True):
|
|
45
|
+
pra = dload("pra")
|
|
46
|
+
config = dload("config")
|
|
47
|
+
plot_config = config["plotting"]
|
|
48
|
+
input_colors = dload("input", "colors") # Load individual color overrides
|
|
49
|
+
|
|
50
|
+
# Sanitize color keys to match dataset keys
|
|
51
|
+
if input_colors:
|
|
52
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
53
|
+
|
|
54
|
+
# Get color map from config, default to "tab10" if not found
|
|
55
|
+
cmap_name = config.get("color_map", "tab10")
|
|
56
|
+
try:
|
|
57
|
+
cmap = get_cmap(cmap_name)
|
|
58
|
+
except ValueError:
|
|
59
|
+
log.warning(f"Color map '{cmap_name}' not found. Falling back to 'tab10'.")
|
|
60
|
+
cmap = get_cmap("tab10")
|
|
61
|
+
|
|
62
|
+
# Increase figure width to accommodate external legend without squashing axes
|
|
63
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
64
|
+
|
|
65
|
+
# Adjust layout to make room for legend on the right
|
|
66
|
+
plt.subplots_adjust(right=0.7)
|
|
67
|
+
|
|
68
|
+
ax.set_xscale("log")
|
|
69
|
+
|
|
70
|
+
# optionally hide minor ticks on the log axis
|
|
71
|
+
if hide_minor_ticks:
|
|
72
|
+
ax.xaxis.set_minor_locator(NullLocator())
|
|
73
|
+
ax.xaxis.set_minor_formatter(NullFormatter())
|
|
74
|
+
|
|
75
|
+
if isinstance(pra, dict):
|
|
76
|
+
# Determine colors for each dataset
|
|
77
|
+
dataset_names = list(pra.keys())
|
|
78
|
+
num_datasets = len(dataset_names)
|
|
79
|
+
|
|
80
|
+
# Generate default colors from colormap
|
|
81
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
82
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
83
|
+
else:
|
|
84
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
85
|
+
|
|
86
|
+
for i, (key, val) in enumerate(pra.items()):
|
|
87
|
+
# Use override color if available, otherwise use default from cmap
|
|
88
|
+
color = input_colors.get(key) if input_colors else None
|
|
89
|
+
if color is None:
|
|
90
|
+
color = default_colors[i]
|
|
91
|
+
|
|
92
|
+
val = val[val.tp > 10]
|
|
93
|
+
ax.plot(val.tp, val.precision, c=color, label=key, linewidth=line_width, alpha=0.9)
|
|
94
|
+
else:
|
|
95
|
+
pra = pra[pra.tp > 10]
|
|
96
|
+
ax.plot(pra.tp, pra.precision, c="black", label="Precision Recall Curve", linewidth=line_width, alpha=0.9)
|
|
97
|
+
|
|
98
|
+
ax.set(title="",
|
|
99
|
+
xlabel="Number of True Positives (TP)",
|
|
100
|
+
ylabel="Precision")
|
|
101
|
+
ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False)
|
|
102
|
+
ax.set_ylim(0, 1)
|
|
103
|
+
|
|
104
|
+
# Nature style: no grid, open top/right spines
|
|
105
|
+
ax.grid(False)
|
|
106
|
+
ax.spines['top'].set_visible(False)
|
|
107
|
+
ax.spines['right'].set_visible(False)
|
|
108
|
+
|
|
109
|
+
if plot_config["save_plot"]:
|
|
110
|
+
output_type = plot_config["output_type"]
|
|
111
|
+
output_path = Path(config["output_folder"]) / f"precision_recall_curve.{output_type}"
|
|
112
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
113
|
+
|
|
114
|
+
if plot_config.get("show_plot", True):
|
|
115
|
+
plt.show()
|
|
116
|
+
plt.close(fig)
|
|
117
|
+
|
|
118
|
+
def plot_aggregated_pra(agg_df, line_width=2.0, hide_minor_ticks=True):
|
|
119
|
+
"""
|
|
120
|
+
Plots an aggregated Precision-Recall curve with mean line and min-max shading.
|
|
121
|
+
agg_df should be indexed by 'tp' and contain 'mean', 'min', 'max' columns for precision.
|
|
122
|
+
"""
|
|
123
|
+
config = dload("config")
|
|
124
|
+
plot_config = config["plotting"]
|
|
125
|
+
|
|
126
|
+
# Increase figure width to accommodate external legend without squashing axes
|
|
127
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
128
|
+
|
|
129
|
+
# Adjust layout to make room for legend on the right
|
|
130
|
+
plt.subplots_adjust(right=0.7)
|
|
131
|
+
|
|
132
|
+
ax.set_xscale("log")
|
|
133
|
+
|
|
134
|
+
# optionally hide minor ticks on the log axis
|
|
135
|
+
if hide_minor_ticks:
|
|
136
|
+
ax.xaxis.set_minor_locator(NullLocator())
|
|
137
|
+
ax.xaxis.set_minor_formatter(NullFormatter())
|
|
138
|
+
|
|
139
|
+
# Filter out very low TP counts if necessary, similar to plot_precision_recall_curve
|
|
140
|
+
agg_df = agg_df[agg_df.index > 10]
|
|
141
|
+
|
|
142
|
+
tp = agg_df.index
|
|
143
|
+
mean_prec = agg_df['mean']
|
|
144
|
+
min_prec = agg_df['min']
|
|
145
|
+
max_prec = agg_df['max']
|
|
146
|
+
|
|
147
|
+
# Plot shading
|
|
148
|
+
ax.fill_between(tp, min_prec, max_prec, color='gray', alpha=0.3, label='Range (Min-Max)')
|
|
149
|
+
|
|
150
|
+
# Plot mean line
|
|
151
|
+
ax.plot(tp, mean_prec, c="black", label="Mean Precision", linewidth=line_width, alpha=0.9)
|
|
152
|
+
|
|
153
|
+
ax.set(title="",
|
|
154
|
+
xlabel="Number of True Positives (TP)",
|
|
155
|
+
ylabel="Precision")
|
|
156
|
+
ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False)
|
|
157
|
+
ax.set_ylim(0, 1)
|
|
158
|
+
|
|
159
|
+
# Nature style: no grid, open top/right spines
|
|
160
|
+
ax.grid(False)
|
|
161
|
+
ax.spines['top'].set_visible(False)
|
|
162
|
+
ax.spines['right'].set_visible(False)
|
|
163
|
+
|
|
164
|
+
if plot_config["save_plot"]:
|
|
165
|
+
output_type = plot_config["output_type"]
|
|
166
|
+
output_path = Path(config["output_folder"]) / f"aggregated_precision_recall_curve.{output_type}"
|
|
167
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
168
|
+
|
|
169
|
+
if plot_config.get("show_plot", True):
|
|
170
|
+
plt.show()
|
|
171
|
+
plt.close(fig)
|
|
172
|
+
|
|
173
|
+
def plot_iqr_pra(agg_df, line_width=2.0, hide_minor_ticks=True):
|
|
174
|
+
"""
|
|
175
|
+
Plots an aggregated Precision-Recall curve with mean line and IQR (25-75%) shading.
|
|
176
|
+
agg_df should be indexed by 'tp' and contain 'mean', '25%', '75%' columns for precision.
|
|
177
|
+
"""
|
|
178
|
+
config = dload("config")
|
|
179
|
+
plot_config = config["plotting"]
|
|
180
|
+
|
|
181
|
+
# Increase figure width to accommodate external legend without squashing axes
|
|
182
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
183
|
+
|
|
184
|
+
# Adjust layout to make room for legend on the right
|
|
185
|
+
plt.subplots_adjust(right=0.7)
|
|
186
|
+
|
|
187
|
+
ax.set_xscale("log")
|
|
188
|
+
|
|
189
|
+
# optionally hide minor ticks on the log axis
|
|
190
|
+
if hide_minor_ticks:
|
|
191
|
+
ax.xaxis.set_minor_locator(NullLocator())
|
|
192
|
+
ax.xaxis.set_minor_formatter(NullFormatter())
|
|
193
|
+
|
|
194
|
+
# Filter out very low TP counts
|
|
195
|
+
agg_df = agg_df[agg_df.index > 10]
|
|
196
|
+
|
|
197
|
+
tp = agg_df.index
|
|
198
|
+
mean_prec = agg_df['mean']
|
|
199
|
+
q25_prec = agg_df['25%']
|
|
200
|
+
q75_prec = agg_df['75%']
|
|
201
|
+
|
|
202
|
+
# Plot shading
|
|
203
|
+
ax.fill_between(tp, q25_prec, q75_prec, color='gray', alpha=0.3, label='IQR (25-75%)')
|
|
204
|
+
|
|
205
|
+
# Plot mean line
|
|
206
|
+
ax.plot(tp, mean_prec, c="black", label="Mean Precision", linewidth=line_width, alpha=0.9)
|
|
207
|
+
|
|
208
|
+
ax.set(title="Precision-Recall (IQR)",
|
|
209
|
+
xlabel="Number of True Positives (TP)",
|
|
210
|
+
ylabel="Precision")
|
|
211
|
+
ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False)
|
|
212
|
+
ax.set_ylim(0, 1)
|
|
213
|
+
|
|
214
|
+
# Nature style
|
|
215
|
+
ax.grid(False)
|
|
216
|
+
ax.spines['top'].set_visible(False)
|
|
217
|
+
ax.spines['right'].set_visible(False)
|
|
218
|
+
|
|
219
|
+
if plot_config["save_plot"]:
|
|
220
|
+
output_type = plot_config["output_type"]
|
|
221
|
+
output_path = Path(config["output_folder"]) / f"aggregated_iqr_precision_recall_curve.{output_type}"
|
|
222
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
223
|
+
|
|
224
|
+
if plot_config.get("show_plot", True):
|
|
225
|
+
plt.show()
|
|
226
|
+
plt.close(fig)
|
|
227
|
+
|
|
228
|
+
def plot_all_runs_pra(pra_list, mean_df=None, line_width=2.0, hide_minor_ticks=True):
|
|
229
|
+
"""
|
|
230
|
+
Plots all individual Precision-Recall curves faintly, with an optional mean line.
|
|
231
|
+
pra_list: list of dataframes (each with 'tp' and 'precision' columns) OR list of Series (if index is tp)
|
|
232
|
+
mean_df: optional dataframe with 'mean' column indexed by tp
|
|
233
|
+
"""
|
|
234
|
+
config = dload("config")
|
|
235
|
+
plot_config = config["plotting"]
|
|
236
|
+
|
|
237
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
238
|
+
plt.subplots_adjust(right=0.7)
|
|
239
|
+
|
|
240
|
+
ax.set_xscale("log")
|
|
241
|
+
|
|
242
|
+
if hide_minor_ticks:
|
|
243
|
+
ax.xaxis.set_minor_locator(NullLocator())
|
|
244
|
+
ax.xaxis.set_minor_formatter(NullFormatter())
|
|
245
|
+
|
|
246
|
+
# Plot individual lines
|
|
247
|
+
for i, df in enumerate(pra_list):
|
|
248
|
+
# Ensure we filter low TPs same as others
|
|
249
|
+
df_filtered = df[df['tp'] > 10] if 'tp' in df.columns else df[df.index > 10]
|
|
250
|
+
|
|
251
|
+
x = df_filtered['tp'] if 'tp' in df_filtered.columns else df_filtered.index
|
|
252
|
+
y = df_filtered['precision'] if 'precision' in df_filtered.columns else df_filtered.values
|
|
253
|
+
|
|
254
|
+
# Only add label for the first line to avoid cluttering legend
|
|
255
|
+
lbl = "Individual Runs" if i == 0 else None
|
|
256
|
+
ax.plot(x, y, c="gray", linewidth=0.5, alpha=0.3, label=lbl)
|
|
257
|
+
|
|
258
|
+
# Plot mean line if provided
|
|
259
|
+
if mean_df is not None:
|
|
260
|
+
mean_df = mean_df[mean_df.index > 10]
|
|
261
|
+
ax.plot(mean_df.index, mean_df['mean'], c="black", label="Mean Precision", linewidth=line_width, alpha=0.9)
|
|
262
|
+
|
|
263
|
+
ax.set(title="Precision-Recall (All Runs)",
|
|
264
|
+
xlabel="Number of True Positives (TP)",
|
|
265
|
+
ylabel="Precision")
|
|
266
|
+
ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), frameon=False)
|
|
267
|
+
ax.set_ylim(0, 1)
|
|
268
|
+
|
|
269
|
+
# Nature style
|
|
270
|
+
ax.grid(False)
|
|
271
|
+
ax.spines['top'].set_visible(False)
|
|
272
|
+
ax.spines['right'].set_visible(False)
|
|
273
|
+
|
|
274
|
+
if plot_config["save_plot"]:
|
|
275
|
+
output_type = plot_config["output_type"]
|
|
276
|
+
output_path = Path(config["output_folder"]) / f"aggregated_all_runs_precision_recall_curve.{output_type}"
|
|
277
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
278
|
+
|
|
279
|
+
if plot_config.get("show_plot", True):
|
|
280
|
+
plt.show()
|
|
281
|
+
plt.close(fig)
|
|
282
|
+
|
|
283
|
+
def plot_percomplex_scatter(
|
|
284
|
+
n_top=10,
|
|
285
|
+
sig_color='black',
|
|
286
|
+
nonsig_color='none',
|
|
287
|
+
label_color='black',
|
|
288
|
+
border_color='black',
|
|
289
|
+
border_width=1.0,
|
|
290
|
+
nonsig_border_color="#7F7F7F",
|
|
291
|
+
nonsig_border_width=0.5,
|
|
292
|
+
show_text_background=True,
|
|
293
|
+
):
|
|
294
|
+
config = dload("config")
|
|
295
|
+
plot_config = config["plotting"]
|
|
296
|
+
rdict = dload("pra_percomplex")
|
|
297
|
+
input_colors = dload("input", "colors")
|
|
298
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()} if input_colors else {}
|
|
299
|
+
|
|
300
|
+
if len(rdict) < 2:
|
|
301
|
+
log.warning(
|
|
302
|
+
"Skipping plot: at least two datasets are required for per-complex scatter plot."
|
|
303
|
+
)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
column_pairs = list(combinations(rdict.keys(), 2))
|
|
307
|
+
df = pd.DataFrame()
|
|
308
|
+
|
|
309
|
+
for i, (key, val) in enumerate(rdict.items()):
|
|
310
|
+
val = val.rename(columns={"auc_score": key})
|
|
311
|
+
if i == 0:
|
|
312
|
+
df = val.copy().drop(columns=["Genes", "Length", "used_genes"], errors="ignore")
|
|
313
|
+
else:
|
|
314
|
+
df = pd.concat([df, val[key]], axis=1)
|
|
315
|
+
|
|
316
|
+
for pair in column_pairs:
|
|
317
|
+
extreme_indices_0 = df[pair[0]].sort_values(ascending=False).head(n_top).index
|
|
318
|
+
extreme_indices_1 = df[pair[1]].sort_values(ascending=False).head(n_top).index
|
|
319
|
+
significant_indices = extreme_indices_0.union(extreme_indices_1)
|
|
320
|
+
significant_in_both = extreme_indices_0.intersection(extreme_indices_1)
|
|
321
|
+
significant_pair0_only = extreme_indices_0.difference(extreme_indices_1)
|
|
322
|
+
significant_pair1_only = extreme_indices_1.difference(extreme_indices_0)
|
|
323
|
+
|
|
324
|
+
bg_df = df.drop(index=significant_indices)
|
|
325
|
+
sig_df = df.loc[significant_indices]
|
|
326
|
+
sig_sizes = (
|
|
327
|
+
sig_df['n_used_genes']
|
|
328
|
+
if 'n_used_genes' in sig_df
|
|
329
|
+
else pd.Series(1, index=sig_df.index)
|
|
330
|
+
) * 8
|
|
331
|
+
|
|
332
|
+
# Create square figure
|
|
333
|
+
fig, ax = plt.subplots(figsize=(6, 6))
|
|
334
|
+
|
|
335
|
+
# Background cloud: non-significant complexes are open circles.
|
|
336
|
+
bg_sizes = (bg_df['n_used_genes'] if 'n_used_genes' in bg_df else pd.Series(1, index=bg_df.index)) * 5
|
|
337
|
+
ax.scatter(
|
|
338
|
+
bg_df[pair[0]], bg_df[pair[1]],
|
|
339
|
+
facecolors="none", edgecolors=nonsig_border_color,
|
|
340
|
+
s=bg_sizes, linewidth=nonsig_border_width, alpha=0.8,
|
|
341
|
+
zorder=0
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
def scatter_significant(indices, color, zorder=2):
|
|
345
|
+
if len(indices) == 0:
|
|
346
|
+
return
|
|
347
|
+
point_df = df.loc[indices]
|
|
348
|
+
point_sizes = (
|
|
349
|
+
point_df['n_used_genes']
|
|
350
|
+
if 'n_used_genes' in point_df
|
|
351
|
+
else pd.Series(1, index=point_df.index)
|
|
352
|
+
) * 8
|
|
353
|
+
ax.scatter(
|
|
354
|
+
point_df[pair[0]], point_df[pair[1]],
|
|
355
|
+
facecolors=color, edgecolors=color,
|
|
356
|
+
s=point_sizes, linewidth=border_width, zorder=zorder
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
# Dataset-specific significant complexes use the dataset input color.
|
|
360
|
+
scatter_significant(
|
|
361
|
+
significant_pair0_only,
|
|
362
|
+
input_colors.get(_sanitize(pair[0]), sig_color),
|
|
363
|
+
zorder=2,
|
|
364
|
+
)
|
|
365
|
+
scatter_significant(
|
|
366
|
+
significant_pair1_only,
|
|
367
|
+
input_colors.get(_sanitize(pair[1]), sig_color),
|
|
368
|
+
zorder=2,
|
|
369
|
+
)
|
|
370
|
+
# Complexes significant in both datasets stay black to avoid ambiguous color mixing.
|
|
371
|
+
scatter_significant(significant_in_both, "black", zorder=3)
|
|
372
|
+
|
|
373
|
+
# Improved label positioning with adaptive spacing
|
|
374
|
+
coords = sorted(
|
|
375
|
+
[(sig_df.loc[idx, pair[0]], sig_df.loc[idx, pair[1]], idx) for idx in sig_df.index],
|
|
376
|
+
key=lambda c: (-c[1], -c[0])
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
# Calculate proper parameters for normalized coordinate system (0-1 range)
|
|
380
|
+
max_y = 1.0 # Normalized plots use 0-1 range
|
|
381
|
+
scale_factor = 1.0 # Standard scaling for normalized plots
|
|
382
|
+
min_distance = 0.08 # Increased spacing for 0-1 range to avoid overlap
|
|
383
|
+
|
|
384
|
+
adjusted_coords = adjust_text_positions_improved(
|
|
385
|
+
coords, sig_sizes,
|
|
386
|
+
min_distance=min_distance,
|
|
387
|
+
max_y=max_y,
|
|
388
|
+
scale_factor=scale_factor,
|
|
389
|
+
y_threshold=0.8 # Points above this will have labels below
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
for x, adj_y, idx, direction in adjusted_coords:
|
|
393
|
+
y = df.loc[idx, pair[1]]
|
|
394
|
+
|
|
395
|
+
# Calculate connector line extension, but constrain within plot bounds
|
|
396
|
+
line_extension_factor = 1.5 # Reduced from 2.5 to keep labels in bounds
|
|
397
|
+
extended_adj_y = y + (adj_y - y) * line_extension_factor
|
|
398
|
+
|
|
399
|
+
# Clip to ensure connector stays within 0-1 range
|
|
400
|
+
extended_adj_y = max(0.02, min(extended_adj_y, 0.98))
|
|
401
|
+
|
|
402
|
+
# Draw connector line
|
|
403
|
+
ax.plot([x, x], [y, extended_adj_y],
|
|
404
|
+
color=label_color, linewidth=0.6, alpha=0.15, zorder=3)
|
|
405
|
+
|
|
406
|
+
# Position text at the end of extended line with small offset
|
|
407
|
+
text_y_offset = 0.01 if direction == "up" else -0.01
|
|
408
|
+
final_text_y = extended_adj_y + text_y_offset
|
|
409
|
+
|
|
410
|
+
# Final clip to ensure text stays within 0-1 range
|
|
411
|
+
final_text_y = max(0.02, min(final_text_y, 0.98))
|
|
412
|
+
|
|
413
|
+
# Prepare text bbox settings (can be turned on/off)
|
|
414
|
+
bbox_props = dict(facecolor="white", alpha=0.7, edgecolor="none", pad=1) if show_text_background else None
|
|
415
|
+
|
|
416
|
+
ax.text(
|
|
417
|
+
x, final_text_y,
|
|
418
|
+
df.loc[idx, 'Name'][:10] + '.' if len(df.loc[idx, 'Name']) > 10 else df.loc[idx, 'Name'],
|
|
419
|
+
fontsize=4,
|
|
420
|
+
ha='left',
|
|
421
|
+
va='bottom' if direction == "up" else 'top',
|
|
422
|
+
color=label_color,
|
|
423
|
+
linespacing=1,
|
|
424
|
+
zorder=4,
|
|
425
|
+
clip_on=True, # Enable clipping to axes bounds
|
|
426
|
+
bbox=bbox_props
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
# Diagonal & axes cosmetics
|
|
430
|
+
ax.plot([0, 1], [0, 1], linestyle='-', color='lightgray', alpha=0.4, linewidth=0.5, zorder=1)
|
|
431
|
+
|
|
432
|
+
# Force square aspect ratio and exact 0-1 range
|
|
433
|
+
ax.set_xlim(0, 1)
|
|
434
|
+
ax.set_ylim(0, 1)
|
|
435
|
+
ax.set_aspect('equal', adjustable='box')
|
|
436
|
+
|
|
437
|
+
# Set explicit ticks at 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
|
|
438
|
+
ticks = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
|
|
439
|
+
ax.set_xticks(ticks)
|
|
440
|
+
ax.set_yticks(ticks)
|
|
441
|
+
|
|
442
|
+
ax.set_xlabel(f"{pair[0]} PR-AUC score")
|
|
443
|
+
ax.set_ylabel(f"{pair[1]} PR-AUC score")
|
|
444
|
+
#ax.set_title(f"{pair[0]} vs {pair[1]} - Comparison of complex performance")
|
|
445
|
+
|
|
446
|
+
# Nature style: no grid, open top/right spines
|
|
447
|
+
ax.grid(False)
|
|
448
|
+
ax.spines['top'].set_visible(False)
|
|
449
|
+
ax.spines['right'].set_visible(False)
|
|
450
|
+
|
|
451
|
+
plt.tight_layout()
|
|
452
|
+
|
|
453
|
+
if plot_config["save_plot"]:
|
|
454
|
+
output_type = plot_config["output_type"]
|
|
455
|
+
output_path = Path(config["output_folder"]) / f"percomplex_scatter_{pair[0]}_vs_{pair[1]}.{output_type}"
|
|
456
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
457
|
+
|
|
458
|
+
if plot_config.get("show_plot", True):
|
|
459
|
+
plt.show()
|
|
460
|
+
|
|
461
|
+
plt.close(fig)
|
|
462
|
+
|
|
463
|
+
def adjust_text_positions_improved(coords, sizes, min_distance=0.08, max_y=1.0, scale_factor=1.0, y_threshold=0.8):
|
|
464
|
+
"""
|
|
465
|
+
Enhanced text positioning with improved logic:
|
|
466
|
+
- Points above y_threshold get labels below
|
|
467
|
+
- Points below y_threshold get labels above
|
|
468
|
+
- Better overlap detection and resolution
|
|
469
|
+
"""
|
|
470
|
+
adjusted = []
|
|
471
|
+
|
|
472
|
+
# Base offset for lines (increased even more for better visibility)
|
|
473
|
+
base_offset = 0.1 * scale_factor # Increased from 0.06 to 0.1
|
|
474
|
+
|
|
475
|
+
# Sort coords by Y position (highest first) then by X
|
|
476
|
+
coords_sorted = sorted(coords, key=lambda c: (-c[1], c[0]))
|
|
477
|
+
|
|
478
|
+
# Track occupied regions to prevent overlap
|
|
479
|
+
occupied_regions = []
|
|
480
|
+
|
|
481
|
+
for x, y, idx in coords_sorted:
|
|
482
|
+
# Determine direction based on Y position
|
|
483
|
+
if y > y_threshold:
|
|
484
|
+
direction = "down"
|
|
485
|
+
adj_y = y - base_offset
|
|
486
|
+
else:
|
|
487
|
+
direction = "up"
|
|
488
|
+
adj_y = y + base_offset
|
|
489
|
+
|
|
490
|
+
# Check for overlaps with existing labels
|
|
491
|
+
overlap_found = True
|
|
492
|
+
attempts = 0
|
|
493
|
+
max_attempts = 10
|
|
494
|
+
|
|
495
|
+
while overlap_found and attempts < max_attempts:
|
|
496
|
+
overlap_found = False
|
|
497
|
+
|
|
498
|
+
for occ_x, occ_y, occ_height in occupied_regions:
|
|
499
|
+
# Check if current label would overlap
|
|
500
|
+
x_overlap = abs(x - occ_x) < 0.15 # Horizontal proximity threshold
|
|
501
|
+
y_overlap = abs(adj_y - occ_y) < occ_height
|
|
502
|
+
|
|
503
|
+
if x_overlap and y_overlap:
|
|
504
|
+
overlap_found = True
|
|
505
|
+
# Adjust position to avoid overlap
|
|
506
|
+
if direction == "up":
|
|
507
|
+
adj_y = occ_y + occ_height + 0.02
|
|
508
|
+
else:
|
|
509
|
+
adj_y = occ_y - occ_height - 0.02
|
|
510
|
+
break
|
|
511
|
+
|
|
512
|
+
attempts += 1
|
|
513
|
+
|
|
514
|
+
# Ensure within bounds
|
|
515
|
+
if direction == "up":
|
|
516
|
+
adj_y = min(adj_y, max_y - 0.05)
|
|
517
|
+
adj_y = max(adj_y, y + base_offset)
|
|
518
|
+
else:
|
|
519
|
+
adj_y = max(adj_y, 0.05)
|
|
520
|
+
adj_y = min(adj_y, y - base_offset)
|
|
521
|
+
|
|
522
|
+
# Add to occupied regions (x, y, approximate height)
|
|
523
|
+
occupied_regions.append((x, adj_y, 0.04))
|
|
524
|
+
|
|
525
|
+
adjusted.append((x, adj_y, idx, direction))
|
|
526
|
+
|
|
527
|
+
return adjusted
|
|
528
|
+
|
|
529
|
+
# Alternative simplified version that groups nearby points
|
|
530
|
+
def adjust_text_positions_grouped(coords, sizes, min_distance=0.08, max_y=1.0, scale_factor=1.0, y_threshold=0.8):
|
|
531
|
+
"""
|
|
532
|
+
Group nearby points and stagger their labels to avoid overlap.
|
|
533
|
+
"""
|
|
534
|
+
adjusted = []
|
|
535
|
+
|
|
536
|
+
# Group points that are close together
|
|
537
|
+
groups = []
|
|
538
|
+
used = set()
|
|
539
|
+
|
|
540
|
+
for i, (x1, y1, idx1) in enumerate(coords):
|
|
541
|
+
if i in used:
|
|
542
|
+
continue
|
|
543
|
+
|
|
544
|
+
group = [(x1, y1, idx1)]
|
|
545
|
+
used.add(i)
|
|
546
|
+
|
|
547
|
+
# Find nearby points
|
|
548
|
+
for j, (x2, y2, idx2) in enumerate(coords[i+1:], i+1):
|
|
549
|
+
if j in used:
|
|
550
|
+
continue
|
|
551
|
+
|
|
552
|
+
# Check if points are close
|
|
553
|
+
if abs(x1 - x2) < 0.1 and abs(y1 - y2) < 0.1:
|
|
554
|
+
group.append((x2, y2, idx2))
|
|
555
|
+
used.add(j)
|
|
556
|
+
|
|
557
|
+
groups.append(group)
|
|
558
|
+
|
|
559
|
+
# Process each group
|
|
560
|
+
for group in groups:
|
|
561
|
+
if len(group) == 1:
|
|
562
|
+
# Single point - simple positioning
|
|
563
|
+
x, y, idx = group[0]
|
|
564
|
+
direction = "down" if y > y_threshold else "up"
|
|
565
|
+
base_offset = 0.06 * scale_factor
|
|
566
|
+
|
|
567
|
+
if direction == "up":
|
|
568
|
+
adj_y = y + base_offset
|
|
569
|
+
else:
|
|
570
|
+
adj_y = y - base_offset
|
|
571
|
+
|
|
572
|
+
adjusted.append((x, adj_y, idx, direction))
|
|
573
|
+
else:
|
|
574
|
+
# Multiple points - stagger them
|
|
575
|
+
group_sorted = sorted(group, key=lambda p: p[1], reverse=True)
|
|
576
|
+
|
|
577
|
+
for i, (x, y, idx) in enumerate(group_sorted):
|
|
578
|
+
direction = "down" if y > y_threshold else "up"
|
|
579
|
+
base_offset = 0.06 * scale_factor
|
|
580
|
+
stagger_offset = i * 0.04 * scale_factor
|
|
581
|
+
|
|
582
|
+
if direction == "up":
|
|
583
|
+
adj_y = y + base_offset + stagger_offset
|
|
584
|
+
else:
|
|
585
|
+
adj_y = y - base_offset - stagger_offset
|
|
586
|
+
|
|
587
|
+
# Ensure within bounds
|
|
588
|
+
adj_y = max(0.05, min(adj_y, max_y - 0.05))
|
|
589
|
+
|
|
590
|
+
adjusted.append((x, adj_y, idx, direction))
|
|
591
|
+
|
|
592
|
+
return adjusted
|
|
593
|
+
|
|
594
|
+
def smart_direction_assignment(point_y, y_max, min_safe_distance=20.0):
|
|
595
|
+
"""Determine the best direction for label placement based on Y position."""
|
|
596
|
+
lower_threshold = y_max / 3
|
|
597
|
+
upper_threshold = 2 * y_max / 3
|
|
598
|
+
|
|
599
|
+
if point_y < lower_threshold:
|
|
600
|
+
return "up_only"
|
|
601
|
+
elif point_y > upper_threshold:
|
|
602
|
+
return "prefer_down"
|
|
603
|
+
else:
|
|
604
|
+
return "both_directions"
|
|
605
|
+
|
|
606
|
+
def group_points_by_y_proximity(coords, y_tolerance=5.0):
|
|
607
|
+
"""Group points that have similar Y values (within tolerance)."""
|
|
608
|
+
groups = []
|
|
609
|
+
remaining_coords = coords.copy()
|
|
610
|
+
|
|
611
|
+
while remaining_coords:
|
|
612
|
+
# Start a new group with the first remaining point
|
|
613
|
+
seed_point = remaining_coords.pop(0)
|
|
614
|
+
current_group = [seed_point]
|
|
615
|
+
seed_y = seed_point[1]
|
|
616
|
+
|
|
617
|
+
# Find all points within Y tolerance of the seed point
|
|
618
|
+
i = 0
|
|
619
|
+
while i < len(remaining_coords):
|
|
620
|
+
if abs(remaining_coords[i][1] - seed_y) <= y_tolerance:
|
|
621
|
+
current_group.append(remaining_coords.pop(i))
|
|
622
|
+
else:
|
|
623
|
+
i += 1
|
|
624
|
+
|
|
625
|
+
groups.append(current_group)
|
|
626
|
+
|
|
627
|
+
return groups
|
|
628
|
+
|
|
629
|
+
def adjust_text_positions(coords, sizes, min_distance=0.08, max_y=1.0, scale_factor=1.0):
|
|
630
|
+
"""Enhanced text positioning with adaptive spacing for dense clusters."""
|
|
631
|
+
adjusted = []
|
|
632
|
+
|
|
633
|
+
# Fix scaling issues - use data coordinates, not pixel scaling
|
|
634
|
+
if max_y > 10: # For gene count plots (large Y values)
|
|
635
|
+
text_height = max_y * 0.02 # 2% of Y range
|
|
636
|
+
min_safe_distance = max_y * 0.05 # 5% of Y range
|
|
637
|
+
y_tolerance = max_y * 0.02 # 2% of Y range for grouping
|
|
638
|
+
else: # For normalized plots (Y values 0-1)
|
|
639
|
+
text_height = 0.04 * scale_factor
|
|
640
|
+
min_safe_distance = 20 * scale_factor
|
|
641
|
+
y_tolerance = 5 * scale_factor
|
|
642
|
+
|
|
643
|
+
# Group points by Y proximity
|
|
644
|
+
groups = group_points_by_y_proximity(coords, y_tolerance)
|
|
645
|
+
|
|
646
|
+
for group in groups:
|
|
647
|
+
group_size = len(group)
|
|
648
|
+
|
|
649
|
+
# Calculate adaptive spacing based on cluster density
|
|
650
|
+
density_multiplier = calculate_density_multiplier(group_size)
|
|
651
|
+
|
|
652
|
+
if group_size == 1:
|
|
653
|
+
# Single point - use original logic but with direction awareness
|
|
654
|
+
x, y, idx = group[0]
|
|
655
|
+
direction = smart_direction_assignment(y, max_y, min_safe_distance)
|
|
656
|
+
|
|
657
|
+
# Use reasonable base offset relative to Y range
|
|
658
|
+
if max_y > 10: # Gene count plots
|
|
659
|
+
base_offset = max(3, max_y * 0.03) # 3% of Y range, minimum 3 units
|
|
660
|
+
else: # Normalized plots
|
|
661
|
+
base_offset = np.sqrt(sizes.loc[idx]) * 0.04 * scale_factor if idx in sizes else 0.04 * scale_factor
|
|
662
|
+
|
|
663
|
+
if direction == "up_only" or direction == "both_directions":
|
|
664
|
+
adj_y = y + base_offset
|
|
665
|
+
elif direction == "prefer_down" and y - base_offset > min_safe_distance:
|
|
666
|
+
adj_y = y - base_offset
|
|
667
|
+
else:
|
|
668
|
+
adj_y = y + base_offset
|
|
669
|
+
|
|
670
|
+
# Ensure within bounds with proper limits
|
|
671
|
+
adj_y = max(min_safe_distance, min(adj_y, max_y - text_height))
|
|
672
|
+
|
|
673
|
+
# Additional safety check to prevent extreme values
|
|
674
|
+
if adj_y < 0 or adj_y > max_y * 1.2: # Allow 20% overflow for safety
|
|
675
|
+
adj_y = y + base_offset # Fallback to simple offset
|
|
676
|
+
|
|
677
|
+
adjusted.append((x, adj_y, idx))
|
|
678
|
+
|
|
679
|
+
else:
|
|
680
|
+
# Multiple points with similar Y - use adaptive distribution
|
|
681
|
+
group.sort(key=lambda p: p[0]) # Sort by X coordinate
|
|
682
|
+
|
|
683
|
+
# Determine available directions for this Y level
|
|
684
|
+
group_y = group[0][1] # All have similar Y, use first as representative
|
|
685
|
+
direction = smart_direction_assignment(group_y, max_y, min_safe_distance)
|
|
686
|
+
|
|
687
|
+
# Calculate adaptive spacing and base offset
|
|
688
|
+
adaptive_spacing = calculate_adaptive_spacing(
|
|
689
|
+
group_size, min_distance, text_height, max_y, density_multiplier
|
|
690
|
+
)
|
|
691
|
+
adaptive_base_offset = calculate_adaptive_base_offset(
|
|
692
|
+
group_size, max_y, scale_factor, density_multiplier
|
|
693
|
+
)
|
|
694
|
+
|
|
695
|
+
for i, (x, y, idx) in enumerate(group):
|
|
696
|
+
if direction == "up_only":
|
|
697
|
+
# Stack all labels upward with adaptive spacing
|
|
698
|
+
adj_y = y + adaptive_base_offset + (i * adaptive_spacing)
|
|
699
|
+
|
|
700
|
+
elif direction == "prefer_down":
|
|
701
|
+
# Alternate down and up with adaptive spacing
|
|
702
|
+
if i % 2 == 0 and y - adaptive_base_offset - (i//2 * adaptive_spacing) > min_safe_distance:
|
|
703
|
+
# Even indices go down
|
|
704
|
+
adj_y = y - adaptive_base_offset - (i//2 * adaptive_spacing)
|
|
705
|
+
else:
|
|
706
|
+
# Odd indices or insufficient space below - go up
|
|
707
|
+
up_level = (i//2) if i % 2 == 0 else ((i+1)//2)
|
|
708
|
+
adj_y = y + adaptive_base_offset + (up_level * adaptive_spacing)
|
|
709
|
+
|
|
710
|
+
else: # both_directions
|
|
711
|
+
# Alternate up and down with adaptive spacing
|
|
712
|
+
if i % 2 == 0:
|
|
713
|
+
# Even indices go up
|
|
714
|
+
adj_y = y + adaptive_base_offset + (i//2 * adaptive_spacing)
|
|
715
|
+
else:
|
|
716
|
+
# Odd indices go down (if safe)
|
|
717
|
+
potential_down = y - adaptive_base_offset - ((i+1)//2 * adaptive_spacing)
|
|
718
|
+
if potential_down > min_safe_distance:
|
|
719
|
+
adj_y = potential_down
|
|
720
|
+
else:
|
|
721
|
+
# Not safe to go down, stack upward instead
|
|
722
|
+
adj_y = y + adaptive_base_offset + (i//2 * adaptive_spacing)
|
|
723
|
+
|
|
724
|
+
# Final bounds check with stricter limits
|
|
725
|
+
adj_y = max(min_safe_distance, min(adj_y, max_y - text_height))
|
|
726
|
+
|
|
727
|
+
# Additional safety check to prevent extreme values
|
|
728
|
+
if adj_y < 0 or adj_y > max_y * 1.2: # Allow 20% overflow for safety
|
|
729
|
+
adj_y = y + adaptive_base_offset # Fallback to simple offset
|
|
730
|
+
|
|
731
|
+
adjusted.append((x, adj_y, idx))
|
|
732
|
+
|
|
733
|
+
return adjusted
|
|
734
|
+
|
|
735
|
+
def calculate_density_multiplier(group_size):
|
|
736
|
+
"""Calculate multiplier for spacing based on cluster density."""
|
|
737
|
+
if group_size <= 3:
|
|
738
|
+
return 1.0
|
|
739
|
+
elif group_size <= 6:
|
|
740
|
+
return 1.3
|
|
741
|
+
elif group_size <= 10:
|
|
742
|
+
return 1.6
|
|
743
|
+
elif group_size <= 15:
|
|
744
|
+
return 2.0
|
|
745
|
+
elif group_size <= 20:
|
|
746
|
+
return 2.5
|
|
747
|
+
else: # 20+ points
|
|
748
|
+
return 3.0 + (group_size - 20) * 0.1 # Progressive scaling for very dense clusters
|
|
749
|
+
|
|
750
|
+
def calculate_adaptive_spacing(group_size, min_distance, text_height, max_y, density_multiplier):
|
|
751
|
+
"""Calculate adaptive vertical spacing between labels based on cluster density."""
|
|
752
|
+
base_spacing = max(min_distance, text_height * 1.5)
|
|
753
|
+
|
|
754
|
+
# Scale spacing based on density and coordinate system
|
|
755
|
+
if max_y > 10: # Gene count plots
|
|
756
|
+
adaptive_spacing = base_spacing * density_multiplier * (max_y / 100.0)
|
|
757
|
+
# Ensure minimum readable spacing for dense clusters
|
|
758
|
+
adaptive_spacing = max(adaptive_spacing, max_y * 0.03)
|
|
759
|
+
else: # Normalized plots
|
|
760
|
+
adaptive_spacing = base_spacing * density_multiplier
|
|
761
|
+
# Ensure minimum readable spacing
|
|
762
|
+
adaptive_spacing = max(adaptive_spacing, 0.05)
|
|
763
|
+
|
|
764
|
+
return adaptive_spacing
|
|
765
|
+
|
|
766
|
+
def calculate_adaptive_base_offset(group_size, max_y, scale_factor, density_multiplier):
|
|
767
|
+
"""Calculate adaptive base offset (connector line height) based on cluster density."""
|
|
768
|
+
if max_y > 10: # Gene count plots
|
|
769
|
+
base_offset = max(3, max_y * 0.03)
|
|
770
|
+
# Increase connector line height for dense clusters
|
|
771
|
+
adaptive_offset = base_offset * density_multiplier
|
|
772
|
+
# Cap to reasonable maximum
|
|
773
|
+
adaptive_offset = min(adaptive_offset, max_y * 0.15)
|
|
774
|
+
else: # Normalized plots
|
|
775
|
+
base_offset = 0.04 * scale_factor
|
|
776
|
+
# Increase connector line height for dense clusters
|
|
777
|
+
adaptive_offset = base_offset * density_multiplier
|
|
778
|
+
# Cap to reasonable maximum
|
|
779
|
+
adaptive_offset = min(adaptive_offset, 0.2)
|
|
780
|
+
|
|
781
|
+
return adaptive_offset
|
|
782
|
+
|
|
783
|
+
def cluster_nearby_points(coords, cluster_threshold=0.1):
|
|
784
|
+
"""
|
|
785
|
+
Group nearby points into clusters to handle overlapping labels intelligently.
|
|
786
|
+
"""
|
|
787
|
+
clusters = []
|
|
788
|
+
used = set()
|
|
789
|
+
|
|
790
|
+
for i, (x1, y1, idx1) in enumerate(coords):
|
|
791
|
+
if i in used:
|
|
792
|
+
continue
|
|
793
|
+
|
|
794
|
+
cluster = [(x1, y1, idx1)]
|
|
795
|
+
used.add(i)
|
|
796
|
+
|
|
797
|
+
# Find all points within cluster threshold
|
|
798
|
+
for j, (x2, y2, idx2) in enumerate(coords[i+1:], i+1):
|
|
799
|
+
if j in used:
|
|
800
|
+
continue
|
|
801
|
+
|
|
802
|
+
# Calculate distance (normalized to data range)
|
|
803
|
+
x_dist = abs(x1 - x2) / 1.0 # X range is 0-1
|
|
804
|
+
y_dist = abs(y1 - y2) / max(coord[1] for coord in coords) # Y range varies
|
|
805
|
+
distance = np.sqrt(x_dist**2 + y_dist**2)
|
|
806
|
+
|
|
807
|
+
if distance < cluster_threshold:
|
|
808
|
+
cluster.append((x2, y2, idx2))
|
|
809
|
+
used.add(j)
|
|
810
|
+
|
|
811
|
+
clusters.append(cluster)
|
|
812
|
+
|
|
813
|
+
return clusters
|
|
814
|
+
|
|
815
|
+
def position_cluster_labels(cluster, cluster_id, max_y, effective_max_y, label_color, ax, top_labels, show_text_background):
|
|
816
|
+
"""
|
|
817
|
+
Position labels for a cluster of points using advanced anti-overlap strategies.
|
|
818
|
+
"""
|
|
819
|
+
cluster_size = len(cluster)
|
|
820
|
+
|
|
821
|
+
if cluster_size == 1:
|
|
822
|
+
# Single point - simple positioning
|
|
823
|
+
x, y, idx = cluster[0]
|
|
824
|
+
base_offset = max_y * 0.08
|
|
825
|
+
|
|
826
|
+
label_y = y + base_offset
|
|
827
|
+
if label_y > effective_max_y:
|
|
828
|
+
label_y = max(y - base_offset, max_y * 0.05)
|
|
829
|
+
|
|
830
|
+
connector_end = min(label_y, effective_max_y)
|
|
831
|
+
|
|
832
|
+
# Draw connector line
|
|
833
|
+
ax.plot([x, x], [y, connector_end],
|
|
834
|
+
color=label_color, linewidth=0.6, alpha=0.4, zorder=3)
|
|
835
|
+
|
|
836
|
+
# Position text
|
|
837
|
+
text_x = x + 0.02 if x < 0.7 else x - 0.02
|
|
838
|
+
ha = 'left' if x < 0.7 else 'right'
|
|
839
|
+
|
|
840
|
+
bbox_props = dict(facecolor="white", alpha=0.8, edgecolor="none", pad=1) if show_text_background else None
|
|
841
|
+
label_text = top_labels.loc[idx, 'Name'][:12] + '...' if len(top_labels.loc[idx, 'Name']) > 12 else top_labels.loc[idx, 'Name']
|
|
842
|
+
|
|
843
|
+
ax.text(
|
|
844
|
+
text_x, connector_end + (max_y * 0.01),
|
|
845
|
+
label_text,
|
|
846
|
+
fontsize=5, ha=ha, va='bottom',
|
|
847
|
+
color=label_color, zorder=4,
|
|
848
|
+
clip_on=True, bbox=bbox_props
|
|
849
|
+
)
|
|
850
|
+
|
|
851
|
+
elif cluster_size <= 3:
|
|
852
|
+
# Small cluster - vertical stacking with dynamic font size
|
|
853
|
+
cluster_center_x = np.mean([p[0] for p in cluster])
|
|
854
|
+
cluster_center_y = np.mean([p[1] for p in cluster])
|
|
855
|
+
|
|
856
|
+
base_offset = max_y * 0.1
|
|
857
|
+
font_size = 4 # Smaller font for clusters
|
|
858
|
+
|
|
859
|
+
for i, (x, y, idx) in enumerate(sorted(cluster, key=lambda p: p[1], reverse=True)):
|
|
860
|
+
# Stagger vertically with increased spacing
|
|
861
|
+
stagger = i * (max_y * 0.06) # Increased spacing
|
|
862
|
+
label_y = cluster_center_y + base_offset + stagger
|
|
863
|
+
|
|
864
|
+
if label_y > effective_max_y:
|
|
865
|
+
# Switch to downward stacking
|
|
866
|
+
label_y = cluster_center_y - base_offset - stagger
|
|
867
|
+
label_y = max(label_y, max_y * 0.05)
|
|
868
|
+
|
|
869
|
+
connector_end = min(label_y, effective_max_y)
|
|
870
|
+
|
|
871
|
+
# Draw connector line from original point
|
|
872
|
+
ax.plot([x, x], [y, connector_end],
|
|
873
|
+
color=label_color, linewidth=0.5, alpha=0.3, zorder=3)
|
|
874
|
+
|
|
875
|
+
# Position text with alternating sides to reduce overlap
|
|
876
|
+
side_offset = 0.03 if i % 2 == 0 else -0.03
|
|
877
|
+
text_x = cluster_center_x + side_offset
|
|
878
|
+
text_x = max(0.02, min(text_x, 0.98)) # Keep within bounds
|
|
879
|
+
|
|
880
|
+
ha = 'left' if side_offset > 0 else 'right'
|
|
881
|
+
|
|
882
|
+
bbox_props = dict(facecolor="white", alpha=0.9, edgecolor="none", pad=0.5) if show_text_background else None
|
|
883
|
+
label_text = top_labels.loc[idx, 'Name'][:10] + '.' if len(top_labels.loc[idx, 'Name']) > 10 else top_labels.loc[idx, 'Name']
|
|
884
|
+
|
|
885
|
+
ax.text(
|
|
886
|
+
text_x, connector_end + (max_y * 0.005),
|
|
887
|
+
label_text,
|
|
888
|
+
fontsize=font_size, ha=ha, va='bottom',
|
|
889
|
+
color=label_color, zorder=4,
|
|
890
|
+
clip_on=True, bbox=bbox_props
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
else:
|
|
894
|
+
# Large cluster - radial/column arrangement with smaller text
|
|
895
|
+
cluster_center_x = np.mean([p[0] for p in cluster])
|
|
896
|
+
cluster_center_y = np.mean([p[1] for p in cluster])
|
|
897
|
+
|
|
898
|
+
base_offset = max_y * 0.12
|
|
899
|
+
font_size = 3.5 # Even smaller font for dense clusters
|
|
900
|
+
|
|
901
|
+
# Arrange in two columns to handle many labels
|
|
902
|
+
left_column = cluster[:len(cluster)//2]
|
|
903
|
+
right_column = cluster[len(cluster)//2:]
|
|
904
|
+
|
|
905
|
+
for col_idx, column in enumerate([left_column, right_column]):
|
|
906
|
+
side = -1 if col_idx == 0 else 1 # Left or right side
|
|
907
|
+
|
|
908
|
+
for i, (x, y, idx) in enumerate(column):
|
|
909
|
+
# Calculate position for this column
|
|
910
|
+
stagger = i * (max_y * 0.05) # Vertical spacing
|
|
911
|
+
label_y = cluster_center_y + base_offset + stagger
|
|
912
|
+
|
|
913
|
+
if label_y > effective_max_y:
|
|
914
|
+
# Switch to downward if too high
|
|
915
|
+
label_y = cluster_center_y - base_offset - stagger
|
|
916
|
+
label_y = max(label_y, max_y * 0.05)
|
|
917
|
+
|
|
918
|
+
connector_end = min(label_y, effective_max_y)
|
|
919
|
+
|
|
920
|
+
# Draw connector line
|
|
921
|
+
ax.plot([x, x], [y, connector_end],
|
|
922
|
+
color=label_color, linewidth=0.4, alpha=0.25, zorder=3)
|
|
923
|
+
|
|
924
|
+
# Position text in columns
|
|
925
|
+
text_x = cluster_center_x + (side * 0.04) # Offset to left/right
|
|
926
|
+
text_x = max(0.02, min(text_x, 0.98)) # Keep within bounds
|
|
927
|
+
|
|
928
|
+
ha = 'right' if side < 0 else 'left'
|
|
929
|
+
|
|
930
|
+
bbox_props = dict(facecolor="white", alpha=0.95, edgecolor="none", pad=0.3) if show_text_background else None
|
|
931
|
+
label_text = top_labels.loc[idx, 'Name'][:8] + '.' if len(top_labels.loc[idx, 'Name']) > 8 else top_labels.loc[idx, 'Name']
|
|
932
|
+
|
|
933
|
+
ax.text(
|
|
934
|
+
text_x, connector_end,
|
|
935
|
+
label_text,
|
|
936
|
+
fontsize=font_size, ha=ha, va='bottom',
|
|
937
|
+
color=label_color, zorder=4,
|
|
938
|
+
clip_on=True, bbox=bbox_props
|
|
939
|
+
)
|
|
940
|
+
|
|
941
|
+
def plot_percomplex_scatter_bysize(
|
|
942
|
+
n_labels=10,
|
|
943
|
+
n_top=10,
|
|
944
|
+
sig_color='black',
|
|
945
|
+
nonsig_color='none',
|
|
946
|
+
label_color='black',
|
|
947
|
+
border_color='black',
|
|
948
|
+
border_width=1.0,
|
|
949
|
+
nonsig_border_color="#7F7F7F",
|
|
950
|
+
nonsig_border_width=0.5,
|
|
951
|
+
show_text_background=True,
|
|
952
|
+
):
|
|
953
|
+
config = dload("config")
|
|
954
|
+
plot_config = config["plotting"]
|
|
955
|
+
rdict = dload("pra_percomplex")
|
|
956
|
+
input_colors = dload("input", "colors")
|
|
957
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()} if input_colors else {}
|
|
958
|
+
|
|
959
|
+
for key, per_complex in rdict.items():
|
|
960
|
+
dataset_color = input_colors.get(_sanitize(key), sig_color)
|
|
961
|
+
sorted_pc = per_complex.sort_values(by="auc_score", ascending=False, na_position="last")
|
|
962
|
+
top_labels, rest = sorted_pc.head(n_labels), sorted_pc.iloc[n_labels:]
|
|
963
|
+
|
|
964
|
+
# Calculate data range for appropriate figure sizing
|
|
965
|
+
max_genes = sorted_pc.n_used_genes.max()
|
|
966
|
+
|
|
967
|
+
# Use rectangular figure with appropriate aspect ratio
|
|
968
|
+
# X-axis is 0-1, Y-axis varies based on gene count data
|
|
969
|
+
aspect_ratio = max_genes / 100.0 # Scale based on gene count range
|
|
970
|
+
fig_height = min(max(4, aspect_ratio), 8) # Between 4-8 inches
|
|
971
|
+
fig, ax = plt.subplots(figsize=(6, fig_height))
|
|
972
|
+
|
|
973
|
+
# Background: non-significant complexes are open circles.
|
|
974
|
+
ax.scatter(
|
|
975
|
+
rest.auc_score, rest.n_used_genes,
|
|
976
|
+
facecolors="none", edgecolors=nonsig_border_color,
|
|
977
|
+
linewidth=nonsig_border_width, s=rest.n_used_genes * 5,
|
|
978
|
+
alpha=0.8, label="Other Complexes",
|
|
979
|
+
zorder=0
|
|
980
|
+
)
|
|
981
|
+
|
|
982
|
+
# Top N/significant complexes are filled black circles.
|
|
983
|
+
ax.scatter(
|
|
984
|
+
top_labels.auc_score, top_labels.n_used_genes,
|
|
985
|
+
facecolors=dataset_color, edgecolors=dataset_color,
|
|
986
|
+
linewidth=border_width, s=top_labels.n_used_genes * 8,
|
|
987
|
+
label=f"Top {n_labels} AUC Scores", alpha=1.0, zorder=2
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
# Enhanced anti-overlap labeling system
|
|
991
|
+
coords = [(row.auc_score, row.n_used_genes, idx) for idx, row in top_labels.iterrows()]
|
|
992
|
+
max_y = sorted_pc.n_used_genes.max()
|
|
993
|
+
|
|
994
|
+
# Define plot boundaries with margins for text
|
|
995
|
+
plot_margin = max_y * 0.2 # Increased margin for complex layouts
|
|
996
|
+
effective_max_y = max_y + plot_margin
|
|
997
|
+
|
|
998
|
+
# Cluster nearby points
|
|
999
|
+
clusters = cluster_nearby_points(coords, cluster_threshold=0.15)
|
|
1000
|
+
|
|
1001
|
+
# Position labels for each cluster
|
|
1002
|
+
for i, cluster in enumerate(clusters):
|
|
1003
|
+
position_cluster_labels(
|
|
1004
|
+
cluster, i, max_y, effective_max_y,
|
|
1005
|
+
label_color, ax, top_labels, show_text_background
|
|
1006
|
+
)
|
|
1007
|
+
|
|
1008
|
+
# Set y-axis to show integer values only
|
|
1009
|
+
from matplotlib.ticker import MaxNLocator
|
|
1010
|
+
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
|
|
1011
|
+
ax.set_xlabel("PR-AUC score")
|
|
1012
|
+
ax.set_ylabel("Number of genes in the complex")
|
|
1013
|
+
|
|
1014
|
+
# Configure axes with proper boundaries
|
|
1015
|
+
ax.grid(visible=False, which='both', axis='both')
|
|
1016
|
+
ax.set_xlim(0, 1.0)
|
|
1017
|
+
ax.set_ylim(0, effective_max_y) # Use effective max to include label space
|
|
1018
|
+
|
|
1019
|
+
# Set explicit x-axis ticks at 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
|
|
1020
|
+
x_ticks = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]
|
|
1021
|
+
ax.set_xticks(x_ticks)
|
|
1022
|
+
|
|
1023
|
+
ax.spines['top'].set_visible(False)
|
|
1024
|
+
ax.spines['right'].set_visible(False)
|
|
1025
|
+
|
|
1026
|
+
# Manual spacing adjustment instead of tight_layout to avoid warnings
|
|
1027
|
+
plt.subplots_adjust(left=0.12, bottom=0.12, right=0.95, top=0.95)
|
|
1028
|
+
|
|
1029
|
+
if plot_config["save_plot"]:
|
|
1030
|
+
output_type = plot_config["output_type"]
|
|
1031
|
+
output_path = Path(config["output_folder"]) / f"percomplex_scatter_by_complexsize_{key}.{output_type}"
|
|
1032
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
1033
|
+
|
|
1034
|
+
if plot_config.get("show_plot", True):
|
|
1035
|
+
plt.show()
|
|
1036
|
+
plt.close(fig)
|
|
1037
|
+
|
|
1038
|
+
def plot_complex_contributions(
|
|
1039
|
+
min_pairs=10,
|
|
1040
|
+
min_precision_cutoff=0.5,
|
|
1041
|
+
num_complex_to_show=10,
|
|
1042
|
+
y_lim=None,
|
|
1043
|
+
fig_title=None,
|
|
1044
|
+
fig_labs=['Fraction of TP', 'Precision'],
|
|
1045
|
+
legend_rows=3, # <— NEW: rows for legend layout (try 3 or 4)
|
|
1046
|
+
):
|
|
1047
|
+
config = dload("config")
|
|
1048
|
+
plot_config = config["plotting"]
|
|
1049
|
+
plot_data_dict = dload("complex_contributions")
|
|
1050
|
+
|
|
1051
|
+
for key, plot_data in plot_data_dict.items():
|
|
1052
|
+
s = plot_data.set_index('Name').sum()
|
|
1053
|
+
find_last_precision = s[s > min_pairs].index[-1]
|
|
1054
|
+
last_prec_value = float(find_last_precision.split('_')[1])
|
|
1055
|
+
|
|
1056
|
+
plot_data = plot_data.drop_duplicates(subset='Name')
|
|
1057
|
+
cont_stepwise_anno = plot_data['Name']
|
|
1058
|
+
cont_stepwise_mat = plot_data.drop(columns=['Name'])
|
|
1059
|
+
tmp_TP = cont_stepwise_mat.sum(axis=0)
|
|
1060
|
+
Precision_ind = (tmp_TP >= min_pairs)
|
|
1061
|
+
cont_stepwise_mat = cont_stepwise_mat.loc[:, Precision_ind]
|
|
1062
|
+
tmp = cont_stepwise_mat.columns
|
|
1063
|
+
y = np.array([float(col.split('_')[1]) if isinstance(col, str) and '_' in col else col for col in tmp])
|
|
1064
|
+
x = cont_stepwise_mat.sum(axis=0)
|
|
1065
|
+
mx, nx = cont_stepwise_mat.shape[0], cont_stepwise_mat.shape[1]
|
|
1066
|
+
tmp = np.tile(x, (mx, 1))
|
|
1067
|
+
x = cont_stepwise_mat.values / tmp
|
|
1068
|
+
x_df = pd.DataFrame(x, index=cont_stepwise_anno, columns=cont_stepwise_mat.columns)
|
|
1069
|
+
|
|
1070
|
+
ind_for_mean = y >= (last_prec_value - min_precision_cutoff)
|
|
1071
|
+
if sum(ind_for_mean) == 0:
|
|
1072
|
+
log.info("No values above 'min.precision.cutoff'"); return False
|
|
1073
|
+
if sum(ind_for_mean) == 1:
|
|
1074
|
+
log.info("Only one value above 'min.precision.cutoff'"); return False
|
|
1075
|
+
|
|
1076
|
+
a = x_df.loc[:, ind_for_mean].mean(axis=1).sort_values()[-num_complex_to_show:]
|
|
1077
|
+
subset = x_df.loc[a.index, :]
|
|
1078
|
+
|
|
1079
|
+
cmap = plt.get_cmap()
|
|
1080
|
+
colors = cmap(np.linspace(0, 1, num_complex_to_show))
|
|
1081
|
+
colors = np.vstack(([0.5, 0.5, 0.5, 1.0], colors)) # 'others' + top K
|
|
1082
|
+
others = pd.DataFrame(1 - subset.sum(axis=0), columns=['others']).T
|
|
1083
|
+
merged = pd.concat([others, subset], ignore_index=False)
|
|
1084
|
+
X = merged.to_numpy()
|
|
1085
|
+
x1 = np.zeros_like(X); x2 = np.zeros_like(X)
|
|
1086
|
+
for i in range(X.shape[0]):
|
|
1087
|
+
if i == 0:
|
|
1088
|
+
x2[i, :] = X[0, :]
|
|
1089
|
+
elif i == 1:
|
|
1090
|
+
x1[i, :] = X[0, :]
|
|
1091
|
+
else:
|
|
1092
|
+
x1[i, :] = X[:i, :].sum(axis=0)
|
|
1093
|
+
if i > 0:
|
|
1094
|
+
x2[i, :] = X[:i + 1, :].sum(axis=0)
|
|
1095
|
+
|
|
1096
|
+
padding = 0.02
|
|
1097
|
+
lower = max(0, min(y) - padding)
|
|
1098
|
+
upper = last_prec_value + padding
|
|
1099
|
+
y_lim = (lower, upper)
|
|
1100
|
+
|
|
1101
|
+
# Give legend a bit more room
|
|
1102
|
+
fig, ax = plt.subplots(2, 1, gridspec_kw={'height_ratios': [5, 1.8]})
|
|
1103
|
+
ax[0].set_xlim(0, 1)
|
|
1104
|
+
ax[0].set_ylim(*y_lim)
|
|
1105
|
+
ax[0].set_xlabel(fig_labs[0])
|
|
1106
|
+
ax[0].set_ylabel(fig_labs[1])
|
|
1107
|
+
#ax[0].set_title(fig_title if fig_title else f"{key} - Contribution of complexes")
|
|
1108
|
+
for i in range(X.shape[0]):
|
|
1109
|
+
ax[0].fill_betweenx(y, x1[i, :], x2[i, :], color=colors[i], edgecolor='white')
|
|
1110
|
+
|
|
1111
|
+
# Legend: multi-row, constrained to width
|
|
1112
|
+
def _short(s, n=14): return (s[:n-1] + '…') if len(s) > n else s
|
|
1113
|
+
labels = [_short(lbl) for lbl in merged.index]
|
|
1114
|
+
handles = [patches.Patch(color=colors[i], label=labels[i]) for i in range(len(labels))]
|
|
1115
|
+
ax[1].axis('off')
|
|
1116
|
+
n_items = len(handles)
|
|
1117
|
+
ncols = int(np.ceil(n_items / max(1, legend_rows))) # spread across rows
|
|
1118
|
+
ax[1].legend(
|
|
1119
|
+
handles=handles,
|
|
1120
|
+
loc='center',
|
|
1121
|
+
ncol=ncols,
|
|
1122
|
+
frameon=False,
|
|
1123
|
+
title="Complexes",
|
|
1124
|
+
fontsize=6, title_fontsize=6,
|
|
1125
|
+
handlelength=0.9, handletextpad=0.25,
|
|
1126
|
+
borderaxespad=0.0,
|
|
1127
|
+
labelspacing=0.25, columnspacing=0.6,
|
|
1128
|
+
mode='expand'
|
|
1129
|
+
)
|
|
1130
|
+
|
|
1131
|
+
plt.tight_layout()
|
|
1132
|
+
|
|
1133
|
+
if plot_config["save_plot"]:
|
|
1134
|
+
output_type = plot_config["output_type"]
|
|
1135
|
+
output_folder= Path(config["output_folder"])
|
|
1136
|
+
output_path = output_folder / f"complex_contributions_{key}.{output_type}"
|
|
1137
|
+
fig.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
1138
|
+
|
|
1139
|
+
if plot_config.get("show_plot", True):
|
|
1140
|
+
plt.show()
|
|
1141
|
+
plt.close(fig)
|
|
1142
|
+
|
|
1143
|
+
def plot_significant_complexes():
|
|
1144
|
+
config = dload("config")
|
|
1145
|
+
plot_config = config["plotting"]
|
|
1146
|
+
pra_percomplex = dload("pra_percomplex")
|
|
1147
|
+
input_colors = dload("input", "colors")
|
|
1148
|
+
|
|
1149
|
+
# Sanitize color keys
|
|
1150
|
+
if input_colors:
|
|
1151
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
1152
|
+
|
|
1153
|
+
thresholds = [0.1, 0.2, 0.3, 0.4, 0.5]
|
|
1154
|
+
if not isinstance(pra_percomplex, dict) or not pra_percomplex:
|
|
1155
|
+
log.warning("No per-complex PRA data found. Run pra_percomplex() first.")
|
|
1156
|
+
return pd.DataFrame(index=thresholds)
|
|
1157
|
+
|
|
1158
|
+
datasets = list(pra_percomplex.keys())
|
|
1159
|
+
num_datasets = len(datasets)
|
|
1160
|
+
|
|
1161
|
+
if num_datasets == 0:
|
|
1162
|
+
return pd.DataFrame(index=thresholds)
|
|
1163
|
+
|
|
1164
|
+
df = pd.DataFrame(index=thresholds)
|
|
1165
|
+
for key, complex_data in pra_percomplex.items():
|
|
1166
|
+
if "corrected_auc_score" in complex_data.columns:
|
|
1167
|
+
score_col = "corrected_auc_score"
|
|
1168
|
+
else:
|
|
1169
|
+
score_col = "auc_score"
|
|
1170
|
+
|
|
1171
|
+
df[key] = [complex_data.query(f'{score_col} >= {t}').shape[0] for t in thresholds]
|
|
1172
|
+
|
|
1173
|
+
fig, ax = plt.subplots()
|
|
1174
|
+
|
|
1175
|
+
# Color logic
|
|
1176
|
+
cmap_name = config.get("color_map", "tab10")
|
|
1177
|
+
try:
|
|
1178
|
+
cmap = get_cmap(cmap_name)
|
|
1179
|
+
except ValueError:
|
|
1180
|
+
cmap = get_cmap("tab10")
|
|
1181
|
+
|
|
1182
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
1183
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
1184
|
+
else:
|
|
1185
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
1186
|
+
|
|
1187
|
+
bar_width = 0.8 / num_datasets
|
|
1188
|
+
for i, dataset in enumerate(datasets):
|
|
1189
|
+
# Use override color if available
|
|
1190
|
+
color = input_colors.get(dataset) if input_colors else None
|
|
1191
|
+
if color is None:
|
|
1192
|
+
color = default_colors[i]
|
|
1193
|
+
|
|
1194
|
+
x = np.arange(len(thresholds)) + i * bar_width
|
|
1195
|
+
ax.bar(x, df[dataset], width=bar_width, color=color, edgecolor='black', label=dataset)
|
|
1196
|
+
|
|
1197
|
+
ax.set_xticks(np.arange(len(thresholds)) + (num_datasets - 1) * bar_width / 2)
|
|
1198
|
+
ax.set_xticklabels([str(t) for t in thresholds], rotation=0, ha='center')
|
|
1199
|
+
|
|
1200
|
+
#ax.set_title("Number of significant complexes above PR-AUC thresholds")
|
|
1201
|
+
ax.set_xlabel("PR-AUC score thresholds")
|
|
1202
|
+
ax.set_ylabel("Number of complexes")
|
|
1203
|
+
|
|
1204
|
+
# Nature style: no grid; open top/right spines
|
|
1205
|
+
ax.grid(False)
|
|
1206
|
+
for spine in ('right', 'top'):
|
|
1207
|
+
ax.spines[spine].set_visible(False)
|
|
1208
|
+
|
|
1209
|
+
ax.legend(loc='upper right', frameon=False)
|
|
1210
|
+
plt.tight_layout()
|
|
1211
|
+
|
|
1212
|
+
if plot_config["save_plot"]:
|
|
1213
|
+
output_type = plot_config["output_type"]
|
|
1214
|
+
output_folder = Path(config["output_folder"])
|
|
1215
|
+
output_path = output_folder / f"number_of_significant_complexes.{output_type}"
|
|
1216
|
+
plt.savefig(output_path, bbox_inches='tight', format=output_type)
|
|
1217
|
+
|
|
1218
|
+
if plot_config.get("show_plot", True):
|
|
1219
|
+
plt.show()
|
|
1220
|
+
|
|
1221
|
+
plt.close(fig)
|
|
1222
|
+
return df
|
|
1223
|
+
|
|
1224
|
+
def plot_auc_scores():
|
|
1225
|
+
config = dload("config")
|
|
1226
|
+
plot_config = config["plotting"]
|
|
1227
|
+
pra_dict = dload("pr_auc")
|
|
1228
|
+
input_colors = dload("input", "colors")
|
|
1229
|
+
|
|
1230
|
+
# Sanitize color keys
|
|
1231
|
+
if input_colors:
|
|
1232
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
1233
|
+
|
|
1234
|
+
sorted_items = sorted(pra_dict.items(), key=lambda x: x[1], reverse=True)
|
|
1235
|
+
datasets = [k for k, _ in sorted_items]
|
|
1236
|
+
auc_scores = [v for _, v in sorted_items]
|
|
1237
|
+
|
|
1238
|
+
fig, ax = plt.subplots()
|
|
1239
|
+
|
|
1240
|
+
# Color logic
|
|
1241
|
+
cmap_name = config.get("color_map", "tab10")
|
|
1242
|
+
try:
|
|
1243
|
+
cmap = get_cmap(cmap_name)
|
|
1244
|
+
except ValueError:
|
|
1245
|
+
cmap = get_cmap("tab10")
|
|
1246
|
+
|
|
1247
|
+
num_datasets = len(datasets)
|
|
1248
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
1249
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
1250
|
+
else:
|
|
1251
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
1252
|
+
|
|
1253
|
+
# Assign colors strictly matching the sorted dataset order
|
|
1254
|
+
final_colors = []
|
|
1255
|
+
for i, dataset in enumerate(datasets):
|
|
1256
|
+
color = input_colors.get(dataset) if input_colors else None
|
|
1257
|
+
if color is None:
|
|
1258
|
+
color = default_colors[i]
|
|
1259
|
+
final_colors.append(color)
|
|
1260
|
+
|
|
1261
|
+
ax.bar(datasets, auc_scores, color=final_colors, edgecolor="black")
|
|
1262
|
+
|
|
1263
|
+
ax.set_ylim(0, max(auc_scores) + 0.01)
|
|
1264
|
+
#ax.set_title("AUC scores for the datasets")
|
|
1265
|
+
ax.set_ylabel("AUC score")
|
|
1266
|
+
plt.xticks(rotation=45, ha="right")
|
|
1267
|
+
|
|
1268
|
+
# Hard-disable any grid/ruler
|
|
1269
|
+
ax.grid(visible=False, which='both', axis='both')
|
|
1270
|
+
ax.set_axisbelow(False) # make sure nothing faint is drawn beneath
|
|
1271
|
+
# Open spines
|
|
1272
|
+
ax.spines['top'].set_visible(False)
|
|
1273
|
+
ax.spines['right'].set_visible(False)
|
|
1274
|
+
|
|
1275
|
+
if plot_config["save_plot"]:
|
|
1276
|
+
output_type = plot_config["output_type"]
|
|
1277
|
+
output_folder = Path(config["output_folder"])
|
|
1278
|
+
output_folder.mkdir(parents=True, exist_ok=True)
|
|
1279
|
+
output_path = output_folder / f"prauc_scores.{output_type}"
|
|
1280
|
+
plt.savefig(output_path, bbox_inches='tight', format=output_type)
|
|
1281
|
+
|
|
1282
|
+
if plot_config.get("show_plot", True):
|
|
1283
|
+
plt.show()
|
|
1284
|
+
|
|
1285
|
+
plt.close(fig)
|
|
1286
|
+
return pra_dict
|
|
1287
|
+
|
|
1288
|
+
|
|
1289
|
+
def plot_mpr_complex_auc_scores(variant: str = "unfiltered", save=None, outname=None):
|
|
1290
|
+
"""Plot AUC scores for the mPR complexes curve (Fig 1F-style).
|
|
1291
|
+
|
|
1292
|
+
Requires `mpr_prepare()` to have been run for each dataset.
|
|
1293
|
+
|
|
1294
|
+
Parameters
|
|
1295
|
+
----------
|
|
1296
|
+
variant : str
|
|
1297
|
+
One of: "unfiltered", "without_mt_ribo_etci",
|
|
1298
|
+
"without_small_high_auprc".
|
|
1299
|
+
save : bool, optional
|
|
1300
|
+
Whether to save the figure. If None, uses config["plotting"]["save_plot"].
|
|
1301
|
+
outname : str, optional
|
|
1302
|
+
Output filename. If None, auto-generated.
|
|
1303
|
+
|
|
1304
|
+
Returns
|
|
1305
|
+
-------
|
|
1306
|
+
pd.Series
|
|
1307
|
+
AUC values indexed by dataset name (sorted descending).
|
|
1308
|
+
"""
|
|
1309
|
+
config = dload("config")
|
|
1310
|
+
plot_config = config["plotting"]
|
|
1311
|
+
mpr_auc_dict = dload("mpr_complexes_auc")
|
|
1312
|
+
input_colors = dload("input", "colors")
|
|
1313
|
+
|
|
1314
|
+
if input_colors:
|
|
1315
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
1316
|
+
|
|
1317
|
+
if not isinstance(mpr_auc_dict, dict) or not mpr_auc_dict:
|
|
1318
|
+
log.warning(
|
|
1319
|
+
"No mPR complexes AUC data found. Run mpr_prepare() first (it stores 'mpr_complexes_auc')."
|
|
1320
|
+
)
|
|
1321
|
+
return pd.Series(dtype=float)
|
|
1322
|
+
|
|
1323
|
+
variant_key = _normalize_mpr_variant(variant)
|
|
1324
|
+
|
|
1325
|
+
# Build Series: dataset -> auc
|
|
1326
|
+
auc_by_dataset = {}
|
|
1327
|
+
for dataset, per_filter in mpr_auc_dict.items():
|
|
1328
|
+
if not isinstance(per_filter, dict):
|
|
1329
|
+
continue
|
|
1330
|
+
val = per_filter.get(variant_key)
|
|
1331
|
+
if val is None:
|
|
1332
|
+
continue
|
|
1333
|
+
try:
|
|
1334
|
+
auc_by_dataset[dataset] = float(val)
|
|
1335
|
+
except (TypeError, ValueError):
|
|
1336
|
+
continue
|
|
1337
|
+
|
|
1338
|
+
if not auc_by_dataset:
|
|
1339
|
+
log.warning(
|
|
1340
|
+
f"No mPR complex AUC scores found for variant '{variant}'. "
|
|
1341
|
+
f"Available variants: {list(PUBLIC_MPR_VARIANTS.keys())}"
|
|
1342
|
+
)
|
|
1343
|
+
return pd.Series(dtype=float)
|
|
1344
|
+
|
|
1345
|
+
s = pd.Series(auc_by_dataset).sort_values(ascending=False)
|
|
1346
|
+
datasets = list(s.index)
|
|
1347
|
+
auc_scores = list(s.values)
|
|
1348
|
+
|
|
1349
|
+
fig, ax = plt.subplots()
|
|
1350
|
+
|
|
1351
|
+
# Color logic (match other bar plots)
|
|
1352
|
+
cmap_name = config.get("color_map", "tab10")
|
|
1353
|
+
try:
|
|
1354
|
+
cmap = get_cmap(cmap_name)
|
|
1355
|
+
except ValueError:
|
|
1356
|
+
cmap = get_cmap("tab10")
|
|
1357
|
+
|
|
1358
|
+
num_datasets = len(datasets)
|
|
1359
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
1360
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
1361
|
+
else:
|
|
1362
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
1363
|
+
|
|
1364
|
+
final_colors = []
|
|
1365
|
+
for i, dataset in enumerate(datasets):
|
|
1366
|
+
color = input_colors.get(dataset) if input_colors else None
|
|
1367
|
+
if color is None:
|
|
1368
|
+
color = default_colors[i]
|
|
1369
|
+
final_colors.append(color)
|
|
1370
|
+
|
|
1371
|
+
ax.bar(datasets, auc_scores, color=final_colors, edgecolor="black")
|
|
1372
|
+
|
|
1373
|
+
ymax = max([v for v in auc_scores if np.isfinite(v)], default=0.0)
|
|
1374
|
+
ax.set_ylim(0, ymax + 0.01)
|
|
1375
|
+
ax.set_ylabel("mPR complexes AUC")
|
|
1376
|
+
plt.xticks(rotation=45, ha="right")
|
|
1377
|
+
|
|
1378
|
+
# Styling consistent with other plots
|
|
1379
|
+
ax.grid(visible=False, which="both", axis="both")
|
|
1380
|
+
ax.set_axisbelow(False)
|
|
1381
|
+
ax.spines["top"].set_visible(False)
|
|
1382
|
+
ax.spines["right"].set_visible(False)
|
|
1383
|
+
|
|
1384
|
+
should_save = plot_config.get("save_plot", False) if save is None else bool(save)
|
|
1385
|
+
if should_save:
|
|
1386
|
+
output_type = plot_config.get("output_type", "pdf")
|
|
1387
|
+
output_folder = Path(config["output_folder"])
|
|
1388
|
+
output_folder.mkdir(parents=True, exist_ok=True)
|
|
1389
|
+
if outname is None:
|
|
1390
|
+
outname = f"mpr_complexes_auc_{variant_key}.{output_type}"
|
|
1391
|
+
output_path = Path(outname)
|
|
1392
|
+
if len(output_path.parts) == 1:
|
|
1393
|
+
output_path = output_folder / outname
|
|
1394
|
+
plt.savefig(output_path, bbox_inches="tight", format=output_type)
|
|
1395
|
+
|
|
1396
|
+
if plot_config.get("show_plot", True):
|
|
1397
|
+
plt.show()
|
|
1398
|
+
|
|
1399
|
+
plt.close(fig)
|
|
1400
|
+
return s
|
|
1401
|
+
|
|
1402
|
+
|
|
1403
|
+
def plot_mpr_complexes_auc_scores(filter_key: str = "all"):
|
|
1404
|
+
"""Backward-compatible wrapper for plot_mpr_complex_auc_scores()."""
|
|
1405
|
+
return plot_mpr_complex_auc_scores(
|
|
1406
|
+
variant=_legacy_filter_to_variant(filter_key, default="unfiltered")
|
|
1407
|
+
)
|
|
1408
|
+
|
|
1409
|
+
# -----------------------------------------------------------------------------
|
|
1410
|
+
# mPR plots (Fig. 1E and Fig. 1F)
|
|
1411
|
+
# -----------------------------------------------------------------------------
|
|
1412
|
+
|
|
1413
|
+
def plot_mpr_complexes(name, ax=None, save=True, outname=None):
|
|
1414
|
+
"""
|
|
1415
|
+
Fig. 1F-style module-level PR:
|
|
1416
|
+
x-axis: number of covered complexes (log)
|
|
1417
|
+
y-axis: precision cutoff
|
|
1418
|
+
x tick labels: 0, 2, 20, 200
|
|
1419
|
+
"""
|
|
1420
|
+
mpr = dload("mpr", name)
|
|
1421
|
+
if mpr is None:
|
|
1422
|
+
raise RuntimeError(
|
|
1423
|
+
f"plot_mpr_complexes(): mPR data for dataset '{name}' not found. "
|
|
1424
|
+
"Run `mpr_prepare` first."
|
|
1425
|
+
)
|
|
1426
|
+
|
|
1427
|
+
precision_cutoffs = np.asarray(mpr["precision_cutoffs"], dtype=float)
|
|
1428
|
+
coverage = mpr["coverage_curves"]
|
|
1429
|
+
|
|
1430
|
+
if ax is None:
|
|
1431
|
+
fig, ax = plt.subplots(figsize=(4, 4))
|
|
1432
|
+
else:
|
|
1433
|
+
fig = ax.figure
|
|
1434
|
+
|
|
1435
|
+
labels = [
|
|
1436
|
+
("all", "all data"),
|
|
1437
|
+
("no_mtRibo_ETCI", "no mtRibo, ETC I"),
|
|
1438
|
+
("no_small_highAUPRC", "no small, high AUPRC"),
|
|
1439
|
+
]
|
|
1440
|
+
styles = {
|
|
1441
|
+
"all": {"linewidth": 1.8},
|
|
1442
|
+
"no_mtRibo_ETCI": {"linewidth": 1.8, "linestyle": "--"},
|
|
1443
|
+
"no_small_highAUPRC": {"linewidth": 1.8, "linestyle": ":"},
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
for key, pretty in labels:
|
|
1447
|
+
if key not in coverage:
|
|
1448
|
+
continue
|
|
1449
|
+
cov = np.asarray(coverage[key], dtype=float)
|
|
1450
|
+
|
|
1451
|
+
# keep only positive coverage up to 200 complexes
|
|
1452
|
+
mask = (cov > 0) & (cov <= 200)
|
|
1453
|
+
if not mask.any():
|
|
1454
|
+
continue
|
|
1455
|
+
|
|
1456
|
+
cov_plot = cov[mask]
|
|
1457
|
+
prec_plot = precision_cutoffs[mask]
|
|
1458
|
+
|
|
1459
|
+
ax.plot(cov_plot, prec_plot, label=pretty, **styles.get(key, {}))
|
|
1460
|
+
|
|
1461
|
+
# log x-axis, show up to 200 complexes
|
|
1462
|
+
ax.set_xscale("log")
|
|
1463
|
+
ax.set_xlim(1, 200) # 1 on log scale will be labelled as "0" below
|
|
1464
|
+
|
|
1465
|
+
ax.set_xlabel("Number of covered complexes")
|
|
1466
|
+
ax.set_ylabel("Precision cutoff")
|
|
1467
|
+
ax.set_ylim(0.0, 1.05)
|
|
1468
|
+
|
|
1469
|
+
# ticks at positions 1, 2, 20, 200 with labels 0, 2, 20, 200
|
|
1470
|
+
tick_positions = [1, 2, 20, 200]
|
|
1471
|
+
tick_labels = ["0", "2", "20", "200"]
|
|
1472
|
+
ax.set_xticks(tick_positions)
|
|
1473
|
+
ax.set_xticklabels(tick_labels)
|
|
1474
|
+
|
|
1475
|
+
ax.legend(frameon=False)
|
|
1476
|
+
ax.set_title(f"[{name}] 19Q2 – mPR (#complexes vs precision)")
|
|
1477
|
+
|
|
1478
|
+
if save:
|
|
1479
|
+
if outname is None:
|
|
1480
|
+
outname = f"mpr_complexes_{name}.pdf"
|
|
1481
|
+
fig.tight_layout()
|
|
1482
|
+
fig.savefig(outname)
|
|
1483
|
+
|
|
1484
|
+
return ax
|
|
1485
|
+
|
|
1486
|
+
def plot_mpr_tp(name, ax=None, save=True, outname=None):
|
|
1487
|
+
"""
|
|
1488
|
+
Plot Fig. 1E-style TP vs precision curves for a dataset.
|
|
1489
|
+
|
|
1490
|
+
Uses the object created by `mpr_prepare(name)` and stored with key 'mpr'.
|
|
1491
|
+
"""
|
|
1492
|
+
mpr = dload("mpr", name)
|
|
1493
|
+
if mpr is None:
|
|
1494
|
+
raise RuntimeError(
|
|
1495
|
+
f"plot_mpr_tp(): mPR data for dataset '{name}' not found. "
|
|
1496
|
+
"Run `mpr_prepare` first."
|
|
1497
|
+
)
|
|
1498
|
+
|
|
1499
|
+
tp_curves = mpr["tp_curves"]
|
|
1500
|
+
|
|
1501
|
+
if ax is None:
|
|
1502
|
+
fig, ax = plt.subplots(figsize=(4, 4))
|
|
1503
|
+
else:
|
|
1504
|
+
fig = ax.figure
|
|
1505
|
+
|
|
1506
|
+
labels = [
|
|
1507
|
+
("all", "all data"),
|
|
1508
|
+
("no_mtRibo_ETCI", "no mtRibo, ETC I"),
|
|
1509
|
+
("no_small_highAUPRC", "no small, high AUPRC"),
|
|
1510
|
+
]
|
|
1511
|
+
styles = {
|
|
1512
|
+
"all": {"linewidth": 1.8},
|
|
1513
|
+
"no_mtRibo_ETCI": {"linewidth": 1.8, "linestyle": "--"},
|
|
1514
|
+
"no_small_highAUPRC": {"linewidth": 1.8, "linestyle": ":"},
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
xmax = 0.0
|
|
1518
|
+
for key, pretty in labels:
|
|
1519
|
+
if key not in tp_curves:
|
|
1520
|
+
continue
|
|
1521
|
+
data = tp_curves[key]
|
|
1522
|
+
tp = np.asarray(data["tp"], dtype=float)
|
|
1523
|
+
prec = np.asarray(data["precision"], dtype=float)
|
|
1524
|
+
mask = np.isfinite(tp) & (tp > 0) & np.isfinite(prec) & (prec > 0)
|
|
1525
|
+
if not mask.any():
|
|
1526
|
+
continue
|
|
1527
|
+
tp_plot = tp[mask]
|
|
1528
|
+
prec_plot = prec[mask]
|
|
1529
|
+
xmax = max(xmax, float(tp_plot.max()))
|
|
1530
|
+
ax.plot(tp_plot, prec_plot, label=pretty, **styles.get(key, {}))
|
|
1531
|
+
|
|
1532
|
+
ax.set_xlabel("Number of true positives")
|
|
1533
|
+
ax.set_ylabel("Precision")
|
|
1534
|
+
ax.set_ylim(0.0, 1.05)
|
|
1535
|
+
|
|
1536
|
+
if xmax > 0:
|
|
1537
|
+
ax.set_xscale("log")
|
|
1538
|
+
|
|
1539
|
+
# If we have enough TPs, start at 10; otherwise fall back.
|
|
1540
|
+
if xmax > 10:
|
|
1541
|
+
ax.set_xlim(10, xmax * 1.05)
|
|
1542
|
+
logmin = 1 # 10^1 = 10
|
|
1543
|
+
else:
|
|
1544
|
+
ax.set_xlim(1, xmax * 1.05)
|
|
1545
|
+
logmin = 0 # 10^0 = 1
|
|
1546
|
+
|
|
1547
|
+
logmax = int(np.ceil(np.log10(xmax)))
|
|
1548
|
+
logmax = max(logmax, logmin)
|
|
1549
|
+
xticks = [10 ** k for k in range(logmin, logmax + 1)]
|
|
1550
|
+
ax.set_xticks(xticks)
|
|
1551
|
+
|
|
1552
|
+
ax.legend(frameon=False)
|
|
1553
|
+
ax.set_title(f"{name} – PR (TP vs precision)")
|
|
1554
|
+
|
|
1555
|
+
if save:
|
|
1556
|
+
if outname is None:
|
|
1557
|
+
outname = f"mpr_tp_{name}.pdf"
|
|
1558
|
+
fig.tight_layout()
|
|
1559
|
+
fig.savefig(outname)
|
|
1560
|
+
|
|
1561
|
+
return ax
|
|
1562
|
+
|
|
1563
|
+
# Default color palette (colorblind-friendly)
|
|
1564
|
+
DEFAULT_COLORS = [
|
|
1565
|
+
"#4E79A7", # blue
|
|
1566
|
+
"#E15759", # red
|
|
1567
|
+
"#76B7B2", # teal
|
|
1568
|
+
"#F28E2B", # orange
|
|
1569
|
+
"#59A14F", # green
|
|
1570
|
+
"#EDC948", # yellow
|
|
1571
|
+
"#B07AA1", # purple
|
|
1572
|
+
"#FF9DA7", # pink
|
|
1573
|
+
"#9C755F", # brown
|
|
1574
|
+
"#BAB0AC", # gray
|
|
1575
|
+
]
|
|
1576
|
+
|
|
1577
|
+
# Public mPR variant names map to the internal keys stored by mpr_prepare().
|
|
1578
|
+
PUBLIC_MPR_VARIANTS = {
|
|
1579
|
+
"unfiltered": "all",
|
|
1580
|
+
"without_mt_ribo_etci": "no_mtRibo_ETCI",
|
|
1581
|
+
"without_small_high_auprc": "no_small_highAUPRC",
|
|
1582
|
+
}
|
|
1583
|
+
INTERNAL_MPR_VARIANTS = {v: k for k, v in PUBLIC_MPR_VARIANTS.items()}
|
|
1584
|
+
|
|
1585
|
+
# mPR variant line styles keyed by internal storage names.
|
|
1586
|
+
MPR_VARIANT_STYLES = {
|
|
1587
|
+
"all": {"linestyle": "-", "label": "all data"},
|
|
1588
|
+
"no_mtRibo_ETCI": {"linestyle": "--", "label": "no mtRibo, ETC I"},
|
|
1589
|
+
"no_small_highAUPRC": {"linestyle": "dotted", "label": "no small, high AUPRC"},
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
# Compatibility alias for users who imported this internal constant.
|
|
1593
|
+
FILTER_STYLES = MPR_VARIANT_STYLES
|
|
1594
|
+
|
|
1595
|
+
|
|
1596
|
+
def _normalize_mpr_variant(variant):
|
|
1597
|
+
"""Return the internal mPR variant key for one public variant name."""
|
|
1598
|
+
if variant in PUBLIC_MPR_VARIANTS:
|
|
1599
|
+
return PUBLIC_MPR_VARIANTS[variant]
|
|
1600
|
+
if variant in MPR_VARIANT_STYLES:
|
|
1601
|
+
if variant == "all":
|
|
1602
|
+
return PUBLIC_MPR_VARIANTS["unfiltered"]
|
|
1603
|
+
return variant
|
|
1604
|
+
raise ValueError(
|
|
1605
|
+
"Unknown mPR variant "
|
|
1606
|
+
f"{variant!r}. Use one of {list(PUBLIC_MPR_VARIANTS.keys())}."
|
|
1607
|
+
)
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
def _normalize_mpr_variants(variants):
|
|
1611
|
+
"""Normalize public mPR variant names to internal storage keys."""
|
|
1612
|
+
if variants is None:
|
|
1613
|
+
raw_variants = ("all",)
|
|
1614
|
+
elif isinstance(variants, str):
|
|
1615
|
+
raw_variants = (variants,)
|
|
1616
|
+
else:
|
|
1617
|
+
try:
|
|
1618
|
+
raw_variants = tuple(variants)
|
|
1619
|
+
except TypeError:
|
|
1620
|
+
raw_variants = (variants,)
|
|
1621
|
+
|
|
1622
|
+
out = []
|
|
1623
|
+
for variant in raw_variants:
|
|
1624
|
+
if variant == "all":
|
|
1625
|
+
out.extend(PUBLIC_MPR_VARIANTS.values())
|
|
1626
|
+
else:
|
|
1627
|
+
out.append(_normalize_mpr_variant(variant))
|
|
1628
|
+
|
|
1629
|
+
# Preserve user order while removing duplicates.
|
|
1630
|
+
return tuple(dict.fromkeys(out))
|
|
1631
|
+
|
|
1632
|
+
|
|
1633
|
+
def _legacy_filter_to_variant(filter_key, default=None):
|
|
1634
|
+
"""Map old filter-key names to public variant names."""
|
|
1635
|
+
if filter_key is None:
|
|
1636
|
+
return default if default is not None else "all"
|
|
1637
|
+
mapping = {
|
|
1638
|
+
"all": "unfiltered",
|
|
1639
|
+
"no_mtRibo_ETCI": "without_mt_ribo_etci",
|
|
1640
|
+
"no_small_highAUPRC": "without_small_high_auprc",
|
|
1641
|
+
}
|
|
1642
|
+
return mapping.get(filter_key, filter_key)
|
|
1643
|
+
|
|
1644
|
+
|
|
1645
|
+
def _legacy_filters_to_variants(show_filters):
|
|
1646
|
+
"""Map old show_filters values to public variant names."""
|
|
1647
|
+
if show_filters is None:
|
|
1648
|
+
return "all"
|
|
1649
|
+
if isinstance(show_filters, str):
|
|
1650
|
+
return _legacy_filter_to_variant(show_filters)
|
|
1651
|
+
try:
|
|
1652
|
+
return tuple(_legacy_filter_to_variant(item) for item in show_filters)
|
|
1653
|
+
except TypeError:
|
|
1654
|
+
return (_legacy_filter_to_variant(show_filters),)
|
|
1655
|
+
|
|
1656
|
+
|
|
1657
|
+
def _normalize_show_filters(show_filters):
|
|
1658
|
+
"""Backward-compatible normalizer for old internal filter keys."""
|
|
1659
|
+
return _normalize_mpr_variants(_legacy_filters_to_variants(show_filters))
|
|
1660
|
+
|
|
1661
|
+
def plot_mpr_true_positive_curve(
|
|
1662
|
+
dataset_names=None,
|
|
1663
|
+
colors=None,
|
|
1664
|
+
ax=None,
|
|
1665
|
+
save=True,
|
|
1666
|
+
outname=None,
|
|
1667
|
+
linewidth=1.8,
|
|
1668
|
+
variants="unfiltered",
|
|
1669
|
+
):
|
|
1670
|
+
"""
|
|
1671
|
+
Plot mPR true-positive vs precision curves for multiple datasets.
|
|
1672
|
+
|
|
1673
|
+
Can auto-detect datasets or use provided dataset names.
|
|
1674
|
+
Each dataset gets one color, each filter type gets one line style.
|
|
1675
|
+
Two legends: one for datasets (colors), one for filters (line styles).
|
|
1676
|
+
|
|
1677
|
+
Parameters
|
|
1678
|
+
----------
|
|
1679
|
+
dataset_names : list of str, optional
|
|
1680
|
+
Names of datasets to plot. If None, auto-detects available datasets.
|
|
1681
|
+
colors : list of str, optional
|
|
1682
|
+
Colors for each dataset. If None, uses default palette.
|
|
1683
|
+
ax : matplotlib.axes.Axes, optional
|
|
1684
|
+
Axes to plot on. If None, creates new figure.
|
|
1685
|
+
save : bool
|
|
1686
|
+
Whether to save the figure
|
|
1687
|
+
outname : str, optional
|
|
1688
|
+
Output filename. If None, auto-generated.
|
|
1689
|
+
linewidth : float
|
|
1690
|
+
Line width for all curves
|
|
1691
|
+
variants : str or iterable of str
|
|
1692
|
+
Which mPR variants to show. Use "unfiltered",
|
|
1693
|
+
"without_mt_ribo_etci", "without_small_high_auprc", or "all".
|
|
1694
|
+
|
|
1695
|
+
Returns
|
|
1696
|
+
-------
|
|
1697
|
+
ax : matplotlib.axes.Axes
|
|
1698
|
+
"""
|
|
1699
|
+
config = dload("config")
|
|
1700
|
+
plot_config = config["plotting"]
|
|
1701
|
+
input_colors = dload("input", "colors")
|
|
1702
|
+
|
|
1703
|
+
variant_keys = _normalize_mpr_variants(variants)
|
|
1704
|
+
|
|
1705
|
+
# Sanitize color keys
|
|
1706
|
+
if input_colors:
|
|
1707
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
1708
|
+
|
|
1709
|
+
# Auto-detect datasets if none provided
|
|
1710
|
+
if dataset_names is None:
|
|
1711
|
+
# Get all available MPR datasets from the storage
|
|
1712
|
+
mpr_data_dict = dload("mpr")
|
|
1713
|
+
if isinstance(mpr_data_dict, dict) and mpr_data_dict:
|
|
1714
|
+
dataset_names = list(mpr_data_dict.keys())
|
|
1715
|
+
else:
|
|
1716
|
+
dataset_names = []
|
|
1717
|
+
|
|
1718
|
+
if not dataset_names:
|
|
1719
|
+
log.warning("No mPR datasets found. Make sure to run mpr_prepare() first.")
|
|
1720
|
+
return None
|
|
1721
|
+
|
|
1722
|
+
# Determine colors
|
|
1723
|
+
if colors is None:
|
|
1724
|
+
cmap_name = config.get("color_map", "tab10")
|
|
1725
|
+
try:
|
|
1726
|
+
cmap = get_cmap(cmap_name)
|
|
1727
|
+
except ValueError:
|
|
1728
|
+
cmap = get_cmap("tab10")
|
|
1729
|
+
|
|
1730
|
+
num_datasets = len(dataset_names)
|
|
1731
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
1732
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
1733
|
+
else:
|
|
1734
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
1735
|
+
|
|
1736
|
+
# Assign colors strictly matching the sorted dataset order
|
|
1737
|
+
final_colors = []
|
|
1738
|
+
for i, dataset in enumerate(dataset_names):
|
|
1739
|
+
color = input_colors.get(dataset) if input_colors else None
|
|
1740
|
+
# fallback to sanitized lookup just in case dataset_name is already sanitized but key isn't (or vice versa though we sanitized keys above)
|
|
1741
|
+
if color is None:
|
|
1742
|
+
color = default_colors[i]
|
|
1743
|
+
final_colors.append(color)
|
|
1744
|
+
colors = final_colors
|
|
1745
|
+
|
|
1746
|
+
if ax is None:
|
|
1747
|
+
# Increase width slightly
|
|
1748
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
1749
|
+
# Reserve space for legend on right
|
|
1750
|
+
plt.subplots_adjust(right=0.7)
|
|
1751
|
+
else:
|
|
1752
|
+
fig = ax.figure
|
|
1753
|
+
|
|
1754
|
+
xmax = 0.0
|
|
1755
|
+
|
|
1756
|
+
# Plot each dataset
|
|
1757
|
+
for i, name in enumerate(dataset_names):
|
|
1758
|
+
mpr = dload("mpr", name)
|
|
1759
|
+
if mpr is None:
|
|
1760
|
+
log.warning(f"mPR data for '{name}' not found, skipping.")
|
|
1761
|
+
continue
|
|
1762
|
+
|
|
1763
|
+
# Check if mPR data has expected structure
|
|
1764
|
+
if "tp_curves" not in mpr:
|
|
1765
|
+
log.warning(f"mPR data for '{name}' missing 'tp_curves', skipping.")
|
|
1766
|
+
continue
|
|
1767
|
+
|
|
1768
|
+
tp_curves = mpr["tp_curves"]
|
|
1769
|
+
color = colors[i % len(colors)]
|
|
1770
|
+
|
|
1771
|
+
for variant_key in variant_keys:
|
|
1772
|
+
if variant_key not in tp_curves:
|
|
1773
|
+
continue
|
|
1774
|
+
|
|
1775
|
+
data = tp_curves[variant_key]
|
|
1776
|
+
if not isinstance(data, dict) or "tp" not in data or "precision" not in data:
|
|
1777
|
+
log.warning(f"Invalid tp_curves data structure for '{name}' variant '{variant_key}', skipping.")
|
|
1778
|
+
continue
|
|
1779
|
+
|
|
1780
|
+
tp = np.asarray(data["tp"], dtype=float)
|
|
1781
|
+
prec = np.asarray(data["precision"], dtype=float)
|
|
1782
|
+
|
|
1783
|
+
mask = np.isfinite(tp) & (tp > 0) & np.isfinite(prec) & (prec > 0)
|
|
1784
|
+
if not mask.any():
|
|
1785
|
+
continue
|
|
1786
|
+
|
|
1787
|
+
tp_plot = tp[mask]
|
|
1788
|
+
prec_plot = prec[mask]
|
|
1789
|
+
xmax = max(xmax, float(tp_plot.max()))
|
|
1790
|
+
|
|
1791
|
+
style = MPR_VARIANT_STYLES.get(variant_key, {})
|
|
1792
|
+
ax.plot(
|
|
1793
|
+
tp_plot,
|
|
1794
|
+
prec_plot,
|
|
1795
|
+
color=color,
|
|
1796
|
+
linestyle=style.get("linestyle", "-"),
|
|
1797
|
+
linewidth=linewidth,
|
|
1798
|
+
)
|
|
1799
|
+
|
|
1800
|
+
# Configure axes
|
|
1801
|
+
ax.set_xlabel("Number of true positives")
|
|
1802
|
+
ax.set_ylabel("Precision")
|
|
1803
|
+
ax.set_ylim(0.0, 1.05)
|
|
1804
|
+
|
|
1805
|
+
if xmax > 0:
|
|
1806
|
+
ax.set_xscale("log")
|
|
1807
|
+
if xmax > 10:
|
|
1808
|
+
ax.set_xlim(10, xmax * 1.05)
|
|
1809
|
+
logmin = 1
|
|
1810
|
+
else:
|
|
1811
|
+
ax.set_xlim(1, xmax * 1.05)
|
|
1812
|
+
logmin = 0
|
|
1813
|
+
|
|
1814
|
+
logmax = int(np.ceil(np.log10(xmax)))
|
|
1815
|
+
logmax = max(logmax, logmin)
|
|
1816
|
+
xticks = [10 ** k for k in range(logmin, logmax + 1)]
|
|
1817
|
+
ax.set_xticks(xticks)
|
|
1818
|
+
|
|
1819
|
+
# Remove top and right spines
|
|
1820
|
+
ax.spines['top'].set_visible(False)
|
|
1821
|
+
ax.spines['right'].set_visible(False)
|
|
1822
|
+
|
|
1823
|
+
# Create vertically stacked legends
|
|
1824
|
+
_add_vertical_legend(ax, dataset_names, colors, variant_keys, linewidth)
|
|
1825
|
+
|
|
1826
|
+
# Save
|
|
1827
|
+
if save:
|
|
1828
|
+
output_type = plot_config.get("output_type", "pdf")
|
|
1829
|
+
if outname is None:
|
|
1830
|
+
outname = f"mpr_tp_multi.{output_type}"
|
|
1831
|
+
|
|
1832
|
+
# Check if outname is just a filename or a full path
|
|
1833
|
+
outpath = Path(outname)
|
|
1834
|
+
if len(outpath.parts) == 1:
|
|
1835
|
+
# Just a filename, prepend configured output folder
|
|
1836
|
+
outpath = Path(config["output_folder"]) / outname
|
|
1837
|
+
|
|
1838
|
+
fig.tight_layout()
|
|
1839
|
+
fig.savefig(outpath, bbox_inches="tight", format=output_type)
|
|
1840
|
+
|
|
1841
|
+
return ax
|
|
1842
|
+
|
|
1843
|
+
|
|
1844
|
+
def plot_mpr_tp_multi(
|
|
1845
|
+
dataset_names=None,
|
|
1846
|
+
colors=None,
|
|
1847
|
+
ax=None,
|
|
1848
|
+
save=True,
|
|
1849
|
+
outname=None,
|
|
1850
|
+
linewidth=1.8,
|
|
1851
|
+
show_filters=("all", "no_mtRibo_ETCI", "no_small_highAUPRC"),
|
|
1852
|
+
):
|
|
1853
|
+
"""Backward-compatible wrapper for plot_mpr_true_positive_curve()."""
|
|
1854
|
+
return plot_mpr_true_positive_curve(
|
|
1855
|
+
dataset_names=dataset_names,
|
|
1856
|
+
colors=colors,
|
|
1857
|
+
ax=ax,
|
|
1858
|
+
save=save,
|
|
1859
|
+
outname=outname,
|
|
1860
|
+
linewidth=linewidth,
|
|
1861
|
+
variants=_legacy_filters_to_variants(show_filters),
|
|
1862
|
+
)
|
|
1863
|
+
|
|
1864
|
+
def plot_mpr_complex_coverage_curve(
|
|
1865
|
+
dataset_names=None,
|
|
1866
|
+
colors=None,
|
|
1867
|
+
ax=None,
|
|
1868
|
+
save=True,
|
|
1869
|
+
outname=None,
|
|
1870
|
+
linewidth=1.8,
|
|
1871
|
+
variants="unfiltered",
|
|
1872
|
+
show_markers="auto",
|
|
1873
|
+
marker_size=20,
|
|
1874
|
+
):
|
|
1875
|
+
"""
|
|
1876
|
+
Plot mPR complex-coverage vs precision curves for multiple datasets.
|
|
1877
|
+
|
|
1878
|
+
Can auto-detect datasets or use provided dataset names.
|
|
1879
|
+
Each dataset gets one color, each filter type gets one line style.
|
|
1880
|
+
Two legends: one for datasets (colors), one for filters (line styles).
|
|
1881
|
+
|
|
1882
|
+
Parameters
|
|
1883
|
+
----------
|
|
1884
|
+
dataset_names : list of str, optional
|
|
1885
|
+
Names of datasets to plot. If None, auto-detects available datasets.
|
|
1886
|
+
colors : list of str, optional
|
|
1887
|
+
Colors for each dataset. If None, uses default palette.
|
|
1888
|
+
ax : matplotlib.axes.Axes, optional
|
|
1889
|
+
Axes to plot on. If None, creates new figure.
|
|
1890
|
+
save : bool
|
|
1891
|
+
Whether to save the figure
|
|
1892
|
+
outname : str, optional
|
|
1893
|
+
Output filename. If None, auto-generated.
|
|
1894
|
+
linewidth : float
|
|
1895
|
+
Line width for all curves
|
|
1896
|
+
variants : str or iterable of str
|
|
1897
|
+
Which mPR variants to show. Use "unfiltered",
|
|
1898
|
+
"without_mt_ribo_etci", "without_small_high_auprc", or "all".
|
|
1899
|
+
show_markers : bool or "auto"
|
|
1900
|
+
If True, draw markers on curves to make short curves visible.
|
|
1901
|
+
If "auto" (default), markers are drawn only for curves with <= 10 points.
|
|
1902
|
+
marker_size : int
|
|
1903
|
+
Scatter marker size (points^2) when markers are shown.
|
|
1904
|
+
|
|
1905
|
+
Returns
|
|
1906
|
+
-------
|
|
1907
|
+
ax : matplotlib.axes.Axes
|
|
1908
|
+
"""
|
|
1909
|
+
config = dload("config")
|
|
1910
|
+
plot_config = config["plotting"]
|
|
1911
|
+
input_colors = dload("input", "colors")
|
|
1912
|
+
|
|
1913
|
+
variant_keys = _normalize_mpr_variants(variants)
|
|
1914
|
+
|
|
1915
|
+
# Sanitize color keys
|
|
1916
|
+
if input_colors:
|
|
1917
|
+
input_colors = {_sanitize(k): v for k, v in input_colors.items()}
|
|
1918
|
+
|
|
1919
|
+
# Auto-detect datasets if none provided
|
|
1920
|
+
if dataset_names is None:
|
|
1921
|
+
# Get all available MPR datasets from the storage
|
|
1922
|
+
mpr_data_dict = dload("mpr")
|
|
1923
|
+
if isinstance(mpr_data_dict, dict) and mpr_data_dict:
|
|
1924
|
+
dataset_names = list(mpr_data_dict.keys())
|
|
1925
|
+
else:
|
|
1926
|
+
dataset_names = []
|
|
1927
|
+
|
|
1928
|
+
if not dataset_names:
|
|
1929
|
+
log.warning("No mPR datasets found. Make sure to run mpr_prepare() first.")
|
|
1930
|
+
return None
|
|
1931
|
+
|
|
1932
|
+
# Determine colors
|
|
1933
|
+
if colors is None:
|
|
1934
|
+
cmap_name = config.get("color_map", "tab10")
|
|
1935
|
+
try:
|
|
1936
|
+
cmap = get_cmap(cmap_name)
|
|
1937
|
+
except ValueError:
|
|
1938
|
+
cmap = get_cmap("tab10")
|
|
1939
|
+
|
|
1940
|
+
num_datasets = len(dataset_names)
|
|
1941
|
+
if num_datasets <= 10 and cmap_name == "tab10":
|
|
1942
|
+
default_colors = [cmap(i) for i in range(num_datasets)]
|
|
1943
|
+
else:
|
|
1944
|
+
default_colors = [cmap(float(i) / max(num_datasets - 1, 1)) for i in range(num_datasets)]
|
|
1945
|
+
|
|
1946
|
+
# Assign colors strictly matching the sorted dataset order
|
|
1947
|
+
final_colors = []
|
|
1948
|
+
for i, dataset in enumerate(dataset_names):
|
|
1949
|
+
color = input_colors.get(dataset) if input_colors else None
|
|
1950
|
+
# fallback to sanitized lookup just in case dataset_name is already sanitized but key isn't (or vice versa though we sanitized keys above)
|
|
1951
|
+
if color is None:
|
|
1952
|
+
color = default_colors[i]
|
|
1953
|
+
final_colors.append(color)
|
|
1954
|
+
colors = final_colors
|
|
1955
|
+
|
|
1956
|
+
if ax is None:
|
|
1957
|
+
# Increase width slightly
|
|
1958
|
+
fig, ax = plt.subplots(figsize=(6, 4))
|
|
1959
|
+
# Reserve space for legend on right
|
|
1960
|
+
plt.subplots_adjust(right=0.7)
|
|
1961
|
+
else:
|
|
1962
|
+
fig = ax.figure
|
|
1963
|
+
|
|
1964
|
+
# First pass: determine max coverage across all datasets/filters for adaptive x-axis
|
|
1965
|
+
max_cov_global = 0
|
|
1966
|
+
_mpr_cache = {}
|
|
1967
|
+
for i, name in enumerate(dataset_names):
|
|
1968
|
+
mpr = dload("mpr", name)
|
|
1969
|
+
_mpr_cache[name] = mpr
|
|
1970
|
+
if mpr is not None:
|
|
1971
|
+
for variant_key in variant_keys:
|
|
1972
|
+
arr = mpr["coverage_curves"].get(variant_key)
|
|
1973
|
+
if arr is not None:
|
|
1974
|
+
max_cov_global = max(max_cov_global, float(np.asarray(arr).max()))
|
|
1975
|
+
|
|
1976
|
+
# Build adaptive x-axis limits and ticks
|
|
1977
|
+
import math
|
|
1978
|
+
if max_cov_global <= 200:
|
|
1979
|
+
# Original fixed range — keeps CORUM plots identical to before
|
|
1980
|
+
x_max_plot = 200
|
|
1981
|
+
tick_positions = [1, 2, 20, 200]
|
|
1982
|
+
tick_labels = ["0", "2", "20", "200"]
|
|
1983
|
+
else:
|
|
1984
|
+
# Round up to the next power of 10 so the max bar has breathing room
|
|
1985
|
+
x_max_plot = 10 ** math.ceil(math.log10(max_cov_global + 1))
|
|
1986
|
+
tick_positions = [1, 2]
|
|
1987
|
+
v = 10
|
|
1988
|
+
while v <= x_max_plot:
|
|
1989
|
+
tick_positions.append(v)
|
|
1990
|
+
v *= 10
|
|
1991
|
+
tick_labels = ["0"] + [str(t) for t in tick_positions[1:]]
|
|
1992
|
+
|
|
1993
|
+
# Plot each dataset
|
|
1994
|
+
for i, name in enumerate(dataset_names):
|
|
1995
|
+
mpr = _mpr_cache[name]
|
|
1996
|
+
if mpr is None:
|
|
1997
|
+
log.warning(f"mPR data for '{name}' not found, skipping.")
|
|
1998
|
+
continue
|
|
1999
|
+
|
|
2000
|
+
precision_cutoffs = np.asarray(mpr["precision_cutoffs"], dtype=float)
|
|
2001
|
+
coverage = mpr["coverage_curves"]
|
|
2002
|
+
color = colors[i % len(colors)]
|
|
2003
|
+
|
|
2004
|
+
for variant_key in variant_keys:
|
|
2005
|
+
if variant_key not in coverage:
|
|
2006
|
+
continue
|
|
2007
|
+
|
|
2008
|
+
cov = np.asarray(coverage[variant_key], dtype=float)
|
|
2009
|
+
|
|
2010
|
+
# Keep only positive coverage within the visible x range
|
|
2011
|
+
mask = (cov > 0) & (cov <= x_max_plot)
|
|
2012
|
+
if not mask.any():
|
|
2013
|
+
continue
|
|
2014
|
+
|
|
2015
|
+
cov_plot = cov[mask]
|
|
2016
|
+
prec_plot = precision_cutoffs[mask]
|
|
2017
|
+
|
|
2018
|
+
style = MPR_VARIANT_STYLES.get(variant_key, {})
|
|
2019
|
+
|
|
2020
|
+
# Decide marker visibility
|
|
2021
|
+
if show_markers == "auto":
|
|
2022
|
+
use_markers = (cov_plot.size <= 10)
|
|
2023
|
+
else:
|
|
2024
|
+
use_markers = bool(show_markers)
|
|
2025
|
+
|
|
2026
|
+
if cov_plot.size == 1:
|
|
2027
|
+
# A single point is effectively invisible as a line; draw a marker.
|
|
2028
|
+
ax.scatter(cov_plot, prec_plot, color=color, s=marker_size, zorder=3)
|
|
2029
|
+
else:
|
|
2030
|
+
ax.plot(
|
|
2031
|
+
cov_plot,
|
|
2032
|
+
prec_plot,
|
|
2033
|
+
color=color,
|
|
2034
|
+
linestyle=style.get("linestyle", "-"),
|
|
2035
|
+
linewidth=linewidth,
|
|
2036
|
+
marker=("o" if use_markers else None),
|
|
2037
|
+
markersize=(3 if use_markers else None),
|
|
2038
|
+
)
|
|
2039
|
+
|
|
2040
|
+
# Configure axes
|
|
2041
|
+
ax.set_xscale("log")
|
|
2042
|
+
ax.set_xlim(1, x_max_plot)
|
|
2043
|
+
ax.set_xlabel("# complexes")
|
|
2044
|
+
ax.set_ylabel("Precision")
|
|
2045
|
+
ax.set_ylim(0.0, 1.05)
|
|
2046
|
+
|
|
2047
|
+
# Adaptive x-ticks
|
|
2048
|
+
ax.set_xticks(tick_positions)
|
|
2049
|
+
ax.set_xticklabels(tick_labels)
|
|
2050
|
+
|
|
2051
|
+
# Remove top and right spines
|
|
2052
|
+
ax.spines['top'].set_visible(False)
|
|
2053
|
+
ax.spines['right'].set_visible(False)
|
|
2054
|
+
|
|
2055
|
+
# Create vertically stacked legends
|
|
2056
|
+
_add_vertical_legend(ax, dataset_names, colors, variant_keys, linewidth)
|
|
2057
|
+
|
|
2058
|
+
# Save
|
|
2059
|
+
if save:
|
|
2060
|
+
output_type = plot_config.get("output_type", "pdf")
|
|
2061
|
+
if outname is None:
|
|
2062
|
+
outname = f"mpr_complexes_multi.{output_type}"
|
|
2063
|
+
|
|
2064
|
+
# Check if outname is just a filename or a full path
|
|
2065
|
+
outpath = Path(outname)
|
|
2066
|
+
if len(outpath.parts) == 1:
|
|
2067
|
+
# Just a filename, prepend configured output folder
|
|
2068
|
+
outpath = Path(config["output_folder"]) / outname
|
|
2069
|
+
|
|
2070
|
+
fig.tight_layout()
|
|
2071
|
+
fig.savefig(outpath, bbox_inches="tight", format=output_type)
|
|
2072
|
+
|
|
2073
|
+
return ax
|
|
2074
|
+
|
|
2075
|
+
|
|
2076
|
+
def plot_mpr_complexes_multi(
|
|
2077
|
+
dataset_names=None,
|
|
2078
|
+
colors=None,
|
|
2079
|
+
ax=None,
|
|
2080
|
+
save=True,
|
|
2081
|
+
outname=None,
|
|
2082
|
+
linewidth=1.8,
|
|
2083
|
+
show_filters=("all", "no_mtRibo_ETCI", "no_small_highAUPRC"),
|
|
2084
|
+
show_markers="auto",
|
|
2085
|
+
marker_size=20,
|
|
2086
|
+
):
|
|
2087
|
+
"""Backward-compatible wrapper for plot_mpr_complex_coverage_curve()."""
|
|
2088
|
+
return plot_mpr_complex_coverage_curve(
|
|
2089
|
+
dataset_names=dataset_names,
|
|
2090
|
+
colors=colors,
|
|
2091
|
+
ax=ax,
|
|
2092
|
+
save=save,
|
|
2093
|
+
outname=outname,
|
|
2094
|
+
linewidth=linewidth,
|
|
2095
|
+
variants=_legacy_filters_to_variants(show_filters),
|
|
2096
|
+
show_markers=show_markers,
|
|
2097
|
+
marker_size=marker_size,
|
|
2098
|
+
)
|
|
2099
|
+
|
|
2100
|
+
|
|
2101
|
+
def plot_mpr_summary(
|
|
2102
|
+
dataset_names=None,
|
|
2103
|
+
colors=None,
|
|
2104
|
+
variants="unfiltered",
|
|
2105
|
+
save=True,
|
|
2106
|
+
linewidth=1.8,
|
|
2107
|
+
show_markers="auto",
|
|
2108
|
+
marker_size=20,
|
|
2109
|
+
auc_variant=None,
|
|
2110
|
+
):
|
|
2111
|
+
"""Generate the standard mPR summary plots and return complex AUC scores."""
|
|
2112
|
+
plot_mpr_true_positive_curve(
|
|
2113
|
+
dataset_names=dataset_names,
|
|
2114
|
+
colors=colors,
|
|
2115
|
+
save=save,
|
|
2116
|
+
linewidth=linewidth,
|
|
2117
|
+
variants=variants,
|
|
2118
|
+
)
|
|
2119
|
+
plot_mpr_complex_coverage_curve(
|
|
2120
|
+
dataset_names=dataset_names,
|
|
2121
|
+
colors=colors,
|
|
2122
|
+
save=save,
|
|
2123
|
+
linewidth=linewidth,
|
|
2124
|
+
variants=variants,
|
|
2125
|
+
show_markers=show_markers,
|
|
2126
|
+
marker_size=marker_size,
|
|
2127
|
+
)
|
|
2128
|
+
|
|
2129
|
+
if auc_variant is None:
|
|
2130
|
+
variant_keys = _normalize_mpr_variants(variants)
|
|
2131
|
+
auc_variant = INTERNAL_MPR_VARIANTS.get(variant_keys[0], "unfiltered")
|
|
2132
|
+
|
|
2133
|
+
return plot_mpr_complex_auc_scores(variant=auc_variant, save=save)
|
|
2134
|
+
|
|
2135
|
+
def _add_vertical_legend(ax, dataset_names, colors, variant_keys, linewidth):
|
|
2136
|
+
"""
|
|
2137
|
+
Add vertically stacked legends: Dataset on top, mPR variant below.
|
|
2138
|
+
"""
|
|
2139
|
+
variant_keys = _normalize_show_filters(variant_keys)
|
|
2140
|
+
# Legend 1: Datasets (colors) - solid lines
|
|
2141
|
+
dataset_handles = []
|
|
2142
|
+
for i, name in enumerate(dataset_names):
|
|
2143
|
+
color = colors[i % len(colors)]
|
|
2144
|
+
handle = Line2D([0], [0], color=color, linewidth=linewidth, linestyle="-")
|
|
2145
|
+
dataset_handles.append(handle)
|
|
2146
|
+
|
|
2147
|
+
# Legend 2: mPR variants (line styles) - black lines
|
|
2148
|
+
variant_handles = []
|
|
2149
|
+
variant_labels = []
|
|
2150
|
+
for variant_key in variant_keys:
|
|
2151
|
+
style = MPR_VARIANT_STYLES.get(variant_key, {})
|
|
2152
|
+
handle = Line2D(
|
|
2153
|
+
[0], [0],
|
|
2154
|
+
color="black",
|
|
2155
|
+
linewidth=linewidth,
|
|
2156
|
+
linestyle=style.get("linestyle", "-")
|
|
2157
|
+
)
|
|
2158
|
+
variant_handles.append(handle)
|
|
2159
|
+
variant_labels.append(style.get("label", variant_key))
|
|
2160
|
+
|
|
2161
|
+
# Position legends vertically with proper alignment
|
|
2162
|
+
# Dataset legend on upper right
|
|
2163
|
+
legend1 = ax.legend(
|
|
2164
|
+
dataset_handles,
|
|
2165
|
+
dataset_names,
|
|
2166
|
+
loc="upper left",
|
|
2167
|
+
frameon=False,
|
|
2168
|
+
title="Dataset",
|
|
2169
|
+
fontsize=7,
|
|
2170
|
+
title_fontsize=8,
|
|
2171
|
+
bbox_to_anchor=(1.05, 1.0)
|
|
2172
|
+
)
|
|
2173
|
+
ax.add_artist(legend1)
|
|
2174
|
+
|
|
2175
|
+
# Filter legend below the dataset legend, aligned properly without title
|
|
2176
|
+
legend2 = ax.legend(
|
|
2177
|
+
variant_handles,
|
|
2178
|
+
variant_labels,
|
|
2179
|
+
loc="upper left",
|
|
2180
|
+
frameon=False,
|
|
2181
|
+
fontsize=7,
|
|
2182
|
+
bbox_to_anchor=(1.05, 1.0 - len(dataset_names) * 0.06 - 0.1)
|
|
2183
|
+
)
|
|
2184
|
+
|
|
2185
|
+
def _add_dual_legend(ax, dataset_names, colors, variant_keys, linewidth):
|
|
2186
|
+
"""
|
|
2187
|
+
Add two legends: one for datasets (colors), one for mPR variants (line styles).
|
|
2188
|
+
"""
|
|
2189
|
+
variant_keys = _normalize_show_filters(variant_keys)
|
|
2190
|
+
# Legend 1: Datasets (colors) - solid lines
|
|
2191
|
+
dataset_handles = []
|
|
2192
|
+
for i, name in enumerate(dataset_names):
|
|
2193
|
+
color = colors[i % len(colors)]
|
|
2194
|
+
handle = Line2D([0], [0], color=color, linewidth=linewidth, linestyle="-")
|
|
2195
|
+
dataset_handles.append(handle)
|
|
2196
|
+
|
|
2197
|
+
# Legend 2: mPR variants (line styles) - black lines
|
|
2198
|
+
variant_handles = []
|
|
2199
|
+
variant_labels = []
|
|
2200
|
+
for variant_key in variant_keys:
|
|
2201
|
+
style = MPR_VARIANT_STYLES.get(variant_key, {})
|
|
2202
|
+
handle = Line2D(
|
|
2203
|
+
[0], [0],
|
|
2204
|
+
color="black",
|
|
2205
|
+
linewidth=linewidth,
|
|
2206
|
+
linestyle=style.get("linestyle", "-")
|
|
2207
|
+
)
|
|
2208
|
+
variant_handles.append(handle)
|
|
2209
|
+
variant_labels.append(style.get("label", variant_key))
|
|
2210
|
+
|
|
2211
|
+
# Position legends
|
|
2212
|
+
# Dataset legend on upper right
|
|
2213
|
+
legend1 = ax.legend(
|
|
2214
|
+
dataset_handles,
|
|
2215
|
+
dataset_names,
|
|
2216
|
+
loc="upper right",
|
|
2217
|
+
frameon=False,
|
|
2218
|
+
title="Dataset",
|
|
2219
|
+
fontsize=7,
|
|
2220
|
+
title_fontsize=8,
|
|
2221
|
+
)
|
|
2222
|
+
ax.add_artist(legend1)
|
|
2223
|
+
|
|
2224
|
+
# Filter legend on lower left or right depending on plot type
|
|
2225
|
+
legend2 = ax.legend(
|
|
2226
|
+
variant_handles,
|
|
2227
|
+
variant_labels,
|
|
2228
|
+
loc="lower left",
|
|
2229
|
+
frameon=False,
|
|
2230
|
+
title="Variant",
|
|
2231
|
+
fontsize=7,
|
|
2232
|
+
title_fontsize=8,
|
|
2233
|
+
)
|
|
2234
|
+
|