use crate::error::CalError;
use std::cmp::Ordering;
use std::fmt;
const MAX_SWEEPS: u32 = 400;
const STEP_TOLERANCE: f64 = 1e-9;
#[derive(Debug, Clone, PartialEq)]
pub struct CalParameter {
pub name: String,
pub value: f64,
pub lower: f64,
pub upper: f64,
}
impl CalParameter {
#[must_use]
pub fn new(name: impl Into<String>, value: f64, lower: f64, upper: f64) -> Self {
Self {
name: name.into(),
value,
lower,
upper,
}
}
#[must_use]
pub fn midpoint(&self) -> f64 {
self.lower.midpoint(self.upper)
}
#[must_use]
pub fn clamp(&self, x: f64) -> f64 {
if x < self.lower {
self.lower
} else if x > self.upper {
self.upper
} else {
x
}
}
}
impl fmt::Display for CalParameter {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} = {:.6} in [{:.6}, {:.6}]",
self.name, self.value, self.lower, self.upper
)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Curve {
points: Vec<(f64, f64)>,
}
impl Curve {
pub fn new(points: Vec<(f64, f64)>) -> Result<Self, CalError> {
if points.len() < 2 {
return Err(CalError::Unsupported {
subject: "calibration curve".to_string(),
reason: format!("{} point(s) given, at least 2 are required", points.len()),
});
}
if points
.iter()
.any(|&(x, y)| !x.is_finite() || !y.is_finite())
{
return Err(CalError::Unsupported {
subject: "calibration curve".to_string(),
reason: "points must be finite".to_string(),
});
}
if points.windows(2).any(|pair| match pair {
[first, second] => !matches!(first.0.partial_cmp(&second.0), Some(Ordering::Less)),
_ => true,
}) {
return Err(CalError::Unsupported {
subject: "calibration curve".to_string(),
reason: "abscissae must be strictly ascending".to_string(),
});
}
Ok(Self { points })
}
#[must_use]
pub fn points(&self) -> &[(f64, f64)] {
&self.points
}
#[must_use]
pub fn len(&self) -> usize {
self.points.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
#[must_use]
pub fn is_monotone(&self) -> bool {
let mut rising = false;
let mut falling = false;
for pair in self.points.windows(2) {
let [first, second] = pair else { continue };
if second.1 > first.1 {
rising = true;
} else if second.1 < first.1 {
falling = true;
}
}
!(rising && falling)
}
#[must_use]
pub fn eval(&self, x: f64) -> f64 {
let Some(&(first_x, first_y)) = self.points.first() else {
return f64::NAN;
};
if x <= first_x {
return first_y;
}
let Some(&(last_x, last_y)) = self.points.last() else {
return f64::NAN;
};
if x >= last_x {
return last_y;
}
for pair in self.points.windows(2) {
let [first, second] = pair else { continue };
let (x0, y0) = *first;
let (x1, y1) = *second;
if x >= x0 && x <= x1 {
let span = x1 - x0;
if span == 0.0 {
return y0;
}
return y0 + (y1 - y0) * (x - x0) / span;
}
}
last_y
}
}
impl fmt::Display for Curve {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "calibration curve ({} points):", self.points.len())?;
for &(x, y) in &self.points {
writeln!(f, " x = {x:>12.4} y = {y:>12.6}")?;
}
Ok(())
}
}
pub fn calibrate_curve(params: &[CalParameter]) -> Result<Curve, CalError> {
let mut nodes: Vec<(f64, &CalParameter)> = Vec::with_capacity(params.len());
for param in params {
validate_bounds(param)?;
nodes.push((param.midpoint(), param));
}
nodes.sort_by(|a, b| {
a.0.partial_cmp(&b.0)
.unwrap_or(std::cmp::Ordering::Equal)
.then_with(|| a.1.name.cmp(&b.1.name))
});
for pair in nodes.windows(2) {
let [first, second] = pair else { continue };
if first.0 == second.0 {
return Err(CalError::Unsupported {
subject: "calibration curve".to_string(),
reason: format!(
"nodes `{}` and `{}` share the abscissa {}",
first.1.name, second.1.name, first.0
),
});
}
}
let mut points: Vec<(f64, f64)> = Vec::with_capacity(nodes.len());
let mut direction = 0_i8;
for (abscissa, param) in &nodes {
if let Some(&(_, previous)) = points.last() {
if param.value > previous && direction < 0 {
return Err(CalError::NonMonotone {
name: param.name.clone(),
value: param.value,
previous,
});
}
if param.value < previous && direction > 0 {
return Err(CalError::NonMonotone {
name: param.name.clone(),
value: param.value,
previous,
});
}
if param.value > previous {
direction = 1;
} else if param.value < previous {
direction = -1;
}
}
points.push((*abscissa, param.value));
}
Curve::new(points)
}
fn validate_bounds(param: &CalParameter) -> Result<(), CalError> {
if !param.lower.is_finite() || !param.upper.is_finite() || !param.value.is_finite() {
return Err(CalError::Unsupported {
subject: format!("parameter `{}`", param.name),
reason: "value and bounds must be finite".to_string(),
});
}
if param.lower > param.upper {
return Err(CalError::OutOfBounds {
name: param.name.clone(),
value: param.lower,
lower: param.lower,
upper: param.upper,
});
}
Ok(())
}
pub fn optimal_point(
params: &[CalParameter],
objective: &dyn Fn(&[f64]) -> f64,
) -> Result<(Vec<f64>, f64), CalError> {
if params.is_empty() {
return Err(CalError::Unsupported {
subject: "optimiser".to_string(),
reason: "no parameters to optimise".to_string(),
});
}
for param in params {
validate_bounds(param)?;
}
let n = params.len();
let widths: Vec<f64> = params.iter().map(|p| p.upper - p.lower).collect();
let mut starts: Vec<Vec<f64>> = vec![params.iter().map(CalParameter::midpoint).collect()];
if n <= 8 {
for corner in 0..n {
for high_corner in [true, false] {
let mut point: Vec<f64> = params
.iter()
.map(|p| if high_corner { p.lower } else { p.upper })
.collect();
let Some(param) = params.get(corner) else {
continue;
};
let opposite = if high_corner {
param.upper
} else {
param.lower
};
if let Some(slot) = point.get_mut(corner) {
*slot = opposite;
}
starts.push(point);
}
}
}
let mut best: Option<(Vec<f64>, f64)> = None;
let mut worst_sweeps = 0_u32;
for start in starts {
match descend(params, &widths, objective, start) {
Ok(found) => {
let replace = best.as_ref().is_none_or(|(_, value)| found.1 > *value);
if replace {
best = Some(found);
}
}
Err(sweeps) => worst_sweeps = worst_sweeps.max(sweeps),
}
}
best.ok_or(CalError::Convergence {
iterations: worst_sweeps.max(1),
})
}
fn descend(
params: &[CalParameter],
widths: &[f64],
objective: &dyn Fn(&[f64]) -> f64,
mut point: Vec<f64>,
) -> Result<(Vec<f64>, f64), u32> {
for (index, param) in params.iter().enumerate() {
if let Some(slot) = point.get_mut(index) {
*slot = param.clamp(*slot);
}
}
let initial = objective(&point);
let mut value = if initial.is_finite() {
initial
} else {
f64::NEG_INFINITY
};
let mut steps: Vec<f64> = widths.iter().map(|w| 0.5 * w).collect();
let mut sweep = 0_u32;
loop {
if sweep >= MAX_SWEEPS {
return Err(MAX_SWEEPS);
}
sweep += 1;
let mut improved = false;
let mut attempted = false;
let mut finite_trial = false;
for index in 0..point.len() {
for direction in [1.0_f64, -1.0_f64] {
let step = steps.get(index).copied().unwrap_or(0.0);
let current = point.get(index).copied().unwrap_or(0.0);
let Some(param) = params.get(index) else {
continue;
};
let trial = param.clamp(current + direction * step);
if trial == current {
continue;
}
attempted = true;
let mut candidate = point.clone();
if let Some(slot) = candidate.get_mut(index) {
*slot = trial;
}
let score = objective(&candidate);
if !score.is_finite() {
continue;
}
finite_trial = true;
if score > value {
value = score;
point = candidate;
improved = true;
break;
}
}
}
if improved {
continue;
}
if !finite_trial {
return if attempted {
Err(sweep)
} else {
Ok((point, value))
};
}
let mut moving = false;
for step in &mut steps {
*step *= 0.5;
if *step > STEP_TOLERANCE {
moving = true;
}
}
if !moving {
return Ok((point, value));
}
}
}
pub fn optimize_working_point(
params: &[CalParameter],
objective: &dyn Fn(&[f64]) -> f64,
) -> Result<f64, CalError> {
optimal_point(params, objective).map(|(_, value)| value)
}