Repository navigation
feat!: choose the mAP null, with label permutation as the default - #156
Conversation
_create_neg_query_solver looked up each query profile in the sorted array of profiles that have negatives with np.searchsorted. A profile with positives but no negatives is absent from that array, so searchsorted returned its insertion point: the profile silently got the next profile's negatives, or raised IndexError when it sorted after every profile with negatives. Give such profiles zero negatives instead. Their AP, normalized AP and pair counts now match copairs.map.average_precision on the same data (AP 1.0, n_total_pairs == n_pos_pairs). Profiles that have negatives are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
get_null_dists draws configuration i from seeds[i], which depends on
the configuration's position in the run, but the cache file name held
only (num_pos, total). A cached null thus depended on whichever run
wrote it first, so the same seed and inputs gave different p-values
depending on cache history.
Add the per-configuration seed to the file name
(n{total}_k{num_pos}_s{seed}.npy) and route get_null_dists through
null_dist_cached so the two share one cache layout. A cached run now
returns exactly what an uncached run returns. Uncached outputs are
unchanged: same seeds, same draws, bitwise identical to 0.5.5.
Cache files written under the old names are no longer read; they are
regenerated under the new names on first use.
Alternative, not taken here: seed each configuration from
(seed, num_pos, total), which would make a configuration's null
independent of the other configurations in a run, but changes every
p-value relative to 0.5.5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
When every AP is NaN or has no positive pairs, mean_average_precision and mean_average_precision_hierarchical raised ZeroDivisionError: parallel_map sized a thread pool of zero and divided by it. The same crash hit compute.p_values with no scores. parallel_map now returns early for no items. The FDR step then failed too, because statsmodels < 0.15 (0.14.5 is locked) divides by zero in multipletests for an empty array. Both FDR corrections now return empty corrected p-values for no tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
mean_average_precision_hierarchical validated hierarchical_by only inside apply_hierarchical_fdr_correction, after get_map_pvalue had generated the full null, so a wrong argument cost a full null run before the error. The check is now check_hierarchical_by, called first and by apply_hierarchical_fdr_correction. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
The previous fix kept the sparse lookup (np.unique + searchsorted) and masked the insertion points of profiles without negatives. Count negatives per profile with np.bincount instead, so a profile without negatives reads a count of 0 directly: no searchsorted, clamp or mask, and no reliance on the caller having rejected an empty negative set. Outputs are identical to the masked lookup on 300 random multilabel inputs (19,108 rows). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
The two get_null_dists tests repeated the mAP-level test one layer down; the cold-vs-warm one also passed before the fix, so it tested nothing new. Keep the integration test, build its frame as a literal, and shorten the comment on the cache key. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
The stage-2 call in apply_hierarchical_fdr_correction still called statsmodels directly. It never sees an empty group, but one wrapper for all three calls keeps a later change to the guard from missing it. Also simplify the empty-input tests: parametrize the invalid AP column directly, and drop the progress_bar parametrization of the empty get_null_dists test, which returns before the progress bar branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
The new before-p-values test repeated the two existing validation tests with the same arguments and messages. Keep one parametrized test, and make get_map_pvalue fail the test if validation lets it run, instead of counting calls to the real function. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
With seed=None, get_null_dists drew random per-configuration seeds and cached under them, so every run wrote files no later run could read. Before the cache key carried the seed, it instead reused the first unseeded run's nulls in every later run, so seed=None was not random after the first call. Unseeded nulls are now fresh draws that never touch the cache, as null_dist_cached already does for seed=None. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
os.cpu_count() returns None when the count is undetermined, which made parallel_map and silent_thread_map raise TypeError. Fall back to one CPU, as ThreadPoolExecutor's own default does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
For no tests the guard returned 0.0 for the Sidak and Bonferroni alphas, values statsmodels never produces. Return NaN, as statsmodels 0.15 does for an empty input, and annotate the helper. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
Path.home() ignores HOME on Windows. Patching Path.home keeps the default cache directory out of the real home on every platform. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
get_null_dists drew configuration i's seed from a master RNG by its position in the run, so a group's mAP p-value changed when other groups were added to or removed from the call. Keying the cache by that seed made cached runs agree with uncached ones, but the cache then hit only when a run repeated exactly the same configurations. Seed each configuration from SeedSequence([seed, num_pos, total]). A group's p-value no longer depends on the other groups, and the cache is shared across runs again. File names keep the configuration's seed, so nulls cached by copairs <= 0.5.5 under position seeds are never read. Every uncached null changes relative to 0.5.5: same distribution, different draws, so p-values agree within Monte Carlo error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
The joint and label-permutation mAP nulls draw from Philox4x32-10, so every draw is a pure function of the seed and a counter: a group's null does not depend on which other groups are computed or in which order, and a compiled kernel can reproduce the NumPy draws exactly. The module is pure NumPy (taken from cytomining#150). common.py holds what the nulls share and needs no optional dependency: tie thresholds for ">=" p-values, seed resolution, null-size checks, sample chunking and the progress bar. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The null of a group's mAP was built by drawing one AP sample per distinct (n_pos_pairs, n_total_pairs) configuration and averaging the rows its members point at. Members with equal counts point at the same row, so the "average" was one draw copied n times and the null never narrowed as replicates were added: the p-value of a four-replicate mAP was the p-value of a single AP at that value, and it changed when one member's pair count differed by one. The unit of randomness moves from the rank list to the pair. Every pair gets one random number; a positive pair inside the group puts the same number into both members' lists; each member's AP falls out of its own sorted list. Negatives are placed by one multinomial draw per member, so the cost does not depend on how many a member ranks. Each member's marginal is unchanged, so per-profile AP p-values are untouched. get_map_pvalue infers the pairs for replicate groups (n_pos_pairs equal to the group size minus one) and takes an explicit pos_pairs array otherwise. Groups it cannot resolve keep the previous null and warn. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
mean_average_precision_hierarchical calls get_map_pvalue too, so it takes the same optional pos_pairs array and passes it through. Document the argument on both public entry points. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
mean_average_precision, its hierarchical variant and get_map_pvalue take null="joint" (the default, cytomining#151's null) or null="copied", the null of copairs <= 0.5.5 with cytomining#153's per-configuration seeds and cache. A study that must stay comparable with earlier results can now ask for the copied null by name instead of relying on the fallback for groups whose positives are not their other members. Both paths share one helper for the copied null, which samples only the configurations its groups use; with seeds keyed by configuration, those nulls are the ones a run over every configuration would draw. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The copied null counted null mAPs strictly above the observed one, so a group whose mAP equals an atom of the null got too small a p-value: two perfect replicates among 100 profiles got 1 / (null_size + 1) instead of about 1/100. AP p-values already count ties (searchsorted, side="left"), and the paper defines p as the share of null values >= the observed. Both nulls now count null values >= the score minus a tolerance from nulls.tie_thresholds. The joint null's fixed 1e-9 missed float32 scores, which round up to 1e-7 away from the atom they come from. The copied null's samples are float32, so its tolerance covers float32 rounding, and its member nulls are averaged in float64. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
cytomining#151's sampler draws from np.random.default_rng, so a compiled kernel cannot reproduce its samples. nulls/joint.py samples the same law (KS against compute.random_map, which stays as the reference) from Philox counters: sample j of a group is a pure function of (seed, signature, j), whatever the chunking or the other groups. Negatives between consecutive positives are binomial draws (inversion or BTRS), so a sample costs the same however many negatives a member ranks. A sample is defined by plain-Python scalar functions built by _make_sampler(philox, uniform, jit=...), so a later Numba backend can compile the same source; joint_nulls runs the same operations vectorized over samples in NumPy, and the tests check the two agree bit for bit. Logarithms and integer powers come from a fixed series and repeated squaring instead of the math library: on this machine np.log and math.log differ in the last bit for 32 of 30,005 inputs, which would let a BTRS accept/reject decision, and with it a sample, depend on the implementation. Replicate groups that list the same members in another order share a signature (canonical_signature), and with it one null. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
Without pos_pairs, the joint null inferred edges only for replicate groups and sent every other group to the copied null with a warning to pass pos_pairs. A group of one profile has no pairs inside it whatever its positives are, so its edges are empty: it now gets the joint sampler's single-AP null, as it does with explicit pos_pairs, and no warning. Designs with one profile per guide and positives by gene hit this. From cytomining#150 (0838e48). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
With chunk=0 the sampling loop drew empty batches and never advanced, so the call hung. random_map stays as the NumPy reference that the joint null is tested against. Flagged by Copilot on cytomining#151; from cytomining#150 (4c21ffd). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
A null that re-ranks profiles needs the pairs and the similarity the APs
came from, which an AP frame does not hold. average_precision now builds
a RankPairs (positive and negative pairs, indexing the frame's rows, and
a pairs -> similarities function of the call's features and distance),
returns it with return_pairs=True and attaches it to the frame in
attrs["copairs_pairs"], so the usual calls need not pass it along.
pandas deep-copies attrs on every operation and writes them to parquet as
JSON, so the attachment is a handle that copies to itself, serializes as
{} and pickles empty: copies and filters keep the pairs cheaply, saved
and reloaded frames have none, and frames concatenated from different AP
calls drop them, since handles are equal only to themselves.
The mAP functions take pairs=; the joint null uses its positive pairs.
It ignores attached pairs and keeps inferring edges, so frames that went
through reset_index do not get misaligned pairs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
cytomining#151 documented pos_pairs as find_pairs(meta, ...) on the meta given to average_precision. find_pairs returns meta's index labels, while average_precision's frame (and so ap_scores) is indexed by position, so a meta with a gapped index (rows filtered beforehand) silently gave the joint null wrong edges. Each profile's positive count in pos_pairs must now equal n_pos_pairs, and the docstring points to average_precision(..., return_pairs=True), whose RankPairs can also be passed whole as pairs=. From cytomining#150 (3db07b6). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
null="permutation" tests the paper's null hypothesis directly: within each block of members ranked against the same references (e.g. a plate's replicates and controls), any of the block's profiles could have carried the group's label. A draw relabels profiles and recomputes the group's mAP from the observed similarities with the same pair rules, so whatever dependence the data has between rank lists stays in the null, which the joint and copied nulls assume away. It needs the pairs the APs came from: pairs=, or the ones average_precision attaches to its frame. Frames without them raise and point to pairs=, null="joint" or null="copied". Groups whose positives are not their other members, or whose members rank overlapping but different references, raise too, as do pairs that do not match the AP table (a recomputed observed mAP off by more than 1e-6). Draw j of a group is a pure function of (seed, members, j) on a Philox stream. It is defined by plain-Python scalar functions built by _make_kernels(philox, uniform, jit=...), so a later Numba backend can compile the same source; _draws_np and _group_maps_np run the same integer and float operations vectorized over draws, bit for bit (tested on four layouts, with tied and NaN similarities, through rank tables and binary searches). Their draws also equal cytomining#150's Numba kernels' on ten layouts of 5,000 draws each. This port is single-label and has no early stopping; both come with multilabel support later. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The vectorized group mAP spent most of its time in two lookups: a Python-level binary search over each code's sorted block-member keys, and a three-way gather of keys and ranks with nested np.where. Count the block-member keys with one np.searchsorted over (code << 32 | key) words, which gives the same counts, and gather keys and ranks from one (code, code) table when it has at most 2**20 entries; larger layouts keep the three-way gather. On 10 hub groups of 20 replicates among 100 controls at null_size 10000, the null took 4.0 s before and 2.5 s after. The parity test now covers the full-table, rank-table and search paths, each draw-for-draw against the scalar functions. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The joint null treats similarities outside a group's positive pairs as independent, so on real profiles, where members share references and some profiles are close to many others, it can give too small p-values for groups of many replicates. The permutation null relabels the observed profiles instead and keeps their dependence, so make it the default of mean_average_precision, its hierarchical variant and get_map_pvalue. AP frames carry their pairs, so the default needs no extra argument; frames that lost them (built, loaded, pickled, concatenated from several AP calls, or multilabel) raise and point to pairs=, null="joint" or null="copied". Tests on hand-built AP tables now name null="copied" (or "joint" where they test it), and cytomining#150's tests for the default on attached pairs, frames without pairs and reset_index are ported. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The default mAP null changes to the permutation null, which needs the pairs AP frames carry, so users need to know which null to pick, what each assumes, when frames lose their pairs, and that null="copied" gives results comparable to copairs 0.5.5 (within Monte Carlo error, with ties now counted >=). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The tie tolerance follows the scores' dtype, so float32 APs tie with the null atoms they round from. pandas 2 averages a float32 AP column to float32, but pandas 3 averages it to float64, which gave the mAP the float64 tolerance: under pandas 3.1, a group of float32 APs of 1/3 with one positive among 3 got p = 0.79 instead of 1 under the joint null (test_float32_scores_count_ties[joint]). Cast the group means to the AP column's dtype before the nulls compare them; the reported mAP column is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
mean_average_precision_hierarchical takes null= and passes it to the p-values, but no test exercised it: each null now must give the flat entry point's p-values there, the default must be the permutation null, and an unknown null must raise. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
_cdist_diag_sim took the diagonal of the full batch-by-batch cdist matrix: at the default 20,000 pairs per batch that is a 3.2 GB float64 temporary and 4e8 distances for 2e4 values. The permutation null now recomputes similarities over every pool's pairs, outside the pool memory budget, so concurrent pool builds with a SciPy metric could run out of memory (reported by Copilot on cytomining#156). Each pair's distance is now taken from cdist calls of 64 rows, which give the same values bitwise for every SciPy metric except seuclidean and mahalanobis (measured on random data); those two estimate their scale from the batch and keep one call, so APs stay as on main. The AP stage gets the same bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
pd.concat keeps a frame's attached pairs when its inputs share them, so concatenating copies or overlapping subsets of one AP frame repeats row numbers. The joint null then mapped profiles to their last copy and treated the copies as independent members, which narrows its null; the permutation null raised only later, from its layout check. _check_row_index now rejects such an index for both (reported by Copilot on cytomining#156). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
The batch-dependent branch of _cdist_diag_sim passes metric= by keyword, which the recorder in 6b8d8a8's test rejected. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
|
Copilot's review of a9d1ce6 also listed a "previously missed" issue outside any thread: duplicate profile indices under |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Alex, thanks for the implementation and fixes. In the end I decided that legacy compatibility is too much work and maintenance, and I'd rather create a new version 0.6.0 that doesn't claim the same null/baselines.
Implemented
I’ve completed the follow-up changes in #156 and synchronized #157:
- Removed automatic copied fallback and count-only graph inference. Multi-member joint tests require actual positive pairs; explicit pairs override attachments.
- Replaced the pair dataclasses with plain dictionaries. Kept the existing pair/count/layout checks and the small pandas attachment wrapper for shared copies and results-only persistence.
- Removed the positive-only
pos_diffbyguard. Permutations preserve the original positive graph, including non-complete graphs. - Added
seed=0defaults, per-call resource controls, and scores-only zero draws with NaN statistical results and unknown significance. Fixed missing-aware correction, nullable/Arrow counts and early argument validation. - Updated the breaking 0.6.0 migration guidance and examples, and consolidated redundant tests while retaining independent statistical checks.
Scope and limitations
I chose to exclude added provenance and original-membership tracking from both PRs. For permutation testing, callers must preserve original AP indices, correct pairs and complete tested groups/labels; structural checks cannot detect every mismatch or omission. Shared backing data must remain unchanged between AP calculation and testing.
#157 integrates Alex’s component-based multilabel model with the same seed, zero-draw and resource contracts. Adaptive stopping, acceleration, new caches and richer persistence remain separate. The models’ exchangeability assumptions still require justification for the data being tested.
Validation and merge coordination
At #156 b94d01a and #157 c754bae, the full Python 3.11 suites pass 332 and 388 tests, respectively. All 10 CI checks pass for each PR, including Python 3.11–3.14, pandas compatibility, Ruff and docs.
Final sign-off and marking #157 ready remain. Merge #156 first; if squashed, reconcile #157 with main and rerun CI. Release 0.6.0 only after both PRs land and combined checks pass.
| PAIRS_ATTR = "copairs_pairs" | ||
|
|
||
|
|
||
| class _AttachedPairs(dict): |
There was a problem hiding this comment.
I don't see the benefit of creating dataclasses with OOP/states when copairs is largely functional. My preference is to avoid OOP and all the cruft that comes with it (we still want to keep the library as readable as possible).
| batch_size: int = 20000, | ||
| distance: str = "cosine", | ||
| progress_bar: bool = True, | ||
| return_pairs: bool = False, |
There was a problem hiding this comment.
I was gonna complain about how this changes the interface, but it's still a dataframe, just with one more column which we have done before in other software (forgot which one, but I think pycytominer). Not a fan of the design but I have no strong opinion.
This comment has been minimized.
This comment has been minimized.
|
Implementation, validation and remaining merge steps are consolidated in the updated review. |
* fix: give multilabel profiles without negatives no negatives
_create_neg_query_solver looked up each query profile in the sorted
array of profiles that have negatives with np.searchsorted. A profile
with positives but no negatives is absent from that array, so
searchsorted returned its insertion point: the profile silently got
the next profile's negatives, or raised IndexError when it sorted
after every profile with negatives.
Give such profiles zero negatives instead. Their AP, normalized AP and
pair counts now match copairs.map.average_precision on the same data
(AP 1.0, n_total_pairs == n_pos_pairs). Profiles that have negatives
are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: key cached null distributions by their seed
get_null_dists draws configuration i from seeds[i], which depends on
the configuration's position in the run, but the cache file name held
only (num_pos, total). A cached null thus depended on whichever run
wrote it first, so the same seed and inputs gave different p-values
depending on cache history.
Add the per-configuration seed to the file name
(n{total}_k{num_pos}_s{seed}.npy) and route get_null_dists through
null_dist_cached so the two share one cache layout. A cached run now
returns exactly what an uncached run returns. Uncached outputs are
unchanged: same seeds, same draws, bitwise identical to 0.5.5.
Cache files written under the old names are no longer read; they are
regenerated under the new names on first use.
Alternative, not taken here: seed each configuration from
(seed, num_pos, total), which would make a configuration's null
independent of the other configurations in a run, but changes every
p-value relative to 0.5.5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: return an empty mAP table when no AP scores are valid
When every AP is NaN or has no positive pairs, mean_average_precision
and mean_average_precision_hierarchical raised ZeroDivisionError:
parallel_map sized a thread pool of zero and divided by it. The same
crash hit compute.p_values with no scores. parallel_map now returns
early for no items.
The FDR step then failed too, because statsmodels < 0.15 (0.14.5 is
locked) divides by zero in multipletests for an empty array. Both FDR
corrections now return empty corrected p-values for no tests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: check hierarchical_by before computing mAP p-values
mean_average_precision_hierarchical validated hierarchical_by only
inside apply_hierarchical_fdr_correction, after get_map_pvalue had
generated the full null, so a wrong argument cost a full null run
before the error. The check is now check_hierarchical_by, called first
and by apply_hierarchical_fdr_correction.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* refactor: index multilabel negative counts by profile
The previous fix kept the sparse lookup (np.unique + searchsorted) and
masked the insertion points of profiles without negatives. Count
negatives per profile with np.bincount instead, so a profile without
negatives reads a count of 0 directly: no searchsorted, clamp or mask,
and no reliance on the caller having rejected an empty negative set.
Outputs are identical to the masked lookup on 300 random multilabel
inputs (19,108 rows).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* test: test the null cache key once, through mean_average_precision
The two get_null_dists tests repeated the mAP-level test one layer
down; the cold-vs-warm one also passed before the fix, so it tested
nothing new. Keep the integration test, build its frame as a literal,
and shorten the comment on the cache key.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* refactor: route every multipletests call through the empty-input guard
The stage-2 call in apply_hierarchical_fdr_correction still called
statsmodels directly. It never sees an empty group, but one wrapper
for all three calls keeps a later change to the guard from missing it.
Also simplify the empty-input tests: parametrize the invalid AP column
directly, and drop the progress_bar parametrization of the empty
get_null_dists test, which returns before the progress bar branch.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* test: fold the hierarchical_by validation tests into one
The new before-p-values test repeated the two existing validation
tests with the same arguments and messages. Keep one parametrized
test, and make get_map_pvalue fail the test if validation lets it run,
instead of counting calls to the real function.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: do not cache unseeded null distributions
With seed=None, get_null_dists drew random per-configuration seeds and
cached under them, so every run wrote files no later run could read.
Before the cache key carried the seed, it instead reused the first
unseeded run's nulls in every later run, so seed=None was not random
after the first call. Unseeded nulls are now fresh draws that never
touch the cache, as null_dist_cached already does for seed=None.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: use one CPU when os.cpu_count() cannot tell
os.cpu_count() returns None when the count is undetermined, which made
parallel_map and silent_thread_map raise TypeError. Fall back to one
CPU, as ThreadPoolExecutor's own default does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* refactor: return NaN alphas from the empty multipletests guard
For no tests the guard returned 0.0 for the Sidak and Bonferroni
alphas, values statsmodels never produces. Return NaN, as statsmodels
0.15 does for an empty input, and annotate the helper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* style: annotate check_hierarchical_by with list[str]
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* test: redirect Path.home, not HOME, in the empty p_values test
Path.home() ignores HOME on Windows. Patching Path.home keeps the
default cache directory out of the real home on every platform.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* fix: seed each null configuration by its values, not its position
get_null_dists drew configuration i's seed from a master RNG by its
position in the run, so a group's mAP p-value changed when other groups
were added to or removed from the call. Keying the cache by that seed
made cached runs agree with uncached ones, but the cache then hit only
when a run repeated exactly the same configurations.
Seed each configuration from SeedSequence([seed, num_pos, total]). A
group's p-value no longer depends on the other groups, and the cache is
shared across runs again. File names keep the configuration's seed, so
nulls cached by copairs <= 0.5.5 under position seeds are never read.
Every uncached null changes relative to 0.5.5: same distribution,
different draws, so p-values agree within Monte Carlo error.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz
* feat: add a counter-based random stream and shared null helpers
The joint and label-permutation mAP nulls draw from Philox4x32-10, so
every draw is a pure function of the seed and a counter: a group's null
does not depend on which other groups are computed or in which order,
and a compiled kernel can reproduce the NumPy draws exactly. The module
is pure NumPy (taken from #150).
common.py holds what the nulls share and needs no optional dependency:
tie thresholds for ">=" p-values, seed resolution, null-size checks,
sample chunking and the progress bar.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: sample the mAP null jointly over a group's members
The null of a group's mAP was built by drawing one AP sample per distinct
(n_pos_pairs, n_total_pairs) configuration and averaging the rows its
members point at. Members with equal counts point at the same row, so the
"average" was one draw copied n times and the null never narrowed as
replicates were added: the p-value of a four-replicate mAP was the p-value
of a single AP at that value, and it changed when one member's pair count
differed by one.
The unit of randomness moves from the rank list to the pair. Every pair gets
one random number; a positive pair inside the group puts the same number
into both members' lists; each member's AP falls out of its own sorted list.
Negatives are placed by one multinomial draw per member, so the cost does
not depend on how many a member ranks. Each member's marginal is unchanged,
so per-profile AP p-values are untouched.
get_map_pvalue infers the pairs for replicate groups (n_pos_pairs equal to
the group size minus one) and takes an explicit pos_pairs array otherwise.
Groups it cannot resolve keep the previous null and warn.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* feat: accept pos_pairs in the hierarchical mAP entry point
mean_average_precision_hierarchical calls get_map_pvalue too, so it takes
the same optional pos_pairs array and passes it through. Document the
argument on both public entry points.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* feat: choose the mAP null with null=
mean_average_precision, its hierarchical variant and get_map_pvalue take
null="joint" (the default, #151's null) or null="copied", the null of
copairs <= 0.5.5 with #153's per-configuration seeds and cache. A study
that must stay comparable with earlier results can now ask for the
copied null by name instead of relying on the fallback for groups whose
positives are not their other members.
Both paths share one helper for the copied null, which samples only the
configurations its groups use; with seeds keyed by configuration, those
nulls are the ones a run over every configuration would draw.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: count null mAPs tied with the observed mAP
The copied null counted null mAPs strictly above the observed one, so a
group whose mAP equals an atom of the null got too small a p-value: two
perfect replicates among 100 profiles got 1 / (null_size + 1) instead of
about 1/100. AP p-values already count ties (searchsorted, side="left"),
and the paper defines p as the share of null values >= the observed.
Both nulls now count null values >= the score minus a tolerance from
nulls.tie_thresholds. The joint null's fixed 1e-9 missed float32 scores,
which round up to 1e-7 away from the atom they come from. The copied
null's samples are float32, so its tolerance covers float32 rounding,
and its member nulls are averaged in float64.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: sample the joint mAP null from Philox streams
#151's sampler draws from np.random.default_rng, so a compiled kernel
cannot reproduce its samples. nulls/joint.py samples the same law (KS
against compute.random_map, which stays as the reference) from Philox
counters: sample j of a group is a pure function of (seed, signature, j),
whatever the chunking or the other groups. Negatives between consecutive
positives are binomial draws (inversion or BTRS), so a sample costs the
same however many negatives a member ranks.
A sample is defined by plain-Python scalar functions built by
_make_sampler(philox, uniform, jit=...), so a later Numba backend can
compile the same source; joint_nulls runs the same operations vectorized
over samples in NumPy, and the tests check the two agree bit for bit.
Logarithms and integer powers come from a fixed series and repeated
squaring instead of the math library: on this machine np.log and
math.log differ in the last bit for 32 of 30,005 inputs, which would let
a BTRS accept/reject decision, and with it a sample, depend on the
implementation.
Replicate groups that list the same members in another order share a
signature (canonical_signature), and with it one null.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: give one-profile groups their AP null under the joint null
Without pos_pairs, the joint null inferred edges only for replicate
groups and sent every other group to the copied null with a warning to
pass pos_pairs. A group of one profile has no pairs inside it whatever
its positives are, so its edges are empty: it now gets the joint
sampler's single-AP null, as it does with explicit pos_pairs, and no
warning. Designs with one profile per guide and positives by gene hit
this. From #150 (0838e48).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: reject a non-positive chunk in compute.random_map
With chunk=0 the sampling loop drew empty batches and never advanced, so
the call hung. random_map stays as the NumPy reference that the joint
null is tested against. Flagged by Copilot on #151; from #150 (4c21ffd).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: return and attach the pairs behind AP frames
A null that re-ranks profiles needs the pairs and the similarity the APs
came from, which an AP frame does not hold. average_precision now builds
a RankPairs (positive and negative pairs, indexing the frame's rows, and
a pairs -> similarities function of the call's features and distance),
returns it with return_pairs=True and attaches it to the frame in
attrs["copairs_pairs"], so the usual calls need not pass it along.
pandas deep-copies attrs on every operation and writes them to parquet as
JSON, so the attachment is a handle that copies to itself, serializes as
{} and pickles empty: copies and filters keep the pairs cheaply, saved
and reloaded frames have none, and frames concatenated from different AP
calls drop them, since handles are equal only to themselves.
The mAP functions take pairs=; the joint null uses its positive pairs.
It ignores attached pairs and keeps inferring edges, so frames that went
through reset_index do not get misaligned pairs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: reject pos_pairs that do not index ap_scores
#151 documented pos_pairs as find_pairs(meta, ...) on the meta given to
average_precision. find_pairs returns meta's index labels, while
average_precision's frame (and so ap_scores) is indexed by position, so
a meta with a gapped index (rows filtered beforehand) silently gave the
joint null wrong edges.
Each profile's positive count in pos_pairs must now equal n_pos_pairs,
and the docstring points to average_precision(..., return_pairs=True),
whose RankPairs can also be passed whole as pairs=. From #150 (3db07b6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: add the label-permutation mAP null
null="permutation" tests the paper's null hypothesis directly: within
each block of members ranked against the same references (e.g. a plate's
replicates and controls), any of the block's profiles could have carried
the group's label. A draw relabels profiles and recomputes the group's
mAP from the observed similarities with the same pair rules, so whatever
dependence the data has between rank lists stays in the null, which the
joint and copied nulls assume away.
It needs the pairs the APs came from: pairs=, or the ones
average_precision attaches to its frame. Frames without them raise and
point to pairs=, null="joint" or null="copied". Groups whose positives
are not their other members, or whose members rank overlapping but
different references, raise too, as do pairs that do not match the AP
table (a recomputed observed mAP off by more than 1e-6).
Draw j of a group is a pure function of (seed, members, j) on a Philox
stream. It is defined by plain-Python scalar functions built by
_make_kernels(philox, uniform, jit=...), so a later Numba backend can
compile the same source; _draws_np and _group_maps_np run the same
integer and float operations vectorized over draws, bit for bit (tested
on four layouts, with tied and NaN similarities, through rank tables and
binary searches). Their draws also equal #150's Numba kernels' on ten
layouts of 5,000 draws each. This port is single-label and has no early
stopping; both come with multilabel support later.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: speed up the NumPy permutation null's rank lookups
The vectorized group mAP spent most of its time in two lookups: a
Python-level binary search over each code's sorted block-member keys, and
a three-way gather of keys and ranks with nested np.where. Count the
block-member keys with one np.searchsorted over (code << 32 | key) words,
which gives the same counts, and gather keys and ranks from one
(code, code) table when it has at most 2**20 entries; larger layouts keep
the three-way gather. On 10 hub groups of 20 replicates among 100
controls at null_size 10000, the null took 4.0 s before and 2.5 s after.
The parity test now covers the full-table, rank-table and search paths,
each draw-for-draw against the scalar functions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat!: default to the permutation mAP null
The joint null treats similarities outside a group's positive pairs as
independent, so on real profiles, where members share references and some
profiles are close to many others, it can give too small p-values for
groups of many replicates. The permutation null relabels the observed
profiles instead and keeps their dependence, so make it the default of
mean_average_precision, its hierarchical variant and get_map_pvalue.
AP frames carry their pairs, so the default needs no extra argument;
frames that lost them (built, loaded, pickled, concatenated from several
AP calls, or multilabel) raise and point to pairs=, null="joint" or
null="copied". Tests on hand-built AP tables now name null="copied"
(or "joint" where they test it), and #150's tests for the default on
attached pairs, frames without pairs and reset_index are ported.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* docs: describe the mAP nulls in the README
The default mAP null changes to the permutation null, which needs the
pairs AP frames carry, so users need to know which null to pick, what
each assumes, when frames lose their pairs, and that null="copied"
gives results comparable to copairs 0.5.5 (within Monte Carlo error,
with ties now counted >=).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: keep the APs' dtype when counting mAP ties
The tie tolerance follows the scores' dtype, so float32 APs tie with
the null atoms they round from. pandas 2 averages a float32 AP column
to float32, but pandas 3 averages it to float64, which gave the mAP the
float64 tolerance: under pandas 3.1, a group of float32 APs of 1/3 with
one positive among 3 got p = 0.79 instead of 1 under the joint null
(test_float32_scores_count_ties[joint]). Cast the group means to the AP
column's dtype before the nulls compare them; the reported mAP column is
unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* test: check null= on the hierarchical mAP entry point
mean_average_precision_hierarchical takes null= and passes it to the
p-values, but no test exercised it: each null now must give the flat
entry point's p-values there, the default must be the permutation null,
and an unknown null must raise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* docs: run the example notebooks on the copied mAP null
The stored outputs of null_size, phenotypic_activity and
phenotypic_consistency were computed with copairs <= 0.5.5's copied
null. Under the new permutation default, null_size.ipynb would raise
(its APs come from a CSV, so no pairs are attached), and
phenotypic_consistency.ipynb would raise on multilabel APs until the
permutation null supports them. Passing null="copied" keeps the cells
runnable and consistent with the outputs they show.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: keep #151's random_map only as a test reference
compute.random_map has no caller in the library since the joint null
moved onto Philox streams: it served only as the distribution reference
of tests/test_nulls_joint.py. Move it there, with the explicit
simulation that validates it, and drop it from compute's public API.
The reference loses its chunking, blake2b seeding and input checks
(joint_plan validates signatures). Of its tests, the check against the
explicit simulation moves with it; the singleton, narrowing and moment
checks are dropped, since test_singleton_is_the_ap_null and
test_replicate_moments cover them for the joint null itself, and the
seeding and validation checks tested code that no longer exists
(test_stream_is_reproducible and test_plan_validates cover joint's).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: share the pairs-to-group-edges step between the mAP nulls
map._group_edges and permutation.group_layouts both reshaped pos_pairs,
mapped profiles to groups, checked each member's positive pairs against
n_pos_pairs and extracted the pairs inside each group, with two
different error messages. nulls.common.group_edges now does this once
(and flags groups with positives leaving them, which the permutation
null rejects), and check_pair_counts raises one message for positive and
negative pair counts. The permutation null's pair scan now handles only
the negatives, so it no longer hashes positive partner sets nobody read.
The joint null's signature, dedup and fallback plumbing moves from
get_map_pvalue into nulls.joint.group_signatures and group_pvalues, so
the joint branch of get_map_pvalue is one call plus the copied fallback,
like the other two nulls. P-values and draws are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: iterate the mAP nulls' chunks with nulls.common.chunks
joint_nulls, joint_pvalues, permutation_null, the pool's sorted rows and
_row_ranks each wrote their own start/size loop, and joint_pvalues
copied joint_nulls' per-signature draw loop. Use common.chunks
everywhere, and let joint_pvalues draw each chunk with joint_nulls.
The joint hit-count test now runs several chunks per signature, and the
permutation chunking test also shrinks the pool's pair and table chunks,
so both fail if a chunk boundary drops or repeats draws.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: count permutation-null ties with tie_thresholds
The permutation null subtracted TIE_TOL from the observed mAP itself,
while every other p-value counts ties with nulls.common.tie_thresholds.
Use tie_thresholds there too. The counts are unchanged: the observed mAP
is a float64 in [0, 1], where TIE_ULPS * eps * |mAP| <= 1.8e-15 is below
TIE_TOL, so the threshold is the same subtraction (bitwise equal to
mAP - TIE_TOL on 2,000,004 values in [0, 1]).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: derive both nulls' Philox keys with one stream_key
joint.signature_keys and permutation.group_key each hashed
repr((seed, obj)) with blake2b and split the 64-bit word into a Philox
key. nulls.common.stream_key now does that once. The derivation is
byte-identical: 44,800 keys (56 seeds x 200 signatures and 200 groups)
equal those of 7087490, and a test pins two of them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: draw a Philox block's two uniforms with one uniform_pair
The joint sampler's scalar pair and NumPy _pair_np, and the permutation
null's next_uniform and _uniforms_np, each turned a Philox block into
two uniforms. philox.make_uniform_pair(philox, uniform, jit) builds that
step once, following the kernels' factory pattern: the scalar kernels
build it from the philox and uniform they are given, so a compiled
kernel calls a compiled uniform_pair, and the module-level Python
uniform_pair serves the NumPy paths on arrays.
Under numba.njit (0.68), the factories still compile and match Python
draw for draw: 14,000 joint draws, 4,000 permutation mAPs and 5,000
uniform pairs identical.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: build both kernels' head sort with one make_head_sort
The joint sampler's sort_head and the permutation kernel's sort_entries
were the same in-place insertion sort with a NumPy fallback, at
thresholds 32 and 128. nulls.common.make_head_sort(threshold, jit)
builds it in the kernels' factory pattern; each kernel keeps its
threshold, so the sorted values are unchanged.
Under numba.njit (0.68) the factories still compile and match Python
(14,000 joint draws, 4,000 permutation mAPs), and the compiled head sort
equals the Python one on 129 heads of 0 to 294 entries per threshold.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: read a permutation layout's block count from its pool
_Layout took the group's blocks only to count them, and its pool already
holds those blocks. Drop the parameter and use len(pool.blocks), so a
layout cannot be built with blocks that differ from its pool's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* docs: say what the attached AP pairs keep alive
The README and average_precision's docstring said the attached pairs
reference the features. They also hold every positive and negative pair
of the AP call, 8 bytes per pair (uint32 index pairs), whichever null
the frame is later used with: 800 MB for 10^8 negative pairs. Say so,
and that attrs.pop("copairs_pairs") drops them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: gather permutation-null ranks from one precomputed table
For small layouts (codes^2 <= 2**20) with rank tables, each draw found a
positive's rank as the reference rank gathered from a (code, code) table
plus a searchsorted of its key in the block members' sorted keys. Both
depend only on the (x, y) pair, so precompute their sum per layout and
gather it once. Build it only when the draws gather more positives than
the table has entries; otherwise keep the rank-table gather.
MEASURED on a cpu node (16 CPUs), null_size=1e4, serial, min of 2 runs,
pr2_bench designs (seconds): hub4 4.30 -> 3.38, hub8 11.73 -> 7.94,
hub20 63.08 -> 37.96, plate4 10.00 -> 7.99, cellhealth 5.98 -> 5.95
(there the table, 606^2 entries for 300,000 gathers, is not built).
P-values are bitwise identical. The scalar-parity test now covers both
table paths.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: build a layout's search rows only for unranked pools
Every _Layout concatenated its members' and the pool's sorted reference
rows (a copy of the pool's srr) with their bounds, but only pools above
RANK_POOL search them; ranked pools read rank tables. Build them only
for unranked pools. MEASURED: a layout of a 4000-reference pool no
longer holds 61.1 MB of search rows; times on the pr2_bench designs are
unchanged within noise (hub20 37.96 -> 37.85 s, bigpool 10.49 -> 10.07 s).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: build a ranked pool's sorted-row words once
_row_ranks rebuilt the pool-wide array of (row, code) words of the
pool's sorted reference rows for every layout's rcm, so groups sharing
one large pool paid it again and again. Build the words once in _Pool
(kept while the pool lives: 8 bytes per row entry, 134 MB at RANK_POOL
references) and pass them to _row_ranks.
MEASURED on a cpu node, serial, min of 2 runs: 40 groups of 4 replicates
sharing one pool of 4000 references, null_size=1e3: 10.07 -> 3.80 s;
the pr2_bench designs at null_size=1e4 are unchanged within noise
(cellhealth 5.76 -> 5.81 s, hub20 37.85 -> 38.65 s). P-values are
bitwise identical.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: run the permutation null's groups on a thread pool
permutation_pvalues ran its groups one by one and ignored max_workers,
which the copied null honours. Run the groups on a ThreadPoolExecutor of
max_workers threads. Groups ranking the same references share one
read-only _Pool, built once by whichever thread needs it first and freed
after its last group; groups are visited pool by pool, so few pools are
alive at once. Each group's p-value depends only on its own draws, so the
results do not depend on the number of threads (tested with 1 and 4,
and against each group run alone, with each pool built once per run).
MEASURED on a cpu node (16 CPUs), null_size=1e4, pr2_bench designs,
1 thread -> 4 threads -> default (20) (seconds): cellhealth 5.89 -> 2.78
-> 3.00, hub4 3.38 -> 2.00 -> 2.70, hub8 7.85 -> 3.83 -> 4.79, hub20
41.04 -> 17.24 -> 19.01, plate4 8.04 -> 5.55 -> 7.54. P-values are
bitwise identical.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* test: share the mAP tests' frame, fixture and scratch helpers
test_map.py's _ap_frame and test_map_nulls.py's ap_frame were the same
builder, and four tests rebuilt the "query x4 + 30 controls" metadata by
hand: both now live in tests/helpers.py (ap_frame, query_meta). The
permutation tests build the scalar group_map's scratch arrays with one
map_scratch helper, and test_map.py imports get_map_pvalue and
find_pairs at the top instead of in each test.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: report the mAP the nulls test, in the APs' dtype
91d774e cast the group means to the AP column's dtype only for the
nulls, so the reported mean_average_precision column could differ from
the score that was tested: pandas 3 averages a float32 AP column of one
string-keyed group to float64, and pandas' float32 group mean differs in
the last bit from the rounded float64 mean in 12 of 50 groups of the new
test (24%), under pandas 2.3 and 3.1 alike.
Average the APs in float64 and round the means to the APs' dtype in the
aggregation itself; the column is then the scores the nulls compare, in
one dtype and value under either pandas. float64 APs (what
average_precision returns) are unchanged, and float32 ties still count.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: compare RankPairs by identity
RankPairs was a frozen dataclass with generated __eq__ and __hash__ over
its array fields, so comparing two instances raised "truth value of an
array is ambiguous" and hashing one raised TypeError. Declare it with
eq=False: instances compare and hash by identity, as the attached-pairs
handle already does. Reported by the /code-review pass on #156 (R8).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: honour the step of joint_nulls' rows slice
joint_nulls read only the start and stop of its rows slice, so
rows=slice(None, None, 2) returned every signature and
slice(None, None, -1) returned none, and a caller could pair samples
with the wrong signatures. Iterate the slice's full range to size and
fill the output. Reported by Copilot on #156 (comment 4355276020).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: bound the joint null's per-sample arrays per vectorized call
_joint_null_np holds a (samples, edges) float64 array of a group's edge
uniforms and a (samples, positives) array per member, and joint_nulls
always passed 2**16 samples: a group of 100 replicates (4950 edges)
needed 2.6 GB for the edges alone, 200 replicates 13 GB. Pick each
signature's samples per call so the wider of the two holds at most
_CHUNK_ELEMENTS = 2**22 float64 (32 MiB), as the permutation null's
_Layout.chunk() bounds its per-slot arrays; at most 2**16 as before.
Samples are pure functions of their index, so the draws do not change
(tested against the unbounded call). Reported by the /code-review pass
on #156 (R1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: take the joint null's positive pairs from attached AP pairs
Without pos_pairs, the joint null inferred a group's edges from its pair
counts alone and ignored the pairs average_precision attaches to its
frame. A group whose members each had len(group) - 1 positives in other
groups was then sampled as a replicate clique: with sameby=["comp"] and
positives by target across compounds, compound A's three members (two
positives each, both in B) got a complete-graph null, p = 0.295 with no
warning, while B fell back to the copied null.
Read the attached pairs as the permutation null does, so such groups get
the existing pos_pairs treatment (positives outside the group are
private to each member). Frames without pairs still infer replicate
groups from the counts, and replicate designs give the same signatures
either way. A frame whose index was reset after filtering now raises the
pairs' "no reset_index" error under this null too, instead of being
inferred. Reported by the /code-review pass on #156 (R3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: check the AP frame's index before the nulls read it as pairs' rows
The permutation null, and the joint null with pairs, read the AP
scores' index as the row numbers the pairs index. A frame given another
index (set_index, or labels such as "query0") failed deep in the nulls
with "invalid literal for int() with base 10", and negative labels
indexed the pair tables from the end. Check up front that the index is
integer and non-negative, and say to keep the AP call's index. Nulls
that do not read pairs (copied, joint without pairs) still accept any
index. Reported by the /code-review pass on #156 (R10).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: say why dropping group members breaks the permutation null
Dropping some of a group's members from an AP frame raised "positives
outside the group or negatives inside it ... Group so they are", which
reads as a grouping mistake, while the README said the attached pairs
follow the frame through filtering. The kept members' APs were computed
with the dropped ones as positives, so relabelling the kept members
cannot test them.
Keep raising, but detect positives to profiles in no group (members
dropped from the AP scores) and say so: drop whole groups only,
recompute average_precision on the kept profiles, or pass null='joint'
or null='copied'. The README and the return_pairs docstring now say
that filtering whole groups (or controls) is fine and dropping some
members of a group is not, for this null. Reported by the /code-review
pass on #156 (R4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: reject batch-dependent distances under the permutation null
The permutation null recomputes similarities in its own batches of
pairs. SciPy's seuclidean and mahalanobis, through
compute._cdist_diag_sim, estimate their variances or covariance from
each batch, and the AP stage ranks positives and negatives in separate
batches, so the recomputed similarities differ from the AP stage's.
The default mAP call then raised "mAP ... from the pairs differs ... in
the AP table" on its own unmodified frame: features [0, 1, 10, 1000],
labels q, q, c0, c1 give an observed mAP of 0.5 and a recomputed 1.0.
Leave the AP stage unchanged, and raise up front for these distances
under null="permutation", naming the distance and pointing to
null="joint" or null="copied", which use the APs as computed. Reported
by Copilot on #156 (comment 4355276003).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: compute the attached pairs' similarities in the calling thread
RankPairs.similarity wrapped compute.get_similarity_fn, whose
batch_processing starts a ThreadPool of cpu_count() threads on every
call. The permutation null calls it from each of its worker threads,
once per similarity chunk of every pool and layout, so each call nested
a fresh pool of up to cpu_count() threads inside a worker.
Split get_similarity_fn's metric lookup into
compute.pairwise_similarity_fn and have the attached similarity run the
same pairwise function over the same batch_size batches, one after
another in the calling thread. Each batch is the same call on the same
rows, so the similarities are identical (tested for cosine, correlation
and cityblock against get_similarity_fn, with no parallel_map call, and
the p-values do not change). Reported by the /code-review pass on #156
(R7).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: reject permutation layouts whose draws break pos_diffby
Identical negative sets do not make relabelling keep the positive-pair
rule. With pos_sameby=["g"], pos_diffby=["plate"], neg_diffby=["g"],
three members on plates A, B, C and two controls on A form one block,
and a draw of profiles on B, A, A keeps the members' complete positive
graph although reapplying pos_diffby drops the A-A pair. The identity
check passes, so the null silently tests the wrong rule: its support
there (0.5, 0.583, 0.639, ...) differs from the relabelled mAPs that
reapply the rule (0.472, 0.361, ...).
Preserving the rule inside draws would change the sampler, so reject
such layouts instead. average_precision records each row's pos_diffby
value codes in a new optional RankPairs.pos_diffby field, and
permutation_pvalues checks that every draw keeps the members' pairs:
per column, a block's pool (members and references) has one value or
no repeated value, and two blocks' pools have one value each or share
none; a column whose profiles never differ for a pair of blocks fixes
that pair. Otherwise it raises and points to blocking references by
those columns, null="joint" or null="copied". Plate-blocked designs
with pos_diffby=["plate"] and per-profile columns such as wells pass.
#150 has the same gap (its permutation null never reads pos_diffby).
Reported by Copilot on #156 (comment 4355275983).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* test: build interleaved permutation pools once
7087490 visited groups by a truncated pool key, (len, first two refs) per
block, so pools [10, 11, 12] and [10, 11, 13] tied and groups ranking A,
B, A stayed interleaved; with only the last pool cached, A was built
twice. e19ff52 already sorts by the complete reference sets and keeps
shared pools until their last group. Pin that: three groups on pools A,
B, A (B shares A's first two references) build exactly two pools, and
their p-values equal each group run alone. Against 7087490's source the
test builds three. Reported by Copilot on #156 (comment 4355276036).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: bound the memory of the permutation null's concurrent pools
Since e19ff52 each worker thread builds the pool its group needs, and a
pool keeps its key matrix and sorted rows (and, up to RANK_POOL, a rank
table and row words): about 2 GiB at MAX_POOL references. With the
default max_workers, a design with many distinct large pools (e.g. a
consistency design, one pool per group) could hold one per thread, 32
pools or ~64 GiB at once.
Estimate each pool's bytes before building it (_pool_bytes) and build
it only when it fits in POOL_BUDGET = 4 GiB beside the alive pools, or
when no pool is alive; otherwise its thread waits until a pool is
freed. Groups are visited pool by pool, so a waiting thread holds no
pool and every alive pool's remaining groups have started: the wait
always ends. P-values do not depend on it (tested: with a budget of one
byte and 4 threads, one pool is alive at a time and the p-values equal
the 1-thread run; at 161f0ea all 3 pools were alive at once).
Reported by the /code-review pass on #156 (R2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: slice overlapping permutation pools' keys from one table
Each distinct pool computed its own R x R key matrix. Designs whose
groups rank overlapping but different references (consistency designs,
where a group's references are all other groups' profiles; groups on
different subsets of plates) recompute the same pairs once per pool:
150 groups of 20 among 3000 profiles evaluate ~1.3e9 similarities for
~4.5e6 distinct pairs.
When the profiles of all pools fit one table of KEY_TABLE_BUDGET =
256 MiB (8192 profiles) and the table has fewer pairs than the distinct
pools' matrices together, compute it once per permutation_pvalues call,
on the call's threads, and slice each pool's matrix from it. A pair's
code is the same whichever chunk computes it, so keys and p-values are
identical (tested against the table disabled, and a sliced matrix
against _key_matrix). Designs with one shared pool or disjoint pools
(the pr2_bench designs) skip the table.
MEASURED on a cpu node (16 CPUs, null_size=1000, pr2_bench/review/
bench_r6.py), seconds, 3d41f43 -> this commit: consistency (150 x 20,
negatives = other targets) 55.2 -> 18.7, plates3 (300 groups on 3 of 40
plates of 100 controls) 2.3 -> 1.5; p-values bitwise identical.
Reported by the /code-review pass on #156 (R6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* docs: describe what check_pos_diffby's refs_stats returns
The comment said it returned sorted values and whether any repeat; it
returns only each column's sorted distinct values.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: attach LabelPairs to multilabel AP frames
multilabel.average_precision now attaches the pairs its APs came from to
the frame it returns (frame.attrs["copairs_pairs"]), as average_precision
does with RankPairs, and return_pairs=True also returns them. LabelPairs
(a RankPairs) adds what a multilabel null needs: each AP row's profile,
the label each positive pair shares, and the lone pairs, which share
exactly one label and meet the negative rules on the other columns, so
that they become negatives when that label moves.
The mAP nulls do not read them yet: get_map_pvalue treats a multilabel
frame as one without pairs, as before (the permutation null raises, the
joint null infers its edges from the pair counts). The label-permutation
null follows.
Ported from #150 (46cb8b0, ea1fc1c), with the lone pairs found by
find_pairs_multilabel instead of #150's fast matcher. Tests check the
attachment, the row-to-profile map, each pair kind against the labels,
and the similarity against the AP stage's.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: share the permutation kernels' subset draw and search
The draw's Floyd-plus-Fisher-Yates loop becomes ordered_subset, with a
vectorized twin _ordered_subsets_np, and the binary search becomes
_make_count_less, so the multilabel null's kernels can build the same
pieces with the same jit argument. Draws and mAPs are unchanged: the
scalar-versus-vectorized tests pass as before, and every single-label
reference array matches 17bdcac bit for bit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: add the label-permutation null for multilabel APs
The permutation null, the default, now runs on multilabel AP frames:
get_map_pvalue reads their LabelPairs and calls
label_permutation_pvalues. Each group holds one label; its pools are the
components of the negative-pair graph holding its profiles, members
included, and a draw moves the label to as many of each component's
profiles as hold it there. A receiver ranks the other receivers against
its own negatives plus the lone pairs it gains when the label moves,
minus the receivers, from the observed similarities.
Draws are defined by scalar functions (_make_label_kernels, built like
the single-label kernels with jit=) and run as their NumPy twins,
_draws_pool_np and _label_maps_np, which the tests check draw for draw
with ties and with ranked and searched pools. Groups whose label lost
some of its AP rows raise, as do pairs that do not match the frame and
layouts whose pos_diffby rule the draws could break. Pools are shared
between groups through _SharedPools, now keyed by any pool name, and one
key table, so _key_table takes the distinct pools' profiles.
Ported from #150 (46cb8b0), with NumPy in place of numba and a
pos_diffby check #150 did not run on multilabel groups. Single-label
p-values, draws and keys stay bit for bit those of 17bdcac (156 of 156
reference arrays).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: stop permutation draws early with stop_after=
get_map_pvalue, mean_average_precision and its hierarchical variant
take stop_after=: the permutation null, single-label or multilabel,
stops a group's draws at its stop_after-th draw whose mAP reaches the
group's and reports stop_after / draws, Besag and Clifford's sequential
p-value. Groups that never reach stop_after hits run all null_size
draws and keep (count + 1) / (null_size + 1). Other nulls reject it,
and it must be a positive integer.
_count_hits runs the draws in rounds, from 256 draws doubling up to the
layout's chunk, or in chunks as before without stop_after. Draw j does
not depend on the rounds, so a stopped run is a prefix of the full one:
tests check the stopped p-value and the mAPs against the full sequence,
with other round sizes, at round edges, and on multilabel groups.
permutation_null now returns (count, identity, pool, draws) and
label_permutation_null (count, identity, draws), as in #150.
Ported from #150 (eeaa041, docs af301fa). Without stop_after,
single-label p-values, draws and keys stay bit for bit those of 17bdcac
(156 of 156 reference arrays).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* feat: let the joint null read multilabel APs' LabelPairs
The joint null takes its edges from the attached pairs since PR 2, but
ignored the LabelPairs of multilabel frames and inferred cliques from
the pair counts, so label groups whose positives are not all their
other members (e.g. pos_diffby) fell back to the copied null with a
warning. It now joins the AP rows of each positive pair's two profiles
for the label they share. Pairs to rows dropped from the frame get
numbers past all rows, so they join a member to a profile outside its
group, as they do for single-label pos_pairs.
Tests check the row pairs against a brute-force enumeration, the
p-values against explicit pos_pairs with and without a dropped row, no
warning where the bare frame falls back, and unchanged p-values on
clique groups. Frames whose index runs past the pairs' frame now raise
in both nulls instead of an IndexError.
This deviates from #150, whose joint null ignores attached pairs
(d7d5bfc); it follows PR 2, whose joint null reads them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* docs: describe the multilabel permutation null and stop_after
The README said multilabel frames carry no pairs and needed another
null. It now describes how the permutation null moves a multilabel
group's label within the components of the negative-pair graph, that a
group needs every AP row of its label, and that the attached pairs keep
the lone pairs too. It adds stop_after's semantics with its
threshold-stability caveat (from #150, af301fa) and how the joint null
reads multilabel pairs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: store multilabel positive pairs as pairs of AP rows
LabelPairs subclassed RankPairs but gave its inherited pos field another
meaning (pairs of profiles), so get_map_pvalue dispatched on the type
twice and rebuilt AP-row pairs for the joint null after the fact
(_label_row_pairs: a search over profile * n_keys + label, plus its own
label-column, row-index and index-range checks). LabelPairs.pos now
pairs AP rows, as RankPairs.pos does, and row_key gives each row's
label, replacing the per-pair pos_key (8 bytes per positive pair). The
joint null takes pairs.pos for both types, and the label permutation
null maps the row pairs to profile pairs and labels itself. It reads
each group's label from row_key, so the AP frame no longer needs its
label column.
Results do not change: single-label dumps are bitwise equal to 17bdcac
(156/156 arrays) and the multilabel bench to 11dc5e4 (30/30 arrays: AP
values and p-values at 1e3, 1e4 and stop_after=10), and the joint null
on label groups equals explicit pos_pairs (test). Frames without the
label column now run under the permutation null instead of raising,
and a shifted index under the joint null raises the positive-pair
count error instead of "index reaches row".
Reported by the /simplify of PR 3 (#157) (A1, A2; with the map.py
parts of S3, S9 and A8).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: keep the label null's helpers private
PR 3 added label_layouts, label_permutation_null, sequential_pvalue and
a label= argument of group_key to the public names of
copairs.nulls.permutation, though only the module itself calls them.
The maintainers want PR 3's interface minimal, so they become
_label_layouts, _label_permutation_null and _sequential_pvalue, and
the multilabel key moves to _label_key; group_key keeps part 2's
signature. label_permutation_pvalues and check_stop_after stay public.
Keys and draws do not change.
Reported by the /simplify of PR 3 (#157) (A4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: keep permutation_null's part 2 return, run draws via _Run
PR 3 widened permutation_null's return from part 2's (count, identity,
pool) to a 4-tuple with the draws run, which breaks callers of part 2's
public function, while _label_permutation_null returned a 3-tuple of
another shape and duplicated its body. A private _Run now holds one
group's layout and key, its recomputed mAP and threshold, and counts
its draws (with stop_after); both p-value drivers and the label tests
use it, and permutation_null goes back to part 2's signature and
return. Layouts gain the identity codes and draws/maps methods that
_Run calls. Draws and p-values do not change.
Reported by the /simplify of PR 3 (#157) (A5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: run single-label and label groups with one driver
permutation_pvalues and label_permutation_pvalues each carried ~25
lines of the same thread driver (key table, shared pools, pool-order
visit, progress bar, cancel on error), differing only in how a pool is
built and how a group's layout starts. _run_groups now holds the
driver; each null passes its pool keys and profiles, build, byte
estimate and a start(g, pool) that returns the group's _Run, which also
checks the recomputed mAP before any draw. The single-label path no
longer computes its pool keys twice. Draws and p-values do not change.
Reported by the /simplify of PR 3 (#157) (A3, S1, R2, S12).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: run a group's chunks of draws as separate thread tasks
A group's draws ran serially on one thread, so a large group kept one
thread busy after the rest finished: on the consistency bench the
259-member label alone took most of the wall time. Each group's pool
build, start and chunks of draws are now separate executor tasks, all
submitted by the calling thread, so no task waits on another. Groups
start pool by pool, at most max_workers at a time, and _SharedPools is
that thread's bookkeeping: a group with a new pool starts once the pool
fits POOL_BUDGET beside those alive, so the budget cannot deadlock.
With stop_after a group's rounds still run one after another.
Draw j does not depend on the chunks, so p-values are unchanged for any
max_workers and with stop_after: single-label dumps 156/156 arrays and
the label bench 30/30 bitwise equal to 17bdcac / 11dc5e4. The new test
splits each group's draws into 10 tasks (or rounds of 32) on 1 and 4
threads and with POOL_BUDGET = 1; it fails when chunks record the wrong
first draw or draw the same draws.
bench_label.py, 16 CPUs, before -> after: consistency 1e4 65.11 ->
44.38 s, consistency_null 1e4 65.49 -> 44.84 s, plates 1e4 66.41 ->
44.81 s; 1e3 9.45 -> 7.63 s.
Reported by the /simplify of PR 3 (#157) (E1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: leave stop_after's value check to the permutation nulls
get_map_pvalue checked stop_after with check_stop_after and then passed
it to permutation_pvalues or label_permutation_pvalues, which check it
again. It now only refuses stop_after for the other nulls; the test also
covers bad values on multilabel frames, which the label null rejects.
Reported by the /simplify of PR 3 (#157) (S4).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: call the permutation nulls from one branch of get_map_pvalue
The multilabel and single-label permutation branches repeated the pair
counts and keyword arguments. One branch now builds them once and picks
label_permutation_pvalues for LabelPairs, permutation_pvalues otherwise.
Reported by the /simplify of PR 3 (#157) (S5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: check multilabel pair counts with common.check_pair_counts
_label_layouts re-implemented the per-profile pair-count check of
check_pair_counts with its own message. check_pair_counts now takes the
counts aligned with the members (its two callers index them first) and
an optional label, whose message keeps the multilabel wording; the
single-label message is unchanged. test_label_guards now covers a wrong
positive and a wrong negative count on a multilabel frame.
Reported by the /review of PR 3 (#157) (RV8) and its /simplify (R8).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* refactor: share the NumPy rank tail of the single-label and label maps
_group_maps_np and _label_maps_np repeated the same steps after their
keys: sort each draw's entries, count the drawn negatives ranked before
each key, find the positives in rank order, and average the precisions.
They now call _rank_entries, _drawn_before, _positives and
_mean_precision, the same operations in the same order, so the mAPs stay
bitwise equal (and equal to the scalar functions the njit check runs).
Reported by the /simplify of PR 3 (#157) (R3, S6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: add each draw's precisions with one cumulative sum
_mean_precision looped over a slot's positives, adding one column of
precisions per pass. It now divides all of them at once and adds them
with np.cumsum along each row, which adds left to right like the loop
and the scalar group_map (not pairwise, as np.sum would), so the mAPs
are bitwise unchanged.
Reported by the /simplify of PR 3 (#157) (E3).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: read lone partners' rank counts from a per-layout table
_label_maps_np searched each moved member's sorted lone-partner keys
once per draw and positive, about a quarter of the label null's time. A
layout that will gather more positives than the table has entries now
builds an (n + 1, pool) int32 table of those counts once, as part 2's
full_before table does for single-label layouts, capped at _FULL_TABLE
entries; smaller runs keep the search. The counts are the same
integers, so the mAPs are bitwise unchanged: the label bench is 30/30
bitwise equal to 11dc5e4, and the vectorized-vs-scalar label test now
also runs with the table (its 16 table cases fail when the table's
last row is 1 instead of 0).
Reported by the /simplify of PR 3 (#157) (E2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: summarize the label null's components once in check_pos_diffby
check_pos_diffby caches each block's reference statistics by the
references array's id, but the label null built fresh references for
every group (its component minus the members), so the cache never hit:
each label sorted its whole component once per pos_diffby column. The
label null now passes its components whole (whole_pools=True), shared
by every group ranking them, and the pool's one value, repeats and
values are read from the cached statistics. They decide the same rules:
a test checks random layouts on 1-3 pools in both forms, and they agree
(it fails when the whole-pool form ignores repeats).
1000 labels of 4 members on one 16384-profile component, one column:
1.501 -> 0.002 s. The label bench and the LabelPairs-derived dumps stay
bitwise equal to 11dc5e4 (30/30, 38/38).
Reported by the /review of PR 3 (#157) (RV6).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: search lone pairs only among profiles holding a label with positives
_lone_pairs ran its multilabel pair query over every profile and only
then dropped pairs of labels without positive pairs. Profiles holding no
such label cannot share one, yet they all joined the query: 10,000
replicates of one control compound under a control-only label (with
pos_diffby=["compound"]) give 49,995,000 pairs, materialized and
deduplicated on every multilabel AP call. The query now sees only the
profiles holding a label with positive pairs, with all their labels, so
a pair also sharing a dropped label still does not count as lone.
The new test fails before (the query saw 12 profiles, not 6) and passes
after; lone pairs match brute force, and the LabelPairs-derived dumps
are bitwise equal to 11dc5e4 (38/38).
Reported by Copilot (4361701454).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: keep the label null's negative CSR uint32, components from it
_label_layouts copied every negative pair to int64, kept int64
partners in the CSR the pools read for the whole run, and built a
second COO graph from the pairs for connected_components. The pairs now
keep their uint32 type, the CSR's partners stay uint32, and the
components come from that CSR, with the same labels.
1e7 negative pairs over 10^5 profiles (traced): peak 965 -> 708 MiB,
kept 154 -> 78 MiB, same pointers, partners and components; the label
bench and the LabelPairs-derived dumps are bitwise equal to 11dc5e4
(30/30, 38/38).
Reported by the /simplify of PR 3 (#157) (E6) and its /review (RV5).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* perf: find multilabel lone pairs when the null asks, from positives if equal
multilabel.average_precision ran a third pair search for the lone pairs
on every call and kept them on LabelPairs (lone, lone_key, int64: 24
bytes per pair against the 8 documented), whichever null was used. Under
the usual rules (the negative rules without the label are the positive
rules) that search repeats the positive one: the lone pairs are the
positive pairs listed once. LabelPairs now holds a private _lone
callable instead of the two fields: it reads the positive pairs in that
case and runs the search otherwise, only when the label null calls it,
and returns uint32 pairs with int32 keys. The README and docstring now
state what the pairs keep: 8 bytes per pair and 12 per AP row.
One commit for the cluster: the deferred callable, the derivation and
the narrower types replace the same two fields.
Bench designs (2000 profiles), multilabel AP median of 3, before ->
after: consistency 8.46 -> 7.46 s, consistency_null 8.44 -> 7.39 s,
plates (neg_sameby, searched) 4.33 -> 3.30 s, plus 0.9 s when the
permutation null asks; the same 74969 / 18748 lone pairs. Label bench
30/30 and LabelPairs-derived dumps 38/38 bitwise equal to 11dc5e4. A
new test counts the searches (2 during the AP call, a third only when
asked and only under neg_sameby) and checks both paths against brute
force.
Reported by the /simplify of PR 3 (#157) (E4, A6, E5) and its /review
(RV2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* test: check stop_after on multilabel groups is the same for any rounds
The rounds invariance of stop_after was tested for single-label layouts
only (monkeypatched _Layout.chunk). test_stop_after_on_multilabel_groups
now reruns with _FIRST_ROUND = 7 and _LabelLayout.chunk = 77, so every
stopped label stops past its first round, and expects the same
p-values. With label draws that ignore their first draw (each round
redraws draws 0, 1, ...), the extended test fails and the old one
passes.
Reported by the /review of PR 3 (#157) (stop_after rounds invariance
untested for label layouts).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
* fix: name the joint and copied nulls when multilabel groups mix labels
Multilabel frames now carry pairs, so g…
Brings copairs 0.6.0 (cytomining#156, cytomining#157, cytomining#166): the mAP null choice with label permutation as the default, multilabel permutation, and the pair dictionaries the AP functions attach to their frames and return with return_pairs=True. Conflicts: - map/average_precision.py: keep return_pairs where 0.6.0 put it and add backend after it, so 0.6.0's positional order holds; one progress_bar entry (main's) in the docstring. - map/multilabel.py: same signature order; import find_pairs_multilabel again next to the label matcher, for main's _lone_pairs. The Numba branch no longer returns early through _merge_results: both backends build the per-label rows and their row_key (the Numba kernel's label, the NumPy loop's label counts), then share main's tail, which builds the AP-row pairs, lone pairs and pair dictionary. Rows are ordered by label and then profile under either backend. pyproject.toml, README.md, tests/helpers.py and uv.lock merged cleanly (version 0.6.0 plus this branch's numba extra, Performance section and run_isolated helper). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
Brings copairs 0.6.0: cytomining#156 and cytomining#157 squashed and reworked (8deda8f, 742f2d8), with no joint->copied fallback, no pos_diffby check, plain pair dictionaries, null_size=0 -> NaN, seed default 0, per-call resource arguments, a bounded draw queue and no stop_after. This branch held the pre-review split/2 and split/3 (3416f19) plus split/5 (ec6ccc5), so the two versions of cytomining#156/cytomining#157 were not merged hunk by hunk. Each file is main's version plus this branch's delta since 3416f19 (git diff 3416f19 10d7471: PR 5's fast/legacy methods and backends, and this PR's Numba kernels), applied 3-way and ported to main's code: - Files the delta does not touch (docs, notebooks, map/__init__.py, hierarchical_fdr.py, multilabel.py, nulls/common.py, nulls/philox.py, main's new tests): main's version. map/__init__.py had auto-merged to this branch's RankPairs/LabelPairs exports, which main added and then removed; it is main's now. - Branch-only files (nulls/_numba.py, backend.py, sampler.py, pvalues.py, _numba_cache.py, tests/test_null_methods.py): kept. - nulls/joint.py: main's, plus backend= on joint_nulls, joint_pvalues and group_pvalues (no fallback list); group_pvalues resolves the backend before its null_size=0 return. - nulls/permutation.py: main's, with this branch's _Run on a backend, _NumpyTables/_LabelNumpyTables, _draw_chunk/_NUMBA_CHUNK task sizes, the Numba thread choice in _run_groups and keyword-only options. Main's resource checks, _Pool(max_reference_profiles), pool/key-table budgets, null_size=0 return, shutdown on failure and its scheduler (at most 2 * workers draw futures, refilled round-robin) stay; the scheduler reads the run's chunk. stop_after (rounds, early counts, task cancellation, _TASKS_PER_WORKER) is not carried over. - map/map.py: main's, plus PR 5's method= and backend= as keyword-only arguments after main's `*`. null defaults to "permutation" as on main: null=None ("the method's null", b7f9455) is gone, and method="legacy" takes null="copied" only. Under the fast method the seed is checked as a Philox seed and the backend resolved before the empty-input raise. - methods.py: METHODS/BACKENDS/check_method from this branch; check_null(null, method) without the None default. - compute.py, average_precision.py, nulls/__init__.py, tests/helpers.py, test_compute.py, test_map.py, test_nulls.py, test_nulls_joint.py, pyproject.toml, uv.lock: main's plus the delta, applied cleanly. - README.md: main's text, with this branch's Numba section; the copied null's legacy method needs null="copied". - tests: main's tests, with this branch's added. stop_after tests are dropped; the label backend test and the task-bound test run without it; main's queue test reads the run's chunk; main's tests that drove the NumPy kernels with a layout pass layout.tables(0); main's failure test caps the chunk with _NUMBA_CHUNK; PR 5's legacy mAP calls name null="copied"; test_map_empty_input expects UnpairedException. Suites on the merge tree: pr6-all 579 passed, 6 skipped; pr6-base 487 passed, 70 skipped; pr6-pd3 492 passed, 65 skipped; pr6-numba060 (Numba 0.60) 579 passed, 6 skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
Part 2 of the #150 split (plan in #151): the choice of mAP null, with the label-permutation null as the new default. #153 is merged; this branch merges main at 310e1ce (482aaff), and its own commits start at 39c1639.
What changes
null=onmean_average_precision,mean_average_precision_hierarchicalandget_map_pvalue:"permutation"(default),"joint"or"copied", validated bycopairs.methods.check_null. All three count null mAPs>=the observed mAP, within float32 rounding of the APs."permutation"(copairs.nulls.permutation) tests the paper's null hypothesis directly."joint"(copairs.nulls.joint) is fix: sample the mAP null jointly over a group's members #151's null, ported fromdefault_rngto the counter-based Philox stream, so results don't depend on whether Numba is installed. A positive pair inside the group is one draw in both members' rank lists. Draws are pure functions of (seed, group signature, sample index), so part 6's Numba kernels can reproduce them draw for draw."copied"is the 0.5.5 null model: per-configuration AP nulls averaged over the members.>=.method="legacy"restores the strict>.average_precisionattaches the pairs behind its frame asattrs["copairs_pairs"]. They follow filtering and copies, not saving or concatenation;return_pairs=Truealso returns them.mean_average_precision(pairs=)takes them explicitly.pos_pairsthat do not indexap_scoresnow raise.feat!: the default changes to"permutation". Existing tests that build frames by hand name"copied"or"joint".phenotypic_activity.ipynb(55 of 58 compounds active at null_size 1e6) andnull_size.ipynb, which recomputes the APs (the CSV has no pairs) and counts the permutation null's relabellings, C(6 + 24, 6) = 593,775.phenotypic_consistency.ipynbkeepsnull="copied": its multilabel APs carry no pairs until part 3 (feat: permutation null on multilabel APs #157).null_comparison.ipynbruns the three nulls on the same plate and APs (null_size 1e6, seed 0): 55, 55 and 50 of 58 compounds active, in 23 s, 19 s and 0.5 s on 16 CPUs. As a negative control, 100 pseudo-groups of 6 DMSO profiles against 12 other DMSO (10^5 draws; their permutation null has C(18, 6) = 18,564 relabellings) get p < 0.05 for 5% (binomial 95% CI 1.6-11.3%, too narrow since the tests share DMSO profiles), 5% and 1% (0-5.4%). The notebook runs in 83 s.Deviations from #150
Joint null arithmetic: it uses its own
logand integer powers instead ofmath.logand**.np.logandmath.logdiffer on 32 of 30,005 inputs (MEASURED), which would break exact Python/NumPy/Numba agreement.Pairs similarity: the similarity behind attached pairs is the generic NumPy cosine (
compute.get_similarity_fn), not Fast exact nulls, counting AP and optional GPU kernels #150's fast kernels. Those are part 4 (perf: optional Numba backend for the AP stage #154).Not in this PR:
stop_after(permutation_nullreturns 3 values);joint_pvalues(budget_bytes=);These belong to part 3.
Results (
null_size=10_000, 16-CPU node, MEASURED)P-values against #150:
Time in seconds.
A consistency-style design (150 groups of 20, overlapping but distinct reference pools,
null_size=1000) went from 55.2 s to 18.7 s with the shared key table (bd089d8).The review commits leave every p-value and draw bitwise identical on these designs.
The scalar joint and permutation functions compile with
numba.njitunchanged and match plain Python bit for bit: 14,000 of 14,000 joint draws, 4,000 of 4,000 permutation draws (MEASURED with numba 0.68, outside this PR). That is the basis of part 6.Bug found on the way
pandas 3 averages float32 APs to float64, so group means missed ties with null atoms: p = 0.79 instead of 1 in
test_float32_scores_count_ties[joint]. Fixed in 91d774e by comparing in the APs' dtype. #150 probably has the same bug (INFERRED, untested).A group failing (e.g. pairs that do not match the AP table) could hang the permutation run instead of raising, when threads waited for pool memory and a pool's queued groups were cancelled (Copilot). Fixed in a9d1ce6; the test forces the race.
SciPy metrics (e.g.
cityblock,canberra) took the diagonal of a full batch-by-batchcdistmatrix, a 3.2 GB temporary per 20,000-pair batch, now also over every permutation pool's pairs (Copilot). Since 6b8d8a8 the diagonal comes from 64-row blocks, bitwise the same for every SciPy metric except the batch-dependentseuclideanandmahalanobis, which keep one call. AP frames concatenated from copies or overlapping subsets of one frame keep its pairs and repeat row numbers, which the joint null took as independent members; such frames now raise under both pairs-based nulls (0b6971a, Copilot).Testing
Full suite on a CPU node at eabb22b, no numba installed:
Mutants fail their tests: reverting the
samebypart of the empty-input check (6 failures), dropping rows withoutsamebyvalues (1), removing the pool abort (the run hangs; the test passed 35 of 35 runs with it), full-batchcdist(3), no repeated-index check (1).The permutation null's smallest p-values in
null_size.ipynbsit below the expected p_min at seed 0. Over 20 seeds at 1e6 draws, the 5 compounds with mAP = 1 drew their observed relabelling 185 times against 168.4 expected (Poisson p = 0.22), so seed 0 is a low draw.Before the merge, at bd089d8, py3.11 with pandas 2.3.3 (CI pandas job build) also passed (228). Before 91d774e, the pandas 3.1.0 environments had 1 failure.
After importing
copairs,copairs.mapandcopairs.nulls, numba is not loaded. The same check returns True in a Fast exact nulls, counting AP and optional GPU kernels #150 environment, so it can detect it.Bitwise identity across the review commits: 156 of 156 reference arrays (191,202 elements) are identical between 7087490 and bd089d8. They cover:
The comparison flags a single-ulp change, so it can detect one.
The scalar per-draw functions still compile with
numba.njitunchanged and match plain Python bit for bit. This was checked outside the repo with numba 0.68 (14,000 joint draws, 4,000 permutation draws, plus the new shared Philox and head-sort helpers).Every review fix below has a test that failed before it.
ruff checkandruff format --checkare clean at the pinned 0.15.20, notebooks included.Review
/simplify(4 cleanup reviewers; 15 commits, 6502f07..161f0ea):random_mapis now only a test reference;tie_thresholds,stream_key,uniform_pairand head-sort helpers. The kernel ones stay compilable by numba;max_workers);/review(high effort):null_size≥ 65,536);RankPairscompares by identity;typing.Optionalstyle, which matches the repo and fix: sample the mAP null jointly over a group's members #151.pos_diffbyare rejected (6f37f07);seuclidean,mahalanobis) are rejected under the permutation null (98ffbbb);joint_nullshonours the step ofrows=(91a84f3);null="permutation", three inputs now raise, each with an error namingnull="joint"ornull="copied":pos_diffbydesigns whose relabelled draws could break the rule;null="joint"uses the frame's attached pairs when there are any, so a frame whose index was reset after filtering now raises instead of being inferred from pair counts.UnpairedException, now under every null. So do frames whose valid rows all miss asamebyvalue (3f7acb4, Copilot), which main still returns as an empty table; one check covers both since 98d0ffc, andindiceskeep main's positions (rows after invalid APs are dropped, as the docstring now says). Non-integer seeds raise instead of being truncated (7fefbe9), and the nulls' own functions check the seed range too (be2cffc). The null,null_size, seed,pos_pairsand pairs checks run first, so a bad argument still raises itsValueErroron such a frame (e3f71c8, tests for all three nulls and both entry points)._copied_pvaluesno longer returns early for no groups, which only an empty table reached.mean_average_precisionis averaged in float64 and rounded to the APs' dtype, the same value the nulls test. User-built float32 AP frames under pandas 2 can move by one float32 ulp.🤖 Generated with Claude Code
https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7