Skip to main content

rsomics_composition/
geometry.rs

1use rayon::prelude::*;
2
3use crate::{CompositionError, LabeledMatrix, Result};
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct GramMatrix {
7    rows: Vec<String>,
8    columns: Vec<String>,
9    values: Vec<f64>,
10}
11
12impl GramMatrix {
13    #[must_use]
14    pub fn rows(&self) -> &[String] {
15        &self.rows
16    }
17
18    #[must_use]
19    pub fn columns(&self) -> &[String] {
20        &self.columns
21    }
22
23    #[must_use]
24    pub fn values(&self) -> &[f64] {
25        &self.values
26    }
27}
28
29pub fn closure(matrix: &LabeledMatrix) -> Result<LabeledMatrix> {
30    let rows: Result<Vec<Vec<f64>>> = matrix
31        .rows()
32        .zip(matrix.samples())
33        .map(|(row, sample)| close_row(row, sample, matrix.components()))
34        .collect();
35    matrix.same_shape(rows?.into_iter().flatten().collect())
36}
37
38pub fn perturb(
39    matrix: &LabeledMatrix,
40    operand: &LabeledMatrix,
41    inverse: bool,
42) -> Result<LabeledMatrix> {
43    let component_order = matrix.component_order_for(operand)?;
44    let row_order = if operand.sample_count() == 1 {
45        vec![0; matrix.sample_count()]
46    } else {
47        matrix.sample_order_for(operand)?
48    };
49    let width = matrix.component_count();
50    let operand_rows: Result<Vec<Vec<f64>>> = operand
51        .rows()
52        .zip(operand.samples())
53        .map(|(row, sample)| close_row(row, sample, operand.components()))
54        .collect();
55    let operand_rows = operand_rows?;
56    let values: Result<Vec<Vec<f64>>> = matrix
57        .rows()
58        .zip(matrix.samples())
59        .enumerate()
60        .map(|(row_index, (row, sample))| {
61            let closed = close_row(row, sample, matrix.components())?;
62            let operand = &operand_rows[row_order[row_index]];
63            let mut logs = Vec::with_capacity(width);
64            for (index, value) in closed.iter().copied().enumerate() {
65                let other = operand[component_order[index]];
66                if value == 0.0 || other == 0.0 {
67                    return Err(invalid_component(
68                        matrix,
69                        row_index,
70                        index,
71                        value.min(other),
72                        "strictly positive for perturbation",
73                    ));
74                }
75                logs.push(value.ln() + if inverse { -other.ln() } else { other.ln() });
76            }
77            softmax(&logs, sample, matrix.components())
78        })
79        .collect();
80    matrix.same_shape(values?.into_iter().flatten().collect())
81}
82
83pub fn power(matrix: &LabeledMatrix, exponent: f64) -> Result<LabeledMatrix> {
84    if !exponent.is_finite() {
85        return Err(CompositionError::NonFiniteScalar(exponent));
86    }
87    let values: Result<Vec<Vec<f64>>> = matrix
88        .rows()
89        .zip(matrix.samples())
90        .enumerate()
91        .map(|(row_index, (row, sample))| {
92            validate_nonnegative(matrix, row_index, row)?;
93            if exponent == 0.0 {
94                return Ok(vec![1.0 / row.len() as f64; row.len()]);
95            }
96            if exponent < 0.0
97                && let Some(index) = row.iter().position(|&value| value == 0.0)
98            {
99                return Err(invalid_component(
100                    matrix,
101                    row_index,
102                    index,
103                    0.0,
104                    "strictly positive for a negative power",
105                ));
106            }
107            let logs: Vec<f64> = row
108                .iter()
109                .map(|&value| {
110                    if value == 0.0 {
111                        f64::NEG_INFINITY
112                    } else {
113                        exponent * value.ln()
114                    }
115                })
116                .collect();
117            softmax(&logs, sample, matrix.components())
118        })
119        .collect();
120    matrix.same_shape(values?.into_iter().flatten().collect())
121}
122
123pub fn centralize(matrix: &LabeledMatrix) -> Result<LabeledMatrix> {
124    let closed = closure(matrix)?;
125    let width = matrix.component_count();
126    let mut center = vec![0.0; width];
127    for (row_index, row) in closed.rows().enumerate() {
128        validate_positive(&closed, row_index, row)?;
129        for (sum, &value) in center.iter_mut().zip(row) {
130            *sum += value.ln();
131        }
132    }
133    for value in &mut center {
134        *value /= matrix.sample_count() as f64;
135    }
136    let values: Result<Vec<Vec<f64>>> = closed
137        .rows()
138        .zip(closed.samples())
139        .map(|(row, sample)| {
140            let logs: Vec<f64> = row
141                .iter()
142                .zip(&center)
143                .map(|(&value, &center)| value.ln() - center)
144                .collect();
145            softmax(&logs, sample, closed.components())
146        })
147        .collect();
148    matrix.same_shape(values?.into_iter().flatten().collect())
149}
150
151pub fn inner(left: &LabeledMatrix, right: &LabeledMatrix) -> Result<GramMatrix> {
152    inner_with_limit(left, right, crate::DEFAULT_MAX_DENSE_CELLS)
153}
154
155pub fn inner_with_limit(
156    left: &LabeledMatrix,
157    right: &LabeledMatrix,
158    maximum_cells: usize,
159) -> Result<GramMatrix> {
160    let mut values = crate::limits::dense_vec(
161        "Aitchison inner-product matrix",
162        left.sample_count(),
163        right.sample_count(),
164        maximum_cells,
165        0.0,
166    )?;
167    let component_order = left.component_order_for(right)?;
168    let left_clr = crate::clr(left)?;
169    let right_clr = crate::clr(right)?;
170    let width = left.component_count();
171    let right_rows: Vec<&[f64]> = right_clr.rows().collect();
172    values
173        .par_chunks_mut(right.sample_count())
174        .zip(left_clr.values().par_chunks(width))
175        .for_each(|(output, left_row)| {
176            for (slot, right_row) in output.iter_mut().zip(&right_rows) {
177                *slot = left_row
178                    .iter()
179                    .enumerate()
180                    .map(|(index, &value)| value * right_row[component_order[index]])
181                    .sum();
182            }
183        });
184    Ok(GramMatrix {
185        rows: left.samples().to_vec(),
186        columns: right.samples().to_vec(),
187        values,
188    })
189}
190
191pub(crate) fn close_row(row: &[f64], sample: &str, components: &[String]) -> Result<Vec<f64>> {
192    let mut maximum = 0.0_f64;
193    for (index, &value) in row.iter().enumerate() {
194        if !value.is_finite() {
195            return Err(CompositionError::NonFinite {
196                sample: sample.to_owned(),
197                component: components[index].clone(),
198                value,
199            });
200        }
201        if value < 0.0 {
202            return Err(CompositionError::InvalidComponent {
203                sample: sample.to_owned(),
204                component: components[index].clone(),
205                value,
206                requirement: "non-negative",
207            });
208        }
209        maximum = maximum.max(value);
210    }
211    if maximum == 0.0 {
212        return Err(CompositionError::EmptyComposition(sample.to_owned()));
213    }
214    let scaled_sum: f64 = row.iter().map(|&value| value / maximum).sum();
215    Ok(row
216        .iter()
217        .map(|&value| (value / maximum) / scaled_sum)
218        .collect())
219}
220
221pub(crate) fn validate_positive(
222    matrix: &LabeledMatrix,
223    row_index: usize,
224    row: &[f64],
225) -> Result<()> {
226    validate_nonnegative(matrix, row_index, row)?;
227    if let Some(index) = row.iter().position(|&value| value == 0.0) {
228        return Err(invalid_component(
229            matrix,
230            row_index,
231            index,
232            0.0,
233            "strictly positive",
234        ));
235    }
236    Ok(())
237}
238
239pub(crate) fn validate_nonnegative(
240    matrix: &LabeledMatrix,
241    row_index: usize,
242    row: &[f64],
243) -> Result<()> {
244    for (index, &value) in row.iter().enumerate() {
245        if !value.is_finite() {
246            return Err(CompositionError::NonFinite {
247                sample: matrix.samples()[row_index].clone(),
248                component: matrix.components()[index].clone(),
249                value,
250            });
251        }
252        if value < 0.0 {
253            return Err(invalid_component(
254                matrix,
255                row_index,
256                index,
257                value,
258                "non-negative",
259            ));
260        }
261    }
262    if !row.iter().any(|&value| value > 0.0) {
263        return Err(CompositionError::EmptyComposition(
264            matrix.samples()[row_index].clone(),
265        ));
266    }
267    Ok(())
268}
269
270pub(crate) fn softmax(
271    coordinates: &[f64],
272    sample: &str,
273    components: &[String],
274) -> Result<Vec<f64>> {
275    for (index, &value) in coordinates.iter().enumerate() {
276        if value.is_nan() || value == f64::INFINITY {
277            return Err(CompositionError::NonFiniteCoordinate {
278                sample: sample.to_owned(),
279                component: components[index].clone(),
280            });
281        }
282    }
283    let maximum = coordinates
284        .iter()
285        .copied()
286        .fold(f64::NEG_INFINITY, f64::max);
287    if maximum == f64::NEG_INFINITY {
288        return Err(CompositionError::EmptyComposition(sample.to_owned()));
289    }
290    let mut output: Vec<f64> = coordinates
291        .iter()
292        .map(|&value| (value - maximum).exp())
293        .collect();
294    let sum: f64 = output.iter().sum();
295    for value in &mut output {
296        *value /= sum;
297    }
298    Ok(output)
299}
300
301fn invalid_component(
302    matrix: &LabeledMatrix,
303    row: usize,
304    component: usize,
305    value: f64,
306    requirement: &'static str,
307) -> CompositionError {
308    CompositionError::InvalidComponent {
309        sample: matrix.samples()[row].clone(),
310        component: matrix.components()[component].clone(),
311        value,
312        requirement,
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319
320    fn matrix(values: &[f64]) -> LabeledMatrix {
321        LabeledMatrix::new(
322            vec!["s1".into(), "s2".into()],
323            vec!["a".into(), "b".into(), "c".into()],
324            values.to_vec(),
325        )
326        .unwrap()
327    }
328
329    #[test]
330    fn closure_is_stable_at_extreme_scale() {
331        let result = closure(&matrix(&[f64::MAX, f64::MAX, 0.0, 1e-300, 2e-300, 3e-300])).unwrap();
332        assert_eq!(&result.values()[..3], &[0.5, 0.5, 0.0]);
333        assert!((result.values()[3] - 1.0 / 6.0).abs() < 1e-15);
334        assert!((result.values()[5] - 0.5).abs() < 1e-15);
335    }
336
337    #[test]
338    fn perturb_aligns_components_and_samples() {
339        let input = matrix(&[1.0, 2.0, 7.0, 2.0, 3.0, 5.0]);
340        let operand = LabeledMatrix::new(
341            vec!["broadcast".into()],
342            vec!["c".into(), "a".into(), "b".into()],
343            vec![2.0, 3.0, 1.0],
344        )
345        .unwrap();
346        let forward = perturb(&input, &operand, false).unwrap();
347        let back = perturb(&forward, &operand, true).unwrap();
348        let closed = closure(&input).unwrap();
349        for (&actual, &expected) in back.values().iter().zip(closed.values()) {
350            assert!((actual - expected).abs() < 1e-12);
351        }
352    }
353
354    #[test]
355    fn zero_power_is_uniform() {
356        let result = power(&matrix(&[0.0, 2.0, 3.0, 1.0, 2.0, 3.0]), 0.0).unwrap();
357        assert!(
358            result
359                .values()
360                .iter()
361                .all(|&value| (value - 1.0 / 3.0).abs() < 1e-15)
362        );
363    }
364
365    #[test]
366    fn centralize_matches_skbio_example() {
367        let table = LabeledMatrix::new(
368            vec!["s1".into(), "s2".into()],
369            vec!["a".into(), "b".into(), "c".into(), "d".into()],
370            vec![0.1, 0.3, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4],
371        )
372        .unwrap();
373        let expected = [
374            0.17445763, 0.30216948, 0.34891526, 0.17445763, 0.32495488, 0.18761279, 0.16247744,
375            0.32495488,
376        ];
377        for (&actual, expected) in centralize(&table).unwrap().values().iter().zip(expected) {
378            assert!((actual - expected).abs() < 1e-7);
379        }
380    }
381
382    #[test]
383    fn inner_is_clr_dot_product() {
384        let left = LabeledMatrix::new(
385            vec!["x".into()],
386            vec!["a".into(), "b".into(), "c".into(), "d".into()],
387            vec![0.1, 0.3, 0.4, 0.2],
388        )
389        .unwrap();
390        let right = LabeledMatrix::new(
391            vec!["y".into()],
392            vec!["d".into(), "c".into(), "b".into(), "a".into()],
393            vec![0.2, 0.2, 0.4, 0.2],
394        )
395        .unwrap();
396        assert!((inner(&left, &right).unwrap().values()[0] - 0.210785247375243).abs() < 1e-12);
397    }
398
399    #[test]
400    fn inner_limit_fails_before_computation() {
401        let input = matrix(&[1.0, 2.0, 3.0, 2.0, 3.0, 4.0]);
402        assert!(matches!(
403            inner_with_limit(&input, &input, 3),
404            Err(CompositionError::DenseMatrixTooLarge { .. })
405        ));
406    }
407}