pflex 1.2__tar.gz → 1.3__tar.gz

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.
Files changed (32) hide show
  1. {pflex-1.2 → pflex-1.3}/PKG-INFO +22 -1
  2. {pflex-1.2 → pflex-1.3}/README.md +21 -0
  3. {pflex-1.2 → pflex-1.3}/docs/user-guide.md +14 -8
  4. {pflex-1.2 → pflex-1.3}/pyproject.toml +1 -1
  5. {pflex-1.2 → pflex-1.3}/src/pflex/__init__.py +5 -6
  6. {pflex-1.2 → pflex-1.3}/src/pflex/analysis.py +221 -92
  7. {pflex-1.2 → pflex-1.3}/src/pflex/examples/basic_usage.py +16 -6
  8. {pflex-1.2 → pflex-1.3}/src/pflex/plotting.py +610 -872
  9. pflex-1.3/tests/test_mpr_filters.py +176 -0
  10. pflex-1.3/tests/test_plotting_labels.py +205 -0
  11. {pflex-1.2 → pflex-1.3}/.gitignore +0 -0
  12. {pflex-1.2 → pflex-1.3}/.python-version +0 -0
  13. {pflex-1.2 → pflex-1.3}/LICENSE +0 -0
  14. {pflex-1.2 → pflex-1.3}/docs/getting-started.md +0 -0
  15. {pflex-1.2 → pflex-1.3}/docs/index.md +0 -0
  16. {pflex-1.2 → pflex-1.3}/docs/installation.md +0 -0
  17. {pflex-1.2 → pflex-1.3}/mkdocs.yml +0 -0
  18. {pflex-1.2 → pflex-1.3}/src/pflex/data/__init__.py +0 -0
  19. {pflex-1.2 → pflex-1.3}/src/pflex/data/example_input/__init__.py +0 -0
  20. {pflex-1.2 → pflex-1.3}/src/pflex/data/example_input/skin_cell_lines_corum_genes.parquet +0 -0
  21. {pflex-1.2 → pflex-1.3}/src/pflex/data/example_input/soft_tissue_cell_lines_corum_genes.parquet +0 -0
  22. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/CORUM.parquet +0 -0
  23. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/GOBP.parquet +0 -0
  24. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/PATHWAY.parquet +0 -0
  25. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/__init__.py +0 -0
  26. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/corum.csv +0 -0
  27. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/gobp.csv +0 -0
  28. {pflex-1.2 → pflex-1.3}/src/pflex/data/functional_standard/pathway.csv +0 -0
  29. {pflex-1.2 → pflex-1.3}/src/pflex/logging_config.py +0 -0
  30. {pflex-1.2 → pflex-1.3}/src/pflex/preprocessing.py +0 -0
  31. {pflex-1.2 → pflex-1.3}/src/pflex/utils.py +0 -0
  32. {pflex-1.2 → pflex-1.3}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pflex
3
- Version: 1.2
3
+ Version: 1.3
4
4
  Summary: pflex is a benchmarking toolkit for evaluating CRISPR screen results against biological functional standards. The toolkit computes gene-level and module-level performance metrics, helping researchers systematically assess the biological relevance and resolution of their CRISPR screening data.
5
5
  Author-email: Yasir Demirtas <tyasird@hotmail.com>
6
6
  License-File: LICENSE
@@ -186,6 +186,27 @@ flex.plot_mpr_summary()
186
186
  flex.save_results_to_csv()
187
187
  ```
188
188
 
189
+ `mpr_prepare()` computes only the standard, unfiltered module-coverage mPR
190
+ curve. `plot_mpr_summary()` plots that curve and the corresponding dataset-level
191
+ mPR AUC values; it does not produce a duplicate global precision-recall plot.
192
+
193
+ The predefined complex-filter comparisons are optional and computed lazily:
194
+
195
+ ```python
196
+ for name in data:
197
+ flex.mpr_filter(name)
198
+ flex.globalpr_filter(name)
199
+
200
+ # Compare all complexes, removal of mtRibo / ETC I, and removal of
201
+ # small high-AUPRC complexes.
202
+ mpr_ax, mpr_filter_auc = flex.plot_mpr_filter()
203
+ globalpr_ax = flex.plot_globalpr_filter()
204
+ ```
205
+
206
+ The calculation and plotting calls are intentionally separate. Calling a
207
+ filter plotting function before its matching calculation raises an error that
208
+ identifies the required preparation function.
209
+
189
210
  See the [User Guide](https://tyasird.github.io/pFLEX/user-guide/) for a detailed explanation of every input field, configuration key, function, return value, and output.
190
211
 
191
212
  ---
@@ -155,6 +155,27 @@ flex.plot_mpr_summary()
155
155
  flex.save_results_to_csv()
156
156
  ```
157
157
 
158
+ `mpr_prepare()` computes only the standard, unfiltered module-coverage mPR
159
+ curve. `plot_mpr_summary()` plots that curve and the corresponding dataset-level
160
+ mPR AUC values; it does not produce a duplicate global precision-recall plot.
161
+
162
+ The predefined complex-filter comparisons are optional and computed lazily:
163
+
164
+ ```python
165
+ for name in data:
166
+ flex.mpr_filter(name)
167
+ flex.globalpr_filter(name)
168
+
169
+ # Compare all complexes, removal of mtRibo / ETC I, and removal of
170
+ # small high-AUPRC complexes.
171
+ mpr_ax, mpr_filter_auc = flex.plot_mpr_filter()
172
+ globalpr_ax = flex.plot_globalpr_filter()
173
+ ```
174
+
175
+ The calculation and plotting calls are intentionally separate. Calling a
176
+ filter plotting function before its matching calculation raises an error that
177
+ identifies the required preparation function.
178
+
158
179
  See the [User Guide](https://tyasird.github.io/pFLEX/user-guide/) for a detailed explanation of every input field, configuration key, function, return value, and output.
159
180
 
160
181
  ---
@@ -154,10 +154,15 @@ for name, dataset in data.items():
154
154
 
155
155
  `mpr_prepare(name)`:
156
156
 
157
- - prepares module-level precision-recall data
158
- - stores true-positive curves, coverage curves, filter metadata, and mPR AUC summaries
157
+ - prepares the unfiltered module-coverage precision-recall data
158
+ - stores one coverage curve and its mPR AUC score
159
159
  - must be run before the mPR plotting functions
160
- - accepts optional thresholds such as `size_th`, `auprc_th`, `tp_th`, and `percent_th` for the module-level filtering logic
160
+ - accepts optional `tp_th` and `percent_th` coverage thresholds
161
+
162
+ `mpr_filter(name)` and `globalpr_filter(name)` are optional sensitivity
163
+ analyses. They lazily compute the predefined all-complexes,
164
+ without-mtRibo/ETC-I, and without-small-high-AUPRC comparisons. They are not
165
+ run by `mpr_prepare()`.
161
166
 
162
167
  ## Plotting and Export
163
168
 
@@ -188,11 +193,12 @@ Per-module plots:
188
193
 
189
194
  mPR preparation and plots:
190
195
 
191
- - `mpr_prepare(name, size_th=30, auprc_th=0.4, tp_th=1, percent_th=0.1, use_corrected=True)` prepares module-level PR data for one dataset. It filters terms for module-level analysis, stores true-positive curves, module-coverage curves, filtered variants, and mPR AUC values.
192
- - `plot_mpr_tp_multi(dataset_names=None, colors=None, linewidth=1.8, show_filters=("all", "no_mtRibo_ETCI", "no_small_highAUPRC"))` shows true positives versus precision for one or more datasets after `mpr_prepare()`. This plot shows how many true-positive gene pairs are recovered as the precision cutoff changes.
193
- - `plot_mpr_modules_multi(dataset_names=None, colors=None, linewidth=1.8, show_filters=("all", "no_mtRibo_ETCI", "no_small_highAUPRC"), show_markers="auto")` shows how many functional-standard terms are covered at each precision cutoff. This plot focuses on term coverage, not pair counts.
194
- - `plot_mpr_summary(dataset_names=None, colors=None, variants="unfiltered", save=True, linewidth=1.8, show_markers="auto")` creates the standard mPR true-positive, module-coverage, and mPR AUC summary plots in one call.
195
- - Newer mPR functions also accept `variants`, with values `"unfiltered"`, `"without_mt_ribo_etci"`, `"without_small_high_auprc"`, or `"all"`.
196
+ - `mpr_prepare(name, tp_th=1, percent_th=0.1)` prepares the single unfiltered module-coverage mPR curve for one dataset.
197
+ - `plot_mpr_module_coverage_curve(dataset_names=None, colors=None, linewidth=1.8, show_markers="auto")` compares unfiltered mPR curves across datasets.
198
+ - `plot_mpr_summary(...)` creates the unfiltered module-coverage plot and the dataset-level mPR AUC plot. It does not create a global PR plot.
199
+ - `mpr_filter(name, size_th=30, auprc_th=0.4, ...)` lazily computes the three predefined module-coverage filter variants. `plot_mpr_filter()` plots them and returns the variant AUC table alongside the axes.
200
+ - `globalpr_filter(name, size_th=30, auprc_th=0.4, ...)` lazily computes the matching global PR variants. `plot_globalpr_filter()` plots them.
201
+ - Filter plotting functions never start calculations automatically; run the matching calculation once for every selected dataset first.
196
202
 
197
203
  Export:
198
204
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pflex"
3
- version = "1.2"
3
+ version = "1.3"
4
4
  description = "pflex is a benchmarking toolkit for evaluating CRISPR screen results against biological functional standards. The toolkit computes gene-level and module-level performance metrics, helping researchers systematically assess the biological relevance and resolution of their CRISPR screening data."
5
5
  readme = "README.md"
6
6
  authors = [
@@ -1,12 +1,12 @@
1
1
  from .logging_config import log
2
2
  from .utils import dsave, dload
3
3
  from .preprocessing import example_input_path, get_example_data_path, load_datasets, get_common_genes, filter_matrix_by_genes, load_functional_standard, filter_duplicate_terms
4
- from .analysis import initialize, prepare_terms_for_dataset, pra, pra_per_module, fast_corr, perform_corr, is_symmetric, binary, has_mirror_of_first_pair, convert_full_to_half_matrix, drop_mirror_pairs, quick_sort, module_contributions, save_results_to_csv, update_matploblib_config, mpr_prepare
4
+ from .analysis import initialize, prepare_terms_for_dataset, pra, pra_per_module, fast_corr, perform_corr, is_symmetric, binary, has_mirror_of_first_pair, convert_full_to_half_matrix, drop_mirror_pairs, quick_sort, module_contributions, save_results_to_csv, update_matploblib_config, mpr_prepare, mpr_filter, globalpr_filter
5
5
  from .plotting import (
6
6
  adjust_text_positions, plot_precision_recall_curve, plot_aggregated_pra, plot_iqr_pra, plot_all_runs_pra, plot_per_module_scatter,
7
7
  plot_per_module_scatter_by_size, plot_module_contributions, plot_significant_modules, plot_auc_scores,
8
- plot_mpr_tp, plot_mpr_modules, plot_mpr_tp_multi, plot_mpr_modules_multi, plot_mpr_modules_auc_scores,
9
- plot_mpr_true_positive_curve, plot_mpr_module_coverage_curve, plot_mpr_module_auc_scores, plot_mpr_summary
8
+ plot_mpr_module_coverage_curve, plot_mpr_module_auc_scores, plot_mpr_summary,
9
+ plot_mpr_filter, plot_globalpr_filter
10
10
  )
11
11
 
12
12
  def main():
@@ -37,8 +37,7 @@ __all__ = [ "log", "example_input_path", "get_example_data_path", "fast_corr",
37
37
  "perform_corr", "is_symmetric", "binary", "has_mirror_of_first_pair", "convert_full_to_half_matrix",
38
38
  "drop_mirror_pairs", "quick_sort", "module_contributions", "adjust_text_positions", "plot_precision_recall_curve",
39
39
  "plot_aggregated_pra", "plot_iqr_pra", "plot_all_runs_pra", "plot_per_module_scatter", "plot_per_module_scatter_by_size", "plot_module_contributions",
40
- "plot_significant_modules", "plot_auc_scores", "plot_mpr_modules_auc_scores", "plot_mpr_module_auc_scores", "save_results_to_csv", "update_matploblib_config",
41
- "mpr_prepare", "plot_mpr_tp", "plot_mpr_modules",
42
- "plot_mpr_tp_multi", "plot_mpr_modules_multi", "plot_mpr_true_positive_curve",
40
+ "plot_significant_modules", "plot_auc_scores", "plot_mpr_module_auc_scores", "save_results_to_csv", "update_matploblib_config",
41
+ "mpr_prepare", "mpr_filter", "globalpr_filter", "plot_mpr_filter", "plot_globalpr_filter",
43
42
  "plot_mpr_module_coverage_curve", "plot_mpr_summary", "main"
44
43
  ]
@@ -1031,9 +1031,8 @@ def save_results_to_csv(categories = ["module_contributions", "pr_auc", "pra_per
1031
1031
  continue
1032
1032
 
1033
1033
  if category == "mpr_modules_auc" and isinstance(data, dict):
1034
- # Dict[dataset_name -> Dict[variant_key -> auc]]
1035
1034
  try:
1036
- df = pd.DataFrame.from_dict(data, orient="index")
1035
+ df = pd.Series(data, name="AUC", dtype=float).to_frame()
1037
1036
  df.index.name = "Dataset"
1038
1037
  csv_path = output_folder / f"{category}.csv"
1039
1038
  df.to_csv(csv_path, index=True)
@@ -1075,7 +1074,7 @@ def save_results_to_csv(categories = ["module_contributions", "pr_auc", "pra_per
1075
1074
  log.done("Results saved to CSV files in the output folder.")
1076
1075
 
1077
1076
  # -----------------------------------------------------------------------------
1078
- # mPR preparation (module-level precision–recall, Fig. 1E / 1F)
1077
+ # Module-level precision-recall and optional complex-filter sensitivity analyses
1079
1078
  # -----------------------------------------------------------------------------
1080
1079
 
1081
1080
 
@@ -1088,7 +1087,7 @@ def _mpr_get_mtRibo_ETCI_ids(terms_like):
1088
1087
  - OR Name contains '55S'
1089
1088
  """
1090
1089
  if "Name" not in terms_like.columns:
1091
- raise KeyError("mpr_prepare(): expected a 'Name' column in the CORUM terms.")
1090
+ raise KeyError("Complex filtering requires a 'Name' column in the term table.")
1092
1091
 
1093
1092
  name = terms_like["Name"].astype(str)
1094
1093
  mask = name.str.contains(
@@ -1109,7 +1108,7 @@ def _mpr_get_small_high_auprc_ids(
1109
1108
  """
1110
1109
  if "Length" not in pra_per_module.columns:
1111
1110
  raise KeyError(
1112
- "mpr_prepare(): expected a 'Length' column in the per-module table."
1111
+ "Complex filtering requires a 'Length' column in the per-module table."
1113
1112
  )
1114
1113
 
1115
1114
  if use_corrected and "corrected_auc_score" in pra_per_module.columns:
@@ -1118,7 +1117,8 @@ def _mpr_get_small_high_auprc_ids(
1118
1117
  score_col = "auc_score"
1119
1118
  else:
1120
1119
  raise KeyError(
1121
- "mpr_prepare(): expected 'corrected_auc_score' or 'auc_score' in the per-module table."
1120
+ "Complex filtering requires 'corrected_auc_score' or 'auc_score' "
1121
+ "in the per-module table."
1122
1122
  )
1123
1123
 
1124
1124
  size_mask = pra_per_module["Length"] < size_th
@@ -1153,7 +1153,7 @@ def _mpr_build_pairs(pra, removed_ids=None, ascending=False):
1153
1153
  """
1154
1154
  if "module_id" not in pra.columns and "module_ids" not in pra.columns:
1155
1155
  raise RuntimeError(
1156
- "mpr_prepare(): expected a 'module_id' or 'module_ids' column in 'pra'."
1156
+ "mPR analysis requires a 'module_id' or 'module_ids' column in 'pra'."
1157
1157
  )
1158
1158
 
1159
1159
  removed_ids = set(int(x) for x in (removed_ids or []))
@@ -1167,7 +1167,7 @@ def _mpr_build_pairs(pra, removed_ids=None, ascending=False):
1167
1167
  cid_col = "module_ids"
1168
1168
 
1169
1169
  if "score" not in df.columns:
1170
- raise RuntimeError("mpr_prepare(): expected a 'score' column in 'pra'.")
1170
+ raise RuntimeError("mPR analysis requires a 'score' column in 'pra'.")
1171
1171
 
1172
1172
  def normalize_ids(cell):
1173
1173
  """Parse module IDs from various formats."""
@@ -1517,23 +1517,11 @@ def _mpr_modules_auc(
1517
1517
 
1518
1518
  def mpr_prepare(
1519
1519
  name,
1520
- size_th=30,
1521
- auprc_th=0.4,
1522
1520
  tp_th=1,
1523
1521
  percent_th=0.1,
1524
- use_corrected=True,
1525
1522
  ):
1526
- """
1527
- Prepare data for Fig. 1E (TP vs precision) and Fig. 1F (mPR) for dataset `name`.
1528
-
1529
- Stores an 'mpr' object with:
1530
- - precision_cutoffs
1531
- - tp_curves[label] : full PR (TP vs precision) per filter
1532
- - coverage_curves[label] : #covered modules per cutoff per filter
1533
- - filters metadata
1534
- """
1523
+ """Prepare the unfiltered module-coverage mPR curve for one dataset."""
1535
1524
  pra = dload("pra", name)
1536
- pra_per_module = dload("pra_per_module", name)
1537
1525
  terms = dload("common", f"terms_{name}")
1538
1526
  if not isinstance(terms, pd.DataFrame):
1539
1527
  # Fallback for backward compatibility
@@ -1544,11 +1532,6 @@ def mpr_prepare(
1544
1532
  f"mpr_prepare(): PRA data for dataset '{name}' not found "
1545
1533
  "(dload('pra', name))."
1546
1534
  )
1547
- if pra_per_module is None or not isinstance(pra_per_module, pd.DataFrame) or pra_per_module.empty:
1548
- raise RuntimeError(
1549
- f"mpr_prepare(): per-module PRA data for dataset '{name}' not found "
1550
- "(dload('pra_per_module', name))."
1551
- )
1552
1535
  if terms is None or not isinstance(terms, pd.DataFrame) or terms.empty:
1553
1536
  raise RuntimeError(
1554
1537
  "mpr_prepare(): functional standard 'terms' table not found (dload('common', 'terms'))."
@@ -1562,97 +1545,243 @@ def mpr_prepare(
1562
1545
  else:
1563
1546
  pra = pra.reset_index(drop=True)
1564
1547
 
1565
- # filters
1566
- mtRibo_ids = _mpr_get_mtRibo_ETCI_ids(pra_per_module)
1567
- small_hi_ids = _mpr_get_small_high_auprc_ids(
1548
+ pairs = _mpr_build_pairs(pra, ascending=ascending)
1549
+ precision_cutoffs = _mpr_precision_cutoffs_from_pairs(pairs)
1550
+ coverage = _mpr_coverage_for_pairs(
1551
+ pairs,
1552
+ precision_cutoffs,
1553
+ terms,
1554
+ ascending=ascending,
1555
+ tp_th=tp_th,
1556
+ percent_th=percent_th,
1557
+ )
1558
+ modules_auc = _mpr_modules_auc(
1559
+ coverage,
1560
+ precision_cutoffs,
1561
+ max_modules=200.0,
1562
+ )
1563
+
1564
+ mpr_data = {
1565
+ "precision_cutoffs": precision_cutoffs,
1566
+ "coverage_curve": coverage,
1567
+ "modules_auc": modules_auc,
1568
+ "parameters": {
1569
+ "percent_th": float(percent_th),
1570
+ "tp_th": int(tp_th),
1571
+ },
1572
+ }
1573
+
1574
+ dsave(mpr_data, "mpr", name)
1575
+ dsave(mpr_data["modules_auc"], "mpr_modules_auc", name)
1576
+ return mpr_data
1577
+
1578
+
1579
+ FILTER_VARIANTS = (
1580
+ "all_complexes",
1581
+ "without_mt_ribo_etci",
1582
+ "without_small_high_auprc",
1583
+ )
1584
+
1585
+
1586
+ def _mpr_coverage_for_pairs(
1587
+ pairs,
1588
+ precision_cutoffs,
1589
+ terms,
1590
+ ascending=False,
1591
+ tp_th=1,
1592
+ percent_th=0.1,
1593
+ ):
1594
+ """Compute a monotone module-coverage curve for a filtered ranking."""
1595
+ contributions = _mpr_stepwise_contributions(
1596
+ pairs,
1597
+ precision_cutoffs,
1598
+ ascending=ascending,
1599
+ )
1600
+ coverage = _mpr_module_coverage(
1601
+ contributions,
1602
+ terms,
1603
+ tp_th=tp_th,
1604
+ percent_th=percent_th,
1605
+ )
1606
+ if coverage.size > 0:
1607
+ coverage = np.maximum.accumulate(coverage[::-1])[::-1]
1608
+ return coverage
1609
+
1610
+
1611
+ def _filter_sets_for_dataset(
1612
+ pra_per_module,
1613
+ size_th=30,
1614
+ auprc_th=0.4,
1615
+ use_corrected=True,
1616
+ ):
1617
+ """Return the three predefined complex sets used in filter comparisons."""
1618
+ mt_ribo_etci_ids = _mpr_get_mtRibo_ETCI_ids(pra_per_module)
1619
+ small_high_auprc_ids = _mpr_get_small_high_auprc_ids(
1568
1620
  pra_per_module,
1569
1621
  size_th=size_th,
1570
1622
  auprc_th=auprc_th,
1571
1623
  use_corrected=use_corrected,
1572
1624
  )
1625
+ return {
1626
+ "all_complexes": set(),
1627
+ "without_mt_ribo_etci": set(mt_ribo_etci_ids),
1628
+ "without_small_high_auprc": set(small_high_auprc_ids),
1629
+ }
1630
+
1631
+
1632
+ def _load_filter_inputs(name, caller, require_terms=False):
1633
+ """Load and validate inputs shared by the lazy filter analyses."""
1634
+ pra = dload("pra", name)
1635
+ pra_per_module = dload("pra_per_module", name)
1636
+ if not isinstance(pra, pd.DataFrame) or pra.empty:
1637
+ raise RuntimeError(
1638
+ f"{caller}(): PRA data for dataset '{name}' not found. "
1639
+ f"Run pra('{name}', ...) first."
1640
+ )
1641
+ if not isinstance(pra_per_module, pd.DataFrame) or pra_per_module.empty:
1642
+ raise RuntimeError(
1643
+ f"{caller}(): per-module PRA data for dataset '{name}' not found. "
1644
+ f"Run pra_per_module('{name}', ...) first."
1645
+ )
1646
+
1647
+ terms = None
1648
+ if require_terms:
1649
+ terms = dload("common", f"terms_{name}")
1650
+ if not isinstance(terms, pd.DataFrame):
1651
+ terms = dload("common", "terms")
1652
+ if not isinstance(terms, pd.DataFrame) or terms.empty:
1653
+ raise RuntimeError(
1654
+ f"{caller}(): functional standard terms for dataset '{name}' not found."
1655
+ )
1656
+ return pra, pra_per_module, terms
1657
+
1573
1658
 
1574
- filter_sets = {
1575
- "all": set(),
1576
- "no_mtRibo_ETCI": set(mtRibo_ids),
1577
- "no_small_highAUPRC": set(small_hi_ids),
1659
+ def _tp_precision_curve(pairs):
1660
+ """Return TP-versus-precision values at true-positive ranking positions."""
1661
+ true = pairs["true"].to_numpy(dtype=int)
1662
+ if true.size == 0 or true.sum() == 0:
1663
+ return {
1664
+ "tp": np.array([], dtype=float),
1665
+ "precision": np.array([], dtype=float),
1666
+ }
1667
+ tp_cumulative = true.cumsum()
1668
+ precision = tp_cumulative / (np.arange(true.size, dtype=float) + 1.0)
1669
+ true_positive_rows = true == 1
1670
+ return {
1671
+ "tp": tp_cumulative[true_positive_rows],
1672
+ "precision": precision[true_positive_rows],
1578
1673
  }
1579
1674
 
1580
- tp_curves = {}
1581
- coverage_curves = {}
1582
- modules_auc = {}
1583
- precision_cutoffs = None
1584
-
1585
- for label, removed in filter_sets.items():
1586
- # 1) Build pairs table after removing modules in `removed`
1587
- pairs = _mpr_build_pairs(pra, removed_ids=removed, ascending=ascending)
1588
-
1589
- true = pairs["true"].to_numpy(dtype=int)
1590
- n = len(true)
1591
- if n == 0 or true.sum() == 0:
1592
- tp_curves[label] = {
1593
- "tp": np.array([], dtype=float),
1594
- "precision": np.array([], dtype=float),
1595
- }
1596
- coverage_curves[label] = np.zeros(0, dtype=float)
1597
- modules_auc[label] = float("nan")
1598
- continue
1599
1675
 
1600
- tp_cum = true.cumsum()
1601
- denom = np.arange(n, dtype=float) + 1.0
1602
- precision = tp_cum / denom
1676
+ def globalpr_filter(
1677
+ name,
1678
+ size_th=30,
1679
+ auprc_th=0.4,
1680
+ use_corrected=True,
1681
+ ):
1682
+ """Lazily compute the three predefined complex-filter global PR curves."""
1683
+ pra, pra_per_module, _ = _load_filter_inputs(name, "globalpr_filter")
1684
+ ascending = _sort_ascending_for_dataset(name)
1685
+ filter_sets = _filter_sets_for_dataset(
1686
+ pra_per_module,
1687
+ size_th=size_th,
1688
+ auprc_th=auprc_th,
1689
+ use_corrected=use_corrected,
1690
+ )
1691
+ curves = {
1692
+ variant: _tp_precision_curve(
1693
+ _mpr_build_pairs(pra, removed_ids=removed, ascending=ascending)
1694
+ )
1695
+ for variant, removed in filter_sets.items()
1696
+ }
1697
+ result = {
1698
+ "curves": curves,
1699
+ "excluded_complexes": {
1700
+ variant: sorted(removed) for variant, removed in filter_sets.items()
1701
+ },
1702
+ "parameters": {
1703
+ "size_th": int(size_th),
1704
+ "auprc_th": float(auprc_th),
1705
+ "use_corrected": bool(use_corrected),
1706
+ },
1707
+ }
1708
+ dsave(result, "globalpr_filter", name)
1709
+ return result
1603
1710
 
1604
- # full PR: only positions where we add a TP
1605
- mask_tp = true == 1
1606
- tp_full = tp_cum[mask_tp]
1607
- prec_full = precision[mask_tp]
1608
- tp_curves[label] = {"tp": tp_full, "precision": prec_full}
1609
1711
 
1610
- # common precision grid from 'all'
1611
- if precision_cutoffs is None:
1612
- precision_cutoffs = _mpr_precision_cutoffs_from_pairs(pairs)
1712
+ def mpr_filter(
1713
+ name,
1714
+ size_th=30,
1715
+ auprc_th=0.4,
1716
+ tp_th=1,
1717
+ percent_th=0.1,
1718
+ use_corrected=True,
1719
+ ):
1720
+ """Lazily compute the three predefined complex-filter mPR curves."""
1721
+ pra, pra_per_module, terms = _load_filter_inputs(
1722
+ name,
1723
+ "mpr_filter",
1724
+ require_terms=True,
1725
+ )
1726
+ expected_base_parameters = {
1727
+ "percent_th": float(percent_th),
1728
+ "tp_th": int(tp_th),
1729
+ }
1730
+ base = dload("mpr", name)
1731
+ if (
1732
+ not isinstance(base, dict)
1733
+ or "coverage_curve" not in base
1734
+ or base.get("parameters") != expected_base_parameters
1735
+ ):
1736
+ base = mpr_prepare(name, tp_th=tp_th, percent_th=percent_th)
1613
1737
 
1614
- contrib_df = _mpr_stepwise_contributions(
1615
- pairs,
1616
- precision_cutoffs,
1738
+ ascending = _sort_ascending_for_dataset(name)
1739
+ precision_cutoffs = np.asarray(base["precision_cutoffs"], dtype=float)
1740
+ filter_sets = _filter_sets_for_dataset(
1741
+ pra_per_module,
1742
+ size_th=size_th,
1743
+ auprc_th=auprc_th,
1744
+ use_corrected=use_corrected,
1745
+ )
1746
+ coverage_curves = {
1747
+ "all_complexes": np.asarray(base["coverage_curve"], dtype=float),
1748
+ }
1749
+ modules_auc = {"all_complexes": float(base["modules_auc"])}
1750
+ for variant in FILTER_VARIANTS[1:]:
1751
+ pairs = _mpr_build_pairs(
1752
+ pra,
1753
+ removed_ids=filter_sets[variant],
1617
1754
  ascending=ascending,
1618
1755
  )
1619
- cov = _mpr_module_coverage(
1620
- contrib_df,
1756
+ coverage = _mpr_coverage_for_pairs(
1757
+ pairs,
1758
+ precision_cutoffs,
1621
1759
  terms,
1760
+ ascending=ascending,
1622
1761
  tp_th=tp_th,
1623
1762
  percent_th=percent_th,
1624
1763
  )
1625
- # precision_cutoffs are sorted ascending (low → high).
1626
- # Coverage must be non-increasing in that direction: a more permissive
1627
- # threshold (lower precision) should never yield fewer covered terms.
1628
- # The independent greedy allocation per cutoff can violate this, so
1629
- # enforce monotonicity by propagating the max from right to left.
1630
- if cov.size > 0:
1631
- cov = np.maximum.accumulate(cov[::-1])[::-1]
1632
- coverage_curves[label] = cov
1633
- modules_auc[label] = _mpr_modules_auc(
1634
- cov,
1764
+ coverage_curves[variant] = coverage
1765
+ modules_auc[variant] = _mpr_modules_auc(
1766
+ coverage,
1635
1767
  precision_cutoffs,
1636
1768
  max_modules=200.0,
1637
1769
  )
1638
1770
 
1639
- mpr_data = {
1771
+ result = {
1640
1772
  "precision_cutoffs": precision_cutoffs,
1641
- "tp_curves": tp_curves,
1642
1773
  "coverage_curves": coverage_curves,
1643
1774
  "modules_auc": modules_auc,
1644
- "filters": {
1645
- "no_mtRibo_ETCI": sorted(mtRibo_ids),
1646
- "no_small_highAUPRC": sorted(small_hi_ids),
1647
- "size_th": size_th,
1648
- "auprc_th": auprc_th,
1649
- "percent_th": percent_th,
1650
- "tp_th": tp_th,
1775
+ "excluded_complexes": {
1776
+ variant: sorted(removed) for variant, removed in filter_sets.items()
1777
+ },
1778
+ "parameters": {
1779
+ "size_th": int(size_th),
1780
+ "auprc_th": float(auprc_th),
1781
+ "percent_th": float(percent_th),
1782
+ "tp_th": int(tp_th),
1651
1783
  "use_corrected": bool(use_corrected),
1652
1784
  },
1653
1785
  }
1654
-
1655
- dsave(mpr_data, "mpr", name)
1656
-
1657
- # Convenience: store AUCs as their own category for easy export / plotting.
1658
- dsave(modules_auc, "mpr_modules_auc", name)
1786
+ dsave(result, "mpr_filter", name)
1787
+ return result
@@ -11,11 +11,11 @@ inputs = {
11
11
  "sort": "high",
12
12
  "color": "#4E79A7",
13
13
  },
14
- "Soft Tissue": {
15
- "path": flex.example_input_path("soft_tissue_cell_lines_corum_genes.parquet"),
16
- "sort": "high",
17
- "color": "#F28E2B",
18
- },
14
+ # "Soft Tissue": {
15
+ # "path": flex.example_input_path("soft_tissue_cell_lines_corum_genes.parquet"),
16
+ # "sort": "high",
17
+ # "color": "#F28E2B",
18
+ # },
19
19
  }
20
20
 
21
21
 
@@ -70,7 +70,17 @@ flex.plot_significant_modules()
70
70
  flex.plot_per_module_scatter(n_top=10)
71
71
  flex.plot_per_module_scatter_by_size(n_top=10)
72
72
  flex.plot_module_contributions()
73
- flex.plot_mpr_summary()
73
+ mpr_auc_by_dataset = flex.plot_mpr_summary()
74
+
75
+ #%%
76
+ # Optional complex-filter sensitivity analysis. These calculations are kept
77
+ # separate because they are not needed for the standard global PR or mPR plots.
78
+ # for name in data:
79
+ # flex.mpr_filter(name)
80
+ # flex.globalpr_filter(name)
81
+ #
82
+ # flex.plot_mpr_filter()
83
+ # flex.plot_globalpr_filter()
74
84
 
75
85
  #%%
76
86
  # Save results to CSV