engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! This module has the composed internal tools for doing the geometric analysis of airfoil
//! sections.  These tools pull together the lower-level tools in the sibling modules to make
//! more convenient ways to extract geometry for most use cases.  The user can always still use
//! the individual pieces manually.

use crate::airfoil2::camber::extract_inscribed_circles;
use crate::airfoil2::edges::{
    AfEdgeFit, fit_blended_round_edge, fit_full_round_edge, fit_open_edge, fit_rounded_square_edge,
    fit_sharp_edge, fit_spline_max_k, fit_square_edge, is_open_at_end,
};
use crate::airfoil2::inscribed::Inscribed;
use crate::airfoil2::{
    AfEdge, AfEdgeGeometry, AfEdgeSearch, AfGeometry, OrientFwdAft, OrientUpperLower, SectionInput,
};
use crate::geom2::LineOps2;
use crate::{AngleDir, Curve2, Point2, Result};

pub fn geometry_only_analysis(
    section: &Curve2,
    general_tol: f64,
    fwd_aft: OrientFwdAft,
    upper_lower: OrientUpperLower,
    le_search: AfEdgeSearch,
    te_search: AfEdgeSearch,
) -> Result<AfGeometry> {
    // Create the unified input struct and then start by capturing the unambiguous inscribed
    // circles. The orientation of the inscribed circles is completely unknown.
    let input = SectionInput::new(section, general_tol);
    let unoriented = extract_inscribed_circles(&input)?;

    // Now we will orient the inscribed circles in the forward/aft direction
    let fwd_oriented = fwd_aft.apply(unoriented)?;

    // Now we orient them in the upper/lower direction
    let oriented = upper_lower.apply(fwd_oriented)?;

    // Now we capture the leading and trailing edges
    let (oriented, trailing) = run_edge_fit(te_search, &input, oriented, false)?;
    let (oriented, leading) = run_edge_fit(le_search, &input, oriented, true)?;

    // Now we extract the camber curve
    let camber = make_camber_curve(leading.point, trailing.point, &oriented, general_tol * 1e-2)?;
    let (lower, upper) = split_sides(leading, trailing, section, &oriented)?;

    Ok(AfGeometry {
        leading,
        trailing,
        camber,
        upper,
        lower,
        circles: oriented,
    })
}

fn split_sides(
    leading: AfEdge,
    trailing: AfEdge,
    section: &Curve2,
    oriented: &[Inscribed],
) -> Result<(Curve2, Curve2)> {
    // Now we split the two sides
    let (side0, side1) = match (leading.geometry, trailing.geometry) {
        (AfEdgeGeometry::Open, AfEdgeGeometry::Open) => {
            // This shouldn't be possible
            return Err("Both leading and trailing edges cannot be open".into());
        }
        (AfEdgeGeometry::Open, _) => {
            // Leading is open, trailing is closed
            let l = section.at_closest_to_point(&trailing.point).length_along();
            section.split_open_at_length(l)?
        }
        (_, AfEdgeGeometry::Open) => {
            // Leading is closed, trailing is open
            let l = section.at_closest_to_point(&leading.point).length_along();
            section.split_open_at_length(l)?
        }
        (_, _) => {
            // Both sides are closed
            let l0 = section.at_closest_to_point(&leading.point).length_along();
            let l1 = section.at_closest_to_point(&trailing.point).length_along();
            section.split_closed_at_lengths(l0, l1)?
        }
    };

    // To identify the sides, we'll check an inscribed circle and see which one is closer to `p0`,
    // which would indicate the lower/pressure side.
    let test_circle = &oriented[oriented.len() / 2];
    let (lower, upper) =
        if side0.dist_to_point(&test_circle.p0) < side1.dist_to_point(&test_circle.p0) {
            (side0, side1)
        } else {
            (side1, side0)
        };

    // Ensure that the upper and lower skins are oriented in the correct direction so that their
    // surface normals face outward
    let line_l = lower.at_closest_to_point(&test_circle.c).direction_line();
    let lower = if line_l.winding_direction(&test_circle.c) == AngleDir::Cw {
        lower.reversed()
    } else {
        lower
    };

    let line_u = upper.at_closest_to_point(&test_circle.c).direction_line();
    let upper = if line_u.winding_direction(&test_circle.c) == AngleDir::Cw {
        upper.reversed()
    } else {
        upper
    };

    Ok((lower, upper))
}

fn make_camber_curve(
    le_point: Point2,
    te_point: Point2,
    oriented_circles: &[Inscribed],
    tol: f64,
) -> Result<Curve2> {
    let mut points = vec![le_point];
    for c in oriented_circles.iter() {
        points.push(c.center());
    }
    points.push(te_point);
    Curve2::from_points(&points, tol, false)
}

fn run_edge_fit(
    search: AfEdgeSearch,
    input: &SectionInput,
    circles: Vec<Inscribed>,
    at_front: bool,
) -> Result<(Vec<Inscribed>, AfEdge)> {
    let result = match search {
        AfEdgeSearch::Auto => fit_auto_edge(input, circles, at_front),
        AfEdgeSearch::Open => fit_open_edge(input, circles, at_front),
        AfEdgeSearch::Sharp => fit_sharp_edge(input, circles, at_front),
        AfEdgeSearch::Square => fit_square_edge(input, circles, at_front),
        AfEdgeSearch::RoundedSquare => fit_rounded_square_edge(input, circles, at_front),
        AfEdgeSearch::FullRound => fit_full_round_edge(input, circles, at_front),
        AfEdgeSearch::BlendedRound => fit_blended_round_edge(input, circles, at_front),
        AfEdgeSearch::SplineMaxK => fit_spline_max_k(input, circles, at_front).map(|r| r.0),
    }?;

    Ok((result.circles, result.edge))
}

struct FitCandidate {
    complexity: usize,
    fit: AfEdgeFit,
}

impl FitCandidate {
    fn new(complexity: usize, fit: AfEdgeFit) -> Self {
        Self { complexity, fit }
    }
}

fn fit_auto_edge(
    input: &SectionInput,
    circles: Vec<Inscribed>,
    at_front: bool,
) -> Result<AfEdgeFit> {
    // An open edge is a property of the section topology rather than of a candidate geometry, so it
    // has no residual to be ranked by and is resolved first, short-circuiting the search.
    if is_open_at_end(input, &circles, at_front)? {
        return fit_open_edge(input, circles, at_front);
    }

    // Candidates have a complexity score based on the type of edge fit, with the goal being to
    // use the lowest complexity method which adequately captures the geometry. For a method to be
    // selected, it must have an average residual at least some tolerance better than the best
    // method with a lower complexity score.
    const COMPLEXITY_TOL: f64 = 0.05; // Starting with 5%

    let mut candidates = Vec::new();
    if let Ok(sharp) = fit_sharp_edge(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(0, sharp));
    }
    if let Ok(square) = fit_square_edge(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(0, square));
    }
    if let Ok(full_round) = fit_full_round_edge(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(0, full_round));
    }

    if let Ok(rounded_square) = fit_rounded_square_edge(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(1, rounded_square));
    }

    if let Ok(blended_round) = fit_blended_round_edge(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(1, blended_round));
    }

    if let Ok(spline_max) = fit_spline_max_k(input, circles.clone(), at_front) {
        candidates.push(FitCandidate::new(2, spline_max.0));
    }

    // Drop any fit whose quality metric is not finite (e.g. an empty residual set yields a NaN
    // mean), since it can neither be ranked nor meaningfully compared against other tiers.
    candidates.retain(|c| c.fit.avg_residual.is_finite());
    if candidates.is_empty() {
        return Err("No edge fits with a valid residual for auto edge search".into());
    }

    // Walk the complexity tiers from lowest to highest. A higher-complexity tier is only adopted
    // when its best residual improves on the best residual achieved by *any* lower-complexity tier
    // by at least `COMPLEXITY_TOL` (a relative fraction), so that added complexity has to pay for
    // itself. `best_lower` accumulates the best residual seen strictly below the current tier and
    // is independent of which tier ended up selected.
    let max_complexity = candidates.iter().map(|c| c.complexity).max().unwrap();

    let mut selected: Option<&FitCandidate> = None;
    let mut best_lower = f64::INFINITY;
    for tier in 0..=max_complexity {
        let best_in_tier = candidates
            .iter()
            .filter(|c| c.complexity == tier)
            .min_by(|a, b| a.fit.avg_residual.total_cmp(&b.fit.avg_residual));

        if let Some(best) = best_in_tier {
            // The first (lowest) tier present is always taken as the baseline; later tiers must
            // beat the best lower residual by the tolerance. Note that a lower tier achieving a
            // residual of exactly zero locks the selection, since nothing can beat zero by a
            // relative margin.
            if selected.is_none() || best.fit.avg_residual < best_lower * (1.0 - COMPLEXITY_TOL) {
                selected = Some(best);
            }
            best_lower = best_lower.min(best.fit.avg_residual);
        }
    }

    Ok(selected
        .expect("non-empty candidates guarantees a selection")
        .fit
        .clone())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::dist;
    use crate::geom2::Segment2;
    use crate::tests::airfoil_curve;
    use approx::assert_relative_eq;

    fn af_curve_known_ccw() -> Curve2 {
        let donor = airfoil_curve();
        Curve2::from_points_ccw(donor.points(), donor.tol(), true).unwrap()
    }

    fn basic_geom(section: &Curve2) -> Result<(Vec<Inscribed>, AfEdge, AfEdge)> {
        let input = SectionInput::new(section, 1e-3);
        let unoriented = extract_inscribed_circles(&input)?;
        let partial = OrientFwdAft::TmaxFwd.apply(unoriented)?;
        let oriented = OrientUpperLower::Curvature.apply(partial)?;

        // Now we capture the leading and trailing edges
        let (oriented, trailing) = run_edge_fit(AfEdgeSearch::FullRound, &input, oriented, false)?;
        let (oriented, leading) = run_edge_fit(AfEdgeSearch::BlendedRound, &input, oriented, true)?;
        Ok((oriented, leading, trailing))
    }

    fn verify_upper_lower(upper: &Curve2, lower: &Curve2, expected: &Curve2) -> Result<()> {
        for p in upper.points() {
            let local = upper.at_closest_to_point(p);
            let check = expected.at_closest_to_point(p);
            assert!(
                local.normal().dot(&check.normal()).is_sign_positive(),
                "Upper point is not facing the right way"
            );
        }

        for p in lower.points() {
            let local = lower.at_closest_to_point(p);
            let check = expected.at_closest_to_point(p);
            assert!(
                local.normal().dot(&check.normal()).is_sign_positive(),
                "Lower point is not facing the right way"
            );
        }

        Ok(())
    }

    #[test]
    fn side_orientation_ccw() -> Result<()> {
        let expected = af_curve_known_ccw();
        let (oriented, leading, trailing) = basic_geom(&expected)?;
        let (lower, upper) = split_sides(leading, trailing, &expected, &oriented)?;
        verify_upper_lower(&upper, &lower, &expected)?;
        Ok(())
    }

    #[test]
    fn side_orientation_cw() -> Result<()> {
        let expected = af_curve_known_ccw();
        let reversed = expected.reversed();

        let (oriented, leading, trailing) = basic_geom(&reversed)?;
        let (lower, upper) = split_sides(leading, trailing, &reversed, &oriented)?;

        verify_upper_lower(&upper, &lower, &expected)?;
        Ok(())
    }

    #[test]
    fn auto_edges() -> Result<()> {
        let curve = airfoil_curve();
        let input = SectionInput::new(&curve, 1e-3);

        let circles = extract_inscribed_circles(&input)?;
        let circles = OrientFwdAft::TmaxFwd.apply(circles)?;
        let circles = OrientUpperLower::Curvature.apply(circles)?;

        let result = fit_auto_edge(&input, circles, true)?;
        let _result = fit_auto_edge(&input, result.circles, false)?;

        Ok(())
    }

    /// Build an open airfoil section by cutting `gap` of arc length out of the closed test section
    /// on either side of its trailing edge point. The vertices are re-ordered to start just past
    /// the trailing edge and wrap all the way around, so the two ends of the resulting open curve
    /// are the two lips of the gap.
    fn open_at_trailing_edge(gap: f64) -> Result<Curve2> {
        let closed = af_curve_known_ccw();
        let full = AfGeometry::try_from_geometric_analysis(
            &closed,
            1e-3,
            OrientFwdAft::TmaxFwd,
            OrientUpperLower::Curvature,
            AfEdgeSearch::Auto,
            AfEdgeSearch::Auto,
        )?;

        let total = closed.length();
        let l_te = closed
            .at_closest_to_point(&full.trailing.point)
            .length_along();

        let mut ordered = closed
            .points()
            .iter()
            .map(|p| {
                let l = closed.at_closest_to_point(p).length_along();
                (((l - l_te) % total + total) % total, *p)
            })
            .collect::<Vec<_>>();
        ordered.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());

        let points = ordered
            .iter()
            .filter(|(s, _)| *s > gap && *s < total - gap)
            .map(|(_, p)| *p)
            .collect::<Vec<_>>();

        Curve2::from_points(&points, closed.tol(), false)
    }

    fn analyze_auto(section: &Curve2) -> Result<AfGeometry> {
        AfGeometry::try_from_geometric_analysis(
            section,
            1e-3,
            OrientFwdAft::TmaxFwd,
            OrientUpperLower::Curvature,
            AfEdgeSearch::Auto,
            AfEdgeSearch::Auto,
        )
    }

    #[test]
    fn auto_detects_open_trailing_edge() -> Result<()> {
        let section = open_at_trailing_edge(1.0)?;
        assert!(!section.is_closed(), "The test section should be open");

        let result = analyze_auto(&section)?;

        assert!(
            matches!(result.trailing.geometry, AfEdgeGeometry::Open),
            "Expected an open trailing edge, got {:?}",
            result.trailing.geometry
        );
        assert!(
            !matches!(result.leading.geometry, AfEdgeGeometry::Open),
            "The leading edge is closed and should not have been detected as open"
        );

        // The open branch of `split_sides` should have produced two usable skins
        assert!(result.upper.points().len() > 1);
        assert!(result.lower.points().len() > 1);

        // The trailing edge point must land on the chord spanning the gap rather than short of it
        let cap = Segment2::new(&section.at_front().point(), &section.at_back().point())?;
        assert!(
            dist(
                &cap.closest_point(&result.trailing.point),
                &result.trailing.point
            ) < 1e-6,
            "Trailing edge point {:?} is not on the gap chord",
            result.trailing.point
        );

        Ok(())
    }

    #[test]
    fn auto_open_detection_is_direction_independent() -> Result<()> {
        let section = open_at_trailing_edge(1.0)?;
        let forward = analyze_auto(&section)?;
        let reversed = analyze_auto(&section.reversed())?;

        assert!(matches!(forward.trailing.geometry, AfEdgeGeometry::Open));
        assert!(matches!(reversed.trailing.geometry, AfEdgeGeometry::Open));
        assert_relative_eq!(
            forward.trailing.point,
            reversed.trailing.point,
            epsilon = 1e-3
        );

        Ok(())
    }

    /// Asking for a closed edge geometry on an open section cannot succeed, but it must fail by
    /// returning an error rather than by panicking. `fit_auto_edge` collects its candidates with
    /// `if let Ok(..)`, so a panic in any fitter would be uncatchable and would take down the whole
    /// analysis instead of just eliminating one candidate.
    #[test]
    fn closed_edge_search_on_open_section_errors() -> Result<()> {
        let section = open_at_trailing_edge(1.0)?;
        let input = SectionInput::new(&section, 1e-3);

        let circles = extract_inscribed_circles(&input)?;
        let circles = OrientFwdAft::TmaxFwd.apply(circles)?;
        let circles = OrientUpperLower::Curvature.apply(circles)?;

        for search in [
            AfEdgeSearch::Sharp,
            AfEdgeSearch::Square,
            AfEdgeSearch::RoundedSquare,
            AfEdgeSearch::FullRound,
            AfEdgeSearch::BlendedRound,
            AfEdgeSearch::SplineMaxK,
        ] {
            // The result itself is meaningless, we only care that it comes back at all
            let _ = run_edge_fit(search, &input, circles.clone(), false);
        }

        Ok(())
    }

    #[test]
    fn auto_leaves_closed_section_alone() -> Result<()> {
        let result = analyze_auto(&af_curve_known_ccw())?;
        assert!(!matches!(result.leading.geometry, AfEdgeGeometry::Open));
        assert!(!matches!(result.trailing.geometry, AfEdgeGeometry::Open));
        Ok(())
    }
}