use std::collections::HashMap;
use crate::geometry::{softmax, validate_positive};
use crate::{Basis, CompositionError, LabeledMatrix, Result};
pub fn alr(matrix: &LabeledMatrix, reference: &str) -> Result<LabeledMatrix> {
if matrix.component_count() < 2 {
return Err(CompositionError::TooFewComponents {
found: matrix.component_count(),
required: 2,
});
}
let reference_index = matrix
.components()
.iter()
.position(|component| component == reference)
.ok_or_else(|| CompositionError::UnknownReference(reference.to_owned()))?;
let components: Vec<String> = matrix
.components()
.iter()
.enumerate()
.filter(|(index, _)| *index != reference_index)
.map(|(_, component)| component.clone())
.collect();
let mut values = Vec::with_capacity(matrix.sample_count() * components.len());
for (row_index, row) in matrix.rows().enumerate() {
validate_positive(matrix, row_index, row)?;
let denominator = row[reference_index].ln();
values.extend(
row.iter()
.enumerate()
.filter(|(index, _)| *index != reference_index)
.map(|(_, value)| value.ln() - denominator),
);
}
matrix.shaped(components, values)
}
pub fn alr_inverse(
coordinates: &LabeledMatrix,
reference: &str,
reference_index: usize,
) -> Result<LabeledMatrix> {
let width = coordinates.component_count() + 1;
if reference_index >= width {
return Err(CompositionError::ReferenceOutOfRange {
index: reference_index,
width,
});
}
if coordinates
.components()
.iter()
.any(|component| component == reference)
{
return Err(CompositionError::DuplicateIdentity {
kind: "component",
identity: reference.to_owned(),
});
}
let mut components = coordinates.components().to_vec();
components.insert(reference_index, reference.to_owned());
let mut values = Vec::with_capacity(coordinates.sample_count() * width);
for (row_index, row) in coordinates.rows().enumerate() {
validate_coordinates(coordinates, row_index, row)?;
let mut expanded = Vec::with_capacity(width);
for index in 0..width {
expanded.push(if index == reference_index {
0.0
} else {
row[index - usize::from(index > reference_index)]
});
}
values.extend(softmax(
&expanded,
&coordinates.samples()[row_index],
&components,
)?);
}
coordinates.shaped(components, values)
}
pub fn clr(matrix: &LabeledMatrix) -> Result<LabeledMatrix> {
let mut values = Vec::with_capacity(matrix.values().len());
for (row_index, row) in matrix.rows().enumerate() {
validate_positive(matrix, row_index, row)?;
let mean = row.iter().map(|value| value.ln()).sum::<f64>() / row.len() as f64;
values.extend(row.iter().map(|value| value.ln() - mean));
}
matrix.same_shape(values)
}
pub fn clr_inverse(coordinates: &LabeledMatrix) -> Result<LabeledMatrix> {
let mut values = Vec::with_capacity(coordinates.values().len());
for (row_index, row) in coordinates.rows().enumerate() {
validate_coordinates(coordinates, row_index, row)?;
values.extend(softmax(
row,
&coordinates.samples()[row_index],
coordinates.components(),
)?);
}
coordinates.same_shape(values)
}
fn validate_coordinates(matrix: &LabeledMatrix, row_index: usize, row: &[f64]) -> Result<()> {
if let Some(component_index) = row.iter().position(|value| !value.is_finite()) {
Err(CompositionError::NonFiniteCoordinate {
sample: matrix.samples()[row_index].clone(),
component: matrix.components()[component_index].clone(),
})
} else {
Ok(())
}
}
pub fn rclr(matrix: &LabeledMatrix) -> Result<LabeledMatrix> {
let mut values = Vec::with_capacity(matrix.values().len());
for (row_index, row) in matrix.rows().enumerate() {
for (component_index, &value) in row.iter().enumerate() {
if value.is_infinite() || value < 0.0 {
return Err(if value.is_infinite() {
CompositionError::NonFinite {
sample: matrix.samples()[row_index].clone(),
component: matrix.components()[component_index].clone(),
value,
}
} else {
CompositionError::InvalidComponent {
sample: matrix.samples()[row_index].clone(),
component: matrix.components()[component_index].clone(),
value,
requirement: "non-negative or NaN for missing data",
}
});
}
}
let observed: Vec<f64> = row
.iter()
.copied()
.filter(|value| *value > 0.0 && !value.is_nan())
.collect();
if observed.is_empty() {
return Err(CompositionError::EmptyComposition(
matrix.samples()[row_index].clone(),
));
}
let mean = observed.iter().map(|value| value.ln()).sum::<f64>() / observed.len() as f64;
values.extend(row.iter().map(|&value| {
if value > 0.0 && !value.is_nan() {
value.ln() - mean
} else {
f64::NAN
}
}));
}
matrix.same_shape(values)
}
pub fn ilr(matrix: &LabeledMatrix, basis: &Basis) -> Result<LabeledMatrix> {
if matrix.component_count() < 2 {
return Err(CompositionError::TooFewComponents {
found: matrix.component_count(),
required: 2,
});
}
let order = basis.component_order(matrix.components())?;
let width = matrix.component_count();
let mut values = Vec::with_capacity(matrix.sample_count() * (width - 1));
for (row_index, row) in matrix.rows().enumerate() {
validate_positive(matrix, row_index, row)?;
let logs: Vec<f64> = row.iter().map(|value| value.ln()).collect();
for balance in 0..width - 1 {
let basis_row = basis.row(balance).unwrap();
values.push(
basis_row
.iter()
.enumerate()
.map(|(column, &coefficient)| coefficient * logs[order[column]])
.sum(),
);
}
}
matrix.shaped(basis.balances().to_vec(), values)
}
pub fn ilr_default(matrix: &LabeledMatrix) -> Result<LabeledMatrix> {
let width = matrix.component_count();
if width < 2 {
return Err(CompositionError::TooFewComponents {
found: width,
required: 2,
});
}
let scales: Vec<f64> = (1..width)
.map(|count| (count as f64 / (count + 1) as f64).sqrt())
.collect();
let mut values = Vec::with_capacity(matrix.sample_count() * (width - 1));
for (row_index, row) in matrix.rows().enumerate() {
validate_positive(matrix, row_index, row)?;
let logged: Vec<f64> = row.iter().map(|value| value.ln()).collect();
let mut prefix = 0.0;
for balance in 0..width - 1 {
let count = balance + 1;
prefix += logged[balance];
values.push(scales[balance] * (prefix / count as f64 - logged[count]));
}
}
matrix.shaped(
(0..width - 1)
.map(|index| format!("balance{index}"))
.collect(),
values,
)
}
pub fn ilr_inverse(coordinates: &LabeledMatrix, basis: &Basis) -> Result<LabeledMatrix> {
let order = basis.balance_order(coordinates.components())?;
let width = basis.components().len();
let mut values = Vec::with_capacity(coordinates.sample_count() * width);
for (row_index, row) in coordinates.rows().enumerate() {
let mut clr = vec![0.0; width];
for (basis_row, &coordinate_index) in order.iter().enumerate() {
let coordinate = row[coordinate_index];
if !coordinate.is_finite() {
return Err(CompositionError::NonFiniteCoordinate {
sample: coordinates.samples()[row_index].clone(),
component: coordinates.components()[coordinate_index].clone(),
});
}
for (slot, &coefficient) in clr.iter_mut().zip(basis.row(basis_row).unwrap()) {
*slot += coordinate * coefficient;
}
}
values.extend(softmax(
&clr,
&coordinates.samples()[row_index],
basis.components(),
)?);
}
coordinates.shaped(basis.components().to_vec(), values)
}
pub fn ilr_default_inverse(
coordinates: &LabeledMatrix,
components: Vec<String>,
) -> Result<LabeledMatrix> {
let width = coordinates.component_count() + 1;
if components.len() != width {
return Err(CompositionError::ComponentMismatch {
details: format!(
"default inverse needs {width} target components, got {}",
components.len()
),
});
}
let coordinate_index: HashMap<&str, usize> = coordinates
.components()
.iter()
.enumerate()
.map(|(index, name)| (name.as_str(), index))
.collect();
let order: Result<Vec<usize>> = (0..width - 1)
.map(|index| {
let name = format!("balance{index}");
coordinate_index.get(name.as_str()).copied().ok_or_else(|| {
CompositionError::ComponentMismatch {
details: format!("coordinates are missing balance {name:?}"),
}
})
})
.collect();
let order = order?;
let scales: Vec<f64> = (1..width)
.map(|count| (count as f64 / (count + 1) as f64).sqrt())
.collect();
let mut values = Vec::with_capacity(coordinates.sample_count() * width);
for (row_index, row) in coordinates.rows().enumerate() {
validate_coordinates(coordinates, row_index, row)?;
let weighted: Vec<f64> = order
.iter()
.enumerate()
.map(|(balance, &column)| row[column] * scales[balance])
.collect();
let mut suffix: f64 = weighted
.iter()
.enumerate()
.map(|(balance, value)| value / (balance + 1) as f64)
.sum();
let mut clr = Vec::with_capacity(width);
for component in 0..width {
clr.push(
suffix
- component
.checked_sub(1)
.map_or(0.0, |index| weighted[index]),
);
if component < width - 1 {
suffix -= weighted[component] / (component + 1) as f64;
}
}
values.extend(softmax(
&clr,
&coordinates.samples()[row_index],
&components,
)?);
}
coordinates.shaped(components, values)
}
#[cfg(test)]
mod tests {
use super::*;
fn example() -> LabeledMatrix {
LabeledMatrix::new(
vec!["s".into()],
vec!["a".into(), "b".into(), "c".into(), "d".into()],
vec![0.1, 0.3, 0.4, 0.2],
)
.unwrap()
}
#[test]
fn alr_uses_named_reference() {
let result = alr(&example(), "a").unwrap();
assert_eq!(result.components(), ["b", "c", "d"]);
let expected = [3.0_f64.ln(), 4.0_f64.ln(), 2.0_f64.ln()];
for (&actual, expected) in result.values().iter().zip(expected) {
assert!((actual - expected).abs() < 1e-12);
}
}
#[test]
fn alr_round_trip_preserves_identity() {
let transformed = alr(&example(), "c").unwrap();
let inverse = alr_inverse(&transformed, "c", 2).unwrap();
assert_eq!(inverse.components(), example().components());
for (&actual, &expected) in inverse.values().iter().zip(example().values()) {
assert!((actual - expected).abs() < 1e-12);
}
}
#[test]
fn clr_round_trip_and_zero_sum() {
let transformed = clr(&example()).unwrap();
assert!(transformed.values().iter().sum::<f64>().abs() < 1e-15);
let inverse = clr_inverse(&transformed).unwrap();
for (&actual, &expected) in inverse.values().iter().zip(example().values()) {
assert!((actual - expected).abs() < 1e-12);
}
}
#[test]
fn inverse_rejects_non_finite_coordinates() {
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let matrix = LabeledMatrix::new(
vec!["s".into()],
vec!["a".into(), "b".into()],
vec![value, 0.0],
)
.unwrap();
assert!(matches!(
clr_inverse(&matrix),
Err(CompositionError::NonFiniteCoordinate { .. })
));
assert!(matches!(
alr_inverse(&matrix, "reference", 0),
Err(CompositionError::NonFiniteCoordinate { .. })
));
}
}
#[test]
fn rclr_preserves_missing_mask() {
let matrix = LabeledMatrix::new(
vec!["s".into()],
vec!["a".into(), "b".into(), "c".into(), "d".into()],
vec![1.0, 2.0, 0.0, f64::NAN],
)
.unwrap();
let result = rclr(&matrix).unwrap();
assert!((result.values()[0] + 0.5 * 2.0_f64.ln()).abs() < 1e-12);
assert!((result.values()[1] - 0.5 * 2.0_f64.ln()).abs() < 1e-12);
assert!(result.values()[2].is_nan());
assert!(result.values()[3].is_nan());
}
#[test]
fn default_ilr_matches_skbio_and_round_trips() {
let input = example();
let basis = Basis::default_for(input.components().to_vec()).unwrap();
let transformed = ilr(&input, &basis).unwrap();
let linear = ilr_default(&input).unwrap();
for (&actual, &expected) in linear.values().iter().zip(transformed.values()) {
assert!((actual - expected).abs() < 1e-12);
}
let expected = [-0.7768362, -0.68339802, 0.11704769];
for (&actual, expected) in transformed.values().iter().zip(expected) {
assert!((actual - expected).abs() < 1e-7);
}
let inverse = ilr_inverse(&transformed, &basis).unwrap();
let linear_inverse = ilr_default_inverse(&linear, input.components().to_vec()).unwrap();
for (&actual, &expected) in linear_inverse.values().iter().zip(inverse.values()) {
assert!((actual - expected).abs() < 1e-12);
}
for (&actual, &expected) in inverse.values().iter().zip(input.values()) {
assert!((actual - expected).abs() < 1e-12);
}
}
#[test]
fn linear_default_matches_dense_basis_across_widths() {
for width in 2..32 {
let samples = vec!["s1".into(), "s2".into()];
let components: Vec<String> = (0..width).map(|index| format!("c{index}")).collect();
let values: Vec<f64> = (0..2 * width)
.map(|index| ((index * 17 + width * 3) % 101 + 1) as f64)
.collect();
let matrix = LabeledMatrix::new(samples, components.clone(), values).unwrap();
let basis = Basis::default_for(components.clone()).unwrap();
let dense = ilr(&matrix, &basis).unwrap();
let linear = ilr_default(&matrix).unwrap();
for (&actual, &expected) in linear.values().iter().zip(dense.values()) {
assert!((actual - expected).abs() < 1e-12);
}
let inverse = ilr_default_inverse(&linear, components).unwrap();
let closed = crate::closure(&matrix).unwrap();
for (&actual, &expected) in inverse.values().iter().zip(closed.values()) {
assert!((actual - expected).abs() < 1e-12);
}
}
}
#[test]
fn ilr_aligns_permuted_components() {
let input = LabeledMatrix::new(
vec!["s".into()],
vec!["c".into(), "a".into(), "b".into()],
vec![0.4, 0.1, 0.5],
)
.unwrap();
let basis = Basis::default_for(vec!["a".into(), "b".into(), "c".into()]).unwrap();
let inverse = ilr_inverse(&ilr(&input, &basis).unwrap(), &basis).unwrap();
assert_eq!(inverse.components(), basis.components());
assert!((inverse.values()[0] - 0.1).abs() < 1e-12);
assert!((inverse.values()[1] - 0.5).abs() < 1e-12);
assert!((inverse.values()[2] - 0.4).abs() < 1e-12);
}
}