pflex 2.0.0__tar.gz → 2.1.0__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 (39) hide show
  1. {pflex-2.0.0 → pflex-2.1.0}/PKG-INFO +11 -7
  2. {pflex-2.0.0 → pflex-2.1.0}/README.md +10 -6
  3. {pflex-2.0.0 → pflex-2.1.0}/docs/half-max-auc-spec.md +35 -16
  4. {pflex-2.0.0 → pflex-2.1.0}/docs/user-guide.md +1 -1
  5. {pflex-2.0.0 → pflex-2.1.0}/pyproject.toml +1 -1
  6. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/analysis.py +45 -18
  7. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/plotting.py +35 -16
  8. {pflex-2.0.0 → pflex-2.1.0}/tests/test_half_max_auc.py +84 -14
  9. {pflex-2.0.0 → pflex-2.1.0}/uv.lock +1 -1
  10. {pflex-2.0.0 → pflex-2.1.0}/.gitignore +0 -0
  11. {pflex-2.0.0 → pflex-2.1.0}/.python-version +0 -0
  12. {pflex-2.0.0 → pflex-2.1.0}/LICENSE +0 -0
  13. {pflex-2.0.0 → pflex-2.1.0}/docs/early-precision-metrics-proposal.md +0 -0
  14. {pflex-2.0.0 → pflex-2.1.0}/docs/getting-started.md +0 -0
  15. {pflex-2.0.0 → pflex-2.1.0}/docs/index.md +0 -0
  16. {pflex-2.0.0 → pflex-2.1.0}/docs/installation.md +0 -0
  17. {pflex-2.0.0 → pflex-2.1.0}/mkdocs.yml +0 -0
  18. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/__init__.py +0 -0
  19. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/__init__.py +0 -0
  20. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/example_input/__init__.py +0 -0
  21. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/example_input/skin_cell_lines_corum_genes.parquet +0 -0
  22. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/example_input/soft_tissue_cell_lines_corum_genes.parquet +0 -0
  23. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/CORUM.parquet +0 -0
  24. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/GOBP.parquet +0 -0
  25. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/PATHWAY.parquet +0 -0
  26. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/__init__.py +0 -0
  27. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/corum.csv +0 -0
  28. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/gobp.csv +0 -0
  29. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/data/functional_standard/pathway.csv +0 -0
  30. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/examples/basic_usage.py +0 -0
  31. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/logging_config.py +0 -0
  32. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/preprocessing.py +0 -0
  33. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/style.py +0 -0
  34. {pflex-2.0.0 → pflex-2.1.0}/src/pflex/utils.py +0 -0
  35. {pflex-2.0.0 → pflex-2.1.0}/tests/conftest.py +0 -0
  36. {pflex-2.0.0 → pflex-2.1.0}/tests/test_benchmark.py +0 -0
  37. {pflex-2.0.0 → pflex-2.1.0}/tests/test_correlation.py +0 -0
  38. {pflex-2.0.0 → pflex-2.1.0}/tests/test_package_data.py +0 -0
  39. {pflex-2.0.0 → pflex-2.1.0}/tests/test_scatter_selection.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pflex
3
- Version: 2.0.0
3
+ Version: 2.1.0
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
@@ -252,10 +252,11 @@ flex.plot_half_max_explainer() # step-by-step figure: formula
252
252
  How it works:
253
253
 
254
254
  - **Threshold** = background + ½ × (max precision − background), the same for
255
- all datasets. Background is the precision of a random ranking (true pairs /
256
- all pairs).
257
- - **Window**: from the first TP to the latest TP where any dataset falls below
258
- the threshold, the same for all datasets.
255
+ all datasets. The max is searched from the 10th TP, so one or two lucky first
256
+ pairs cannot set it. Background is the precision of a random ranking (true
257
+ pairs / all pairs).
258
+ - **Window**: from the first TP to the largest TP where any dataset is still
259
+ at or above the threshold, the same for all datasets.
259
260
  - **Score**: the average precision in that window, scaled so a random ranking
260
261
  is 0 and a perfect one is 1.
261
262
 
@@ -267,8 +268,11 @@ Options (on `half_max_auc_scores`, `plot_half_max_auc_scores` and
267
268
  `plot_half_max_explainer`):
268
269
 
269
270
  - `fraction="three_quarter"` or `"quarter"`: threshold at 3/4 or 1/4 instead of 1/2.
270
- - `max_rank=3`: use the 3rd highest precision instead of the max, so one or two
271
- lucky first pairs cannot set the threshold.
271
+ - `max_rank=3`: use the 3rd highest precision instead of the max.
272
+ - `k0=1`, `crossing="first"`: the pFLEX 2.0 definition (max from the first TP;
273
+ window end where a curve first falls below the threshold).
274
+ - `sort=True` (bar plot and explainer table): order by score instead of
275
+ dataset order.
272
276
 
273
277
  The full definition and all parameters are in
274
278
  [docs/half-max-auc-spec.md](docs/half-max-auc-spec.md).
@@ -220,10 +220,11 @@ flex.plot_half_max_explainer() # step-by-step figure: formula
220
220
  How it works:
221
221
 
222
222
  - **Threshold** = background + ½ × (max precision − background), the same for
223
- all datasets. Background is the precision of a random ranking (true pairs /
224
- all pairs).
225
- - **Window**: from the first TP to the latest TP where any dataset falls below
226
- the threshold, the same for all datasets.
223
+ all datasets. The max is searched from the 10th TP, so one or two lucky first
224
+ pairs cannot set it. Background is the precision of a random ranking (true
225
+ pairs / all pairs).
226
+ - **Window**: from the first TP to the largest TP where any dataset is still
227
+ at or above the threshold, the same for all datasets.
227
228
  - **Score**: the average precision in that window, scaled so a random ranking
228
229
  is 0 and a perfect one is 1.
229
230
 
@@ -235,8 +236,11 @@ Options (on `half_max_auc_scores`, `plot_half_max_auc_scores` and
235
236
  `plot_half_max_explainer`):
236
237
 
237
238
  - `fraction="three_quarter"` or `"quarter"`: threshold at 3/4 or 1/4 instead of 1/2.
238
- - `max_rank=3`: use the 3rd highest precision instead of the max, so one or two
239
- lucky first pairs cannot set the threshold.
239
+ - `max_rank=3`: use the 3rd highest precision instead of the max.
240
+ - `k0=1`, `crossing="first"`: the pFLEX 2.0 definition (max from the first TP;
241
+ window end where a curve first falls below the threshold).
242
+ - `sort=True` (bar plot and explainer table): order by score instead of
243
+ dataset order.
240
244
 
241
245
  The full definition and all parameters are in
242
246
  [docs/half-max-auc-spec.md](docs/half-max-auc-spec.md).
@@ -1,4 +1,20 @@
1
- # Spec: half-max AUC (early precision, global PRA, pFLEX 2.0)
1
+ # Spec: half-max AUC (early precision, global PRA, pFLEX 2.1)
2
+
3
+ ## Changes in 2.1
4
+
5
+ - **Max from the 10th TP** (`k0=10`, was 1): the first few TPs are noisy (one
6
+ or two lucky hits give precision 1), and a max from them puts the threshold
7
+ above the curves' real level.
8
+ - **Crossing = the largest TP still at or above the threshold**
9
+ (`crossing="last"`, was `"first"`): with "first falls below", a curve that
10
+ starts below the threshold (first pairs wrong) and rises above it later
11
+ crossed at its start. On GO BP this cut the shared window at TP 5 although
12
+ the best curves stay above the threshold until TP ~2,700, so the window did
13
+ not reach where the best curve crosses.
14
+ - **Bar plot and explainer table in dataset order** (`sort=False`, was sorted
15
+ by score).
16
+
17
+ `k0=1, crossing="first"` reproduces the 2.0 scores.
2
18
 
3
19
  ## Why
4
20
 
@@ -30,9 +46,9 @@ have the same number of true positives `P`, pairs `N` and background.
30
46
 
31
47
  1. **Curve points.** One point per true positive: for the k-th TP found at rank
32
48
  `r_k`, `p(k) = k / r_k`.
33
- 2. **Start for max and crossing.** `K0 = 1` by default: both are searched from
34
- the first TP. Option `k0=10` starts the search at the 10th TP, where the log
35
- plot starts (the first TPs are noisy). The area always starts at TP 1.
49
+ 2. **Start for max and crossing.** `K0 = 10` by default: both are searched
50
+ from the 10th TP, where the log plot starts (the first TPs are noisy).
51
+ `k0=1` searches from the first TP (2.0). The area always starts at TP 1.
36
52
  3. **Background.** `p_bg = P / N`, the precision of a random ranking. The same
37
53
  for every dataset; if it differs, a warning is logged and the reference
38
54
  dataset's value is used for the threshold.
@@ -48,10 +64,13 @@ have the same number of true positives `P`, pairs `N` and background.
48
64
  **default**), 3/4 or 1/4; `fraction="half"`, `"three_quarter"`, `"quarter"`
49
65
  or a number in (0, 1). Example: max 0.8, bg 0.1 → 3/4: 0.625, 1/2: 0.45,
50
66
  1/4: 0.275. A lower fraction cuts later.
51
- 6. **Crossing (per dataset).** `k_cross` = the first `k >= K0` with
52
- `p(k) < p_threshold`, interpolated linearly between the last TP above and
53
- the first TP below. Later recoveries are ignored. `K0` if the curve starts
54
- below the threshold, `P` if it never falls below.
67
+ 6. **Crossing (per dataset).** `k_cross` = the largest `k >= K0` with
68
+ `p(k) >= p_threshold`, interpolated linearly between that TP and the next
69
+ (below) one: where the curve falls below the threshold for the last time.
70
+ A curve that starts below the threshold and rises above it later is not
71
+ cut at its start. `K0` if the curve is never at or above the threshold, `P`
72
+ if it ends at or above. Option `crossing="first"` (2.0): the first
73
+ `k >= K0` with `p(k) < p_threshold`, later recoveries ignored.
55
74
  7. **Window (one for all datasets).** `K = max k_cross` over the datasets
56
75
  (`cut_from` names the dataset). Every dataset is scored over TP 1 to K.
57
76
  8. **Score.**
@@ -71,10 +90,10 @@ up to `K` in the average, so dropping early lowers its score.
71
90
 
72
91
  ## API
73
92
 
74
- - `half_max_auc(prediction, k0=1, threshold=None, k_end=None, max_window=1, fraction=0.5, max_rank=1)`:
93
+ - `half_max_auc(prediction, k0=10, threshold=None, k_end=None, max_window=1, fraction=0.5, max_rank=1, crossing="last")`:
75
94
  one ranked label vector. Without `threshold` it uses the dataset's own
76
95
  threshold; without `k_end` its own crossing as the window end.
77
- - `half_max_auc_scores(fraction=0.5, k0=1, max_window=1, max_rank=1)`: reads every cached
96
+ - `half_max_auc_scores(fraction=0.5, k0=10, max_window=1, max_rank=1, crossing="last")`: reads every cached
78
97
  `pra` result, computes the shared threshold and window, scores all datasets,
79
98
  saves each under `half_max_auc` and returns `{dataset: result}`. Plots and
80
99
  `save_results_to_csv()` call it, so scores always reflect the current set of
@@ -92,15 +111,15 @@ fraction 3/4, 1/2 or 1/4
92
111
  p_threshold shared threshold; threshold_from: reference dataset
93
112
  k_cross this dataset's own crossing
94
113
  k_cut shared window end K; cut_from: dataset it comes from
95
- n_tp (P), n_pairs (N), k0, max_window, max_rank, reason
114
+ n_tp (P), n_pairs (N), k0, max_window, max_rank, crossing, reason
96
115
  ```
97
116
 
98
117
  ## Edge cases
99
118
 
100
119
  - `P < K0` (fewer than 10 TPs): score NaN with a reason.
101
120
  - No dataset with precision above background: all scores NaN.
102
- - Every dataset below the threshold from `K0`: `K = K0`, the window is TP 1 to
103
- `K0`.
121
+ - Every dataset below the threshold from `K0` on: `K = K0`, the window is TP
122
+ 1 to `K0`.
104
123
  - Window end beyond a dataset's last TP (only with different gene sets): cut
105
124
  at its last TP, with a reason.
106
125
  - Point exactly on the threshold counts as above.
@@ -111,9 +130,9 @@ n_tp (P), n_pairs (N), k0, max_window, max_rank, reason
111
130
  usual log-TP plot, the shared threshold (grey dashed), each dataset's
112
131
  crossing (dot) and the window end K (grey dotted). No area is shaded there,
113
132
  because the score is not an area on a log axis.
114
- - `plot_half_max_auc_scores(fraction=0.5)`: one bar per dataset
115
- (`half_max_auc_values`, `three_quarter_max_auc_values`,
116
- `quarter_max_auc_values`).
133
+ - `plot_half_max_auc_scores(fraction=0.5)`: one bar per dataset, in dataset
134
+ order (`sort=True`: by score) (`half_max_auc_values`,
135
+ `three_quarter_max_auc_values`, `quarter_max_auc_values`).
117
136
  - `plot_half_max_explainer(fraction=0.5)` (optional): step-by-step figure on
118
137
  the linear TP axis, with the scored area, the formula and a results table.
119
138
  - `save_results_to_csv()` writes `csv/half_max_auc.csv` (default fraction).
@@ -190,7 +190,7 @@ Global plots:
190
190
 
191
191
  - `plot_precision_recall_curve(line_width=1.0, hide_minor_ticks=True)` shows precision against the cumulative number of true-positive gene pairs. This is the main global performance curve; higher precision at the same true-positive count means better ranking.
192
192
  - `plot_auc_scores()` shows one bar per dataset using the global AUPRC value saved by `pra()`. Higher AUPRC means the ranked gene-pair network recovers functional-standard pairs earlier in the ranking.
193
- - `plot_half_max_auc_scores(fraction=0.5)` shows one bar per dataset with the half-max AUC, an early-precision score. Global AUPRC averages precision over all of recall, so a long low-precision tail can outweigh a short high-precision head. The half-max AUC scores only the head, in one TP window for all datasets: take the highest precision of any dataset, searched from the first TP (options: `k0=10` to start at the 10th TP, `max_window=3` to require it for 3 consecutive TPs, `max_rank=3` to take the 3rd highest precision), and the background (global prevalence, P/N); the threshold is background + `fraction` of the distance to that max (1/2 by default, or 3/4 or 1/4: `fraction="half"`, `"three_quarter"`, `"quarter"`); the window runs from the first TP to the latest TP where any dataset's precision first falls below the threshold. The score is each dataset's average precision over that window on the linear TP axis (every TP the same weight, no log scaling), measured from the background: (mean - background) / (1 - background), so a random ranking scores 0 and a perfect one 1. Standard AUPRC is unchanged. `flex.half_max_auc_scores(fraction=...)` returns the values. `plot_precision_recall_curve(half_max=True, half_max_fraction=...)` marks the threshold (grey dashed), each dataset's crossing (dot) and the window end (grey dotted) on the usual log-TP plot, without shading. Half-max values are exported to `csv/half_max_auc.csv`. Definition: `docs/half-max-auc-spec.md`.
193
+ - `plot_half_max_auc_scores(fraction=0.5)` shows one bar per dataset with the half-max AUC, an early-precision score. Global AUPRC averages precision over all of recall, so a long low-precision tail can outweigh a short high-precision head. The half-max AUC scores only the head, in one TP window for all datasets: take the highest precision of any dataset, searched from the 10th TP so lucky first pairs cannot set it (options: `k0=1` to search from the first TP, `max_window=3` to require it for 3 consecutive TPs, `max_rank=3` to take the 3rd highest precision), and the background (global prevalence, P/N); the threshold is background + `fraction` of the distance to that max (1/2 by default, or 3/4 or 1/4: `fraction="half"`, `"three_quarter"`, `"quarter"`); each dataset's crossing is the largest TP where its precision is still at or above the threshold (`crossing="first"`: where it first falls below, the pFLEX 2.0 rule), and the window runs from the first TP to the latest crossing of any dataset. The score is each dataset's average precision over that window on the linear TP axis (every TP the same weight, no log scaling), measured from the background: (mean - background) / (1 - background), so a random ranking scores 0 and a perfect one 1. Standard AUPRC is unchanged. `flex.half_max_auc_scores(fraction=...)` returns the values. `plot_precision_recall_curve(half_max=True, half_max_fraction=...)` marks the threshold (grey dashed), each dataset's crossing (dot) and the window end (grey dotted) on the usual log-TP plot, without shading. Bars are in dataset order (`sort=True` orders them by score). Half-max values are exported to `csv/half_max_auc.csv`. Definition: `docs/half-max-auc-spec.md`.
194
194
  - `plot_half_max_explainer(dataset_names=None, fraction=0.5)` (optional) draws a step-by-step explanation of the score for sharing, on the linear TP axis the score is computed on: the PR curves with the background, the max, the threshold, each dataset's crossing, the single TP line and the scored area marked, and below the plot how the score is calculated, the formula and a table with each dataset's crossing, mean precision, score and AUPRC. Saved as `half_max_explainer` (`three_quarter_max_explainer`, `quarter_max_explainer`) in the output folder.
195
195
 
196
196
  Per-module plots:
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pflex"
3
- version = "2.0.0"
3
+ version = "2.1.0"
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 = [
@@ -444,11 +444,30 @@ def _sustained_max(precision, window, rank=1):
444
444
  return value, i
445
445
 
446
446
 
447
- def _threshold_crossing(k, precision, threshold):
448
- """TP where precision first falls below ``threshold``, interpolated linearly in TP.
447
+ CROSSINGS = ("first", "last")
449
448
 
450
- ``k[0]`` if it starts below, ``k[-1]`` if it never falls below.
449
+
450
+ def _threshold_crossing(k, precision, threshold, crossing="last"):
451
+ """TP where precision falls below ``threshold``, interpolated linearly in TP.
452
+
453
+ ``crossing="last"`` (default): the largest TP still at or above the
454
+ threshold (where it falls below for the last time), so a curve that starts
455
+ below the threshold and rises above it later is not cut at its start;
456
+ ``k[0]`` if it is never at or above, ``k[-1]`` if it ends at or above.
457
+ ``crossing="first"`` (pFLEX 2.0): the first TP where it falls below; ``k[0]``
458
+ if it starts below, ``k[-1]`` if it never falls below.
451
459
  """
460
+ if crossing not in CROSSINGS:
461
+ raise ValueError(f"crossing must be one of {CROSSINGS}")
462
+ if crossing == "last":
463
+ above = np.flatnonzero(precision >= threshold)
464
+ if above.size == 0:
465
+ return float(k[0])
466
+ j = int(above[-1])
467
+ if j == len(k) - 1:
468
+ return float(k[-1])
469
+ frac = (precision[j] - threshold) / (precision[j] - precision[j + 1])
470
+ return float(k[j] + frac * (k[j + 1] - k[j]))
452
471
  below = np.flatnonzero(precision < threshold)
453
472
  if below.size == 0:
454
473
  return float(k[-1])
@@ -495,26 +514,29 @@ def threshold_name(fraction):
495
514
  return f"{f:g}"
496
515
 
497
516
 
498
- def half_max_auc(prediction, k0=1, threshold=None, k_end=None, max_window=1, fraction=0.5,
499
- max_rank=1):
517
+ def half_max_auc(prediction, k0=10, threshold=None, k_end=None, max_window=1, fraction=0.5,
518
+ max_rank=1, crossing="last"):
500
519
  """Half-max AUC of one ranked label vector.
501
520
 
502
521
  ``prediction`` is the binary label vector in rank order. One curve point
503
522
  per true positive: the k-th TP found at rank r has precision k / r.
504
523
 
505
524
  - Max: the highest precision from the ``k0``-th TP on. Defaults use the
506
- plain max from the first TP (``k0=1``, ``max_window=1``, ``max_rank=1``).
525
+ plain max from the 10th TP (``k0=10``, ``max_window=1``, ``max_rank=1``),
526
+ where the log plot starts: the first few TPs are noisy (one or two lucky
527
+ hits give precision 1). ``k0=1`` searches from the first TP (pFLEX 2.0).
507
528
  Options: ``max_rank=3`` takes the 3rd highest precision instead, so one
508
529
  or two lucky hits cannot set it (1, 1, 1, ... still gives 1);
509
530
  ``max_window=3`` takes the highest precision held for 3 consecutive TPs
510
- (a single early hit cannot set it); ``k0=10`` starts the search for the
511
- max and the crossing at the 10th TP, where the log plot starts.
531
+ (a single early hit cannot set it).
512
532
  - ``threshold``: background (P / N) + ``fraction`` of the distance from
513
533
  background to the max. ``fraction`` 1/2 (default, half max), 3/4 or 1/4
514
534
  (also "half", "three_quarter", "quarter"). Normally passed in, shared by
515
535
  all datasets (``half_max_auc_scores``).
516
- - ``k_cross``: the first TP from ``k0`` on where precision falls below the
517
- threshold.
536
+ - ``k_cross``: the largest TP from ``k0`` on where precision is still at or
537
+ above the threshold (``crossing="last"``, default), or the first TP where
538
+ it falls below (``crossing="first"``, pFLEX 2.0; a curve that starts below
539
+ the threshold is then cut at its start, even if it rises above later).
518
540
  - Window: the linear TP axis from the **first** TP to ``k_end`` (always
519
541
  from TP 1, whatever ``k0`` is). ``k_end`` is normally
520
542
  passed in, the same for all datasets (the largest ``k_cross``);
@@ -530,12 +552,14 @@ def half_max_auc(prediction, k0=1, threshold=None, k_end=None, max_window=1, fra
530
552
  See docs/half-max-auc-spec.md.
531
553
  """
532
554
  f = _threshold_fraction(fraction)
555
+ if crossing not in CROSSINGS:
556
+ raise ValueError(f"crossing must be one of {CROSSINGS}")
533
557
  k_all, p_all, p_bg, n_tp, n_pairs = _tp_precision(prediction, 1)
534
558
  res = {"score": np.nan, "mean_precision": np.nan, "area": np.nan,
535
559
  "p_max": np.nan, "k_max": np.nan, "p_bg": p_bg, "fraction": f,
536
560
  "p_threshold": np.nan, "k_cross": np.nan, "k_cut": np.nan,
537
561
  "n_tp": n_tp, "n_pairs": n_pairs, "k0": k0, "max_window": max_window, "max_rank": max_rank,
538
- "reason": ""}
562
+ "crossing": crossing, "reason": ""}
539
563
  if k_all is None or n_tp < k0:
540
564
  res["reason"] = f"fewer than {k0} true positives"
541
565
  return res
@@ -549,7 +573,7 @@ def half_max_auc(prediction, k0=1, threshold=None, k_end=None, max_window=1, fra
549
573
  return res
550
574
  threshold = p_bg + f * (p_max - p_bg)
551
575
  res["p_threshold"] = float(threshold)
552
- res["k_cross"] = _threshold_crossing(k, precision, threshold)
576
+ res["k_cross"] = _threshold_crossing(k, precision, threshold, crossing)
553
577
 
554
578
  if k_end is None:
555
579
  k_end = res["k_cross"]
@@ -568,16 +592,18 @@ def half_max_auc(prediction, k0=1, threshold=None, k_end=None, max_window=1, fra
568
592
  return res
569
593
 
570
594
 
571
- def half_max_auc_scores(fraction=0.5, k0=1, max_window=1, max_rank=1):
595
+ def half_max_auc_scores(fraction=0.5, k0=10, max_window=1, max_rank=1, crossing="last"):
572
596
  """Half-max AUC of every dataset with global PRA results, on one shared window.
573
597
 
574
598
  1. Threshold: from the dataset with the highest precision (from the
575
- ``k0``-th TP on, default the first; held for ``max_window`` consecutive
599
+ ``k0``-th TP on, default the 10th; held for ``max_window`` consecutive
576
600
  TPs, default 1; or its ``max_rank``-th highest value, default 1 = plain max): its
577
601
  background (P / N) + ``fraction`` of the distance from background to
578
602
  that max. ``fraction`` 1/2 (default), 3/4 or 1/4 ("half",
579
603
  "three_quarter", "quarter").
580
- 2. Each dataset's ``k_cross``: where its precision first falls below it.
604
+ 2. Each dataset's ``k_cross``: the largest TP still at or above it
605
+ (``crossing="last"``, default), or where its precision first falls
606
+ below it (``crossing="first"``, pFLEX 2.0).
581
607
  3. Window: TP 1 to the largest ``k_cross``, the same for every dataset.
582
608
  4. Score: plain average precision over the window (linear TP axis, every
583
609
  TP the same weight), measured from the background.
@@ -609,7 +635,7 @@ def half_max_auc_scores(fraction=0.5, k0=1, max_window=1, max_rank=1):
609
635
  if threshold is not None:
610
636
  for name, pred in predictions.items():
611
637
  k_cross = half_max_auc(pred, k0, threshold=threshold, max_window=max_window, max_rank=max_rank,
612
- fraction=f)["k_cross"]
638
+ fraction=f, crossing=crossing)["k_cross"]
613
639
  if np.isfinite(k_cross):
614
640
  crossings[name] = k_cross
615
641
  k_end = cut_from = None
@@ -620,13 +646,14 @@ def half_max_auc_scores(fraction=0.5, k0=1, max_window=1, max_rank=1):
620
646
  results = {}
621
647
  for name, pred in predictions.items():
622
648
  if k_end is None:
623
- res = half_max_auc(pred, k0, max_window=max_window, fraction=f, max_rank=max_rank)
649
+ res = half_max_auc(pred, k0, max_window=max_window, fraction=f, max_rank=max_rank,
650
+ crossing=crossing)
624
651
  res.update(score=np.nan, mean_precision=np.nan, area=np.nan,
625
652
  p_threshold=np.nan, k_cross=np.nan, k_cut=np.nan,
626
653
  reason=res["reason"] or "no dataset above background")
627
654
  else:
628
655
  res = half_max_auc(pred, k0, threshold=threshold, k_end=k_end,
629
- max_window=max_window, fraction=f, max_rank=max_rank)
656
+ max_window=max_window, fraction=f, max_rank=max_rank, crossing=crossing)
630
657
  res.update(threshold_from=ref, cut_from=cut_from)
631
658
  results[name] = res
632
659
  dsave(res, "half_max_auc", name)
@@ -773,7 +773,7 @@ def _global_prevalence(pra):
773
773
 
774
774
 
775
775
  def _draw_half_max(ax, pra, hm, color, line_width):
776
- """Dot where one dataset's precision first falls below the shared threshold.
776
+ """Dot where one dataset's precision falls below the shared threshold (its ``k_cross``).
777
777
 
778
778
  No shaded area: this plot has a log TP axis, while the score averages
779
779
  precision over the linear TP axis, so an area drawn here would not be the
@@ -817,7 +817,8 @@ def plot_precision_recall_curve(line_width=1.0, hide_minor_ticks=True, min_preci
817
817
  caption="Gene pairs ranked by score; a true positive is a pair "
818
818
  "sharing a module in {standard}.",
819
819
  global_prevalence=False, half_max=False, half_max_fraction=0.5,
820
- half_max_k0=1, half_max_window=1, half_max_rank=1, ax=None):
820
+ half_max_k0=10, half_max_window=1, half_max_rank=1,
821
+ half_max_crossing="last", ax=None):
821
822
  """Global PR curve of every dataset.
822
823
 
823
824
  ``global_prevalence=True`` adds a black dashed line at the fraction of all
@@ -830,13 +831,14 @@ def plot_precision_recall_curve(line_width=1.0, hide_minor_ticks=True, min_preci
830
831
  crossing) as a grey dotted line. No area is shaded: the x axis here is
831
832
  log-scaled for reading, while the score averages precision over the
832
833
  linear TP axis (see ``half_max_auc_scores``, ``plot_half_max_explainer``).
833
- ``half_max_k0``, ``half_max_window`` and ``half_max_rank`` are its ``k0``,
834
- ``max_window`` and ``max_rank``.
834
+ ``half_max_k0``, ``half_max_window``, ``half_max_rank`` and
835
+ ``half_max_crossing`` are its ``k0``, ``max_window``, ``max_rank`` and ``crossing``.
835
836
  """
836
837
  pra = dload("pra")
837
838
  config = dload("config")
838
839
  hm_all = (half_max_auc_scores(fraction=half_max_fraction, k0=half_max_k0,
839
- max_window=half_max_window, max_rank=half_max_rank)
840
+ max_window=half_max_window, max_rank=half_max_rank,
841
+ crossing=half_max_crossing)
840
842
  if half_max else None)
841
843
  fig, ax, owns = _start(ax, CURVE_FIGSIZE)
842
844
  _setup_log_tp_axis(ax, hide_minor_ticks)
@@ -1620,24 +1622,31 @@ def plot_auc_scores(title="Area under the global PR curve per dataset",
1620
1622
 
1621
1623
 
1622
1624
  @_publication_style
1623
- def plot_half_max_auc_scores(fraction=0.5, k0=1, max_window=1, max_rank=1, title=None,
1625
+ def plot_half_max_auc_scores(fraction=0.5, k0=10, max_window=1, max_rank=1, crossing="last",
1626
+ sort=False, title=None,
1624
1627
  caption="Mean precision of the TPs from the first TP to the shared cut "
1625
1628
  "(linear TP axis), scaled so background is 0 and perfect is 1.",
1626
1629
  ax=None):
1627
1630
  """One bar per dataset with the half-max AUC (see ``half_max_auc_scores``).
1628
1631
 
1629
1632
  ``fraction`` sets the threshold: 1/2 (half max, default), 3/4 or 1/4 of
1630
- the distance from background to the max. ``k0``, ``max_window`` and ``max_rank`` as in
1631
- ``half_max_auc_scores``. Saved as ``half_max_auc_values``
1633
+ the distance from background to the max. ``k0``, ``max_window``, ``max_rank`` and
1634
+ ``crossing`` as in ``half_max_auc_scores``. ``sort=False`` (default) keeps the
1635
+ dataset order (SVD_2 before SVD_10); ``sort=True`` orders the bars by score.
1636
+ Saved as ``half_max_auc_values``
1632
1637
  (``three_quarter_max_auc_values``, ``quarter_max_auc_values``).
1633
1638
  """
1634
1639
  config = dload("config")
1635
1640
  name = threshold_name(fraction)
1636
1641
  f_word, _ = _fraction_text(fraction)
1637
- hm_all = half_max_auc_scores(fraction=fraction, k0=k0, max_window=max_window, max_rank=max_rank)
1642
+ hm_all = half_max_auc_scores(fraction=fraction, k0=k0, max_window=max_window, max_rank=max_rank,
1643
+ crossing=crossing)
1638
1644
  scores = {d: hm["score"] for d, hm in hm_all.items()}
1639
1645
 
1640
- datasets = sorted(scores, key=lambda d: np.nan_to_num(scores[d], nan=-np.inf), reverse=True)
1646
+ if sort:
1647
+ datasets = sorted(scores, key=lambda d: np.nan_to_num(scores[d], nan=-np.inf), reverse=True)
1648
+ else:
1649
+ datasets = sorted(scores, key=_natural_key)
1641
1650
  colors = _plot_dataset_colors(datasets, None, config, dload("input", "colors"))
1642
1651
 
1643
1652
  fig, ax, owns = _start(ax, _bar_figsize(len(datasets)))
@@ -1665,8 +1674,8 @@ def _fraction_text(fraction):
1665
1674
  return _FRACTION_TEXT.get(name, (name, name))
1666
1675
 
1667
1676
 
1668
- def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=1, max_window=1, max_rank=1,
1669
- filename=None):
1677
+ def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=10, max_window=1, max_rank=1,
1678
+ filename=None, crossing="last", sort=False):
1670
1679
  """Step-by-step explanation figure of the half-max AUC, for sharing.
1671
1680
 
1672
1681
  Optional; nothing else depends on it. Uses the cached global PRA results
@@ -1680,7 +1689,9 @@ def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=1,
1680
1689
  crossing, mean precision, score and AUPRC.
1681
1690
 
1682
1691
  ``dataset_names`` limits and orders the datasets (the threshold and K are
1683
- still computed from all of them). Saved as ``filename`` (default
1692
+ still computed from all of them). ``crossing`` as in ``half_max_auc_scores``.
1693
+ ``sort=False`` (default) keeps the dataset order in the table; ``sort=True``
1694
+ orders it by score. Saved as ``filename`` (default
1684
1695
  ``half_max_explainer``, ``three_quarter_max_explainer``,
1685
1696
  ``quarter_max_explainer``) in the output folder when
1686
1697
  ``plotting.save_plot`` is on. Returns the half-max results.
@@ -1692,7 +1703,8 @@ def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=1,
1692
1703
  fname = threshold_name(f)
1693
1704
  f_word, f_text = _fraction_text(f)
1694
1705
  filename = filename or f"{fname}_max_explainer"
1695
- results = half_max_auc_scores(fraction=f, k0=k0, max_window=max_window, max_rank=max_rank)
1706
+ results = half_max_auc_scores(fraction=f, k0=k0, max_window=max_window, max_rank=max_rank,
1707
+ crossing=crossing)
1696
1708
  # Natural order (SVD_2 before SVD_10) unless the caller gives one.
1697
1709
  # Names as written by the user ("Soft Tissue") or as stored ("Soft_Tissue").
1698
1710
  wanted = [_sanitize(n) for n in dataset_names] if dataset_names else sorted(results, key=_natural_key)
@@ -1781,13 +1793,20 @@ def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=1,
1781
1793
  ncol=3, fontsize=9, frameon=False)
1782
1794
 
1783
1795
  width = max(len("Dataset"), *(len(label[n]) for n in names)) + 2
1784
- rows = sorted(names, key=lambda n: -np.nan_to_num(results[n]["score"], nan=-np.inf))
1796
+ rows = (sorted(names, key=lambda n: -np.nan_to_num(results[n]["score"], nan=-np.inf))
1797
+ if sort else names)
1785
1798
  table = "\n".join(
1786
1799
  f" {label[n]:<{width}}{results[n]['k_cross']:>9.0f} {results[n]['mean_precision']:>9.3f}"
1787
1800
  f" {results[n]['score']:>7.3f} {float(auprc.get(n, np.nan)):>7.4f}"
1788
1801
  for n in rows)
1789
1802
  P, N = ref_hm["n_tp"], ref_hm["n_pairs"]
1790
1803
  start_text = f" (from the {k0}th on)" if k0 > 1 else ""
1804
+ if crossing == "last":
1805
+ crossing_line = (f"(4) For each dataset, the largest TP{start_text} where its precision is still "
1806
+ "at or above it\n (where it falls below for the last time; dots; table).\n")
1807
+ else:
1808
+ crossing_line = (f"(4) For each dataset, the TP{start_text} where its precision first falls "
1809
+ "below it (dots; table).\n")
1791
1810
  where = f"{_display_name(ref)}, TP {k_max}" + (f"–{k_max + max_window - 1}" if max_window > 1 else "")
1792
1811
  if max_window > 1:
1793
1812
  max_lines = (f"(2) Max = highest precision any dataset keeps for {max_window} consecutive TPs"
@@ -1805,7 +1824,7 @@ def plot_half_max_explainer(dataset_names=None, fraction=0.5, title=None, k0=1,
1805
1824
  " Identical for all datasets (same shared genes). The area is measured from this line.\n" +
1806
1825
  max_lines +
1807
1826
  f"(3) Threshold = bg + {f_text} × (max − bg) = {thr:.3f} ({f_word.lower()} max; options 1/2, 3/4, 1/4) — one value for all.\n"
1808
- f"(4) For each dataset, the TP{start_text} where its precision first falls below it (dots; table).\n"
1827
+ + crossing_line +
1809
1828
  f"(5) K = the largest of these TPs = {K:.0f} ({_display_name(last)}) — one vertical line for all datasets.\n"
1810
1829
  "(6) For each dataset, average its precision over TP 1 → K, then rescale so random = 0 and perfect = 1:\n\n"
1811
1830
  " mean precision = area under p(k) from k = 1 to K / (K − 1) (trapezoid; = average of p(k))\n\n"
@@ -102,15 +102,53 @@ def test_random_level_ranking_scores_zero():
102
102
  assert res["score"] == pytest.approx(0.0, abs=1e-9)
103
103
 
104
104
 
105
- def test_crossing_is_first_fall_even_if_curve_recovers():
106
- # Drops below threshold at k=3, then recovers to 20/27 > threshold.
105
+ def test_first_crossing_ignores_a_recovery():
106
+ # crossing="first" (pFLEX 2.0): drops below at k=3, recovery to 20/27 is ignored.
107
107
  ranks = [1, 2, 10] + list(range(11, 28))
108
- res = half_max_auc(labels_from_ranks(ranks, 100), k0=1, max_window=1)
108
+ res = half_max_auc(labels_from_ranks(ranks, 100), k0=1, max_window=1, crossing="first")
109
109
 
110
110
  assert res["p_threshold"] == pytest.approx(0.6)
111
111
  assert 2 < res["k_cross"] < 3
112
112
 
113
113
 
114
+ def test_last_crossing_takes_the_largest_tp_above_threshold():
115
+ # Same ranking: falls below at k=3 (3/10), recovers to 20/27; never falls below again.
116
+ ranks = [1, 2, 10] + list(range(11, 28))
117
+ res = half_max_auc(labels_from_ranks(ranks, 100), k0=1, crossing="last")
118
+
119
+ assert res["p_threshold"] == pytest.approx(0.6)
120
+ assert res["k_cross"] == 20 # still above at the last TP
121
+ assert res["crossing"] == "last"
122
+
123
+
124
+ def test_last_crossing_curve_that_starts_low_is_not_cut_at_its_start():
125
+ # p: 1/5, 2/6, 3/7, 4/8, 5/9, ... rises above 0.5, then falls below for good.
126
+ ranks = list(range(5, 45)) + [45 + 10 * i for i in range(1, 40)]
127
+ labels = labels_from_ranks(ranks, 2000)
128
+ k = np.arange(1, len(ranks) + 1)
129
+ p = k / np.array(ranks)
130
+ j = int(np.flatnonzero(p >= 0.5)[-1]) # last TP at or above
131
+ expected = k[j] + (p[j] - 0.5) / (p[j] - p[j + 1])
132
+
133
+ first = half_max_auc(labels, threshold=0.5, k0=1, crossing="first")
134
+ last = half_max_auc(labels, threshold=0.5, k0=1) # default: last crossing
135
+
136
+ assert first["k_cross"] == 1 # starts below: the first-crossing rule cuts at TP 1
137
+ assert last["k_cross"] == pytest.approx(expected)
138
+ assert last["k_cross"] > 30
139
+
140
+
141
+ def test_last_crossing_never_above_is_first_tp():
142
+ res = half_max_auc(labels_from_ranks(range(10, 1001, 10), 1000), threshold=0.5)
143
+
144
+ assert res["k_cross"] == 10 # the first TP searched (k0=10)
145
+
146
+
147
+ def test_invalid_crossing():
148
+ with pytest.raises(ValueError):
149
+ half_max_auc(labels_from_ranks([1, 2, 10], 100), crossing="middle")
150
+
151
+
114
152
  def test_max_starts_at_k0():
115
153
  # A precision-1 head below k0 must not set the max.
116
154
  ranks = list(range(1, 6)) + [10 * k for k in range(6, 40)]
@@ -132,14 +170,17 @@ def test_max_ignores_a_single_spike():
132
170
  assert res["k_max"] == 10
133
171
 
134
172
 
135
- def test_defaults_plain_max_from_first_tp():
136
- # Precision 1 at TP 1-9 (ranks 1-9), lower afterwards: default max comes from TP 1.
173
+ def test_defaults_max_from_tenth_tp_and_last_crossing():
174
+ # Precision 1 at TP 1-9 (ranks 1-9), lower afterwards: the default max skips them.
137
175
  ranks = list(range(1, 10)) + [12] + [12 + 8 * (k - 10) for k in range(11, 40)]
138
- res = half_max_auc(labels_from_ranks(ranks, 1000))
176
+ labels = labels_from_ranks(ranks, 1000)
177
+ res = half_max_auc(labels)
139
178
 
140
- assert res["k0"] == 1 and res["max_window"] == 1
141
- assert res["p_max"] == 1.0
142
- assert res["k_max"] == 1
179
+ assert res["k0"] == 10 and res["max_window"] == 1 and res["crossing"] == "last"
180
+ assert res["p_max"] == pytest.approx(10 / 12)
181
+ assert res["k_max"] == 10
182
+ # k0=1 (pFLEX 2.0): the lucky head sets the max.
183
+ assert half_max_auc(labels, k0=1)["p_max"] == 1.0
143
184
 
144
185
 
145
186
  def test_high_head_beats_long_mediocre_tail():
@@ -169,11 +210,11 @@ def test_dominated_curve_never_scores_higher():
169
210
  def test_curve_below_threshold_from_start():
170
211
  flat = labels_from_ranks(curve_from_precision(lambda k: 0.3), 100_000)
171
212
 
172
- own = half_max_auc(flat, threshold=0.5)
173
- from_10 = half_max_auc(flat, threshold=0.5, k0=10)
213
+ own = half_max_auc(flat, threshold=0.5, k0=1)
214
+ from_10 = half_max_auc(flat, threshold=0.5) # default k0=10
174
215
  shared = half_max_auc(flat, threshold=0.5, k_end=500)
175
216
 
176
- # Crossing at the first TP searched: TP 1 by default (no window of its own), TP 10 with k0=10.
217
+ # Never above: crossing at the first TP searched, TP 1 with k0=1 (no window of its own), TP 10 by default.
177
218
  assert own["k_cross"] == 1 and math.isnan(own["score"]) and own["reason"]
178
219
  assert from_10["k_cross"] == from_10["k_cut"] == 10
179
220
  assert np.isfinite(from_10["score"])
@@ -297,6 +338,35 @@ def test_half_max_auc_bar_plot(config):
297
338
  assert scores["Network_A"] == flex.dload("half_max_auc", "Network_A")["score"]
298
339
 
299
340
 
341
+ def test_bar_plot_unsorted_keeps_dataset_order(config):
342
+ # Weaker network first by name: sorted bars would put it second.
343
+ inputs = {
344
+ "SVD_10": {"path": make_dataset(seed=5, signal=0.3), "sort": "high"},
345
+ "SVD_2": {"path": make_dataset(seed=0), "sort": "high"},
346
+ }
347
+ run_pipeline(config, inputs)
348
+
349
+ import matplotlib.pyplot as plt
350
+ fig, ax = plt.subplots()
351
+ flex.plot_half_max_auc_scores(sort=False, crossing="last", ax=ax)
352
+ names = [t.get_text() for t in ax.get_xticklabels()]
353
+ plt.close(fig)
354
+
355
+ assert names == ["SVD_2", "SVD_10"] # natural order, not by score
356
+
357
+
358
+ def test_explainer_with_last_crossing(config):
359
+ inputs = {
360
+ "clean": {"path": make_dataset(seed=0), "sort": "high"},
361
+ "noisy": {"path": make_dataset(seed=5, signal=0.3), "sort": "high"},
362
+ }
363
+ run_pipeline(config, inputs)
364
+
365
+ res = flex.plot_half_max_explainer(k0=10, crossing="last", sort=False)
366
+
367
+ assert all(r["crossing"] == "last" and r["k0"] == 10 for r in res.values())
368
+
369
+
300
370
  def test_fraction_in_scores_and_plots(config):
301
371
  inputs = {
302
372
  "clean": {"path": make_dataset(seed=0), "sort": "high"},
@@ -326,8 +396,8 @@ def test_max_rank_takes_nth_highest_precision():
326
396
  k = np.arange(1, 201)
327
397
  p = k / (np.array(ranks) + 0)
328
398
 
329
- plain = half_max_auc(labels)
330
- third = half_max_auc(labels, max_rank=3)
399
+ plain = half_max_auc(labels, k0=1)
400
+ third = half_max_auc(labels, k0=1, max_rank=3)
331
401
 
332
402
  assert plain["p_max"] == 1.0
333
403
  assert third["p_max"] == pytest.approx(np.sort(p)[-3])
@@ -1247,7 +1247,7 @@ wheels = [
1247
1247
 
1248
1248
  [[package]]
1249
1249
  name = "pflex"
1250
- version = "2.0.0"
1250
+ version = "2.1.0"
1251
1251
  source = { editable = "." }
1252
1252
  dependencies = [
1253
1253
  { name = "art" },
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes