use crate::retarget::{
AnchorChange,
metrics::RetargetMetrics,
validity::{InvalidReason, RetargetValidity},
};
use indicatrix_cut_core::{Design, ObjectiveComponents};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CandidateNumbers {
pub score: f32,
pub windowing_pct: f32,
pub brilliance_pct: f32,
pub extinction_pct: f32,
pub yield_loss_pct: f32,
}
impl CandidateNumbers {
pub(super) const fn new(after: ObjectiveComponents, score: f32, yield_loss_pct: f32) -> Self {
Self {
score,
windowing_pct: after.windowing_pct,
brilliance_pct: after.tilt_brilliance_pct,
extinction_pct: after.extinction_pct,
yield_loss_pct,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateKind {
Shift,
Partial {
percent: u32,
},
Optimized,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SearchCandidate {
pub kind: CandidateKind,
pub angles: Vec<(usize, f64)>,
pub anchors: Vec<AnchorChange>,
pub validity: RetargetValidity,
pub metrics: RetargetMetrics,
pub numbers: CandidateNumbers,
pub design: Design,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartPoint {
Shift,
Partial {
percent: u32,
},
Unchanged,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SearchReport {
pub start: StartPoint,
pub shift_validity: RetargetValidity,
pub start_numbers: CandidateNumbers,
pub candidates: Vec<SearchCandidate>,
pub dropped: Vec<Vec<InvalidReason>>,
pub evaluations: usize,
pub free_tiers: usize,
pub keep_look: bool,
}
fn plural(count: usize, one: &str, many: &str) -> String {
if count == 1 {
format!("{count} {one}")
} else {
format!("{count} {many}")
}
}
impl SearchReport {
#[must_use]
pub fn best(&self) -> Option<&SearchCandidate> {
self.candidates.first()
}
#[must_use]
pub fn optimized_count(&self) -> usize {
self.candidates
.iter()
.filter(|candidate| candidate.kind == CandidateKind::Optimized)
.count()
}
#[must_use]
pub fn notes(&self) -> Vec<String> {
let mut notes = Vec::new();
let why = self
.shift_validity
.reasons
.first()
.map(InvalidReason::message)
.unwrap_or_default();
match self.start {
StartPoint::Shift => {}
StartPoint::Partial { percent } => notes.push(format!(
"Shift alone is not valid here. {why} The search started from {percent} % of the Shift change."
)),
StartPoint::Unchanged => notes.push(format!(
"Shift alone is not valid here. {why} The search started from the design as it is."
)),
}
if self.free_tiers == 0 {
notes.push(
"No crown or pavilion facet could be varied, so there was nothing to search."
.to_string(),
);
}
if !self.dropped.is_empty() {
let mut reasons: Vec<String> = Vec::new();
for reason in self.dropped.iter().flatten() {
let message = reason.message();
if !reasons.contains(&message) {
reasons.push(message);
}
}
let count = self.dropped.len();
let counted = plural(count, "result", "results");
let verb = if count == 1 {
"was dropped because it is"
} else {
"were dropped because they are"
};
notes.push(format!(
"{counted} of the search {verb} not valid: {}",
reasons.join(" ")
));
}
if self.keep_look && self.free_tiers > 0 {
notes.push(
"Options are scored with a penalty for drifting from the design's table size and crown-to-pavilion ratio (keep the look)."
.to_string(),
);
}
if self.optimized_count() == 0 && self.free_tiers > 0 {
notes.push(match (self.candidates.is_empty(), self.start) {
(true, _) => "The search found no valid option. Try a wider range, another objective or more steps.",
(false, StartPoint::Shift) => "The search found nothing better than the Shift result.",
(false, _) => "The search found nothing better than the part of the Shift change it started from.",
}
.to_string());
}
notes
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum SearchError {
Unusable(InvalidReason),
Solve(String),
Cancelled,
}
impl fmt::Display for SearchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unusable(InvalidReason::DoesNotSolve(why)) => write!(
f,
"Optimize needs a design that solves first. This one does not ({why})."
),
Self::Unusable(InvalidReason::NotClosed) => write!(
f,
"Optimize needs a design whose facets enclose a stone. This one does not."
),
Self::Unusable(other) => write!(f, "Optimize cannot start. {}", other.message()),
Self::Solve(why) => write!(f, "The search could not start ({why})."),
Self::Cancelled => write!(f, "The search was cancelled."),
}
}
}
impl std::error::Error for SearchError {}