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
//! The 5-point similarity alignment to the ArcFace 112×112 template.
//!
//! **Alignment lives OUTSIDE the embedder on purpose.** The embedder is then a
//! pure function of an [`AlignedFace`], and the template — the thing every
//! downstream cosine is measured through — is an explicit value with a golden
//! of its own rather than a private preprocessing step nobody can test in
//! isolation. A wrong transform does not fail; it degrades silently, moving
//! every embedding by an amount no shape check can see.
//!
//! # What is being reproduced
//!
//! deepinsight/insightface, `python-package/insightface/utils/face_align.py`,
//! pinned at commit `ffa12d315041c0505b077c7ff057ca914bb8dc7e` (2022-12-17):
//!
//! ```text
//! arcface_dst = np.array(
//! [[38.2946, 51.6963], [73.5318, 51.5014], [56.0252, 71.7366],
//! [41.5493, 92.3655], [70.7299, 92.2041]], dtype=np.float32)
//!
//! tform = trans.SimilarityTransform()
//! tform.estimate(lmk, dst)
//! M = tform.params[0:2, :]
//! warped = cv2.warpAffine(img, M, (112, 112), borderValue=0.0)
//! ```
//!
//! `estimate` is `skimage`'s Umeyama least-squares similarity, and
//! `cv2.warpAffine` without `WARP_INVERSE_MAP` **inverts** `M` itself and
//! samples the source at the inverse-mapped destination pixel centre,
//! `INTER_LINEAR`, constant-0 border. [`FaceAlign::to_template`] is that
//! pipeline in the same order.
//!
//! **The two halves are reproduced to different standards, and the difference
//! is measured rather than assumed.** The warp is bit-exact with OpenCV 4.x
//! given a matrix. The solve is not bit-exact with `skimage`, and the section
//! below measures both how far apart they are and — the part that decides
//! what may be claimed — how far the reference is from ITSELF.
//!
//! # The resampler is BIT-EXACT with `cv2.warpAffine`, and that is the contract
//!
//! `INTER_LINEAR` is **not** a float bilinear kernel. For an 8-bit image
//! OpenCV quantises the inverse-mapped coordinate to a five-bit fraction
//! (`INTER_BITS = 5`) and interpolates with 15-bit fixed-point weights, so a
//! true fraction below the half-step `1/64` collapses to **zero** and the tap
//! is the pure left pixel. On a 0-to-255 edge that is the difference between
//! `0` and `255/64 ≈ 4` — two thirds of a level short of `4` is not a rounding
//! difference, it is a different pixel.
//!
//! An earlier revision of this module resampled in `f64` and recorded the
//! divergence as "at most one LSB per channel". **That was a measurement on
//! one fixture stated as a bound over the domain, and it is false.** Measured
//! against `cv2.warpAffine` over ArcFace-shaped warps of random crops
//! (`opencv-python-headless` 4.12.0, 451 584 bytes): **11.6 % of bytes differ
//! and the worst differs by 6 levels.** Every published ArcFace accuracy
//! number is measured against crops `cv2.warpAffine` produced, so this module
//! reproduces OpenCV's fixed-point pipeline exactly rather than approximating
//! it. The sampler's constants are each named after the OpenCV symbol they
//! come from (`INTER_BITS`, `AB_SCALE`, `INTER_REMAP_COEF_BITS`, …), so the
//! pipeline can be read against `imgproc/src/imgwarp.cpp` line by line.
//!
//! **Which OpenCV — the version is part of the contract.** The 4.x line, which
//! is what InsightFace's pinned `face_align.py` runs against and what every
//! published number was measured on. OpenCV **5.0 replaced the fixed-point
//! path with a float one**: on the same warps it tracks an unquantised `f64`
//! sampler (one differing byte in 73 728, an exact-tie rounding) and so
//! differs from 4.x on the same 11.6 % of bytes. "Bit-exact with OpenCV" is
//! therefore version-bearing, and it is pinned here to **4.x** deliberately.
//!
//! # The SOLVE is not bit-exact with `skimage`, and there is no single
//! # `skimage` to be exact against
//!
//! The resampler above reproduces `cv2.warpAffine` exactly **given a matrix**.
//! Which matrix is a separate question, and the honest answer is that the
//! reference has no single one to reproduce.
//!
//! `skimage`'s `_umeyama` (`skimage/transform/_geometric.py` v0.19.3, L107-149)
//! keeps its **`f32`** input through the centroids, the covariance and the SVD,
//! storing only the result as `f64`. This module promotes to `f64` first. Same
//! minimiser, different numbers — and the difference is large enough to move a
//! five-bit source coordinate. On the landmarks
//!
//! ```text
//! [[48.073643, 97.0597], [103.45303, 115.63326], [68.99921, 127.54772],
//! [37.211536, 152.98666], [82.01403, 169.19621]]
//! ```
//!
//! **10 of the 12 544 destination pixels** take a different five-bit source
//! coordinate than `skimage` gives under numpy 2.5.1 / OpenBLAS 0.3.33.
//!
//! That much is a real divergence. What makes it unclosable is the next
//! measurement. `_umeyama`'s `f32` path is two library calls — a `sgemm` for
//! the covariance and a `sgesdd` for the 2×2 SVD — and neither is specified
//! beyond returning *a* correct answer. Running the identical `_umeyama`
//! source, same machine, same landmarks, under two BLAS/LAPACK builds (numpy's
//! OpenBLAS 0.3.33 and Apple's Accelerate):
//!
//! - the `f32` covariance differs on **16 618 of 20 000** face-like landmark
//! sets. OpenBLAS's aarch64 `sgemm` contracts its multiply-adds into `fma`:
//! an `fma` chain reproduces it on 3 000 of 3 000 random inputs and a
//! non-fused chain on 341. Whether a kernel contracts is a build flag, not a
//! specification;
//! - the `f32` `sgesdd` differs on its singular values on 13 657 of 20 000,
//! and on the rotation `U @ V` that `_umeyama` actually uses on all 20 000;
//! - end to end, **on the witness above the two builds differ from each other
//! on 15 destination pixels** — more than either differs from this module —
//! and over 20 000 face-like sets on a mean of 14.8 (median 11, worst 212).
//!
//! So "bit-exact with `skimage`" is not a property of `skimage`. It is a
//! property of `skimage` *and the BLAS the measuring machine happened to
//! link*, and picking one build to be exact against would be picking one of
//! several equally correct references while presenting it as having removed a
//! choice.
//!
//! A structural obstruction sits on top of the numeric one:
//! [`SimilarityTransform`] cannot hold a shear by construction, and under
//! Accelerate **19 624 of those same 20 000** `_umeyama` results are not
//! exactly similarities — `a ≠ d` or `b ≠ −c` in the last bits, because a
//! `f32` `U @ V` is only approximately orthogonal. (Under OpenBLAS, 0 of
//! 20 000, which is itself the point: the property is the build's, not the
//! reference's.) The reference's own output is routinely not a value this type
//! can represent.
//!
//! **What this module claims, therefore, and nothing more:** the transform is
//! the least-squares similarity minimiser of the `f32` landmarks, evaluated in
//! `f64` (not exactly — `f64` rounds too; it is `f64`-accurate where the
//! reference is `f32`-accurate), and the resampler is bit-exact with
//! `cv2.warpAffine`
//! 4.x given that transform. It sits 10 five-bit coordinates from one
//! reference build and 5 from another, inside a 15-wide band the reference
//! occupies on its own.
//! `the_solve_diverges_from_skimage_by_less_than_skimage_diverges_from_itself`
//! pins all three numbers, so an attempt to close the gap toward one build has
//! to confront the gap that cannot be closed.
//!
//! Regenerate every number above with
//! `python3 conversion/face/align_oracle.py --reference-divergence --sweep 20000`
//! (about ten seconds; without `--sweep` it prints the matrices and the three
//! witness counts alone). Deciding
//! it on accuracy instead of on bit-exactness needs a number this branch
//! cannot produce — the embedding drift the divergence causes, measured
//! against a staged artifact, and there is none (see the
//! [`crate::embeddings::face`] module doc). So it is recorded rather than
//! traded away.
//!
//! # The transform is solved without an SVD
//!
//! Umeyama's construction is stated with an SVD, but in 2-D **without
//! reflection** — which is what an alignment is; a mirrored face is not the
//! same face — the minimiser has a closed form. Writing the scaled rotation as
//! `[[a, −b], [b, a]]` makes the residual linear in `(a, b, tx, ty)`, so the
//! least-squares solution is a pair of dot products over the centred point
//! sets. See [`SimilarityTransform::estimate`].
//!
//! The evidence that this is the right minimiser deliberately does **not** rest
//! on agreeing with a second copy of the same derivation. Three independent
//! legs, in `tests.rs` and `tests/face/align_golden.rs`:
//!
//! - `recovered_transform_is_the_least_squares_minimiser` perturbs the solved
//! parameters in all four directions and asserts the residual **rises** —
//! an optimality proof that names no formula at all;
//! - `exact_similarity_landmarks_recover_the_analytic_inverse` feeds landmarks
//! that are an exact similarity image of the template and asserts the
//! recovered scale and rotation are the constructed ones inverted;
//! - the committed golden compares 112×112×3 bytes against
//! `conversion/face/align_oracle.py`, which solves the same minimiser
//! through a different derivation.
//!
//! All three legs are about the minimiser, not about `skimage`'s `f32`
//! evaluation of it; the section above is what covers that.
//!
//! The golden's THIRD leg covers the solve only. Since the resampler became
//! bit-exact, the oracle reproduces the same OpenCV specification this module
//! does, so their byte agreement catches a transcription slip on either side
//! and is not independent evidence about the pipeline. What carries that is
//! `a_fraction_below_the_five_bit_half_step_takes_the_pure_left_pixel`, which
//! pins the one behaviour separating the fixed-point pipeline from a float
//! one, plus `cv_round_breaks_ties_to_even_and_refuses_what_leaves_int` and
//! `the_fixed_point_pixel_cast_rounds_half_up_and_saturates` for the two tie
//! rules that no whole-image comparison can see.
//!
//! # The coordinate pipeline is TOTAL, and where it is not it says so
//!
//! Everything between the solved transform and a sampled byte rounds, casts,
//! clamps or accumulates, and each of those is a place an answer can be
//! invented. Two rounds of review found one invented answer each — an `i16`
//! tap that aliased a real column onto a saturated one, then two `i32` terms
//! that saturated in opposite directions and CANCELLED into a small,
//! plausible coordinate — and both were first met by bounding the input.
//! Bounding the input is an argument about every future caller; it does not
//! make the operation total, it makes it safe for the inputs someone thought
//! of. So the operation is fallible instead:
//!
//! - `cv_round` returns `Option<i32>` rather than saturating. OpenCV's
//! `saturate_cast<int>(double)` is UNDEFINED past `int`, so there is no
//! reference answer to reproduce there — only a domain to stay inside;
//! - the `round_delta` fold and the per-row/per-column SUM are checked
//! additions, the sum for all 112² pairs at once by an extremes argument
//! (`check_sum_domain`);
//! - the whole map is built and validated in `SourceGrid::new` BEFORE the
//! first pixel is sampled, so a transform outside the domain produces
//! [`Error::CoordinateOverflow`] rather than a partially warped face;
//! - the source tap is written EXACTLY rather than saturated into `i16`,
//! which agrees with the reference on every crop the reference admits and
//! is total on the ones it does not.
//!
//! **[`SimilarityTransform::inverse`] is total a different way, and the
//! difference is the point.** Everything above is an operation made fallible
//! because its input set is open. The inverse's is not, because it is closed
//! at the PRODUCER: a [`SimilarityTransform`] exists only as a value
//! [`SimilarityTransform::estimate`] returned or as the inverse of one, and
//! both of those doors check the same thing. So the inverse computes
//! `cv2.warpAffine`'s own expression on every value the type can hold, with no
//! second association anywhere, and `None` outside that band is a declaration
//! that the inverse is undefined there rather than an attempt to rescue one.
//! Each earlier round instead widened the predicate and was met by the next
//! value outside the new enumeration.
//!
//! **That band was published as a THEOREM about `f32` inputs, and the theorem
//! was false.** Review round 5 on #135 produced five finite `f32` landmarks
//! whose minimiser is `a = 6.1e-168` — nonzero, and with a perfectly finite
//! `1/a = 1.6e167` — and whose `a² + b²` underflows `f64` to exactly zero, so
//! `estimate` returned `Ok` on a transform `inverse` then refused. The
//! lower-bound argument behind the claim ("a nonzero λ is at least one `f32`
//! ulp of the perturbed coordinate over `Σ‖uᵢ‖²`") does not survive a
//! numerator that is a product of two subnormal-scale deviations while the
//! denominator is near `f32::MAX²`, and the 860 810-set sweep that measured the
//! claim never visited that corner.
//!
//! So the band is **enforced rather than argued**: both producers evaluate the
//! predicate — the same function, not a second spelling of it — and refuse,
//! naming the scale. Refusing is also strictly better than the reference,
//! which computes `D = a·a + b·b = 0` here and warps on with a matrix that
//! maps every pixel to one point.
//!
//! # The postcondition is over the CLOSURE, and the enumeration is gone
//!
//! Round 5's cure enforced the band on what `estimate` returns, and round 6
//! found the half it left open. `inverse` is a PRODUCER too, and the value it
//! constructed was checked only for finiteness — so it could hand back a
//! transform whose own `a² + b²` is outside the band, and the sentence "every
//! transform this type holds inverts on the reference path" was false for
//! values `inverse` itself produced. The witness is public:
//! `estimate_refuses_a_solve_whose_inverse_does_not_invert` feeds ten finite
//! `f32` landmarks whose minimiser has `a = b` and `a² + b² = 0x1p-1022`
//! EXACTLY — the smallest normal `f64`, admitted by the band with a normal
//! reciprocal — and whose inverse's determinant lands one ulp ABOVE
//! `0x1p+1022`, where the reciprocal is subnormal. `estimate` was `Ok`,
//! `t.inverse()` was `Some`, and `t.inverse().unwrap().inverse()` was `None`.
//!
//! The mechanism is subnormal precision, and it is worth stating because it is
//! why no wider band would have helped: `a²` and `b²` are each subnormal
//! (`0x1p-1023`), so each has already lost a bit to the subnormal grid before
//! they are added, while the INVERSE's squares are formed in the normal range
//! at full precision. `D` and `D'` are therefore not exact reciprocals, and no
//! interval of `f64` is exactly closed under `D ↦ 1/D` with rounding.
//!
//! The cure is not a wider band — that is the enumeration this module keeps
//! being met by. It is that **both producers enforce the postcondition, and
//! the postcondition is over the closure**: [`SimilarityTransform::inverse`]
//! routes its candidate through the same band, so no value of this type has an
//! out-of-band determinant; and [`SimilarityTransform::estimate`] computes the
//! inverse and requires THAT to invert too, so a transform it returns has an
//! inverse, and that inverse has an inverse, by construction rather than by
//! measurement.
//!
//! **Both levels are load-bearing, and each has a public witness.** The one
//! above is refused by the first level alone. The second level has its own —
//! `estimate_refuses_a_solve_whose_inverses_inverse_does_not_invert`, whose
//! determinant is one ulp above `0x1p-1022` and whose INVERSE's determinant is
//! `0x1p+1022` exactly, both inside the band, with only the third subnormal.
//! A postcondition that asked `t.inverse().is_some()` and stopped returns `Ok`
//! there, and `t.inverse().unwrap().inverse()` is `None` — the round-6
//! sentence again, one level further out. Removing either level reds a
//! different gate.
//!
//! **Where the claim stops, stated rather than implied.** It is two levels,
//! not an unbounded chain, and that is a fact about IEEE arithmetic rather
//! than a choice: since no band is exactly closed under reciprocation, some
//! k-th iterate of `inverse` on a determinant sitting at a band edge is
//! `None` for every band, and the two witnesses above are k = 1 and k = 2 of
//! exactly that family. Iterating `inverse` past the second call is therefore
//! not claimed total; what is claimed is that a refusal there is a refusal,
//! never a wrong matrix, and that [`FaceAlign::to_template`] — which inverts
//! once — is inside the guarantee with a level to spare.
//! [`SimilarityTransform::estimate`] carries the postcondition,
//! [`SimilarityTransform::inverse`] the arithmetic and what remains measured
//! about it.
//!
//! What remains a clamp is `fixed_point_to_u8`'s saturation into `u8`, which
//! is OpenCV's `FixedPtCast` and is unreachable for a `u8` source (the four
//! 15-bit weights sum to exactly `1 << 15`, so the accumulator cannot leave
//! `0..=255` after the shift); and [`MAX_CROP_AXIS`], which is now purely the
//! reference's own `CV_Assert` and no longer stands between an aliased tap
//! and a wrong pixel.
use crate;
/// The number of landmarks the ArcFace family aligns on.
pub const LANDMARK_COUNT: usize = 5;
/// The ArcFace template's side, in pixels.
pub const TEMPLATE_SIZE: usize = 112;
/// Bytes in one [`AlignedFace`]: `112 · 112 · 3`, RGB8 interleaved.
pub const TEMPLATE_BYTES: usize = TEMPLATE_SIZE * TEMPLATE_SIZE * 3;
/// The largest crop axis [`FaceCrop::new`] admits: one short of `i16::MAX`.
///
/// **This is the REFERENCE's admitted geometry, and nothing here depends on it
/// for safety.** OpenCV 4.x's `remap` — the fixed-point pipeline `warpAffine`
/// funnels into — opens with `CV_Assert( dst.cols < SHRT_MAX && dst.rows <
/// SHRT_MAX && src.cols < SHRT_MAX && src.rows < SHRT_MAX )`, so a wider crop
/// is a shape the reference declines to define. This module's contract is to be
/// bit-exact with `cv2.warpAffine` (see the module doc); admitting geometry the
/// reference refuses would mean claiming exactness against an answer that does
/// not exist.
///
/// **It used to be load-bearing, and that is worth recording rather than
/// quietly dropping.** The sampler once saturated each integer source tap into
/// `i16` — OpenCV's own `saturate_cast<short>` on the `short XY[]` its
/// `WarpAffineInvoker` fills — and decided the constant-0 border by comparing
/// the SATURATED tap against the crop's extent. That comparison is right only
/// while the saturation value is not a coordinate the crop actually has, which
/// this bound was introduced to guarantee. Guaranteeing it is not the same as
/// removing it: the tap is now written exactly (`sample_fixed_point`), so a
/// coordinate outside the crop reads the border at any crop width, and the
/// bound no longer stands between an aliased tap and a wrong pixel.
/// `the_tap_is_exact_rather_than_saturated_into_the_crop` measures both forms
/// on the geometry that separates them.
///
/// **Why `i16::MAX − 1` and not `i16::MAX`.** OpenCV's bound is strictly less
/// than `SHRT_MAX`, so this takes the same one: the admitted set is exactly the
/// reference's and the two cannot disagree about a crop at the boundary. One
/// pixel of conservatism, chosen to keep a second number from existing.
pub const MAX_CROP_AXIS: usize = i16MAX as usize - 1;
/// One 2-D point in a crop's pixel coordinates, pixel centres on integers.
///
/// `f32` because that is what a detector emits. The solve then promotes to
/// `f64`, where `skimage`'s stays in `f32` — a divergence the module doc
/// measures rather than waves at.
/// The ArcFace 112×112 destination template, in the landmark order the whole
/// family uses: **left eye, right eye, nose tip, left mouth corner, right mouth
/// corner**.
///
/// Left and right are the VIEWER's, matching the upstream array — the first
/// entry has the smaller `x`. Passing the subject's own left/right instead
/// mirrors every face and is invisible to every check but the cosine.
///
/// Verbatim from the pinned `face_align.py` (see the module doc), `f32` because
/// upstream declares `dtype=np.float32`.
pub const ARCFACE_TEMPLATE: = ;
/// A 2-D similarity transform `p ↦ [[a, −b], [b, a]] · p + t`, in the
/// source → template direction.
///
/// The rotation-and-uniform-scale block is stored as the two free parameters
/// `(a, b)` rather than a general 2×2, so a value of this type **cannot**
/// represent a shear, a non-uniform scale, or a reflection. That is the point:
/// the alignment contract is a similarity, and making the type unable to hold
/// anything else removes a whole class of silent corruption.
///
/// # There is exactly one door
///
/// ```compile_fail,E0624
/// use coremlit::embeddings::face::SimilarityTransform;
/// // `new` is private. `estimate` is the only producer, and `inverse` the
/// // only other way a value of this type comes into existence.
/// let _ = SimilarityTransform::new(1.0, 0.0, 0.0, 0.0);
/// ```
/// The rotation block of `[[a, −b], [b, a]]⁻¹` — the complex reciprocal
/// `1/(a + bi)`, returned as `(re, im)`.
///
/// `cv2.warpAffine`'s own `D = a·a + b·b; D = 1./D;` and nothing else, in the
/// reference's operation order, guarded by [`reciprocal_determinant`] — the
/// band both quantities are normal in, about `1.5e-154` to `6.7e153` in scale.
/// [`SimilarityTransform::estimate`] applies that same guard as a
/// postcondition, so this one refuses nothing the public surface can hand it.
///
/// **One expression, no fallback.** A second association for the out-of-band
/// case was tried (Smith's scaling, `max + min·(min/max)`) and is the shape
/// this module is done with: it existed only to serve a public unvalidated
/// constructor, it overflowed on its own at `a = b = f64::MAX` and returned a
/// zero transform as an "inverse", and where it ran at all the reference had
/// already left `f64` and there was no answer to be exact against. Outside the
/// band the inverse is undefined by declaration.
///
/// Both arguments are finite by [`SimilarityTransform::inverse`]'s entry
/// guard; a non-finite one would fail the band test here regardless.
/// `cv2.warpAffine`'s `D = a·a + b·b; D = 1./D;`, or `None` where either
/// quantity is not normal.
///
/// **The single definition of "this rotation inverts", and it has THREE
/// callers on purpose.** [`SimilarityTransform::estimate`] evaluates it as a
/// postcondition before returning; [`inverse_rotation`] evaluates it as the
/// precondition of the arithmetic it is about to run; and
/// [`SimilarityTransform::inverse`] evaluates it on the value it is about to
/// CONSTRUCT, which is what keeps the type's invariant true of everything
/// either producer hands out. All three have to be the same question — a
/// producer that admits a value its own inverse refuses is exactly the defect
/// review rounds 5 and 6 on #135 found, on the two different producers — so
/// they are one function rather than three spellings that agree today.
///
/// Both halves of the test are load-bearing, and neither implies the other:
///
/// - `determinant.is_normal()` rejects the ZERO the reference divides by
/// (`a = b = 0`, and the underflow witness in `estimate`'s doc), and it
/// rejects a SUBNORMAL determinant, which `> 0.0` would admit — `1e-309` is
/// nonzero and its reciprocal is still `∞`;
/// - `reciprocal.is_normal()` rejects the other end, where `D` is finite and
/// normal but `1/D` has flushed to zero or a subnormal.
///
/// A non-finite `a` or `b` fails it too: `a·a + b·b` is then NaN or infinite,
/// and neither is normal.
/// Rejects a NaN or infinite coordinate in one NAMED point set, so the error
/// says which of [`SimilarityTransform::estimate`]'s two sides failed.
/// The centroid of five landmarks, in `f64`.
/// A borrowed view of one decoded RGB8 face crop: `width · height · 3`
/// row-major, RGB-interleaved bytes.
///
/// The sans-I/O seam — decoding PNG/JPEG and cropping to the detector's box is
/// the caller's job, exactly as `clap` takes resampled 48 kHz audio and
/// `siglip` takes a decoded [`crate::embeddings::siglip::Rgb8Image`]. This
/// module deliberately keeps its own view type rather than reaching into
/// `siglip`: the `face` feature must not pull the `siglip` feature's
/// dependencies in to name a slice and two integers.
///
/// The landmarks passed alongside are in **this crop's** coordinates, not the
/// original frame's.
/// One face warped onto the ArcFace 112×112 template: `112 · 112 · 3` RGB8
/// bytes, row-major and interleaved, plus the transform that produced them.
///
/// This is the embedder's ONLY input. Its pixels are still raw 0–255 bytes —
/// channel order, scale and bias belong to the model manifest
/// ([`crate::embeddings::face::Preprocessing`]), not to the alignment and not
/// to the caller.
/// The 5-point similarity alignment onto the ArcFace 112×112 template.
///
/// A unit type rather than a free function so the template it targets is named
/// at every call site.
;
/// OpenCV's `INTER_BITS`: the inverse-mapped source coordinate keeps five
/// fractional bits, so its interpolation weight is drawn from a 32-step table
/// and a true fraction under `1/64` quantises to zero.
const INTER_BITS: u32 = 5;
/// OpenCV's `INTER_TAB_SIZE`, `1 << INTER_BITS`.
const INTER_TAB_SIZE: i64 = 1 << INTER_BITS;
/// OpenCV's `AB_BITS`, `MAX(10, INTER_BITS)`: the precision the per-row and
/// per-column halves of the mapped coordinate are rounded to BEFORE they are
/// added together.
const AB_BITS: u32 = 10;
/// OpenCV's `AB_SCALE`, `1 << AB_BITS`.
const AB_SCALE: f64 = as f64;
/// OpenCV's `round_delta` for a non-nearest interpolation,
/// `AB_SCALE / INTER_TAB_SIZE / 2` — the half-step folded in so that the
/// truncating shift down to the five-bit grid becomes a round-to-nearest.
const ROUND_DELTA: i32 = / / 2;
/// OpenCV's `INTER_REMAP_COEF_BITS`: the four interpolation weights are
/// 15-bit fixed point and sum to exactly `1 << 15`.
const REMAP_COEF_BITS: u32 = 15;
/// OpenCV's `cvRound`, which is `lrint` under the default rounding mode:
/// nearest, **ties to even** — not the half-up rounding used for pixels.
///
/// `None` outside `int`, rather than a saturated value, and that is the whole
/// point of the signature. OpenCV reaches this through
/// `saturate_cast<int>(double)`, which is *undefined* past `int`'s range: there
/// is no reference answer to reproduce, only a domain to stay inside. Rust has
/// to define something, and the two definitions on offer are not equally safe.
///
/// **Saturating was tried and is wrong.** The coordinate is SPLIT — a per-column
/// term and a per-row term, each rounded on its own, then added — so two
/// saturated terms can cancel: `i32::MIN + 16` plus `i32::MAX` is `15`, which
/// after the shift onto the five-bit grid is source pixel `0`. A destination
/// pixel whose true source is 1.9 billion columns outside the crop then reads
/// the crop's own first pixel and reports nothing. Refusing the term instead
/// makes the map total, because a term that has no answer cannot cancel against
/// another that has none either.
/// [`cv_round`] with the domain failure NAMED, so a refusal can say which term
/// of which coordinate left `int`.
/// `cv2.warpAffine(crop, M, (112, 112), flags=INTER_LINEAR,
/// borderMode=BORDER_CONSTANT, borderValue=0)`, given `M⁻¹`.
///
/// Destination-driven, and **fixed point throughout** — see the module doc for
/// why a float bilinear kernel is a different function and not a rounding of
/// this one. The structure mirrors `imgwarp.cpp`'s `WarpAffineInvoker`: the
/// per-destination-column contribution is rounded to `1/AB_SCALE` of a pixel
/// once (`adelta`/`bdelta`), the per-row half likewise, and only then are the
/// two added and dropped to the five-bit grid. That intermediate rounding is
/// part of the answer, so it is reproduced rather than folded into a single
/// expression: `cvRound(a·u·1024) + cvRound(m·v·1024)` is not
/// `cvRound((a·u + m·v)·1024)`.
///
/// # Errors
/// [`Error::CoordinateOverflow`] if any term of the destination → source map,
/// or the sum of two of them, leaves the `int` domain OpenCV computes it in.
/// The whole map is built and checked BEFORE the first sample, so this is a
/// refusal rather than a template warped from some pixels and not others.
/// The destination → five-bit source coordinate map `cv2.warpAffine` walks,
/// for one ALREADY-INVERTED 2×3 matrix.
///
/// Split out of [`warp_bilinear`] for two reasons. It names the intermediate
/// rounding that is part of the answer — the per-column and per-row halves are
/// each rounded to `1/AB_SCALE` before they are added, so
/// `cvRound(a·u·1024) + cvRound(m·v·1024)` is not `cvRound((a·u + m·v)·1024)`.
/// And it lets two matrices be compared on the coordinates themselves rather
/// than on pixels, which is what
/// `the_solve_diverges_from_skimage_by_less_than_skimage_diverges_from_itself`
/// needs: a moved coordinate leaves the output unchanged wherever the
/// neighbourhood it lands in happens to be flat, so counting differing bytes
/// under-reports a moved map.
///
/// Takes a raw `[f64; 6]` rather than a [`SimilarityTransform`] because the
/// reference's own solved matrix usually is NOT a similarity — see the module
/// doc — and comparing against one means being able to walk one.
///
/// **Every term is `i32` and every one of them was checked before this value
/// existed**, which is what makes the map total. A `SourceGrid` cannot be
/// constructed for a transform whose coordinates leave `int`, so [`Self::at`]
/// is infallible for the same reason a `FaceCrop`'s indices are: the
/// constructor is the only door.
/// One row origin: [`cv_round`] plus OpenCV's `round_delta`, with BOTH steps
/// required to stay inside `int`.
///
/// The fold is checked separately because it is a real overflow site and not a
/// formality: the witness that motivated this whole path rounds to `i32::MAX`
/// and then adds 16.
/// Proves every one of the 112² sums `origin[v] + delta[u]` fits in the single
/// `int` OpenCV forms it in — with two checked additions rather than 12 544.
///
/// Addition is monotone in both arguments, so for every pair
/// `min(origin) + min(delta) ≤ origin[v] + delta[u] ≤ max(origin) + max(delta)`,
/// and `i32` is a contiguous interval: if both bounds are representable, so is
/// everything between them. Checking the two extreme pairs therefore covers
/// the whole grid, and it is why [`SourceGrid::at`] can be infallible.
///
/// # Errors
/// [`Error::CoordinateOverflow`] with [`CoordinateTerm::Sum`], carrying the
/// offending sum computed in `f64` where it does not overflow.
/// One destination pixel from a five-bit fixed-point source coordinate:
/// `remapBilinear`'s tap gather, weight table and output cast.
///
/// `x` and `y` are in units of `1/INTER_TAB_SIZE` of a source pixel. The high
/// bits are the integer tap and the low [`INTER_BITS`] are the fraction's table
/// index, which is how OpenCV splits them:
///
/// ```text
/// xy[k] = saturate_cast<short>(X >> INTER_BITS);
/// alpha = (Y & (INTER_TAB_SIZE-1))*INTER_TAB_SIZE + (X & (INTER_TAB_SIZE-1));
/// ```
/// `BilinearTab_i[fy·INTER_TAB_SIZE + fx]`, in tap order
/// `(0,0), (0,1), (1,0), (1,1)`.
///
/// The products of the two 1-D weights `(1 − i/32, i/32)` scaled by
/// `1 << INTER_REMAP_COEF_BITS`. Every entry is an exact integer and the four
/// sum to exactly `1 << 15`, which is what makes the fixed-point cast below
/// unbiased.
///
/// OpenCV's own table differs in ONE of its 1 024 cells: `initInterTab2D`
/// fills it with `saturate_cast<short>`, so the unit weight at fraction
/// `(0, 0)` saturates to 32 767 and the sum-fixing step that follows puts the
/// missing 1 on the opposite corner — `[32767, 0, 0, 1]` where this returns
/// `[32768, 0, 0, 0]`. For a `u8` source the two are the same function;
/// `the_saturating_weight_table_cell_is_invisible_for_u8_sources` proves that
/// exhaustively over the 65 536 tap pairs the difference can see, so the exact
/// form is used here rather than a transcription of an overflow.
/// The byte offset of the source tap at `(x, y)`, or `None` when it lies
/// outside the crop and reads the constant-0 border.
/// OpenCV's `FixedPtCast<int, uchar, INTER_REMAP_COEF_BITS>`: add half a unit,
/// shift down, saturate into `u8`.
///
/// Half-up on the fixed-point accumulator, which is NOT the same tie rule as
/// [`cv_round`]'s half-to-even on the coordinate; both are reproduced as
/// OpenCV has them.