Skip to main content

legume_numeric/matrix/
dmatrix_util.rs

1use nalgebra::{ComplexField, DMatrix, DVectorViewMut, Matrix};
2use nalgebra_sparse::{coo::CooMatrix, csc::CscMatrix, csr::CsrMatrix};
3
4use crate::matrix::rand_util::{collect_seeded, entropy_seed};
5use num_traits::Float;
6use rand_distr::{Gamma, StandardNormal, Uniform};
7use rayon::prelude::*;
8
9pub use crate::matrix::dmatrix_rsvd::nystrom_basis;
10use crate::matrix::traits::*;
11
12/// Build a `DMatrix<f32>` column-by-column in parallel. `build_col(j, col)`
13/// fills the `j`-th output column (length `nrows`) directly into the
14/// matrix's backing slice — no per-column `Vec` allocation, no stitching.
15///
16/// Each task gets a disjoint `&mut [f32]`, so reductions stay deterministic
17/// (per-column accumulation order is whatever `build_col` does internally).
18pub fn build_columns_par<F>(nrows: usize, ncols: usize, build_col: F) -> DMatrix<f32>
19where
20    F: Fn(usize, &mut [f32]) + Sync + Send,
21{
22    let mut out = DMatrix::<f32>::zeros(nrows, ncols);
23    if nrows > 0 && ncols > 0 {
24        out.as_mut_slice()
25            .par_chunks_mut(nrows)
26            .enumerate()
27            .for_each(|(j, col)| build_col(j, col));
28    }
29    out
30}
31
32/// Winsorize each row of `m` (one row per feature, one column per
33/// sample) to `median ± n_mads · MAD · 1.4826` across its columns, so a few
34/// extreme samples cannot dominate distances on the table. MAD-based, so
35/// no Gaussian shape is assumed. A row with zero MAD is left alone, and
36/// `n_mads <= 0` or fewer than 8 columns is a no-op. Returns how many
37/// values were clipped.
38pub fn winsorize_rows_inplace(m: &mut DMatrix<f32>, n_mads: f32) -> usize {
39    let (d, n) = m.shape();
40    if n_mads <= 0.0 || n < 8 || d == 0 {
41        return 0;
42    }
43    // Each row's bounds, rows in parallel; `None` for a row with zero MAD.
44    let bounds: Vec<Option<(f32, f32)>> = (0..d)
45        .into_par_iter()
46        .map(|r| {
47            let mut buf: Vec<f32> = m.row(r).iter().copied().collect();
48            let med = upper_median(&mut buf);
49            buf.iter_mut().for_each(|v| *v = (*v - med).abs());
50            let mad = upper_median(&mut buf) * 1.4826;
51            (mad > 1e-12).then_some((med - n_mads * mad, med + n_mads * mad))
52        })
53        .collect();
54    // Then one contiguous pass over the columns.
55    m.as_mut_slice()
56        .par_chunks_mut(d)
57        .map(|col| {
58            let mut clipped = 0;
59            for (v, b) in col.iter_mut().zip(&bounds) {
60                if let Some((lo, hi)) = *b {
61                    if *v < lo || *v > hi {
62                        *v = v.clamp(lo, hi);
63                        clipped += 1;
64                    }
65                }
66            }
67            clipped
68        })
69        .sum()
70}
71
72/// The element at index `len / 2` once sorted (reorders `buf`); 0 if empty.
73/// A quickselect, not `utils::median`, which sorts a copy and averages the
74/// middle two.
75fn upper_median(buf: &mut [f32]) -> f32 {
76    if buf.is_empty() {
77        return 0.0;
78    }
79    let mid = buf.len() / 2;
80    *buf.select_nth_unstable_by(mid, f32::total_cmp).1
81}
82
83pub fn subset_columns<T, D, S, I>(
84    matrix: &Matrix<T, nalgebra::Dyn, D, S>,
85    indices: I,
86) -> anyhow::Result<DMatrix<T>>
87where
88    T: nalgebra::RealField,
89    D: nalgebra::Dim,
90    S: nalgebra::RawStorage<T, nalgebra::Dyn, D>,
91    I: IntoIterator<Item = usize>,
92{
93    let cols = indices
94        .into_iter()
95        .map(|j| matrix.column(j))
96        .collect::<Vec<_>>();
97
98    concatenate_horizontal(&cols)
99}
100
101pub fn subset_rows<T, D, S, I>(
102    matrix: &Matrix<T, D, nalgebra::Dyn, S>,
103    indices: I,
104) -> anyhow::Result<DMatrix<T>>
105where
106    T: nalgebra::RealField,
107    D: nalgebra::Dim,
108    S: nalgebra::RawStorage<T, D, nalgebra::Dyn>,
109    I: IntoIterator<Item = usize>,
110{
111    let rows = indices
112        .into_iter()
113        .map(|j| matrix.row(j))
114        .collect::<Vec<_>>();
115
116    concatenate_vertical(&rows)
117}
118
119pub fn assign_columns<T, D, S, R, I>(
120    source: &Matrix<T, nalgebra::Dyn, D, S>,
121    indices: I,
122    target: &mut Matrix<T, nalgebra::Dyn, D, R>,
123) where
124    T: nalgebra::RealField,
125    D: nalgebra::Dim,
126    S: nalgebra::RawStorage<T, nalgebra::Dyn, D>,
127    R: nalgebra::RawStorageMut<T, nalgebra::Dyn, D>,
128    I: IntoIterator<Item = usize>,
129{
130    indices
131        .into_iter()
132        .zip(source.column_iter())
133        .for_each(|(j, x_j)| {
134            target.column_mut(j).copy_from(&x_j);
135        });
136}
137
138/// concatenate matrices or row vectors vertically
139pub fn concatenate_vertical<T, D, S>(
140    matrices: &[Matrix<T, D, nalgebra::Dyn, S>],
141) -> anyhow::Result<DMatrix<T>>
142where
143    T: nalgebra::RealField,
144    D: nalgebra::Dim,
145    S: nalgebra::RawStorage<T, D, nalgebra::Dyn>,
146{
147    if matrices.is_empty() {
148        anyhow::bail!("empty in concatenate_vertical");
149    }
150
151    let ncols = matrices[0].ncols();
152    assert!(
153        matrices.iter().all(|m| m.ncols() == ncols),
154        "should have the same number of columns"
155    );
156
157    let rows = matrices
158        .iter()
159        .flat_map(|m| m.row_iter().map(|row| row.into_owned()))
160        .collect::<Vec<_>>();
161
162    Ok(DMatrix::from_rows(&rows))
163}
164
165/// concatenate matrices or column vectors horizontally
166pub fn concatenate_horizontal<T, D, S>(
167    matrices: &[Matrix<T, nalgebra::Dyn, D, S>],
168) -> anyhow::Result<DMatrix<T>>
169where
170    T: nalgebra::RealField,
171    D: nalgebra::Dim,
172    S: nalgebra::RawStorage<T, nalgebra::Dyn, D>,
173{
174    if matrices.is_empty() {
175        anyhow::bail!("empty in concatenate_horizontal");
176    }
177
178    let nrows = matrices[0].nrows();
179    assert!(
180        matrices.iter().all(|m| m.nrows() == nrows),
181        "should have the same number of rows"
182    );
183
184    let cols = matrices
185        .iter()
186        .flat_map(|m| m.column_iter().map(|col| col.into_owned()))
187        .collect::<Vec<_>>();
188
189    Ok(DMatrix::from_columns(&cols))
190}
191
192impl<T> AdjustByDivisionOp<nalgebra_sparse::CscMatrix<T>, T> for nalgebra_sparse::CscMatrix<T>
193where
194    T: nalgebra::RealField + Copy + std::iter::Sum<T>,
195{
196    fn adjust_by_division_inplace(&mut self, denom: &nalgebra_sparse::CscMatrix<T>) {
197        self.col_iter_mut()
198            .zip(denom.col_iter())
199            .for_each(|(mut x_j, d_j)| {
200                let dsum = d_j.values().iter().copied().sum::<T>();
201                let xsum = x_j.values().iter().copied().sum::<T>();
202                let scale = if dsum > T::zero() {
203                    xsum / dsum
204                } else {
205                    T::one()
206                };
207
208                let (x_rows, x_values) = x_j.rows_and_values_mut();
209
210                let mut d_j_values = vec![T::zero(); x_rows.len()];
211
212                x_rows.iter().enumerate().for_each(|(idx, &i)| {
213                    if let Some(pos) = d_j.row_indices().iter().position(|&d_i| d_i == i) {
214                        d_j_values[idx] = d_j.values()[pos];
215                    }
216                });
217
218                x_values
219                    .iter_mut()
220                    .zip(d_j_values)
221                    .for_each(|(x_ij, d_ij)| {
222                        if d_ij > T::zero() {
223                            *x_ij /= d_ij * scale;
224                        }
225                    });
226            });
227    }
228
229    fn adjust_by_division_of_selected_inplace(
230        &mut self,
231        denom_db: &nalgebra_sparse::CscMatrix<T>,
232        batches: &[usize],
233    ) {
234        self.col_iter_mut().zip(batches).for_each(|(mut x_j, &b)| {
235            let d_j = denom_db.col(b);
236
237            let dsum = d_j.values().iter().copied().sum::<T>();
238            let xsum = x_j.values().iter().copied().sum::<T>();
239            let scale = if dsum > T::zero() {
240                xsum / dsum
241            } else {
242                T::one()
243            };
244
245            let (x_rows, x_values) = x_j.rows_and_values_mut();
246
247            let mut d_j_values = vec![T::zero(); x_rows.len()];
248
249            x_rows.iter().enumerate().for_each(|(idx, &i)| {
250                if let Some(pos) = d_j.row_indices().iter().position(|&d_i| d_i == i) {
251                    d_j_values[idx] = d_j.values()[pos];
252                }
253            });
254
255            x_values
256                .iter_mut()
257                .zip(d_j_values)
258                .for_each(|(x_ij, d_ij)| {
259                    if d_ij > T::zero() {
260                        *x_ij /= d_ij * scale;
261                    }
262                });
263        });
264    }
265}
266
267/// Self-normalizing Poisson-ratio divide of one sparse column's values, in place.
268///
269/// Models `Y[g] ~ Poisson(X[g]·λ)`: estimate `λ = Σ Y / Σ divisor` over the
270/// column's nonzeros, then replace each `Y[g]` by the residual `Y[g] / (divisor(g)·λ)`
271/// when `divisor(g) > 0` (entries with a non-positive divisor are left unchanged).
272/// `divisor(k)` returns the divisor for the `k`-th value, `k` in `0..vals.len()`.
273///
274/// This is the shared core of the [`AdjustByDivisionOp`] `DMatrix` impls below; it
275/// is also callable directly on any `(values, divisor)` pair without materializing
276/// a matrix — e.g. one cell's counts indexed into a per-pseudobulk fold-factor.
277pub fn adjust_by_poisson_ratio<T, F>(vals: &mut [T], divisor: F)
278where
279    T: nalgebra::RealField + Copy + std::iter::Sum<T>,
280    F: Fn(usize) -> T,
281{
282    let dsum: T = (0..vals.len()).map(&divisor).sum();
283    let xsum: T = vals.iter().copied().sum();
284    let scale = if dsum > T::zero() {
285        xsum / dsum
286    } else {
287        T::one()
288    };
289    for (k, x) in vals.iter_mut().enumerate() {
290        let d = divisor(k);
291        if d > T::zero() {
292            *x /= d * scale;
293        }
294    }
295}
296
297impl<T> AdjustByDivisionOp<nalgebra::DMatrix<T>, T> for nalgebra_sparse::CscMatrix<T>
298where
299    T: nalgebra::RealField + Copy + std::iter::Sum<T>,
300{
301    fn adjust_by_division_of_selected_inplace(
302        &mut self,
303        denom_db: &nalgebra::DMatrix<T>,
304        batches: &[usize],
305    ) {
306        self.col_iter_mut().zip(batches).for_each(|(mut x_j, &b)| {
307            let (rows, vals) = x_j.rows_and_values_mut();
308            adjust_by_poisson_ratio(vals, |k| denom_db[(rows[k], b)]);
309        });
310    }
311
312    fn adjust_by_division_inplace(&mut self, denom: &nalgebra::DMatrix<T>) {
313        self.col_iter_mut()
314            .zip(denom.column_iter())
315            .for_each(|(mut x_j, d_col)| {
316                let (rows, vals) = x_j.rows_and_values_mut();
317                adjust_by_poisson_ratio(vals, |k| d_col[rows[k]]);
318            });
319    }
320}
321
322/// Generate one-hot membership matrix (`row x K`) where the number of
323/// rows corresponds to the length of the membership vector and the
324/// `K` corresponds to the maximum membership value + 1.
325///
326pub fn row_membership_matrix<T>(row_membership: Vec<usize>) -> anyhow::Result<DMatrix<T>>
327where
328    T: nalgebra::RealField + Copy,
329{
330    let kk = match row_membership.iter().max() {
331        Some(&m) => m + 1,
332        _ => 1,
333    };
334
335    let mut ret_dm = DMatrix::zeros(row_membership.len(), kk);
336    let oneval = T::from_f32(1.).ok_or(anyhow::anyhow!("cannot find 1 value"))?;
337    for (i, k) in row_membership.into_iter().enumerate() {
338        ret_dm[(i, k)] += oneval;
339    }
340
341    Ok(ret_dm)
342}
343
344fn csc_euclidean_distance_on_select_columns<T>(
345    lhs: &CscMatrix<T>,
346    rhs: &CscMatrix<T>,
347    select_columns_in_rhs: Option<&[usize]>,
348) -> anyhow::Result<Vec<(usize, usize, T)>>
349where
350    T: nalgebra::RealField + Copy + std::iter::Sum<T>,
351{
352    let all_rhs = (0..rhs.ncols()).collect::<Vec<_>>();
353    let select_columns_in_rhs = select_columns_in_rhs.unwrap_or(all_rhs.as_slice());
354
355    if select_columns_in_rhs.len() != rhs.ncols() {
356        return Err(anyhow::anyhow!(
357            "found mismatches in `select_columns` maps: lhs -> rhs"
358        ));
359    }
360
361    let mut ret = Vec::with_capacity(select_columns_in_rhs.len() * lhs.ncols());
362
363    for (src_pos, src_col) in lhs.col_iter().enumerate() {
364        for &tgt_pos in select_columns_in_rhs {
365            let tgt_col = rhs.col(tgt_pos);
366
367            let nn = src_col.nrows();
368            let denom = T::from_usize(nn).unwrap_or(T::one());
369
370            let idx_src = src_col.row_indices();
371            let idx_tgt = tgt_col.row_indices();
372            let val_src = src_col.values();
373            let val_tgt = tgt_col.values();
374
375            // sum_g (src[g] - tgt[g])^2 / sum_g 1
376            // sum_g tgt[g]^2 + sum_g src[g]^2 - 2 sum_g tgt[g] * src[g]
377            let mut s: usize = 0;
378            let mut t: usize = 0;
379
380            let tgt_sq_sum = val_tgt.iter().map(|&x| x * x).sum::<T>();
381            let src_sq_sum = val_src.iter().map(|&x| x * x).sum::<T>();
382            let mut overlap = T::zero();
383            while s < idx_src.len() && t < idx_tgt.len() {
384                if idx_src[s] == idx_tgt[t] {
385                    overlap += val_src[s] * val_tgt[t];
386                    s += 1;
387                    t += 1;
388                } else if idx_src[s] < idx_tgt[t] {
389                    s += 1;
390                } else {
391                    t += 1;
392                }
393            }
394
395            let dist = ((src_sq_sum + tgt_sq_sum - overlap - overlap) / denom).sqrt();
396
397            ret.push((src_pos, tgt_pos, dist));
398        }
399    }
400
401    Ok(ret)
402}
403
404impl<T> DistanceOps for CscMatrix<T>
405where
406    T: nalgebra::RealField + Copy + std::iter::Sum<T>,
407{
408    type Scalar = T;
409    type Other = CscMatrix<T>;
410
411    fn euclidean_distance(
412        &self,
413        other: &Self::Other,
414    ) -> anyhow::Result<Vec<(usize, usize, Self::Scalar)>> {
415        csc_euclidean_distance_on_select_columns(self, other, None)
416    }
417
418    fn euclidean_distance_on_select_columns(
419        &self,
420        other: &Self::Other,
421        select_columns_in_other: &[usize],
422    ) -> anyhow::Result<Vec<(usize, usize, Self::Scalar)>> {
423        csc_euclidean_distance_on_select_columns(self, other, Some(select_columns_in_other))
424    }
425}
426
427impl<T> MeltOps for DMatrix<T>
428where
429    T: nalgebra::RealField + Copy,
430{
431    type Scalar = T;
432    type Mat = Self;
433    fn melt_with_indexes(&self) -> (Vec<Self::Scalar>, Vec<Vec<usize>>) {
434        let nelem = self.nrows() * self.ncols();
435
436        let mut idx: Vec<Vec<usize>> = vec![Vec::with_capacity(nelem), Vec::with_capacity(nelem)];
437        let mut val: Vec<Self::Scalar> = Vec::with_capacity(nelem);
438
439        // Iterate column-major to match nalgebra's storage layout for cache efficiency
440        for c in 0..self.ncols() {
441            for r in 0..self.nrows() {
442                idx[0].push(r);
443                idx[1].push(c);
444                val.push(self[(r, c)]);
445            }
446        }
447
448        (val, idx)
449    }
450
451    fn melt(&self) -> Vec<Self::Scalar> {
452        let nelem = self.len();
453        let mut val: Vec<Self::Scalar> = Vec::with_capacity(nelem);
454        // Iterate column-major to match nalgebra's storage layout for cache efficiency
455        for c in 0..self.ncols() {
456            for r in 0..self.nrows() {
457                val.push(self[(r, c)]);
458            }
459        }
460        val
461    }
462
463    fn melt_many_with_indexes(
464        &self,
465        others: &[&Self],
466    ) -> (Vec<Vec<Self::Scalar>>, Vec<Vec<usize>>) {
467        let nrows = self.nrows();
468        let ncols = self.ncols();
469        let nelem = nrows * ncols;
470        let n_matrices = 1 + others.len();
471
472        // Pre-allocate all vectors
473        let mut values: Vec<Vec<Self::Scalar>> =
474            (0..n_matrices).map(|_| Vec::with_capacity(nelem)).collect();
475        let mut idx: Vec<Vec<usize>> = vec![Vec::with_capacity(nelem), Vec::with_capacity(nelem)];
476
477        // Single traversal in column-major order for cache efficiency
478        for c in 0..ncols {
479            for r in 0..nrows {
480                idx[0].push(r);
481                idx[1].push(c);
482                values[0].push(self[(r, c)]);
483                for (i, other) in others.iter().enumerate() {
484                    values[i + 1].push(other[(r, c)]);
485                }
486            }
487        }
488
489        (values, idx)
490    }
491}
492
493impl<T> EncodingOps for DMatrix<T>
494where
495    T: nalgebra::RealField + Float,
496    f32: From<T>,
497{
498    type Scalar = T;
499    type Mat = Self;
500
501    fn positional_embedding_columns(&self, emb_dim: usize) -> anyhow::Result<Self::Mat> {
502        let ncols = self.ncols();
503
504        let ncodes_per_col = emb_dim * 2;
505
506        let mut output = Self::zeros(self.nrows(), ncols * ncodes_per_col);
507
508        for j in 0..ncols {
509            let x_j = self.column(j);
510
511            for i in 0..emb_dim {
512                let power = T::from(2.0 * i as f32 / emb_dim as f32).unwrap();
513                let denom = T::from(10000_f32.powf(f32::from(power))).unwrap();
514
515                let column_data = if i % 2 == 0 {
516                    x_j.map(|x_ij| ComplexField::sin(x_ij / denom))
517                } else {
518                    x_j.map(|x_ij| ComplexField::cos(x_ij / denom))
519                };
520
521                // Assign the computed column to the output matrix
522                output
523                    .column_mut(j * ncodes_per_col + i)
524                    .copy_from(&column_data);
525            }
526        }
527        Ok(output)
528    }
529}
530
531impl<T> CompositeOps for DMatrix<T>
532where
533    T: nalgebra::RealField + Copy,
534{
535    type Scalar = T;
536    type Mat = Self;
537    type Other = CscMatrix<T>;
538
539    /// `self[:,col] += other[:,col]`
540    /// * `col` - column index
541    fn add_assign_column(&mut self, other: &Self::Other, j: usize) {
542        debug_assert_eq!(self.nrows(), other.nrows());
543        debug_assert_eq!(self.ncols(), other.ncols());
544        if let Some(x_j) = other.get_col(j) {
545            let vals = x_j.values();
546            let rows = x_j.row_indices();
547            for k in 0..vals.len() {
548                let i = rows[k];
549                let x_ij = vals[k];
550                self[(i, j)] += x_ij;
551            }
552        }
553    }
554
555    /// `self += other`
556    /// * `other` - `CscMatrix`
557    fn add_assign(&mut self, other: &Self::Other) {
558        debug_assert_eq!(self.nrows(), other.nrows());
559        debug_assert_eq!(self.ncols(), other.ncols());
560        for j in 0..other.ncols() {
561            if let Some(x_j) = other.get_col(j) {
562                let vals = x_j.values();
563                let rows = x_j.row_indices();
564                for k in 0..vals.len() {
565                    let i = rows[k];
566                    let x_ij = vals[k];
567                    self[(i, j)] += x_ij;
568                }
569            }
570        }
571    }
572}
573
574#[cfg(feature = "tensor")]
575impl<T> ConvertMatOps for DMatrix<T>
576where
577    T: nalgebra::RealField + Copy + candle_core::WithDType,
578{
579    type Mat = Self;
580    type Scalar = T;
581
582    fn from_tensor(tensor: &candle_core::Tensor) -> anyhow::Result<Self::Mat> {
583        if tensor.dims().len() != 2 {
584            return Err(anyhow::anyhow!("expected 2D tensor"));
585        }
586
587        let nrows = tensor.dims()[0];
588        let ncols = tensor.dims()[1];
589        let data: Vec<T> = tensor.flatten_all()?.to_vec1()?;
590        Ok(Self::from_row_iterator(nrows, ncols, data.iter().cloned()))
591    }
592
593    fn to_tensor(&self, dev: &candle_core::Device) -> anyhow::Result<candle_core::Tensor> {
594        use candle_core::Tensor;
595        // Note: x.as_slice() will take values in the column-major order
596        // However, Tensor::from_slice will take them in the row-major order
597        let nrow = self.nrows();
598        let ncol = self.ncols();
599        Ok(Tensor::from_slice(self.as_slice(), (ncol, nrow), dev)?.transpose(0, 1)?)
600    }
601}
602
603#[cfg(feature = "tensor")]
604impl<T> ConvertMatOps for CscMatrix<T>
605where
606    T: nalgebra::RealField + Copy + candle_core::WithDType,
607{
608    type Mat = Self;
609    type Scalar = T;
610    fn from_tensor(tensor: &candle_core::Tensor) -> anyhow::Result<Self::Mat> {
611        if tensor.dims().len() != 2 {
612            return Err(anyhow::anyhow!("expected 2D tensor"));
613        }
614
615        let nrows = tensor.dims()[0];
616        let ncols = tensor.dims()[1];
617        let data: Vec<T> = tensor.flatten_all()?.to_vec1()?;
618
619        let dense_matrix = DMatrix::from_row_iterator(nrows, ncols, data.iter().cloned());
620        let csc_matrix = CscMatrix::from(&dense_matrix);
621
622        Ok(csc_matrix)
623    }
624
625    fn to_tensor(&self, dev: &candle_core::Device) -> anyhow::Result<candle_core::Tensor> {
626        use candle_core::Tensor;
627        let dense_matrix = DMatrix::from(self);
628        let nrow = dense_matrix.nrows();
629        let ncol = dense_matrix.ncols();
630        // Note: x.as_slice() will take values in the column-major order
631        // However, Tensor::from_slice will take them in the row-major order
632        Ok(Tensor::from_slice(dense_matrix.as_slice(), (ncol, nrow), dev)?.transpose(0, 1)?)
633    }
634}
635
636impl<T> SampleOps for DMatrix<T>
637where
638    T: nalgebra::RealField + Float,
639{
640    type Mat = Self;
641    type Scalar = T;
642
643    fn runif(nrow: usize, ncol: usize) -> Self::Mat {
644        Self::runif_seeded(nrow, ncol, entropy_seed())
645    }
646
647    fn rnorm(nrow: usize, ncol: usize) -> Self::Mat {
648        Self::rnorm_seeded(nrow, ncol, entropy_seed())
649    }
650
651    fn rgamma(nrow: usize, ncol: usize, param: (f32, f32)) -> Self::Mat {
652        Self::rgamma_seeded(nrow, ncol, param, entropy_seed())
653    }
654
655    fn runif_seeded(nrow: usize, ncol: usize, seed: u64) -> Self::Mat {
656        let u01 = Uniform::<f32>::new(0., 1.).expect("failed to create uniform distribution");
657        DMatrix::<T>::from_vec(nrow, ncol, collect_seeded(nrow * ncol, u01, seed))
658    }
659
660    fn rnorm_seeded(nrow: usize, ncol: usize, seed: u64) -> Self::Mat {
661        DMatrix::<T>::from_vec(
662            nrow,
663            ncol,
664            collect_seeded(nrow * ncol, StandardNormal, seed),
665        )
666    }
667
668    fn rgamma_seeded(nrow: usize, ncol: usize, param: (f32, f32), seed: u64) -> Self::Mat {
669        let (shape, scale) = param;
670        let pdf = Gamma::new(shape, scale).unwrap();
671        DMatrix::<T>::from_vec(nrow, ncol, collect_seeded(nrow * ncol, pdf, seed))
672    }
673}
674
675/// `f` on each column of `x`, the columns in parallel.
676fn dense_columns_par<T, F>(x: &mut DMatrix<T>, f: F)
677where
678    T: nalgebra::Scalar + Send,
679    F: Fn(DVectorViewMut<T>) + Sync,
680{
681    let nrows = x.nrows();
682    if nrows > 0 {
683        x.as_mut_slice()
684            .par_chunks_mut(nrows)
685            .for_each(|col| f(DVectorViewMut::from_slice(col, nrows)));
686    }
687}
688
689/// Each column's stored values of `x` as its own mutable slice, so the
690/// columns can be worked on in parallel.
691fn csc_columns_mut<T>(x: &mut CscMatrix<T>) -> Vec<&mut [T]> {
692    let (offsets, _, mut rest) = x.csc_data_mut();
693    offsets
694        .windows(2)
695        .map(|w| {
696            let (col, tail) = std::mem::take(&mut rest).split_at_mut(w[1] - w[0]);
697            rest = tail;
698            col
699        })
700        .collect()
701}
702
703impl<T> MatElemOps for CscMatrix<T>
704where
705    T: nalgebra::RealField + Copy,
706{
707    type Mat = Self;
708    type Scalar = T;
709
710    fn log1p_inplace(&mut self) {
711        self.values_mut()
712            .par_iter_mut()
713            .for_each(|x| *x = (*x).ln_1p());
714    }
715
716    fn log1p(&self) -> Self::Mat {
717        let mut ret = self.clone();
718        ret.log1p_inplace();
719        ret
720    }
721}
722
723impl<T> MatOps for CscMatrix<T>
724where
725    T: nalgebra::RealField + Copy,
726{
727    type Mat = Self;
728    type Scalar = T;
729
730    fn normalize_exp_logits_columns_inplace(&mut self) {
731        let ncol = self.ncols();
732
733        for j in 0..ncol {
734            if let Some(log_j) = self.get_col(j) {
735                let mut log_max = log_j.values()[0];
736                for &logx_ij in log_j.values() {
737                    log_max = log_max.min(logx_ij);
738                }
739
740                let mut denom = T::zero();
741                for &logx_ij in log_j.values() {
742                    denom += (logx_ij - log_max).exp();
743                }
744
745                if let Some(mut log_j) = self.get_col_mut(j) {
746                    for x_ij in log_j.values_mut() {
747                        *x_ij = (*x_ij - log_max).exp() / denom;
748                    }
749                }
750            }
751        }
752    }
753
754    fn normalize_exp_logits_columns(&self) -> Self::Mat {
755        let mut ret = self.clone();
756        ret.normalize_exp_logits_columns_inplace();
757        ret
758    }
759
760    fn log_softmax_columns_inplace(&mut self) {
761        for j in 0..self.ncols() {
762            let lse = {
763                let Some(col) = self.get_col(j) else { continue };
764                let vals = col.values();
765                if vals.is_empty() {
766                    continue;
767                }
768                let mut log_max = vals[0];
769                for &v in vals {
770                    if v > log_max {
771                        log_max = v;
772                    }
773                }
774                let mut denom = T::zero();
775                for &v in vals {
776                    denom += (v - log_max).exp();
777                }
778                log_max + denom.ln()
779            };
780            if let Some(mut col) = self.get_col_mut(j) {
781                for x in col.values_mut() {
782                    *x -= lse;
783                }
784            }
785        }
786    }
787
788    fn log_softmax_columns(&self) -> Self::Mat {
789        let mut ret = self.clone();
790        ret.log_softmax_columns_inplace();
791        ret
792    }
793
794    fn sum_to_one_columns_inplace(&mut self) {
795        csc_columns_mut(self).into_par_iter().for_each(|x_j| {
796            let denom = x_j.iter().fold(T::zero(), |a, &x_ij| a + x_ij);
797            if denom > T::zero() {
798                x_j.iter_mut().for_each(|x_ij| *x_ij /= denom);
799            }
800        });
801    }
802
803    fn sum_to_one_columns(&self) -> Self::Mat {
804        let mut ret = self.clone();
805        ret.sum_to_one_columns_inplace();
806        ret
807    }
808
809    fn sum_to_one_rows(&self) -> Self::Mat {
810        let mut ret = self.clone();
811        ret.sum_to_one_rows_inplace();
812        ret
813    }
814
815    fn sum_to_one_rows_inplace(&mut self) {
816        let nrow = self.nrows();
817        let mut denom = vec![T::zero(); nrow];
818
819        for col in self.col_iter() {
820            col.row_indices()
821                .iter()
822                .zip(col.values().iter())
823                .for_each(|(&i, &x_ij)| {
824                    denom[i] += x_ij;
825                });
826        }
827
828        for mut col in self.col_iter_mut() {
829            let (row_indices, values) = col.rows_and_values_mut();
830            row_indices.iter().zip(values).for_each(|(&i, x_ij)| {
831                *x_ij /= denom[i];
832            });
833        }
834    }
835
836    fn normalize_columns_inplace(&mut self) {
837        let ncol = self.ncols();
838
839        for j in 0..ncol {
840            if let Some(x_j) = self.get_col(j) {
841                let mut denom = T::zero();
842                for &x_ij in x_j.values() {
843                    denom += x_ij * x_ij;
844                }
845                denom = denom.sqrt().max(T::from_f64(1e-8).unwrap());
846
847                if let Some(mut x_j) = self.get_col_mut(j) {
848                    for x_ij in x_j.values_mut() {
849                        *x_ij /= denom;
850                    }
851                }
852            }
853        }
854    }
855
856    fn normalize_columns(&self) -> Self::Mat {
857        let mut ret = self.clone();
858        ret.normalize_columns_inplace();
859        ret
860    }
861
862    fn scale_columns_inplace(&mut self) {
863        let ncol = self.ncols();
864
865        for j in 0..ncol {
866            if let Some(x_j) = self.get_col(j) {
867                let mut s0 = T::zero();
868                let mut s1 = T::zero();
869                let mut s2 = T::zero();
870
871                for &x_ij in x_j.values() {
872                    s0 += T::one();
873                    s1 += x_ij;
874                    s2 += x_ij * x_ij;
875                }
876
877                let mu = s1 / s0.max(T::one());
878                let sig = (s2 / s0.max(T::one()) - mu * mu).sqrt();
879
880                if let Some(mut x_j) = self.get_col_mut(j) {
881                    if sig > T::zero() {
882                        for x_ij in x_j.values_mut() {
883                            *x_ij = (*x_ij - mu) / sig;
884                        }
885                    } else {
886                        for x_ij in x_j.values_mut() {
887                            *x_ij -= mu;
888                        }
889                    }
890                }
891            }
892        }
893    }
894
895    fn scale_rows_inplace(&mut self) {
896        let nrow = self.nrows();
897        let ncol = self.ncols();
898        let mut s0 = vec![T::zero(); nrow];
899        let mut s1 = vec![T::zero(); nrow];
900        let mut s2 = vec![T::zero(); nrow];
901
902        for j in 0..ncol {
903            if let Some(x_j) = self.get_col(j) {
904                for (&x_ij, &i) in x_j.values().iter().zip(x_j.row_indices()) {
905                    s0[i] += T::one();
906                    s1[i] += x_ij;
907                    s2[i] += x_ij * x_ij;
908                }
909            }
910        }
911
912        let mu = s1
913            .into_iter()
914            .zip(s0.iter())
915            .map(|(x, &n)| x / n.max(T::one()))
916            .collect::<Vec<_>>();
917
918        let sig = s2
919            .into_iter()
920            .zip(mu.iter())
921            .zip(s0.iter())
922            .map(|((s2, &mu), &s0)| (s2 / s0.max(T::one()) - mu * mu).sqrt())
923            .collect::<Vec<_>>();
924
925        for j in 0..ncol {
926            if let Some(mut x_j) = self.get_col_mut(j) {
927                let (rows, values) = x_j.rows_and_values_mut();
928
929                for (&i, x_ij) in rows.iter().zip(values) {
930                    let mu_i = mu[i];
931                    let sig_i = sig[i];
932                    if sig_i > T::zero() {
933                        *x_ij = (*x_ij - mu_i) / sig_i;
934                    } else {
935                        *x_ij -= mu_i;
936                    }
937                }
938            }
939        }
940    }
941
942    fn scale_columns(&self) -> Self::Mat {
943        let mut ret = self.clone();
944        ret.scale_columns_inplace();
945        ret
946    }
947
948    fn scale_rows(&self) -> Self::Mat {
949        let mut ret = self.clone();
950        ret.scale_rows_inplace();
951        ret
952    }
953
954    fn centre_columns_inplace(&mut self) {
955        let ncol = self.ncols();
956
957        for j in 0..ncol {
958            if let Some(x_j) = self.get_col(j) {
959                let mut s0 = T::zero();
960                let mut s1 = T::zero();
961
962                for &x_ij in x_j.values() {
963                    s0 += T::one();
964                    s1 += x_ij;
965                }
966
967                let mu = s1 / s0.max(T::one());
968
969                if let Some(mut x_j) = self.get_col_mut(j) {
970                    for x_ij in x_j.values_mut() {
971                        *x_ij -= mu;
972                    }
973                }
974            }
975        }
976    }
977
978    fn centre_columns(&self) -> Self::Mat {
979        let mut ret = self.clone();
980        ret.centre_columns_inplace();
981        ret
982    }
983}
984
985impl<T> MatOps for DMatrix<T>
986where
987    T: nalgebra::RealField,
988{
989    type Mat = Self;
990    type Scalar = T;
991
992    fn normalize_exp_logits_columns_inplace(&mut self) {
993        for mut x_j in self.column_iter_mut() {
994            let log_max = x_j.max();
995            let denom = x_j.map(|l| (l - log_max.clone()).exp()).sum();
996            x_j.iter_mut()
997                .for_each(|l| *l = (l.clone() - log_max.clone()).exp() / denom.clone());
998        }
999    }
1000
1001    fn normalize_exp_logits_columns(&self) -> Self::Mat {
1002        let mut ret = self.clone();
1003        ret.normalize_exp_logits_columns_inplace();
1004        ret
1005    }
1006
1007    fn log_softmax_columns_inplace(&mut self) {
1008        for mut x_j in self.column_iter_mut() {
1009            let log_max = x_j.max();
1010            let denom = x_j.map(|l| (l - log_max.clone()).exp()).sum();
1011            let lse = log_max + denom.ln();
1012            x_j.iter_mut().for_each(|l| *l = l.clone() - lse.clone());
1013        }
1014    }
1015
1016    fn log_softmax_columns(&self) -> Self::Mat {
1017        let mut ret = self.clone();
1018        ret.log_softmax_columns_inplace();
1019        ret
1020    }
1021
1022    fn sum_to_one_columns_inplace(&mut self) {
1023        self.column_iter_mut()
1024            .for_each(|mut c| c.unscale_mut(c.sum()));
1025    }
1026
1027    fn sum_to_one_columns(&self) -> Self::Mat {
1028        let mut ret = self.clone();
1029        ret.sum_to_one_columns_inplace();
1030        ret
1031    }
1032
1033    fn sum_to_one_rows_inplace(&mut self) {
1034        self.row_iter_mut().for_each(|mut r| r.unscale_mut(r.sum()));
1035    }
1036
1037    fn sum_to_one_rows(&self) -> Self::Mat {
1038        let mut ret = self.clone();
1039        ret.sum_to_one_rows_inplace();
1040        ret
1041    }
1042
1043    fn normalize_columns_inplace(&mut self) {
1044        let floor = T::from_f64(1e-8).unwrap();
1045        dense_columns_par(self, |mut xx_j| {
1046            let denom = xx_j.norm().max(floor.clone());
1047            xx_j /= denom;
1048        });
1049    }
1050
1051    fn normalize_columns(&self) -> Self::Mat {
1052        let mut ret = self.clone();
1053        ret.normalize_columns_inplace();
1054        ret
1055    }
1056
1057    fn scale_columns_inplace(&mut self) {
1058        dense_columns_par(self, |mut xx_j| {
1059            let mu = xx_j.mean();
1060            let sig = xx_j.variance().sqrt();
1061            xx_j.add_scalar_mut(-mu);
1062            if sig > T::zero() {
1063                xx_j /= sig;
1064            }
1065        });
1066    }
1067
1068    fn scale_rows_inplace(&mut self) {
1069        for mut xx_i in self.row_iter_mut() {
1070            let mu = xx_i.mean();
1071            let sig = xx_i.variance().sqrt();
1072            xx_i.add_scalar_mut(-mu);
1073            if sig > T::zero() {
1074                xx_i /= sig;
1075            }
1076        }
1077    }
1078
1079    fn scale_columns(&self) -> Self::Mat {
1080        let mut ret = self.clone();
1081        ret.scale_columns_inplace();
1082        ret
1083    }
1084
1085    fn scale_rows(&self) -> Self::Mat {
1086        let mut ret = self.clone();
1087        ret.scale_rows_inplace();
1088        ret
1089    }
1090
1091    fn centre_columns_inplace(&mut self) {
1092        for mut xx_j in self.column_iter_mut() {
1093            let mu = xx_j.mean();
1094            xx_j.add_scalar_mut(-mu);
1095        }
1096    }
1097
1098    fn centre_columns(&self) -> Self::Mat {
1099        let mut ret = self.clone();
1100        ret.centre_columns_inplace();
1101        ret
1102    }
1103}
1104
1105/// TF-IDF (Term Frequency–Inverse Document Frequency)
1106///
1107/// A numerical statistic reflecting how important a word (term) is to a document
1108/// in a collection or corpus. (Wikipedia)
1109///
1110/// Given a term-document matrix where rows are terms and columns are documents:
1111///
1112/// - **TF (Term Frequency)**: The raw count or frequency of term t in document d.
1113///   Here we use the matrix values directly as TF.
1114///
1115/// - **IDF (Inverse Document Frequency)**: A measure of how much information
1116///   the term provides, i.e., how common or rare it is across all documents.
1117///
1118///   IDF(t) = log(N / df(t))
1119///
1120///   where N = total number of documents, df(t) = number of documents containing term t.
1121///   We use log(N / (df(t) + 1)) to avoid division by zero.
1122///
1123/// - **TF-IDF(t, d) = TF(t, d) × IDF(t)**
1124///
1125/// Terms appearing in many documents get lower weight; terms specific to few
1126/// documents get higher weight.
1127impl<T> TfIdfOps for DMatrix<T>
1128where
1129    T: nalgebra::RealField,
1130{
1131    type Mat = Self;
1132
1133    fn tfidf(&self) -> Self::Mat {
1134        let (nrows, ncols) = self.shape();
1135        let n_docs = T::from_usize(ncols).unwrap();
1136        let mut result = self.clone();
1137
1138        for i in 0..nrows {
1139            // df(t) = document frequency = number of documents containing term t
1140            let df = (0..ncols).filter(|&j| self[(i, j)] != T::zero()).count();
1141            let df_t = T::from_usize(df).unwrap();
1142            // IDF(t) = log(N / (df(t) + 1))
1143            let idf = (n_docs.clone() / (df_t + T::one())).ln();
1144            // TF-IDF(t, d) = TF(t, d) × IDF(t)
1145            for j in 0..ncols {
1146                result[(i, j)] = result[(i, j)].clone() * idf.clone();
1147            }
1148        }
1149        result
1150    }
1151
1152    fn tfidf_normalize_columns(&self) -> Self::Mat {
1153        let mut result = self.tfidf();
1154        result.normalize_columns_inplace();
1155        result
1156    }
1157}
1158
1159////////////////////////////////////////
1160// Input and output in triplet format //
1161////////////////////////////////////////
1162
1163impl<T> MatTriplets for DMatrix<T>
1164where
1165    T: nalgebra::RealField + Float,
1166{
1167    type Mat = Self;
1168    type Scalar = T;
1169
1170    fn from_nonzero_triplets<I>(
1171        nrow: usize,
1172        ncol: usize,
1173        triplets: &[(I, I, T)],
1174    ) -> anyhow::Result<Self::Mat>
1175    where
1176        I: TryInto<usize> + Copy,
1177        <I as TryInto<usize>>::Error: std::fmt::Debug,
1178    {
1179        let mut data = vec![T::zero(); ncol * nrow];
1180        for &(ii, jj, x_ij) in triplets {
1181            let ii: usize = ii.try_into().expect("failed to convert index ii");
1182            let jj: usize = jj.try_into().expect("failed to convert index jj");
1183            data[ii * ncol + jj] = x_ij;
1184        }
1185        Ok(DMatrix::from_row_slice(nrow, ncol, &data))
1186    }
1187
1188    fn to_nonzero_triplets(&self) -> anyhow::Result<NRowNColTriplets<Self::Scalar>> {
1189        if let Some(eps) = T::from(1e-6) {
1190            let nrow = self.nrows();
1191            let ncol = self.ncols();
1192            let mut triplets = vec![];
1193            for j in 0..ncol {
1194                for i in 0..nrow {
1195                    let x_ij = &self[(i, j)];
1196                    if x_ij.abs() > eps {
1197                        triplets.push((i, j, *x_ij));
1198                    }
1199                }
1200            }
1201            Ok(NRowNColTriplets {
1202                nrow,
1203                ncol,
1204                triplets,
1205            })
1206        } else {
1207            anyhow::bail!("eps is not defined")
1208        }
1209    }
1210}
1211
1212impl<T> MatTriplets for CsrMatrix<T>
1213where
1214    T: nalgebra::RealField + Float,
1215{
1216    type Mat = Self;
1217    type Scalar = T;
1218
1219    fn from_nonzero_triplets<I>(
1220        nrow: usize,
1221        ncol: usize,
1222        triplets: &[(I, I, Self::Scalar)],
1223    ) -> anyhow::Result<Self::Mat>
1224    where
1225        I: TryInto<usize> + Copy,
1226        <I as TryInto<usize>>::Error: std::fmt::Debug,
1227    {
1228        let mut coo = CooMatrix::<T>::new(nrow, ncol);
1229        for &(ii, jj, x_ij) in triplets {
1230            let ii: usize = ii.try_into().expect("failed to convert index ii");
1231            let jj: usize = jj.try_into().expect("failed to convert index jj");
1232            coo.push(ii, jj, x_ij);
1233        }
1234        Ok(CsrMatrix::from(&coo))
1235    }
1236    fn to_nonzero_triplets(&self) -> anyhow::Result<NRowNColTriplets<Self::Scalar>> {
1237        if let Some(eps) = T::from(1e-6) {
1238            let nrow = self.nrows();
1239            let ncol = self.ncols();
1240
1241            let mut triplets = Vec::new();
1242
1243            for i in 0..nrow {
1244                if let Some(x_i) = self.get_row(i) {
1245                    let cols = x_i.col_indices();
1246                    let vals = x_i.values();
1247                    for k in 0..cols.len() {
1248                        let j = cols[k];
1249                        let x_ij = vals[k];
1250                        if x_ij > eps {
1251                            triplets.push((i, j, x_ij))
1252                        };
1253                    }
1254                }
1255            }
1256
1257            Ok(NRowNColTriplets {
1258                nrow,
1259                ncol,
1260                triplets,
1261            })
1262        } else {
1263            anyhow::bail!("eps is not defined")
1264        }
1265    }
1266}
1267
1268impl<T> MatTriplets for CscMatrix<T>
1269where
1270    T: nalgebra::RealField + Float,
1271{
1272    type Mat = Self;
1273    type Scalar = T;
1274
1275    fn from_nonzero_triplets<I>(
1276        nrow: usize,
1277        ncol: usize,
1278        triplets: &[(I, I, Self::Scalar)],
1279    ) -> anyhow::Result<Self::Mat>
1280    where
1281        I: TryInto<usize> + Copy,
1282        <I as TryInto<usize>>::Error: std::fmt::Debug,
1283    {
1284        let mut coo = CooMatrix::<T>::new(nrow, ncol);
1285        for &(ii, jj, x_ij) in triplets {
1286            let ii: usize = ii.try_into().expect("failed to convert index ii");
1287            let jj: usize = jj.try_into().expect("failed to convert index jj");
1288            coo.push(ii, jj, x_ij);
1289        }
1290        Ok(CscMatrix::from(&coo))
1291    }
1292
1293    fn to_nonzero_triplets(&self) -> anyhow::Result<NRowNColTriplets<Self::Scalar>> {
1294        if let Some(eps) = T::from(1e-6) {
1295            let nrow = self.nrows();
1296            let ncol = self.ncols();
1297
1298            let mut triplets = Vec::new();
1299            for j in 0..ncol {
1300                if let Some(x_j) = self.get_col(j) {
1301                    let rows = x_j.row_indices();
1302                    let vals = x_j.values();
1303                    for k in 0..rows.len() {
1304                        let i = rows[k];
1305                        let x_ij = vals[k];
1306                        if x_ij > eps {
1307                            triplets.push((i, j, x_ij))
1308                        }
1309                    }
1310                }
1311            }
1312
1313            Ok(NRowNColTriplets {
1314                nrow,
1315                ncol,
1316                triplets,
1317            })
1318        } else {
1319            anyhow::bail!("eps is not defined")
1320        }
1321    }
1322}
1323
1324#[cfg(feature = "tensor")]
1325impl<T> CandleDataLoaderOps for DMatrix<T>
1326where
1327    T: nalgebra::RealField + Copy + candle_core::WithDType,
1328{
1329    type Scalar = T;
1330    type Mat = Self;
1331
1332    // fn transpose(&self) -> Self::Mat {
1333    //     self.transpose()
1334    // }
1335
1336    fn rows_to_tensor_vec(&self) -> Vec<candle_core::Tensor> {
1337        let mut idx_data = self
1338            .row_iter()
1339            .enumerate()
1340            .par_bridge()
1341            .map(|(i, row)| {
1342                let mut v =
1343                    candle_core::Tensor::from_iter(row.iter().copied(), &candle_core::Device::Cpu)
1344                        .expect("failed to create tensor");
1345                v = v.reshape((1, row.len())).expect("failed to reshape");
1346                (i, v)
1347            })
1348            .collect::<Vec<_>>();
1349
1350        idx_data.sort_by_key(|(i, _)| *i);
1351        idx_data.into_iter().map(|(_, t)| t).collect()
1352    }
1353
1354    fn data_shape(&self) -> (usize, usize) {
1355        (self.nrows(), self.ncols())
1356    }
1357
1358    fn row_to_f32_vec(&self, i: usize) -> Vec<f32> {
1359        let row_data: Vec<T> = self.row(i).iter().copied().collect();
1360        let t = candle_core::Tensor::from_vec(row_data, self.ncols(), &candle_core::Device::Cpu)
1361            .expect("tensor from row");
1362        t.to_dtype(candle_core::DType::F32)
1363            .expect("to f32")
1364            .to_vec1::<f32>()
1365            .expect("to vec")
1366    }
1367}
1368
1369#[cfg(test)]
1370mod par_tests {
1371    use super::*;
1372    use rand::{rngs::SmallRng, RngExt, SeedableRng};
1373
1374    /// A sparse matrix with empty columns and an all-zero-valued column.
1375    fn sparse(seed: u64) -> CscMatrix<f32> {
1376        let (nr, nc) = (37, 23);
1377        let mut rng = SmallRng::seed_from_u64(seed);
1378        let mut coo = CooMatrix::new(nr, nc);
1379        for j in 0..nc {
1380            if j % 5 == 3 {
1381                continue;
1382            }
1383            for i in 0..nr {
1384                if rng.random::<f32>() < 0.3 {
1385                    let v = if j == 7 {
1386                        0.0
1387                    } else {
1388                        rng.random::<f32>() * 9.0
1389                    };
1390                    coo.push(i, j, v);
1391                }
1392            }
1393        }
1394        CscMatrix::from(&coo)
1395    }
1396
1397    #[test]
1398    fn csc_log1p_and_sum_to_one_match_the_serial_loops() {
1399        let x = sparse(1);
1400        let mut want = x.clone();
1401        for v in want.values_mut() {
1402            *v = v.ln_1p();
1403        }
1404        assert_eq!(x.log1p().values(), want.values());
1405
1406        let mut want = x.clone();
1407        for j in 0..want.ncols() {
1408            let mut col = want.get_col_mut(j).unwrap();
1409            let denom: f32 = col.values().iter().fold(0.0, |a, &v| a + v);
1410            if denom > 0.0 {
1411                col.values_mut().iter_mut().for_each(|v| *v /= denom);
1412            }
1413        }
1414        let got = x.sum_to_one_columns();
1415        assert_eq!(got.col_offsets(), want.col_offsets());
1416        assert_eq!(got.row_indices(), want.row_indices());
1417        assert_eq!(got.values(), want.values());
1418    }
1419
1420    #[test]
1421    fn dense_scale_and_normalize_columns_match_the_serial_loops() {
1422        let mut rng = SmallRng::seed_from_u64(2);
1423        let mut x = DMatrix::<f32>::from_fn(31, 9, |_, _| rng.random::<f32>() * 5.0);
1424        x.column_mut(4).fill(2.5);
1425        let mut want = x.clone();
1426        for mut col in want.column_iter_mut() {
1427            let mu = col.mean();
1428            let sig = col.variance().sqrt();
1429            col.add_scalar_mut(-mu);
1430            if sig > 0.0 {
1431                col /= sig;
1432            }
1433        }
1434        assert_eq!(x.scale_columns(), want);
1435
1436        let mut want = x.clone();
1437        for mut col in want.column_iter_mut() {
1438            let denom = col.norm().max(1e-8);
1439            col /= denom;
1440        }
1441        assert_eq!(x.normalize_columns(), want);
1442        assert_eq!(DMatrix::<f32>::zeros(0, 3).scale_columns().shape(), (0, 3));
1443    }
1444}