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
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
//! A simultaneous alignment of several curve bodies to each other in one combined
//! Levenberg-Marquardt minimization.
//!
//! This is a bundle adjustment rather than a pose graph optimization: it carries a single
//! transformation for each body except one, which is held fixed, and solves for all of them at
//! once against the raw correspondences. It was built to register metrology-quality profiles of
//! objects with unambiguous morphology, and it works best on low-noise data which has already
//! been pre-aligned close to each other with substantial overlap.
//!
//! Each body is a [`crate::geom2::CurveGroup2`]: one or more disjoint curves moving together
//! rigidly, such as the loops and open segments a planar section of a mesh produces. Everything
//! per-body is indexed by the body, while a sample point's `member` field records which curve
//! within its body it sits on.
//!
//! This is the 2D counterpart of `geom3::align3::multi_mesh`, and is deliberately structured
//! identically to it.
//!
//! # How a correspondence constrains two bodies
//!
//! Every alignment point belongs to one body and is matched against another, and *both* of those
//! bodies are moving. A single residual therefore contributes two blocks to its jacobian row: the
//! forward derivative with respect to the test body's parameters, and the reverse derivative with
//! respect to the reference body's. See [`point_surf_jacobian`] and [`point_surf_jacobian_rev`].
//!
//! # Coordinate frames
//!
//! Everything is measured in world coordinates. A test point is moved by its own body's
//! transform, the query is pushed into the reference body's frame only long enough to find the
//! closest point on any of its members, and that match is brought back out to the world before
//! the residual is taken.
//!
//! This matters because each body's [`AlignValues2`] describes its transform *to the world*, so
//! the residual and both jacobian blocks have to live there too for the derivatives to be
//! consistent with it.
//!
//! # The distance gate is not optional
//!
//! [`MultiOptions2::max_distance`] must be supplied, and there is no `Default` for the
//! options precisely so that it cannot be forgotten. See its documentation for the measurements
//! behind that, which were taken on the 3D side but describe a property of the bundle rather than
//! of the dimension.
//!
//! # A known mismatch with the robust weighting, inherited from the single-body solver
//!
//! [`RESIDUAL_DOF`] is 2 here, matching `points_to_surface2`, on the grounds that the residual is
//! a Euclidean point-to-curve distance in the plane. That describes the arithmetic rather than the
//! distribution. What sets the degrees of freedom is how many independent dimensions of noise
//! survive into the residual, and against a curve the answer is usually one: noise which slides a
//! test point along the local tangent does not change its distance to the curve at all, because
//! the closest point slides along to follow it. Only the normal component contributes. The
//! residual regains its second dimension only where the projection clamps, at a vertex or at the
//! end of an open curve.
//!
//! The practical effect is that MAGSAC++ treats residuals as drawn from a wider distribution than
//! they are, so robust refinement down-weights outliers less aggressively than it should. The
//! geometry is unaffected. Fixing it means changing the weighting, and `MagsacWeight` will not
//! accept a dof of 1 as written, so it is recorded here rather than tuned around. The same is true
//! of the 3D path, and any fix should be judged against both.

use crate::Result;
use crate::common::align::{RefinementHalt, SolveQuality, TerminationReason};
use crate::common::consensus::weights::{MagsacWeight, estimate_sigma_max};
use crate::common::points::dist;
use crate::geom2::align2::curve::{CAPParams, CurveSurfPoint, generate_alignment_points};
use crate::geom2::align2::jacobian::{point_surf_jacobian, point_surf_jacobian_rev};
use crate::geom2::align2::{AlignValues2, Dof3, MultiParams2};
use crate::geom2::{Align2, CurveGroup2, Iso2, MultiOutcome2, Point2, SurfacePoint2, Vector2};
use crate::na::{DMatrix, DVector, Dyn, Matrix, Owned, U1, Vector};
use levenberg_marquardt::{LeastSquaresProblem, LevenbergMarquardt};
use rayon::prelude::*;

/// The residual degrees of freedom for the MAGSAC++ weight function. The residual is a full
/// Euclidean point-to-curve distance in the plane, so it follows a chi distribution with two
/// degrees of freedom. See the module documentation for why this overstates the true figure.
const RESIDUAL_DOF: usize = 2;

// ================================================================================================
// Options
// ================================================================================================

/// Options controlling a simultaneous multi-curve alignment.
///
/// Construct with [`MultiOptions2::new`], which requires the correspondence distance gate,
/// and override the remaining fields you care about. The robust-estimation fields mirror
/// `AlignOptions2` and behave identically; the two gates at the top are specific to multi-body
/// work.
///
/// There is deliberately no `Default`. See [`MultiOptions2::max_distance`] for why the gate
/// cannot be left to a default.
#[derive(Clone, Copy, Debug)]
pub struct MultiOptions2 {
    /// A hard cutoff on correspondence distance, in the units of the geometry. A point whose
    /// closest match on the reference curve is further than this contributes nothing.
    ///
    /// This is required rather than optional, and that is a deliberate reversal of the earlier
    /// advice to leave it off and let robust weighting do the work. On real multi-scan data that
    /// advice is wrong, and expensively so.
    ///
    /// Bodies overlap only partially, so a point in a region the reference never saw has no
    /// meaningful match at any distance. The alignment opens with an *unweighted* least squares
    /// solve, in order to have residuals from which to estimate a noise scale, and unweighted least
    /// squares has no defense whatsoever against a gross outlier. A handful of correspondences
    /// sampled across non-overlapping regions is enough to drag the whole bundle.
    ///
    /// Measured on the 3D path, over seventeen partially overlapping laser scans of a part 127 mm
    /// across, starting from an already converged alignment: with no gate the initial solve moved
    /// the group by 0.83 mm and left ten times as many points beyond a tenth of a millimetre of the
    /// reference. Any gate at all fixed it, taking the drift to 0.09 mm. A gate of 1.0 mm and one
    /// of 0.5 mm gave identical results, which says the offending correspondences were more than a
    /// millimetre out rather than marginal. Robust refinement afterwards did not rescue it, because
    /// the noise scale is estimated by a median absolute deviation from that same bad solve: the
    /// estimate describes the well-fitted core, and MAGSAC then treats the displaced body's
    /// correspondences as outliers and stops pulling on them, entrenching the error it inherited.
    ///
    /// Curves are, if anything, more exposed to this than meshes. A profile sliced out of a scan
    /// carries fewer correspondences than a mesh does, so a given number of bad ones is a larger
    /// share of the total.
    ///
    /// Choose it from the geometry rather than from the expected residual. It only has to be
    /// tighter than the scale of a spurious match, so err generous: a value far larger than the
    /// alignment error still removes the correspondences that matter.
    ///
    /// Note that, like `ignore_off_target` in the single-body case, this is a hard gate
    /// re-evaluated as the points move, so it makes the objective piecewise.
    pub max_distance: f64,

    /// An optional cutoff on the angle, in radians, between a test point's normal and its match's
    /// normal. A correspondence exceeding it contributes nothing.
    ///
    /// This suppresses matches onto the far side of a thin wall, where the geometry is close but
    /// facing the wrong way. `None` accepts any orientation.
    pub max_normal_angle: Option<f64>,

    /// The number of iteratively reweighted refinement rounds to perform after the initial
    /// unweighted solve. Zero disables robust weighting entirely.
    pub refinement_steps: usize,

    /// The MAGSAC++ upper noise bound, estimated from the initial residuals via the median
    /// absolute deviation when `None`.
    ///
    /// This is in the units of the geometry, not in units of sigma. The single-body solver
    /// divides its residuals through by a measurement uncertainty before weighting them, so its
    /// `AlignOptions2::sigma_max` is a multiple of that; there is no uncertainty on this path, so
    /// the residuals reaching the weight function are plain distances and this bound is one too.
    pub sigma_max: Option<f64>,

    /// The Levenberg-Marquardt evaluation budget, as a multiplier on the parameter count.
    ///
    /// A multi-body solve carries `3 * (n - 1)` parameters, so this budget stretches a long way
    /// with many bodies. A solve which exhausts it is not a failure: the alignments are kept and
    /// the outcome reports [`crate::common::SolveQuality::Unconverged`]. That is a common outcome
    /// here, since correspondences flip between every overlapping pair.
    ///
    /// Must be greater than zero.
    pub patience: usize,

    /// An optional degree-of-freedom constraint applied to every non-static body.
    pub dof: Option<Dof3>,
}

impl MultiOptions2 {
    /// Options with the required correspondence distance gate and defaults for everything else.
    ///
    /// `max_distance` has no safe default and so has to be supplied; see its documentation for the
    /// measurements behind that. Everything else follows the single-body defaults: four rounds of
    /// robust refinement with the noise scale estimated from the data, no normal gate, no degree of
    /// freedom locks.
    pub fn new(max_distance: f64) -> Self {
        Self {
            max_distance,
            max_normal_angle: None,
            refinement_steps: 4,
            sigma_max: None,
            patience: 100,
            dof: None,
        }
    }
}

// ================================================================================================
// Alignment points
// ================================================================================================

/// A single correspondence in a multi-curve adjustment: a sample point on one body which is
/// being matched against another body.
///
/// `group_i` and `ref_i` are body indices; which member curve *within* each body is involved is
/// carried by the sample point's own `member` field.
#[derive(Clone, Debug)]
pub struct CurveAlignPoint {
    /// The index of the body this point was sampled from.
    pub group_i: usize,

    /// The sample point, in the coordinates of its own body.
    pub cp: CurveSurfPoint,

    /// The index of the body this point is being matched against.
    pub ref_i: usize,

    /// A base weight for the correspondence, applied on top of any robust weighting.
    pub weight: f64,
}

impl CurveAlignPoint {
    /// Creates a correspondence from a sample `cp` on body `group_i`, matched against reference
    /// body `ref_i` with the given weight.
    pub fn new(group_i: usize, cp: CurveSurfPoint, ref_i: usize, weight: f64) -> Self {
        Self {
            group_i,
            cp,
            ref_i,
            weight,
        }
    }
}

// ================================================================================================
// Entry points
// ================================================================================================

/// Runs a simultaneous alignment over an explicit set of correspondences.
///
/// Use this when the correspondences have already been chosen, whether by sampling them yourself
/// or by pruning an existing set.
///
/// # Arguments
///
/// * `groups`: the bodies taking part
/// * `initial`: an optional starting pose per body. `None` starts every body at the identity.
/// * `points`: the correspondences, each naming the body it was sampled from and the body it is
///   matched against
/// * `static_i`: the index of the body to hold fixed, which becomes the frame every result is
///   expressed in
/// * `opts`: the solver options, which must carry a correspondence distance gate
///
/// # Failure
///
/// As with the single-body solver, `Err` is reserved for the case where there is no answer at
/// all: rejected arguments, or an initial solve that broke down. A solve which merely exhausts
/// its budget is reported on the outcome and its alignments kept.
pub fn multi_curve_adjustment_with_points(
    groups: &[CurveGroup2],
    initial: Option<&[Iso2]>,
    points: Vec<CurveAlignPoint>,
    static_i: usize,
    opts: &MultiOptions2,
) -> Result<MultiOutcome2> {
    let poses = resolve_poses(groups, initial)?;
    validate(groups, &points, static_i, opts)?;
    solve_bundle(
        MultiCurveProblem::new(groups, poses, points, static_i, opts)?,
        opts,
    )
}

/// Expands the optional per-body starting poses into one pose per body, validating the length.
fn resolve_poses(groups: &[CurveGroup2], initial: Option<&[Iso2]>) -> Result<Vec<Iso2>> {
    match initial {
        None => Ok(vec![Iso2::identity(); groups.len()]),
        Some(t) if t.len() == groups.len() => Ok(t.to_vec()),
        Some(t) => Err(format!(
            "there are {} bodies but {} initial transforms",
            groups.len(),
            t.len()
        )
        .into()),
    }
}

/// Samples correspondences between every pair of bodies and runs a simultaneous alignment.
///
/// The static body is chosen automatically as the one the others reference most broadly; see
/// `correspondence_matrix` for how that is scored. Correspondences are sampled with
/// [`generate_alignment_points`], and each unordered pair of bodies produces correspondences in
/// one direction only.
///
/// # Arguments
///
/// * `groups`: the bodies taking part. At least two are required.
/// * `initial`: an optional starting pose per body. `None` starts every body at the identity.
/// * `opts`: the solver options, which must carry a correspondence distance gate
/// * `sample_opts`: the parameters controlling which points along each body's members become
///   correspondences
///
/// # Failure
///
/// As with [`multi_curve_adjustment_with_points`], `Err` is reserved for the case where there is
/// no answer at all.
pub fn multi_curve_adjustment(
    groups: &[CurveGroup2],
    initial: Option<&[Iso2]>,
    opts: &MultiOptions2,
    sample_opts: &CAPParams,
) -> Result<MultiOutcome2> {
    if groups.len() < 2 {
        return Err(format!(
            "a multi-curve alignment needs at least two bodies, but {} were given",
            groups.len()
        )
        .into());
    }
    let poses = resolve_poses(groups, initial)?;

    let reference_order = reference_priority(groups, &poses, sample_opts)?;
    let static_i = reference_order[0];

    // Build the work list so that each unordered pair of bodies produces correspondences in one
    // direction only, never both.
    let mut work_list = Vec::new();
    let mut bodies_to_test = (0..groups.len()).collect::<Vec<_>>();
    for ref_i in reference_order {
        bodies_to_test.retain(|j| *j != ref_i);
        for &group_i in bodies_to_test.iter() {
            work_list.push((group_i, ref_i));
        }
    }

    let points = work_list
        .par_iter()
        .map(|&(group_i, ref_i)| {
            let t = poses[ref_i].inv_mul(&poses[group_i]);
            let samples =
                generate_alignment_points(&groups[group_i], &groups[ref_i], &t, sample_opts);

            samples
                .into_iter()
                .map(|cp| CurveAlignPoint::new(group_i, cp, ref_i, 1.0))
                .collect::<Vec<_>>()
        })
        .flatten()
        .collect::<Vec<_>>();

    multi_curve_adjustment_with_points(groups, initial, points, static_i, opts)
}

// ================================================================================================
// The solve
// ================================================================================================

fn validate(
    groups: &[CurveGroup2],
    points: &[CurveAlignPoint],
    static_i: usize,
    opts: &MultiOptions2,
) -> Result<()> {
    if opts.patience == 0 {
        return Err("patience must be greater than zero".into());
    }
    if let Some(s) = opts.sigma_max
        && (!s.is_finite() || s <= 0.0)
    {
        return Err(format!("sigma_max is {s}, but must be finite and strictly positive").into());
    }
    if !opts.max_distance.is_finite() || opts.max_distance <= 0.0 {
        return Err(format!(
            "max_distance is {}, but must be finite and strictly positive",
            opts.max_distance
        )
        .into());
    }
    if static_i >= groups.len() {
        return Err(format!(
            "the static body index {} is out of range for {} bodies",
            static_i,
            groups.len()
        )
        .into());
    }
    if let Some(p) = points
        .iter()
        .find(|p| p.group_i >= groups.len() || p.ref_i >= groups.len())
    {
        return Err(format!(
            "an alignment point references body {} against body {}, but there are only {} bodies",
            p.group_i,
            p.ref_i,
            groups.len()
        )
        .into());
    }

    Ok(())
}

fn solve_bundle(problem: MultiCurveProblem<'_>, opts: &MultiOptions2) -> Result<MultiOutcome2> {
    let lm = LevenbergMarquardt::<f64>::new().with_patience(opts.patience);
    let n_params = problem.params.param_count();

    let (mut problem, termination) = run(&lm, problem);
    if !SolveQuality::from_termination(&termination).is_usable() {
        return Err(format!("Failed to align bodies to each other: {termination:?}").into());
    }

    let mut solves = vec![termination];
    let mut halt = None;

    if opts.refinement_steps > 0 {
        match resolve_sigma_max(opts, &problem) {
            None => halt = Some(RefinementHalt::NoNoiseEstimate),
            Some(sigma_max) => {
                let weighting = MagsacWeight::new(sigma_max, RESIDUAL_DOF);

                for _ in 0..opts.refinement_steps {
                    let weighted = problem.count_if_reweighted(&weighting);
                    if weighted < n_params {
                        halt = Some(RefinementHalt::Underdetermined {
                            weighted,
                            params: n_params,
                        });
                        break;
                    }

                    let last_good = problem.params.storage().clone();
                    problem.apply_magsac_weights(&weighting);

                    let (next, termination) = run(&lm, problem);
                    problem = next;

                    if !SolveQuality::from_termination(&termination).is_usable() {
                        problem.restore(&last_good);
                        halt = Some(RefinementHalt::SolveFailed(termination));
                        break;
                    }
                    solves.push(termination);
                }
            }
        }
    }

    Ok(MultiOutcome2::new(problem.alignments(), solves, halt))
}

fn run<'a>(
    lm: &LevenbergMarquardt<f64>,
    problem: MultiCurveProblem<'a>,
) -> (MultiCurveProblem<'a>, TerminationReason) {
    let (result, report) = lm.minimize(problem);
    (result, report.termination)
}

fn resolve_sigma_max(opts: &MultiOptions2, problem: &MultiCurveProblem<'_>) -> Option<f64> {
    match opts.sigma_max {
        Some(s) => Some(s),
        None => estimate_sigma_max(&problem.residuals),
    }
}

// ================================================================================================
// The problem
// ================================================================================================

/// The per-correspondence state produced by one pass of `move_points`.
struct Moved {
    p_world: Point2,
    c_world: SurfacePoint2,
    residual: f64,
    target_weight: f64,
}

struct MultiCurveProblem<'a> {
    groups: &'a [CurveGroup2],
    handles: Vec<CurveAlignPoint>,
    params: MultiParams2,

    /// The alignment values of every body for the current parameters, cached so the residual and
    /// jacobian loops don't recompute them per correspondence.
    values: Vec<AlignValues2>,

    /// The test point of each correspondence in world coordinates.
    moved: Vec<Point2>,

    /// The matching surface point of each correspondence, also in world coordinates.
    closest: Vec<SurfacePoint2>,

    /// The signed geometric distance of each correspondence, in model units.
    residuals: Vec<f64>,

    /// The weight contributed by the correspondence itself: the point's base weight and the two
    /// geometric gates.
    target_weights: Vec<f64>,

    /// The weight contributed by MAGSAC++ reweighting, held fixed across a solve.
    magsac_weights: Vec<f64>,

    max_distance: f64,
    min_normal_dot: Option<f64>,
}

impl<'a> MultiCurveProblem<'a> {
    fn new(
        groups: &'a [CurveGroup2],
        poses: Vec<Iso2>,
        handles: Vec<CurveAlignPoint>,
        static_i: usize,
        opts: &MultiOptions2,
    ) -> Result<Self> {
        let centers = groups.iter().map(|g| g.aabb().center()).collect::<Vec<_>>();
        let params = MultiParams2::from_centers(static_i, &centers, Some(&poses), opts.dof)?;

        let n = handles.len();

        let values = params.compute_all_values();
        let mut item = Self {
            groups,
            handles,
            params,
            values,
            moved: vec![Point2::origin(); n],
            closest: vec![SurfacePoint2::new(Point2::origin(), Vector2::y_axis()); n],
            residuals: vec![0.0; n],
            target_weights: vec![1.0; n],
            magsac_weights: vec![1.0; n],
            max_distance: opts.max_distance,
            min_normal_dot: opts.max_normal_angle.map(f64::cos),
        };

        item.move_points();
        Ok(item)
    }

    /// Moves every test point into world coordinates, finds its match on the reference body,
    /// brings that match back out to the world, and recomputes the residual and the geometric
    /// weights.
    fn move_points(&mut self) {
        self.values = self.params.compute_all_values();

        let values = &self.values;
        let groups = self.groups;
        let max_distance = self.max_distance;
        let min_normal_dot = self.min_normal_dot;

        let collected: Vec<Moved> = self
            .handles
            .par_iter()
            .map(|h| {
                let t_test = values[h.group_i].transform;
                let t_ref = values[h.ref_i].transform;

                // Into the world, then into the reference body's frame just long enough to find
                // the closest point on any of its members.
                let p_world = t_test * h.cp.sp.point;
                let query = t_ref.inverse_transform_point(&p_world);
                let (_, station) = groups[h.ref_i].at_closest_to_point(&query);

                // ...and back out to the world, where the residual is measured.
                let c_world = station.surface_point().transformed_by(&t_ref);

                let d = dist(&p_world, &c_world.point);
                let residual = d * c_world.scalar_projection(&p_world).signum();

                let mut weight = h.weight;
                if d > max_distance {
                    weight = 0.0;
                }
                if let Some(min_dot) = min_normal_dot {
                    let n_test = t_test.rotation * h.cp.sp.normal;
                    if n_test.dot(&c_world.normal) < min_dot {
                        weight = 0.0;
                    }
                }

                Moved {
                    p_world,
                    c_world,
                    residual,
                    target_weight: weight,
                }
            })
            .collect();

        for (i, m) in collected.into_iter().enumerate() {
            self.moved[i] = m.p_world;
            self.closest[i] = m.c_world;
            self.residuals[i] = m.residual;
            self.target_weights[i] = m.target_weight;
        }
    }

    /// Puts the parameters back to a previous state and rebuilds the correspondences to match.
    fn restore(&mut self, storage: &DVector<f64>) {
        self.params.set_storage(storage);
        self.move_points();
    }

    /// The factor applied to both the residual and the jacobian row of a correspondence.
    fn scale(&self, i: usize) -> f64 {
        (self.target_weights[i] * self.magsac_weights[i]).sqrt()
    }

    fn apply_magsac_weights(&mut self, weighting: &MagsacWeight) {
        for i in 0..self.handles.len() {
            self.magsac_weights[i] = weighting.weight(self.residuals[i].abs());
        }
    }

    fn count_if_reweighted(&self, weighting: &MagsacWeight) -> usize {
        (0..self.handles.len())
            .filter(|&i| self.target_weights[i] * weighting.weight(self.residuals[i].abs()) > 0.0)
            .count()
    }

    /// Builds one [`Align2`] per body, with that body's own correspondence residuals.
    fn alignments(&self) -> Vec<Align2> {
        let mut grouped = vec![Vec::new(); self.groups.len()];
        for (i, h) in self.handles.iter().enumerate() {
            grouped[h.group_i].push(self.residuals[i]);
        }

        self.values
            .iter()
            .enumerate()
            .zip(grouped)
            .map(|((i, v), residuals)| {
                let body = self.params.body(i);
                Align2::new(v.transform, v.align, body.local, body.offset, residuals)
            })
            .collect()
    }
}

impl LeastSquaresProblem<f64, Dyn, Dyn> for MultiCurveProblem<'_> {
    type ResidualStorage = Owned<f64, Dyn, U1>;
    type JacobianStorage = Owned<f64, Dyn, Dyn>;
    type ParameterStorage = Owned<f64, Dyn>;

    fn set_params(&mut self, x: &Vector<f64, Dyn, Self::ParameterStorage>) {
        self.params.set_storage(x);
        self.move_points();
    }

    fn params(&self) -> Vector<f64, Dyn, Self::ParameterStorage> {
        self.params.storage().clone()
    }

    fn residuals(&self) -> Option<Vector<f64, Dyn, Self::ResidualStorage>> {
        let mut res = Matrix::<f64, Dyn, U1, Self::ResidualStorage>::zeros(self.handles.len());
        for i in 0..self.handles.len() {
            res[i] = self.residuals[i] * self.scale(i);
        }
        Some(res)
    }

    fn jacobian(&self) -> Option<Matrix<f64, Dyn, Dyn, Self::JacobianStorage>> {
        let mut jac = Matrix::<f64, Dyn, Dyn, Self::JacobianStorage>::zeros(
            self.handles.len(),
            self.params.param_count(),
        );

        for (i, h) in self.handles.iter().enumerate() {
            let scale = self.scale(i);
            let p = &self.moved[i];
            let c = &self.closest[i];

            // The correspondence constrains the test curve...
            let fwd = point_surf_jacobian(p, c, &self.values[h.group_i]) * scale;
            self.params.add_jacobian_block(&mut jac, i, h.group_i, &fwd);

            // ...and the reference curve, which is also free to move.
            let rev = point_surf_jacobian_rev(p, c, &self.values[h.ref_i]) * scale;
            self.params.add_jacobian_block(&mut jac, i, h.ref_i, &rev);
        }

        Some(jac)
    }
}

// ================================================================================================
// Choosing the static curve
// ================================================================================================

/// Orders the bodies by how broadly the others reference them, most-referenced first. The head
/// of the returned order is the best candidate for the static body. The scoring lives in
/// [`crate::common::align::reference`].
fn reference_priority(
    groups: &[CurveGroup2],
    poses: &[Iso2],
    params: &CAPParams,
) -> Result<Vec<usize>> {
    Ok(crate::common::align::reference::reference_priority(
        correspondence_matrix(groups, poses, params)?,
    ))
}

/// The pairwise correspondence counts of the bodies: each `i, j` entry is the number of sample
/// points in body `j` which are a good match for body `i`.
fn correspondence_matrix(
    groups: &[CurveGroup2],
    poses: &[Iso2],
    params: &CAPParams,
) -> Result<DMatrix<f64>> {
    // The 2D sampler cannot currently fail. The shared helper accepts a fallible closure only to
    // match its 3D counterpart, whose sampler rejects invalid spacing.
    crate::common::align::reference::correspondence_matrix(groups.len(), |i, j| {
        let t = poses[i].inv_mul(&poses[j]);
        Ok(generate_alignment_points(&groups[j], &groups[i], &t, params).len() as f64)
    })
    .map_err(|e| e.into())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::random_geometry::RandomGeometry2;
    use crate::geom2::{Curve2, CurveGroup2, Iso2};
    use approx::assert_relative_eq;
    use std::f64::consts::{PI, TAU};

    /// A correspondence gate wider than the test rectangles themselves, so that the synthetic
    /// cases exercise the solver rather than the gate. Cases which are about the gate set their
    /// own.
    const WIDE_GATE: f64 = 20.0;

    fn test_opts() -> MultiOptions2 {
        MultiOptions2::new(WIDE_GATE)
    }

    /// A closed counter-clockwise rectangle 10 by 6, centered on the origin, so its normals point
    /// outward. Its corners sit at arc lengths 0, 10, 16 and 26 out of a perimeter of 32.
    fn rect_curve() -> Curve2 {
        let points =
            [(-5.0, -3.0), (5.0, -3.0), (5.0, 3.0), (-5.0, 3.0)].map(|(x, y)| Point2::new(x, y));
        Curve2::from_points(&points, 1e-8, true).unwrap()
    }

    /// A straight open segment along the x axis, from `x0` to `x1`.
    fn segment_curve(x0: f64, x1: f64) -> Curve2 {
        Curve2::from_points(&[Point2::new(x0, 0.0), Point2::new(x1, 0.0)], 1e-8, false).unwrap()
    }

    /// Correspondences from every curve onto the one before it, sampled at a uniform arc length
    /// spacing. The half-spacing offset keeps samples off the corners, where the normal of a
    /// polyline is ambiguous.
    fn chain_points(curves: &[Curve2], spacing: f64) -> Vec<CurveAlignPoint> {
        let mut points = Vec::new();
        for (i, curve) in curves.iter().enumerate().skip(1) {
            let n = (curve.length() / spacing).floor() as usize;
            for k in 0..n {
                let l = (k as f64 + 0.5) * spacing;
                if let Some(station) = curve.at_length(l) {
                    let cp = CurveSurfPoint::from_station(&station, 0);
                    points.push(CurveAlignPoint::new(i, cp, i - 1, 1.0));
                }
            }
        }
        points
    }

    /// A straight open segment along the y axis at `x`, from `y0` to `y1`.
    fn vertical_segment(x: f64, y0: f64, y1: f64) -> Curve2 {
        Curve2::from_points(&[Point2::new(x, y0), Point2::new(x, y1)], 1e-8, false).unwrap()
    }

    /// A closed circle of 64 segments, which turns gently everywhere and so has no corners for
    /// the sampler to reject. This is the stand-in for the closed loops a real section produces.
    ///
    /// Note that it is not a stand-in for a rotationally symmetric body: the facets of a 64-gon
    /// give a rotation of a fraction of a degree a real signal to work against, so a lone circle
    /// does pin down its own orientation here.
    fn circle_curve(cx: f64, cy: f64, r: f64) -> Curve2 {
        const N: usize = 64;
        let points = (0..N)
            .map(|i| {
                let a = TAU * (i as f64) / (N as f64);
                Point2::new(cx + r * a.cos(), cy + r * a.sin())
            })
            .collect::<Vec<_>>();
        Curve2::from_points(&points, 1e-8, true).unwrap()
    }

    /// A body of two circles ten units apart, centered on the origin as a whole.
    fn two_circle_body() -> CurveGroup2 {
        CurveGroup2::new(vec![
            circle_curve(-5.0, 0.0, 2.0),
            circle_curve(5.0, 0.0, 2.0),
        ])
        .unwrap()
    }

    /// A small rigid disturbance: a rotation about the world origin plus a translation.
    fn small_disturbance(tx: f64, ty: f64, rz: f64) -> Iso2 {
        Iso2::new(Vector2::new(tx, ty), rz)
    }

    /// Wraps each fixture curve as a body of one, which is how the pre-group tests exercise the
    /// solver. Multi-member bodies build their own groups.
    fn groups_of_one(curves: &[Curve2]) -> Vec<CurveGroup2> {
        curves.iter().cloned().map(CurveGroup2::from).collect()
    }

    // ============================================================================================
    // Recovery
    // ============================================================================================

    #[test]
    fn a_disturbed_curve_is_brought_back_onto_its_twin() -> Result<()> {
        // Two identical rectangles, one of them displaced. The adjustment should undo the
        // displacement, since the two curves coincide when aligned.
        let curves = vec![rect_curve(), rect_curve()];
        let disturb = Iso2::new(Vector2::new(0.2, -0.15), PI / 90.0);
        let initial = vec![Iso2::identity(), disturb];

        let groups = groups_of_one(&curves);
        let points = chain_points(&curves, 0.4);

        let outcome =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &test_opts())?;

        assert_eq!(outcome.len(), 2);
        // Curve 0 is static and must not have moved at all.
        assert_relative_eq!(
            outcome.alignment(0).full_transform().to_matrix(),
            Iso2::identity().to_matrix(),
            epsilon = 1e-12
        );
        // Curve 1 should have come back to the identity, undoing its initial displacement.
        assert_relative_eq!(
            outcome.alignment(1).full_transform().to_matrix(),
            Iso2::identity().to_matrix(),
            epsilon = 1e-6
        );

        Ok(())
    }

    #[test]
    fn three_curves_settle_together() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve(), rect_curve()];
        let initial = vec![
            Iso2::identity(),
            Iso2::new(Vector2::new(0.15, -0.1), PI / 120.0),
            Iso2::new(Vector2::new(-0.1, 0.12), -PI / 100.0),
        ];

        let groups = groups_of_one(&curves);
        let points = chain_points(&curves, 0.5);

        let outcome =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &test_opts())?;

        for i in 0..3 {
            assert_relative_eq!(
                outcome.alignment(i).full_transform().to_matrix(),
                Iso2::identity().to_matrix(),
                epsilon = 1e-5
            );
        }

        Ok(())
    }

    #[test]
    fn the_static_curve_never_moves() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::translation(0.3, 0.0), Iso2::translation(0.0, 0.25)];
        let groups = groups_of_one(&curves);

        // Make curve 1 the static one this time, so the check is not trivially about index zero.
        let outcome = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            chain_points(&curves, 0.5),
            1,
            &test_opts(),
        )?;

        assert_relative_eq!(
            outcome.alignment(1).full_transform().to_matrix(),
            initial[1].to_matrix(),
            epsilon = 1e-12
        );

        Ok(())
    }

    #[test]
    fn residuals_are_grouped_by_the_curve_they_came_from() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(); 3];
        let groups = groups_of_one(&curves);
        let points = chain_points(&curves, 0.6);

        let from_1 = points.iter().filter(|p| p.group_i == 1).count();
        let from_2 = points.iter().filter(|p| p.group_i == 2).count();

        let outcome =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &test_opts())?;

        // Curve 0 sourced no correspondences, so it has no residuals of its own.
        assert_eq!(outcome.alignment(0).residuals().len(), 0);
        assert_eq!(outcome.alignment(1).residuals().len(), from_1);
        assert_eq!(outcome.alignment(2).residuals().len(), from_2);

        Ok(())
    }

    // ============================================================================================
    // Robustness and reporting
    // ============================================================================================

    #[test]
    fn locked_dof_are_honored() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(), Iso2::translation(0.3, 0.0)];
        let groups = groups_of_one(&curves);

        let opts = MultiOptions2 {
            dof: Some(Dof3::new(false, true, true)),
            ..test_opts()
        };
        let outcome = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            chain_points(&curves, 0.5),
            0,
            &opts,
        )?;

        // tx is locked, so the x displacement cannot be undone and must survive untouched.
        assert_relative_eq!(
            outcome.alignment(1).full_transform().translation.vector.x,
            0.3,
            epsilon = 1e-9
        );

        Ok(())
    }

    #[test]
    fn exhausted_budget_is_reported_not_raised() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![
            Iso2::identity(),
            Iso2::new(Vector2::new(1.5, -1.0), PI / 12.0),
        ];
        let groups = groups_of_one(&curves);

        let opts = MultiOptions2 {
            patience: 1,
            ..test_opts()
        };
        let outcome = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            chain_points(&curves, 0.5),
            0,
            &opts,
        )?;

        assert_eq!(outcome.quality(), SolveQuality::Unconverged);
        assert!(outcome.solves().contains(&TerminationReason::LostPatience));
        // The alignments are still real geometry rather than something degenerate.
        for a in outcome.alignments() {
            assert!(a.full_transform().to_matrix().iter().all(|v| v.is_finite()));
        }

        Ok(())
    }

    #[test]
    fn gross_outliers_are_rejected() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let disturb = Iso2::new(Vector2::new(0.2, -0.15), PI / 120.0);
        let initial = vec![Iso2::identity(), disturb];
        let groups = groups_of_one(&curves);

        // Corrupt a tenth of the correspondences by throwing their sample points off the curve.
        let mut points = chain_points(&curves, 0.4);
        for (k, p) in points.iter_mut().enumerate() {
            if k.is_multiple_of(10) {
                p.cp.sp.point += Vector2::new(0.0, 5.0);
            }
        }

        let naive = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            points.clone(),
            0,
            &MultiOptions2 {
                refinement_steps: 0,
                ..test_opts()
            },
        )?;
        let robust =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &test_opts())?;

        let error = |o: &MultiOutcome2| {
            (o.alignment(1).full_transform().to_matrix() - Iso2::identity().to_matrix()).norm()
        };

        assert!(
            error(&robust) < error(&naive) * 0.5,
            "robust weighting should have suppressed the outliers: naive {}, robust {}",
            error(&naive),
            error(&robust)
        );

        Ok(())
    }

    /// The initial unweighted solve is dragged by correspondences into regions the other curve
    /// never covered, which is why `max_distance` is required rather than optional.
    ///
    /// This is the unit-scale form of a failure found on real 3D data: seventeen partially
    /// overlapping laser scans, starting from an already correct alignment, were moved most of a
    /// millimetre by a handful of such correspondences, and the robust refinement that followed
    /// entrenched the error rather than undoing it. See the module documentation.
    #[test]
    fn without_a_distance_gate_the_unweighted_solve_is_dragged() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(), Iso2::identity()];
        let groups = groups_of_one(&curves);

        // Both bodies start on the answer, so any motion at all is damage. A twentieth of the
        // correspondences are thrown well clear of the curve, standing in for points sampled over
        // a region the two curves never both saw.
        let mut points = chain_points(&curves, 0.4);
        for (k, p) in points.iter_mut().enumerate() {
            if k.is_multiple_of(20) {
                p.cp.sp.point += Vector2::new(0.0, 8.0);
            }
        }

        let unweighted = |gate: f64| MultiOptions2 {
            refinement_steps: 0,
            ..MultiOptions2::new(gate)
        };
        let drift = |o: &MultiOutcome2| {
            (o.alignment(1).full_transform().to_matrix() - Iso2::identity().to_matrix()).norm()
        };

        let ungated = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            points.clone(),
            0,
            &unweighted(WIDE_GATE),
        )?;
        let gated = multi_curve_adjustment_with_points(
            &groups,
            Some(&initial),
            points,
            0,
            &unweighted(1.0),
        )?;

        assert!(
            drift(&ungated) > 1e-3,
            "the ungated solve should have been pulled off the answer, but moved only {}",
            drift(&ungated)
        );
        assert!(
            drift(&gated) < drift(&ungated) * 0.1,
            "the gate should have held the solve in place: ungated {}, gated {}",
            drift(&ungated),
            drift(&gated)
        );

        Ok(())
    }

    #[test]
    fn the_distance_gate_excludes_far_correspondences() -> Result<()> {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(), Iso2::identity()];
        let groups = groups_of_one(&curves);

        let mut points = chain_points(&curves, 0.5);
        let far = points.len() / 2;
        points[far].cp.sp.point += Vector2::new(0.0, 50.0);

        // With a tight gate the distant point contributes nothing, so the fit is unchanged from
        // the identity it already sits at.
        let opts = MultiOptions2 {
            max_distance: 1.0,
            refinement_steps: 0,
            ..test_opts()
        };
        let outcome =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &opts)?;

        assert_relative_eq!(
            outcome.alignment(1).full_transform().to_matrix(),
            Iso2::identity().to_matrix(),
            epsilon = 1e-6
        );

        Ok(())
    }

    #[test]
    fn the_normal_gate_excludes_disagreeing_correspondences() -> Result<()> {
        // A point whose normal faces the opposite way from its match is suppressed, which is what
        // keeps a match from landing on the far side of a thin wall.
        let curves = vec![rect_curve(), rect_curve()];
        let initial = [Iso2::identity(), Iso2::identity()];
        let groups = groups_of_one(&curves);

        // One correspondence, sampled mid-way along the bottom edge and then flipped so its
        // normal points inward while its match still points outward.
        let station = curves[1].at_length(5.0).unwrap();
        let mut cp = CurveSurfPoint::from_station(&station, 0);
        cp.sp.normal = -cp.sp.normal;

        let opts = MultiOptions2 {
            max_normal_angle: Some(PI / 4.0),
            refinement_steps: 0,
            ..test_opts()
        };
        let points = vec![CurveAlignPoint::new(1, cp, 0, 1.0)];
        let problem = MultiCurveProblem::new(&groups, initial.to_vec(), points, 0, &opts)?;

        assert_eq!(problem.target_weights[0], 0.0);

        Ok(())
    }

    // ============================================================================================
    // The jacobian
    // ============================================================================================

    #[test]
    fn jacobian_matches_finite_differences() -> Result<()> {
        // The recovery tests above are insensitive to jacobian errors: a wrong jacobian usually
        // costs Levenberg-Marquardt iterations rather than moving the minimum, so the solve still
        // lands in the right place. This checks the derivative itself.
        //
        // Three bodies are needed, not two. With two, the only reference is the static body, whose
        // jacobian block is dropped anyway, so the reverse derivative would never be exercised.
        // Here body 1 is a reference for body 2's correspondences *and* is free to move, which is
        // the configuration that puts the reverse block to work.
        let curves = vec![rect_curve(), rect_curve(), rect_curve()];
        let initial = [
            Iso2::identity(),
            Iso2::new(Vector2::new(0.21, -0.13), 0.03),
            Iso2::new(Vector2::new(-0.17, 0.11), -0.04),
        ];
        let groups = groups_of_one(&curves);

        // Sample points well away from the corners of the rectangle, so every projection lands in
        // the interior of an edge. The analytic jacobian holds the correspondence fixed, which is
        // right for a locally straight target but not across a corner, and near a corner the
        // finite difference would pick up a correspondence flip the analytic form does not model.
        let probes = [2.0, 5.0, 8.0, 12.0, 14.0, 18.0, 21.0, 24.0, 28.0, 30.0];
        let mut points = Vec::new();
        for body in [1usize, 2] {
            for l in probes {
                let cp = CurveSurfPoint::from_station(&curves[body].at_length(l).unwrap(), 0);
                points.push(CurveAlignPoint::new(body, cp, body - 1, 1.0));
            }
        }

        let opts = MultiOptions2 {
            refinement_steps: 0,
            ..test_opts()
        };
        let mut problem = MultiCurveProblem::new(&groups, initial.to_vec(), points, 0, &opts)?;

        let x0 = problem.params.storage().clone();
        let analytic = problem.jacobian().unwrap();
        assert_eq!(
            analytic.ncols(),
            6,
            "two free bodies, three parameters each"
        );

        let eps = 1e-7;
        for k in 0..x0.len() {
            let mut lo = x0.clone();
            lo[k] -= eps;
            problem.set_params(&lo);
            let r_lo = problem.residuals().unwrap();

            let mut hi = x0.clone();
            hi[k] += eps;
            problem.set_params(&hi);
            let r_hi = problem.residuals().unwrap();

            for row in 0..r_lo.len() {
                let numeric = (r_hi[row] - r_lo[row]) / (2.0 * eps);
                assert_relative_eq!(analytic[(row, k)], numeric, epsilon = 1e-5);
            }
        }

        Ok(())
    }

    #[test]
    fn a_reference_body_receives_jacobian_columns() -> Result<()> {
        // A narrower statement of the same thing, which fails loudly if the reverse block is ever
        // dropped: correspondences sourced from body 2 must produce nonzero derivatives in body
        // 1's columns, because body 1 is what they are matched against.
        let curves = vec![rect_curve(), rect_curve(), rect_curve()];
        let initial = [
            Iso2::identity(),
            Iso2::translation(0.2, 0.0),
            Iso2::translation(0.0, 0.2),
        ];
        let groups = groups_of_one(&curves);

        let cp = CurveSurfPoint::from_station(&curves[2].at_length(5.0).unwrap(), 0);
        let points = vec![CurveAlignPoint::new(2, cp, 1, 1.0)];

        let problem = MultiCurveProblem::new(&groups, initial.to_vec(), points, 0, &test_opts())?;
        let jac = problem.jacobian().unwrap();

        let body1 = problem.params.column_offset(1).unwrap();
        let body2 = problem.params.column_offset(2).unwrap();

        let block_norm =
            |start: usize| -> f64 { (0..3).map(|k| jac[(0, start + k)].abs()).sum::<f64>() };

        assert!(
            block_norm(body2) > 1e-9,
            "the test body should have a nonzero jacobian block"
        );
        assert!(
            block_norm(body1) > 1e-9,
            "the reference body should have a nonzero jacobian block too"
        );

        Ok(())
    }

    #[test]
    fn a_self_correspondence_cancels_to_a_zero_row() -> Result<()> {
        // A point matched against its own curve carries no information: moving that curve moves
        // the test point and its match together, so the distance between them cannot change. The
        // two jacobian blocks land in the same columns and must cancel, which they do because the
        // reverse form is the negation of the forward one when both share a body.
        //
        // This is why the blocks are accumulated rather than assigned. Overwriting would keep only
        // the reverse block and report a spurious sensitivity for a correspondence that has none.
        let curves = vec![rect_curve(), rect_curve()];
        let initial = [Iso2::identity(), Iso2::translation(0.3, -0.2)];
        let groups = groups_of_one(&curves);

        let cp = CurveSurfPoint::from_station(&curves[1].at_length(5.0).unwrap(), 0);
        let points = vec![CurveAlignPoint::new(1, cp, 1, 1.0)];

        let problem = MultiCurveProblem::new(&groups, initial.to_vec(), points, 0, &test_opts())?;
        let jac = problem.jacobian().unwrap();

        for k in 0..jac.ncols() {
            assert_relative_eq!(jac[(0, k)], 0.0, epsilon = 1e-12);
        }

        Ok(())
    }

    // ============================================================================================
    // Validation
    // ============================================================================================

    #[test]
    fn invalid_options_and_indices_are_rejected() {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(); 2];
        let groups = groups_of_one(&curves);
        let points = chain_points(&curves, 1.0);

        let bad_patience = MultiOptions2 {
            patience: 0,
            ..test_opts()
        };
        assert!(
            multi_curve_adjustment_with_points(
                &groups,
                Some(&initial),
                points.clone(),
                0,
                &bad_patience
            )
            .is_err()
        );

        let bad_sigma = MultiOptions2 {
            sigma_max: Some(-1.0),
            ..test_opts()
        };
        assert!(
            multi_curve_adjustment_with_points(
                &groups,
                Some(&initial),
                points.clone(),
                0,
                &bad_sigma
            )
            .is_err()
        );

        let bad_distance = MultiOptions2 {
            max_distance: 0.0,
            ..test_opts()
        };
        assert!(
            multi_curve_adjustment_with_points(
                &groups,
                Some(&initial),
                points.clone(),
                0,
                &bad_distance
            )
            .is_err()
        );

        // A static index past the end of the curve list.
        assert!(
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 5, &test_opts())
                .is_err()
        );
    }

    #[test]
    fn out_of_range_alignment_points_are_rejected() {
        let curves = vec![rect_curve(), rect_curve()];
        let initial = vec![Iso2::identity(); 2];
        let groups = groups_of_one(&curves);

        let mut points = chain_points(&curves, 1.0);
        points[0].ref_i = 7;

        let err =
            multi_curve_adjustment_with_points(&groups, Some(&initial), points, 0, &test_opts())
                .unwrap_err()
                .to_string();
        assert!(err.contains("only 2 bodies"), "unexpected message: {err}");
    }

    #[test]
    fn a_mismatched_initial_slice_is_rejected() {
        let curves = vec![rect_curve(), rect_curve()];
        let groups = groups_of_one(&curves);
        let short = [Iso2::identity(); 1];

        let err = multi_curve_adjustment_with_points(
            &groups,
            Some(&short),
            chain_points(&curves, 1.0),
            0,
            &test_opts(),
        )
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("initial transforms"),
            "unexpected message: {err}"
        );
    }

    // ============================================================================================
    // The automatic entry point
    // ============================================================================================

    #[test]
    fn sampled_correspondences_settle_three_curves_together() -> Result<()> {
        // The same recovery as `three_curves_settle_together`, but letting the entry point choose
        // the static curve and sample the correspondences itself.
        let curves = vec![rect_curve(), rect_curve(), rect_curve()];
        let initial = vec![
            Iso2::identity(),
            Iso2::new(Vector2::new(0.15, -0.1), PI / 120.0),
            Iso2::new(Vector2::new(-0.1, 0.12), -PI / 100.0),
        ];
        let groups = groups_of_one(&curves);

        let outcome = multi_curve_adjustment(
            &groups,
            Some(&initial),
            &test_opts(),
            &CAPParams::defaults(0.5),
        )?;

        assert_eq!(outcome.len(), 3);

        // Whichever curve was held static keeps its starting pose, and the others come into
        // agreement with it. Every pair of curves should end up coincident, which is the same
        // thing as every relative transform being the identity.
        let t: Vec<Iso2> = (0..3)
            .map(|i| *outcome.alignment(i).full_transform())
            .collect();
        for i in 0..3 {
            for j in 0..3 {
                assert_relative_eq!(
                    t[i].inv_mul(&t[j]).to_matrix(),
                    Iso2::identity().to_matrix(),
                    epsilon = 1e-5
                );
            }
        }

        Ok(())
    }

    #[test]
    fn the_static_curve_is_the_one_the_others_reference_most() {
        // Three curves in a row, overlapping only with their neighbors: the middle one is seen by
        // both of the others and is the only sensible frame to express the result in.
        //
        // Each is a straight open segment, so the ends are the only thing that can disqualify a
        // sample and the counts reflect overlap rather than shape.
        let left = segment_curve(0.0, 6.0);
        let middle = segment_curve(4.0, 12.0);
        let right = segment_curve(10.0, 16.0);

        let curves = [left, middle, right];
        let initial = [Iso2::identity(); 3];
        let groups = groups_of_one(&curves);

        let order = reference_priority(
            &groups,
            &initial,
            &CAPParams::new(0.25, PI / 3.0, 0.25, None),
        )
        .unwrap();

        assert_eq!(order[0], 1, "the middle curve should be the static one");
    }

    #[test]
    fn a_correspondence_matrix_is_symmetric_and_empty_on_the_diagonal() {
        let curves = [
            segment_curve(0.0, 6.0),
            segment_curve(4.0, 12.0),
            segment_curve(20.0, 26.0),
        ];
        let initial = [Iso2::identity(); 3];
        let groups = groups_of_one(&curves);

        let m = correspondence_matrix(
            &groups,
            &initial,
            &CAPParams::new(0.25, PI / 3.0, 0.25, None),
        )
        .unwrap();

        for i in 0..3 {
            assert_eq!(m[(i, i)], 0.0);
            for j in 0..3 {
                assert_eq!(m[(i, j)], m[(j, i)]);
            }
        }

        // The first two overlap, the third is off on its own.
        assert!(m[(0, 1)] > 0.0);
        assert_eq!(m[(0, 2)], 0.0);
        assert_eq!(m[(1, 2)], 0.0);
    }

    #[test]
    fn fewer_than_two_curves_is_rejected() {
        let curves = vec![rect_curve()];
        let initial = vec![Iso2::identity()];
        let groups = groups_of_one(&curves);

        let err = multi_curve_adjustment(
            &groups,
            Some(&initial),
            &test_opts(),
            &CAPParams::defaults(0.5),
        )
        .unwrap_err()
        .to_string();
        assert!(
            err.contains("at least two bodies"),
            "unexpected message: {err}"
        );

        let empty: Vec<CurveGroup2> = Vec::new();
        assert!(
            multi_curve_adjustment(&empty, None, &test_opts(), &CAPParams::defaults(0.5)).is_err()
        );
    }

    // ============================================================================================
    // Multi-member bodies
    // ============================================================================================

    #[test]
    fn a_two_member_body_recovers_a_motion_neither_member_could() -> Result<()> {
        // The point of a body being a group: its members constrain the pose together.
        //
        // A straight segment is blind to sliding along its own direction, and no amount of
        // discretization changes that, so a body made only of a horizontal segment cannot see an
        // x displacement. Add a vertical member and the pair sees both axes. The same disturbance
        // is put to each, and the assertion is the contrast.
        let disturb = small_disturbance(0.1, 0.08, 0.0);

        let leftover_x = |groups: &[CurveGroup2]| -> Result<f64> {
            let initial = vec![Iso2::identity(), disturb];
            let outcome = multi_curve_adjustment(
                groups,
                Some(&initial),
                &test_opts(),
                &CAPParams::defaults(0.5),
            )?;
            // Body 0 is static, so body 1 carries whatever displacement survived.
            Ok(outcome
                .alignment(1)
                .full_transform()
                .translation
                .vector
                .x
                .abs())
        };

        let cross = || {
            CurveGroup2::new(vec![
                segment_curve(-6.0, 6.0),
                vertical_segment(10.0, -6.0, 6.0),
            ])
            .unwrap()
        };
        let pair = vec![cross(), cross()];
        let lone = vec![
            CurveGroup2::from(segment_curve(-6.0, 6.0)),
            CurveGroup2::from(segment_curve(-6.0, 6.0)),
        ];

        let with_two = leftover_x(&pair)?;
        let with_one = leftover_x(&lone)?;

        assert!(
            with_two < 1e-5,
            "the two member body should have taken the x displacement out, \
             but {with_two} was left"
        );
        assert!(
            with_one > 0.5 * 0.1,
            "a lone horizontal segment cannot see an x displacement, so most of the 0.1 \
             should survive, but only {with_one} did"
        );

        Ok(())
    }

    #[test]
    fn both_members_of_a_body_are_brought_onto_their_twins() -> Result<()> {
        // Recovery stated geometrically rather than through the transform: every member of the
        // moved body ends up back on the matching member of the static one, and none of them
        // drifts onto a different member's twin.
        //
        // Note what this does not test. One transform moves the whole body, so the members cannot
        // disagree about where they went, and a solve driven by only one of them would still land
        // the rest correctly. The member coverage question is asked by
        // `a_two_member_body_recovers_a_motion_neither_member_could` and by the sampler's own
        // tests; what is checked here is that a body with several members comes back as a whole
        // and that member identity survives the round trip.
        let groups = vec![two_circle_body(), two_circle_body()];
        let disturb = small_disturbance(0.08, 0.06, -0.015);
        let initial = vec![Iso2::identity(), disturb];

        let outcome = multi_curve_adjustment(
            &groups,
            Some(&initial),
            &test_opts(),
            &CAPParams::defaults(0.25),
        )?;

        let t = outcome.alignment(1).full_transform();
        for (i, member) in groups[1].curves().iter().enumerate() {
            let moved = member.new_transformed_by(t);
            for p in moved.points() {
                let (m, station) = groups[0].at_closest_to_point(p);
                assert_eq!(m, i, "member {i} drifted onto member {m} of the reference");
                assert!(
                    dist(p, &station.point()) < 1e-4,
                    "member {i} did not settle back onto its twin"
                );
            }
        }

        Ok(())
    }

    #[test]
    fn a_body_may_mix_open_and_closed_members() -> Result<()> {
        // Sections produce closed loops and unclosed strands in the same cut, so a body has to
        // tolerate both at once. The open member's ends are the part that needs care: a
        // projection past one clamps, and the sampler is what keeps those out.
        let body = || CurveGroup2::new(vec![rect_curve(), segment_curve(-4.0, 4.0)]).unwrap();
        let groups = vec![body(), body()];
        let disturb = small_disturbance(0.05, 0.04, 0.01);
        let initial = vec![Iso2::identity(), disturb];

        // Both members must actually contribute, or this is only testing the rectangle.
        let samples =
            generate_alignment_points(&groups[1], &groups[0], &disturb, &CAPParams::defaults(0.5));
        assert!(samples.iter().any(|cp| cp.member == 0));
        assert!(samples.iter().any(|cp| cp.member == 1));

        let outcome = multi_curve_adjustment(
            &groups,
            Some(&initial),
            &test_opts(),
            &CAPParams::defaults(0.5),
        )?;

        assert_relative_eq!(
            outcome.alignment(1).full_transform().to_matrix(),
            Iso2::identity().to_matrix(),
            epsilon = 1e-5
        );

        Ok(())
    }

    #[test]
    fn stress_two_member_bodies_recover_small_disturbances() -> Result<()> {
        // Seeded, so a failure is reproducible and this can never join the flaky-by-RNG set.
        let mut rg = RandomGeometry2::from_seed(0x9a1_c0de);

        for _ in 0..20 {
            let groups = vec![two_circle_body(), two_circle_body()];
            let disturb = small_disturbance(rg.f64_sym(0.1), rg.f64_sym(0.1), rg.f64_sym(0.02));
            let initial = vec![Iso2::identity(), disturb];

            let outcome = multi_curve_adjustment(
                &groups,
                Some(&initial),
                &test_opts(),
                &CAPParams::defaults(0.25),
            )?;

            assert_relative_eq!(
                outcome.alignment(1).full_transform().to_matrix(),
                Iso2::identity().to_matrix(),
                epsilon = 1e-4
            );
        }

        Ok(())
    }

    #[test]
    fn static_selection_counts_a_multi_member_body_across_its_members() {
        // Two lone segments which do not reach each other, plus a two member body with one
        // member over each of them. Only the two member body sees both, so it is the one frame
        // the others can be expressed in, and that has to be found by pooling its members.
        let groups = vec![
            CurveGroup2::from(segment_curve(0.0, 6.0)),
            CurveGroup2::from(segment_curve(20.0, 26.0)),
            CurveGroup2::new(vec![segment_curve(1.0, 5.0), segment_curve(21.0, 25.0)]).unwrap(),
        ];
        let poses = [Iso2::identity(); 3];

        let order =
            reference_priority(&groups, &poses, &CAPParams::new(0.25, PI / 3.0, 0.25, None))
                .unwrap();

        assert_eq!(order[0], 2, "the two member body should be the static one");
    }
}