Skip to content

Fast exact nulls, counting AP and optional GPU kernels - #150

Draft
alxndrkalinin wants to merge 124 commits into
cytomining:mainfrom
alxndrkalinin:perf/fast-null
Draft

alxndrkalinin wants to merge 124 commits into
cytomining:mainfrom
alxndrkalinin:perf/fast-null

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

copairs spent most of its time in three places: permuting a null_size x total
matrix for every null configuration, gathering both rows of every pair to
compute a similarity, and lexsorting all pairs to build rank lists. This PR
replaces each with an exact, parallel computation (Numba on CPU, CuPy on GPU)
and keeps the old code behind method="legacy". It also merges #151 (joint
mAP null, @shntnu) and adds a label-permutation mAP null, the new default,
both as Numba kernels.

What changes

  • copairs.nulls: AP nulls are sampled exactly from a counter-based Philox
    stream with Vitter's Algorithm A (gap per positive), in O(1) memory per
    sample. Sample j of (num_pos, total) depends only on
    (seed, num_pos, total, j); NumPy, Numba and CUDA return identical bits.
    Long gaps use a certified closed-form search, and the GPU steps in float32
    with an exact float64 fallback; neither changes a single sample.
  • p-values (compute.p_values, get_map_pvalue, mean_average_precision*)
    stream nulls in chunks under a memory budget; the on-disk cache is only used
    by method="legacy".
  • copairs.fastap: per-pair similarity kernels and AP by counting (rank of the
    t-th positive = t + negatives with a smaller key), equal to rank-list AP to
    float64 rounding for the same similarities; draw_average_precisions for
    batched query-vs-reference draws.
  • Multilabel: inverted label index for find_pairs_multilabel (SQL fallback
    for inputs it cannot represent exactly) and per-label AP by counting.
  • normalize_ap: vectorized, bitwise equal to the scalar formula.

mAP nulls (null=)

The paper's null hypothesis is that a group's profiles and its references come
from the same distribution. copairs <= 0.5.5 approximated the mAP null by
averaging the members' AP nulls, and members with equal pair counts share one
draw (#151), so that null is one AP's null and does not narrow with
replicates. mean_average_precision, mean_average_precision_hierarchical
and get_map_pvalue now take null=:

  • "permutation" (default of method="fast") tests the null hypothesis
    itself: within each block of members ranked against the same references
    (e.g. a plate's replicates and controls), a draw relabels a uniform subset
    of the block's profiles and recomputes the mAP from the observed
    similarities. For multilabel APs (multilabel.average_precision) a draw
    moves the group's label to other profiles of its components of the
    negative graph, which keep their other labels: a receiver ranks the other
    receivers against its own negatives plus the profiles that share only the
    moved label with it. Each group's positives must be its other members.
    nulls/permutation.py finds blocks by hashing negative sets in one pass,
    builds each pool's rank codes and ranks once, and per draw gathers each
    slot's codes branch-free, sorts the drawn profiles once and walks them in
    rank order, in parallel from Philox streams. Opt-in stop_after=h stops a
    group's draws at the h-th one reaching its mAP and reports h / draws
    (Besag and Clifford's sequential p-value); draws run in fixed doubling
    rounds, so p-values do not depend on threads.
  • "joint" (from fix: sample the mAP null jointly over a group's members #151): a positive pair inside a group is one random number
    in both members' rank lists; other similarities are independent.
    nulls/joint.py samples it in parallel from Philox streams, placing
    negatives between consecutive positives by binomial draws (inversion /
    BTRS), so the cost does not depend on the number of negatives. Replicate
    groups that differ only in row order share a signature.
  • "copied": the 0.5.5 null at the fast method's speed; the only null of
    method="legacy", which stays bitwise 0.5.5.

The permutation null needs the pairs and similarity the APs came from.
average_precision and multilabel.average_precision attach them to the
frame they return (frame.attrs["copairs_pairs"]), so
mean_average_precision(ap, ...) needs nothing extra. The handle is shared
by pandas' copies (pandas deep-copies attrs on every operation), serializes
as {} (to_parquet writes attrs as JSON) and pickles to an empty handle,
and it equals only itself, so concatenating frames of different AP calls
drops it while pieces of one frame keep it (checked on pandas 2.3.3 and
3.0.6). A frame without pairs raises under the default null and says what to
do: recompute, pass pairs= (return_pairs=True also returns them), or
choose null="joint" / "copied". The pairs hold a reference to the
features, not the kernel: the kernel (on the GPU with backend="cuda") is
rebuilt on first use with the AP call's backend and distance, so
similarities equal the AP stage's, and released after each p-value call.

pos_pairs (from #151) now has to agree with n_pos_pairs: #151 documented
find_pairs(meta, ...), which returns meta's index labels while the AP frame
is indexed by position, so a meta with a gapped index silently gave wrong edges.

Calibration on data with no effect (fraction of null groups with p <= 0.05;
NTC = inert KO guides, katamari embeddings centred per well, scored through
average_precision + mean_average_precision, half the guides as groups and
half as experiment-matched controls, then swapped):

null data copied joint permutation
iid profiles, 512-d, 20 replicates, 100 controls each (1,000 groups) 0.000 0.061 0.055
profiles with hubs (uncentred, varying norm), 20 replicates (1,000 groups) 0.044 0.260 0.062
iid, plate-matched, 24-40 controls per plate (2,400 groups) 0.087 0.047 0.049
NTC guide-well profiles, 4 wells per guide (211 guides) 0.043 0.052 0.057
NTC guide-well profiles, all wells, median 14 (211 guides) 0.024 0.071 0.081
NTC cells, 20 of one guide in one well (4,000 draws) 0.133 0.683 -
independently assigned multilabel targets, 300 profiles (test) - - uniform (KS)

On 40,000 fresh hub groups (20 replicates, 100 controls, 64-d, null 1e3)
the permutation null gives 0.0104 / 0.0502 / 0.0999 at 0.01 / 0.05 / 0.10, and
its p-values match an independent NumPy implementation of the same test
(mean difference +0.0001 +- 0.0004 over 800 blocks).

The joint null is exact for independent similarities but too narrow on real
embeddings (at p <= 0.01 on hubs: joint 0.199, permutation 0.012); the copied
null is conservative for equal pair counts and too narrow when they differ.
Permutation p-values are exact under exchangeability. The NTC 0.081 is 1.6
SE above nominal, and split-half p-values of the same guides barely correlate
(Spearman 0.09, p = 0.17), so it may reflect small guide effects rather than
miscalibration. Cells of one well are not exchangeable with other cells: such
groups need whole units permuted, which this PR does not do. Resolution is
bounded by the number of distinct relabellings (91 for 2 replicates among 12
controls on one plate).

Paper data (2025_Kalinin_mAP rerun)

The paper's pipelines and simulations rerun on this branch (unchanged
analysis code; nulls set at interpreter start):

  • False positives on pseudo-perturbations of negative-control wells, at p <= 0.05:

    design 0.5.1 / copied joint permutation
    cellhealth EMPTY wells, 3,600 groups 0.64% 5.53% 5.39%
    cpg0016 negcons, any negatives, 6,000 groups 4.6-4.8% 4.6-4.8% 4.6-4.8%
    cpg0016, plate-matched negatives (the paper's design) 2.1% 1.65% 5.48%

    On cellhealth, joint's BH families reject in 11.3% of null splits (nominal
    5%), permutation's in 6.7%. A planted shift is found 94.7% of the time by
    permutation vs 83% by copied in the plate-matched design.

  • Real cpg0016 ORF activity, p < 0.05 of 13,739: permutation 11,345,
    joint 10,738, copied 7,433 (0.5.1 pipeline: 7,380).

  • Stability: cellhealth calls flip 1/0/0 between seeds at null
    1e4/1e5/1e6 for permutation (0.5.1: 7/15/0).

  • legacy: matches 0.5.1 bitwise everywhere.

  • Simulations (Fig 2, S2-S5; the paper's own copied-style mAP null on
    get_null_dists): the fast sampler shifts recall by +0.0008 to +0.0046
    vs 0.5.1, with 70-94% of configurations identical. The fast sampler's AP
    atoms are the correctly rounded float32 values; 0.5.1's are off by a few
    ulp for 16-37% of atoms, mostly upward, which under the paper's strict >
    counts tied null values against the observed mAP.

  • Cost: cellhealth step 3 at null 1e6 takes 1,577 s with permutation vs
    35-68 s for the other nulls. stop_after=10 brings it to 427 s and stays
    calibrated (5.58% of control groups at p < 0.05, vs 5.39% full), but 8 of
    300 groups change their BH call between two seeds (0 with the full null at
    1e5 and 1e6), so it stays opt-in.

  • Where the permutation null raises:

    • pipelines that save AP tables between steps (cpg0004);
    • frames whose index was reset after filtering (cpg0016 step 1);
    • groups whose positives lie outside them (perturbseq bulk: one profile per
      guide, positives by gene). Moving one profile among 10 controls has 11
      relabellings, so p could never go below 1/11; the error now points to
      , which for a one-profile group is that profile's AP null
      (and no longer falls back to the copied null with a warning).

Behavior changes (method="fast", the new default)

  • mAP p-values use the permutation null (above) instead of the copied one.
    AP frames carry their pairs; frames without them (hand-built, reloaded,
    pickled, concatenated across AP calls) raise under the default null.
  • Different random stream: AP p-values agree with 0.5.5 within Monte Carlo
    error.
  • mAP p-values count null values >= the mAP (the paper's definition). 0.5.5
    counted >, which made p-values too small when the mAP equals a null atom:
    with one positive among 100 ranks, perfect retrieval got p = 1/(null_size+1)
    instead of 0.01.
  • Kernel similarities match the generic functions to float32 rounding, so
    near-tied pairs can rank differently.
  • numba becomes a dependency. CuPy is optional (README).

Benchmarks (L40 node, 16 CPU threads)

workload 0.5.5 fast, Numba fast, CUDA
null (3, 213), 5M samples 18.3 s 0.089 s 0.017 s
null (99, 1099), 1M samples 18.9 s 0.28 s 0.021 s
activity AP, 9k profiles, 8M neg pairs, 500-d 9.0 s 0.76 s 0.75 s
activity mAP p-values, 2000 groups, null 1e6 17.7 s 0.58 s 0.09 s
consistency AP, 5000 genes x 400 complexes 77 s 1.2 s 1.2 s
consistency mAP p-values, 1168 configs, null 1e5 ~2.3 h single-thread (est.) 66 s 14 s
draw AP, k=100, m=1000, d=1024 (per draw) 9.1 ms 2.3 ms 0.058 ms

mAP nulls (8 CPU threads, shared login node):

workload #151 (NumPy) joint, Numba permutation
one signature, 4 replicates, 100 or 5,000 negatives, 1e5 samples 0.21-0.27 s 0.011 s 0.005-0.011 s per group
one signature, 20 replicates, 1e5 samples 3.5-4.9 s 0.29-0.41 s -
1,000 groups of 20 replicates, 100 controls each, null 1e4 - 0.17 s 13.4 s
2,400 groups, plate-matched controls, null 1e4 0.13-0.18 s 0.11-0.14 s 1.8-1.9 s
1,000 groups vs 2,000 shared controls, null 1e4 0.09 s 0.04 s 2.9 s

With stop_after=10, 1,000 groups of 20 hub profiles take 2.6 s at null 1e4
(13.8 s without) and 2.6 s at 1e5 (119 s); 98-99% of calls at 0.05 agree with
the full runs.

Permutation cost per draw grows with group size: one thread, 0.37 us for 4
members among 100 references, 7.9 us for 20 (11.3 us among 2,000), 260 us for
100. The rewrite in this PR cut those from 0.8, 27.9 (48.6) and 986 us with
bitwise-equal draws; the remaining cost is mostly sorting each member's
drawn profiles.

Bugs found in 0.5.5

  • get_map_pvalue strict > (above), and the copied mAP null (fix: sample the mAP null jointly over a group's members #151).
  • _create_neg_query_solver gives a profile without negatives its neighbor's
    negatives (searchsorted on a missing key).
  • get_null_dists seeds configurations by list position (rng.integers(8096))
    but caches by configuration, so a cached null depends on the run that made it.

Testing

  • 265 passed, 5 skipped CPU-only (the skips are 3 CUDA and 2 pyarrow tests);
    earlier 194 passed, 2 skipped on an L40 node with all CUDA backends. CI has
    no GPU, so CUDA tests skip there. The new nulls run on the CPU only.
  • Bitwise CPU/GPU parity of null samples, including adversarial uniforms at decision boundaries of both accelerated gap paths (0 mismatches in 240k cases each; the check reports 113,681 mismatches when the margin is set to 0).
  • Brute-force equality of streamed p-values; rank-list equality of counting AP (ties, NaN, self/duplicate pairs); SQL-path equality of multilabel pair sets.
  • Joint null: same law as fix: sample the mAP null jointly over a group's members #151's NumPy sampler (KS on its configurations),
    the exact AP null for one member, closed-form moments, the 1/9 atom; the
    binomial sampler against scipy.
  • Permutation null: draws match every relabelling of small one-pool and
    plate-blocked layouts recomputed through average_precision, and every
    move of a label recomputed through multilabel.average_precision
    (values and frequencies, including a pair sharing two labels); injected
    kernel bugs fail these tests (three single-label, three multilabel);
    uniform p-values on exchangeable profiles and independently assigned
    labels; rank table and binary search give the same draws; the rewritten
    kernel's draws equal the previous kernel's bitwise on 10 layouts (ties,
    NaN similarities, plates, cross-plate positives).
  • stop_after: stopped p-values equal the value computed from the full,
    ordered draw sequence (single-label, multilabel, stops past the first
    round), and calibrate on exchangeable profiles.
  • Attached pairs: the default null on filtered, re-concatenated, pickled and
    cross-call concatenated frames, and on multilabel frames; pandas 2.3.3 and
    3.0.6.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Jq1AbKhjd5DaGdvBm4AWEz

alxndrkalinin and others added 30 commits October 6, 2026 23:22
The legacy null permutes a null_size x total matrix per configuration:
about 14 ns per element and null_size * total * 2 bytes of memory, e.g.
~9 min and 11 GB for 5M samples of a 1099-long rank list.

copairs.nulls samples the same distribution exactly by drawing the gap
before each positive (Vitter's Algorithm A), one uniform per positive and
O(1) memory per sample. Uniforms come from Philox4x32-10 keyed on
(seed, num_pos, total) with the sample index as counter, so a null does
not depend on chunking, thread count, or the other configurations in a
run. The NumPy, Numba and CUDA (CuPy) backends perform the same IEEE
double operations and return bitwise-identical samples.

ap_pvalues and map_pvalues regenerate nulls in sample chunks within a
memory budget and count null >= score in float64, treating values within
TIE_TOL as ties so a null rank list equal to the observed one counts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
get_null_dists, compute.p_values, average_precision.p_values,
get_map_pvalue, mean_average_precision and
mean_average_precision_hierarchical take method="fast" (default) or
"legacy", and backend="auto"|"cuda"|"numba"|"numpy".

The fast method changes results within Monte Carlo error: it draws a
different (counter-based) random stream, and mAP p-values now count
group nulls >= mAP instead of > mAP. The strict comparison made p-values
too small whenever the observed mAP equals an atom of the null: with one
positive among 100 ranks, perfect retrieval got p = 1/(null_size + 1)
although P(AP >= 1) = 0.01. The fast method also skips the on-disk cache,
since regenerating a null is faster than reading it. method="legacy"
reproduces copairs <= 0.5.5.

numba becomes a dependency; the NumPy backend is a reference
implementation about as slow as the legacy sampler. The CUDA backend is
used when CuPy is installed and sees a GPU.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
CuPy raises CUDARuntimeError for a missing device or an insufficient
driver, and RuntimeError when the CUDA runtime library cannot be loaded.
Both mean the CUDA backend is unusable, so catch the common base class
and fall back to the CPU backends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
normalize_ap evaluated expected_ap in a Python loop per profile, and each
call summed L terms of the harmonic series in Python: O(n_profiles * L)
interpreter work, ~1 s for 20k profiles with L ~ 1500, and minutes for
cell-scale inputs.

expected_ap_array evaluates each distinct (M, N) once and reads H_L from
a table built with the same summation sum() performs (Neumaier-
compensated from Python 3.12, sequential before), so results are equal
to the scalar formula bit for bit on every supported Python.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
average_precision spent its time gathering both rows of every pair to
compute a similarity (4.6 s for 8M pairs of 500-d profiles) and
lexsorting every pair to build rank lists (3.5 s), while the copairs
work it feeds is O(pairs).

copairs.fastap normalizes each profile once and takes one dot product
per pair (cosine, abs_cosine, correlation; euclidean, manhattan and
chebyshev directly), and computes AP by counting: the t-th positive of
a profile sits at rank t + #{negatives with a smaller key}, found by
binary search into the profile's sorted positive keys. Keys and tie
order are those of build_rank_lists, so AP equals the rank-list AP to
float64 rounding for the same similarities. Numba and CUDA backends.

On the benchmark above average_precision drops from 9.0 s to 0.75 s.
method="legacy" (or backend="numpy") keeps the previous path; kernel
similarities match it to float32 rounding, so near-ties can reorder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
Cell-level designs score many draws of k query cells against m
reference cells, each by sorting a (k, k + m) similarity matrix row by
row: ~9 ms per draw at k=100, m=1000, d=1024, so tens of thousands of
draws (and the control-vs-control draws of an empirical null) take
minutes.

draw_average_precisions computes a chunk of draws' similarities in one
batched matrix product and each query's AP by counting the references
above each of its sorted positives (ties: queries first). It equals the
full-sort AP to float64 rounding. Measured at k=100, m=1000, d=1024:
2.3 ms per draw with Numba on 16 threads, 0.058 ms on an L40.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
For 5000 profiles with 1-3 of 400 labels each, multilabel
average_precision took 77 s: 47 s in the SQL query for pairs sharing no
label (a list intersection for every row pair), 11 s deduplicating 12M
negative pairs with np.unique(axis=0), and 8 s in per-label lexsorts.

find_pairs_multilabel now builds an inverted label index for DataFrames
with a default index: pairs sharing a label come from each label's
members, and pairs sharing none are all other candidate pairs (or the
monolabel pairs of the remaining columns). Inputs it cannot represent
exactly fall back to SQL. The pair sets are unchanged; order was never
specified. The fast method computes each (label, profile) AP by counting
against the profile's negatives, equal to the legacy loop to float64
rounding. The same benchmark takes 1.2 s.

Unlike the legacy loop, a profile without negatives gets zero
negatives; _create_neg_query_solver's searchsorted gave it a neighbor's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
Algorithm A steps one rank at a time to the next positive, so a sample
costs O(total) however few positives it has: 1M samples of (2, 5000)
take ~1 s, and multilabel nulls, with many (few, ~5000) configurations,
dominate the run.

When the expected gap is long (total - k > 32 k (k + 1)), the gap is
found by exponential and binary search on the closed form
log P(G > g) = sum_t log1p(-(g + 1) / (total - t)). A probe trusts the
closed form only when it clears log(u) by more than its error bound
(1e-9 plus the product's rounding) and otherwise replays Algorithm A's
product exactly, so the gaps, and the samples, are unchanged on every
backend. 1M samples of (2, 5000) now take 9 ms (Numba) / 5 ms (L40).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
GPUs like the L40 run float64 at 1/64 of the float32 rate, and the null
kernel's gap loop is one float64 multiply and divide per rank.

gap_loop_f32 steps the product in float32 and decides each step only
when the float32 product clears u by twice its error bound relative to
Algorithm A's float64 product, (2 g + 1) 2^-24 plus the roundings of the
thresholds. Inside the band it replays the float64 product and finishes
in float64, so gaps are unchanged; the tests' bitwise CPU/GPU parity
holds. On an L40: 5M samples of (99, 1099) 0.41 s -> 0.11 s; multilabel
mAP nulls for 1168 configurations at null_size=1e5 32 s -> 14 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
Document method/backend, what the fast path changes relative to
copairs <= 0.5.5 (random stream, >= ties in mAP p-values, float32-level
similarity differences), and how to install CuPy for the CUDA backend.
CuPy stays out of the extras: CI syncs with --all-extras, which cannot
resolve conflicting cuda12/cuda13 extras.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The guided search's undecidable band includes Algorithm A's rounding
bound, (2g + 2) eps, which grows with the gap. From totals of ~1e8 the
last probes all fall inside it and replay the O(g) product, so the
search took twice as long as stepping (measured at total 1e9, k=2).
Totals that large fall back to stepping; results are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
GUIDED_RATIO * k * (k + 1) could overflow int64 (undefined behaviour in
the CUDA kernel) for k >= 2**29, and the log1p margin assumes few
positives. The total cap is evaluated first, so k <= total < 2**26 keeps
the product within int64, and the guided condition then implies
k < 1449. Say so where the constant is defined.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
A score whose conf_ix pointed past confs fell outside every CSR segment
and kept a zero exceedance count, returning p = 1 / (null_size + 1)
instead of raising. Check lengths and the index range up front.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
An empty last group made np.add.reduceat raise IndexError before the
"every group needs a member" check ran. Validate the CSR pointers
(start, end and non-empty groups) first, with a ValueError.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
With every AP NaN or without positives, the fast get_map_pvalue tried to
concatenate zero index lists and failed with a dtype cast error (the
legacy path divides by zero). Return the empty table with a p_value
column, which the FDR step passes through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The inverted-index matcher took np.unique over an object array, so
integer labels came back as an object array of keys where the SQL path
returns integers. Convert non-string keys to a numeric array.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
Distinct AP values are not always farther apart than 1e-10: with 2
positives among 5000 ranks some differ by 9e-13. Say that such null
values count as ties and why the effect on p-values is negligible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The GPU path sorts positives by a 64-bit key packing the profile index
into the high 32 bits, which aliases from 2**32 profiles on. Use the
Numba path there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
statsmodels < 0.15 (0.14.5 is locked) divides by zero in multipletests
for an empty p-value array, so mean_average_precision failed on an
empty mAP table even though the fast path now returns one. Return empty
corrected p-values instead, for both standard and hierarchical FDR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
numba is a required dependency and other modules already import it
without a guard, so the ImportError fallback and the `numba is not None`
blocks were dead code; pvalues also imported numba through sampler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
CPU_BACKENDS was never used, and to_numpy was a no-op since ap_nulls
always returns NumPy arrays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The chunk size was read back from the first element of a chunk list
built for that purpose; compute it from the budget instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
compute.p_values already calls _get_null_dists_legacy; get_map_pvalue
went through get_null_dists(method="legacy") and its re-dispatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
map_pvalues and ap_pvalues called the sampler once per sample chunk,
and each call re-validated the configurations and re-derived every
Philox key in a Python loop (~4.7 us per configuration): ~16 s of host
work for 9.5k configurations at null_size 5e6. null_plan computes
(num_pos, total, k0, k1) once; the chunk loops slice it, and the CUDA
backend uploads it to the device once instead of per chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
average_precision and multilabel.average_precision each repeated the
same block: check the method, resolve the backend, map "numpy" to the
legacy path, and wrap a similarity kernel in a closure. Draws mapped
"numpy" to Numba instead, so the same backend name meant different
things per entry point.

fastap.setup does it once and returns (method, backend, similarity_fn);
fastap re-exports copairs.nulls.resolve_backend instead of wrapping it.
draw_average_precisions, which has no NumPy implementation, now rejects
backend="numpy".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
fastap.multilabel._profile_csr was a copy of ranking._positive_csr
without the final per-profile sort, and that sort ran serially (1.07 s
of 1.40 s for 1e6 profiles and 2e7 pairs). pair_csr builds the layout
once for both, and _positive_csr sorts the segments in a parallel
kernel: 0.60 s for the same input on 8 threads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The loop turning per-gap negative counts into AP was written out three
times (pair AP, multilabel AP, draw AP). ap_from_counts inlines the
same operations in the same order, so results are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
The fast get_map_pvalue rebuilt group membership by flattening the
per-group index lists of the legacy `indices` column, which needed a
special case for empty input (np.concatenate of nothing). Group codes
from groupby().ngroup() give the same (group, configuration) table
directly; rows with missing keys belong to no group, as in the agg.
map_pvalues now returns no p-values for no groups itself, which also
avoids a zero-sized CUDA grid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cx9huqMhgJWvKm52zFPMxu
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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.
cytomining#150 has the same gap (its permutation null never reads pos_diffby).
Reported by Copilot on cytomining#156 (comment 4355275983).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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 cytomining#150 (46cb8b0, ea1fc1c), with the lone pairs found by
find_pairs_multilabel instead of cytomining#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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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 cytomining#150 (46cb8b0), with NumPy in place of numba and a
pos_diffby check cytomining#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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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 cytomining#150.

Ported from cytomining#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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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 cytomining#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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
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 cytomining#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
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
_label_key copied stream_key's blake2b digest and split for its text
"(seed, members)/label", and permutation.py imported hashlib for it
alone. stream_key now takes an optional suffix appended to its text, so
the label key is stream_key(seed, members, "/label"): the same text and
keys as cytomining#150's (pinned in the test), and single-label keys unchanged.

Reported by the /simplify of PR 3 (cytomining#157) (S2, R1, A7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 23, 2026
Under Numba each group ran its draws as one task of up to 2**16 draws, so
on pool threads (many groups) the largest group ran alone on one thread
while the others idled. On PR 3's multilabel bench (351 labels, the
largest on 259 profiles, 16 CPUs) the 1e4 label null took 23 s, as long
as that label's serial draws, and only 1.25x less than NumPy.

Groups on pool threads now run tasks as large as NumPy's chunks
(_draw_chunk: 2**22 // n**2 draws, 256 to 2**16), so threads share a
large group's draws. Draws on Numba's threads (few groups) keep 2**16 per
launch, and rounds of stop_after, which run one at a time, still double
up to 2**16 (_Hits' new rounds=). P-values do not change: draw j does not
depend on the tasks.

Same node, label bench at 1e4 without stop_after: 23.4 -> 4.7 s
(consistency), 22.8 -> 4.9 s (null labels), 23.3 -> 5.9 s (plates);
cytomining#150 3.9 s.

The new test fails on the previous code (one task for the 30-member
group) and on the chunk change alone (stop_after rounds capped at 4660).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
alxndrkalinin added a commit to alxndrkalinin/copairs that referenced this pull request Oct 24, 2026
The permutation null recomputes a Numba AP stage's similarities in
hundreds of small calls from its pool threads, each a parallel launch
under the launch lock, about 5x slower than cytomining#150's (0.031-0.035 s against
0.005-0.007 s on cellhealth). pair_similarity(parallel=False) runs serial
nogil kernels on the calling thread instead, without the lock. Both forms
call one per-pair function, so they give the same bits: tested over every
metric, float32/float64/int64 rows and d in 1, 7, 37, 300; the parallel
kernels' bits are unchanged (1.8M similarities, d up to 1000, digest equal
to the previous commit's), and a serial kernel without reassociation
differs for int64 rows (34-479 of 20,000), which the test covers.
Concurrent first calls build one kernel (one copy of the features).

The null's pool threads no longer launch parallel kernels for a Numba AP
stage, so 8f11f57's Numba thread setup for them under the NumPy null goes;
its test now checks that the null calls no parallel similarity kernel
(it failed before: _dot_pairs called from the null).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7
afermg added a commit that referenced this pull request Oct 31, 2026
* 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

* fix: check the seed and null size before raising on no valid AP scores

get_map_pvalue raises UnpairedException when no AP score is valid, and
its seed and null size were only checked downstream, by the nulls, so an
empty table hid a bad value. They are now checked with the other
arguments, before the filter: null_size by check_null_size, the seed by
the new nulls.common.check_seed under the joint and permutation nulls
(Philox seeds, [0, 2**64)) and as non-negative under the copied null,
whose NumPy seeding takes any non-negative int.

_copied_pvalues no longer returns an empty array for no groups: it is
only called with at least one group now.

Tests: every null and both entry points raise on AP frames with pairs
attached and no valid AP score; bad arguments raise their ValueError on
an empty frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* test: give the hierarchical raise tests a proper sameby superset

hierarchical_by must be a proper subset of sameby, so the hierarchical
cases of the new empty-input tests group by g and a constant h.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: say why the consistency example keeps the copied null, and rerun it

Its multilabel APs carry no pairs in this PR, so the default permutation
null cannot run on them; part 3 (#157) switches it. Rerun on the new
activity_map.csv: 55 of 58 compounds are now active, and 5 of 28 targets
are consistent (AURKA joins DRD2, EGFR, HTR3A and PSMB1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: use the default permutation null in the activity and null size examples

phenotypic_activity drops null="copied" and says what the permutation
null of a compound's mAP relabels; the replicate AP p-values keep their
own null, and the text now says so. 55 of 58 compounds are active.

null_size recomputes the APs (the saved CSV has no pairs) and counts the
permutation null's relabellings, C(m + n, m) = 593,775 for 6 replicates
among 24 DMSO, instead of the copied null's per-AP rank lists. The
p-values of the compounds with mAP = 1 follow the expected floor
(1 + null_size/d) / (null_size + 1). The grid up to 5e6 runs in about
3.5 minutes on 16 CPUs, so it is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: add an example comparing the three mAP nulls

null_comparison runs the permutation, joint and copied nulls on the
activity plate's APs at null_size 1e6, seed 0: 55, 55 and 50 of 58
compounds active, in 33 s, 19 s and 0.7 s. It plots their p-values
pairwise and explains where they differ. As a negative control with
known truth, 100 pseudo-groups of 6 DMSO profiles ranked against 12
others: p < 0.05 for 5%, 5% and 1%. Listed in the docs nav and the
examples README.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: drop the tqdm notebook-mode warning from example outputs

The warning is environment noise and printed the local path of the
machine that ran the notebooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: list the null comparison example in the README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* fix: raise UnpairedException when no AP row has its sameby keys

Rows with a missing sameby value fall out of the groupby, so a frame
whose valid APs all lack a key gave no groups: the copied null then
failed in np.concatenate, while the joint and permutation nulls
returned an empty table. No groups means no usable AP scores, so raise
the error the empty-table check raises, under every null (Copilot on
#156).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: say how the permutation null ranks relabelled profiles

The docs said draws recompute the mAP "with the same pair rules". A
draw ranks each labelled profile against the block's unlabelled pool
profiles, as the observed members rank their references, so the
statistic is the same function of every labelling; the negative rules
are not re-applied to relabelled metadata. That is what control-flag
columns in neg_diffby (Metadata_negcon, pert_type, control indices in
the paper's experiments) need, but a layout column there is not
enforced for relabelled profiles. Say so, and point such designs to
the joint or copied null (Copilot on #156).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* refactor: check the seed range where the nulls resolve the seed

resolve_seed's docstring said config_key_arrays checks the range, but no
null path calls config_key_arrays, so permutation_pvalues and
joint_pvalues accepted any int seed when called directly. resolve_seed
and config_key_arrays now both call check_seed, the one copy of the
[0, 2**64) rule and its message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* refactor: drop rows without sameby keys before the empty-input check

The groupby drops rows with a missing sameby value, so a frame whose
valid rows all lack a key needed a second UnpairedException after the
groupby. Dropping those rows with the invalid APs makes the one check
cover both cases, with the message the Raises sections already give.
The nulls only read the rows of groups, so p-values are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* test: drop the joint seed case that repeats the default null's

seed=-1 under null="joint" and under the default permutation null take
the same check_seed branch of get_map_pvalue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: index the null comparison's mAP tables once

The comparison cells re-indexed each null's mAP table by compound three
times, and the calibration table grouped the control's p-values by null
three times. Outputs are unchanged: the re-executed notebook in the
next commit gives the same p-value, calls and calibration tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: run the null comparison's negative control at 10^5 draws

Each DMSO pseudo-group's permutation null has C(18, 6) = 18,564
relabellings, so 10^6 draws per test bought nothing for p near 0.05
and made the 300 control tests most of the notebook's runtime. At 10^5
the calibration table is unchanged and the notebook runs in 83 s on 16
CPUs instead of 302 s. The comparison of the three nulls keeps 10^6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* fix: keep the indices positions of rows without sameby values

83058cf dropped rows missing a sameby value before reset_index, which
shifted the positions in the returned `indices` column against main
for any frame with such rows. One mask now filters the invalid APs as
before, and the empty-input check counts only rows that also have every
sameby value, so a single UnpairedException still covers both cases.
The mask also replaces the query and dropna copies of the frame.

The docstring called `indices` positions in the original ap_scores;
on main and here they are positions after the invalid APs are dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* perf: drop the copy after reset_index in get_map_pvalue

Under pandas 2, reset_index(drop=True) already returns an unshared copy
(measured: no shared memory, no SettingWithCopyWarning on the column
assignment that follows), so .copy() held a second full copy of the AP
frame. Under pandas 3 copy-on-write it was a lazy copy anyway.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* fix: reject non-integer seeds before the nulls truncate them

check_seed tested only the range, so seed=1.5 passed and resolve_seed
truncated it to the nulls of seed 1; under the copied null it passed
the sign check and failed late in NumPy (or, on an empty frame, raised
UnpairedException instead). Both checks now also require an integer,
as check_null_size does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: say the null comparison's control CIs assume independent tests

The two pseudo-groups of a split share their references and all splits
draw from the same 24 DMSO profiles, so the binomial intervals are too
narrow and the control cannot separate the copied null's 1% from the
others' 5% either.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* docs: say the null size table's smallest p-values carry Monte Carlo noise

From 5e5 draws on, the mean p-value of the 5 mAP = 1 compounds lies
below the expected p_min (e.g. 1.6e-6 against 2.68e-6 at 1e6), which
the text called following it. Each p-value counts only 0.8 to 8.4
expected draws of the observed relabelling. Over 20 seeds at 1e6 the
5 compounds drew it 185 times against 168.4 expected (Poisson p =
0.22), so seed 0 is a low draw, not a biased sampler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* fix: stop threads waiting for pool memory when a permutation run fails

When a group raised, permutation_pvalues cancelled the queued groups,
which then never released their pools. A thread waiting for pool memory
could depend on such a pool: two waiters race when a pool is freed, and
a later pool can be built first while its other groups are still
queued. The waiter then waited forever, and the executor's exit hung
instead of raising the group's error. The run now aborts its shared
pools on failure, which wakes the waiters and makes them, and any later
pool build, raise CancelledError.

The test forces that race with pool sizes and events; without the
abort it hangs (reported by Copilot on #156).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* perf: take SciPy metric diagonals from cdist blocks of 64 rows

_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 #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

* fix: reject repeated AP row numbers under the pairs-based nulls

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 #156).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CJJk7R7WP15tsAyfVvnwK7

* test: let the blocked-cdist test's recorder take metric by keyword

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

* fix: enforce reviewed mAP null and provenance contracts

* docs: prepare breaking 0.6.0 migration and package validation

* refactor: use pair dictionaries without provenance tracking

* test: trim redundant validation matrices and consolidate regressions

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Shantanu Singh <shsingh@broadinstitute.org>
Co-authored-by: Alán F. Muñoz <afer.mg@gmail.com>
afermg added a commit that referenced this pull request Nov 1, 2026
* 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…

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants