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