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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
use crate::common::points::dist;
use crate::common::{Intersection, PCoords, signed_compliment_2pi};
use crate::geom2::aabb2::circle_aabb2;
use crate::geom2::line2::intersect_lines;
use crate::geom2::{Aabb2, HasBounds2, Iso2, LineOps2, Point2, Segment2, Vector2, signed_angle};
use crate::geom3::Vector3;
use crate::stats::{compute_mean, compute_st_dev};
use crate::{AngleInterval, BestFit, SurfacePoint2};
use crate::{Arc2, Result};
use levenberg_marquardt::{LeastSquaresProblem, LevenbergMarquardt};
use parry2d_f64::na::{Dyn, Matrix, Owned, U1, U3, Vector};
use parry2d_f64::shape::Ball;
use rand::SeedableRng;
use rand::distr::{Distribution, Uniform};
use rand::prelude::StdRng;
use serde::{Deserialize, Serialize};
use std::f64::consts::FRAC_PI_2;
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub struct Circle2 {
pub center: Point2,
pub ball: Ball,
aabb: Aabb2,
}
//=============================================================================================
// Creation Methods
//=============================================================================================
impl Circle2 {
/// Create a new circle from the x and y coordinates of its center and its radius
///
/// # Arguments
///
/// * `x`: the x coordinate of the circle's center
/// * `y`: the y coordinate of the circle's center
/// * `r`: the radius of the circle
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let circle = Circle2::new(1.0, 2.0, 3.0);
///
/// assert_eq!(circle.x(), 1.0);
/// assert_eq!(circle.y(), 2.0);
/// assert_eq!(circle.r(), 3.0);
/// ```
pub fn new(x: f64, y: f64, r: f64) -> Self {
let center = Point2::new(x, y);
Self::from_point(center, r)
}
/// Create a new circle from a center point and a radius
///
/// # Arguments
///
/// * `center`: the center point of the circle
/// * `r`: the radius of the circle
///
/// returns: Circle2
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let circle = Circle2::from_point(Point2::new(1.0, 2.0), 3.0);
///
/// assert_eq!(circle.x(), 1.0);
/// assert_eq!(circle.y(), 2.0);
/// assert_eq!(circle.r(), 3.0);
/// ```
pub fn from_point(center: Point2, r: f64) -> Circle2 {
let aabb = circle_aabb2(¢er, r);
Circle2 {
center,
ball: Ball::new(r),
aabb,
}
}
/// Attempt to create a fitting circle from the given points and an initial guess. The fitting
/// is an unconstrained Levenberg-Marquardt minimization of the sum of squared errors between
/// the points and the boundary of the circle.
///
/// The initial guess is used to provide an initial estimate of the circle's center and radius,
/// for best results this should at least be in the general vicinity of the test points.
///
/// The mode parameter controls the fitting algorithm. The `BestFit::All` mode will weight all
/// points equally, while the `BestFit::Gaussian(sigma)` mode will assign zero weights to
/// points beyond `sigma` standard deviations from the mean.
///
/// # Arguments
///
/// * `points`: the points to be fit to the circle
/// * `guess`: an initial guess for the circle's center and radius
/// * `mode`: the fitting mode to use
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// use engeom::BestFit::All;
/// use approx::assert_relative_eq;
///
/// let points = vec![
/// Point2::new(-1.0, 0.0),
/// Point2::new(0.0, 1.0),
/// Point2::new(1.0, 0.0),
/// Point2::new(0.0, -1.0),
/// ];
///
/// let guess = Circle2::new(-1.0, 1.0, 0.1);
/// let circle = Circle2::fitting_circle(&points, &guess, All).unwrap();
/// assert_relative_eq!(circle.x(), 0.0);
/// assert_relative_eq!(circle.y(), 0.0);
/// assert_relative_eq!(circle.r(), 1.0);
/// ```
pub fn fitting_circle(points: &[Point2], guess: &Circle2, mode: BestFit) -> Result<Circle2> {
fit_circle(points, guess, mode)
}
/// Given a set of points, attempt to fit a circle to them using the RANSAC algorithm.
///
/// # Arguments
///
/// * `points`: a slice of points to fit the circle to
/// * `tol`: The tolerance to use for the RANSAC algorithm. If a point is within this distance
/// of the circle's perimeter, it is considered an inlier.
/// * `iterations`: An optional number of iterations to run the RANSAC algorithm. If not
/// provided, the default is 500.
/// * `min_r`: An optional minimum radius for the circle. If provided, the circle's radius must
/// be greater than or equal to this value to be considered a valid candidate.
/// * `max_r`: An optional maximum radius for the circle. If provided, the circle's radius must
/// be less than or equal to this value to be considered a valid candidate.
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
///
/// ```
pub fn ransac(
points: &[Point2],
tol: f64,
iterations: Option<usize>,
min_r: Option<f64>,
max_r: Option<f64>,
) -> Result<Circle2> {
let iterations = iterations.unwrap_or(500);
let min_r = min_r.unwrap_or(0.0);
let max_r = max_r.unwrap_or(f64::INFINITY);
let mut best_count = 0;
let mut best_circle = None;
let mut rng = StdRng::seed_from_u64(24601);
let u = Uniform::new(0, points.len())?;
let n = iterations.max(10);
for _ in 0..n {
let i0 = u.sample(&mut rng);
let i1 = u.sample(&mut rng);
let i2 = u.sample(&mut rng);
if let Ok(c) = Circle2::from_3_points(&points[i0], &points[i1], &points[i2]) {
// Check that the circle is smaller than that of the last station
if c.r() > max_r || c.r() < min_r {
continue;
}
// Count the number of inliers
let mut count = 0;
for p in points {
if c.distance_to(p).abs() < tol {
count += 1;
}
}
if count > best_count {
best_count = count;
best_circle = Some(c);
}
}
}
best_circle.ok_or("Failed to find a single valid RANSAC circle candidate".into())
}
/// Attempt to create a fitting circle from three points. Will return an `Err` if the points
/// are collinear.
///
/// # Arguments
///
/// * `p0`: the first point
/// * `p1`: the second point
/// * `p2`: the third point
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let p0 = Point2::new(-1.0, 0.0);
/// let p1 = Point2::new(0.0, 1.0);
/// let p2 = Point2::new(1.0, 0.0);
///
/// let circle = Circle2::from_3_points(&p0, &p1, &p2).unwrap();
/// assert_relative_eq!(circle.x(), 0.0);
/// assert_relative_eq!(circle.y(), 0.0);
/// assert_relative_eq!(circle.r(), 1.0);
///
/// ```
pub fn from_3_points(
p0: &impl PCoords<2>,
p1: &impl PCoords<2>,
p2: &impl PCoords<2>,
) -> Result<Circle2> {
let (p0, p1, p2) = (p0.coords(), p1.coords(), p2.coords());
let temp = p1.x.powi(2) + p1.y.powi(2);
let bc = (p0.x.powi(2) + p0.y.powi(2) - temp) / 2.0;
let cd = (temp - p2.x.powi(2) - p2.y.powi(2)) / 2.0;
let det = (p0.x - p1.x) * (p1.y - p2.y) - (p1.x - p2.x) * (p0.y - p1.y);
if det.abs() < 1.0e-6 {
Err("Points are collinear".into())
} else {
let cx = (bc * (p1.y - p2.y) - cd * (p0.y - p1.y)) / det;
let cy = ((p0.x - p1.x) * cd - (p1.x - p2.x) * bc) / det;
let radius = ((cx - p0.x).powi(2) + (cy - p0.y).powi(2)).sqrt();
Ok(Self::new(cx, cy, radius))
}
}
/// Creates a circle at the tangent of a corner. The corner is defined by a corner point and
/// two direction vectors which define the directions of the two lines which meet at the corner.
/// The radius argument specifies the radius of the tangent circle. The circle is created by
/// finding the bisector of the angle formed by the two lines, and then offsetting each line
/// by the radius in the positive direction of the bisector. The intersection of the two offset
/// lines is the center of the tangent circle.
///
/// This method will return an error if the two direction vectors are collinear (i.e. the angle
/// between them is zero or 180 degrees), as in that case a unique tangent circle cannot be
/// defined.
///
/// This construction method is similar to putting a fillet on the corner formed by the two
/// lines.
///
/// # Arguments
///
/// * `corner`: the corner point where the two lines meet
/// * `d0`: the direction vector of the first line
/// * `d1`: the direction vector of the second line
/// * `radius`: the radius of the tangent circle
///
/// returns: Result<Circle2, Box<dyn Error, Global>>
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2, Vector2};
/// use approx::assert_relative_eq;
/// let corner = Point2::new(1.0, 1.0);
/// let d0 = Vector2::new(1.0, 0.0); // Horizontal line to the right
/// let d1 = Vector2::new(0.0, 1.0); // Vertical line upwards
/// let radius = 1.0;
///
/// let circle = Circle2::tangent_to_corner(&corner, &d0, &d1, radius).unwrap();
/// assert_relative_eq!(circle.x(), 2.0);
/// assert_relative_eq!(circle.y(), 2.0);
/// assert_relative_eq!(circle.r(), radius);
/// ```
pub fn tangent_to_corner(
corner: &impl PCoords<2>,
d0: &Vector2,
d1: &Vector2,
radius: f64,
) -> Result<Circle2> {
// Compute the angle from the direction of line a to the direction of line b
let angle = signed_angle(d0, d1);
// Figure out the bisector direction
let bisector = Iso2::rotation(angle / 2.0) * d0.normalize();
let a = SurfacePoint2::new_normalize(Point2::from(corner.coords()), *d0);
let b = SurfacePoint2::new_normalize(Point2::from(corner.coords()), *d1);
let da = if bisector.dot(&a.orthogonal()) > 0.0 {
radius
} else {
-radius
};
let db = if bisector.dot(&b.orthogonal()) > 0.0 {
radius
} else {
-radius
};
let a1 = a.shift_orthogonal(da);
let b1 = b.shift_orthogonal(db);
let ts = intersect_lines(&a1, &b1);
if let Some((t_a, _t_b)) = ts {
let center = a1.at(t_a);
Ok(Circle2::from_point(center, radius))
} else {
Err("Failed to compute tangent circle from lines".into())
}
}
}
//=============================================================================================
// Operational Methods
//=============================================================================================
impl Circle2 {
/// Returns the x coordinate of the circle's center
pub fn x(&self) -> f64 {
self.center.x
}
/// Returns the y coordinate of the circle's center
pub fn y(&self) -> f64 {
self.center.y
}
/// Returns the radius of the circle
pub fn r(&self) -> f64 {
self.ball.radius
}
/// Returns the point on the circle's perimeter at the given angle (referenced as a
/// counter-clockwise angle where zero is the x-axis), measured in radians
///
/// # Arguments
///
/// * `angle`: the CCW angle from the x-axis in radians
///
/// returns: OPoint<f64, Const<2>>
///
/// # Examples
///
/// ```
/// use std::f64::consts::FRAC_PI_2;
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = c.point_at_angle(FRAC_PI_2);
///
/// assert_relative_eq!(p.x, 0.0);
/// assert_relative_eq!(p.y, 1.0);
/// ```
pub fn point_at_angle(&self, angle: f64) -> Point2 {
let v = Vector2::new(self.ball.radius, 0.0);
let t = Iso2::rotation(angle);
self.center + (t * v)
}
/// Given a point, project it onto the perimeter of the circle. If the point is within 1.0e-10
/// of the center, then `None` is returned.
///
/// # Arguments
///
/// * `point`:
///
/// returns: Option<OPoint<f64, Const<2>>>
///
/// # Examples
///
/// ```
///
/// ```
pub fn project_point_to_perimeter(&self, point: &impl PCoords<2>) -> Option<Point2> {
let v = point.coords() - self.center.coords;
if v.norm() < 1.0e-10 {
None
} else {
let n = v.normalize();
Some(self.center + (n * self.ball.radius))
}
}
/// Determines the angle of the given point relative to the circle's center, measured in
/// radians where zero is the x-axis and positive angles are counter-clockwise.
///
/// # Arguments
///
/// * `point`: the test point to measure the angle of
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use std::f64::consts::FRAC_PI_2;
/// use engeom::{Circle2, Point2};
/// use approx::assert_relative_eq;
///
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = Point2::new(0.0, 1.0);
/// let a = c.angle_of_point(&p);
///
/// assert_relative_eq!(a, FRAC_PI_2);
/// ```
pub fn angle_of_point(&self, point: &impl PCoords<2>) -> f64 {
let v = point.coords() - self.center.coords;
v.y.atan2(v.x)
}
pub fn intersection_interval(&self, other: Circle2) -> Option<AngleInterval> {
let ints = self.intersections_with(&other);
if ints.is_empty() {
return None;
}
if ints.len() == 1 {
let start = self.angle_of_point(&ints[0]);
return Some(AngleInterval::new(start, 0.0));
}
// There are two possible intervals, one going from the first point to the second in the
// clockwise direction, and one going via its signed compliment in the counter-clockwise
// direction. The valid interval is the one which also contains the center of the other
// circle.
let v0 = ints[0] - self.center;
let v1 = ints[1] - self.center;
let a = signed_angle(&v0, &v1);
let ac = signed_compliment_2pi(a);
let s = self.angle_of_point(&ints[0]);
let i0 = AngleInterval::new(s, a);
let i1 = AngleInterval::new(s, ac);
if i0.contains(self.angle_of_point(&other.center)) {
Some(i0)
} else {
Some(i1)
}
}
pub fn intersections_with(&self, other: &Circle2) -> Vec<Point2> {
const TOL: f64 = 1.0e-10;
let mut result = Vec::new();
let d = dist(&self.center, &other.center);
if d < TOL {
// Circles are concentric
return result;
}
let r_sum = self.ball.radius + other.ball.radius;
if d > r_sum {
// Circles are too far apart
return result;
}
let v = (other.center - self.center).normalize();
let a = (self.ball.radius.powi(2) - other.ball.radius.powi(2) + d.powi(2)) / (2.0 * d);
let p2 = self.center + (v * a);
if (d - r_sum).abs() < TOL {
// Circles are touching
result.push(p2);
return result;
}
let h = (self.ball.radius.powi(2) - a.powi(2)).sqrt();
let n = Iso2::rotation(FRAC_PI_2) * v;
result.push(p2 + (n * h));
result.push(p2 - (n * h));
result
}
/// Create a full arc of the circle, starting at zero and extending for 2Ï€ radians.
pub fn to_arc(&self) -> Arc2 {
Arc2::new(*self, 0.0, 2.0 * std::f64::consts::PI)
}
/// Create a partial arc of the circle, starting at `angle0` and extending for `angle` radians.
///
/// # Arguments
///
/// * `angle0`:
/// * `angle`:
///
/// returns: Arc2
///
/// # Examples
///
/// ```
///
/// ```
pub fn to_partial_arc(&self, angle0: f64, angle: f64) -> Arc2 {
Arc2::new(*self, angle0, angle)
}
/// Computes the distance from the test point to the outer perimeter of the circle. If the
/// point lies within the circle boundary, the distance will be negative.
///
/// # Arguments
///
/// * `point`: the test point to check against the circle
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use engeom::{Circle2, Point2};
/// let c = Circle2::new(0.0, 0.0, 1.0);
///
/// let d0 = c.distance_to(&Point2::new(0.0, 0.0));
/// assert_eq!(d0, -1.0);
///
/// let d1 = c.distance_to(&Point2::new(1.0, 0.0));
/// assert_eq!(d1, 0.0);
///
/// let d2 = c.distance_to(&Point2::new(2.0, 0.0));
/// assert_eq!(d2, 1.0);
/// ```
pub fn distance_to(&self, point: &impl PCoords<2>) -> f64 {
dist(&self.center, point) - self.ball.radius
}
/// Returns `true` if the point lies at or inside the boundary of the circle.
pub fn contains_point(&self, point: &impl PCoords<2>) -> bool {
self.distance_to(point) <= 0.0
}
/// Compute and return the two tangent points on the circle from a given point. If the point is
/// on or within the circle, then `None` is returned.
///
/// If they exist, the tangent points will always be returned in the same order relative to the
/// line passing through the test point in the direction of the circle center. The first point
/// will be in the negative normal direction (to the left) of the line, and the second point
/// will be in the positive normal direction (to the right).
///
/// # Arguments
///
/// * `point`: the test point
///
/// returns: Option<(OPoint<f64, Const<2>>, OPoint<f64, Const<2>>)>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::{Circle2, Point2};
/// let c = Circle2::new(0.0, 0.0, 1.0);
/// let p = Point2::new(-1.0, -1.0);
/// let (p0, p1) = c.tangent_points_to(&p).unwrap();
/// assert_relative_eq!(p0, Point2::new(-1.0, 0.0));
/// assert_relative_eq!(p1, Point2::new(0.0, -1.0));
/// ```
pub fn tangent_points_to(&self, point: &impl PCoords<2>) -> Option<(Point2, Point2)> {
let dv = point.coords() - self.center.coords;
let d = dv.norm();
if d <= self.ball.radius {
return None;
}
let angle = f64::asin(self.ball.radius / d);
let d1 = self.r() * f64::sin(angle);
let e0 = self.r() * f64::cos(angle);
let d_vec = SurfacePoint2::new_normalize(self.center, dv);
let e = d_vec.orthogonal();
let p0 = d_vec.at_distance(d1) + e * e0;
let p1 = d_vec.at_distance(d1) + e * -e0;
Some((p0, p1))
}
/// Compute and return two segments which are the outer tangents between this circle and another
/// circle.
///
/// If the circles are concentric, the result will be `None`. Otherwise, both segments will
/// start on the tangency point on *this* circle and end on the tangency point on the other
/// circle. The segments will be symmetric about the line connecting the two circle centers.
///
/// The segments will always be returned in the same order relative to the line passing through
/// this circle center in the direction of the other circle center. The first segment will be
/// the one in the negative half-space of the line (the negative normal direction, to the left),
/// and the second segment will be in the positive half-space of the line (the positive normal
/// direction, to the right).
///
/// # Arguments
///
/// * `other`:
///
/// returns: Option<(Segment2, Segment2)>
///
/// # Examples
///
/// ```
///
/// ```
pub fn outer_tangents_to(&self, other: &Circle2) -> Option<(Segment2, Segment2)> {
if dist(&self.center, &other.center) < 1.0e-10 {
// If the circles are concentric, there will be no outer tangents
None
} else if (self.ball.radius - other.ball.radius).abs() < 1.0e-10 {
// If the circles have the same radius, the outer tangent method must be computed
// by a simpler, special case
let s = Segment2::try_new(&self.center, &other.center).unwrap();
Some((
s.with_offset(self.ball.radius),
s.with_offset(-self.ball.radius),
))
} else if self.ball.radius > other.ball.radius {
if let Some((seg0, seg1)) = other.outer_tangents_to(self) {
// Swap the segments and reverse them
Some((seg1.reversed(), seg0.reversed()))
} else {
// Shouldn't happen
None
}
} else {
// General case. At this point we know that this circle is smaller than the other, and
// that the circles are not concentric. From here we use the method shown in
// https://upload.wikimedia.org/wikipedia/commons/7/7c/Aeussere_tangente_computation.svg
// where we re-frame the problem as the point-to-circle tangent problem.
let proxy = Circle2::new(other.x(), other.y(), other.r() - self.r());
// p0 is in the negative half space and p1 is in the positive half space
let (p0, p1) = proxy.tangent_points_to(&self.center).unwrap();
let s0 = Segment2::try_new(&self.center, &p0).unwrap();
let s1 = Segment2::try_new(&self.center, &p1).unwrap();
Some((s0.with_offset(-self.r()), s1.with_offset(self.r())))
}
}
}
impl HasBounds2 for Circle2 {
fn aabb(&self) -> &Aabb2 {
&self.aabb
}
}
/// Computes the intersection parameters of a line and a circle. The intersection parameters are
/// the values of the line's parameter at the intersection points. There will be zero, one, or two
/// intersection parameters. The intersection points can be recovered from the parameters by
/// calling `line.at(t)`.
///
/// # Arguments
///
/// * `line`:
/// * `circle`:
///
/// returns: Vec<f64, Global>
///
/// # Examples
///
/// ```
///
/// ```
pub fn intersection_line_circle(line: &impl LineOps2, circle: &Circle2) -> Vec<f64> {
// Get the parameter of the circle center onto the line
let tc = line.projected_parameter(&circle.center);
let d = dist(&circle.center, &line.projected_point(&circle.center));
if (d - circle.ball.radius).abs() < 1.0e-10 {
// If the distance from the center to the line is equal to the radius, then there is one
// single intersection point at the tangency point
vec![tc]
} else if d > circle.ball.radius {
// If the distance from the center to the line is greater than the radius, then there
// are no intersection points
Vec::new()
} else {
// There are two intersection points. The distance from the tangency point to the
// intersection points is the height of a right triangle with hypotenuse `r` and base
// `d`.
let h = (circle.ball.radius.powi(2) - d.powi(2)).sqrt();
// We can't simply add and subtract `h` from `tc` because the line may not be
// normalized, so we need to scale the value `h` by the norm of the line's direction
// vector.
let th = h / line.dir().norm();
vec![tc - th, tc + th]
}
}
impl<T: LineOps2> Intersection<T, Vec<f64>> for &Circle2 {
fn intersection(&self, other: T) -> Vec<f64> {
intersection_line_circle(&other, self)
}
}
impl Intersection<&Segment2, Vec<Point2>> for &Circle2 {
fn intersection(&self, other: &Segment2) -> Vec<Point2> {
let line = other.to_line();
let ts = intersection_line_circle(&line, self);
ts.iter()
.filter_map(|&t| {
if (-1.0e-10..=1.0 + 1.0e-10).contains(&t) {
Some(line.at(t))
} else {
None
}
})
.collect()
}
}
type Residuals = Matrix<f64, Dyn, U1, Owned<f64, Dyn, U1>>;
fn fit_circle(points: &[Point2], initial: &Circle2, mode: BestFit) -> Result<Circle2> {
let problem = CircleFit::new(points, mode, initial);
let (result, report) = LevenbergMarquardt::new().minimize(problem);
if report.termination.was_successful() {
Ok(result.circle)
} else {
let text = format!("Failed to fit circle: {:?}", report.termination);
Err(text.into())
}
}
struct CircleFit<'a> {
/// The points to be fit to the circle.
points: &'a [Point2],
/// The best fitting mode
mode: BestFit,
/// The parameters being fit
x: Vector3,
/// The current active circle
circle: Circle2,
/// The active base residuals
base_residuals: Residuals,
/// The active weights
weights: Residuals,
}
impl<'a> CircleFit<'a> {
fn new(points: &'a [Point2], mode: BestFit, initial: &Circle2) -> Self {
let x = Vector3::new(initial.center.x, initial.center.y, initial.r());
let circle = *initial;
// Compute the residuals
let mut base_residuals = Residuals::zeros(points.len());
compute_residuals_mut(points, &circle, &mut base_residuals);
// Compute the weights
let mut weights = Residuals::zeros(points.len());
compute_weights_mut(&base_residuals, &mut weights, mode);
Self {
points,
mode,
x,
circle,
base_residuals,
weights,
}
}
}
fn compute_residuals_mut(points: &[Point2], circle: &Circle2, residuals: &mut Residuals) {
for (i, p) in points.iter().enumerate() {
residuals[i] = circle.distance_to(p)
}
}
fn compute_weights_mut(residuals: &Residuals, weights: &mut Residuals, mode: BestFit) {
match mode {
BestFit::All => {
weights.fill(1.0);
}
BestFit::Gaussian(sigma) => {
let mean = compute_mean(residuals.as_slice()).expect("Empty slice");
let std = compute_st_dev(residuals.as_slice()).expect("Empty slice");
for (i, r) in residuals.iter().enumerate() {
// How many standard deviations are we from the mean?
let d = (r - mean).abs() / std;
if d > sigma {
weights[i] = 0.0;
} else {
weights[i] = 1.0;
}
}
}
}
}
impl LeastSquaresProblem<f64, Dyn, U3> for CircleFit<'_> {
type ResidualStorage = Owned<f64, Dyn, U1>;
type JacobianStorage = Owned<f64, Dyn, U3>;
type ParameterStorage = Owned<f64, U3>;
fn set_params(&mut self, x: &Vector<f64, U3, Self::ParameterStorage>) {
self.x = *x;
self.circle = Circle2::new(x[0], x[1], x[2]);
compute_residuals_mut(self.points, &self.circle, &mut self.base_residuals);
compute_weights_mut(&self.base_residuals, &mut self.weights, self.mode);
}
fn params(&self) -> Vector<f64, U3, Self::ParameterStorage> {
self.x
}
fn residuals(&self) -> Option<Vector<f64, Dyn, Self::ResidualStorage>> {
let mut res = Residuals::zeros(self.points.len());
for i in 0..self.points.len() {
res[i] = self.base_residuals[i] * self.weights[i];
}
Some(res)
}
fn jacobian(&self) -> Option<Matrix<f64, Dyn, U3, Self::JacobianStorage>> {
let mut jac = Matrix::<f64, Dyn, U3, Self::JacobianStorage>::zeros(self.points.len());
for (i, p) in self.points.iter().enumerate() {
// Find the vector from the center of the circle to the point
let v = p - self.circle.center;
// Normalize it
let n = v.normalize();
// Fill in the jacobian for this row
jac[(i, 0)] = -n.x * self.weights[i];
jac[(i, 1)] = -n.y * self.weights[i];
jac[(i, 2)] = -self.weights[i];
}
Some(jac)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::RngExt;
use crate::geom2::Ray2;
use approx::assert_relative_eq;
use rand_distr::Normal;
use std::f64::consts::PI;
use test_case::test_case;
#[test]
fn simple_tangent_corner() {
let corner = Point2::new(1.0, 1.0);
let v0 = Vector2::new(-1.0, 0.0);
let v1 = Vector2::new(0.0, -1.0);
let circle = Circle2::tangent_to_corner(&corner, &v0, &v1, 1.0).unwrap();
assert_relative_eq!(circle.center, Point2::new(0.0, 0.0), epsilon = 1.0e-8);
assert_relative_eq!(circle.r(), 1.0, epsilon = 1.0e-8);
}
#[test]
fn stress_tangent_lines() {
let mut rng = rand::rng();
for _ in 0..1000 {
let expected = Circle2::new(
rng.random_range(-5.0..5.0),
rng.random_range(-5.0..5.0),
rng.random_range(0.5..2.0),
);
// let expected = Circle2::new(0.0, 0.0, 1.0);
let tr = rng.random_range(0.01..5.0) + expected.r();
let tv = Iso2::rotation(rng.random_range(-PI..PI)) * Vector2::new(tr, 0.0);
let tc = expected.center + tv;
let (p0, p1) = expected.tangent_points_to(&tc).unwrap();
let result =
Circle2::tangent_to_corner(&tc, &(p0 - tc), &(p1 - tc), expected.r()).unwrap();
assert_relative_eq!(expected.center, result.center, epsilon = 1.0e-8);
assert_relative_eq!(expected.r(), result.r(), epsilon = 1.0e-8);
}
}
#[test_case((0.0, 0.0, 2.0), None)]
#[test_case((1.0, 0.0, 1.0), Some(((0.0, -1.0, 1.0, -1.0), (0.0, 1.0, 1.0, 1.0))))]
#[test_case((2.0, 2.0, 3.0), Some(((-1.0, 0.0, -1.0, 2.0), (0.0, -1.0, 2.0, -1.0))))]
#[test_case((0.5, 0.5, 0.5), Some(((0.0, 1.0, 0.5, 1.0), (1.0, 0.0, 1.0, 0.5))))]
fn outer_tangencies(
c: (f64, f64, f64),
e: Option<((f64, f64, f64, f64), (f64, f64, f64, f64))>,
) {
let c0 = Circle2::new(0.0, 0.0, 1.0);
let c1 = Circle2::new(c.0, c.1, c.2);
let result = c0.outer_tangents_to(&c1);
if let Some((e0, e1)) = e {
assert!(result.is_some());
let (s0, s1) = result.unwrap();
assert_relative_eq!(s0.a, Point2::new(e0.0, e0.1));
assert_relative_eq!(s0.b, Point2::new(e0.2, e0.3));
assert_relative_eq!(s1.a, Point2::new(e1.0, e1.1));
assert_relative_eq!(s1.b, Point2::new(e1.2, e1.3));
} else {
assert!(result.is_none());
}
}
#[test_case((0.0, 0.0), (1.0, 0.0), vec![-1.0, 1.0])]
#[test_case((0.0, 0.0), (2.0, 0.0), vec![-0.5, 0.5])]
#[test_case((1.0, 0.0), (1.0, 0.0), vec![-2.0, 0.0])]
#[test_case((0.0, 1.0), (1.0, 0.0), vec![0.0])]
#[test_case((0.0, 1.5), (1.0, 0.0), Vec::<f64>::new())]
fn simple_line_intersection(s: (f64, f64), d: (f64, f64), e: Vec<f64>) {
let c = Circle2::new(0.0, 0.0, 1.0);
let l = Ray2::new(Point2::new(s.0, s.1), Vector2::new(d.0, d.1));
// let result = c.intersection(&l);
let result = intersection_line_circle(&l, &c);
assert_eq!(result.len(), e.len());
for (r, e) in result.iter().zip(e.iter()) {
assert_relative_eq!(*e, *r, epsilon = 1.0e-10);
}
}
#[test_case((0.0, 0.0, 1.0), 0.0, (1.0, 0.0))]
#[test_case((0.0, 0.0, 1.0), 90.0, (0.0, 1.0))]
#[test_case((0.0, 0.0, 1.0), 180.0, (-1.0, 0.0))]
#[test_case((0.0, 0.0, 1.0), 360.0, (1.0, 0.0))]
#[test_case((1.0, 1.0, 1.0), 0.0, (2.0, 1.0))]
#[test_case((1.0, 1.0, 1.0), 90.0, (1.0, 2.0))]
#[test_case((1.0, 1.0, 1.0), 180.0, (0.0, 1.0))]
#[test_case((1.0, 1.0, 1.0), 360.0, (2.0, 1.0))]
fn test_circle_point(c: (f64, f64, f64), a: f64, r: (f64, f64)) {
let circle = Circle2::new(c.0, c.1, c.2);
let point = circle.point_at_angle(a * std::f64::consts::PI / 180.0);
assert_relative_eq!(r.0, point.x, epsilon = 1.0e-10);
assert_relative_eq!(r.1, point.y, epsilon = 1.0e-10);
}
#[test]
fn test_intersection_simple() {
let c0 = Circle2::new(0.0, 0.0, 1.0);
let c1 = Circle2::new(1.0, 0.0, 1.0);
let result = c0.intersections_with(&c1);
assert_eq!(result.len(), 2);
assert_relative_eq!(result[0].x, 0.5, epsilon = 1.0e-10);
assert_relative_eq!(result[0].y, 0.8660254037844386, epsilon = 1.0e-10);
assert_relative_eq!(result[1].x, 0.5, epsilon = 1.0e-10);
assert_relative_eq!(result[1].y, -0.8660254037844386, epsilon = 1.0e-10);
}
#[test]
fn tangent_points_to_simple() {
let c = Circle2::new(0.0, 0.0, 1.0);
let p = Point2::new(-1.0, -1.0);
let (p0, p1) = c.tangent_points_to(&p).unwrap();
assert_relative_eq!(p0, Point2::new(-1.0, 0.0));
assert_relative_eq!(p1, Point2::new(0.0, -1.0));
}
#[test]
fn tangent_points_to() {
let c = Circle2::new(0.5, -0.25, 1.1);
let p = Point2::new(-2.1, -3.0);
let (p0, p1) = c.tangent_points_to(&p).unwrap();
assert_relative_eq!(p0, Point2::new(-0.4844568895369135, 0.24075924101671814));
assert_relative_eq!(p1, Point2::new(1.045148109645135, -1.2054127582099456));
}
#[test]
fn least_squares_fit() -> Result<()> {
let expected = Circle2::new(2.0, 3.0, 1.0);
let samples = make_sample_circle_points(&expected, 500, Some(0.01));
let guess = Circle2::new(0.0, 0.0, 1.0);
let result = Circle2::fitting_circle(&samples, &guess, BestFit::All)?;
assert_relative_eq!(result.center, expected.center, epsilon = 3.0e-3);
assert_relative_eq!(result.r(), expected.r(), epsilon = 3.0e-3);
Ok(())
}
#[test]
fn ransac_fit() -> Result<()> {
let expected = Circle2::new(2.0, 3.0, 1.2);
let decoy = Circle2::new(0.0, 0.0, 1.0);
let samples = [
make_sample_circle_points(&expected, 100, None),
make_sample_circle_points(&decoy, 50, None),
]
.concat();
let result = Circle2::ransac(&samples, 0.005, None, None, None)?;
assert_relative_eq!(result.center, expected.center, epsilon = 3.0e-3);
assert_relative_eq!(result.r(), expected.r(), epsilon = 3.0e-3);
Ok(())
}
fn make_sample_circle_points(c: &Circle2, n: usize, sigma: Option<f64>) -> Vec<Point2> {
let mut points = Vec::with_capacity(n);
let angle_step = 2.0 * PI / (n as f64);
let mut rng = rand::rng();
for i in 0..n {
let angle = angle_step * i as f64;
let r = if let Some(sigma) = sigma {
Normal::new(0.0, sigma).unwrap().sample(&mut rng)
} else {
0.0
} + c.r();
let point = c.center + Vector2::new(r * angle.cos(), r * angle.sin());
points.push(point);
}
points
}
}