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/analysis.py
ADDED
|
@@ -0,0 +1,1647 @@
|
|
|
1
|
+
# Standard library imports
|
|
2
|
+
import gc
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import time
|
|
7
|
+
from collections import defaultdict, OrderedDict
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
# Third-party imports
|
|
11
|
+
from art import tprint
|
|
12
|
+
from bitarray import bitarray
|
|
13
|
+
from joblib import Parallel, delayed, dump, load
|
|
14
|
+
from numba import njit, prange
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
from sklearn import metrics
|
|
18
|
+
from tqdm import tqdm
|
|
19
|
+
|
|
20
|
+
# Local/application-specific imports
|
|
21
|
+
from .logging_config import log
|
|
22
|
+
from .preprocessing import filter_matrix_by_genes, filter_duplicate_terms
|
|
23
|
+
from .utils import dsave, dload, _sanitize, normalize_analysis_genes
|
|
24
|
+
|
|
25
|
+
import matplotlib as mpl
|
|
26
|
+
|
|
27
|
+
def deep_update(source, overrides):
|
|
28
|
+
"""Recursively update the source dict with the overrides."""
|
|
29
|
+
for key, value in overrides.items():
|
|
30
|
+
if isinstance(value, dict) and key in source and isinstance(source[key], dict):
|
|
31
|
+
deep_update(source[key], value)
|
|
32
|
+
else:
|
|
33
|
+
source[key] = value
|
|
34
|
+
return source
|
|
35
|
+
|
|
36
|
+
def initialize(config={}):
|
|
37
|
+
|
|
38
|
+
user_overrides = config if isinstance(config, dict) else {}
|
|
39
|
+
|
|
40
|
+
default_config = {
|
|
41
|
+
"min_genes_in_complex": 3,
|
|
42
|
+
"min_genes_per_complex_analysis": 2,
|
|
43
|
+
"output_folder": "output",
|
|
44
|
+
"gold_standard": "CORUM",
|
|
45
|
+
"color_map": "RdYlBu",
|
|
46
|
+
"jaccard": True,
|
|
47
|
+
# Which genes are used for analysis (drives used_genes intersection)
|
|
48
|
+
# - 'shared' : use genes common to all datasets (common_genes)
|
|
49
|
+
# - 'dataset_specific' : use genes present in each dataset individually
|
|
50
|
+
"analysis_genes": "shared",
|
|
51
|
+
"plotting": {
|
|
52
|
+
"save_plot": True,
|
|
53
|
+
"show_plot": True,
|
|
54
|
+
"output_type": "pdf",
|
|
55
|
+
},
|
|
56
|
+
"preprocessing": {
|
|
57
|
+
"normalize": False,
|
|
58
|
+
"fill_na": False,
|
|
59
|
+
"drop_na": False,
|
|
60
|
+
},
|
|
61
|
+
"corr_function": "numpy",
|
|
62
|
+
"per_complex": {
|
|
63
|
+
"n_jobs": 4,
|
|
64
|
+
"chunk_size": 200,
|
|
65
|
+
"max_nbytes": "100M",
|
|
66
|
+
},
|
|
67
|
+
"logging": { # Added: Default logging config
|
|
68
|
+
"visible_levels": ["DONE"] # if needed #, "PROGRESS", "STARTED", "INFO"
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
# Early merge to get user-overridden config (including logging.visible_levels)
|
|
73
|
+
if config is not None:
|
|
74
|
+
config = deep_update(default_config, config)
|
|
75
|
+
else:
|
|
76
|
+
config = default_config
|
|
77
|
+
|
|
78
|
+
# Backward compatibility: if user provided legacy key but not the new one,
|
|
79
|
+
# map it to analysis_genes. (We must look at the original overrides, because
|
|
80
|
+
# defaults always include analysis_genes.)
|
|
81
|
+
analysis_genes_provided = (
|
|
82
|
+
isinstance(user_overrides, dict)
|
|
83
|
+
and "analysis_genes" in user_overrides
|
|
84
|
+
and user_overrides.get("analysis_genes") is not None
|
|
85
|
+
and str(user_overrides.get("analysis_genes")).strip() != ""
|
|
86
|
+
)
|
|
87
|
+
if (
|
|
88
|
+
isinstance(user_overrides, dict)
|
|
89
|
+
and "use_common_genes" in user_overrides
|
|
90
|
+
and not analysis_genes_provided
|
|
91
|
+
):
|
|
92
|
+
config["analysis_genes"] = (
|
|
93
|
+
"shared" if bool(user_overrides.get("use_common_genes")) else "dataset_specific"
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
config["analysis_genes"] = normalize_analysis_genes(config.get("analysis_genes"))
|
|
97
|
+
|
|
98
|
+
# Extract visible_levels from the merged config and set logging visibility immediately (before any logs)
|
|
99
|
+
visible_levels = config.get("logging", {}).get("visible_levels", ["DONE"])
|
|
100
|
+
log.set_visible_levels(visible_levels)
|
|
101
|
+
|
|
102
|
+
log.info("******************************************************************")
|
|
103
|
+
log.info("🧬 pflex: Systematic CRISPR screen benchmarking framework")
|
|
104
|
+
log.info("******************************************************************")
|
|
105
|
+
log.started("Initialization")
|
|
106
|
+
|
|
107
|
+
# Check and remove .tmp folder if it exists (clean slate to avoid overriding old results)
|
|
108
|
+
tmp_folder = ".tmp"
|
|
109
|
+
if os.path.exists(tmp_folder):
|
|
110
|
+
log.info(f"Removing existing '{tmp_folder}' folder for a clean start.")
|
|
111
|
+
shutil.rmtree(tmp_folder)
|
|
112
|
+
log.done(f"'{tmp_folder}' folder removed successfully.")
|
|
113
|
+
|
|
114
|
+
log.progress("Saving configuration settings.")
|
|
115
|
+
|
|
116
|
+
dsave(config, "config")
|
|
117
|
+
update_matploblib_config(config)
|
|
118
|
+
output_folder = config.get("output_folder", "output")
|
|
119
|
+
os.makedirs(output_folder, exist_ok=True)
|
|
120
|
+
log.progress(f"Output folder '{output_folder}' ensured to exist.")
|
|
121
|
+
log.done("Initialization completed. ")
|
|
122
|
+
tprint("FLEX",font="standard")
|
|
123
|
+
|
|
124
|
+
def update_matploblib_config(config=None, font_family="Arial", layout="single"):
|
|
125
|
+
"""
|
|
126
|
+
Configure matplotlib settings optimized for Nature journal figures:
|
|
127
|
+
- 7 pt fonts (labels, ticks, legend), 9 pt titles
|
|
128
|
+
- Thin spines (0.5 pt), ticks out (left/bottom only), no minor ticks
|
|
129
|
+
- No grid, clean minimalist look
|
|
130
|
+
- Colorblind-friendly Tableau 10 color cycle
|
|
131
|
+
- Illustrator-safe PDF export (Type 42)
|
|
132
|
+
- Figure sizes: "single" (~89 mm), "double" (~183 mm), or custom (width, height) in inches
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
config (dict, optional): Configuration dict (e.g., {'color_map': 'RdYlBu'}).
|
|
136
|
+
font_family (str): Preferred font (e.g., 'Arial', falls back to 'Helvetica').
|
|
137
|
+
layout (str or tuple): 'single' (~89 mm), 'double' (~183 mm), or (width, height) in inches.
|
|
138
|
+
"""
|
|
139
|
+
if config is None:
|
|
140
|
+
config = {}
|
|
141
|
+
# Fallback if chosen font missing
|
|
142
|
+
requested_font_family = font_family
|
|
143
|
+
try:
|
|
144
|
+
from matplotlib.font_manager import findfont, FontProperties
|
|
145
|
+
findfont(FontProperties(family=font_family))
|
|
146
|
+
except Exception:
|
|
147
|
+
font_family = "Helvetica" # Nature prefers Helvetica if Arial unavailable
|
|
148
|
+
log.warning(
|
|
149
|
+
f"Font '{requested_font_family}' not found; falling back to '{font_family}'."
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
# Figure size presets (Nature: single ≈ 89 mm, double ≈ 183 mm at 25.4 mm/inch)
|
|
153
|
+
if isinstance(layout, tuple):
|
|
154
|
+
fig_w, fig_h = layout
|
|
155
|
+
else:
|
|
156
|
+
if layout == "double":
|
|
157
|
+
fig_w = 7.2 # ~183 mm
|
|
158
|
+
fig_h = 5.4 # Adjusted aspect
|
|
159
|
+
else: # "single"
|
|
160
|
+
fig_w = 4.0 # Increased from 3.5" for more space (~102 mm)
|
|
161
|
+
fig_h = 3.0 # Increased from 2.6" for better aspect (~76 mm)
|
|
162
|
+
# Colorblind-friendly cycle (Tableau 10 adapted)
|
|
163
|
+
cb_cycle = [
|
|
164
|
+
"#4E79A7", "#F28E2B", "#E15759", "#76B7B2", "#59A14F",
|
|
165
|
+
"#EDC948", "#B07AA1", "#FF9DA7", "#9C755F", "#BAB0AC"
|
|
166
|
+
]
|
|
167
|
+
mpl.rcParams.update({
|
|
168
|
+
# --- Text & Fonts ---
|
|
169
|
+
"text.usetex": False, # Avoid LaTeX
|
|
170
|
+
"font.family": [font_family], # Explicit font
|
|
171
|
+
"mathtext.fontset": "dejavusans", # Disable mathtext
|
|
172
|
+
"mathtext.default": "regular", # Plain text
|
|
173
|
+
"axes.unicode_minus": True, # Proper minus signs
|
|
174
|
+
# --- Sizes (7 pt baseline, adjusted for space) ---
|
|
175
|
+
"font.size": 7, # Reduced from 8 pt
|
|
176
|
+
"axes.titlesize": 9, # Reduced from 10 pt
|
|
177
|
+
"axes.labelsize": 7,
|
|
178
|
+
"legend.fontsize": 7,
|
|
179
|
+
"xtick.labelsize": 7,
|
|
180
|
+
"ytick.labelsize": 7,
|
|
181
|
+
# --- Lines & Markers ---
|
|
182
|
+
"lines.linewidth": 1.5, # Kept for data visibility
|
|
183
|
+
"lines.markersize": 4.0,
|
|
184
|
+
"patch.linewidth": 0.5,
|
|
185
|
+
"errorbar.capsize": 2,
|
|
186
|
+
# --- Axes, Spines, Ticks ---
|
|
187
|
+
"axes.linewidth": 0.5,
|
|
188
|
+
"axes.edgecolor": "black",
|
|
189
|
+
"axes.facecolor": "none",
|
|
190
|
+
"axes.titlepad": 3.0,
|
|
191
|
+
"axes.labelpad": 2.0,
|
|
192
|
+
"axes.prop_cycle": mpl.cycler(color=cb_cycle),
|
|
193
|
+
"xtick.direction": "out",
|
|
194
|
+
"ytick.direction": "out",
|
|
195
|
+
"xtick.major.size": 2.5,
|
|
196
|
+
"ytick.major.size": 2.5,
|
|
197
|
+
"xtick.minor.visible": False,
|
|
198
|
+
"ytick.minor.visible": False,
|
|
199
|
+
"xtick.major.width": 0.5,
|
|
200
|
+
"ytick.major.width": 0.5,
|
|
201
|
+
"xtick.top": False,
|
|
202
|
+
"ytick.right": False,
|
|
203
|
+
# --- Grid ---
|
|
204
|
+
"axes.grid": False,
|
|
205
|
+
# --- Legend ---
|
|
206
|
+
"legend.frameon": False,
|
|
207
|
+
"legend.handlelength": 1.6, # Slightly adjusted
|
|
208
|
+
"legend.handletextpad": 0.4,
|
|
209
|
+
"legend.borderaxespad": 0.3,
|
|
210
|
+
"legend.loc": "best", # Dynamic placement to avoid overlap
|
|
211
|
+
# --- Figure & Save ---
|
|
212
|
+
"figure.dpi": 600,
|
|
213
|
+
"figure.figsize": (fig_w, fig_h),
|
|
214
|
+
"savefig.dpi": 600,
|
|
215
|
+
"savefig.bbox": "tight",
|
|
216
|
+
"savefig.pad_inches": 0.1, # Increased for spacing
|
|
217
|
+
"savefig.transparent": False, # White background
|
|
218
|
+
# --- PDF/SVG Export ---
|
|
219
|
+
"pdf.fonttype": 42,
|
|
220
|
+
"ps.fonttype": 42,
|
|
221
|
+
"pdf.use14corefonts": False,
|
|
222
|
+
"svg.fonttype": "none",
|
|
223
|
+
})
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _sort_ascending_for_dataset(dataset_name):
|
|
227
|
+
sorting = dload("input", "sorting")
|
|
228
|
+
if not isinstance(sorting, dict):
|
|
229
|
+
return False
|
|
230
|
+
sort_order = str(sorting.get(dataset_name, "high")).strip().lower()
|
|
231
|
+
return sort_order == "low"
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def prepare_terms_for_dataset(dataset_name, matrix):
|
|
235
|
+
"""Prepare dataset-specific gold-standard terms and filtered matrix.
|
|
236
|
+
|
|
237
|
+
This computes:
|
|
238
|
+
- terms['used_genes'] as the intersection of terms['all_genes'] with either
|
|
239
|
+
shared genes (config['analysis_genes']=='shared') or the dataset genes
|
|
240
|
+
(config['analysis_genes']=='dataset_specific').
|
|
241
|
+
- genes_present_in_terms_<dataset_name>
|
|
242
|
+
|
|
243
|
+
Side effects:
|
|
244
|
+
- stores dataset-specific terms and genes list under:
|
|
245
|
+
dsave(..., 'common', f'terms_{dataset_name}')
|
|
246
|
+
dsave(..., 'common', f'genes_present_in_terms_{dataset_name}')
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
(terms, genes_present, matrix_filtered)
|
|
250
|
+
"""
|
|
251
|
+
config = dload("config")
|
|
252
|
+
if config is None:
|
|
253
|
+
raise RuntimeError(
|
|
254
|
+
"prepare_terms_for_dataset(): config not found. Run initialize() first."
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
terms_data = dload("common", "terms")
|
|
258
|
+
if terms_data is None or not isinstance(terms_data, pd.DataFrame):
|
|
259
|
+
raise ValueError(
|
|
260
|
+
"prepare_terms_for_dataset(): expected 'terms' to be a DataFrame, but got None or invalid type. "
|
|
261
|
+
"Make sure to run load_gold_standard() first."
|
|
262
|
+
)
|
|
263
|
+
terms = terms_data.copy()
|
|
264
|
+
|
|
265
|
+
analysis_genes = normalize_analysis_genes(config.get("analysis_genes"))
|
|
266
|
+
|
|
267
|
+
if analysis_genes == "shared":
|
|
268
|
+
common_genes = dload("common", "common_genes")
|
|
269
|
+
if common_genes is None:
|
|
270
|
+
raise ValueError(
|
|
271
|
+
"prepare_terms_for_dataset(): common genes not found. "
|
|
272
|
+
"Run get_common_genes() or set analysis_genes='dataset_specific'."
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
common_genes_list = list(common_genes)
|
|
276
|
+
if len(common_genes_list) == 0:
|
|
277
|
+
raise ValueError(
|
|
278
|
+
"prepare_terms_for_dataset(): common genes is empty. "
|
|
279
|
+
"Run get_common_genes() or set analysis_genes='dataset_specific'."
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
gene_universe = set(common_genes_list)
|
|
283
|
+
log.info(f"Using shared genes approach: {len(gene_universe)} genes")
|
|
284
|
+
else:
|
|
285
|
+
gene_universe = set(matrix.index)
|
|
286
|
+
log.info(
|
|
287
|
+
f"Using dataset-specific approach for {dataset_name}: {len(gene_universe)} genes in dataset"
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
terms["used_genes"] = terms["all_genes"].apply(
|
|
291
|
+
lambda genes: list(set(genes) & gene_universe)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
min_genes_raw = config.get("min_genes_in_complex", 3)
|
|
295
|
+
min_genes = int(min_genes_raw) if min_genes_raw is not None else 3
|
|
296
|
+
terms["n_used_genes"] = terms["used_genes"].apply(len)
|
|
297
|
+
terms = terms[terms["n_used_genes"] >= min_genes]
|
|
298
|
+
|
|
299
|
+
if bool(config.get("jaccard", False)):
|
|
300
|
+
before = len(terms)
|
|
301
|
+
terms = filter_duplicate_terms(terms)
|
|
302
|
+
log.done(
|
|
303
|
+
f"After Jaccard duplicate used_genes filtering for {dataset_name}: "
|
|
304
|
+
f"{len(terms)} terms ({before - len(terms)} removed)"
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
genes_present = list(
|
|
308
|
+
set(gene for genes_list in terms["used_genes"] for gene in genes_list)
|
|
309
|
+
)
|
|
310
|
+
log.info(f"Genes present in terms for {dataset_name}: {len(genes_present)}")
|
|
311
|
+
|
|
312
|
+
matrix_filtered = filter_matrix_by_genes(matrix, genes_present)
|
|
313
|
+
|
|
314
|
+
dsave(terms, "common", f"terms_{dataset_name}")
|
|
315
|
+
dsave(genes_present, "common", f"genes_present_in_terms_{dataset_name}")
|
|
316
|
+
|
|
317
|
+
return terms, genes_present, matrix_filtered
|
|
318
|
+
|
|
319
|
+
def pra(dataset_name, matrix, is_corr=False):
|
|
320
|
+
log.info(f"******************** {dataset_name} ********************")
|
|
321
|
+
log.started(f"** Global Precision-Recall Analysis - {dataset_name} **")
|
|
322
|
+
config = dload("config")
|
|
323
|
+
ascending = _sort_ascending_for_dataset(dataset_name)
|
|
324
|
+
|
|
325
|
+
if not is_corr:
|
|
326
|
+
matrix = perform_corr(matrix, config.get("corr_function"))
|
|
327
|
+
|
|
328
|
+
terms, _genes_present, matrix = prepare_terms_for_dataset(dataset_name, matrix)
|
|
329
|
+
log.info(f"Matrix shape: {matrix.shape}")
|
|
330
|
+
df = binary(matrix)
|
|
331
|
+
log.info(f"Pair-wise shape: {df.shape}")
|
|
332
|
+
df = quick_sort(df, ascending=ascending)
|
|
333
|
+
|
|
334
|
+
log.started("Building gene-to-pair indices")
|
|
335
|
+
gold_pair_to_complex = _build_gold_pair_to_complex(terms)
|
|
336
|
+
log.done("Gene-to-pair indices built.")
|
|
337
|
+
|
|
338
|
+
log.started("Precomputing complex IDs")
|
|
339
|
+
df = _precompute_complex_ids(df, gold_pair_to_complex)
|
|
340
|
+
log.done("Complex IDs precomputed.")
|
|
341
|
+
|
|
342
|
+
df["prediction"] = df["complex_ids"].astype(bool).astype(int)
|
|
343
|
+
df["complex_id"] = df["complex_ids"].apply(
|
|
344
|
+
lambda s: list(map(int, s.split(";"))) if s else []
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
if df["prediction"].sum() == 0:
|
|
348
|
+
log.info("No true positives found in dataset.")
|
|
349
|
+
pr_auc = np.nan
|
|
350
|
+
df["tp"] = 0
|
|
351
|
+
df["precision"] = np.nan
|
|
352
|
+
df["recall"] = np.nan
|
|
353
|
+
else:
|
|
354
|
+
tp = df["prediction"].cumsum()
|
|
355
|
+
df["tp"] = tp
|
|
356
|
+
precision = tp / (np.arange(len(df)) + 1)
|
|
357
|
+
recall = tp / tp.iloc[-1]
|
|
358
|
+
df["precision"] = precision
|
|
359
|
+
df["recall"] = recall
|
|
360
|
+
pr_auc = metrics.auc(recall, precision) if len(recall) >= 2 else np.nan
|
|
361
|
+
|
|
362
|
+
log.info(f"PR-AUC: {pr_auc:.4f}, Number of true positives: {df['prediction'].sum()}")
|
|
363
|
+
dsave(df, "pra", dataset_name)
|
|
364
|
+
dsave(pr_auc, "pr_auc", dataset_name)
|
|
365
|
+
dsave(_corrected_auc(df), "corrected_pr_auc", dataset_name)
|
|
366
|
+
|
|
367
|
+
log.done(f"Global PRA completed for {dataset_name}")
|
|
368
|
+
return df
|
|
369
|
+
|
|
370
|
+
# --------------------------------------------------------------------------
|
|
371
|
+
# helper functions for PRA per-complex analysis
|
|
372
|
+
# --------------------------------------------------------------------------
|
|
373
|
+
|
|
374
|
+
def _corrected_auc(df: pd.DataFrame) -> float:
|
|
375
|
+
if df.empty or "precision" not in df.columns or "recall" not in df.columns:
|
|
376
|
+
return np.nan
|
|
377
|
+
valid = df[["precision", "recall"]].replace([np.inf, -np.inf], np.nan).dropna()
|
|
378
|
+
if len(valid) < 2:
|
|
379
|
+
return np.nan
|
|
380
|
+
return np.trapz(valid["precision"], valid["recall"]) - valid["precision"].iloc[-1]
|
|
381
|
+
|
|
382
|
+
def _build_gene_to_pair_indices(pairwise_df):
|
|
383
|
+
indices = pairwise_df.index.values
|
|
384
|
+
genes = pd.concat([pairwise_df['gene1'], pairwise_df['gene2']], ignore_index=True)
|
|
385
|
+
stacked_indices = np.concatenate([indices, indices])
|
|
386
|
+
idx_series = pd.Series(stacked_indices, index=range(len(genes)))
|
|
387
|
+
gene_to_pair_indices = defaultdict(list)
|
|
388
|
+
for gene, group in idx_series.groupby(genes):
|
|
389
|
+
gene_to_pair_indices[gene] = group.values.tolist()
|
|
390
|
+
return gene_to_pair_indices
|
|
391
|
+
|
|
392
|
+
def _build_gold_pair_to_complex(terms):
|
|
393
|
+
pair_map = defaultdict(set)
|
|
394
|
+
for comp_id, genes in zip(terms.index, terms['used_genes']):
|
|
395
|
+
genes = list(genes)
|
|
396
|
+
if len(genes) < 2: continue
|
|
397
|
+
for i in range(len(genes)):
|
|
398
|
+
for j in range(i+1, len(genes)):
|
|
399
|
+
g1, g2 = sorted([genes[i], genes[j]])
|
|
400
|
+
pair_map[(g1, g2)].add(comp_id)
|
|
401
|
+
return pair_map
|
|
402
|
+
|
|
403
|
+
def _precompute_complex_ids(pairwise_df, gold_pair_to_complex):
|
|
404
|
+
if not gold_pair_to_complex:
|
|
405
|
+
pairwise_df['complex_ids'] = ''
|
|
406
|
+
return pairwise_df
|
|
407
|
+
|
|
408
|
+
# Precompute pairs as tuples
|
|
409
|
+
g1 = pairwise_df['gene1']
|
|
410
|
+
g2 = pairwise_df['gene2']
|
|
411
|
+
pairs = [tuple(sorted((a, b))) for a, b in zip(g1, g2)]
|
|
412
|
+
pairwise_df['complex_ids'] = [
|
|
413
|
+
';'.join(map(str, sorted(gold_pair_to_complex[p])))
|
|
414
|
+
if p in gold_pair_to_complex else ''
|
|
415
|
+
for p in pairs
|
|
416
|
+
]
|
|
417
|
+
return pairwise_df
|
|
418
|
+
|
|
419
|
+
def _dump_pairwise_memmap(df: pd.DataFrame, tag: str) -> Path:
|
|
420
|
+
tmp_dir = Path(os.path.join(".tmp", "mmap")) # Use .tmp/mmap/ for organization
|
|
421
|
+
tmp_dir.mkdir(parents=True, exist_ok=True) # Create if it doesn't exist
|
|
422
|
+
path = tmp_dir / f".pairwise_{_sanitize(tag)}.pkl"
|
|
423
|
+
dump(df, path, compress=0)
|
|
424
|
+
return path
|
|
425
|
+
|
|
426
|
+
# Global variables for worker processes (compatible with older joblib)
|
|
427
|
+
PAIRWISE_DF = None
|
|
428
|
+
GENE2IDX = None
|
|
429
|
+
|
|
430
|
+
def _init_worker_globals(memmap_path, gene_to_pair_indices):
|
|
431
|
+
"""Initialize global variables for worker processes"""
|
|
432
|
+
global PAIRWISE_DF, GENE2IDX
|
|
433
|
+
PAIRWISE_DF = load(memmap_path)
|
|
434
|
+
GENE2IDX = gene_to_pair_indices
|
|
435
|
+
|
|
436
|
+
def delete_memmap(memmap_path, log, wait_seconds=0.1):
|
|
437
|
+
|
|
438
|
+
gc.collect()
|
|
439
|
+
time.sleep(wait_seconds)
|
|
440
|
+
|
|
441
|
+
try:
|
|
442
|
+
os.remove(memmap_path)
|
|
443
|
+
log.info(f"Cleaned up temporary memmap file: {memmap_path}")
|
|
444
|
+
except OSError as e:
|
|
445
|
+
log.warning(f"Original error: {e}")
|
|
446
|
+
|
|
447
|
+
# --------------------------------------------------------------------------
|
|
448
|
+
# Process each chunk of terms
|
|
449
|
+
# --------------------------------------------------------------------------
|
|
450
|
+
def _process_chunk(chunk_terms, min_genes, memmap_path, gene_to_pair_indices):
|
|
451
|
+
"""Process a chunk of terms - compatible with older joblib versions"""
|
|
452
|
+
try:
|
|
453
|
+
# Load data in each worker (compatible with older joblib)
|
|
454
|
+
pairwise_df = load(memmap_path)
|
|
455
|
+
local_auc_scores = {}
|
|
456
|
+
local_corrected_auc_scores = {}
|
|
457
|
+
|
|
458
|
+
for idx, row in chunk_terms.iterrows():
|
|
459
|
+
gene_set = set(row.used_genes)
|
|
460
|
+
if len(gene_set) < min_genes:
|
|
461
|
+
continue
|
|
462
|
+
|
|
463
|
+
candidate_indices = bitarray(len(pairwise_df))
|
|
464
|
+
for g in gene_set:
|
|
465
|
+
if g in gene_to_pair_indices:
|
|
466
|
+
candidate_indices[gene_to_pair_indices[g]] = True
|
|
467
|
+
if not candidate_indices.any():
|
|
468
|
+
continue
|
|
469
|
+
|
|
470
|
+
selected = np.unpackbits(candidate_indices).view(bool)[:len(pairwise_df)]
|
|
471
|
+
sub_df = pairwise_df.iloc[selected]
|
|
472
|
+
|
|
473
|
+
complex_id = str(idx)
|
|
474
|
+
pattern = r'(?:^|;)' + re.escape(complex_id) + r'(?:;|$)'
|
|
475
|
+
true_label = sub_df["complex_ids"].str.contains(pattern, regex=True).astype(int)
|
|
476
|
+
mask = (sub_df["complex_ids"] == "") | (true_label == 1)
|
|
477
|
+
preds = true_label[mask]
|
|
478
|
+
|
|
479
|
+
if preds.sum() == 0:
|
|
480
|
+
continue
|
|
481
|
+
|
|
482
|
+
tp_cum = preds.cumsum()
|
|
483
|
+
precision = tp_cum / (np.arange(len(preds)) + 1)
|
|
484
|
+
recall = tp_cum / tp_cum.iloc[-1]
|
|
485
|
+
if len(recall) >= 2 and recall.iloc[-1] != 0:
|
|
486
|
+
# Compute regular AUC
|
|
487
|
+
local_auc_scores[idx] = metrics.auc(recall, precision)
|
|
488
|
+
# Compute corrected AUC using the same logic as _corrected_auc function
|
|
489
|
+
local_corrected_auc_scores[idx] = np.trapz(precision, recall) - precision.iloc[-1]
|
|
490
|
+
|
|
491
|
+
return {'auc': local_auc_scores, 'corrected_auc': local_corrected_auc_scores}
|
|
492
|
+
|
|
493
|
+
except Exception as e:
|
|
494
|
+
# Return error info for debugging
|
|
495
|
+
return {'error': str(e), 'chunk_size': len(chunk_terms)}
|
|
496
|
+
|
|
497
|
+
def pra_percomplex(dataset_name, matrix, is_corr=False, chunk_size=None, n_jobs=None):
|
|
498
|
+
log.started(f"*** Per-complex PRA started - {dataset_name} ***")
|
|
499
|
+
config = dload("config")
|
|
500
|
+
ascending = _sort_ascending_for_dataset(dataset_name)
|
|
501
|
+
per_complex_config = config.get("per_complex", {})
|
|
502
|
+
if not isinstance(per_complex_config, dict):
|
|
503
|
+
per_complex_config = {}
|
|
504
|
+
chunk_size_value = (
|
|
505
|
+
chunk_size if chunk_size is not None else per_complex_config.get("chunk_size", 200)
|
|
506
|
+
)
|
|
507
|
+
n_jobs_value = n_jobs if n_jobs is not None else per_complex_config.get("n_jobs", 4)
|
|
508
|
+
max_nbytes = per_complex_config.get("max_nbytes", "100M")
|
|
509
|
+
|
|
510
|
+
try:
|
|
511
|
+
effective_chunk_size = int(chunk_size_value)
|
|
512
|
+
effective_n_jobs = int(n_jobs_value)
|
|
513
|
+
except (TypeError, ValueError) as exc:
|
|
514
|
+
raise ValueError(
|
|
515
|
+
"per-complex chunk_size and n_jobs must be integer-compatible values."
|
|
516
|
+
) from exc
|
|
517
|
+
|
|
518
|
+
if effective_chunk_size <= 0:
|
|
519
|
+
raise ValueError("per-complex chunk_size must be greater than 0.")
|
|
520
|
+
if effective_n_jobs <= 0:
|
|
521
|
+
raise ValueError("per-complex n_jobs must be greater than 0.")
|
|
522
|
+
|
|
523
|
+
if not is_corr:
|
|
524
|
+
matrix = perform_corr(matrix, config.get("corr_function"))
|
|
525
|
+
|
|
526
|
+
# Prefer terms prepared by pra(); if absent, prepare them here so direct
|
|
527
|
+
# pra_percomplex() calls use the same dataset-specific gene universe.
|
|
528
|
+
terms = dload("common", f"terms_{dataset_name}")
|
|
529
|
+
genes_present = dload("common", f"genes_present_in_terms_{dataset_name}")
|
|
530
|
+
|
|
531
|
+
if not isinstance(terms, pd.DataFrame) or genes_present is None:
|
|
532
|
+
log.warning(
|
|
533
|
+
f"No dataset-specific terms found for {dataset_name}; preparing them now."
|
|
534
|
+
)
|
|
535
|
+
terms, genes_present, matrix = prepare_terms_for_dataset(dataset_name, matrix)
|
|
536
|
+
else:
|
|
537
|
+
matrix = filter_matrix_by_genes(matrix, genes_present)
|
|
538
|
+
|
|
539
|
+
log.info(f"Matrix shape: {matrix.shape}")
|
|
540
|
+
df = binary(matrix)
|
|
541
|
+
log.info(f"Pair-wise shape: {df.shape}")
|
|
542
|
+
df = quick_sort(df, ascending=ascending)
|
|
543
|
+
pairwise_df = df.copy()
|
|
544
|
+
pairwise_df['gene1'] = pairwise_df['gene1'].astype("category")
|
|
545
|
+
pairwise_df['gene2'] = pairwise_df['gene2'].astype("category")
|
|
546
|
+
|
|
547
|
+
# Use helper functions for precomputations
|
|
548
|
+
log.started("Building gene-to-pair indices")
|
|
549
|
+
gene_to_pair_indices = _build_gene_to_pair_indices(pairwise_df)
|
|
550
|
+
log.done("Building gene-to-pair indices")
|
|
551
|
+
|
|
552
|
+
log.started("Building gold pair to complex mapping")
|
|
553
|
+
gold_pair_to_complex = _build_gold_pair_to_complex(terms) # Now serial
|
|
554
|
+
log.done("Building gold pair to complex mapping")
|
|
555
|
+
|
|
556
|
+
log.started("Precomputing complex IDs")
|
|
557
|
+
pairwise_df = _precompute_complex_ids(pairwise_df, gold_pair_to_complex)
|
|
558
|
+
log.done("Precomputing complex IDs") #
|
|
559
|
+
|
|
560
|
+
chunks = [
|
|
561
|
+
terms.iloc[i:i + effective_chunk_size]
|
|
562
|
+
for i in range(0, len(terms), effective_chunk_size)
|
|
563
|
+
]
|
|
564
|
+
min_genes = config["min_genes_per_complex_analysis"]
|
|
565
|
+
|
|
566
|
+
if not chunks:
|
|
567
|
+
terms["auc_score"] = pd.Series(dtype=float)
|
|
568
|
+
terms["corrected_auc_score"] = pd.Series(dtype=float)
|
|
569
|
+
dsave(terms, "pra_percomplex", dataset_name)
|
|
570
|
+
log.done("Per-complex PRA completed with no eligible terms.")
|
|
571
|
+
return terms
|
|
572
|
+
|
|
573
|
+
log.info('Dumping pairwise_df to memmap')
|
|
574
|
+
memmap_path = _dump_pairwise_memmap(pairwise_df, dataset_name)
|
|
575
|
+
log.done('Dumping pairwise_df to memmap')
|
|
576
|
+
|
|
577
|
+
# Initialize results variable
|
|
578
|
+
results = None
|
|
579
|
+
|
|
580
|
+
try:
|
|
581
|
+
# Compatible parallel execution for older joblib versions
|
|
582
|
+
log.started("Processing chunks in parallel")
|
|
583
|
+
actual_n_jobs = min(effective_n_jobs, len(chunks))
|
|
584
|
+
log.info(
|
|
585
|
+
"Per-complex parallel config: "
|
|
586
|
+
f"n_jobs={actual_n_jobs}, requested_n_jobs={effective_n_jobs}, "
|
|
587
|
+
f"chunk_size={effective_chunk_size}, chunks={len(chunks)}, "
|
|
588
|
+
f"max_nbytes={max_nbytes}"
|
|
589
|
+
)
|
|
590
|
+
|
|
591
|
+
# Use a more conservative approach with older joblib
|
|
592
|
+
results = Parallel(
|
|
593
|
+
n_jobs=actual_n_jobs,
|
|
594
|
+
temp_folder=os.path.dirname(memmap_path),
|
|
595
|
+
max_nbytes=max_nbytes,
|
|
596
|
+
verbose=1 # Show progress
|
|
597
|
+
)(delayed(_process_chunk)(chunk, min_genes, memmap_path, gene_to_pair_indices)
|
|
598
|
+
for chunk in tqdm(chunks, desc="Per-complex PRA"))
|
|
599
|
+
|
|
600
|
+
log.done("Processing chunks in parallel")
|
|
601
|
+
|
|
602
|
+
except Exception as e:
|
|
603
|
+
log.error(f"Error during parallel processing: {e}")
|
|
604
|
+
log.error(f"Error type: {type(e).__name__}")
|
|
605
|
+
# Still try to clean up the memmap file
|
|
606
|
+
try:
|
|
607
|
+
if os.path.exists(memmap_path):
|
|
608
|
+
os.remove(memmap_path)
|
|
609
|
+
log.info(f"Cleaned up temporary memmap file after error: {memmap_path}")
|
|
610
|
+
except OSError as cleanup_error:
|
|
611
|
+
log.warning(f"Failed to remove memmap file after error {memmap_path}: {cleanup_error}")
|
|
612
|
+
raise # Re-raise the original exception
|
|
613
|
+
|
|
614
|
+
finally:
|
|
615
|
+
# Ensure cleanup happens regardless of success or failure
|
|
616
|
+
try:
|
|
617
|
+
if os.path.exists(memmap_path):
|
|
618
|
+
os.remove(memmap_path)
|
|
619
|
+
log.info(f"Cleaned up temporary memmap file: {memmap_path}")
|
|
620
|
+
except OSError as e:
|
|
621
|
+
log.warning(f"Failed to remove memmap file {memmap_path}: {e}")
|
|
622
|
+
|
|
623
|
+
# Merge results with enhanced error handling
|
|
624
|
+
auc_scores = {}
|
|
625
|
+
corrected_auc_scores = {}
|
|
626
|
+
errors = []
|
|
627
|
+
if results:
|
|
628
|
+
for i, res in enumerate(results):
|
|
629
|
+
if isinstance(res, dict):
|
|
630
|
+
if 'error' in res:
|
|
631
|
+
log.error(f"Error in chunk {i}: {res['error']}")
|
|
632
|
+
errors.append(f"chunk {i}: {res['error']}")
|
|
633
|
+
elif 'auc' in res and 'corrected_auc' in res:
|
|
634
|
+
# New format with both AUC types
|
|
635
|
+
auc_scores.update(res['auc'])
|
|
636
|
+
corrected_auc_scores.update(res['corrected_auc'])
|
|
637
|
+
else:
|
|
638
|
+
# Fallback for old format (backward compatibility)
|
|
639
|
+
auc_scores.update(res)
|
|
640
|
+
elif isinstance(res, tuple) and len(res) >= 2 and res[0] is None:
|
|
641
|
+
log.error(f"Chunk {i} error: {res[1]}")
|
|
642
|
+
errors.append(f"chunk {i}: {res[1]}")
|
|
643
|
+
else:
|
|
644
|
+
log.warning(f"Unexpected result type from chunk {i}: {type(res)} - {res}")
|
|
645
|
+
errors.append(f"chunk {i}: unexpected result type {type(res)}")
|
|
646
|
+
|
|
647
|
+
if errors:
|
|
648
|
+
preview = "; ".join(errors[:3])
|
|
649
|
+
extra = f" ({len(errors) - 3} more)" if len(errors) > 3 else ""
|
|
650
|
+
raise RuntimeError(f"Per-complex PRA failed in worker chunks: {preview}{extra}")
|
|
651
|
+
|
|
652
|
+
# Add the computed AUC scores to the terms DataFrame.
|
|
653
|
+
terms["auc_score"] = pd.Series(auc_scores)
|
|
654
|
+
terms["corrected_auc_score"] = pd.Series(corrected_auc_scores)
|
|
655
|
+
dsave(terms, "pra_percomplex", dataset_name)
|
|
656
|
+
log.done(f"Per-complex PRA completed.")
|
|
657
|
+
return terms
|
|
658
|
+
|
|
659
|
+
def complex_contributions(name):
|
|
660
|
+
log.info(f"Computing complex contributions (Greedy) for dataset: {name}")
|
|
661
|
+
pra = dload("pra", name)
|
|
662
|
+
terms = dload("common", f"terms_{name}")
|
|
663
|
+
if not isinstance(terms, pd.DataFrame):
|
|
664
|
+
# Fallback for backward compatibility
|
|
665
|
+
terms = dload("common", "terms")
|
|
666
|
+
if not isinstance(pra, pd.DataFrame) or pra.empty:
|
|
667
|
+
raise RuntimeError(f"complex_contributions(): PRA data for dataset '{name}' not found.")
|
|
668
|
+
if not isinstance(terms, pd.DataFrame) or terms.empty:
|
|
669
|
+
raise RuntimeError(f"complex_contributions(): terms for dataset '{name}' not found.")
|
|
670
|
+
|
|
671
|
+
# Respect the dataset's score direction: high scores by default, low scores if configured.
|
|
672
|
+
pra = pra.sort_values(
|
|
673
|
+
by='score',
|
|
674
|
+
ascending=_sort_ascending_for_dataset(name),
|
|
675
|
+
).reset_index(drop=True)
|
|
676
|
+
|
|
677
|
+
# Compute cumulative TP and precision (matches R's TP.count = cumsum(true), Precision = TP / (1:n))
|
|
678
|
+
pra['cumTP'] = pra['prediction'].cumsum()
|
|
679
|
+
pra['rank'] = pra.index + 1
|
|
680
|
+
pra['precision'] = pra['cumTP'] / pra['rank']
|
|
681
|
+
|
|
682
|
+
# R-style precision thresholds (matches c( min, seq(0.1, max, 0.025) ) rounded)
|
|
683
|
+
prec_min = pra['precision'].min()
|
|
684
|
+
prec_max = pra['precision'].max()
|
|
685
|
+
precision_cutoffs = [round(prec_min, 3)]
|
|
686
|
+
cutoffs_range = np.arange(0.1, prec_max + 0.001, 0.025)
|
|
687
|
+
precision_cutoffs += [round(t, 3) for t in cutoffs_range if t > prec_min]
|
|
688
|
+
thresholds = sorted(set(precision_cutoffs)) # Ensure unique and sorted
|
|
689
|
+
|
|
690
|
+
# Precompute positives for faster access
|
|
691
|
+
pos_mask = pra['prediction'] == 1
|
|
692
|
+
positives = pra[pos_mask].reset_index(drop=True)
|
|
693
|
+
|
|
694
|
+
# Compute global unique ordered IDs for initial tie-breaking (appearance order from all positives)
|
|
695
|
+
global_row_to_cids = []
|
|
696
|
+
for ids in positives['complex_id']:
|
|
697
|
+
if isinstance(ids, str):
|
|
698
|
+
cleaned = [str(int(float(i.strip()))) for i in ids.split(';') if i.strip()]
|
|
699
|
+
else:
|
|
700
|
+
cleaned = [str(int(i)) for i in ids if pd.notnull(i)]
|
|
701
|
+
global_row_to_cids.append(cleaned)
|
|
702
|
+
all_global_ids = [cid for cids in global_row_to_cids for cid in cids]
|
|
703
|
+
global_unique_ordered = list(OrderedDict.fromkeys(all_global_ids))
|
|
704
|
+
|
|
705
|
+
results = {}
|
|
706
|
+
valid_thresholds = [] # Track valid like R's ind.valid.precision
|
|
707
|
+
|
|
708
|
+
# Progress bar for the main loop (thresholds)
|
|
709
|
+
with tqdm(total=len(thresholds), desc="Processing thresholds", unit="thresh") as pbar:
|
|
710
|
+
for thresh_idx, t in enumerate(thresholds):
|
|
711
|
+
# Check if valid (matches R's ind.valid.precision)
|
|
712
|
+
if not (prec_min <= t <= prec_max):
|
|
713
|
+
pbar.update(1)
|
|
714
|
+
continue
|
|
715
|
+
valid_thresholds.append(thresh_idx) # Track for later sorting
|
|
716
|
+
|
|
717
|
+
# Find rightmost k where precision >= t (matches R's cand.ind[length(cand.ind)])
|
|
718
|
+
cand_mask = pra['precision'] >= t
|
|
719
|
+
if not cand_mask.any():
|
|
720
|
+
pbar.update(1)
|
|
721
|
+
continue
|
|
722
|
+
k = pra.index[cand_mask].max()
|
|
723
|
+
tp_target = pra.loc[k, 'cumTP']
|
|
724
|
+
if tp_target <= 0:
|
|
725
|
+
pbar.update(1)
|
|
726
|
+
continue
|
|
727
|
+
|
|
728
|
+
# Find first ind where cumTP == tp_target (matches R's tmp.ind[1])
|
|
729
|
+
matching_inds = pra[pra['cumTP'] == tp_target].index
|
|
730
|
+
if matching_inds.empty:
|
|
731
|
+
pbar.update(1)
|
|
732
|
+
continue
|
|
733
|
+
ind = matching_inds.min() # First (smallest) like R
|
|
734
|
+
|
|
735
|
+
# Get top (ind+1) rows, filter to prediction==1 and non-null complex_id
|
|
736
|
+
tmp = pra.iloc[0:ind + 1]
|
|
737
|
+
tmp = tmp[(tmp['prediction'] == 1) & tmp['complex_id'].notnull()].reset_index(drop=True)
|
|
738
|
+
if tmp.empty:
|
|
739
|
+
pbar.update(1)
|
|
740
|
+
continue
|
|
741
|
+
|
|
742
|
+
# Build row_to_cids as list of lists (str for consistency, matches R strsplit)
|
|
743
|
+
row_to_cids = []
|
|
744
|
+
for ids in tmp['complex_id']:
|
|
745
|
+
if isinstance(ids, str):
|
|
746
|
+
cleaned = [str(int(float(i.strip()))) for i in ids.split(';') if i.strip()]
|
|
747
|
+
else:
|
|
748
|
+
cleaned = [str(int(i)) for i in ids if pd.notnull(i)]
|
|
749
|
+
row_to_cids.append(cleaned)
|
|
750
|
+
|
|
751
|
+
N = len(row_to_cids)
|
|
752
|
+
cid_to_rows = defaultdict(list)
|
|
753
|
+
for row_idx in range(N):
|
|
754
|
+
for cid in row_to_cids[row_idx]:
|
|
755
|
+
cid_to_rows[cid].append(row_idx)
|
|
756
|
+
|
|
757
|
+
current_size = {cid: len(lst) for cid, lst in cid_to_rows.items()}
|
|
758
|
+
covered = np.zeros(N, dtype=bool)
|
|
759
|
+
remaining_rows = list(range(N)) # Track remaining for tie-breaking
|
|
760
|
+
final_contrib = {}
|
|
761
|
+
is_first = True # Flag for initial greedy step
|
|
762
|
+
|
|
763
|
+
while current_size:
|
|
764
|
+
if not current_size:
|
|
765
|
+
break
|
|
766
|
+
max_contrib = max(current_size.values())
|
|
767
|
+
candidates = [cid for cid, cnt in current_size.items() if cnt == max_contrib]
|
|
768
|
+
|
|
769
|
+
if len(candidates) == 1:
|
|
770
|
+
top_cid = candidates[0]
|
|
771
|
+
else:
|
|
772
|
+
if is_first:
|
|
773
|
+
# Initial tie-break: first in global appearance order (matches R's global matrix row order)
|
|
774
|
+
positions = {cid: global_unique_ordered.index(cid) for cid in candidates if cid in global_unique_ordered}
|
|
775
|
+
top_cid = min(positions, key=positions.get)
|
|
776
|
+
else:
|
|
777
|
+
# Subsequent: first in local remaining appearance order
|
|
778
|
+
all_ids = [cid for ri in remaining_rows for cid in row_to_cids[ri]]
|
|
779
|
+
unique_ordered = list(OrderedDict.fromkeys(all_ids))
|
|
780
|
+
positions = {cid: unique_ordered.index(cid) for cid in candidates if cid in unique_ordered}
|
|
781
|
+
top_cid = min(positions, key=positions.get) # Earliest appearance
|
|
782
|
+
|
|
783
|
+
contrib = current_size[top_cid]
|
|
784
|
+
if contrib <= 0:
|
|
785
|
+
current_size.pop(top_cid, None)
|
|
786
|
+
continue
|
|
787
|
+
|
|
788
|
+
# Cover the remaining rows for top_cid
|
|
789
|
+
for row_idx in cid_to_rows[top_cid]:
|
|
790
|
+
if not covered[row_idx]:
|
|
791
|
+
covered[row_idx] = True
|
|
792
|
+
for cid in row_to_cids[row_idx]:
|
|
793
|
+
if cid in current_size:
|
|
794
|
+
current_size[cid] -= 1
|
|
795
|
+
if current_size[cid] <= 0:
|
|
796
|
+
current_size.pop(cid, None)
|
|
797
|
+
|
|
798
|
+
# Update remaining_rows (remove covered)
|
|
799
|
+
remaining_rows = [ri for ri in remaining_rows if not covered[ri]]
|
|
800
|
+
|
|
801
|
+
final_contrib[top_cid] = contrib
|
|
802
|
+
is_first = False # Only first time is special
|
|
803
|
+
|
|
804
|
+
# Store for this threshold
|
|
805
|
+
for cid, count in final_contrib.items():
|
|
806
|
+
if cid not in results:
|
|
807
|
+
results[cid] = [0] * len(thresholds)
|
|
808
|
+
results[cid][thresh_idx] = count
|
|
809
|
+
|
|
810
|
+
pbar.update(1) # Update progress after processing threshold
|
|
811
|
+
|
|
812
|
+
# Build result DataFrame (index=cid as str)
|
|
813
|
+
r = pd.DataFrame(results, index=thresholds).T
|
|
814
|
+
r.index = r.index.astype(str)
|
|
815
|
+
|
|
816
|
+
# Filter to non-zero first (matches R's nonzero.cont.ind)
|
|
817
|
+
r = r[r.sum(axis=1) > 0]
|
|
818
|
+
|
|
819
|
+
# Intersect with terms IDs, preserving terms order
|
|
820
|
+
gold_ids = set(r.index)
|
|
821
|
+
common_ids = [str(id) for id in terms.index if str(id) in gold_ids]
|
|
822
|
+
r = r.loc[common_ids]
|
|
823
|
+
|
|
824
|
+
# Map Names and insert as first column
|
|
825
|
+
t = pd.Series(terms['Name'].values, index=terms.index.astype(str))
|
|
826
|
+
r.insert(0, 'Name', r.index.map(t))
|
|
827
|
+
|
|
828
|
+
# Set all column names: Name + Precision_*
|
|
829
|
+
precision_cols = [f"Precision_{t}" for t in thresholds]
|
|
830
|
+
r.columns = ['Name'] + precision_cols
|
|
831
|
+
|
|
832
|
+
# Sort by the last valid precision column descending, stable sort (matches R's stable order)
|
|
833
|
+
if valid_thresholds:
|
|
834
|
+
last_valid_col = f"Precision_{thresholds[valid_thresholds[-1]]}"
|
|
835
|
+
r = r.sort_values(by=last_valid_col, ascending=False, kind='stable')
|
|
836
|
+
|
|
837
|
+
# De-duplicate by Name, keeping first (matches R's !duplicated(Name) after function)
|
|
838
|
+
r = r[~r['Name'].duplicated(keep='first')].reset_index(drop=True)
|
|
839
|
+
|
|
840
|
+
dsave(r, "complex_contributions", name)
|
|
841
|
+
log.info(f"Complex contribution (Greedy) completed for dataset: {name}")
|
|
842
|
+
return r
|
|
843
|
+
|
|
844
|
+
# --------------------------------------------------------------------------
|
|
845
|
+
# Helpers
|
|
846
|
+
# --------------------------------------------------------------------------
|
|
847
|
+
|
|
848
|
+
def perform_corr(df, corr_func):
|
|
849
|
+
if corr_func not in {"numpy", "numpy_without_mask","pandas","numba"}:
|
|
850
|
+
raise ValueError("corr_func must be 'numpy' or 'pandas'")
|
|
851
|
+
|
|
852
|
+
log.started(f"Performing correlation using '{corr_func}' method.")
|
|
853
|
+
|
|
854
|
+
x_axis, y_axis = df.shape
|
|
855
|
+
log.info(f"Data shape: {x_axis} features, {y_axis} samples")
|
|
856
|
+
|
|
857
|
+
if corr_func == "numpy":
|
|
858
|
+
M = np.ma.masked_invalid(df.values)
|
|
859
|
+
corr = np.ma.corrcoef(M)
|
|
860
|
+
arr = corr.filled(np.nan)
|
|
861
|
+
df_corr = pd.DataFrame(arr, index=df.index, columns=df.index)
|
|
862
|
+
np.fill_diagonal(df_corr.values, np.nan)
|
|
863
|
+
# check shape is x_axis x x_axis
|
|
864
|
+
if df_corr.shape != (x_axis, x_axis):
|
|
865
|
+
raise ValueError(f"Correlation matrix shape mismatch: expected ({x_axis}, {x_axis}), got {df_corr.shape}")
|
|
866
|
+
log.done("Correlation.")
|
|
867
|
+
return df_corr
|
|
868
|
+
|
|
869
|
+
elif corr_func == "numpy_without_mask":
|
|
870
|
+
corr = np.corrcoef(df.values)
|
|
871
|
+
df_corr = pd.DataFrame(corr, index=df.index, columns=df.index)
|
|
872
|
+
np.fill_diagonal(df_corr.values, np.nan)
|
|
873
|
+
if df_corr.shape != (x_axis, x_axis):
|
|
874
|
+
raise ValueError(f"Correlation matrix shape mismatch: expected ({x_axis}, {x_axis}), got {df_corr.shape}")
|
|
875
|
+
log.done("Correlation.")
|
|
876
|
+
return df_corr
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
elif corr_func == "numba":
|
|
880
|
+
corr = fast_corr(df)
|
|
881
|
+
np.fill_diagonal(corr.values, np.nan)
|
|
882
|
+
if corr.shape != (x_axis, x_axis):
|
|
883
|
+
raise ValueError(f"Correlation matrix shape mismatch: expected ({x_axis}, {x_axis}), got {corr.shape}")
|
|
884
|
+
log.done("Correlation using Numba.")
|
|
885
|
+
return corr
|
|
886
|
+
|
|
887
|
+
else:
|
|
888
|
+
# Compute correlations and modify diagonal in-place
|
|
889
|
+
corr = df.T.corr()
|
|
890
|
+
np.fill_diagonal(corr.values, np.nan)
|
|
891
|
+
if corr.shape != (x_axis, x_axis):
|
|
892
|
+
raise ValueError(f"Correlation matrix shape mismatch: expected ({x_axis}, {x_axis}), got {corr.shape}")
|
|
893
|
+
return corr
|
|
894
|
+
|
|
895
|
+
def fast_corr(df):
|
|
896
|
+
@njit(parallel=True)
|
|
897
|
+
def compute_corr(data):
|
|
898
|
+
m, n = data.shape
|
|
899
|
+
corr = np.full((n, n), np.nan, dtype=np.float64)
|
|
900
|
+
# Compute off-diagonal (upper triangle, parallel over i)
|
|
901
|
+
for i in prange(n):
|
|
902
|
+
for j in range(i + 1, n):
|
|
903
|
+
sum_x = 0.0
|
|
904
|
+
sum_y = 0.0
|
|
905
|
+
sum_xx = 0.0
|
|
906
|
+
sum_yy = 0.0
|
|
907
|
+
sum_xy = 0.0
|
|
908
|
+
count = 0
|
|
909
|
+
for k in range(m):
|
|
910
|
+
x = data[k, i]
|
|
911
|
+
y = data[k, j]
|
|
912
|
+
if not np.isnan(x) and not np.isnan(y):
|
|
913
|
+
sum_x += x
|
|
914
|
+
sum_y += y
|
|
915
|
+
sum_xx += x * x
|
|
916
|
+
sum_yy += y * y
|
|
917
|
+
sum_xy += x * y
|
|
918
|
+
count += 1
|
|
919
|
+
if count >= 2:
|
|
920
|
+
# Sample variance/covariance (div by count-1)
|
|
921
|
+
var_x = (sum_xx - (sum_x ** 2) / count) / (count - 1)
|
|
922
|
+
var_y = (sum_yy - (sum_y ** 2) / count) / (count - 1)
|
|
923
|
+
cov = (sum_xy - (sum_x * sum_y) / count) / (count - 1)
|
|
924
|
+
denom = np.sqrt(var_x * var_y)
|
|
925
|
+
if denom > 0: # Avoid div-by-zero (e.g., constant cols -> nan)
|
|
926
|
+
r = cov / denom
|
|
927
|
+
else:
|
|
928
|
+
r = np.nan
|
|
929
|
+
else:
|
|
930
|
+
r = np.nan
|
|
931
|
+
corr[i, j] = r
|
|
932
|
+
corr[j, i] = r # Symmetric
|
|
933
|
+
# Compute diagonal in parallel
|
|
934
|
+
for i in prange(n):
|
|
935
|
+
sum_x = 0.0
|
|
936
|
+
sum_xx = 0.0
|
|
937
|
+
count = 0
|
|
938
|
+
for k in range(m):
|
|
939
|
+
x = data[k, i]
|
|
940
|
+
if not np.isnan(x):
|
|
941
|
+
sum_x += x
|
|
942
|
+
sum_xx += x * x
|
|
943
|
+
count += 1
|
|
944
|
+
if count >= 2:
|
|
945
|
+
var_x = (sum_xx - (sum_x ** 2) / count) / (count - 1)
|
|
946
|
+
if var_x > 0:
|
|
947
|
+
corr[i, i] = 1.0
|
|
948
|
+
else:
|
|
949
|
+
corr[i, i] = np.nan # Constant column
|
|
950
|
+
else:
|
|
951
|
+
corr[i, i] = np.nan
|
|
952
|
+
return corr
|
|
953
|
+
|
|
954
|
+
df_numeric = df.select_dtypes(include=np.number)
|
|
955
|
+
data = df_numeric.to_numpy().T
|
|
956
|
+
corr_matrix = compute_corr(data)
|
|
957
|
+
corr_df = pd.DataFrame(corr_matrix, index=df_numeric.index, columns=df_numeric.index)
|
|
958
|
+
return corr_df
|
|
959
|
+
|
|
960
|
+
def is_symmetric(df):
|
|
961
|
+
return np.allclose(df, df.T, equal_nan=True)
|
|
962
|
+
|
|
963
|
+
def binary(corr):
|
|
964
|
+
log.started("Converting correlation matrix to pair-wise format.")
|
|
965
|
+
if is_symmetric(corr):
|
|
966
|
+
corr = convert_full_to_half_matrix(corr)
|
|
967
|
+
|
|
968
|
+
stack = corr.stack().rename_axis(index=['gene1', 'gene2']).\
|
|
969
|
+
reset_index().rename(columns={0: 'score'})
|
|
970
|
+
if stack.empty:
|
|
971
|
+
log.done("Pair-wise conversion.")
|
|
972
|
+
return stack
|
|
973
|
+
if has_mirror_of_first_pair(stack):
|
|
974
|
+
log.info("Mirror pairs detected. Dropping them to ensure unique gene pairs.")
|
|
975
|
+
stack = drop_mirror_pairs(stack)
|
|
976
|
+
log.done("Pair-wise conversion.")
|
|
977
|
+
return stack
|
|
978
|
+
|
|
979
|
+
def has_mirror_of_first_pair(df):
|
|
980
|
+
g1, g2 = df.iloc[0]['gene1'], df.iloc[0]['gene2']
|
|
981
|
+
mirror_exists = ((df['gene1'] == g2) & (df['gene2'] == g1)).iloc[1:].any()
|
|
982
|
+
return mirror_exists
|
|
983
|
+
|
|
984
|
+
def convert_full_to_half_matrix(df):
|
|
985
|
+
if not is_symmetric(df):
|
|
986
|
+
raise ValueError("Matrix must be symmetric to convert to half matrix.")
|
|
987
|
+
|
|
988
|
+
log.started("Converting full correlation matrix to upper triangle (half-matrix) format.")
|
|
989
|
+
arr = df.values.copy()
|
|
990
|
+
arr[np.tril_indices_from(arr)] = np.nan # zero-based lower triangle + diagonal → NaN
|
|
991
|
+
log.done("Matrix conversion.")
|
|
992
|
+
return pd.DataFrame(arr, index=df.index, columns=df.columns)
|
|
993
|
+
|
|
994
|
+
def drop_mirror_pairs(df):
|
|
995
|
+
log.started("Dropping mirror pairs to ensure unique gene pairs (Optimized).")
|
|
996
|
+
gene_pairs = np.sort(df[["gene1", "gene2"]].to_numpy(), axis=1)
|
|
997
|
+
df.loc[:, ["gene1", "gene2"]] = gene_pairs
|
|
998
|
+
df = df.loc[~df.duplicated(subset=["gene1", "gene2"], keep="first")]
|
|
999
|
+
log.done("Mirror pairs are dropped.")
|
|
1000
|
+
return df
|
|
1001
|
+
|
|
1002
|
+
def quick_sort(df, ascending=False):
|
|
1003
|
+
log.started(f"Pair-wise matrix is sorting based on the 'score' column: ascending:{ascending}")
|
|
1004
|
+
order = 1 if ascending else -1
|
|
1005
|
+
sorted_df = df.iloc[np.argsort(order * df["score"].values)].reset_index(drop=True)
|
|
1006
|
+
log.done("Pair-wise matrix sorting.")
|
|
1007
|
+
return sorted_df
|
|
1008
|
+
|
|
1009
|
+
def save_results_to_csv(categories = ["complex_contributions", "pr_auc", "pra_percomplex", "mpr_complexes_auc"]):
|
|
1010
|
+
|
|
1011
|
+
config = dload("config") # Load config to get output folder
|
|
1012
|
+
output_folder = Path(config.get("output_folder", "output"))
|
|
1013
|
+
output_folder = output_folder / "csv" # Create a subfolder for results
|
|
1014
|
+
output_folder.mkdir(parents=True, exist_ok=True) # Ensure output folder exists
|
|
1015
|
+
|
|
1016
|
+
for category in categories:
|
|
1017
|
+
data = dload(category) # Load the data for this category
|
|
1018
|
+
if data is None:
|
|
1019
|
+
log.warning(f"No data found for category '{category}'. Skipping save.")
|
|
1020
|
+
continue
|
|
1021
|
+
|
|
1022
|
+
if category == "mpr_complexes_auc" and isinstance(data, dict):
|
|
1023
|
+
# Dict[dataset_name -> Dict[variant_key -> auc]]
|
|
1024
|
+
try:
|
|
1025
|
+
df = pd.DataFrame.from_dict(data, orient="index")
|
|
1026
|
+
df.index.name = "Dataset"
|
|
1027
|
+
csv_path = output_folder / f"{category}.csv"
|
|
1028
|
+
df.to_csv(csv_path, index=True)
|
|
1029
|
+
log.info(f"Saved '{category}' to {csv_path}")
|
|
1030
|
+
except Exception as e:
|
|
1031
|
+
log.warning(f"Failed to convert and save '{category}': {e}")
|
|
1032
|
+
continue
|
|
1033
|
+
|
|
1034
|
+
if category == "pr_auc" and isinstance(data, dict):
|
|
1035
|
+
# Special handling: Convert dict to DataFrame (assuming keys are indices, values are data)
|
|
1036
|
+
# If values are scalars, create a simple DF with 'Dataset' and 'AUC' columns
|
|
1037
|
+
try:
|
|
1038
|
+
df = pd.DataFrame.from_dict(data, orient='index', columns=['AUC'])
|
|
1039
|
+
df.index.name = 'Dataset'
|
|
1040
|
+
txt_path = output_folder / f"{category}.txt"
|
|
1041
|
+
df.to_csv(txt_path, sep='\t', index=True) # Save as tab-delimited TXT
|
|
1042
|
+
log.info(f"Saved '{category}' as tabular TXT to {txt_path}")
|
|
1043
|
+
except Exception as e:
|
|
1044
|
+
log.warning(f"Failed to convert and save '{category}' as TXT: {e}")
|
|
1045
|
+
continue # Skip to next category after handling pr_auc
|
|
1046
|
+
|
|
1047
|
+
if isinstance(data, dict):
|
|
1048
|
+
# If it's a dict of datasets, save each as a separate CSV
|
|
1049
|
+
for key, df in data.items():
|
|
1050
|
+
if isinstance(df, pd.DataFrame):
|
|
1051
|
+
csv_path = output_folder / f"{category}_{key}.csv"
|
|
1052
|
+
df.to_csv(csv_path, index=False)
|
|
1053
|
+
log.info(f"Saved '{category}_{key}' to {csv_path}")
|
|
1054
|
+
else:
|
|
1055
|
+
log.warning(f"Skipping non-DataFrame item '{key}' in '{category}'.")
|
|
1056
|
+
elif isinstance(data, pd.DataFrame):
|
|
1057
|
+
# If it's a single DataFrame, save it directly
|
|
1058
|
+
csv_path = output_folder / f"{category}.csv"
|
|
1059
|
+
data.to_csv(csv_path, index=False)
|
|
1060
|
+
log.info(f"Saved '{category}' to {csv_path}")
|
|
1061
|
+
else:
|
|
1062
|
+
log.warning(f"Unsupported data type for '{category}'. Expected DataFrame or dict of DataFrames. Skipping.")
|
|
1063
|
+
|
|
1064
|
+
log.done("Results saved to CSV files in the output folder.")
|
|
1065
|
+
|
|
1066
|
+
# -----------------------------------------------------------------------------
|
|
1067
|
+
# mPR preparation (module-level precision–recall, Fig. 1E / 1F)
|
|
1068
|
+
# -----------------------------------------------------------------------------
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def _mpr_get_mtRibo_ETCI_ids(terms_like):
|
|
1072
|
+
"""
|
|
1073
|
+
Identify mitochondrial ribosome and ETC I complexes to remove.
|
|
1074
|
+
|
|
1075
|
+
Rule (matching the FLEX paper):
|
|
1076
|
+
- Name contains 'Respiratory chain complex I (holoenzyme)'
|
|
1077
|
+
- OR Name contains '55S'
|
|
1078
|
+
"""
|
|
1079
|
+
if "Name" not in terms_like.columns:
|
|
1080
|
+
raise KeyError("mpr_prepare(): expected a 'Name' column in the CORUM terms.")
|
|
1081
|
+
|
|
1082
|
+
name = terms_like["Name"].astype(str)
|
|
1083
|
+
mask = name.str.contains(
|
|
1084
|
+
"Respiratory chain complex I \\(holoenzyme\\)", case=False, regex=True
|
|
1085
|
+
) | name.str.contains("55S", case=False, regex=False)
|
|
1086
|
+
|
|
1087
|
+
return set(terms_like.index[mask])
|
|
1088
|
+
|
|
1089
|
+
|
|
1090
|
+
def _mpr_get_small_high_auprc_ids(
|
|
1091
|
+
pra_percomplex, size_th=30, auprc_th=0.4, use_corrected=True
|
|
1092
|
+
):
|
|
1093
|
+
"""
|
|
1094
|
+
Identify complexes that are small and have high per-complex AUPRC.
|
|
1095
|
+
|
|
1096
|
+
Small: full CORUM size (Length) < size_th
|
|
1097
|
+
High AUPRC: per-complex AUPRC >= auprc_th
|
|
1098
|
+
"""
|
|
1099
|
+
if "Length" not in pra_percomplex.columns:
|
|
1100
|
+
raise KeyError(
|
|
1101
|
+
"mpr_prepare(): expected a 'Length' column in the per-complex table."
|
|
1102
|
+
)
|
|
1103
|
+
|
|
1104
|
+
if use_corrected and "corrected_auc_score" in pra_percomplex.columns:
|
|
1105
|
+
score_col = "corrected_auc_score"
|
|
1106
|
+
elif "auc_score" in pra_percomplex.columns:
|
|
1107
|
+
score_col = "auc_score"
|
|
1108
|
+
else:
|
|
1109
|
+
raise KeyError(
|
|
1110
|
+
"mpr_prepare(): expected 'corrected_auc_score' or 'auc_score' in the per-complex table."
|
|
1111
|
+
)
|
|
1112
|
+
|
|
1113
|
+
size_mask = pra_percomplex["Length"] < size_th
|
|
1114
|
+
score_mask = pra_percomplex[score_col] >= auprc_th
|
|
1115
|
+
|
|
1116
|
+
mask = size_mask & score_mask
|
|
1117
|
+
return set(pra_percomplex.index[mask])
|
|
1118
|
+
|
|
1119
|
+
|
|
1120
|
+
# -------------------------------------------------------------------------
|
|
1121
|
+
# Helpers implementing the FLEX stepwise module-level PR logic
|
|
1122
|
+
# -------------------------------------------------------------------------
|
|
1123
|
+
|
|
1124
|
+
def _mpr_build_pairs(pra, removed_ids=None, ascending=False):
|
|
1125
|
+
"""
|
|
1126
|
+
Build a Pairs.in.data-like table for mPR / stepwise contributions.
|
|
1127
|
+
|
|
1128
|
+
Rows containing filtered positive complex IDs are removed from the ranking,
|
|
1129
|
+
matching the FLEX stepwise module-level precision-recall behavior.
|
|
1130
|
+
|
|
1131
|
+
Input:
|
|
1132
|
+
pra : DataFrame with at least columns
|
|
1133
|
+
- 'score' : ranking score
|
|
1134
|
+
- 'complex_id' : complex annotations
|
|
1135
|
+
removed_ids : set[int] of complexes to remove
|
|
1136
|
+
|
|
1137
|
+
Output:
|
|
1138
|
+
DataFrame with columns:
|
|
1139
|
+
- predicted : score
|
|
1140
|
+
- true : 0/1
|
|
1141
|
+
- complex_ids : list[int] per row
|
|
1142
|
+
"""
|
|
1143
|
+
if "complex_id" not in pra.columns and "complex_ids" not in pra.columns:
|
|
1144
|
+
raise RuntimeError(
|
|
1145
|
+
"mpr_prepare(): expected a 'complex_id' or 'complex_ids' column in 'pra'."
|
|
1146
|
+
)
|
|
1147
|
+
|
|
1148
|
+
removed_ids = set(int(x) for x in (removed_ids or []))
|
|
1149
|
+
|
|
1150
|
+
df = pra.copy()
|
|
1151
|
+
|
|
1152
|
+
# Normalize complex-ID column name
|
|
1153
|
+
if "complex_id" in df.columns:
|
|
1154
|
+
cid_col = "complex_id"
|
|
1155
|
+
else:
|
|
1156
|
+
cid_col = "complex_ids"
|
|
1157
|
+
|
|
1158
|
+
if "score" not in df.columns:
|
|
1159
|
+
raise RuntimeError("mpr_prepare(): expected a 'score' column in 'pra'.")
|
|
1160
|
+
|
|
1161
|
+
def normalize_ids(cell):
|
|
1162
|
+
"""Parse complex IDs from various formats."""
|
|
1163
|
+
if isinstance(cell, (list, tuple, np.ndarray, pd.Series)):
|
|
1164
|
+
return [int(x) for x in cell if pd.notnull(x)]
|
|
1165
|
+
elif isinstance(cell, str):
|
|
1166
|
+
if not cell:
|
|
1167
|
+
return []
|
|
1168
|
+
parts = [p for p in cell.split(";") if p]
|
|
1169
|
+
return [int(float(p)) for p in parts]
|
|
1170
|
+
elif pd.isna(cell):
|
|
1171
|
+
return []
|
|
1172
|
+
else:
|
|
1173
|
+
try:
|
|
1174
|
+
return [int(cell)]
|
|
1175
|
+
except Exception:
|
|
1176
|
+
return []
|
|
1177
|
+
|
|
1178
|
+
def should_remove(cell):
|
|
1179
|
+
"""Check if this row should be removed (contains any removed_id AND is a TP)."""
|
|
1180
|
+
ids = normalize_ids(cell)
|
|
1181
|
+
if not ids:
|
|
1182
|
+
return False # Not a TP, keep it
|
|
1183
|
+
# Remove if ANY of the IDs is in removed_ids
|
|
1184
|
+
return any(cid in removed_ids for cid in ids)
|
|
1185
|
+
|
|
1186
|
+
# Build output DataFrame
|
|
1187
|
+
out = pd.DataFrame(index=df.index)
|
|
1188
|
+
out["predicted"] = df["score"].astype(float)
|
|
1189
|
+
out["complex_ids"] = df[cid_col].apply(normalize_ids)
|
|
1190
|
+
out["true"] = out["complex_ids"].apply(lambda ids: 1 if len(ids) > 0 else 0)
|
|
1191
|
+
|
|
1192
|
+
# Remove rows that are TPs and contain a removed complex ID.
|
|
1193
|
+
if removed_ids:
|
|
1194
|
+
should_remove_mask = df[cid_col].apply(should_remove)
|
|
1195
|
+
remove_mask = should_remove_mask & (out["true"] == 1)
|
|
1196
|
+
out = out[~remove_mask].copy()
|
|
1197
|
+
|
|
1198
|
+
# Also filter the complex_ids to remove the removed IDs (for stepwise contributions)
|
|
1199
|
+
if removed_ids:
|
|
1200
|
+
out["complex_ids"] = out["complex_ids"].apply(
|
|
1201
|
+
lambda ids: [cid for cid in ids if cid not in removed_ids]
|
|
1202
|
+
)
|
|
1203
|
+
|
|
1204
|
+
# Sort by the dataset's configured score direction.
|
|
1205
|
+
out = out.sort_values("predicted", ascending=ascending).reset_index(drop=True)
|
|
1206
|
+
return out
|
|
1207
|
+
|
|
1208
|
+
|
|
1209
|
+
def _mpr_precision_cutoffs_from_pairs(pairs, step=0.025):
|
|
1210
|
+
"""
|
|
1211
|
+
Choose precision cutoffs similar to FLEX:
|
|
1212
|
+
- start at min positive precision
|
|
1213
|
+
- add grid 0.10, 0.125, 0.15, ... up to max precision
|
|
1214
|
+
"""
|
|
1215
|
+
true = pairs["true"].to_numpy(dtype=int)
|
|
1216
|
+
n = len(true)
|
|
1217
|
+
if n == 0 or true.sum() == 0:
|
|
1218
|
+
return np.array([1.0], dtype=float)
|
|
1219
|
+
|
|
1220
|
+
tp_cum = true.cumsum()
|
|
1221
|
+
denom = np.arange(n, dtype=float) + 1.0
|
|
1222
|
+
precision = tp_cum / denom
|
|
1223
|
+
|
|
1224
|
+
pos_prec = precision[true == 1]
|
|
1225
|
+
min_p = float(pos_prec.min())
|
|
1226
|
+
max_p = float(precision.max())
|
|
1227
|
+
|
|
1228
|
+
cuts = [round(min_p, 3)]
|
|
1229
|
+
|
|
1230
|
+
v = 0.10
|
|
1231
|
+
while v <= max_p + 1e-9:
|
|
1232
|
+
if v > min_p:
|
|
1233
|
+
cuts.append(round(v, 3))
|
|
1234
|
+
v += step
|
|
1235
|
+
|
|
1236
|
+
cuts = sorted(set(cuts))
|
|
1237
|
+
return np.array(cuts, dtype=float)
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
def _mpr_stepwise_contributions(pairs, precision_cutoffs, ascending=False):
|
|
1241
|
+
"""
|
|
1242
|
+
Greedy, stepwise TP allocation per complex at each precision cutoff.
|
|
1243
|
+
|
|
1244
|
+
Input:
|
|
1245
|
+
pairs : DataFrame with columns
|
|
1246
|
+
- predicted (float)
|
|
1247
|
+
- true (0/1)
|
|
1248
|
+
- complex_ids : list[int]
|
|
1249
|
+
precision_cutoffs : 1D array of precision thresholds
|
|
1250
|
+
|
|
1251
|
+
Output:
|
|
1252
|
+
contrib_df : DataFrame [complex_id x cutoff] with TP counts
|
|
1253
|
+
"""
|
|
1254
|
+
pairs = pairs.copy()
|
|
1255
|
+
pairs = pairs.sort_values("predicted", ascending=ascending).reset_index(drop=True)
|
|
1256
|
+
|
|
1257
|
+
true = pairs["true"].to_numpy(dtype=int)
|
|
1258
|
+
n = len(true)
|
|
1259
|
+
if n == 0 or true.sum() == 0:
|
|
1260
|
+
return pd.DataFrame()
|
|
1261
|
+
|
|
1262
|
+
tp_cum = true.cumsum()
|
|
1263
|
+
denom = np.arange(n, dtype=float) + 1.0
|
|
1264
|
+
precision = tp_cum / denom
|
|
1265
|
+
|
|
1266
|
+
complex_lists = []
|
|
1267
|
+
for cell in pairs["complex_ids"].tolist():
|
|
1268
|
+
if isinstance(cell, (list, tuple, np.ndarray, pd.Series)):
|
|
1269
|
+
complex_lists.append([int(x) for x in cell if pd.notnull(x)])
|
|
1270
|
+
elif pd.isna(cell):
|
|
1271
|
+
complex_lists.append([])
|
|
1272
|
+
else:
|
|
1273
|
+
try:
|
|
1274
|
+
complex_lists.append([int(cell)])
|
|
1275
|
+
except Exception:
|
|
1276
|
+
complex_lists.append([])
|
|
1277
|
+
|
|
1278
|
+
all_cids = sorted({cid for cids in complex_lists for cid in cids})
|
|
1279
|
+
if not all_cids:
|
|
1280
|
+
return pd.DataFrame()
|
|
1281
|
+
|
|
1282
|
+
cid_to_idx = {cid: i for i, cid in enumerate(all_cids)}
|
|
1283
|
+
n_cids = len(all_cids)
|
|
1284
|
+
n_cut = len(precision_cutoffs)
|
|
1285
|
+
|
|
1286
|
+
contrib = np.zeros((n_cids, n_cut), dtype=float)
|
|
1287
|
+
|
|
1288
|
+
pos_prec = precision[true == 1]
|
|
1289
|
+
prec_min = float(pos_prec.min())
|
|
1290
|
+
prec_max = float(precision.max())
|
|
1291
|
+
|
|
1292
|
+
for j, cutoff in enumerate(precision_cutoffs):
|
|
1293
|
+
if cutoff < prec_min or cutoff > prec_max:
|
|
1294
|
+
continue
|
|
1295
|
+
|
|
1296
|
+
cand_mask = precision >= cutoff
|
|
1297
|
+
if not np.any(cand_mask & (true == 1)):
|
|
1298
|
+
continue
|
|
1299
|
+
|
|
1300
|
+
k = np.where(cand_mask)[0][-1]
|
|
1301
|
+
tp_target = tp_cum[k]
|
|
1302
|
+
i_end = np.where(tp_cum == tp_target)[0][0]
|
|
1303
|
+
|
|
1304
|
+
rows = np.arange(i_end + 1, dtype=int)
|
|
1305
|
+
tp_rows = rows[true[rows] == 1]
|
|
1306
|
+
if tp_rows.size == 0:
|
|
1307
|
+
continue
|
|
1308
|
+
|
|
1309
|
+
cid_to_rows = {}
|
|
1310
|
+
for r in tp_rows:
|
|
1311
|
+
for cid in complex_lists[r]:
|
|
1312
|
+
cid_to_rows.setdefault(cid, set()).add(r)
|
|
1313
|
+
|
|
1314
|
+
covered = set()
|
|
1315
|
+
|
|
1316
|
+
while True:
|
|
1317
|
+
best_cid = None
|
|
1318
|
+
best_size = 0
|
|
1319
|
+
for cid, rset in cid_to_rows.items():
|
|
1320
|
+
size = len(rset - covered)
|
|
1321
|
+
if size > best_size:
|
|
1322
|
+
best_size = size
|
|
1323
|
+
best_cid = cid
|
|
1324
|
+
|
|
1325
|
+
if best_cid is None or best_size == 0:
|
|
1326
|
+
break
|
|
1327
|
+
|
|
1328
|
+
new_rows = cid_to_rows[best_cid] - covered
|
|
1329
|
+
covered.update(new_rows)
|
|
1330
|
+
row_idx = cid_to_idx[best_cid]
|
|
1331
|
+
contrib[row_idx, j] = float(len(new_rows))
|
|
1332
|
+
|
|
1333
|
+
contrib_df = pd.DataFrame(
|
|
1334
|
+
contrib,
|
|
1335
|
+
index=pd.Index(all_cids, name="complex_id"),
|
|
1336
|
+
columns=precision_cutoffs,
|
|
1337
|
+
)
|
|
1338
|
+
return contrib_df
|
|
1339
|
+
|
|
1340
|
+
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
|
|
1347
|
+
def _mpr_module_coverage(contrib_df, terms, tp_th=1, percent_th=0.1):
|
|
1348
|
+
"""
|
|
1349
|
+
Convert stepwise contribution matrix to "#covered complexes" per cutoff.
|
|
1350
|
+
|
|
1351
|
+
contrib_df : rows = complex_id (int), columns = precision_cutoffs (float)
|
|
1352
|
+
terms : CORUM 'terms' table (index = complex_id)
|
|
1353
|
+
|
|
1354
|
+
A complex is covered at a precision cutoff if:
|
|
1355
|
+
1. It contributes at least tp_th TP pairs (stepwise)
|
|
1356
|
+
2. The fraction of contributed pairs vs total possible pairs > percent_th
|
|
1357
|
+
(matches R behavior: x > percent_th)
|
|
1358
|
+
"""
|
|
1359
|
+
if contrib_df.empty:
|
|
1360
|
+
return np.zeros(0, dtype=float)
|
|
1361
|
+
|
|
1362
|
+
precision_cutoffs = np.asarray(contrib_df.columns, dtype=float)
|
|
1363
|
+
data = contrib_df.to_numpy(dtype=float)
|
|
1364
|
+
n_cut = data.shape[1]
|
|
1365
|
+
|
|
1366
|
+
n_pairs = np.zeros(data.shape[0], dtype=float)
|
|
1367
|
+
for i, cid in enumerate(contrib_df.index):
|
|
1368
|
+
cid_int = int(cid)
|
|
1369
|
+
if cid_int not in terms.index:
|
|
1370
|
+
n_pairs[i] = 0.0
|
|
1371
|
+
continue
|
|
1372
|
+
row = terms.loc[cid_int]
|
|
1373
|
+
|
|
1374
|
+
n_genes = None
|
|
1375
|
+
|
|
1376
|
+
# Prefer used_genes (genes actually in the dataset) for a fair coverage
|
|
1377
|
+
# fraction. This matters for GOBP/PATHWAY where all_genes >> used_genes.
|
|
1378
|
+
if "used_genes" in row.index:
|
|
1379
|
+
genes = row["used_genes"]
|
|
1380
|
+
if isinstance(genes, (list, np.ndarray)) and len(genes) > 0:
|
|
1381
|
+
n_genes = len(genes)
|
|
1382
|
+
if n_genes is None and "n_used_genes" in row.index:
|
|
1383
|
+
try:
|
|
1384
|
+
v = int(row["n_used_genes"])
|
|
1385
|
+
if v > 0:
|
|
1386
|
+
n_genes = v
|
|
1387
|
+
except (ValueError, TypeError):
|
|
1388
|
+
pass
|
|
1389
|
+
|
|
1390
|
+
# Fallback: all_genes (how it's stored in preprocessing)
|
|
1391
|
+
if n_genes is None and "all_genes" in row.index:
|
|
1392
|
+
genes = row["all_genes"]
|
|
1393
|
+
if isinstance(genes, (list, np.ndarray)):
|
|
1394
|
+
n_genes = len(genes)
|
|
1395
|
+
elif isinstance(genes, str):
|
|
1396
|
+
n_genes = len([g for g in genes.split(";") if g])
|
|
1397
|
+
|
|
1398
|
+
# Fallback to Genes column (original string from CORUM)
|
|
1399
|
+
if n_genes is None and "Genes" in row.index:
|
|
1400
|
+
genes_str = row["Genes"]
|
|
1401
|
+
if isinstance(genes_str, str):
|
|
1402
|
+
n_genes = len([g for g in genes_str.split(";") if g])
|
|
1403
|
+
|
|
1404
|
+
# Fallback to n_all_genes (computed during preprocessing)
|
|
1405
|
+
if n_genes is None and "n_all_genes" in row.index:
|
|
1406
|
+
try:
|
|
1407
|
+
n_genes = int(row["n_all_genes"])
|
|
1408
|
+
except (ValueError, TypeError):
|
|
1409
|
+
n_genes = None
|
|
1410
|
+
|
|
1411
|
+
# Fallback to Length column (from original CORUM file)
|
|
1412
|
+
if n_genes is None and "Length" in row.index:
|
|
1413
|
+
try:
|
|
1414
|
+
n_genes = int(row["Length"])
|
|
1415
|
+
except (ValueError, TypeError):
|
|
1416
|
+
n_genes = None
|
|
1417
|
+
|
|
1418
|
+
if n_genes is None or n_genes < 2:
|
|
1419
|
+
n_pairs[i] = 0.0
|
|
1420
|
+
else:
|
|
1421
|
+
n_pairs[i] = n_genes * (n_genes - 1) / 2.0
|
|
1422
|
+
|
|
1423
|
+
coverage = np.zeros(n_cut, dtype=float)
|
|
1424
|
+
|
|
1425
|
+
for j in range(n_cut):
|
|
1426
|
+
tps = data[:, j]
|
|
1427
|
+
mask = (tps >= tp_th) & (n_pairs > 0)
|
|
1428
|
+
if not np.any(mask):
|
|
1429
|
+
coverage[j] = 0.0
|
|
1430
|
+
continue
|
|
1431
|
+
|
|
1432
|
+
frac = np.zeros_like(tps)
|
|
1433
|
+
frac[mask] = tps[mask] / n_pairs[mask]
|
|
1434
|
+
# Note: Using > (strict inequality) to match R code behavior
|
|
1435
|
+
covered = (tps >= tp_th) & (frac > percent_th)
|
|
1436
|
+
coverage[j] = float(covered.sum())
|
|
1437
|
+
|
|
1438
|
+
return coverage
|
|
1439
|
+
|
|
1440
|
+
|
|
1441
|
+
def _mpr_complexes_auc(
|
|
1442
|
+
coverage: np.ndarray,
|
|
1443
|
+
precision_cutoffs: np.ndarray,
|
|
1444
|
+
max_complexes: float = 200.0,
|
|
1445
|
+
) -> float:
|
|
1446
|
+
"""Compute AUC for the Fig. 1F-style mPR curve (#complexes vs precision).
|
|
1447
|
+
|
|
1448
|
+
The plot uses:
|
|
1449
|
+
x = #covered complexes (capped at `max_complexes`, shown on a log axis)
|
|
1450
|
+
y = precision cutoff
|
|
1451
|
+
|
|
1452
|
+
We compute a normalized AUC by integrating precision over the *normalized*
|
|
1453
|
+
coverage axis:
|
|
1454
|
+
AUC = integral y d(x/max_complexes)
|
|
1455
|
+
|
|
1456
|
+
This yields a score in [0, 1] (or NaN if insufficient data).
|
|
1457
|
+
"""
|
|
1458
|
+
cov = np.asarray(coverage, dtype=float)
|
|
1459
|
+
prec = np.asarray(precision_cutoffs, dtype=float)
|
|
1460
|
+
|
|
1461
|
+
if cov.size == 0 or prec.size == 0:
|
|
1462
|
+
return 0.0
|
|
1463
|
+
|
|
1464
|
+
# Match plot_mpr_complex_coverage_curve(): only count cov>0 (log-x cannot show 0)
|
|
1465
|
+
mask = (
|
|
1466
|
+
np.isfinite(cov)
|
|
1467
|
+
& np.isfinite(prec)
|
|
1468
|
+
& (cov > 0)
|
|
1469
|
+
& (cov <= max_complexes)
|
|
1470
|
+
& (prec >= 0)
|
|
1471
|
+
& (prec <= 1.0)
|
|
1472
|
+
)
|
|
1473
|
+
if not np.any(mask):
|
|
1474
|
+
return 0.0
|
|
1475
|
+
|
|
1476
|
+
x_cov = cov[mask]
|
|
1477
|
+
y = prec[mask]
|
|
1478
|
+
|
|
1479
|
+
# x-axis is log-scaled in the plot; normalize so cov=1 -> 0, cov=max_complexes -> 1
|
|
1480
|
+
# (This matches the plot's tick hack where 1 is labeled as "0".)
|
|
1481
|
+
x = np.log10(x_cov) / np.log10(float(max_complexes))
|
|
1482
|
+
|
|
1483
|
+
# Sort by x and collapse duplicate x values by taking max y (upper envelope)
|
|
1484
|
+
order = np.argsort(x)
|
|
1485
|
+
x = x[order]
|
|
1486
|
+
y = y[order]
|
|
1487
|
+
|
|
1488
|
+
x_unique = np.unique(x)
|
|
1489
|
+
if x_unique.size != x.size:
|
|
1490
|
+
y = np.array([float(np.nanmax(y[x == xv])) for xv in x_unique], dtype=float)
|
|
1491
|
+
x = x_unique
|
|
1492
|
+
|
|
1493
|
+
if x.size < 2:
|
|
1494
|
+
return 0.0
|
|
1495
|
+
|
|
1496
|
+
return float(np.trapz(y, x))
|
|
1497
|
+
|
|
1498
|
+
|
|
1499
|
+
|
|
1500
|
+
|
|
1501
|
+
|
|
1502
|
+
|
|
1503
|
+
|
|
1504
|
+
|
|
1505
|
+
|
|
1506
|
+
|
|
1507
|
+
def mpr_prepare(
|
|
1508
|
+
name,
|
|
1509
|
+
size_th=30,
|
|
1510
|
+
auprc_th=0.4,
|
|
1511
|
+
tp_th=1,
|
|
1512
|
+
percent_th=0.1,
|
|
1513
|
+
use_corrected=True,
|
|
1514
|
+
):
|
|
1515
|
+
"""
|
|
1516
|
+
Prepare data for Fig. 1E (TP vs precision) and Fig. 1F (mPR) for dataset `name`.
|
|
1517
|
+
|
|
1518
|
+
Stores an 'mpr' object with:
|
|
1519
|
+
- precision_cutoffs
|
|
1520
|
+
- tp_curves[label] : full PR (TP vs precision) per filter
|
|
1521
|
+
- coverage_curves[label] : #covered complexes per cutoff per filter
|
|
1522
|
+
- filters metadata
|
|
1523
|
+
"""
|
|
1524
|
+
pra = dload("pra", name)
|
|
1525
|
+
pra_percomplex = dload("pra_percomplex", name)
|
|
1526
|
+
terms = dload("common", f"terms_{name}")
|
|
1527
|
+
if not isinstance(terms, pd.DataFrame):
|
|
1528
|
+
# Fallback for backward compatibility
|
|
1529
|
+
terms = dload("common", "terms")
|
|
1530
|
+
|
|
1531
|
+
if pra is None or not isinstance(pra, pd.DataFrame) or pra.empty:
|
|
1532
|
+
raise RuntimeError(
|
|
1533
|
+
f"mpr_prepare(): PRA data for dataset '{name}' not found "
|
|
1534
|
+
"(dload('pra', name))."
|
|
1535
|
+
)
|
|
1536
|
+
if pra_percomplex is None or not isinstance(pra_percomplex, pd.DataFrame) or pra_percomplex.empty:
|
|
1537
|
+
raise RuntimeError(
|
|
1538
|
+
f"mpr_prepare(): per-complex PRA data for dataset '{name}' not found "
|
|
1539
|
+
"(dload('pra_percomplex', name))."
|
|
1540
|
+
)
|
|
1541
|
+
if terms is None or not isinstance(terms, pd.DataFrame) or terms.empty:
|
|
1542
|
+
raise RuntimeError(
|
|
1543
|
+
"mpr_prepare(): CORUM 'terms' table not found (dload('common', 'terms'))."
|
|
1544
|
+
)
|
|
1545
|
+
|
|
1546
|
+
ascending = _sort_ascending_for_dataset(name)
|
|
1547
|
+
|
|
1548
|
+
# Sort by the dataset's configured score direction.
|
|
1549
|
+
if "score" in pra.columns:
|
|
1550
|
+
pra = pra.sort_values("score", ascending=ascending).reset_index(drop=True)
|
|
1551
|
+
else:
|
|
1552
|
+
pra = pra.reset_index(drop=True)
|
|
1553
|
+
|
|
1554
|
+
# filters
|
|
1555
|
+
mtRibo_ids = _mpr_get_mtRibo_ETCI_ids(pra_percomplex)
|
|
1556
|
+
small_hi_ids = _mpr_get_small_high_auprc_ids(
|
|
1557
|
+
pra_percomplex,
|
|
1558
|
+
size_th=size_th,
|
|
1559
|
+
auprc_th=auprc_th,
|
|
1560
|
+
use_corrected=use_corrected,
|
|
1561
|
+
)
|
|
1562
|
+
|
|
1563
|
+
filter_sets = {
|
|
1564
|
+
"all": set(),
|
|
1565
|
+
"no_mtRibo_ETCI": set(mtRibo_ids),
|
|
1566
|
+
"no_small_highAUPRC": set(small_hi_ids),
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
tp_curves = {}
|
|
1570
|
+
coverage_curves = {}
|
|
1571
|
+
complexes_auc = {}
|
|
1572
|
+
precision_cutoffs = None
|
|
1573
|
+
|
|
1574
|
+
for label, removed in filter_sets.items():
|
|
1575
|
+
# 1) Build pairs table after removing complexes in `removed`
|
|
1576
|
+
pairs = _mpr_build_pairs(pra, removed_ids=removed, ascending=ascending)
|
|
1577
|
+
|
|
1578
|
+
true = pairs["true"].to_numpy(dtype=int)
|
|
1579
|
+
n = len(true)
|
|
1580
|
+
if n == 0 or true.sum() == 0:
|
|
1581
|
+
tp_curves[label] = {
|
|
1582
|
+
"tp": np.array([], dtype=float),
|
|
1583
|
+
"precision": np.array([], dtype=float),
|
|
1584
|
+
}
|
|
1585
|
+
coverage_curves[label] = np.zeros(0, dtype=float)
|
|
1586
|
+
complexes_auc[label] = float("nan")
|
|
1587
|
+
continue
|
|
1588
|
+
|
|
1589
|
+
tp_cum = true.cumsum()
|
|
1590
|
+
denom = np.arange(n, dtype=float) + 1.0
|
|
1591
|
+
precision = tp_cum / denom
|
|
1592
|
+
|
|
1593
|
+
# full PR: only positions where we add a TP
|
|
1594
|
+
mask_tp = true == 1
|
|
1595
|
+
tp_full = tp_cum[mask_tp]
|
|
1596
|
+
prec_full = precision[mask_tp]
|
|
1597
|
+
tp_curves[label] = {"tp": tp_full, "precision": prec_full}
|
|
1598
|
+
|
|
1599
|
+
# common precision grid from 'all'
|
|
1600
|
+
if precision_cutoffs is None:
|
|
1601
|
+
precision_cutoffs = _mpr_precision_cutoffs_from_pairs(pairs)
|
|
1602
|
+
|
|
1603
|
+
contrib_df = _mpr_stepwise_contributions(
|
|
1604
|
+
pairs,
|
|
1605
|
+
precision_cutoffs,
|
|
1606
|
+
ascending=ascending,
|
|
1607
|
+
)
|
|
1608
|
+
cov = _mpr_module_coverage(
|
|
1609
|
+
contrib_df,
|
|
1610
|
+
terms,
|
|
1611
|
+
tp_th=tp_th,
|
|
1612
|
+
percent_th=percent_th,
|
|
1613
|
+
)
|
|
1614
|
+
# precision_cutoffs are sorted ascending (low → high).
|
|
1615
|
+
# Coverage must be non-increasing in that direction: a more permissive
|
|
1616
|
+
# threshold (lower precision) should never yield fewer covered terms.
|
|
1617
|
+
# The independent greedy allocation per cutoff can violate this, so
|
|
1618
|
+
# enforce monotonicity by propagating the max from right to left.
|
|
1619
|
+
if cov.size > 0:
|
|
1620
|
+
cov = np.maximum.accumulate(cov[::-1])[::-1]
|
|
1621
|
+
coverage_curves[label] = cov
|
|
1622
|
+
complexes_auc[label] = _mpr_complexes_auc(
|
|
1623
|
+
cov,
|
|
1624
|
+
precision_cutoffs,
|
|
1625
|
+
max_complexes=200.0,
|
|
1626
|
+
)
|
|
1627
|
+
|
|
1628
|
+
mpr_data = {
|
|
1629
|
+
"precision_cutoffs": precision_cutoffs,
|
|
1630
|
+
"tp_curves": tp_curves,
|
|
1631
|
+
"coverage_curves": coverage_curves,
|
|
1632
|
+
"complexes_auc": complexes_auc,
|
|
1633
|
+
"filters": {
|
|
1634
|
+
"no_mtRibo_ETCI": sorted(mtRibo_ids),
|
|
1635
|
+
"no_small_highAUPRC": sorted(small_hi_ids),
|
|
1636
|
+
"size_th": size_th,
|
|
1637
|
+
"auprc_th": auprc_th,
|
|
1638
|
+
"percent_th": percent_th,
|
|
1639
|
+
"tp_th": tp_th,
|
|
1640
|
+
"use_corrected": bool(use_corrected),
|
|
1641
|
+
},
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
dsave(mpr_data, "mpr", name)
|
|
1645
|
+
|
|
1646
|
+
# Convenience: store AUCs as their own category for easy export / plotting.
|
|
1647
|
+
dsave(complexes_auc, "mpr_complexes_auc", name)
|