data-beans 0.14.1

Sparse genomics data backends, QC, algorithms, and simulation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
use super::cell_pair_units::{
    place_cell_pairs_on_sample_tree, split_cell_reads_over_pair_units_without_double_counting,
};
use super::cross_batch_matched_fold::{delta_as_base_of_every_node, estimate_fold_on_pseudobulks};
use super::pseudobulk_sums::{sum_by_pseudobulk, PseudobulkKeys, PseudobulkSums};
use super::*;
use crate::sparse_io::{create_sparse_from_triplets, SparseIoBackend};
use crate::sparse_io_vector::SparseIoVec;
use nalgebra::DMatrix;
use std::sync::Arc;

fn data_from(dir: &std::path::Path, tag: &str, x: &DMatrix<f32>) -> SparseIoVec {
    let mut trip = Vec::new();
    for c in 0..x.ncols() {
        for g in 0..x.nrows() {
            if x[(g, c)] != 0.0 {
                trip.push((g as u64, c as u64, x[(g, c)]));
            }
        }
    }
    let path = dir.join(format!("{tag}.zarr"));
    let mut b = create_sparse_from_triplets(
        &trip,
        (x.nrows(), x.ncols(), trip.len()),
        Some(path.to_str().expect("utf8")),
        Some(&SparseIoBackend::Zarr),
    )
    .expect("backend");
    b.register_row_names_vec(
        &(0..x.nrows())
            .map(|g| format!("g{g}").into())
            .collect::<Vec<_>>(),
    );
    b.register_column_names_vec(
        &(0..x.ncols())
            .map(|c| format!("c{c}").into())
            .collect::<Vec<_>>(),
    );
    let mut v = SparseIoVec::new();
    v.push(Arc::from(b), None).expect("push");
    v
}

fn rule(n_labels: usize, min_spans: usize, min_pseudobulks: usize) -> BatchSpanningRule {
    BatchSpanningRule {
        n_labels,
        min_spans,
        min_pseudobulks,
    }
}

/// Every unit its own pseudobulk (in its batch and node), summed from `data`.
fn units_as_pseudobulks(
    data: &SparseIoVec,
    batch: &[usize],
    coords: &DMatrix<f32>,
) -> PseudobulkSums {
    let n = batch.len();
    let key: Vec<Option<(usize, usize, usize)>> = (0..n).map(|u| Some((u, batch[u], 0))).collect();
    let own: Vec<usize> = (0..n).collect();
    sum_by_pseudobulk(
        data,
        &PseudobulkKeys {
            key: &key,
            batch,
            span_label: batch,
            coarsest: &own,
            coords,
        },
    )
    .expect("sums")
}

/// Each pair's spanning key: (its pb pair, its label).
fn count_keys(pb: &[usize], label: &[usize]) -> Vec<(usize, usize)> {
    pb.iter().copied().zip(label.iter().copied()).collect()
}

/// Two tight, far-apart clumps: Ward's root splits them.
#[test]
fn ward_root_splits_two_clumps() {
    let pts = DMatrix::from_row_slice(5, 1, &[0.0, 0.1, 0.2, 10.0, 10.1]);
    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    let (a, b) = t.children[t.root].expect("root splits");
    let mut sides = [t.leaves(a), t.leaves(b)];
    sides.iter_mut().for_each(|s| s.sort_unstable());
    sides.sort();
    assert_eq!(sides, [vec![0, 1, 2], vec![3, 4]]);
    assert_eq!(t.parent[t.root], t.root);
}

/// A node is split only if both children span; a root that does not span
/// leaves every group without a node.
#[test]
fn cut_splits_only_where_both_children_span() {
    let pts = DMatrix::from_row_slice(4, 1, &[0.0, 0.1, 10.0, 10.1]);
    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    // groups 0,1 hold both batches; groups 2,3 only batch 0
    let both = vec![vec![5, 5], vec![5, 5], vec![5, 0], vec![5, 0]];
    let r = rule(2, 2, 3);
    let cut = t.cut_where_both_children_span_batches(&both, &r);
    assert!(
        cut.iter().all(|n| *n == Some(t.root)),
        "one side fails: no split"
    );

    // each group alone is too thin, each clump of two spans
    let all = vec![vec![2, 2]; 4];
    let cut = t.cut_where_both_children_span_batches(&all, &r);
    assert_eq!(cut[0], cut[1]);
    assert_eq!(cut[2], cut[3]);
    assert_ne!(cut[0], cut[2]);

    let thin = vec![vec![1, 0]; 4]; // one batch only, even at the root
    assert!(t
        .cut_where_both_children_span_batches(&thin, &r)
        .iter()
        .all(Option::is_none));
}

/// A fold planted per (gene, node, batch) on noiseless data is recovered
/// (as the n/(n−1) contrast),
/// and a node seen in one batch keeps δ exactly.
#[test]
fn matched_fold_recovers_a_planted_fold() {
    let dir = tempfile::tempdir().expect("tempdir");
    let (g, per) = (3usize, 4usize);
    let mu = [[10.0f32, 20.0, 30.0], [30.0, 5.0, 25.0], [8.0, 8.0, 8.0]];
    // fold[node][batch][gene]: geometric mean 1 over batches; equal totals per batch
    let f = [
        [[2.0f32, 0.5, 1.0], [0.5, 2.0, 1.0]],
        [[1.5, 1.0, 1.0 / 1.5], [1.0 / 1.5, 1.0, 1.5]],
    ];
    let mut cols = Vec::new();
    let (mut batch, mut node) = (Vec::new(), Vec::new());
    for (k, fk) in f.iter().enumerate() {
        for (b, fkb) in fk.iter().enumerate() {
            for _ in 0..per {
                cols.push((0..g).map(|j| mu[k][j] * fkb[j]).collect::<Vec<_>>());
                batch.push(b);
                node.push(Some(k));
            }
        }
    }
    for _ in 0..per {
        cols.push(mu[2].to_vec());
        batch.push(0);
        node.push(Some(2));
    }
    let n = cols.len();
    let x = DMatrix::from_fn(g, n, |r, c| cols[c][r]);
    let coords = DMatrix::from_fn(1, n, |_, c| node[c].unwrap_or(0) as f32);
    let log_delta = DMatrix::<f32>::from_row_slice(g, 2, &[0.1, -0.1, 0.0, 0.0, 0.2, -0.2]);
    let x_raw = DMatrix::from_fn(g, n, |r, c| x[(r, c)] * log_delta[(r, batch[c])].exp());
    let data_raw = data_from(dir.path(), "planted_raw", &x_raw);
    let params = StateAwareBatchFoldParams {
        pseudo_count: 0.0,
        min_pseudobulks: 1,
        ..StateAwareBatchFoldParams::default()
    };
    let sums = units_as_pseudobulks(&data_raw, &batch, &coords);
    let node_of_pb: Vec<Option<usize>> = (0..n).map(|pb| node[pb]).collect();
    let log_fold = estimate_fold_on_pseudobulks(
        &sums,
        &node_of_pb,
        3,
        &delta_as_base_of_every_node(&log_delta, 3),
        &params,
    )
    .expect("fold");
    let gf = StateAwareBatchFold {
        n_batches: 2,
        n_nodes: 3,
        log_fold,
        log_delta: log_delta.clone(),
        node_of_unit: node.clone(),
    };
    // a fold is a rate ratio up to the column's scale (the division trait
    // matches it): compare across genes, relative to gene 0
    for (k, fk) in f.iter().enumerate() {
        for (b, fkb) in fk.iter().enumerate() {
            let col = gf.log_fold.column(k * 2 + b);
            for j in 1..g {
                // two batches: the contrast is n/(n−1) = 2 × log f
                let want = (log_delta[(j, b)] + 2.0 * fkb[j].ln())
                    - (log_delta[(0, b)] + 2.0 * fkb[0].ln());
                let got = col[j] - col[0];
                assert!(
                    (got - want).abs() < 1e-4,
                    "node {k} batch {b} gene {j}: {got} vs {want}"
                );
            }
        }
    }
    for b in 0..2 {
        assert_eq!(
            gf.log_fold_at(Some(2), b),
            log_delta.column(b),
            "one-batch node keeps δ"
        );
    }
    assert_eq!(gf.log_fold_at(None, 1), log_delta.column(1));
}

/// Every read lands in exactly one unit; a self-loop holds its own cell's
/// reads only; a pair holds no more than its two endpoints.
#[test]
fn split_conserves_reads_and_keeps_loops_apart() {
    let dir = tempfile::tempdir().expect("tempdir");
    let x = DMatrix::from_row_slice(2, 3, &[5.0, 0.0, 7.0, 3.0, 9.0, 1.0]);
    let pairs = vec![(0, 1), (1, 2), (0, 2)];
    let data = data_from(dir.path(), "split", &x);
    let trip = split_cell_reads_over_pair_units_without_double_counting(&data, &pairs, None)
        .expect("split");
    let mut units = DMatrix::<f32>::zeros(2, pairs.len() + 3);
    for &(g, u, v) in &trip {
        units[(g as usize, u as usize)] += v;
    }
    for g in 0..2 {
        assert_eq!(units.row(g).sum(), x.row(g).sum(), "gene {g} conserved");
        for c in 0..3 {
            assert!(units[(g, pairs.len() + c)] <= x[(g, c)]);
        }
        for (k, &(u, v)) in pairs.iter().enumerate() {
            assert!(units[(g, k)] <= x[(g, u)] + x[(g, v)]);
        }
    }
    let mut keys: Vec<(u64, u64)> = trip.iter().map(|&(g, u, _)| (g, u)).collect();
    keys.dedup();
    assert_eq!(keys.len(), trip.len(), "one triplet per (gene, unit)");
}

/// A pair key that does not span climbs both endpoints; one that never
/// spans, not even at the root, keeps δ.
#[test]
fn pair_nodes_climb_until_they_span() {
    // tree: ((0,1),(2,3))
    let pts = DMatrix::from_row_slice(4, 1, &[0.0, 0.1, 10.0, 10.1]);
    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    let p01 = t.parent[0];
    // 4 pairs (0,0) in batches 0/1 → spans at (0,0); 2 pairs (0,1) in batch 0
    // and 2 pairs (1,1) in batch 1 → each fails, both climb to (p01,p01) and span
    let at = vec![
        Some((0, 0)),
        Some((0, 0)),
        Some((0, 0)),
        Some((0, 0)),
        Some((0, 1)),
        Some((1, 0)),
        Some((1, 1)),
        Some((1, 1)),
        None,
    ];
    let label = vec![0, 1, 0, 1, 0, 0, 1, 1, 0];
    let r = rule(2, 2, 2);
    let (node, keys) = place_cell_pairs_on_sample_tree(
        &t,
        &at,
        &count_keys(&(0..9).collect::<Vec<_>>(), &label),
        &r,
    );
    assert_eq!(node[0], Some(keys[&(0, 0)]));
    assert!(node[..4].iter().all(|n| *n == node[0]));
    let up = Some(keys[&(p01, p01)]);
    assert!(node[4..8].iter().all(|n| *n == up));
    assert_eq!(node[8], None);

    // a lone pair never spans: it climbs to the root and keeps δ
    let (node, keys) =
        place_cell_pairs_on_sample_tree(&t, &[Some((2, 3))], &count_keys(&[0], &[0]), &r);
    assert_eq!(node, vec![None]);
    assert!(keys.is_empty());
}

/// The nearest-neighbour chain builds the same tree as greedy Ward: the same
/// clusters (leaf sets) at every internal node.
#[test]
fn nn_chain_ward_matches_greedy_ward() {
    let (k, dim) = (40usize, 3usize);
    let mut s = 12345u64;
    let mut next = || {
        s = s
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (s >> 33) as f32 / (1u64 << 31) as f32
    };
    let pts = DMatrix::from_fn(k, dim, |_, _| next());

    // greedy Ward, O(K³), as the reference
    let mut members: Vec<Option<Vec<usize>>> = (0..k).map(|i| Some(vec![i])).collect();
    let mut want: Vec<Vec<usize>> = Vec::new();
    let cost = |a: &[usize], b: &[usize]| {
        let mean = |s: &[usize]| {
            (0..dim)
                .map(|c| s.iter().map(|&i| f64::from(pts[(i, c)])).sum::<f64>() / s.len() as f64)
                .collect::<Vec<_>>()
        };
        let (ma, mb) = (mean(a), mean(b));
        let d2: f64 = ma.iter().zip(&mb).map(|(x, y)| (x - y).powi(2)).sum();
        2.0 * (a.len() * b.len()) as f64 / (a.len() + b.len()) as f64 * d2
    };
    for _ in 0..k - 1 {
        let live: Vec<usize> = (0..k).filter(|&i| members[i].is_some()).collect();
        let (mut bi, mut bj, mut best) = (0, 0, f64::INFINITY);
        for (x, &i) in live.iter().enumerate() {
            for &j in &live[x + 1..] {
                let c = cost(members[i].as_ref().unwrap(), members[j].as_ref().unwrap());
                if c < best {
                    (bi, bj, best) = (i, j, c);
                }
            }
        }
        let mut m = members[bi].take().unwrap();
        m.extend(members[bj].take().unwrap());
        m.sort_unstable();
        want.push(m.clone());
        members[bi] = Some(m);
    }
    want.sort();

    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    let mut got: Vec<Vec<usize>> = (k..t.parent.len())
        .map(|nd| {
            let mut l = t.leaves(nd);
            l.sort_unstable();
            l
        })
        .collect();
    got.sort();
    assert_eq!(got, want);
}

/// On a complete graph, Ward along the graph is exact Ward; on a sparse one
/// it still separates far-apart clumps at the root.
#[test]
fn graph_ward_matches_exact_on_a_complete_graph_and_splits_clumps() {
    let (k, dim) = (30usize, 2usize);
    let mut s = 777u64;
    let mut next = || {
        s = s
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        (s >> 33) as f32 / (1u64 << 31) as f32
    };
    let pts = DMatrix::from_fn(k, dim, |r, _| next() + if r < 15 { 0.0 } else { 50.0 });
    let clusters = |t: &CoarseGroupWardTree| {
        let mut c: Vec<Vec<usize>> = (k..t.parent.len())
            .map(|nd| {
                let mut l = t.leaves(nd);
                l.sort_unstable();
                l
            })
            .collect();
        c.sort();
        c
    };
    let exact = CoarseGroupWardTree::build_exact_by_nearest_neighbour_chain(&pts);
    assert_eq!(
        clusters(&CoarseGroupWardTree::build_along_knn_graph(&pts, k - 1).expect("tree")),
        clusters(&exact)
    );

    let sparse = CoarseGroupWardTree::build_along_knn_graph(&pts, 3).expect("tree");
    let (a, b) = sparse.children[sparse.root].expect("root splits");
    let mut sides = [sparse.leaves(a), sparse.leaves(b)];
    sides.iter_mut().for_each(|x| x.sort_unstable());
    sides.sort();
    assert_eq!(
        sides,
        [(0..15).collect::<Vec<_>>(), (15..30).collect::<Vec<_>>()]
    );
}

/// No neighbours means no counterfactual: refused, not a blown-up fold.
#[test]
fn matched_fold_refuses_zero_neighbours() {
    let dir = tempfile::tempdir().expect("tempdir");
    let x = DMatrix::from_row_slice(1, 2, &[3.0, 4.0]);
    let data = data_from(dir.path(), "knn0", &x);
    let params = StateAwareBatchFoldParams {
        knn: 0,
        ..StateAwareBatchFoldParams::default()
    };
    let coords = DMatrix::zeros(1, 2);
    let log_delta = DMatrix::zeros(1, 2);
    let sums = units_as_pseudobulks(&data, &[0, 1], &coords);
    let r = estimate_fold_on_pseudobulks(
        &sums,
        &[Some(0), Some(0)],
        1,
        &delta_as_base_of_every_node(&log_delta, 1),
        &params,
    );
    assert!(r.is_err());
}

/// Pairs reaching the root in different rounds are pooled there: together
/// they span, though neither round's arrivals do alone.
#[test]
fn pairs_reaching_the_root_in_different_rounds_are_pooled() {
    // tree: (((0,1),2),3); root's children are (0,1,2) and 3
    let pts = DMatrix::from_row_slice(4, 1, &[0.0, 0.1, 1.0, 10.0]);
    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    // pair (3,3) in batch 0: one climb to (root,root); pair (0,0) in batch 1: three climbs
    let at = vec![Some((3, 3)), Some((0, 0))];
    let r = rule(2, 2, 1);
    let (node, _) = place_cell_pairs_on_sample_tree(&t, &at, &count_keys(&[0, 1], &[0, 1]), &r);
    assert!(node[0].is_some() && node[0] == node[1], "{node:?}");
}

/// Local swaps: a cell placed in the other state's node moves back to its
/// own state's node, and nodes keep spanning both batches.
#[test]
fn local_swaps_move_a_misplaced_cell_to_its_state() {
    use super::local_swap_refinement::refine_nodes_by_local_swaps;
    let dir = tempfile::tempdir().expect("tempdir");
    // state A expresses gene 0, state B gene 1; 6 cells of each, 2 batches
    let per = 6usize;
    let mut cols = Vec::new();
    let (mut batch, mut node, mut xy) = (Vec::new(), Vec::new(), Vec::new());
    for (state, profile) in [[20.0f32, 1.0], [1.0, 20.0]].iter().enumerate() {
        for i in 0..per {
            cols.push(profile.to_vec());
            batch.push(i % 2);
            node.push(Some(state));
            xy.push(state as f32 * 10.0 + i as f32 * 0.01);
        }
    }
    node[0] = Some(1); // a state-A cell placed in B's node
    let n = cols.len();
    let x = DMatrix::from_fn(2, n, |r, c| cols[c][r]);
    let data = data_from(dir.path(), "swap", &x);
    let coords = DMatrix::from_fn(1, n, |_, c| xy[c]);
    let rule = rule(2, 2, 1);
    let sums = units_as_pseudobulks(&data, &batch, &coords);
    let refined = refine_nodes_by_local_swaps(&sums, &rule, node, 2, &DMatrix::zeros(2, 4));
    assert_eq!(
        refined[0],
        Some(0),
        "the misplaced cell returns to its state"
    );
    assert!(refined[1..per].iter().all(|k| *k == Some(0)));
    assert!(refined[per..].iter().all(|k| *k == Some(1)));
}

/// Pairs reaching one key from different depths are tested together: in
/// the tree (((0,1),2),3), pairs (0,2) start at depth 3 and climb to (p01, 2)
/// at depth 2, where pairs (p01-level) already wait; together they span.
#[test]
fn a_key_reached_from_different_depths_is_tested_once_with_every_pair() {
    let pts = DMatrix::from_row_slice(4, 1, &[0.0, 0.1, 1.0, 10.0]);
    let t = CoarseGroupWardTree::build(&pts).expect("tree");
    let p01 = t.parent[0];
    // key (0,2): depth 3 (leaf 0) — fails alone (batch 0 only) and climbs to (p01,2)
    // key (p01,2): depth 2 — a pair already there in batch 1; together they span
    let at = vec![Some((0, 2)), Some((p01, 2))];
    let r = rule(2, 2, 1);
    let (node, keys) = place_cell_pairs_on_sample_tree(&t, &at, &count_keys(&[0, 1], &[0, 1]), &r);
    let k = keys[&(p01.min(2), p01.max(2))];
    assert_eq!(node, vec![Some(k), Some(k)]);
}

/// A level's fold keeps each batch's pseudobulk sample apart, and an empty
/// sample holds δ.
#[test]
fn per_level_folds_keep_batches_apart() {
    let log_delta = DMatrix::from_row_slice(1, 2, &[0.5, -0.5]);
    let fold = StateAwareBatchFold {
        n_batches: 2,
        n_nodes: 1,
        log_fold: DMatrix::from_row_slice(1, 2, &[1.0, -1.0]),
        log_delta: log_delta.clone(),
        node_of_unit: vec![Some(0), Some(0)],
    };
    // both units in group 0, one per batch; group 1 has none
    let lvl = fold.per_level(&[0, 0], &[0, 1], 2);
    assert_eq!(lvl.ncols(), 4);
    assert_eq!(lvl[(0, 0)], 1.0);
    assert_eq!(lvl[(0, 1)], -1.0);
    assert_eq!(lvl[(0, 2)], 0.5);
    assert_eq!(lvl[(0, 3)], -0.5);
}

/// The read split refuses counts that are not whole reads.
#[test]
fn split_refuses_fractional_counts() {
    let dir = tempfile::tempdir().expect("tempdir");
    let x = DMatrix::from_row_slice(1, 2, &[0.3, 2.0]);
    let data = data_from(dir.path(), "frac", &x);
    assert!(
        split_cell_reads_over_pair_units_without_double_counting(&data, &[(0, 1)], None).is_err()
    );
}

/// Two link profiles, 2 pb pairs per (profile, batch); each pb its own
/// coarsest group and its own cell-predicted fold. `planted` multiplies gene
/// 0 by 2 in profile 0's batch-1 pb pairs only, after the cell part (a
/// pair-level effect the cells do not predict). Returns the sums already
/// divided by the cell-predicted fold, and each pb's profile.
fn link_state_fixture(dir: &std::path::Path, planted: bool) -> (PseudobulkSums, Vec<usize>) {
    use super::link_state_pair_fold::divide_pb_pairs_by_cell_predicted_fold;
    let mu = [[20.0f32, 2.0, 5.0], [2.0, 20.0, 5.0]];
    let (mut cols, mut batch, mut profile, mut xy) =
        (Vec::new(), Vec::new(), Vec::new(), Vec::new());
    for (p, m) in mu.iter().enumerate() {
        for i in 0..4 {
            let b = i % 2;
            let mut c = m.to_vec();
            if planted && p == 0 && b == 1 {
                c[0] *= 2.0;
            }
            cols.push(c);
            batch.push(b);
            profile.push(p);
            xy.push(p as f32 * 10.0 + i as f32 * 0.01);
        }
    }
    let n = cols.len();
    // a different cell-predicted log fold per pb, applied to the counts
    let cell_predicted = DMatrix::from_fn(3, n, |g, c| 0.1 * (g as f32 + 1.0) * (c as f32 - 3.5));
    let x = DMatrix::from_fn(3, n, |g, c| cols[c][g] * cell_predicted[(g, c)].exp());
    let data = data_from(dir, if planted { "link_planted" } else { "link_null" }, &x);
    let coords = DMatrix::from_fn(1, n, |_, c| xy[c]);
    let mut sums = units_as_pseudobulks(&data, &batch, &coords);
    divide_pb_pairs_by_cell_predicted_fold(&mut sums, &cell_predicted, &(0..n).collect::<Vec<_>>());
    (sums, profile)
}

fn link_state_params() -> StateAwareBatchFoldParams {
    StateAwareBatchFoldParams {
        pseudo_count: 0.0,
        min_pseudobulks: 1,
        knn: 2,
        ..StateAwareBatchFoldParams::default()
    }
}

/// With no pair-level effect, dividing by the cell-predicted fold leaves
/// nothing batch-specific: every link state's leftover is 0, and no link
/// state mixes the two profiles.
#[test]
fn link_state_leftover_is_zero_without_a_pair_level_effect() {
    use super::link_state_pair_fold::link_states_and_leftover_fold;
    let dir = tempfile::tempdir().expect("tempdir");
    let (mut sums, profile) = link_state_fixture(dir.path(), false);
    let (state, n_states, leftover) =
        link_states_and_leftover_fold(&mut sums, 2, &rule(2, 2, 1), &link_state_params())
            .expect("link states");
    assert!(n_states >= 2, "{n_states} link states");
    for s in 0..n_states {
        let ps: Vec<usize> = (0..state.len())
            .filter(|&pb| state[pb] == Some(s))
            .map(|pb| profile[pb])
            .collect();
        assert!(
            ps.windows(2).all(|w| w[0] == w[1]),
            "link state {s} mixes profiles: {ps:?}"
        );
    }
    let max = leftover.iter().fold(0f32, |m, v| m.max(v.abs()));
    assert!(max < 1e-4, "leftover {max}");
}

/// A pair-level effect the cells do not predict stays in the leftover of its
/// own link states, and only there.
#[test]
fn link_state_leftover_recovers_a_planted_pair_level_effect() {
    use super::link_state_pair_fold::link_states_and_leftover_fold;
    let dir = tempfile::tempdir().expect("tempdir");
    let (mut sums, profile) = link_state_fixture(dir.path(), true);
    let (state, n_states, leftover) =
        link_states_and_leftover_fold(&mut sums, 2, &rule(2, 2, 1), &link_state_params())
            .expect("link states");
    let mut seen = [false; 2];
    for s in 0..n_states {
        let p = profile[(0..state.len())
            .find(|&pb| state[pb] == Some(s))
            .expect("member")];
        seen[p] = true;
        // gene 0 against gene 2, batch 1 against batch 0: the planted log 2 (× n/(n−1))
        let col = |b: usize| leftover.column(s * 2 + b);
        let contrast = (col(1)[0] - col(1)[2]) - (col(0)[0] - col(0)[2]);
        if p == 0 {
            assert!(contrast > 0.5, "link state {s} (planted): {contrast}");
        } else {
            let max = leftover
                .columns(s * 2, 2)
                .iter()
                .fold(0f32, |m, v| m.max(v.abs()));
            assert!(max < 1e-4, "link state {s} (not planted): {max}");
        }
    }
    assert_eq!(seen, [true, true], "both profiles have a link state");
}

/// Placement by composition: a unit lands in the node whose composition
/// explains it; a batch the fit saw is scored with that batch's fold, one it
/// never saw against the fold-corrected composition alone; an empty unit
/// lands nowhere.
#[test]
fn unseen_units_are_placed_by_composition() {
    use super::node_compositions::place_by_composition;
    // node 0 expresses gene 0, node 1 gene 1 (fold-corrected, log)
    let log_mean =
        DMatrix::from_row_slice(2, 2, &[0.9f32.ln(), 0.1f32.ln(), 0.1f32.ln(), 0.9f32.ln()]);
    // 2 batches (column node · 2 + batch); in batch 1, node 1's fold
    // multiplies gene 0 by e^5, so node 1 there is 94 % gene 0 (node 0: 90 %)
    // and a gene-0-only unit read in batch 1 is better explained by node 1
    let mut log_fold = DMatrix::<f32>::zeros(2, 4);
    log_fold[(0, 3)] = 5.0;
    let heavy0 = vec![(0usize, 10.0f32)];
    let heavy1 = vec![(0usize, 1.0f32), (1, 9.0)];
    let placed = place_by_composition(
        &[heavy0.clone(), heavy1, heavy0.clone(), heavy0, vec![]],
        &[Some(0), Some(0), Some(1), None, Some(0)],
        &log_mean,
        &log_fold,
        2,
    )
    .expect("placement");
    assert_eq!(placed, vec![Some(0), Some(1), Some(1), Some(0), None]);
    // a batch the fit never had, or one batch entry short, is refused
    assert!(place_by_composition(&[vec![(0, 1.0)]], &[Some(2)], &log_mean, &log_fold, 2).is_err());
    assert!(place_by_composition(&[vec![(0, 1.0)]], &[], &log_mean, &log_fold, 2).is_err());
}

/// An unseen pair's fold in a batch the fit saw: its endpoints'
/// cell-predicted fold plus its link state's leftover.
#[test]
fn unseen_pair_fold_is_cell_predicted_plus_its_link_state_leftover() {
    use super::link_state_pair_fold::LinkStateDecomposition;
    let cells = StateAwareBatchFold {
        n_batches: 1,
        n_nodes: 2,
        log_fold: DMatrix::from_row_slice(1, 2, &[1.0, 3.0]),
        log_delta: DMatrix::from_row_slice(1, 1, &[0.0]),
        node_of_unit: vec![],
    };
    let d = LinkStateDecomposition {
        link_state_of_pair: vec![],
        leftover_log_fold: DMatrix::from_row_slice(1, 2, &[0.5, -0.5]),
        n_batches: 1,
        link_state_log_mean_composition: DMatrix::zeros(1, 2),
    };
    // cell-predicted: (1 + 3) / 2 = 2; link state 1's leftover: −0.5
    let f = d
        .unseen_pair_log_fold(&cells, Some(0), Some(1), Some(1), 0)
        .expect("in the fit");
    assert!((f[0] - 1.5).abs() < 1e-6, "{}", f[0]);
    // no link state: the cell-predicted fold alone; an endpoint without a node: δ
    let f = d
        .unseen_pair_log_fold(&cells, None, Some(1), None, 0)
        .expect("in the fit");
    assert!((f[0] - 1.5).abs() < 1e-6, "{}", f[0]);
    // a batch past the fit's is refused, not read from the next link state
    assert!(d
        .unseen_pair_log_fold(&cells, None, None, Some(0), 1)
        .is_err());
}

/// No within-batch pair (every pair crosses batches, or none at all): no link
/// state, no Ward tree built, no error.
#[test]
fn link_states_of_no_pair_are_none() {
    use super::link_state_pair_fold::link_states_and_leftover_fold;
    let mut sums = PseudobulkSums {
        counts: vec![],
        batch: vec![],
        span_label: vec![],
        coarsest: vec![],
        coords: DMatrix::zeros(1, 0),
        of_unit: vec![],
        n_genes: 3,
    };
    let (state, n_states, leftover) =
        link_states_and_leftover_fold(&mut sums, 2, &rule(2, 2, 1), &link_state_params())
            .expect("no pairs");
    assert!(state.is_empty());
    assert_eq!(n_states, 0);
    assert_eq!(leftover.shape(), (3, 0));
}