use super::{
optimize_hint, parse_optimize_weights,
ranges::{RangeInput, range_bounds, range_rows},
};
use crate::loading::eval_number;
use glam::DVec3;
use indicatrix::{geometry::meet_solver::SolvedTier, optics::LightingPreset};
use indicatrix_cut_core::{
Design, DesignSolveError, ObjectivePreset, ObjectiveWeights, OptimizeConfig, OptimizeOptions,
design::tier_hinge_points,
free_tier_indices,
optimize::{effective_starts, inclusive_max_evaluations_for},
};
use std::collections::{BTreeMap, BTreeSet};
pub const CUSTOM_PRESET_INDEX: usize = ObjectivePreset::ALL.len();
pub const DEFAULT_CANDIDATES: usize = 3;
pub const MAX_CANDIDATES: usize = 5;
pub const DEFAULT_GIRDLE_FRACTION: f64 = 0.5;
pub const DEFAULT_BUDGET: usize = 800;
pub const DEFAULT_STARTS: usize = 8;
pub const MAX_STARTS: usize = 32;
const MAX_BUDGET: usize = 100_000;
const CANDIDATE_SEPARATION_DEG: f64 = 0.5;
const SMALL_DESIGN_TIERS: f64 = 12.0;
const SMALL_DESIGN_EVALUATION_MS: f64 = 7.0;
const FULL_SCORING_SECONDS: f64 = 1.3;
#[must_use]
pub fn preset_labels() -> Vec<&'static str> {
ObjectivePreset::ALL
.into_iter()
.map(ObjectivePreset::label)
.chain(["Custom"])
.collect()
}
#[must_use]
pub const fn preset_description(index: usize) -> &'static str {
if index < CUSTOM_PRESET_INDEX {
ObjectivePreset::from_index(index).description()
} else {
"Custom: set the three weights, the yield weight and the tone yourself."
}
}
#[must_use]
pub fn weights_for_preset(index: usize) -> Option<ObjectiveWeights> {
(index < CUSTOM_PRESET_INDEX).then(|| ObjectivePreset::from_index(index).weights())
}
#[must_use]
pub fn default_vary_anchored(design: &Design) -> bool {
free_tier_indices(design).is_empty()
}
pub fn parse_budget(text: &str) -> Result<usize, String> {
if text.trim().is_empty() {
return Ok(DEFAULT_BUDGET);
}
let value = eval_number(text, None).map_err(|error| error.message("Budget", text))?;
if !value.is_finite() || value < 0.5 {
return Err("Budget must be at least 1 evaluation.".to_string());
}
if value > MAX_BUDGET as f64 {
return Err(format!("Budget is at most {MAX_BUDGET} evaluations."));
}
Ok(value.round() as usize)
}
pub fn parse_starts(text: &str) -> Result<usize, String> {
if text.trim().is_empty() {
return Ok(DEFAULT_STARTS);
}
let value = eval_number(text, None).map_err(|error| error.message("Starts", text))?;
if !value.is_finite() || value.fract().abs() > 1e-9 || value < 0.5 {
return Err("Starts must be a whole number, 1 or more.".to_string());
}
if value > MAX_STARTS as f64 + 0.5 {
return Err(format!("Starts is at most {MAX_STARTS}."));
}
Ok(value.round() as usize)
}
pub fn parse_seed(text: &str) -> Result<u64, String> {
if text.trim().is_empty() {
return Ok(0);
}
let value = eval_number(text, None).map_err(|error| error.message("Seed", text))?;
if !value.is_finite() || value < 0.0 || value.fract().abs() > 1e-9 || value > 9.0e15 {
return Err("Seed must be a whole number, 0 or more.".to_string());
}
Ok(value as u64)
}
#[derive(Debug, Clone, Copy)]
pub struct RunForm<'a> {
pub preset_index: usize,
pub weight_windowing: &'a str,
pub weight_extinction: &'a str,
pub weight_tilt_brilliance: &'a str,
pub yield_weight: f32,
pub tone: f32,
pub vary_anchored: bool,
pub keep_girdle: bool,
pub budget_text: &'a str,
pub starts: usize,
pub seed_text: &'a str,
pub polish: bool,
pub candidates: usize,
pub ranges: &'a [RangeInput],
}
#[derive(Debug, Clone, PartialEq)]
pub struct RunPlan {
pub config: OptimizeConfig,
pub options: OptimizeOptions,
pub movable_tiers: usize,
}
pub fn build_run_plan(
design: &Design,
form: &RunForm<'_>,
lighting: LightingPreset,
) -> Result<RunPlan, String> {
let weights = match weights_for_preset(form.preset_index) {
Some(weights) => weights,
None => parse_optimize_weights(
form.weight_windowing,
form.weight_extinction,
form.weight_tilt_brilliance,
form.yield_weight,
form.tone,
)?,
};
let max_evaluations = parse_budget(form.budget_text)?;
let seed = parse_seed(form.seed_text)?;
let angle_bounds = range_bounds(design, form.vary_anchored, form.ranges)?;
let mut config = OptimizeConfig {
weights,
seed,
max_evaluations,
starts: form.starts.clamp(1, MAX_STARTS),
lighting,
..OptimizeConfig::default()
};
if !form.polish {
config.polish_start_step_deg = None;
}
let movable_tiers = range_rows(design, form.vary_anchored)
.iter()
.filter(|row| !row.driven)
.count();
let options = OptimizeOptions {
vary_anchored: form.vary_anchored,
anchor_hinges: BTreeMap::new(),
angle_bounds,
min_girdle_fraction: form.keep_girdle.then_some(DEFAULT_GIRDLE_FRACTION),
min_girdle_thinnest_fraction: None,
keep_candidates: form.candidates.clamp(1, MAX_CANDIDATES),
candidate_separation_deg: Some(CANDIDATE_SEPARATION_DEG),
shape_target: None,
};
Ok(RunPlan {
config,
options,
movable_tiers,
})
}
pub fn fill_anchor_hinges(
options: &mut OptimizeOptions,
design: &Design,
hinges: &BTreeMap<usize, DVec3>,
only: Option<&BTreeSet<usize>>,
) {
options.anchor_hinges = hinges
.iter()
.filter(|(index, _)| !design.is_tier_driven(**index))
.filter(|(index, _)| only.is_none_or(|selected| selected.contains(*index)))
.map(|(index, hinge)| (*index, *hinge))
.collect();
}
pub fn measure_anchor_hinges(
options: &mut OptimizeOptions,
design: &Design,
solved: &[SolvedTier],
only: Option<&BTreeSet<usize>>,
) {
let hinges = tier_hinge_points(design, solved);
fill_anchor_hinges(options, design, &hinges, only);
}
pub fn prepare_anchor_hinges(
design: &Design,
options: &mut OptimizeOptions,
only: Option<&BTreeSet<usize>>,
) -> Result<(), DesignSolveError> {
if !options.vary_anchored {
return Ok(());
}
let solved = design.solve()?;
measure_anchor_hinges(options, design, &solved, only);
Ok(())
}
#[must_use]
pub fn optimize_availability(
design: &Design,
max_evaluations: usize,
vary_anchored: bool,
) -> (bool, String) {
let (available, hint) = optimize_hint(design, max_evaluations);
if available {
return (true, hint);
}
let movable = range_rows(design, vary_anchored)
.iter()
.filter(|row| !row.driven)
.count();
if vary_anchored && movable > 0 {
return (
true,
format!(
"Turns {movable} tier(s) about the edge each keeps on the girdle, scored on \
windowing, extinction and tilt brilliance, and the face-up tone when a tone \
objective is chosen, under a fixed canonical light pose. It runs in the \
background and can be cancelled."
),
);
}
(
false,
format!(
"{hint} Or tick \"Vary anchored tiers\" in the Optimize tab to turn them about \
their girdle edges."
),
)
}
#[must_use]
pub fn estimate_run_seconds(
tier_count: usize,
free_tiers: usize,
evaluations: usize,
candidates: usize,
starts: usize,
measured_ms_per_evaluation: Option<f64>,
) -> f64 {
let scale = (tier_count as f64 / SMALL_DESIGN_TIERS).max(1.0);
let scorings = (candidates.clamp(1, MAX_CANDIDATES) + 1) as f64;
let config = OptimizeConfig {
max_evaluations: evaluations,
starts,
..OptimizeConfig::default()
};
let effective = effective_starts(&config, free_tiers);
let (searched, lanes) = if effective > 1 {
(
inclusive_max_evaluations_for(&config, candidates.clamp(1, MAX_CANDIDATES), free_tiers),
estimate_lanes(effective),
)
} else {
(evaluations, 1)
};
let per_evaluation_ms = measured_ms_per_evaluation
.unwrap_or_else(|| SMALL_DESIGN_EVALUATION_MS * scale * scale / lanes as f64);
(searched as f64).mul_add(per_evaluation_ms / 1000.0, scorings * FULL_SCORING_SECONDS)
}
fn estimate_lanes(effective_starts: usize) -> usize {
if cfg!(target_arch = "wasm32") {
return 1;
}
let cores = std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get);
effective_starts.min(cores / 2).max(1)
}
#[must_use]
pub fn measured_ms_per_evaluation(
elapsed_secs: f64,
evaluations: usize,
candidates_found: usize,
) -> Option<f64> {
if evaluations < 20 || !elapsed_secs.is_finite() {
return None;
}
let scorings = (candidates_found.max(1) + 1) as f64 * FULL_SCORING_SECONDS;
let searching = elapsed_secs - scorings;
(searching > 0.0).then_some(searching / evaluations as f64 * 1000.0)
}
#[must_use]
pub fn format_duration(seconds: f64) -> String {
if !seconds.is_finite() || seconds < 0.0 {
return "unknown".to_string();
}
if seconds < 2.0 {
"a second or two".to_string()
} else if seconds < 60.0 {
let rounded = if seconds < 10.0 {
seconds.round()
} else {
(seconds / 5.0).round() * 5.0
};
format!("about {rounded:.0} seconds")
} else if seconds < 5400.0 {
let minutes = (seconds / 60.0).round();
if minutes < 1.5 {
"about 1 minute".to_string()
} else {
format!("about {minutes:.0} minutes")
}
} else {
format!("about {:.1} hours", seconds / 3600.0)
}
}
#[must_use]
pub fn estimate_text(seconds: f64, measured: bool) -> String {
let duration = format_duration(seconds);
if measured {
format!("Estimated time: {duration} (from your last run on this design).")
} else {
format!(
"Estimated time: {duration} (a rough guess from the design size; the next run is estimated from this one)."
)
}
}
#[cfg(test)]
mod tests;