use crate::FitError;
use crate::error::invalid;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UncoveredPolicy {
Reject,
Unpenalized,
}
#[derive(Clone, Debug)]
pub struct DisjointGroups {
ncoefficients: usize,
groups: Vec<Vec<usize>>,
weights: Vec<f64>,
uncovered_policy: UncoveredPolicy,
uncovered: Vec<usize>,
}
impl DisjointGroups {
pub fn new(
ncoefficients: usize,
groups: Vec<Vec<usize>>,
weights: Vec<f64>,
uncovered_policy: UncoveredPolicy,
) -> Result<Self, FitError> {
if weights.len() != groups.len() {
return Err(invalid("group weights must have one entry per group"));
}
let mut owners = vec![None; ncoefficients];
for (group_index, (group, &weight)) in groups.iter().zip(&weights).enumerate() {
if group.is_empty() {
return Err(invalid(format!("group {group_index} must not be empty")));
}
if !weight.is_finite() || weight < 0.0 {
return Err(invalid(format!(
"weight for group {group_index} must be finite and nonnegative"
)));
}
for &coefficient in group {
if coefficient >= ncoefficients {
return Err(invalid(format!(
"coefficient {coefficient} in group {group_index} is out of range for {ncoefficients} coefficients"
)));
}
if let Some(previous) = owners[coefficient].replace(group_index) {
return Err(invalid(if previous == group_index {
format!(
"coefficient {coefficient} appears more than once in group {group_index}"
)
} else {
format!(
"coefficient {coefficient} is shared by groups {previous} and {group_index}"
)
}));
}
}
}
let mut uncovered = Vec::new();
for (coefficient, owner) in owners.iter().enumerate() {
if owner.is_none() {
if uncovered_policy == UncoveredPolicy::Reject {
return Err(invalid(format!(
"coefficient {coefficient} is not covered by any group"
)));
}
uncovered.push(coefficient);
}
}
Ok(Self {
ncoefficients,
groups,
weights,
uncovered_policy,
uncovered,
})
}
pub fn ncoefficients(&self) -> usize {
self.ncoefficients
}
pub fn groups(&self) -> &[Vec<usize>] {
&self.groups
}
pub fn weights(&self) -> &[f64] {
&self.weights
}
pub fn uncovered_policy(&self) -> UncoveredPolicy {
self.uncovered_policy
}
pub fn uncovered(&self) -> &[usize] {
&self.uncovered
}
}