Skip to main content

brep_ransac/
options.rs

1use serde::{Deserialize, Serialize};
2
3#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
4/// Selects which geometric samples are used during fitting.
5pub enum SamplingMode {
6    /// Sample one point at each triangle centroid.
7    TriangleCentroids,
8    /// Sample mesh vertices.
9    Vertices,
10    /// Sample both triangle centroids and mesh vertices.
11    CentroidsAndVertices,
12}
13
14/// How generic hypotheses are drawn when a connected component is not one
15/// carrier.
16///
17/// Hidden and outside the semver contract: no census has favoured a policy
18/// other than [`HypothesisPolicy::Classical`] (validation records of
19/// 2026-10-28), so the adaptive policy stays an experiment until one does.
20#[doc(hidden)]
21#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
22pub enum HypothesisPolicy {
23    /// Every primitive kind in turn, each over its own uniform permutation of
24    /// the remaining triangles, from a probe of 128 triangles doubled while a
25    /// candidate does not outgrow it; a round stops at the classical bound
26    /// `ln(1 - confidence) / ln(1 - w)` seeds per kind, `w` the incumbent's
27    /// share of the remaining triangles.
28    Classical,
29    /// Seeds, kinds and probe sizes drawn by [`AdaptiveSampling`]: a
30    /// Boltzmann distribution over the triangles' history mixed with a
31    /// uniform floor, a cost-aware bandit over kinds and over probe sizes,
32    /// and a risk bound that credits the uniform floor alone.
33    Adaptive(AdaptiveSampling),
34}
35
36impl Default for HypothesisPolicy {
37    fn default() -> Self {
38        Self::Classical
39    }
40}
41
42/// Parameters of [`HypothesisPolicy::Adaptive`].
43///
44/// The policy's three temperatures, one per axis of the search:
45/// - spatial: each hypothesis draws its seed from a mixture, with probability
46///   `seed_exploration` uniformly over the remaining triangles, otherwise from
47///   `exp(-explored / T)` over the triangles outside the round's incumbent
48///   that this kind has not seeded yet, where `explored` counts the losing
49///   supports a triangle has sat in and `T` is `seed_temperature` times one
50///   of {0.05, 0.1, 0.25, 0.5, 1, 2, ∞}, chosen by Thompson sampling on how
51///   often draws at that temperature improved the incumbent and by how much
52///   (the infinite temperature is uniform over those triangles, so reheating
53///   is one arm among the others);
54/// - primitive family: the kind is drawn by Thompson sampling on the support
55///   a kind's hypotheses gain per unit of fitting cost, learned over the
56///   component's rounds, every kind worth a draw keeping `kind_floor` of the
57///   round's draws;
58/// - sample: the probe around the seed starts at 128 triangles and doubles
59///   while the candidate does not outgrow it, as in the classical policy, but
60///   at the first probe whose candidate explained fewer than `minimum_support`
61///   triangles the chain is kept only with the probability that such a chain
62///   has been rescued for this kind so far, never below `probe_floor`; a kept
63///   chain runs on as the classical one does.
64///
65/// A round stops for one of three separately reported reasons (see
66/// [`crate::RecognitionWork`]): the risk bound, seed exhaustion, or the
67/// hypothesis cap. The risk bound of each kind is
68/// `(1 - seed_exploration * w)` to the power of the kind's draws, `w` the
69/// incumbent's share of the round's triangles, and it certifies the round
70/// when every kind's bound is at most the round's share of the component's
71/// error budget: `(1 - confidence)` times the incumbent's share of the
72/// component. Extracted regions are disjoint, so the certified rounds' shares
73/// sum to at most `1 - confidence`, which bounds the probability that any
74/// certified round missed a support larger than the one it extracted; rounds
75/// that stop for another reason certify nothing and spend nothing. The uniform
76/// part is the only part of the draw the bound credits, so it stays valid
77/// however the Boltzmann part and the bandits adapt.
78#[doc(hidden)]
79#[derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)]
80#[serde(default)]
81#[non_exhaustive]
82pub struct AdaptiveSampling {
83    /// Probability that a hypothesis takes its seed uniformly from the
84    /// remaining triangles, in (0, 1]. The risk bound credits these draws
85    /// alone, so a smaller value explores more and certifies more slowly.
86    pub seed_exploration: f64,
87    /// Scale of the spatial temperature bank over the explored counts;
88    /// positive. Lower concentrates every arm on unexplored triangles.
89    pub seed_temperature: f64,
90    /// Share of a round's draws every eligible primitive kind receives at
91    /// least, divided evenly among the kinds, in [0, 1]. The remainder goes to
92    /// the kinds the posterior ranks best on support per cost.
93    pub kind_floor: f64,
94    /// Probability, at least, of keeping a probe chain past its first size
95    /// whose candidate explained fewer than `minimum_support` triangles, in
96    /// [0, 1]; one coin per chain. 1 restores the classical chain for every
97    /// hypothesis; 0 keeps a chain only as often as the kind's rescue rate
98    /// says.
99    pub probe_floor: f64,
100}
101
102impl Default for AdaptiveSampling {
103    fn default() -> Self {
104        Self {
105            seed_exploration: 0.5,
106            seed_temperature: 1.0,
107            kind_floor: 0.5,
108            probe_floor: 0.1,
109        }
110    }
111}
112
113#[derive(Clone, Debug, Deserialize, Serialize)]
114#[serde(default)]
115/// Controls surface recognition, refinement, and region discovery.
116///
117/// Non-exhaustive: start from [`RecognitionOptions::default`] and set the
118/// fields you need, so a later field is not a breaking change.
119#[non_exhaustive]
120pub struct RecognitionOptions {
121    /// Maximum absolute positional residual accepted as an inlier.
122    pub distance_tolerance: f64,
123    /// Scale-relative positional tolerance added to the absolute tolerance.
124    pub relative_tolerance: f64,
125    /// Maximum accepted normal-angle residual, in radians.
126    pub normal_tolerance: f64,
127    /// Minimum number of supporting triangles required for a fit.
128    pub minimum_support: usize,
129    /// Minimum total supporting triangle area required for a fit.
130    pub minimum_support_area: f64,
131    /// Desired probability that adaptive generic hypothesis generation has
132    /// sampled a seed from the best support observed so far. This controls
133    /// support visitation, not whether a boundary/degenerate seed yields a
134    /// usable hypothesis and not the reported residual-evidence quality score.
135    pub confidence: f64,
136    /// Seed for deterministic hypothesis sampling, or `None` for entropy-based
137    /// sampling.
138    pub deterministic_seed: Option<u64>,
139    /// Maximum number of generic recognition hypotheses to generate.
140    pub max_hypotheses: usize,
141    /// Maximum number of numerical refinement iterations per candidate.
142    pub max_refinement_iterations: usize,
143    /// Dihedral-angle threshold, in radians, used to identify feature edges.
144    pub feature_angle: f64,
145    /// Whether region traversal stops at detected feature edges.
146    pub respect_features: bool,
147    /// Whether to split the input selection into recognized surface regions.
148    pub discover_regions: bool,
149    /// Merge disconnected regions only when a joint fit validates that they
150    /// lie on one carrier and have the same observed orientation.
151    pub allow_disconnected_same_surface: bool,
152    /// Collect wall-clock phase timings in fit diagnostics. Disabled by
153    /// default so deterministic result comparisons do not contain clock data.
154    pub collect_phase_timings: bool,
155    /// Geometric sampling strategy used by fitting and validation.
156    pub sampling: SamplingMode,
157    /// How generic hypotheses are drawn for a component no single carrier
158    /// explains. [`HypothesisPolicy::Classical`] by default. Hidden and
159    /// outside the semver contract, like [`HypothesisPolicy`].
160    #[doc(hidden)]
161    pub hypothesis_policy: HypothesisPolicy,
162    /// Worker threads for the work recognition splits without changing its
163    /// result: the connected components of a run without an attempt budget,
164    /// and the hypotheses of one classical extraction round, which are
165    /// evaluated in batches and applied in draw order. 0 uses one worker per
166    /// core the process may run on; 1 runs everything on the caller's thread.
167    /// On `wasm32` every value runs on the caller's thread. The regions,
168    /// their diagnostics and the reported work are the same for every value.
169    pub threads: usize,
170    /// Lane U row 3: run a torus seed's roundoff-recovery normal-offset
171    /// refinement only when some seed already agrees with the observed
172    /// normals within the multistart fidelity (1e-2 rad), the condition its
173    /// normal-disambiguation twin already requires. The refinement keeps only
174    /// candidates whose every normal agrees to 1.28e-5 rad, which a sample
175    /// whose best seed is 780 times further off has not been seen to reach;
176    /// on noisy meshes it ran on every torus fit and kept nothing. Off by
177    /// default.
178    pub torus_fast: bool,
179    /// A hypothesis's diversity probe does not cross a mesh edge whose two
180    /// triangle normals differ by more than `normal_tolerance`, so a sample
181    /// is drawn from one smooth wall. On a coarse tessellation of two crossing
182    /// cylinders one region of ~800 long triangles held both walls, a
183    /// 128-triangle probe spanned the crease, and every normal-diverse
184    /// cylinder sample mixed the walls (fitted radii 9-2 900 against 10).
185    /// Off by default.
186    pub probe_crease_gate: bool,
187    /// The triangles a hypothesis's diversity probe first grows to (it
188    /// doubles while a candidate explains no more than its probe). On a
189    /// coarse tessellation whose walls hold about 100 long triangles each, a
190    /// 128-triangle probe spans two walls whatever its seed. Defaults to 128.
191    pub hypothesis_probe_triangles: usize,
192}
193
194impl Default for RecognitionOptions {
195    fn default() -> Self {
196        Self {
197            distance_tolerance: 1.0e-6,
198            relative_tolerance: 1.0e-8,
199            normal_tolerance: 5.0_f64.to_radians(),
200            minimum_support: 6,
201            minimum_support_area: 0.0,
202            confidence: 0.999,
203            deterministic_seed: Some(0x4341_4452_414e_5341),
204            max_hypotheses: 512,
205            // Small, partial torus patches have a shallow coupled
206            // center/axis/radii valley.  They can require well over 40
207            // monotonically improving LM steps to reach CAD-level accuracy.
208            max_refinement_iterations: 160,
209            feature_angle: 30.0_f64.to_radians(),
210            respect_features: true,
211            discover_regions: true,
212            allow_disconnected_same_surface: false,
213            collect_phase_timings: false,
214            sampling: SamplingMode::CentroidsAndVertices,
215            hypothesis_policy: HypothesisPolicy::Classical,
216            threads: 0,
217            torus_fast: false,
218            probe_crease_gate: false,
219            hypothesis_probe_triangles: 128,
220        }
221    }
222}
223
224impl RecognitionOptions {
225    pub(crate) fn validate(&self) -> Result<(), crate::RecognitionError> {
226        if !self.distance_tolerance.is_finite() || self.distance_tolerance <= 0.0 {
227            return Err(crate::RecognitionError::InvalidOptions(
228                "distance_tolerance must be finite and positive".into(),
229            ));
230        }
231        if !self.relative_tolerance.is_finite() || self.relative_tolerance < 0.0 {
232            return Err(crate::RecognitionError::InvalidOptions(
233                "relative_tolerance must be finite and non-negative".into(),
234            ));
235        }
236        if !(0.0..=std::f64::consts::PI).contains(&self.normal_tolerance) {
237            return Err(crate::RecognitionError::InvalidOptions(
238                "normal_tolerance must be in [0, pi]".into(),
239            ));
240        }
241        if self.minimum_support == 0 {
242            return Err(crate::RecognitionError::InvalidOptions(
243                "minimum_support must be non-zero".into(),
244            ));
245        }
246        if !self.minimum_support_area.is_finite() || self.minimum_support_area < 0.0 {
247            return Err(crate::RecognitionError::InvalidOptions(
248                "minimum_support_area must be finite and non-negative".into(),
249            ));
250        }
251        if !(0.0..1.0).contains(&self.confidence) {
252            return Err(crate::RecognitionError::InvalidOptions(
253                "confidence must be in [0, 1)".into(),
254            ));
255        }
256        if self.max_hypotheses == 0 || self.max_refinement_iterations == 0 {
257            return Err(crate::RecognitionError::InvalidOptions(
258                "iteration limits must be non-zero".into(),
259            ));
260        }
261        if !(0.0..=std::f64::consts::PI).contains(&self.feature_angle) {
262            return Err(crate::RecognitionError::InvalidOptions(
263                "feature_angle must be finite and in [0, pi]".into(),
264            ));
265        }
266        if let HypothesisPolicy::Adaptive(adaptive) = self.hypothesis_policy {
267            if !(adaptive.seed_exploration > 0.0 && adaptive.seed_exploration <= 1.0) {
268                return Err(crate::RecognitionError::InvalidOptions(
269                    "seed_exploration must be in (0, 1]".into(),
270                ));
271            }
272            if !(adaptive.seed_temperature.is_finite() && adaptive.seed_temperature > 0.0) {
273                return Err(crate::RecognitionError::InvalidOptions(
274                    "seed_temperature must be finite and positive".into(),
275                ));
276            }
277            if !(0.0..=1.0).contains(&adaptive.kind_floor)
278                || !(0.0..=1.0).contains(&adaptive.probe_floor)
279            {
280                return Err(crate::RecognitionError::InvalidOptions(
281                    "kind_floor and probe_floor must be in [0, 1]".into(),
282                ));
283            }
284        }
285        Ok(())
286    }
287}
288