use crate::diagram::{IntervalEnd, PersistenceDiagram};
use crate::{Error, Result, canonical_zero};
#[derive(Clone, Debug, PartialEq)]
pub struct LifetimeSummary {
finite_count: usize,
total_persistence: f64,
max_persistence: Option<f64>,
entropy: Option<f64>,
excluded_essential_count: usize,
excluded_censored_count: usize,
}
impl LifetimeSummary {
pub fn finite_count(&self) -> usize {
self.finite_count
}
pub fn total_persistence(&self) -> f64 {
self.total_persistence
}
pub fn max_persistence(&self) -> Option<f64> {
self.max_persistence
}
pub fn entropy(&self) -> Option<f64> {
self.entropy
}
pub fn excluded_essential_count(&self) -> usize {
self.excluded_essential_count
}
pub fn excluded_censored_count(&self) -> usize {
self.excluded_censored_count
}
}
pub fn finite_lifetime_summary(
diagram: &PersistenceDiagram,
dimension: usize,
) -> Result<LifetimeSummary> {
let view = diagram.dimension(dimension)?;
let mut summary = LifetimeSummary {
finite_count: 0,
total_persistence: 0.0,
max_persistence: None,
entropy: None,
excluded_essential_count: 0,
excluded_censored_count: 0,
};
let mut compensation = 0.0;
for interval in view.iter() {
match interval.end() {
IntervalEnd::Essential => summary.excluded_essential_count += 1,
IntervalEnd::RightCensored { .. } => summary.excluded_censored_count += 1,
IntervalEnd::Finite(death) => {
let lifetime = death - interval.birth();
if !lifetime.is_finite() {
return Err(Error::NumericalFailure {
context: "finite lifetime",
});
}
let corrected = lifetime - compensation;
let next = summary.total_persistence + corrected;
if !next.is_finite() {
return Err(Error::NumericalFailure {
context: "total persistence",
});
}
compensation = (next - summary.total_persistence) - corrected;
summary.total_persistence = next;
summary.max_persistence = Some(
summary
.max_persistence
.map_or(lifetime, |old| old.max(lifetime)),
);
summary.finite_count += 1;
}
}
}
if summary.finite_count > 0 {
let mut entropy = 0.0;
for interval in view.iter() {
if let IntervalEnd::Finite(death) = interval.end() {
let probability = (death - interval.birth()) / summary.total_persistence;
if probability > 0.0 {
entropy -= probability * probability.ln();
}
}
}
if !entropy.is_finite() {
return Err(Error::NumericalFailure {
context: "persistence entropy",
});
}
summary.entropy = Some(canonical_zero(entropy));
}
Ok(summary)
}