own-baseline 0.2.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.
@@ -0,0 +1,103 @@
1
+ """
2
+ own-baseline — does a single-cell potency score add anything beyond the
3
+ low-order statistic it is closest to?
4
+
5
+ Two tests, in increasing strength:
6
+
7
+ run_own_baseline(adata, score, gt_ordinal)
8
+ The marginal gap. tau(score, ordinal) - tau(gene counts, ordinal).
9
+ One line, no residualization. Cheap, and weaker than it looks: a
10
+ score that is its primitive plus noise can show a positive gap.
11
+
12
+ conditional_skill_report(score, ordinal, primitives)
13
+ The test the paper reports. Rank-residualize the score on its own
14
+ primitive(s), then score the residual against the ordinal under two
15
+ weighting kernels with a bootstrap interval. Also returns the
16
+ marginal gap and a direction check, so the weaker number is visible
17
+ next to the stronger one.
18
+
19
+ Both are documented in own_baseline/own_baseline.py and
20
+ own_baseline/conditional_skill.py.
21
+
22
+ Layout:
23
+ own_baseline.py marginal gap + the Test-A error-model flavour
24
+ conditional_skill.py the track-2 conditional-skill estimator
25
+ potency_metrics.py the primitives, plus SR / CCAT / CytoTRACE reimpls
26
+ atlas_run/wdm_tau.py Kang wdm weighted-Kendall kernel (== R wdm::wdm)
27
+ paths.py where this repo reads and writes
28
+ synthetic.py synthetic generators for the self-tests
29
+ """
30
+ __version__ = "0.2.0"
31
+ # One place. The anonymised review copy blanks this line and nothing else.
32
+ __author__ = "Damir Iskakov"
33
+
34
+ from .own_baseline import (
35
+ ADDS_DELTA,
36
+ REDUCES_DELTA,
37
+ VERDICT_ADDS,
38
+ VERDICT_INCONCLUSIVE,
39
+ VERDICT_REDUCES,
40
+ VERDICT_UNDEFINED,
41
+ nnz_per_cell,
42
+ own_entropy_baseline,
43
+ run_own_baseline,
44
+ score_vs_gt_tau,
45
+ test_A,
46
+ transfer_auc,
47
+ )
48
+ from .conditional_skill import (
49
+ align,
50
+ conditional_skill_report,
51
+ kang_taub,
52
+ rank_resid_multi,
53
+ scipy_wtau,
54
+ )
55
+ from .potency_metrics import (
56
+ build_ppi_adjacency,
57
+ ccat,
58
+ compute_all_metrics,
59
+ cytotrace_proxy,
60
+ load_string_ppi,
61
+ scaffold_null,
62
+ scent_sr,
63
+ stemid_entropy,
64
+ )
65
+ from .paths import data_root, repo_root, scratch_root
66
+
67
+ __all__ = [
68
+ "__version__",
69
+ "__author__",
70
+ # marginal gap
71
+ "run_own_baseline",
72
+ "nnz_per_cell",
73
+ "score_vs_gt_tau",
74
+ "REDUCES_DELTA",
75
+ "ADDS_DELTA",
76
+ "VERDICT_REDUCES",
77
+ "VERDICT_INCONCLUSIVE",
78
+ "VERDICT_ADDS",
79
+ "VERDICT_UNDEFINED",
80
+ # conditional skill
81
+ "conditional_skill_report",
82
+ "rank_resid_multi",
83
+ "align",
84
+ "scipy_wtau",
85
+ "kang_taub",
86
+ # error-model flavour
87
+ "test_A",
88
+ "transfer_auc",
89
+ "own_entropy_baseline",
90
+ # primitives and scores
91
+ "stemid_entropy",
92
+ "cytotrace_proxy",
93
+ "scent_sr",
94
+ "ccat",
95
+ "load_string_ppi",
96
+ "build_ppi_adjacency",
97
+ "compute_all_metrics",
98
+ "scaffold_null",
99
+ # paths
100
+ "repo_root",
101
+ "data_root",
102
+ "scratch_root",
103
+ ]
@@ -0,0 +1,345 @@
1
+ """
2
+ wdm_tau.py
3
+ ==========
4
+ Efficient weighted Kendall tau-b implementation that emulates
5
+ R `wdm::wdm(x, y, method="kendall", weights=w)` — the exact protocol
6
+ Kang et al. 2025 (Nat Methods, doi:10.1038/s41592-025-02857-2) uses to
7
+ evaluate CytoTRACE 2 and 8 benchmarking methods.
8
+
9
+ Formula (weighted tau-b, per-observation weights):
10
+
11
+ Cw = sum_{i<j} w_i w_j [x_i<x_j][y_i<y_j] + [x_i>x_j][y_i>y_j] (concordant)
12
+ Dw = sum_{i<j} w_i w_j [x_i<x_j][y_i>y_j] + [x_i>x_j][y_i<y_j] (discordant)
13
+ Tx = sum_{i<j} w_i w_j [x_i==x_j] (x-ties)
14
+ Ty = sum_{i<j} w_i w_j [y_i==y_j] (y-ties)
15
+
16
+ numer = Cw - Dw
17
+ denom = sqrt( (Cw + Dw + Tx) * (Cw + Dw + Ty) )
18
+ tau_b = numer / denom
19
+
20
+ Algorithm: O(n^2) direct implementation, chunked to bound memory.
21
+
22
+ For n up to 30k this is 30k^2 = 9e8 pair operations. Naive: ~10s per score
23
+ if we chunk properly with numpy vector broadcast (2000-row chunks × 30k cols).
24
+
25
+ Reference: Vanderwerken et al. (2016); Nešlehová & Machler R:wdm package;
26
+ Newson (2002) Somers' D and weighted tau-b.
27
+
28
+ Validation: reproduces Kang Supplementary Table S12 relative-order tau
29
+ values to <0.02 absolute tolerance on 'Retinal neurons (10x)' (verified
30
+ 2026-07-17 in atlas_run/metric_compat_probe log).
31
+ """
32
+ from __future__ import annotations
33
+ import numpy as np
34
+
35
+
36
+ def wdm_tau_b(x, y, w, chunk: int = 1024) -> float:
37
+ """
38
+ Weighted Kendall tau-b (dense O(n^2)), matching R wdm::wdm.
39
+
40
+ x, y : 1D arrays of scores (numeric), same length.
41
+ w : 1D array of nonnegative per-observation weights.
42
+ chunk: row-chunk size for memory-bounded outer-product accumulation.
43
+
44
+ Returns tau_b in [-1, 1] or NaN if fewer than 3 usable observations.
45
+
46
+ Suitable for n <= ~5000 cells. For larger n, use wdm_tau_b_bit() below.
47
+ """
48
+ x = np.asarray(x, dtype=np.float64)
49
+ y = np.asarray(y, dtype=np.float64)
50
+ w = np.asarray(w, dtype=np.float64)
51
+ m = ~(np.isnan(x) | np.isnan(y)) & (w > 0)
52
+ x, y, w = x[m], y[m], w[m]
53
+ n = len(x)
54
+ if n < 3:
55
+ return float("nan")
56
+
57
+ # Full-sum accumulators (over all i != j pairs, then divide by 2)
58
+ num = 0.0 # sum_{i,j} w_i w_j * sign(x_i-x_j) * sign(y_i-y_j)
59
+ T_x = 0.0 # sum_{i,j} w_i w_j * [sign(x_i-x_j) != 0]
60
+ T_y = 0.0 # sum_{i,j} w_i w_j * [sign(y_i-y_j) != 0]
61
+
62
+ for i0 in range(0, n, chunk):
63
+ i1 = min(i0 + chunk, n)
64
+ xi = x[i0:i1, None]
65
+ yi = y[i0:i1, None]
66
+ wi = w[i0:i1, None]
67
+ dx = np.sign(xi - x[None, :]).astype(np.float64) # (c, n)
68
+ dy = np.sign(yi - y[None, :]).astype(np.float64) # (c, n)
69
+ ww = wi * w[None, :] # (c, n)
70
+ num += float((ww * dx * dy).sum())
71
+ T_x += float((ww * (dx != 0)).sum())
72
+ T_y += float((ww * (dy != 0)).sum())
73
+
74
+ # These sums double-count (i,j) and (j,i); divide by 2 for i<j
75
+ num /= 2.0
76
+ T_x /= 2.0
77
+ T_y /= 2.0
78
+
79
+ denom = np.sqrt(T_x * T_y)
80
+ if denom <= 0:
81
+ return float("nan")
82
+ return float(num / denom)
83
+
84
+
85
+ class _BIT:
86
+ """Fenwick tree over floats for weighted prefix sums."""
87
+ __slots__ = ("n", "t")
88
+
89
+ def __init__(self, n):
90
+ self.n = n
91
+ self.t = np.zeros(n + 1, dtype=np.float64)
92
+
93
+ def update(self, i, v):
94
+ i += 1
95
+ while i <= self.n:
96
+ self.t[i] += v
97
+ i += i & (-i)
98
+
99
+ def prefix(self, i):
100
+ """Sum of positions [0..i]."""
101
+ i += 1
102
+ s = 0.0
103
+ while i > 0:
104
+ s += self.t[i]
105
+ i -= i & (-i)
106
+ return s
107
+
108
+ def total(self):
109
+ return self.prefix(self.n - 1)
110
+
111
+
112
+ def wdm_tau_b_bit(x, y, w) -> float:
113
+ """
114
+ Weighted Kendall tau-b via Fenwick tree — O(n log n) — matching R wdm::wdm.
115
+
116
+ Uses the sort-by-x, count-concordant/discordant/ties-in-y-via-BIT algorithm,
117
+ generalized with per-observation weights on the accumulators.
118
+
119
+ Correctness: identical to wdm_tau_b() for the same inputs (validated in
120
+ __main__ self-test).
121
+ """
122
+ x = np.asarray(x, dtype=np.float64)
123
+ y = np.asarray(y, dtype=np.float64)
124
+ w = np.asarray(w, dtype=np.float64)
125
+ m = ~(np.isnan(x) | np.isnan(y)) & (w > 0)
126
+ x, y, w = x[m], y[m], w[m]
127
+ n = len(x)
128
+ if n < 3:
129
+ return float("nan")
130
+
131
+ # Sort by x (stable sort so equal x values retain order)
132
+ ord_x = np.argsort(x, kind="stable")
133
+ x = x[ord_x]; y = y[ord_x]; w = w[ord_x]
134
+
135
+ # Discretize y to ranks (with ties)
136
+ uniq_y, y_idx = np.unique(y, return_inverse=True)
137
+ K = len(uniq_y)
138
+
139
+ # BITs on y-ranks:
140
+ # bit_w : sum of weights of already-seen cells at y-rank
141
+ # bit_wy : (not needed for tau-b — but we do need x-tie handling)
142
+ bit_w = _BIT(K)
143
+ bit_w_by_y_tie_group = None # not needed; y ties handled inline
144
+
145
+ # Aggregate: iterate cells in x-ascending order. For each incoming cell i,
146
+ # partition already-seen cells j (j has x_j <= x_i) into:
147
+ # - x_j < x_i (strict): call these "prior" pairs
148
+ # - x_j == x_i (tie on x): call these "x-tie" pairs; contribute to T_x
149
+ # For prior pairs, further partition by y_j vs y_i:
150
+ # - y_j < y_i : concordant
151
+ # - y_j > y_i : discordant
152
+ # - y_j == y_i: y-tie (contribute to T_y, not to num)
153
+ #
154
+ # We process x-groups in ascending-x order.
155
+
156
+ Cw = 0.0 # concordant weight
157
+ Dw = 0.0 # discordant weight
158
+ Txy = 0.0 # x-tied pairs
159
+ Ty_only = 0.0 # y-tied pairs (where x is untied)
160
+
161
+ # Group indices by equal x values (stable-sorted)
162
+ i = 0
163
+ prior_total_w = 0.0
164
+ while i < n:
165
+ j = i
166
+ # find end of x-tie group (all cells with x == x[i])
167
+ while j < n and x[j] == x[i]:
168
+ j += 1
169
+ # Pairs *within* the current x-tie group: both x-tied.
170
+ # For each pair (a, b) in group with a != b: contributes to T_x (untied? no — tied on x)
171
+ # Weighted count of such pairs = 0.5 * ( (sum w_grp)^2 - sum w_grp^2 )
172
+ grp_w = w[i:j]
173
+ gW = grp_w.sum()
174
+ gW2 = (grp_w * grp_w).sum()
175
+ # weighted pairs within group where x_i==x_j:
176
+ # partition by y:
177
+ for a in range(i, j):
178
+ ya = y_idx[a]; wa = w[a]
179
+ # look at other cells in group b != a
180
+ # split by y_b vs y_a:
181
+ # but this is O(group^2). For small groups this is fine.
182
+ pass
183
+ # Simpler: process the whole group in one shot using BIT-like sub-accumulator
184
+ # For x-tie pairs, we don't care about C/D distinction; only whether y is tied too.
185
+ # y-tie within group:
186
+ # pairs where y_a == y_b (both in group): contribute to (T_x AND T_y)? Actually
187
+ # pairs tied in both x and y are counted in both T_x and T_y (in tau-b denominator).
188
+ # So we just need total-pair-weight, plus y-tie-only-in-group.
189
+ # Total unordered pairs in group = 0.5 * (gW^2 - gW2)
190
+ # Of those, y-tie pairs (where y_a == y_b in group):
191
+ # aggregate by y within group:
192
+ y_in_grp = y_idx[i:j]
193
+ # sort by y
194
+ ord_y = np.argsort(y_in_grp, kind="stable")
195
+ yg = y_in_grp[ord_y]
196
+ wg = grp_w[ord_y]
197
+ yt = 0.0
198
+ k0 = 0
199
+ while k0 < len(yg):
200
+ k1 = k0
201
+ while k1 < len(yg) and yg[k1] == yg[k0]:
202
+ k1 += 1
203
+ sub = wg[k0:k1].sum()
204
+ sub2 = (wg[k0:k1] * wg[k0:k1]).sum()
205
+ yt += 0.5 * (sub * sub - sub2) # y-tie pairs within group
206
+ k0 = k1
207
+ # Contribution:
208
+ # Every within-group pair has x tied -> T_x += all
209
+ Txy_group_pairs = 0.5 * (gW * gW - gW2)
210
+ Txy += Txy_group_pairs
211
+ # Every y-tie pair within group also contributes to T_y
212
+ Ty_only += yt
213
+
214
+ # Now count pairs between group and *prior* cells (i.e., cells k < i with x_k < x_i).
215
+ # BIT holds prior cells' weights indexed by y-rank.
216
+ prior_W = prior_total_w
217
+ # For each cell 'a' in group:
218
+ # concordant_a = sum_{k prior} w_k * [y_k < y_a] * w_a
219
+ # discordant_a = sum_{k prior} w_k * [y_k > y_a] * w_a
220
+ # y_tie_a = sum_{k prior} w_k * [y_k == y_a] * w_a
221
+ # sum of concord + discord + y_tie = prior_W * w_a
222
+ # To get y_tie_a, we need weight of prior cells at exactly y_idx[a]:
223
+ # BIT does prefix sums; we can query prefix(y-1) and prefix(y), diff = at y.
224
+ for a in range(i, j):
225
+ ya = y_idx[a]; wa = w[a]
226
+ below = bit_w.prefix(ya - 1) if ya > 0 else 0.0
227
+ at_and_below = bit_w.prefix(ya)
228
+ at = at_and_below - below
229
+ above = prior_W - at_and_below
230
+ Cw += wa * below
231
+ Dw += wa * above
232
+ Ty_only += wa * at
233
+ # Now add cells of this group to the BIT (they become prior for next groups)
234
+ for a in range(i, j):
235
+ bit_w.update(y_idx[a], w[a])
236
+ prior_total_w += gW
237
+ i = j
238
+
239
+ # tau-b numerator: Cw - Dw
240
+ # tau-b denominator: sqrt( (Cw + Dw + Ty_only) * (Cw + Dw + Txy) )
241
+ # NOTE: our T_x/T_y here are pair-weights not counts of ties;
242
+ # * pairs where x is tied but y untied = Txy_x_only
243
+ # * pairs where y is tied but x untied = Ty_only
244
+ # * pairs tied in both = Txy_both (counted inside Txy_group_pairs)
245
+ # tau-b (Kendall):
246
+ # n_x = # pairs untied in x = Cw + Dw + Ty_only
247
+ # n_y = # pairs untied in y = Cw + Dw + Txy - both (but Txy already includes both)
248
+ # Actually the standard tau-b definition:
249
+ # n_0 = total pairs
250
+ # n_1 = sum over groups of x-ties: 0.5 g(g-1) = Txy_group_pairs_summed (weighted here)
251
+ # n_2 = sum over groups of y-ties: 0.5 h(h-1) = Ty_only_summed + within-x-group y-ties
252
+ # tau_b = (C - D) / sqrt( (n_0 - n_1)(n_0 - n_2) )
253
+ # In our accounting:
254
+ # n_1 = Txy (all pairs tied on x, including double-tied)
255
+ # n_2 = (Ty_only accumulated) which already includes within-x-group y-ties
256
+ n_0 = 0.5 * (w.sum() ** 2 - (w * w).sum())
257
+ n_1 = Txy
258
+ n_2 = Ty_only
259
+ denom = np.sqrt((n_0 - n_1) * (n_0 - n_2))
260
+ if denom <= 0:
261
+ return float("nan")
262
+ return float((Cw - Dw) / denom)
263
+
264
+
265
+ def kang_absolute_weights(std_phenotype, potency_level):
266
+ """
267
+ Kang S5 'Absolute order' per-cell weight (broad/granular potency ordinal target).
268
+
269
+ 'First balanced by number of cells per dataset assigned to a given phenotype,
270
+ then balanced across phenotypes within a given broad/granular potency level'
271
+
272
+ weight_i = 1 / ( n_cells_in_std_phenotype_i * n_std_phenotypes_at_potency_level_i )
273
+
274
+ Note: Kang's exact spec balances by ORIGINAL author-supplied phenotype (S3 col E) first,
275
+ then by STANDARDIZED phenotype (S3 col D). Because S11 gives only standardized phenotype
276
+ per cell, this implementation approximates by using standardized phenotype for both nesting
277
+ levels. Empirical validation against Kang S12 shows <0.02 absolute error on the tested
278
+ dataset (Retinal neurons 10x). Report this approximation as such.
279
+ """
280
+ import pandas as pd
281
+ ph = pd.Series(std_phenotype)
282
+ lv = pd.Series(potency_level)
283
+ ph_count = ph.value_counts().to_dict()
284
+ lv_ph = ph.groupby(lv).nunique().to_dict()
285
+ n = len(ph)
286
+ w = np.zeros(n)
287
+ for i in range(n):
288
+ p = ph.iloc[i]
289
+ l = lv.iloc[i]
290
+ if pd.isna(l) or pd.isna(p):
291
+ w[i] = 0.0
292
+ else:
293
+ w[i] = 1.0 / (ph_count[p] * lv_ph[l])
294
+ return w
295
+
296
+
297
+ if __name__ == "__main__":
298
+ from scipy.stats import kendalltau
299
+
300
+ # Self-test 1: uniform weights + continuous data (no ties)
301
+ rng = np.random.default_rng(0)
302
+ n = 200
303
+ x = rng.standard_normal(n)
304
+ y = x + 0.5 * rng.standard_normal(n)
305
+ w = np.ones(n)
306
+ t_wdm = wdm_tau_b(x, y, w)
307
+ t_bit = wdm_tau_b_bit(x, y, w)
308
+ t_ref = kendalltau(x, y).statistic
309
+ print(f"Self-test 1: uniform weights, no ties (n={n})")
310
+ print(f" wdm_tau_b = {t_wdm:+.6f}")
311
+ print(f" wdm_tau_b_bit = {t_bit:+.6f}")
312
+ print(f" kendalltau = {t_ref:+.6f}")
313
+ assert abs(t_wdm - t_ref) < 1e-9
314
+ assert abs(t_bit - t_ref) < 1e-9
315
+ print(" OK — dense & BIT versions both equal kendalltau.\n")
316
+
317
+ # Self-test 2: heavy y-ties (ordinal-target case, mimics broad potency GT)
318
+ n = 500
319
+ x = rng.standard_normal(n)
320
+ y = rng.integers(0, 4, n).astype(float) # 4 categories -> heavy ties
321
+ w = rng.uniform(0.1, 2.0, n)
322
+ t_wdm = wdm_tau_b(x, y, w)
323
+ t_bit = wdm_tau_b_bit(x, y, w)
324
+ print(f"Self-test 2: random weights + heavy y-ties (n={n})")
325
+ print(f" wdm_tau_b = {t_wdm:+.6f}")
326
+ print(f" wdm_tau_b_bit = {t_bit:+.6f}")
327
+ print(f" |diff| = {abs(t_wdm - t_bit):.2e}")
328
+ assert abs(t_wdm - t_bit) < 1e-9, "dense and BIT must agree"
329
+ print(" OK — dense & BIT agree under weights + y-ties.\n")
330
+
331
+ # Self-test 3: heavy x-ties AND heavy y-ties
332
+ n = 400
333
+ x = rng.integers(0, 6, n).astype(float) # 6 x-categories
334
+ y = rng.integers(0, 4, n).astype(float) # 4 y-categories
335
+ w = rng.uniform(0.1, 2.0, n)
336
+ t_wdm = wdm_tau_b(x, y, w)
337
+ t_bit = wdm_tau_b_bit(x, y, w)
338
+ print(f"Self-test 3: random weights + heavy x&y-ties (n={n})")
339
+ print(f" wdm_tau_b = {t_wdm:+.6f}")
340
+ print(f" wdm_tau_b_bit = {t_bit:+.6f}")
341
+ print(f" |diff| = {abs(t_wdm - t_bit):.2e}")
342
+ assert abs(t_wdm - t_bit) < 1e-9, "dense and BIT must agree with both-ties"
343
+ print(" OK — dense & BIT agree under weights + both-side ties.\n")
344
+
345
+ print("All wdm_tau self-tests passed.")