use alloc::vec::Vec;
use rand_core::Rng;
use super::Formula;
use crate::cmaes::{CmaEs, Config};
use crate::{Limits, Objective};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FitConfig {
pub negative_weight: f64,
pub complexity_weight: f64,
pub sigma: f64,
pub evaluations: u64,
}
impl Default for FitConfig {
fn default() -> Self {
Self {
negative_weight: 2.0,
complexity_weight: 0.01,
sigma: 1.0,
evaluations: 3_000,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Fitted {
pub formula: Formula,
pub score: f64,
}
#[must_use]
pub fn score<S: AsRef<[f64]>>(
formula: &Formula,
positives: &[Vec<S>],
negatives: &[Vec<S>],
config: &FitConfig,
) -> f64 {
const BOUND: f64 = 1e6;
let mean = |values: &mut dyn Iterator<Item = f64>, count: usize| {
#[expect(clippy::cast_precision_loss, reason = "demonstration counts are small")]
let count = count.max(1) as f64;
values.sum::<f64>() / count
};
let rho = |trace: &Vec<S>| formula.robustness(trace).clamp(-BOUND, BOUND);
let satisfied = mean(&mut positives.iter().map(rho), positives.len());
let admitted = mean(
&mut negatives.iter().map(|t| rho(t).max(0.0)),
negatives.len(),
);
#[expect(clippy::cast_precision_loss, reason = "formula sizes are small")]
let complexity = formula.complexity() as f64;
satisfied - config.negative_weight * admitted - config.complexity_weight * complexity
}
pub fn fit<S: AsRef<[f64]>, R: Rng + ?Sized>(
template: &Formula,
positives: &[Vec<S>],
negatives: &[Vec<S>],
config: &FitConfig,
rng: &mut R,
) -> Fitted {
let start = template.thresholds();
if start.is_empty() {
return Fitted {
formula: template.clone(),
score: score(template, positives, negatives, config),
};
}
let mut objective = |thresholds: &Vec<f64>| {
-score(
&template.with_thresholds(thresholds),
positives,
negatives,
config,
)
};
let mut cma = CmaEs::new(start.clone(), config.sigma, Config::default());
let outcome = cma.minimize(
&mut objective,
&mut Limits::evaluations(config.evaluations),
&mut (),
rng,
);
let thresholds = outcome.best.map_or(start, |b| b.genome);
let formula = template.with_thresholds(&thresholds);
let fitted_score = -objective.evaluate(&thresholds);
Fitted {
formula,
score: fitted_score,
}
}