1use crate::geometry::close_row;
2use crate::{CompositionError, Grouping, LabeledMatrix, Result};
3
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub struct StructuralZeroGrid {
6 components: Vec<String>,
7 groups: Vec<String>,
8 values: Vec<bool>,
9}
10
11impl StructuralZeroGrid {
12 #[must_use]
13 pub fn components(&self) -> &[String] {
14 &self.components
15 }
16
17 #[must_use]
18 pub fn groups(&self) -> &[String] {
19 &self.groups
20 }
21
22 #[must_use]
23 pub fn values(&self) -> &[bool] {
24 &self.values
25 }
26
27 #[must_use]
28 pub fn get(&self, component: usize, group: usize) -> Option<bool> {
29 self.values
30 .get(component.checked_mul(self.groups.len())? + group)
31 .copied()
32 }
33}
34
35pub fn multi_replace(matrix: &LabeledMatrix, delta: Option<f64>) -> Result<LabeledMatrix> {
36 let width = matrix.component_count();
37 let delta = delta.unwrap_or_else(|| (1.0 / width as f64).powi(2));
38 if !delta.is_finite() || delta <= 0.0 {
39 return Err(CompositionError::InvalidParameter {
40 name: "delta",
41 requirement: "greater than zero",
42 value: delta,
43 });
44 }
45 let mut values = Vec::with_capacity(matrix.values().len());
46 for (row, sample) in matrix.rows().zip(matrix.samples()) {
47 let closed = close_row(row, sample, matrix.components())?;
48 let zeros = closed.iter().filter(|&&value| value == 0.0).count();
49 let remaining = 1.0 - zeros as f64 * delta;
50 if remaining < 0.0 {
51 return Err(CompositionError::InvalidParameter {
52 name: "delta",
53 requirement: "small enough to keep replacement proportions non-negative",
54 value: delta,
55 });
56 }
57 values.extend(closed.into_iter().map(|value| {
58 if value == 0.0 {
59 delta
60 } else {
61 remaining * value
62 }
63 }));
64 }
65 matrix.same_shape(values)
66}
67
68pub fn structural_zeros(
69 matrix: &LabeledMatrix,
70 grouping: &Grouping,
71 negative_lower_bound: bool,
72) -> Result<StructuralZeroGrid> {
73 let labels = grouping.align(matrix)?;
74 let mut groups = labels.clone();
75 groups.sort_unstable();
76 groups.dedup();
77 let mut members = vec![Vec::new(); groups.len()];
78 for (row, label) in labels.iter().enumerate() {
79 members[groups.binary_search(label).unwrap()].push(row);
80 }
81 for (row_index, row) in matrix.rows().enumerate() {
82 for (column, &value) in row.iter().enumerate() {
83 if !value.is_finite() {
84 return Err(CompositionError::NonFinite {
85 sample: matrix.samples()[row_index].clone(),
86 component: matrix.components()[column].clone(),
87 value,
88 });
89 }
90 if value < 0.0 {
91 return Err(CompositionError::InvalidComponent {
92 sample: matrix.samples()[row_index].clone(),
93 component: matrix.components()[column].clone(),
94 value,
95 requirement: "non-negative",
96 });
97 }
98 }
99 }
100 let mut values = vec![false; matrix.component_count() * groups.len()];
101 for component in 0..matrix.component_count() {
102 for (group, rows) in members.iter().enumerate() {
103 let observations = rows.len() as f64;
104 let present = rows
105 .iter()
106 .filter(|&&row| matrix.values()[row * matrix.component_count() + component] != 0.0)
107 .count() as f64;
108 let prevalence = present / observations;
109 let lower = if negative_lower_bound {
110 prevalence - 1.96 * (prevalence * (1.0 - prevalence) / observations).sqrt()
111 } else {
112 prevalence
113 };
114 values[component * groups.len() + group] = lower <= 0.0;
115 }
116 }
117 Ok(StructuralZeroGrid {
118 components: matrix.components().to_vec(),
119 groups,
120 values,
121 })
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn matches_skbio_example() {
130 let matrix = LabeledMatrix::new(
131 vec!["s1".into(), "s2".into()],
132 ["a", "b", "c", "d"].map(str::to_owned).to_vec(),
133 vec![0.2, 0.4, 0.4, 0.0, 0.0, 0.5, 0.5, 0.0],
134 )
135 .unwrap();
136 let expected = [0.1875, 0.375, 0.375, 0.0625, 0.0625, 0.4375, 0.4375, 0.0625];
137 for (&actual, expected) in multi_replace(&matrix, None)
138 .unwrap()
139 .values()
140 .iter()
141 .zip(expected)
142 {
143 assert!((actual - expected).abs() < 1e-12);
144 }
145 }
146
147 #[test]
148 fn invalid_delta_fails_before_output() {
149 let matrix = LabeledMatrix::new(
150 vec!["s".into()],
151 ["a", "b", "c"].map(str::to_owned).to_vec(),
152 vec![1.0, 0.0, 0.0],
153 )
154 .unwrap();
155 for delta in [f64::NAN, -0.1, 0.0, 0.6] {
156 assert!(multi_replace(&matrix, Some(delta)).is_err());
157 }
158 }
159
160 #[test]
161 fn structural_zero_matches_skbio_example() {
162 let matrix = LabeledMatrix::new(
163 (0..10).map(|index| format!("s{index}")).collect(),
164 (0..6).map(|index| format!("f{index}")).collect(),
165 vec![
166 7.0, 1.0, 0.0, 11.0, 3.0, 1.0, 1.0, 1.0, 0.0, 13.0, 13.0, 0.0, 11.0, 5.0, 0.0, 1.0,
167 4.0, 1.0, 2.0, 2.0, 0.0, 16.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 6.0, 0.0, 14.0, 8.0,
168 7.0, 9.0, 0.0, 5.0, 0.0, 7.0, 4.0, 1.0, 0.0, 26.0, 8.0, 1.0, 4.0, 28.0, 0.0, 10.0,
169 2.0, 2.0, 2.0, 4.0, 0.0, 5.0, 6.0, 4.0, 10.0, 1.0, 0.0, 9.0,
170 ],
171 )
172 .unwrap();
173 let grouping = Grouping::new((0..10).map(|index| {
174 (
175 format!("s{index}"),
176 if index < 5 { "treatment" } else { "placebo" }.into(),
177 )
178 }))
179 .unwrap();
180 let result = structural_zeros(&matrix, &grouping, true).unwrap();
181 assert_eq!(result.groups(), ["placebo", "treatment"]);
182 assert_eq!(result.get(2, 1), Some(true));
183 assert_eq!(result.get(4, 0), Some(true));
184 assert_eq!(result.get(5, 1), Some(true));
185 }
186}