ternary_contours/contour/
mod.rs1mod bands;
4mod error;
5mod linear;
6mod locate;
7mod options;
8mod paths;
9mod regularize;
10mod topology;
11
12pub use bands::{ContourBand, ContourBandOptions, ContourBandSet, ContourFragment, ContourRegion};
13pub use error::ContourError;
14pub use options::{
15 AdaptiveContourOptions, ContourInterpolation, ContourOptions, ContourRegularization,
16 CubicAlphaMethod, CubicAlphaOptions, CubicBoundaryPolicy, CubicContourDiagnostics,
17};
18pub use paths::ContourPath;
19
20use crate::RegularTernaryScalarField;
21
22#[derive(Clone, Debug, PartialEq)]
24pub struct ContourLevel {
25 pub value: f64,
27 pub paths: Vec<ContourPath>,
29}
30
31#[derive(Clone, Debug, PartialEq)]
36pub struct ContourSet {
37 pub levels: Vec<ContourLevel>,
39 diagnostics: Option<CubicContourDiagnostics>,
40}
41
42impl ContourSet {
43 pub fn compute(
49 field: &RegularTernaryScalarField,
50 levels: &[f64],
51 options: ContourOptions,
52 ) -> Result<Self, ContourError> {
53 options.validate()?;
54 let levels = validated_levels(levels, options.value_tolerance)?;
55 match options.interpolation {
56 ContourInterpolation::Linear => {
57 let evaluator = regularize::FieldEvaluator::Linear(field);
58 let mut result = Vec::with_capacity(levels.len());
59 for level in levels {
60 let mut paths = linear::linear_paths(
61 field,
62 level,
63 options.value_tolerance,
64 options.geometry_tolerance,
65 )?;
66 if let Some(regularization) = options.regularization {
67 regularize::regularize_paths(
68 &mut paths,
69 level,
70 regularization,
71 &evaluator,
72 )?;
73 }
74 result.push(ContourLevel {
75 value: level,
76 paths,
77 });
78 }
79 Ok(Self {
80 levels: result,
81 diagnostics: None,
82 })
83 }
84 ContourInterpolation::CubicAlpha(cubic_options) => {
85 #[cfg(not(feature = "cubic-alpha"))]
86 {
87 let _ = (field, levels, cubic_options);
88 Err(ContourError::CubicFeatureUnavailable)
89 }
90 #[cfg(feature = "cubic-alpha")]
91 {
92 let mut model = locate::ContourCubicField::new(field, cubic_options)?;
93 let mut result = Vec::with_capacity(levels.len());
94 for level in levels {
95 let mut paths =
96 topology::cubic_paths(&mut model, level, cubic_options.adaptive)?;
97 if let Some(regularization) = options.regularization {
98 let evaluator = regularize::FieldEvaluator::Cubic(&model);
99 if let Err(error) = regularize::regularize_paths(
100 &mut paths,
101 level,
102 regularization,
103 &evaluator,
104 ) {
105 model.diagnostics_mut().projection_failures += 1;
106 return Err(error);
107 }
108 }
109 result.push(ContourLevel {
110 value: level,
111 paths,
112 });
113 }
114 let diagnostics = Some(model.diagnostics().clone());
115 Ok(Self {
116 levels: result,
117 diagnostics,
118 })
119 }
120 }
121 }
122 }
123
124 pub fn diagnostics(&self) -> Option<&CubicContourDiagnostics> {
126 self.diagnostics.as_ref()
127 }
128}
129
130fn validated_levels(levels: &[f64], tolerance: f64) -> Result<Vec<f64>, ContourError> {
131 let mut indexed = levels.iter().copied().enumerate().collect::<Vec<_>>();
132 if let Some((index, value)) = indexed
133 .iter()
134 .copied()
135 .find(|(_, value)| !value.is_finite())
136 {
137 return Err(ContourError::NonFiniteLevel { index, value });
138 }
139 indexed.sort_by(|left, right| left.1.total_cmp(&right.1));
140 for pair in indexed.windows(2) {
141 if (pair[0].1 - pair[1].1).abs() <= tolerance {
142 return Err(ContourError::DuplicateLevel {
143 first: pair[0].0,
144 second: pair[1].0,
145 value: pair[0].1,
146 });
147 }
148 }
149 Ok(indexed.into_iter().map(|(_, value)| value).collect())
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155 #[test]
156 fn levels_are_sorted_and_duplicates_or_nonfinite_values_are_rejected() {
157 let field = RegularTernaryScalarField::new(1, vec![0.0, 1.0, 2.0]).unwrap();
158 let set = ContourSet::compute(&field, &[1.5, 0.5], ContourOptions::linear()).unwrap();
159 assert_eq!(
160 set.levels
161 .iter()
162 .map(|level| level.value)
163 .collect::<Vec<_>>(),
164 vec![0.5, 1.5]
165 );
166 assert!(matches!(
167 ContourSet::compute(&field, &[1.0, 1.0 + 1e-12], ContourOptions::linear()),
168 Err(ContourError::DuplicateLevel { .. })
169 ));
170 assert!(matches!(
171 ContourSet::compute(&field, &[f64::NAN], ContourOptions::linear()),
172 Err(ContourError::NonFiniteLevel { .. })
173 ));
174 }
175 #[cfg(not(feature = "cubic-alpha"))]
176 #[test]
177 fn cubic_mode_reports_unavailable_feature() {
178 let field = RegularTernaryScalarField::new(1, vec![0.0, 1.0, 2.0]).unwrap();
179 assert!(matches!(
180 ContourSet::compute(
181 &field,
182 &[1.0],
183 ContourOptions::cubic_alpha(CubicAlphaOptions::default())
184 ),
185 Err(ContourError::CubicFeatureUnavailable)
186 ));
187 }
188}