use crate::geometry::close_row;
use crate::{CompositionError, Grouping, LabeledMatrix, Result};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StructuralZeroGrid {
components: Vec<String>,
groups: Vec<String>,
values: Vec<bool>,
}
impl StructuralZeroGrid {
#[must_use]
pub fn components(&self) -> &[String] {
&self.components
}
#[must_use]
pub fn groups(&self) -> &[String] {
&self.groups
}
#[must_use]
pub fn values(&self) -> &[bool] {
&self.values
}
#[must_use]
pub fn get(&self, component: usize, group: usize) -> Option<bool> {
self.values
.get(component.checked_mul(self.groups.len())? + group)
.copied()
}
}
pub fn multi_replace(matrix: &LabeledMatrix, delta: Option<f64>) -> Result<LabeledMatrix> {
let width = matrix.component_count();
let delta = delta.unwrap_or_else(|| (1.0 / width as f64).powi(2));
if !delta.is_finite() || delta <= 0.0 {
return Err(CompositionError::InvalidParameter {
name: "delta",
requirement: "greater than zero",
value: delta,
});
}
let mut values = Vec::with_capacity(matrix.values().len());
for (row, sample) in matrix.rows().zip(matrix.samples()) {
let closed = close_row(row, sample, matrix.components())?;
let zeros = closed.iter().filter(|&&value| value == 0.0).count();
let remaining = 1.0 - zeros as f64 * delta;
if remaining < 0.0 {
return Err(CompositionError::InvalidParameter {
name: "delta",
requirement: "small enough to keep replacement proportions non-negative",
value: delta,
});
}
values.extend(closed.into_iter().map(|value| {
if value == 0.0 {
delta
} else {
remaining * value
}
}));
}
matrix.same_shape(values)
}
pub fn structural_zeros(
matrix: &LabeledMatrix,
grouping: &Grouping,
negative_lower_bound: bool,
) -> Result<StructuralZeroGrid> {
let labels = grouping.align(matrix)?;
let mut groups = labels.clone();
groups.sort_unstable();
groups.dedup();
let mut members = vec![Vec::new(); groups.len()];
for (row, label) in labels.iter().enumerate() {
members[groups.binary_search(label).unwrap()].push(row);
}
for (row_index, row) in matrix.rows().enumerate() {
for (column, &value) in row.iter().enumerate() {
if !value.is_finite() {
return Err(CompositionError::NonFinite {
sample: matrix.samples()[row_index].clone(),
component: matrix.components()[column].clone(),
value,
});
}
if value < 0.0 {
return Err(CompositionError::InvalidComponent {
sample: matrix.samples()[row_index].clone(),
component: matrix.components()[column].clone(),
value,
requirement: "non-negative",
});
}
}
}
let mut values = vec![false; matrix.component_count() * groups.len()];
for component in 0..matrix.component_count() {
for (group, rows) in members.iter().enumerate() {
let observations = rows.len() as f64;
let present = rows
.iter()
.filter(|&&row| matrix.values()[row * matrix.component_count() + component] != 0.0)
.count() as f64;
let prevalence = present / observations;
let lower = if negative_lower_bound {
prevalence - 1.96 * (prevalence * (1.0 - prevalence) / observations).sqrt()
} else {
prevalence
};
values[component * groups.len() + group] = lower <= 0.0;
}
}
Ok(StructuralZeroGrid {
components: matrix.components().to_vec(),
groups,
values,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn matches_skbio_example() {
let matrix = LabeledMatrix::new(
vec!["s1".into(), "s2".into()],
["a", "b", "c", "d"].map(str::to_owned).to_vec(),
vec![0.2, 0.4, 0.4, 0.0, 0.0, 0.5, 0.5, 0.0],
)
.unwrap();
let expected = [0.1875, 0.375, 0.375, 0.0625, 0.0625, 0.4375, 0.4375, 0.0625];
for (&actual, expected) in multi_replace(&matrix, None)
.unwrap()
.values()
.iter()
.zip(expected)
{
assert!((actual - expected).abs() < 1e-12);
}
}
#[test]
fn invalid_delta_fails_before_output() {
let matrix = LabeledMatrix::new(
vec!["s".into()],
["a", "b", "c"].map(str::to_owned).to_vec(),
vec![1.0, 0.0, 0.0],
)
.unwrap();
for delta in [f64::NAN, -0.1, 0.0, 0.6] {
assert!(multi_replace(&matrix, Some(delta)).is_err());
}
}
#[test]
fn structural_zero_matches_skbio_example() {
let matrix = LabeledMatrix::new(
(0..10).map(|index| format!("s{index}")).collect(),
(0..6).map(|index| format!("f{index}")).collect(),
vec![
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,
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,
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,
2.0, 2.0, 2.0, 4.0, 0.0, 5.0, 6.0, 4.0, 10.0, 1.0, 0.0, 9.0,
],
)
.unwrap();
let grouping = Grouping::new((0..10).map(|index| {
(
format!("s{index}"),
if index < 5 { "treatment" } else { "placebo" }.into(),
)
}))
.unwrap();
let result = structural_zeros(&matrix, &grouping, true).unwrap();
assert_eq!(result.groups(), ["placebo", "treatment"]);
assert_eq!(result.get(2, 1), Some(true));
assert_eq!(result.get(4, 0), Some(true));
assert_eq!(result.get(5, 1), Some(true));
}
}