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
#![allow(dead_code)]
use super::*;
impl SparseIoVec {
/////////////////////////////////////
// data dictionary related methods //
/////////////////////////////////////
/// Register batch membership information along with the feature
/// matrix for quick look up operations.
///
/// # Arguments
/// * `feature_matrix` - A feature matrix where each column corresponds to a cell.
/// * `batch_membership` - A vector of batch membership information for each cell.
pub fn register_batches_ndarray<T>(
&mut self,
feature_matrix: &ndarray::Array2<f32>,
batch_membership: &[T],
) -> anyhow::Result<()>
where
T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
{
{
debug_assert_eq!(batch_membership.len(), feature_matrix.ncols());
}
self._register_batches(
feature_matrix,
batch_membership,
|feature_matrix, batch_cells| {
let columns = batch_cells
.iter()
.map(|&c| feature_matrix.column(c))
.collect::<Vec<_>>();
ColumnDict::<usize>::from_ndarray_views(columns, batch_cells.clone())
},
)
}
/// Register batch membership information along with the feature
/// matrix for quick look up operations.
///
/// # Arguments
/// * `feature_matrix` - A feature matrix where each column corresponds to a cell.
/// * `batch_membership` - A vector of batch membership information for each cell.
pub fn register_batches_dmatrix<T>(
&mut self,
feature_matrix: &nalgebra::DMatrix<f32>,
batch_membership: &[T],
) -> anyhow::Result<()>
where
T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
{
{
debug_assert_eq!(batch_membership.len(), feature_matrix.ncols());
}
self._register_batches(
feature_matrix,
batch_membership,
|feature_matrix, batch_cells| {
let columns = batch_cells
.iter()
.map(|&c| feature_matrix.column(c))
.collect::<Vec<_>>();
ColumnDict::<usize>::from_dvector_views(columns, batch_cells.clone())
},
)
}
fn _register_batches<M, F, T>(
&mut self,
feature_matrix: &M,
batch_membership: &[T],
create_column_dict: F,
) -> anyhow::Result<()>
where
M: Sync,
F: Fn(&M, &Vec<usize>) -> ColumnDict<usize> + Sync,
T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
{
let batches = partition_by_membership(batch_membership, None);
let ntot = self.num_columns();
let mut col_to_batch = vec![0; ntot];
// A ColumnDict build is internally parallel (instant-distance's rayon
// insert) only ABOVE EXACT_THRESHOLD points; smaller batches use the
// exact backend and build single-threaded. So when batches are many
// (>= n_threads) run the outer loop in parallel — that is the only
// parallelism the small batches get, and large ones just nest into the
// same work-stealing pool (safe, no true oversubscription). When batches
// are few, build sequentially so each large build owns the pool and only
// one HNSW index is under construction at a time (bounds peak memory).
let n_threads = rayon::current_num_threads();
let outer_parallel = batches.len() >= n_threads;
info!(
"building per-batch kNN indices ({} batches, {} cells, {}) ...",
batches.len(),
ntot,
if outer_parallel {
"parallel over batches"
} else {
"sequential over batches"
}
);
let prog_bar =
crate::sparse_data_visitors::styled_progress_bar(batches.len() as u64, "batches kNN");
// Canonical batch id = SORTED LABEL order (consistent with
// `register_batch_membership`), so per-batch stats / δ columns carry the
// same batch ids as the rest of the pipeline. Previously this sorted by
// descending size and used the processing position as the id, which
// silently permuted batch ids vs the label order — a latent bug for δ /
// `AdjMethod::Batch` consumers.
let mut batches_vec: Vec<_> = batches.into_iter().collect();
batches_vec.sort_by(|a, b| a.0.to_string().cmp(&b.0.to_string()));
// Schedule largest batches first (LPT) so the heavy tail overlaps with
// the small batches. The canonical id rides along; `sort_by_key(idx)`
// below restores canonical order.
let mut enumerated: Vec<_> = batches_vec.iter().enumerate().collect();
enumerated.sort_by_key(|(_, (_, cells))| std::cmp::Reverse(cells.len()));
let mut idx_name_glob_dict: Vec<_> = if outer_parallel {
enumerated
.into_par_iter()
.progress_with(prog_bar.clone())
.map(|(batch_index, (batch_name, batch_glob_indices))| {
(
batch_index,
batch_name.to_string().into_boxed_str(),
batch_glob_indices.clone(),
create_column_dict(feature_matrix, batch_glob_indices),
)
})
.collect()
} else {
enumerated
.into_iter()
.progress_with(prog_bar.clone())
.map(|(batch_index, (batch_name, batch_glob_indices))| {
(
batch_index,
batch_name.to_string().into_boxed_str(),
batch_glob_indices.clone(),
create_column_dict(feature_matrix, batch_glob_indices),
)
})
.collect()
};
prog_bar.finish_and_clear();
idx_name_glob_dict.sort_by_key(|&(idx, _, _, _)| idx);
let mut batch_names = vec![];
let mut batch_to_cols = vec![];
let mut dictionaries = vec![];
for (batch_idx, batch_name, glob_indices, dict) in idx_name_glob_dict.into_iter() {
dict.names()
.iter()
.for_each(|&cell| col_to_batch[cell] = batch_idx);
batch_names.push(batch_name);
batch_to_cols.push(glob_indices);
dictionaries.push(dict);
}
self.derived.batch_knn_lookup = Some(dictionaries);
self.derived.col_to_batch = Some(col_to_batch);
self.derived.batch_to_cols = Some(batch_to_cols);
self.derived.batch_idx_to_name = Some(batch_names);
if self.num_batches() > 2 {
self.sort_batch_proximity()?;
}
Ok(())
}
fn sort_batch_proximity(&mut self) -> anyhow::Result<()> {
let lookups = self
.derived
.batch_knn_lookup
.as_ref()
.ok_or(anyhow::anyhow!("no knn lookup"))?;
use nalgebra::DMatrix;
info!("retrieving batch-specific lookups");
let batch_data = lookups
.iter()
.flat_map(|dict| {
let data: Vec<f32> = dict.points().flatten().copied().collect();
let ncols = dict.num_points();
let nrows = data.len() / ncols;
DMatrix::from_vec(nrows, ncols, data)
.column_mean()
.data
.as_vec()
.clone()
})
.collect::<Vec<_>>();
let ncols = self.num_batches();
let nrows = batch_data.len() / ncols;
let batch_features = DMatrix::<f32>::from_vec(nrows, ncols, batch_data);
info!(
"built feature matrix across batches: {} x {}",
batch_features.nrows(),
batch_features.ncols()
);
let nbatches = self.num_batches();
let batches = (0..nbatches).collect();
let dict = ColumnDict::<usize>::from_dvector_views(
batch_features.column_iter().collect(),
batches,
);
let ret: Vec<Vec<usize>> = (0..nbatches)
.into_par_iter()
.map(|b| {
dict.search_by_query_name(&b, nbatches, false)
.map(|(others, _)| others)
})
.collect::<anyhow::Result<Vec<Vec<usize>>>>()?;
self.derived.between_batch_proximity = Some(ret);
Ok(())
}
pub fn batch_name_map(&self) -> Option<HashMap<Box<str>, usize>> {
self.derived.batch_idx_to_name.as_ref().map(|names| {
names
.iter()
.enumerate()
.map(|(idx, name)| (name.clone(), idx))
.collect::<HashMap<Box<str>, usize>>()
})
}
pub fn num_batches(&self) -> usize {
if let Some(v) = &self.derived.batch_to_cols {
v.len()
} else if let Some(v) = &self.derived.batch_knn_lookup {
v.len()
} else {
0
}
}
/// Borrow the per-batch HNSW lookups populated by
/// `build_hnsw_per_batch` / `register_batches_dmatrix`. Returns `None`
/// before the indices have been built.
pub fn batch_knn_lookup(&self) -> Option<&Vec<ColumnDict<usize>>> {
self.derived.batch_knn_lookup.as_ref()
}
/// Register batch membership information without building HNSW
/// indices. This is a lightweight alternative to `register_batches_dmatrix`
/// for use with pb-sample based batch correction.
pub fn register_batch_membership<T>(&mut self, batch_membership: &[T])
where
T: Sync + Send + std::hash::Hash + Eq + Clone + ToString,
{
let batches = partition_by_membership(batch_membership, None);
let ntot = self.num_columns();
let mut col_to_batch = vec![0; ntot];
let mut sorted_batches: Vec<_> = batches.into_iter().collect();
sorted_batches.sort_by(|a, b| a.0.to_string().cmp(&b.0.to_string()));
let mut batch_names = Vec::with_capacity(sorted_batches.len());
let mut batch_to_cols = Vec::with_capacity(sorted_batches.len());
for (batch_idx, (batch_name, glob_indices)) in sorted_batches.into_iter().enumerate() {
for &cell in &glob_indices {
col_to_batch[cell] = batch_idx;
}
batch_names.push(batch_name.to_string().into_boxed_str());
batch_to_cols.push(glob_indices);
}
self.derived.col_to_batch = Some(col_to_batch);
self.derived.batch_to_cols = Some(batch_to_cols);
self.derived.batch_idx_to_name = Some(batch_names);
}
/// Declare that each column stands for more than one observation.
///
/// A column is normally one cell, so every statistic that divides by a
/// count adds `1` per column. That breaks when a column is a *summary* of
/// many cells — a carried pseudobulk, or a bulk sample — because the
/// per-cell rate `μ = Σy / n` would divide a whole group's counts by one.
///
/// With multiplicities registered, a column holding the **mean** profile of
/// `m` cells and a weight of `m` contributes exactly what those `m` cells
/// would have: `m·mean` to the sums and `m` to the count.
///
/// Absent (the default) every column weighs `1`, and every accumulation is
/// bit-for-bit what it was before this existed.
///
/// # Errors
/// If `multiplicity` is not one entry per column, or holds a non-finite or
/// non-positive weight — a zero would silently delete a column from the
/// denominator while leaving its counts in the numerator.
pub fn register_column_multiplicity(&mut self, multiplicity: &[f32]) -> anyhow::Result<()> {
let ntot = self.num_columns();
anyhow::ensure!(
multiplicity.len() == ntot,
"column multiplicity has {} entries but there are {ntot} columns",
multiplicity.len(),
);
if let Some((i, w)) = multiplicity
.iter()
.enumerate()
.find(|(_, w)| !w.is_finite() || **w <= 0.0)
{
anyhow::bail!("column {i} has multiplicity {w}; weights must be finite and positive");
}
self.derived.col_multiplicity = Some(multiplicity.to_vec());
Ok(())
}
/// Weight of a single column — `1.0` when no multiplicities are registered.
#[must_use]
pub fn column_multiplicity(&self, col: usize) -> f32 {
self.derived
.col_multiplicity
.as_ref()
.map_or(1.0, |m| m[col])
}
/// True when any column stands for more than one observation.
#[must_use]
pub fn has_column_multiplicity(&self) -> bool {
self.derived.col_multiplicity.is_some()
}
/// The whole multiplicity vector, one weight per column — `None` when no
/// multiplicities are registered (every column is one observation).
///
/// Prefer this over gathering [`Self::column_multiplicity`] in a loop:
/// callers were rebuilding the vector element-by-element, re-encoding the
/// "absent means 1.0" default at every site.
#[must_use]
pub fn column_multiplicities(&self) -> Option<&[f32]> {
self.derived.col_multiplicity.as_deref()
}
pub fn batch_names(&self) -> Option<Vec<Box<str>>> {
self.derived.batch_idx_to_name.clone()
}
pub fn batch_to_columns(&self, batch: usize) -> Option<&Vec<usize>> {
if let Some(batch_to_cols) = &self.derived.batch_to_cols {
Some(&batch_to_cols[batch])
} else {
None
}
}
pub fn get_batch_membership<I>(&self, cells: I) -> Vec<usize>
where
I: Iterator<Item = usize>,
{
let cell_to_batch = self
.derived
.col_to_batch
.as_ref()
.expect("cell_to_batch not initialized");
cells.into_iter().map(|c| cell_to_batch[c]).collect()
}
pub fn column_names(&self) -> anyhow::Result<Vec<Box<str>>> {
debug_assert_eq!(self.num_columns(), self.column_names_with_data_tag.len());
Ok(self.column_names_with_data_tag.clone())
}
}