use crate::de::{DEConfig, DEReport};
use std::sync::Arc;
pub(super) fn count_free_dimensions(lower_bounds: &[f64], upper_bounds: &[f64]) -> usize {
lower_bounds
.iter()
.zip(upper_bounds.iter())
.filter(|(lo, hi)| **hi > **lo)
.count()
.max(1)
}
pub(super) const MIN_DE_GENERATIONS: usize = 5000;
pub(super) fn derive_de_budget(
lower_bounds: &[f64],
upper_bounds: &[f64],
population: usize,
maxeval: usize,
) -> (usize, usize, usize) {
let n_free = count_free_dimensions(lower_bounds, upper_bounds);
let desired_population = population.max(1).min(maxeval.max(1));
let pop_multiplier = desired_population.div_ceil(n_free).max(4);
let population_size = pop_multiplier * n_free;
let computed = maxeval.saturating_sub(population_size) / population_size;
let budget_supports_floor = maxeval >= MIN_DE_GENERATIONS.saturating_mul(population_size);
let max_iter = if budget_supports_floor {
computed.max(MIN_DE_GENERATIONS)
} else {
let budget_generations = maxeval / population_size.max(1);
let capped = computed.max(1).min(budget_generations.max(1));
log::warn!(
"DE maxeval={} with population_size={} is below MIN_DE_GENERATIONS × pop = {}. \
Running {} generations (≈{} evals) instead of the usual {} floor — expect \
degraded convergence. Increase maxeval to {} or more to regain full exploration.",
maxeval,
population_size,
MIN_DE_GENERATIONS.saturating_mul(population_size),
capped,
capped
.saturating_mul(population_size)
.saturating_add(population_size),
MIN_DE_GENERATIONS,
MIN_DE_GENERATIONS.saturating_mul(population_size),
);
capped
};
(pop_multiplier, population_size, max_iter)
}
pub(super) fn register_de_constraint<T, F>(config: &mut DEConfig, constraint_fn: F, data: T)
where
T: Send + Sync + 'static,
F: Fn(&[f64], Option<&mut [f64]>, &T) -> f64 + Send + Sync + 'static,
{
config.penalty_ineq.push((
Arc::new(move |x| {
constraint_fn(
x.as_slice().expect("DE candidates are contiguous"),
None,
&data,
)
}),
1e3,
));
}
pub fn process_de_results(
x: &mut [f64],
result: DEReport,
algo_name: &str,
) -> Result<(String, f64), (String, f64)> {
if result.x.len() == x.len() {
for (i, &value) in result.x.iter().enumerate() {
x[i] = value;
}
}
let status = if result.success {
format!("AutoEQ {}: {}", algo_name, result.message)
} else {
format!("AutoEQ {}: {} (not converged)", algo_name, result.message)
};
Ok((status, result.fun))
}