use super::{
anchors::{angle_differences, fold_relations, mast_differences},
check::{AnalysisResult, Attempt, GirdleAllowance, best_attempt},
metrics::{MetricColumn, RetargetMetrics, measure_column},
plan::RetargetPlan,
refit::refit_flats,
retarget_scope,
validity::{
InvalidReason, KNIFE_EDGE_PERCENT, MIN_GIRDLE_FRACTION, RetargetStrategy, RetargetValidity,
StoneAnalysis, analyze, judge,
},
};
use indicatrix::{
geometry::meet_solver::{Block, MeetConstraint},
optics::{LightingPreset, materials::GemMaterial},
};
use indicatrix_cut_core::{
Design, ObjectivePreset, OptimizeCandidate, OptimizeConfig, OptimizeOptions, SearchHooks,
ShapeTarget,
design::hinge::{TierHinge, mast_through, tier_hinges},
free_tier_indices_with,
optics_hints::{
MAX_RETARGET_ANGLE_DEG, MIN_RETARGET_ANGLE_DEG, critical_angle_deg, tier_margin_deg,
},
optimize::{
ObjectiveFidelity, SearchStage, inclusive_max_evaluations_for, score_finished_design,
},
optimize_design_with,
};
use std::{
collections::BTreeMap,
sync::atomic::{AtomicBool, Ordering},
};
mod report;
pub use report::{
CandidateKind, CandidateNumbers, SearchCandidate, SearchError, SearchReport, StartPoint,
};
pub const RANGE_CHOICES_DEG: [f64; 4] = [3.0, 6.0, 10.0, 15.0];
pub const DEFAULT_RANGE_INDEX: usize = 1;
pub const EFFORT_CHOICES: [usize; 3] = [100, 300, 800];
pub const DEFAULT_EFFORT_INDEX: usize = 1;
pub const CANDIDATES_KEPT: usize = 3;
pub const KEEP_LOOK_WEIGHT: f32 = 0.5;
const PAVILION_MARGIN_CAP_DEG: f64 = 2.0;
const SEARCH_SEED: u64 = 0;
const SEARCH_CEILING_DEG: f64 = MAX_RETARGET_ANGLE_DEG - 0.5;
const PARTIAL_STEPS: usize = 5;
const MIN_FOLLOWER_MAST: f64 = 1e-6;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SearchSettings {
pub preset: ObjectivePreset,
pub range_deg: f64,
pub evaluations: usize,
pub seed: u64,
pub keep: usize,
pub keep_look: bool,
pub girdle: Option<GirdleAllowance>,
}
impl Default for SearchSettings {
fn default() -> Self {
Self::from_choices(0, DEFAULT_RANGE_INDEX, DEFAULT_EFFORT_INDEX)
}
}
impl SearchSettings {
#[must_use]
pub fn from_choices(objective_index: usize, range_index: usize, effort_index: usize) -> Self {
Self {
preset: ObjectivePreset::from_index(objective_index),
range_deg: RANGE_CHOICES_DEG[range_index.min(RANGE_CHOICES_DEG.len() - 1)],
evaluations: EFFORT_CHOICES[effort_index.min(EFFORT_CHOICES.len() - 1)],
seed: SEARCH_SEED,
keep: CANDIDATES_KEPT,
keep_look: true,
girdle: Some(GirdleAllowance::standard()),
}
}
#[must_use]
pub fn config(&self, lighting: LightingPreset) -> OptimizeConfig {
OptimizeConfig {
weights: self.preset.weights(),
seed: self.seed,
max_evaluations: self.evaluations,
lighting,
..OptimizeConfig::default()
}
}
#[must_use]
pub fn total_steps(&self, free_tiers: usize) -> usize {
let config = OptimizeConfig {
max_evaluations: self.evaluations,
..OptimizeConfig::default()
};
inclusive_max_evaluations_for(
&config,
OptimizeOptions::default().keep_candidates,
free_tiers,
)
}
}
#[must_use]
pub fn estimate_text(total_steps: usize, step_ms: Option<f64>) -> String {
step_ms
.filter(|ms| ms.is_finite() && *ms > 0.0)
.map_or_else(
|| {
format!(
"Up to {total_steps} steps. The time per step is measured once the change has been checked."
)
},
|ms| {
let seconds = total_steps as f64 * ms / 1000.0;
let time = if seconds < 1.0 {
"under a second".to_string()
} else if seconds < 90.0 {
format!("about {seconds:.0} s")
} else {
format!("about {:.0} min", seconds / 60.0)
};
format!(
"Up to {total_steps} steps, {time} at {ms:.0} ms a step, plus a few seconds to score the results."
)
},
)
}
#[must_use]
pub fn probe_evaluation(design: &Design, gem: &GemMaterial, lighting: LightingPreset) -> bool {
analyze(design, false)
.map(|analysis| measure_column(&analysis.planes, gem, lighting))
.is_ok()
}
#[derive(Debug, Clone, Copy)]
pub struct SearchInputs<'a> {
pub design: &'a Design,
pub plan: &'a RetargetPlan,
pub current_gem: Option<&'a GemMaterial>,
pub lighting: LightingPreset,
pub settings: &'a SearchSettings,
}
#[must_use]
pub fn angle_bounds(angle_deg: f64, range_deg: f64) -> (f64, f64) {
let magnitude = angle_deg.abs();
let low = (magnitude - range_deg).max(MIN_RETARGET_ANGLE_DEG);
let low = low.min(magnitude);
let high = (magnitude + range_deg).min(SEARCH_CEILING_DEG);
let high = high.max(magnitude);
if angle_deg.is_sign_negative() {
(-high, -low)
} else {
(low, high)
}
}
fn girdle_fraction(original: &StoneAnalysis, start: &StoneAnalysis) -> f64 {
match (original.girdle_percent, start.girdle_percent) {
(Some(was), Some(now)) if now > 0.0 => (MIN_GIRDLE_FRACTION * was / now).min(1.0),
_ => MIN_GIRDLE_FRACTION,
}
}
fn thinnest_fraction(original: &StoneAnalysis, start: &StoneAnalysis) -> f64 {
match (
original.girdle_thinnest_percent,
start.girdle_thinnest_percent,
) {
(Some(was), Some(now)) if now > KNIFE_EDGE_PERCENT => {
(MIN_GIRDLE_FRACTION * was / now).min(1.0)
}
_ => MIN_GIRDLE_FRACTION,
}
}
fn guard_fractions(original: &StoneAnalysis, start: &StoneAnalysis) -> GuardFractions {
GuardFractions {
overall: girdle_fraction(original, start),
thinnest: thinnest_fraction(original, start),
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct GuardFractions {
overall: f64,
thinnest: f64,
}
fn free_candidates(design: &Design) -> Vec<usize> {
retarget_scope(design)
.0
.into_iter()
.filter(|&index| !design.is_tier_driven(index))
.collect()
}
#[must_use]
pub fn pavilion_floor_deg(live_angle_deg: f64, n_from: f64, n_to: f64) -> f64 {
critical_angle_deg(n_to) + tier_margin_deg(live_angle_deg, n_from).min(PAVILION_MARGIN_CAP_DEG)
}
fn raise_floor(bounds: (f64, f64), start_deg: f64, floor_deg: f64) -> (f64, f64) {
if !floor_deg.is_finite() {
return bounds;
}
let floor = floor_deg.min(start_deg.abs());
if start_deg.is_sign_negative() {
(bounds.0, bounds.1.min(-floor))
} else {
(bounds.0.max(floor), bounds.1)
}
}
fn shape_target(settings: &SearchSettings, original: &StoneAnalysis) -> Option<ShapeTarget> {
settings.keep_look.then_some(ShapeTarget {
table_percent: original.table_percent,
crown_to_pavilion: original.crown_to_pavilion,
weight: KEEP_LOOK_WEIGHT,
})
}
fn search_options(
inputs: &SearchInputs<'_>,
original: &StoneAnalysis,
start: &Design,
free: &[usize],
hinges: &BTreeMap<usize, TierHinge>,
fractions: GuardFractions,
) -> OptimizeOptions {
let settings = inputs.settings;
let mut options = OptimizeOptions {
vary_anchored: true,
min_girdle_fraction: Some(fractions.overall),
min_girdle_thinnest_fraction: Some(fractions.thinnest),
keep_candidates: settings.keep,
shape_target: shape_target(settings, original),
..OptimizeOptions::default()
};
let blocks = retarget_scope(start).1;
for &index in free {
let start_deg = start.tiers[index].angle_deg;
let mut bounds = angle_bounds(start_deg, settings.range_deg);
if blocks.get(index) == Some(&Block::Pavilion)
&& let Some(live) = inputs.design.tiers.get(index)
{
let floor = pavilion_floor_deg(live.angle_deg, inputs.plan.n_from, inputs.plan.n_to);
bounds = raise_floor(bounds, start_deg, floor);
}
options.angle_bounds.insert(index, bounds);
if let Some(hinge) = hinges.get(&index) {
options.anchor_hinges.insert(index, hinge.point);
}
}
options
}
struct Columns {
current_in_current: Option<MetricColumn>,
current_in_target: Option<MetricColumn>,
}
impl Columns {
fn measure(inputs: &SearchInputs<'_>, original: &StoneAnalysis) -> Self {
Self {
current_in_current: inputs
.current_gem
.map(|gem| measure_column(&original.planes, gem, inputs.lighting)),
current_in_target: Some(measure_column(
&original.planes,
&inputs.plan.target.gem,
inputs.lighting,
)),
}
}
fn metrics(&self, inputs: &SearchInputs<'_>, candidate: &AnalysisResult) -> RetargetMetrics {
RetargetMetrics {
current_in_current: self.current_in_current,
current_in_target: self.current_in_target,
retargeted_in_target: candidate.as_ref().ok().map(|analysis| {
measure_column(&analysis.planes, &inputs.plan.target.gem, inputs.lighting)
}),
}
}
}
fn partial_start(
inputs: &SearchInputs<'_>,
original: &StoneAnalysis,
should_stop: &dyn Fn() -> bool,
) -> Result<(Attempt, StartPoint), SearchError> {
let (mut low, mut high) = (0.0_f64, 1.0_f64);
let mut best: Option<(f64, Attempt)> = None;
for _ in 0..PARTIAL_STEPS {
if should_stop() {
return Err(SearchError::Cancelled);
}
let middle = f64::midpoint(low, high);
let moves = inputs.plan.moving_angles_at(middle);
match best_attempt(
inputs.design,
&moves,
original,
inputs.settings.girdle,
should_stop,
) {
Ok(None) => return Err(SearchError::Cancelled),
Ok(Some(attempt)) if attempt.reasons.is_empty() => {
low = middle;
best = Some((middle, attempt));
}
Ok(Some(_)) | Err(_) => high = middle,
}
}
Ok(match best {
Some((fraction, attempt)) => (
attempt,
StartPoint::Partial {
percent: (fraction * 100.0).round() as u32,
},
),
None => (
Attempt::unchanged(inputs.design, original),
StartPoint::Unchanged,
),
})
}
fn choose_start(
inputs: &SearchInputs<'_>,
original: &StoneAnalysis,
should_stop: &dyn Fn() -> bool,
) -> Result<(Attempt, StartPoint, RetargetValidity), SearchError> {
let moves = inputs.plan.moving_angles();
let shift_verdict = match best_attempt(
inputs.design,
&moves,
original,
inputs.settings.girdle,
should_stop,
) {
Ok(None) => return Err(SearchError::Cancelled),
Ok(Some(attempt)) => {
let verdict = RetargetValidity::judged(
original,
&attempt.analysis,
attempt.reasons.clone(),
attempt.strategy,
)
.with_girdle_thickened(attempt.girdle_step);
if attempt.reasons.is_empty() {
return Ok((attempt, StartPoint::Shift, verdict));
}
verdict
}
Err(error) => {
let reason = InvalidReason::RelationFails(error.to_string());
let none: AnalysisResult = Err(reason.clone());
RetargetValidity::judged(original, &none, vec![reason], RetargetStrategy::AnglesOnly)
}
};
let (start, point) = partial_start(inputs, original, should_stop)?;
Ok((start, point, shift_verdict))
}
fn reanchor_followers(
design: &mut Design,
start: &Design,
hinges: &BTreeMap<usize, TierHinge>,
) -> bool {
let mut changed = false;
for index in 0..design.tiers.len() {
let moved =
design.tiers[index].angle_deg.to_bits() != start.tiers[index].angle_deg.to_bits();
if !moved || !design.is_tier_driven(index) {
continue;
}
let Some(hinge) = hinges.get(&index) else {
continue;
};
let MeetConstraint::ScaleReference(before) = design.tiers[index].constraint else {
continue;
};
let mast = mast_through(
design.tiers[index].angle_deg,
hinge.azimuth_rad,
hinge.side,
hinge.point,
);
if mast.is_finite() && mast >= MIN_FOLLOWER_MAST {
changed |= mast.to_bits() != before.to_bits();
design.tiers[index].constraint = MeetConstraint::ScaleReference(mast);
}
}
changed
}
fn refit_table_and_culet(design: &mut Design, original: &StoneAnalysis) -> bool {
let Ok(stone) = analyze(design, false) else {
return false;
};
let refits = refit_flats(design, &stone.solved, &stone.flats, original, &|| false);
for refit in &refits {
design.tiers[refit.tier_index].constraint = MeetConstraint::ScaleReference(refit.new_mast);
}
!refits.is_empty()
}
fn delivered_numbers(
inputs: &SearchInputs<'_>,
original: &StoneAnalysis,
design: &Design,
stone: &StoneAnalysis,
) -> CandidateNumbers {
let weights = inputs.settings.config(inputs.lighting).weights;
let scored = score_finished_design(
design,
&stone.planes,
&inputs.plan.target.gem,
&weights,
ObjectiveFidelity::Full,
inputs.lighting,
shape_target(inputs.settings, original),
);
CandidateNumbers::new(scored.after, scored.score, scored.yield_loss_pct)
}
fn finish_candidate(
inputs: &SearchInputs<'_>,
original: &StoneAnalysis,
start: &Design,
hinges: &BTreeMap<usize, TierHinge>,
found: &OptimizeCandidate,
columns: &Columns,
girdle_step: Option<f64>,
) -> Result<SearchCandidate, Vec<InvalidReason>> {
let mut design = start.clone();
for change in &found.changes {
if let Some(tier) = design.tiers.get_mut(change.index) {
tier.angle_deg = change.to_deg;
}
}
for change in &found.mast_changes {
if let Some(tier) = design.tiers.get_mut(change.index) {
tier.constraint = MeetConstraint::ScaleReference(change.to_mast);
}
}
fold_relations(&mut design)
.map_err(|error| vec![InvalidReason::RelationFails(error.to_string())])?;
let followers_moved = reanchor_followers(&mut design, start, hinges);
let refit_moved = refit_table_and_culet(&mut design, original);
let analysis = analyze(&design, false);
let reasons = judge(inputs.design, original, &analysis);
if !reasons.is_empty() {
return Err(reasons);
}
let numbers = analysis
.as_ref()
.ok()
.filter(|_| followers_moved || refit_moved)
.map_or_else(
|| CandidateNumbers::new(found.after, found.score, found.yield_loss_pct),
|stone| delivered_numbers(inputs, original, &design, stone),
);
Ok(SearchCandidate {
kind: CandidateKind::Optimized,
angles: angle_differences(inputs.design, &design),
anchors: mast_differences(inputs.design, &design),
validity: RetargetValidity::judged(
original,
&analysis,
Vec::new(),
RetargetStrategy::Optimized,
)
.with_girdle_thickened(girdle_step),
metrics: columns.metrics(inputs, &analysis),
numbers,
design,
})
}
pub fn run_search(
inputs: &SearchInputs<'_>,
cancel: &AtomicBool,
on_progress: &dyn Fn(usize, SearchStage),
) -> Result<SearchReport, SearchError> {
let should_stop = || cancel.load(Ordering::Relaxed);
let original = analyze(inputs.design, true).map_err(SearchError::Unusable)?;
if should_stop() {
return Err(SearchError::Cancelled);
}
let (start, start_point, shift_validity) = choose_start(inputs, &original, &should_stop)?;
let start_analysis = start
.analysis
.as_ref()
.map_err(|reason| SearchError::Unusable(reason.clone()))?;
let hinges = tier_hinges(&start.design, &start_analysis.solved);
let free = free_candidates(&start.design);
let options = search_options(
inputs,
&original,
&start.design,
&free,
&hinges,
guard_fractions(&original, start_analysis),
);
let free_tiers = free_tier_indices_with(&start.design, &options).len();
let config = inputs.settings.config(inputs.lighting);
let hooks = SearchHooks {
cancel: Some(cancel),
on_progress: Some(on_progress),
on_start: None,
};
let result = optimize_design_with(
&start.design,
&inputs.plan.target.gem,
&config,
&options,
&hooks,
)
.map_err(|error| SearchError::Solve(error.to_string()))?;
if should_stop() {
return Err(SearchError::Cancelled);
}
let columns = Columns::measure(inputs, &original);
let start_numbers = CandidateNumbers::new(
result.outcome.before,
result.outcome.before_score,
result.outcome.before_yield_loss_pct,
);
let mut candidates = Vec::new();
let start_kind = match start_point {
StartPoint::Shift => Some(CandidateKind::Shift),
StartPoint::Partial { percent } => Some(CandidateKind::Partial { percent }),
StartPoint::Unchanged => None,
};
if let Some(kind) = start_kind {
candidates.push(SearchCandidate {
kind,
angles: angle_differences(inputs.design, &start.design),
anchors: mast_differences(inputs.design, &start.design),
validity: RetargetValidity::judged(
&original,
&start.analysis,
Vec::new(),
start.strategy,
)
.with_girdle_thickened(start.girdle_step),
metrics: columns.metrics(inputs, &start.analysis),
numbers: start_numbers,
design: start.design.clone(),
});
}
let mut dropped = Vec::new();
for found in &result.candidates {
match finish_candidate(
inputs,
&original,
&start.design,
&hinges,
found,
&columns,
start.girdle_step,
) {
Ok(candidate) => candidates.push(candidate),
Err(reasons) => dropped.push(reasons),
}
}
candidates.sort_by(|a, b| a.numbers.score.total_cmp(&b.numbers.score));
Ok(SearchReport {
start: start_point,
shift_validity,
start_numbers,
candidates,
dropped,
evaluations: result.outcome.evaluations,
free_tiers,
keep_look: inputs.settings.keep_look,
})
}
#[cfg(test)]
mod tests;