openreadout-core 0.4.0

Core traits, normalized metadata model, provenance tags, JSON output and exit codes for OpenReadout
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
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
//! Counting objects: nuclei, cells or spots, with their sizes, intensities in every channel
//! and positions. The steps and their sources are in `segment.rs`; the definitions users see
//! are in `book/src/reference/commands/stats.md`, "Objects".

// x, y, w, h, c, k are the natural names in image arithmetic.
#![allow(clippy::many_single_char_names)]

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::segment as sg;
use super::{Grid, Spread, Target, inside, read, spread, usage};
use crate::error::{Error, Result};
use crate::model::ImageInfo;
use crate::region::Region;

/// Objects listed by default.
pub const DEFAULT_MAX_OBJECTS: usize = 100;
/// Below this `fit` a count has low confidence. On annotated nuclei (BBBC038) it marks most
/// brightfield smears, whose counts were several times too high, and few fluorescence images.
pub const LOW_FIT: f64 = 0.5;
/// Regions up to this many pixels (2896 × 2896) are counted in one piece.
const ONE_PIECE: u64 = 1 << 23;
/// Larger regions are counted in tiles this many pixels a side.
const TILE: u32 = 2048;
/// Most pixels an object count covers (an 8192 × 8192 region).
pub const MAX_OBJECT_PIXELS: u64 = 1 << 26;

/// What to count.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// nuclei (default): touching nuclei are split
    #[default]
    Nuclei,
    /// whole cells stained throughout (larger; touching cells are split)
    Cells,
    /// small bright spots (puncta, foci, single molecules), found by a Laplacian of Gaussian
    Spots,
}

/// Bright or dark objects.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Polarity {
    /// from the image: dark objects on a bright background (brightfield) or bright ones
    #[default]
    Auto,
    /// objects brighter than the background (fluorescence)
    Bright,
    /// objects darker than the background (brightfield)
    Dark,
}

/// How the threshold is chosen.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ThresholdMethod {
    /// Otsu's, or the triangle method when objects are sparse
    #[default]
    Auto,
    /// Otsu's (two classes of similar spread)
    Otsu,
    /// the triangle method (a big background peak, few objects)
    Triangle,
    /// each pixel against its neighbourhood (uneven staining)
    Local,
}

/// How far a count can be trusted.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum CountConfidence {
    /// the objects look like what was asked for
    #[default]
    High,
    /// many objects are irregular or of the wrong size: check a picture before quoting the count
    Low,
}

/// What an RGB image's objects are found in.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Stain {
    /// hematoxylin for brightfield (stained tissue); for fluorescence, blue for nuclei when the
    /// blue component holds signal, else the brightest component
    #[default]
    Auto,
    /// the nuclear stain of H&E and IHC, by colour deconvolution
    Hematoxylin,
    /// eosin, by colour deconvolution
    Eosin,
    /// the brown IHC chromogen, by colour deconvolution
    Dab,
    /// one component
    Red,
    /// one component
    Green,
    /// one component
    Blue,
    /// the mean of the components
    Luminance,
}

/// How objects are found. Everything is optional; the defaults suit nuclei.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ObjectsRequest {
    /// Default nuclei.
    #[serde(default)]
    pub kind: Kind,
    /// Expected object diameter in µm. Default: measured from the image (spots: 0.5 µm).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diameter_um: Option<f64>,
    /// The same in pixels, for images without a pixel size.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diameter_px: Option<f64>,
    /// Threshold in raw units of what is measured (spots: the height above the local
    /// background). Default: chosen by `method`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
    /// Default auto.
    #[serde(default)]
    pub method: ThresholdMethod,
    /// Default auto.
    #[serde(default)]
    pub polarity: Polarity,
    /// RGB images. Default auto.
    #[serde(default)]
    pub stain: Stain,
    /// Cut touching objects apart (seeded watershed). Default true.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub split: Option<bool>,
    /// Smallest object kept in µm². Default: a fifth of the expected area.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_area_um2: Option<f64>,
    /// Largest object kept in µm². Default: no limit.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_area_um2: Option<f64>,
    /// Objects listed (in reading order). Default 100; the counts cover all.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_objects: Option<usize>,
    /// Trace each object's outline (for pictures; not part of the JSON request).
    #[serde(skip)]
    #[schemars(skip)]
    pub outlines: bool,
}

/// One object.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Object {
    /// Number, in reading order (the label on a picture of the objects).
    pub id: u32,
    /// Centroid column, in pixels of the level read.
    pub x: f64,
    /// Centroid row.
    pub y: f64,
    /// Pixels.
    pub area_px: u64,
    /// Area in µm².
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area_um2: Option<f64>,
    /// Diameter of a disc of the same area, in µm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diameter_um: Option<f64>,
    /// Area over the area of its convex hull (1 = convex; low values suggest merged objects).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub solidity: Option<f64>,
    /// Spots: height above the local background in what was measured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub height: Option<f64>,
    /// Mean raw value in each channel of `channels`, in that order.
    pub mean: Vec<f64>,
    /// True when the object touches the edge of the area searched (it may be cut).
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub edge: bool,
    /// Outline vertices (pixel corners, pixels of the level read), only for pictures.
    #[serde(skip)]
    #[schemars(skip)]
    pub outline: Vec<[f64; 2]>,
}

/// Objects above a threshold in one channel.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Positive {
    /// Threshold on the object mean.
    pub threshold: f64,
    /// `otsu` (the object means fall in two groups), `background` (the channel's background
    /// plus five robust standard deviations) or `none` (no object is clearly brighter).
    pub method: String,
    /// Objects whose mean is above it.
    pub count: usize,
    /// The same as a fraction of all objects.
    pub fraction: f64,
}

/// One channel measured in every object.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ObjectChannel {
    /// Channel index (`c`), or the RGB component or stain index.
    pub c: u32,
    /// Channel, component or stain name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Median value outside the objects.
    pub background: f64,
    /// Object means.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mean: Option<Spread>,
    /// Objects clearly brighter than the rest (or than the background).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub positive: Option<Positive>,
}

/// Objects found in one plane.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct Objects {
    /// What was counted.
    pub kind: Kind,
    /// What objects were found in: a channel (`c=0 DAPI`), an RGB component, `luminance` or a
    /// stain (`hematoxylin`, `eosin`, `dab`).
    pub measured: String,
    /// The rectangle searched, in pixels of the level read.
    pub region: Region,
    /// Area searched (the region, or the polygon) in µm².
    #[serde(skip_serializing_if = "Option::is_none")]
    pub searched_um2: Option<f64>,
    /// Object diameter expected, in pixels: it sets the smoothing, the background scale, how
    /// close two objects may be and the smallest object kept.
    pub expected_diameter_px: f64,
    /// The same in µm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_diameter_um: Option<f64>,
    /// `given`, `measured` (from the image) or `default`.
    pub expected_diameter_from: String,
    /// `bright` or `dark`.
    pub polarity: Polarity,
    /// Threshold, in units of what was measured after background subtraction (spots: height
    /// above the local background).
    pub threshold: f64,
    /// `otsu`, `otsu-3`, `triangle`, `local`, `sparse` (a few objects on a large background:
    /// half way from the background to the objects), `noise` (spots: five robust standard
    /// deviations of the background) or `given`.
    pub threshold_method: String,
    /// Whether touching objects were cut apart.
    pub split: bool,
    /// Objects found, including those touching the edge.
    pub count: usize,
    /// `high`, or `low` when less than half of the objects' area is in compact objects of the
    /// expected size (`fit`), when most objects are under a third of the expected area, or
    /// when more objects were found than the area holds: the image may not suit the count, or
    /// the threshold cut noise into pieces (see `notes`).
    pub confidence: CountConfidence,
    /// Share of the objects' area in compact objects (solidity at least 0.85) of the expected
    /// size (a third to three times the area of its disc), 0 to 1. Not for spots.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fit: Option<f64>,
    /// Objects touching the edge of the area searched.
    pub touching_edge: usize,
    /// Objects per mm² (edge objects count half).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub density_per_mm2: Option<f64>,
    /// Fraction of the area searched covered by objects.
    pub area_fraction: f64,
    /// Objects more than twice the median area: possibly several objects together.
    pub large: usize,
    /// Object areas in pixels (objects off the edge, or all when every one touches it).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area_px: Option<Spread>,
    /// Object areas in µm².
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area_um2: Option<Spread>,
    /// Diameters (of a disc of the same area) in µm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub diameter_um: Option<Spread>,
    /// Every channel measured in the objects, in the order of each object's `mean`.
    pub channels: Vec<ObjectChannel>,
    /// The objects in reading order (top to bottom, then left to right).
    pub objects: Vec<Object>,
    /// True when `objects` lists fewer than `count`.
    pub truncated: bool,
}

/// What objects are found in, decided once for the whole area searched.
#[derive(Debug, Clone)]
pub(crate) struct Signal {
    /// `None`: a channel as stored; `Some`: computed from RGB.
    pub stain: Option<Stain>,
    /// Brightfield RGB: the light through empty glass, per component.
    pub i0: [f32; 3],
    /// Objects are darker than the background.
    pub dark: bool,
    /// The value objects are measured against when dark (the signal is `flip - value`).
    pub flip: f32,
}

impl Signal {
    /// True for stain amounts from colour deconvolution.
    fn deconvolved(&self) -> bool {
        matches!(
            self.stain,
            Some(Stain::Hematoxylin | Stain::Eosin | Stain::Dab)
        )
    }

    /// The bright-object signal of one tile.
    fn of(&self, comps: &[Vec<f32>]) -> Vec<f32> {
        let n = comps.first().map_or(0, Vec::len);
        let base: Vec<f32> = match self.stain {
            None => comps[0].clone(),
            Some(Stain::Red) => comps[0].clone(),
            Some(Stain::Green) => comps[1.min(comps.len() - 1)].clone(),
            Some(Stain::Blue) => comps[2.min(comps.len() - 1)].clone(),
            Some(Stain::Luminance) => {
                let k = comps.len().min(3);
                (0..n)
                    .map(|i| comps[..k].iter().map(|c| c[i]).sum::<f32>() / k as f32)
                    .collect()
            }
            Some(Stain::Auto) => (0..n)
                .map(|i| comps.iter().take(3).map(|c| c[i]).fold(f32::MIN, f32::max))
                .collect(),
            Some(s @ (Stain::Hematoxylin | Stain::Eosin | Stain::Dab)) => {
                return stains(comps, self.i0)[stain_index(s)].clone();
            }
        };
        if self.dark {
            base.iter().map(|v| self.flip - v).collect()
        } else {
            base
        }
    }
}

fn stain_index(s: Stain) -> usize {
    match s {
        Stain::Eosin => 1,
        Stain::Dab => 2,
        _ => 0,
    }
}

/// Hematoxylin, eosin and DAB amounts (optical density) of each RGB pixel.
fn stains(comps: &[Vec<f32>], i0: [f32; 3]) -> [Vec<f32>; 3] {
    let n = comps[0].len();
    let inv = sg::unmixing([sg::HEMATOXYLIN, sg::EOSIN, sg::DAB]).unwrap_or([[0.0; 3]; 3]);
    let mut out = [vec![0f32; n], vec![0f32; n], vec![0f32; n]];
    for i in 0..n {
        let od = [
            f64::from(sg::optical_density(comps[0][i], i0[0])),
            f64::from(sg::optical_density(comps[1][i], i0[1])),
            f64::from(sg::optical_density(comps[2][i], i0[2])),
        ];
        for (j, o) in out.iter_mut().enumerate() {
            o[i] = (od[0] * inv[0][j] + od[1] * inv[1][j] + od[2] * inv[2][j]).max(0.0) as f32;
        }
    }
    out
}

/// The share of clearly stained pixels (optical density over 0.3) whose colour needs a
/// negative amount of hematoxylin, eosin or DAB to be explained: high for other stains.
fn stain_misfit(comps: &[Vec<f32>], i0: [f32; 3]) -> f64 {
    let Some(inv) = sg::unmixing([sg::HEMATOXYLIN, sg::EOSIN, sg::DAB]) else {
        return 0.0;
    };
    let (mut stained, mut bad) = (0usize, 0usize);
    for i in (0..comps[0].len()).step_by(7) {
        let od = [0, 1, 2].map(|k| f64::from(sg::optical_density(comps[k][i], i0[k])));
        if od.iter().sum::<f64>() < 0.3 {
            continue;
        }
        stained += 1;
        let worst = (0..3)
            .map(|j| od[0] * inv[0][j] + od[1] * inv[1][j] + od[2] * inv[2][j])
            .fold(f64::INFINITY, f64::min);
        if worst < -0.15 {
            bad += 1;
        }
    }
    if stained == 0 {
        0.0
    } else {
        bad as f64 / stained as f64
    }
}

/// True for transmitted light (brightfield), where objects are darker than the background:
/// the median sits closer to the top of the range than to the bottom, or the plane has no
/// dark background at all (stained tissue filling the field). Fluorescence always has one,
/// though a camera offset can lift it: there the brightest few objects (the 20th brightest
/// pixel, which a handful of hot pixels do not reach) stand far above it, even when they
/// cover less than a thousandth of the plane.
fn looks_dark(v: &[f32]) -> bool {
    let n = v.len().max(1) as f64;
    let (Some(p1), Some(p50), Some(p99), Some(top)) = (
        sg::quantile(v, 0.01),
        sg::quantile(v, 0.5),
        sg::quantile(v, 0.99),
        sg::quantile(v, 0.999f64.max(1.0 - 20.0 / n)),
    ) else {
        return false;
    };
    (p50 - p1) > 1.5 * (p99 - p50) || (top > 0.0 && p1 > 0.12 * top && p50 > 0.5 * top)
}

/// Decide what to measure from a sample tile of the image (`comps`: one plane, or three RGB).
fn signal_for(
    comps: &[Vec<f32>],
    o: &ObjectsRequest,
    notes: &mut Vec<String>,
) -> Result<(Signal, String)> {
    let rgb = comps.len() >= 3;
    if !rgb && o.stain != Stain::Auto {
        return Err(usage(
            "stain is for RGB images; this image has one value per pixel (choose a channel with select c=N)",
        ));
    }
    if rgb {
        let lum: Vec<f32> = (0..comps[0].len())
            .map(|i| (comps[0][i] + comps[1][i] + comps[2][i]) / 3.0)
            .collect();
        // colour pictures of fluorescence have a black background; transmitted light does not
        let brightfield = match o.polarity {
            Polarity::Auto => {
                looks_dark(&lum)
                    || match (sg::quantile(&lum, 0.5), sg::quantile(&lum, 0.999)) {
                        (Some(mid), Some(top)) => top > 0.0 && mid > 0.3 * top,
                        _ => false,
                    }
            }
            p => p == Polarity::Dark,
        };
        let i0 = [0, 1, 2].map(|k| sg::quantile(&comps[k], 0.99).unwrap_or(255.0).max(1.0));
        // nuclear stains (DAPI, Hoechst) are drawn blue in colour pictures of fluorescence
        let blue_nuclei = !brightfield
            && o.kind == Kind::Nuclei
            && i0[2] >= 32.0
            && i0[2] >= 0.25 * i0[0].max(i0[1]);
        let stain = match (o.stain, brightfield) {
            (Stain::Auto, true) => Stain::Hematoxylin,
            (Stain::Auto, false) if blue_nuclei => {
                notes.push(
                    "nuclei counted in the blue component (where DAPI and Hoechst are drawn); stain=red|green picks another"
                        .into(),
                );
                Stain::Blue
            }
            (s, _) => s,
        };
        let deconvolved = matches!(stain, Stain::Hematoxylin | Stain::Eosin | Stain::Dab);
        if deconvolved {
            let misfit = stain_misfit(comps, i0);
            if misfit > 0.3 {
                notes.push(format!(
                    "{:.0}% of the stained pixels have colours that hematoxylin, eosin and DAB do not explain (another stain, such as a trichrome?): the {} amounts may be wrong; check a picture (preview marks=objects), or count in one colour with stain=red|green|blue",
                    misfit * 100.0,
                    serde_json::to_value(stain)
                        .ok()
                        .and_then(|v| v.as_str().map(str::to_string))
                        .unwrap_or_default()
                ));
            }
        }
        let dark = brightfield && !deconvolved;
        let name = match stain {
            Stain::Auto => "brightest component".into(),
            s => serde_json::to_value(s)
                .ok()
                .and_then(|v| v.as_str().map(str::to_string))
                .unwrap_or_default(),
        };
        let flip = if dark {
            sg::quantile(&lum, 0.999).unwrap_or(255.0)
        } else {
            0.0
        };
        return Ok((
            Signal {
                stain: Some(stain),
                i0,
                dark,
                flip,
            },
            name,
        ));
    }
    let dark = match o.polarity {
        Polarity::Auto => looks_dark(&comps[0]),
        p => p == Polarity::Dark,
    };
    Ok((
        Signal {
            stain: None,
            i0: [0.0; 3],
            dark,
            flip: if dark {
                sg::quantile(&comps[0], 0.999).unwrap_or(0.0)
            } else {
                0.0
            },
        },
        String::new(),
    ))
}

/// Object diameter in pixels measured from the image. Candidates: the size of the regions
/// above Otsu's threshold, the scale of the strongest blobs (Laplacian of Gaussian) and, for
/// textured objects, the size of the regions in a smoothed copy. When they disagree, the one
/// whose segmentation gives the most compact objects of the expected size wins.
///
/// `range` bounds the candidates in pixels (from the physical sizes the kind can have, when
/// the pixel size is known); `typical`, the kind's typical size, competes as a last candidate.
/// Returns the diameter and whether it is the typical one.
fn measure_diameter(
    s: &[f32],
    w: usize,
    h: usize,
    kind: Kind,
    signal: &Signal,
    range: (f64, f64),
    typical: Option<f64>,
) -> Option<(f64, bool)> {
    let background = !signal.deconvolved();
    // objects narrower than 4 pixels cannot be told apart; wider than a third of the plane
    // they cannot be counted
    let plausible = |d: &f64| *d >= range.0.max(4.0) && *d <= range.1.min((w.min(h) as f64) / 3.0);
    // one candidate per size
    let distinct = |cands: &[f64], d: f64| cands.iter().all(|c| (c / d).max(d / c) > 1.3);
    let mut cands: Vec<f64> = Vec::new();
    {
        let mut add = |d: Option<f64>| {
            if let Some(d) = d.filter(plausible)
                && distinct(&cands, d)
            {
                cands.push(d);
            }
        };
        let (compact, peaks) = mask_sizes(s, w, h);
        add(compact.or(peaks));
        add(sg::blob_diameter(s, w, h));
        // textured objects (chromatin, granules) look like many small ones until smoothed;
        // not in brightfield, where the coarse scale is that of the cells around the nuclei
        if !signal.dark {
            let k = (w.min(h) / 128).max(2);
            let (small, sw, sh) = sg::shrink(s, w, h, k);
            let sm = sg::gaussian(&small, sw, sh, 1.5);
            let (compact, peaks) = mask_sizes(&sm, sw, sh);
            add(peaks.map(|d| d * k as f64));
            add(compact.map(|d| d * k as f64));
        }
    }
    let measured = cands.len();
    if let Some(t) = typical.filter(|t| *t <= w.min(h) as f64)
        && distinct(&cands, t)
    {
        cands.push(t);
    }
    if cands.len() <= 1 {
        return cands.pop().map(|d| (d, measured == 0));
    }
    let q = |d: f64| {
        let mut plan = Plan::new(kind, d, background, ThresholdMethod::Otsu);
        let (ws, ww, wh, k) = working(s, w, h, &plan);
        let Some((t, _)) = sg::otsu(&scaled(&plan, k).flatten(&ws, ww, wh)) else {
            return 0.0;
        };
        plan.threshold = t;
        quality(s, w, h, &plan)
    };
    // the first (the compact regions' size) unless another is clearly better
    let mut best = (q(cands[0]), 0usize);
    for (i, &d) in cands.iter().enumerate().skip(1) {
        let qd = q(d);
        if qd > best.0 {
            best = (qd, i);
        }
    }
    Some((cands[best.1], best.1 >= measured))
}

/// How well a plan explains the plane: the share of the segmented area in objects that are
/// compact (solidity at least 0.85) and of a plausible size (a third to three times the
/// expected area). Measured on a central crop of at most about a thousand pixels a side.
fn quality(s: &[f32], w: usize, h: usize, plan: &Plan) -> f64 {
    let side = (8.0 * plan.d).max(768.0) as usize;
    let (cw, ch) = (w.min(side), h.min(side));
    let (x0, y0) = ((w - cw) / 2, (h - ch) / 2);
    let crop: Vec<f32> = (0..ch)
        .flat_map(|y| s[(y0 + y) * w + x0..(y0 + y) * w + x0 + cw].iter().copied())
        .collect();
    let (lab, _) = label_tile(&crop, cw, ch, plan);
    fit(&shapes(&lab, cw, ch), plan.d)
}

/// Why a count has low confidence.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Doubt {
    /// Less than [`LOW_FIT`] of the objects' area is in compact objects of the expected size.
    Shapes(f64),
    /// Most objects are under a third of the expected area: noise or texture cut into specks.
    Specks,
    /// More objects of the expected size than the area searched holds.
    Crowded,
}

impl Doubt {
    fn note(self, count: usize, d: f64, kind: Kind) -> String {
        let why = match self {
            Doubt::Shapes(f) => format!(
                "only {:.0}% of the objects' area is in compact objects about {d:.0} px across; this image may not suit counting {} (cytoplasm, another stain or debris counted, or touching objects merged)",
                f * 100.0,
                kind_name(kind)
            ),
            Doubt::Specks => format!(
                "most of the {count} objects are under a third of the area of a {d:.0} px disc: the threshold probably cut background noise or texture into specks"
            ),
            Doubt::Crowded => format!(
                "{count} objects about {d:.0} px across would need more than the area searched: the threshold probably cut background noise or texture into pieces"
            ),
        };
        format!(
            "low confidence: {why}. Do not quote the count without checking a picture (preview marks=objects); set diameter_um, threshold, another channel or stain if the picture shows why"
        )
    }
}

/// The fit of a count (see [`fit`]; not for spots) and why it has low confidence, if it has:
/// from each object's `(area, solidity)`, the expected diameter `d` and the pixels searched.
pub(crate) fn assess(
    kind: Kind,
    shapes: &[(f64, f64)],
    d: f64,
    searched: f64,
) -> (Option<f64>, Option<Doubt>) {
    if kind == Kind::Spots || shapes.is_empty() {
        return (None, None);
    }
    let f = fit(shapes, d);
    let expected = std::f64::consts::PI * d * d / 4.0;
    let mut areas: Vec<f64> = shapes.iter().map(|s| s.0).collect();
    let doubt = if f < LOW_FIT {
        Some(Doubt::Shapes(f))
    } else if shapes.len() >= 10 && median(&mut areas).is_some_and(|a| a < expected / 3.0) {
        Some(Doubt::Specks)
    } else if shapes.len() as f64 * expected > searched {
        Some(Doubt::Crowded)
    } else {
        None
    };
    (Some(f), doubt)
}

/// The share of the objects' area in objects that are compact (solidity at least 0.85) and
/// of a plausible size for diameter `d` (a third to three times its disc's area), from each
/// object's `(area, solidity)`.
fn fit(shapes: &[(f64, f64)], d: f64) -> f64 {
    let expected = std::f64::consts::PI * d * d / 4.0;
    let (mut good, mut all) = (0.0, 0.0);
    for &(area, solidity) in shapes {
        all += area;
        let r = area / expected;
        if solidity >= 0.85 && (0.3..=3.0).contains(&r) {
            good += area;
        }
    }
    if all > 0.0 { good / all } else { 0.0 }
}

/// Area and solidity of each labelled object.
fn shapes(lab: &[u32], w: usize, h: usize) -> Vec<(f64, f64)> {
    let n = lab.iter().copied().max().unwrap_or(0) as usize;
    let mut area = vec![0usize; n + 1];
    let mut pts: Vec<Vec<[f64; 2]>> = vec![Vec::new(); n + 1];
    for (i, &l) in lab.iter().enumerate() {
        if l == 0 {
            continue;
        }
        area[l as usize] += 1;
        let (x, y) = (i % w, i / w);
        let rim = x == 0
            || y == 0
            || x + 1 == w
            || y + 1 == h
            || lab[i - 1] != l
            || lab[i + 1] != l
            || lab[i - w] != l
            || lab[i + w] != l;
        if rim {
            let (fx, fy) = (x as f64, y as f64);
            pts[l as usize].extend([
                [fx, fy],
                [fx + 1.0, fy],
                [fx, fy + 1.0],
                [fx + 1.0, fy + 1.0],
            ]);
        }
    }
    (1..=n)
        .filter(|l| area[*l] > 0)
        .map(|l| {
            let hull = sg::hull_area(&mut pts[l]);
            let a = area[l] as f64;
            (a, if hull > 0.0 { (a / hull).min(1.0) } else { 1.0 })
        })
        .collect()
}

/// Two sizes of the regions above Otsu's threshold: the median diameter of the compact ones
/// (when there are enough), and twice the median depth of the distance-transform peaks (one
/// per object even where objects touch).
fn mask_sizes(s: &[f32], w: usize, h: usize) -> (Option<f64>, Option<f64>) {
    let sm = sg::gaussian(s, w, h, 1.0);
    let Some((t, _)) = sg::otsu(&sm) else {
        return (None, None);
    };
    let mut fg: Vec<bool> = sm.iter().map(|v| *v > t).collect();
    sg::fill_holes(&mut fg, w, h, (w * h) / 100);
    let (lab, n) = sg::components(&fg, w, h);
    if n == 0 {
        return (None, None);
    }
    let mut compact = Vec::new();
    let mut all = 0usize;
    for (area, solidity) in shapes(&lab, w, h) {
        if area < 12.0 {
            continue;
        }
        all += 1;
        if solidity >= 0.85 {
            compact.push(2.0 * (area / std::f64::consts::PI).sqrt());
        }
    }
    let compact = if compact.len() >= 5 && compact.len() * 3 >= all {
        median(&mut compact)
    } else {
        None
    };
    let dist = sg::distance(&fg, w, h);
    let (seeds, k) = sg::seeds(&dist, &fg, w, h, 3, 2.0);
    let mut depth = vec![0f32; k as usize + 1];
    for (i, &l) in seeds.iter().enumerate() {
        if l > 0 {
            depth[l as usize] = depth[l as usize].max(dist[i]);
        }
    }
    let mut d: Vec<f64> = depth
        .iter()
        .skip(1)
        .map(|r| 2.0 * f64::from(*r) * 1.1)
        .collect();
    (compact, median(&mut d))
}

fn median(v: &mut [f64]) -> Option<f64> {
    if v.is_empty() {
        return None;
    }
    v.sort_by(f64::total_cmp);
    Some(super::median_sorted(v))
}

/// Every setting of a count, fixed before the tiles are read.
#[derive(Debug, Clone)]
pub(crate) struct Plan {
    pub kind: Kind,
    /// Expected diameter in pixels.
    pub d: f64,
    pub split: bool,
    /// Applies to [`Plan::flatten`]'s output.
    pub threshold: f32,
    pub method: ThresholdMethod,
    pub min_area: usize,
    pub max_area: usize,
    /// Remove the slowly varying background first. Stain amounts from colour deconvolution
    /// are already relative to empty glass and keep theirs.
    pub background: bool,
}

impl Plan {
    fn new(kind: Kind, d: f64, background: bool, method: ThresholdMethod) -> Plan {
        let expected = std::f64::consts::PI * d * d / 4.0;
        Plan {
            kind,
            d,
            split: kind != Kind::Spots,
            threshold: 0.0,
            method,
            min_area: if kind == Kind::Spots {
                1
            } else {
                (expected / 5.0).max(1.0) as usize
            },
            max_area: usize::MAX,
            background,
        }
    }

    /// What the threshold applies to: the signal smoothed at a twentieth of the object size,
    /// less the background under objects of that size (spots: the height above the local
    /// background).
    pub(crate) fn flatten(&self, s: &[f32], w: usize, h: usize) -> Vec<f32> {
        if self.kind == Kind::Spots {
            let sm = sg::gaussian(s, w, h, spot_sigma(self.d).min(1.0));
            let bg = sg::background(&sm, w, h, (self.d * 3.0).max(6.0));
            return sm.iter().zip(&bg).map(|(a, b)| a - b).collect();
        }
        let sm = sg::gaussian(s, w, h, (self.d / 20.0).max(0.6));
        if !self.background {
            return sm;
        }
        let bg = sg::background(&sm, w, h, self.d);
        sm.iter().zip(&bg).map(|(a, b)| a - b).collect()
    }
}

/// Laplacian-of-Gaussian scale for spots of diameter `d`.
fn spot_sigma(d: f64) -> f64 {
    (d / (2.0 * std::f64::consts::SQRT_2)).max(0.7)
}

/// Object diameter (pixels) above which a tile is labelled at a reduced scale: the steps
/// need only about 32 pixels per object, and large objects would make them slow.
const LARGE_OBJECTS: f64 = 64.0;

/// The most [`working`] shrinks by (diameters are at most the area's side, so only objects
/// too large to count get near it).
const MAX_WORKING_FACTOR: usize = 1 << 12;

/// The factor [`working`] shrinks by.
fn working_factor(p: &Plan) -> usize {
    if p.kind == Kind::Spots || p.d < LARGE_OBJECTS {
        1
    } else {
        // about 32 pixels per object
        ((p.d / 32.0).floor().max(1.0) as usize).min(MAX_WORKING_FACTOR)
    }
}

/// The plane the steps work on: `s` itself, or for large objects a copy shrunk by a whole
/// factor (returned last) with the plan scaled to match.
fn working(s: &[f32], w: usize, h: usize, p: &Plan) -> (Vec<f32>, usize, usize, usize) {
    let f = working_factor(p);
    if f == 1 {
        return (s.to_vec(), w, h, 1);
    }
    let (small, sw, sh) = sg::shrink(s, w, h, f);
    (small, sw, sh, f)
}

/// `p` for a plane shrunk by `k`.
fn scaled(p: &Plan, k: usize) -> Plan {
    let mut q = p.clone();
    if k > 1 {
        q.d = p.d / k as f64;
        q.min_area = (p.min_area / k.saturating_mul(k)).max(1);
    }
    q
}

/// The label image of one tile (`s`: the bright-object signal) and, for spots, each spot's
/// height above the background.
pub(crate) fn label_tile(s: &[f32], w: usize, h: usize, p: &Plan) -> (Vec<u32>, Vec<f32>) {
    if p.kind == Kind::Spots {
        return spots(s, w, h, p);
    }
    let (ws, sw, sh, f) = working(s, w, h, p);
    if f == 1 {
        return (label_objects(&ws, w, h, p), Vec::new());
    }
    // label the shrunken copy, then give each pixel the label of its block
    let lab_s = label_objects(&ws, sw, sh, &scaled(p, f));
    let mut lab = vec![0u32; w * h];
    for y in 0..h {
        for x in 0..w {
            lab[y * w + x] = lab_s[(y / f) * sw + x / f];
        }
    }
    (lab, Vec::new())
}

/// Nuclei and cells: threshold the flattened signal, fill holes smaller than half an object,
/// split touching objects by a watershed of the distance to the background (and to dark
/// seams) from one seed per distance peak, join pieces that texture cut off an object back
/// to it, and merge specks under the smallest size into their neighbour.
fn label_objects(s: &[f32], w: usize, h: usize, p: &Plan) -> Vec<u32> {
    let f = p.flatten(s, w, h);
    let mut fg = foreground(&f, w, h, p);
    let expected = std::f64::consts::PI * p.d * p.d / 4.0;
    sg::fill_holes(&mut fg, w, h, (expected * 0.5) as usize);
    let mut lab = if p.split {
        // dark seams between touching objects: valleys narrower than a fifth of an object
        // where the signal falls from the ridges around them (a black top-hat) by 40% or
        // more, and by more than it falls inside the objects; cut there before measuring
        // the distance to the background
        let r = ((p.d * 0.1).round() as usize).max(1);
        let closed = sg::rank_filter(&sg::rank_filter(&f, w, h, r, true), w, h, r, false);
        let t = p.threshold.abs().max(f32::EPSILON);
        let fall: Vec<f32> = closed
            .iter()
            .zip(&f)
            .map(|(c, v)| (c - v) / c.max(t))
            .collect();
        let texture = texture(&fall, &sg::distance(&fg, w, h), p.d);
        let seam = SEAM_FALL.max(texture + SEAM_OVER_TEXTURE);
        let cut: Vec<bool> = fg.iter().zip(&fall).map(|(g, x)| *g && *x < seam).collect();
        let dist = sg::distance(&cut, w, h);
        // seeds: peaks of the smoothed distance at least a quarter diameter apart
        let m = sg::gaussian(&dist, w, h, (p.d * 0.08).max(0.7));
        let radius = ((p.d * 0.25).round() as usize).max(1);
        let floor = (p.d * 0.05) as f32;
        let (seeds, _) = sg::seeds(&m, &fg, w, h, radius, floor);
        let mut lab = sg::watershed(&m, &fg, &seeds, w, h);
        let rule = sg::JoinRule {
            small: (expected * 0.4) as usize,
            seam: (texture + SEAM_OVER_TEXTURE).max(0.2),
            convexity: 0.08,
        };
        sg::join_small_pieces(&mut lab, w, h, &f, &rule);
        lab
    } else {
        sg::components(&fg, w, h).0
    };
    sg::tidy_labels(&mut lab, w, h, p.min_area);
    lab
}

/// A seam falls at least this far below the ridges around it (a share of their height).
const SEAM_FALL: f32 = 0.4;

/// In textured objects (chromatin at high magnification), a seam also falls this much
/// further than the signal falls inside the objects.
const SEAM_OVER_TEXTURE: f32 = 0.2;

/// How far the signal falls inside objects: the 95th percentile of `fall` (the black top-hat
/// as a share of the ridges around it) over the pixels more than an eighth of the diameter
/// `d` from the background (`depth`). Near 0 for smooth nuclei; about 0.3 for 63x DAPI with
/// bright chromocentres.
fn texture(fall: &[f32], depth: &[f32], d: f64) -> f32 {
    let inner: Vec<f32> = fall
        .iter()
        .zip(depth)
        .filter(|(_, z)| f64::from(**z) > d / 8.0)
        .map(|(x, _)| *x)
        .collect();
    sg::quantile(&inner, 0.95).unwrap_or(0.0).clamp(0.0, 1.0)
}

fn foreground(f: &[f32], w: usize, h: usize, p: &Plan) -> Vec<bool> {
    if p.method == ThresholdMethod::Local {
        // against the neighbourhood mean (twice the object size), never below the global
        // threshold's half
        let local = sg::gaussian(f, w, h, p.d);
        return f
            .iter()
            .zip(&local)
            .map(|(v, l)| *v > l.max(0.0) + 0.5 * p.threshold.max(0.0) && *v > 0.5 * p.threshold)
            .collect();
    }
    f.iter().map(|v| *v > p.threshold).collect()
}

/// Spots: local maxima of the Laplacian of Gaussian at the spot scale whose height above the
/// local background reaches the threshold. Each spot is labelled as a disc of the expected
/// diameter.
fn spots(s: &[f32], w: usize, h: usize, p: &Plan) -> (Vec<u32>, Vec<f32>) {
    let resp = sg::log_filter(s, w, h, spot_sigma(p.d));
    let height = p.flatten(s, w, h);
    let fg = vec![true; w * h];
    let r = (p.d / 2.0).ceil().max(1.0) as usize;
    let (peaks, n) = sg::seeds(&resp, &fg, w, h, r, f32::MIN_POSITIVE);
    // one point per peak (plateaus: the first pixel)
    let mut first = vec![usize::MAX; n as usize + 1];
    for (i, &l) in peaks.iter().enumerate() {
        if l > 0 && first[l as usize] == usize::MAX {
            first[l as usize] = i;
        }
    }
    let mut lab = vec![0u32; w * h];
    let mut heights = Vec::new();
    let rr = (p.d / 2.0).max(1.0);
    for &i in first.iter().skip(1) {
        if i == usize::MAX || height[i] < p.threshold {
            continue;
        }
        let id = heights.len() as u32 + 1;
        heights.push(height[i]);
        let (cx, cy) = ((i % w) as isize, (i / w) as isize);
        let ri = rr.ceil() as isize;
        for dy in -ri..=ri {
            for dx in -ri..=ri {
                let (x, y) = (cx + dx, cy + dy);
                if x < 0 || y < 0 || x >= w as isize || y >= h as isize {
                    continue;
                }
                if ((dx * dx + dy * dy) as f64) <= rr * rr + 0.5 {
                    let j = y as usize * w + x as usize;
                    if lab[j] == 0 {
                        lab[j] = id;
                    }
                }
            }
        }
    }
    (lab, heights)
}

/// The error when no threshold can be chosen.
fn flat() -> Error {
    usage(
        "the area has no contrast (one value once the background is removed), so there is nothing to count: check the channel, z plane and region with preview",
    )
}

/// The threshold for a few bright objects on a large background, or `None` when the objects
/// are not sparse. Objects that cover under about a thousandth of the area lie above the
/// range the histogram thresholds look at (the 0.1th to 99.9th percentile), and Otsu's
/// threshold then splits the background noise: it lands within 3 robust standard deviations
/// (σ) of the median. When the brightest pixels (the 20th brightest, which a handful of hot
/// pixels do not reach) stand far above that range, the threshold is half way from the
/// background to the median of the pixels more than 5σ above it (the objects), and at least
/// 5σ above the background.
fn sparse_threshold(sample: &[f32]) -> Option<f32> {
    let n = sample.iter().filter(|v| v.is_finite()).count();
    let med = sg::quantile(sample, 0.5)?;
    let hi = sg::quantile(sample, 0.999)?;
    let top = sg::quantile(sample, 0.999f64.max(1.0 - 20.0 / n.max(1) as f64))?;
    let dev: Vec<f32> = sample.iter().map(|v| (v - med).abs()).collect();
    let sd = 1.4826 * sg::quantile(&dev, 0.5)?;
    // nothing far above the histogram's range
    if top <= hi + 2.0 * (hi - med).max(sd) {
        return None;
    }
    // Otsu's threshold clear of the noise: it sees the objects
    if let Some((t, _)) = sg::otsu(sample)
        && (t - med).abs() >= 3.0 * sd
    {
        return None;
    }
    let noise_top = med + 5.0 * sd;
    let bright: Vec<f32> = sample.iter().copied().filter(|v| *v > noise_top).collect();
    let objects = sg::quantile(&bright, 0.5)?;
    Some(noise_top.max(med + 0.5 * (objects - med)))
}

/// The threshold for `plan` from a sample of the flattened signal, and its name. `auto` tries
/// Otsu's two-class threshold and the upper of Otsu's three-class thresholds (objects that
/// stand out from a middle class such as cytoplasm), and keeps the three-class one only when
/// its objects on the probe tile are clearly more compact and better sized.
fn settle_threshold(
    probe: &[f32],
    w: usize,
    h: usize,
    plan: &Plan,
    sample: &[f32],
) -> Option<(f32, &'static str)> {
    if plan.kind == Kind::Spots {
        // spots: a multiple of the background noise (robust standard deviation)
        let med = sg::quantile(sample, 0.5)?;
        let dev: Vec<f32> = sample.iter().map(|v| (v - med).abs()).collect();
        let mad = sg::quantile(&dev, 0.5)?;
        let sd = (1.4826 * mad).max(f32::EPSILON);
        return Some((med + 5.0 * sd, "noise"));
    }
    if let Some(t) = sparse_threshold(sample) {
        let name = if plan.method == ThresholdMethod::Local {
            "local"
        } else {
            "sparse"
        };
        return Some((t, name));
    }
    match plan.method {
        ThresholdMethod::Otsu => sg::otsu(sample).map(|t| (t.0, "otsu")),
        ThresholdMethod::Local => sg::otsu(sample).map(|t| (t.0, "local")),
        ThresholdMethod::Triangle => sg::triangle(sample).map(|t| (t, "triangle")),
        ThresholdMethod::Auto => {
            let (t, _) = sg::otsu(sample)?;
            // each class boundary moved 30% of the way towards the class below, so that dim
            // objects are whole and bright ones not much enlarged
            let k = 0.7f32;
            let med = sg::quantile(sample, 0.5)?;
            let mut cands: Vec<(f32, &'static str)> = vec![(med + k * (t - med), "otsu")];
            if let Some((lo, hi)) = sg::otsu3(sample)
                && hi > t
            {
                cands.push((lo + k * (hi - lo), "otsu-3"));
            }
            if cands.len() == 1 {
                return cands.pop();
            }
            let mut best = (f64::NEG_INFINITY, cands[0]);
            for c in cands {
                let mut p = plan.clone();
                p.threshold = c.0;
                let q = quality(probe, w, h, &p);
                // the three-class threshold only when clearly better
                if q > best.0 + 0.2 {
                    best = (q, c);
                }
            }
            Some(best.1)
        }
    }
}

/// A channel name for the label `c=N NAME`.
fn channel_label(tg: &Target<'_>, c: u32) -> Option<String> {
    tg.im
        .channels
        .iter()
        .find(|ch| ch.index == c)
        .and_then(|ch| ch.name.clone().or_else(|| ch.fluorophore.clone()))
}

/// The channel objects of `kind` are found in when the request selects none: for nuclei, the
/// first channel named like a DNA stain, otherwise channel 0. Previews show this channel so
/// that the outlines sit on the plane they were found in.
pub fn default_channel(im: &ImageInfo, kind: Kind) -> u32 {
    const DNA: [&str; 14] = [
        "dapi", "hoechst", "draq5", "draq7", "nucblue", "sir-dna", "sirdna", "spy-dna", "spydna",
        "nuclear", "nuclei", "h2b", "to-pro", "topro",
    ];
    if kind != Kind::Nuclei {
        return 0;
    }
    im.channels
        .iter()
        .find(|ch| {
            [&ch.name, &ch.fluorophore].iter().any(|n| {
                n.as_deref()
                    .is_some_and(|n| DNA.iter().any(|d| n.to_ascii_lowercase().contains(d)))
            })
        })
        .map_or(0, |ch| ch.index)
}

/// Per-object sums while tiles are read.
#[derive(Default, Clone)]
struct Acc {
    n: u64,
    sx: f64,
    sy: f64,
    sums: Vec<f64>,
    edge: bool,
    hull: Vec<[f64; 2]>,
    height: Option<f64>,
    outline: Vec<[f64; 2]>,
}

/// The planes of one tile: the components of the counted channel and every channel measured.
struct TileData {
    comps: Vec<Vec<f32>>,
    /// One plane per measured channel (RGB brightfield: the three stains).
    measured: Vec<Vec<f32>>,
}

fn grid_f32(g: &Grid) -> Vec<Vec<f32>> {
    g.comps
        .iter()
        .map(|c| c.iter().map(|v| *v as f32).collect())
        .collect()
}

pub(crate) fn objects(
    ds: &mut dyn crate::reader::Dataset,
    tg: &Target<'_>,
    req: &super::MeasureRequest,
    o: &ObjectsRequest,
    notes: &mut Vec<String>,
) -> Result<Objects> {
    validate(o)?;
    let poly = req.polygon.as_deref();
    let r = match (req.region, poly) {
        (Some(r), _) => {
            r.check_within(
                tg.level_w,
                tg.level_h,
                &format!("image {} level {}", tg.im.index, req.level),
            )?;
            r
        }
        (None, Some(p)) => super::bounds(p, 0.0, tg.level_w, tg.level_h)?,
        (None, None) => Region::full(tg.level_w, tg.level_h),
    };
    let total = u64::from(r.width) * u64::from(r.height);
    if total > MAX_OBJECT_PIXELS {
        let coarser = (1..tg.im.pyramid_levels.max(1))
            .find(|l| total >> (2 * l) <= MAX_OBJECT_PIXELS)
            .map(|l| format!(" (level {})", req.level + l))
            .unwrap_or_default();
        return Err(Error::unsupported(
            "stats",
            format!("an object count over {} x {} pixels", r.width, r.height),
            format!(
                "Count objects in at most {MAX_OBJECT_PIXELS} pixels: pass a region (or polygon) inside it, or a coarser level{coarser}; coordinates are then that level's pixels."
            ),
        ));
    }
    // the channel objects are found in
    let selected_c = !req.select.iter().all(|s| !s.contains('c'));
    let c = if selected_c {
        tg.channels.first().copied().unwrap_or(0)
    } else {
        default_channel(tg.im, o.kind)
    };
    let counted = c;
    let all_channels: Vec<u32> = (0..tg.im.size_c.max(1)).take(8).collect();
    if tg.im.size_c > 1 && !selected_c {
        notes.push(format!(
            "objects were found in channel {c}{}; select c=N for another",
            channel_label(tg, c)
                .map(|n| format!(" ({n})"))
                .unwrap_or_default()
        ));
    }
    let pixel_um = tg.pixel_um;
    let area_px_um2 = pixel_um.map(|p| p * tg.pixel_um_y.unwrap_or(p));
    // probe: the tile at the centre decides polarity, stain and diameter
    let probe = centre_tile(r);
    let g = read(ds, tg, req.level, c, probe)?;
    let comps = grid_f32(&g);
    let rgb = comps.len() >= 3;
    let (signal, stain_name) = signal_for(&comps, o, notes)?;
    let measured = if rgb {
        stain_name
    } else {
        format!(
            "c={c}{}",
            channel_label(tg, c)
                .map(|n| format!(" {n}"))
                .unwrap_or_default()
        )
    };
    let s = signal.of(&comps);
    let background = !signal.deconvolved();
    let (d, from) = diameter(o, &s, probe, r, pixel_um, &signal, notes)?;
    if d < 3.0 && o.kind != Kind::Spots {
        notes.push(format!(
            "objects are about {d:.1} px across at this level: too small to separate; read a finer level"
        ));
    }
    let to_px2 = |um2: f64| area_px_um2.map(|a| um2 / a);
    let expected = std::f64::consts::PI * d * d / 4.0;
    let min_area = match (o.min_area_um2, to_px2(1.0)) {
        (Some(a), Some(_)) => to_px2(a).unwrap_or(1.0),
        (Some(_), None) => {
            return Err(usage(
                "min_area_um2 needs the pixel size, which this image does not record; set diameter_px instead (objects under a fifth of its area are dropped)",
            ));
        }
        (None, _) if o.kind == Kind::Spots => 1.0,
        (None, _) => expected / 5.0,
    }
    .max(1.0) as usize;
    let max_area = match (o.max_area_um2, to_px2(1.0)) {
        (Some(a), Some(_)) => to_px2(a).unwrap_or(f64::MAX),
        (Some(_), None) => {
            return Err(usage(
                "max_area_um2 needs the pixel size, which this image does not record",
            ));
        }
        (None, _) => f64::MAX,
    };
    // validated finite and positive; `as` saturates at usize::MAX
    let max_area = max_area as usize;
    if max_area < min_area {
        return Err(usage(format!(
            "max_area_um2 is below the smallest object kept ({:.3} µm², a fifth of the expected area): raise it, or set min_area_um2 too",
            min_area as f64 * area_px_um2.unwrap_or(1.0)
        )));
    }
    // threshold: from the whole area (tile by tile when it is large)
    let tiles = tiles(r, d);
    let mut plan = Plan::new(o.kind, d, background, o.method);
    plan.split &= o.split.unwrap_or(true);
    plan.min_area = min_area;
    plan.max_area = max_area;
    let method_name;
    if let Some(t) = o.threshold {
        plan.threshold = t as f32;
        method_name = "given".to_string();
    } else {
        let mut sample: Vec<f32> = Vec::new();
        let single = tiles.len() == 1;
        for t in &tiles {
            let s = if single && t.read == probe {
                s.clone()
            } else {
                let g = read(ds, tg, req.level, c, t.read)?;
                signal.of(&grid_f32(&g))
            };
            let (w, h) = (t.read.width as usize, t.read.height as usize);
            let (ws, sw, _, k) = working(&s, w, h, &plan);
            let f = scaled(&plan, k).flatten(&ws, sw, ws.len() / sw.max(1));
            // every pixel of one tile, every third of many
            let stride = if single { 1 } else { 3 };
            let core = t.core_in_read();
            let k32 = k as u32;
            for y in (core.y / k32..(core.y + core.height) / k32).step_by(stride) {
                for x in (core.x / k32..(core.x + core.width) / k32).step_by(stride) {
                    let i = y as usize * sw + x as usize;
                    let (gx, gy) = (t.read.x + x * k32, t.read.y + y * k32);
                    if i < f.len()
                        && poly.is_none_or(|p| inside(p, f64::from(gx) + 0.5, f64::from(gy) + 0.5))
                    {
                        sample.push(f[i]);
                    }
                }
            }
        }
        let (pw, ph) = (probe.width as usize, probe.height as usize);
        let (t, m) = settle_threshold(&s, pw, ph, &plan, &sample).ok_or_else(flat)?;
        if o.kind != Kind::Spots
            && let Some((_, sep)) = sg::otsu(&sample)
            && sep < 0.5
        {
            notes.push(format!(
                        "weak contrast between objects and background (Otsu separability {sep:.2}): the count may be unreliable; check a picture (preview marks=objects)"
                    ));
        }
        plan.threshold = t;
        method_name = m.to_string();
    }
    // the objects, tile by tile
    let n_meas = if rgb { 3 } else { all_channels.len() };
    let mut accs: Vec<Acc> = Vec::new();
    let mut bg_samples: Vec<Vec<f32>> = vec![Vec::new(); n_meas];
    let mut covered = 0u64;
    let mut searched = 0u64;
    for t in &tiles {
        let data = tile_data(ds, tg, req.level, c, &all_channels, t.read, &signal)?;
        let (w, h) = (t.read.width as usize, t.read.height as usize);
        let s = signal.of(&data.comps);
        let (lab, heights) = label_tile(&s, w, h, &plan);
        let n = lab.iter().copied().max().unwrap_or(0) as usize;
        let mut a: Vec<Acc> = vec![
            Acc {
                sums: vec![0.0; n_meas],
                ..Acc::default()
            };
            n + 1
        ];
        let mut first = vec![usize::MAX; n + 1];
        for (i, &l) in lab.iter().enumerate() {
            let (x, y) = (i % w, i / w);
            let (gx, gy) = (t.read.x + x as u32, t.read.y + y as u32);
            let in_core = t.core.contains_px(gx, gy);
            let in_poly = poly.is_none_or(|p| inside(p, f64::from(gx) + 0.5, f64::from(gy) + 0.5));
            if in_core && in_poly {
                searched += 1;
            }
            if l == 0 {
                if in_core && in_poly && (x + y * 7) % 5 == 0 {
                    for (k, m) in data.measured.iter().enumerate() {
                        bg_samples[k].push(m[i]);
                    }
                }
                continue;
            }
            let l = l as usize;
            if first[l] == usize::MAX {
                first[l] = i;
            }
            let e = &mut a[l];
            e.n += 1;
            e.sx += x as f64;
            e.sy += y as f64;
            for (k, m) in data.measured.iter().enumerate() {
                e.sums[k] += f64::from(m[i]);
            }
            // the object touches the edge of what is searched
            e.edge |= gx == r.x
                || gy == r.y
                || gx + 1 == r.x + r.width
                || gy + 1 == r.y + r.height
                || poly.is_some() && !in_poly;
            let (fx, fy) = (gx as f64, gy as f64);
            let at_rim = x == 0
                || y == 0
                || x + 1 == w
                || y + 1 == h
                || lab[i - 1] != lab[i]
                || lab[i + 1] != lab[i]
                || lab[i - w] != lab[i]
                || lab[i + w] != lab[i];
            if at_rim {
                e.hull.extend([
                    [fx, fy],
                    [fx + 1.0, fy],
                    [fx, fy + 1.0],
                    [fx + 1.0, fy + 1.0],
                ]);
            }
        }
        for (l, e) in a.iter_mut().enumerate().skip(1) {
            if e.n == 0 {
                continue;
            }
            let (cx, cy) = (
                f64::from(t.read.x) + e.sx / e.n as f64 + 0.5,
                f64::from(t.read.y) + e.sy / e.n as f64 + 0.5,
            );
            // each object belongs to the tile whose core holds its centroid
            if !t.core.contains_px(cx as u32, cy as u32) {
                continue;
            }
            if poly.is_some_and(|p| !inside(p, cx, cy)) {
                continue;
            }
            if (e.n as usize) > plan.max_area {
                continue;
            }
            // cut by the tile margin (not the area's edge): the margin is two diameters wide,
            // so this only happens to very large objects
            covered += e.n;
            e.sx = cx;
            e.sy = cy;
            e.height = heights.get(l - 1).map(|h| f64::from(*h));
            if o.outlines {
                // labels found on a shrunken copy have block-sized steps: smooth them away
                let block = working_factor(&plan);
                let mut ol = sg::outline(&lab, w, h, l as u32, first[l], 0.4 + 0.6 * block as f64);
                if block > 1 {
                    ol = sg::chaikin(&ol, 2);
                }
                for p in &mut ol {
                    p[0] += f64::from(t.read.x);
                    p[1] += f64::from(t.read.y);
                }
                e.outline = ol;
            }
            accs.push(std::mem::take(e));
        }
    }
    // reading order: rows of about one object height, then left to right
    let band = d.max(1.0);
    accs.sort_by(|a, b| {
        ((a.sy / band).floor())
            .total_cmp(&(b.sy / band).floor())
            .then(a.sx.total_cmp(&b.sx))
    });
    let stained = rgb && (signal.dark || signal.deconvolved());
    let channels_meta: Vec<(u32, Option<String>)> = if stained {
        vec![
            (0, Some("hematoxylin".into())),
            (1, Some("eosin".into())),
            (2, Some("dab".into())),
        ]
    } else if rgb {
        vec![
            (0, Some("R".into())),
            (1, Some("G".into())),
            (2, Some("B".into())),
        ]
    } else {
        all_channels
            .iter()
            .map(|c| (*c, channel_label(tg, *c)))
            .collect()
    };
    let mut all: Vec<Object> = accs
        .into_iter()
        .enumerate()
        .map(|(i, mut e)| {
            let solidity = (o.kind != Kind::Spots)
                .then(|| {
                    let hull = sg::hull_area(&mut e.hull);
                    (hull > 0.0).then(|| (e.n as f64 / hull).min(1.0))
                })
                .flatten();
            let area_um2 = area_px_um2.map(|a| e.n as f64 * a);
            Object {
                id: i as u32 + 1,
                x: (e.sx * 10.0).round() / 10.0,
                y: (e.sy * 10.0).round() / 10.0,
                area_px: e.n,
                area_um2: area_um2.map(round4),
                diameter_um: area_um2.map(|a| round4(2.0 * (a / std::f64::consts::PI).sqrt())),
                solidity: solidity.map(|s| (s * 100.0).round() / 100.0),
                height: e.height.map(round4),
                mean: e.sums.iter().map(|s| round4(s / e.n as f64)).collect(),
                edge: e.edge,
                outline: e.outline,
            }
        })
        .collect();
    let count = all.len();
    let touching = all.iter().filter(|o| o.edge).count();
    let inner: Vec<&Object> = if touching < count {
        all.iter().filter(|o| !o.edge).collect()
    } else {
        all.iter().collect()
    };
    let areas: Vec<f64> = inner.iter().map(|o| o.area_px as f64).collect();
    let area_px = spread(areas.clone());
    let med = area_px.as_ref().map_or(0.0, |s| s.median);
    let large = if o.kind == Kind::Spots {
        0
    } else {
        all.iter().filter(|o| o.area_px as f64 > 2.0 * med).count()
    };
    let area_um2 = area_px_um2.and_then(|a| spread(areas.iter().map(|x| x * a).collect()));
    let diameter_um_spread = area_px_um2.and_then(|a| {
        spread(
            areas
                .iter()
                .map(|x| 2.0 * (x * a / std::f64::consts::PI).sqrt())
                .collect(),
        )
    });
    let searched_um2 = area_px_um2.map(|a| searched as f64 * a);
    let density = searched_um2
        .filter(|a| *a > 0.0)
        .map(|a| round4((count as f64 - touching as f64 / 2.0) / (a / 1e6)));
    let channels = channels_meta
        .into_iter()
        .enumerate()
        .map(|(k, (c, name))| {
            let means: Vec<f64> = all.iter().map(|o| o.mean[k]).collect();
            let bg = &bg_samples[k];
            let background = sg::quantile(bg, 0.5).map_or(f64::NAN, f64::from);
            // positive calls for markers: other channels than the one counted, and DAB
            let marker = if stained { k == 2 } else { rgb || c != counted };
            let positive = marker.then(|| positive(&means, bg)).flatten();
            ObjectChannel {
                c,
                name,
                background: round4(background),
                mean: spread(means).map(round_spread),
                positive,
            }
        })
        .collect();
    // say when the objects do not look like what was asked for
    let shapes: Vec<(f64, f64)> = all
        .iter()
        .map(|o| (o.area_px as f64, o.solidity.unwrap_or(1.0)))
        .collect();
    let (fit, doubt) = assess(o.kind, &shapes, d, searched as f64);
    let fit = fit.map(round4);
    let confidence = if doubt.is_some() {
        CountConfidence::Low
    } else {
        CountConfidence::High
    };
    if let Some(doubt) = doubt {
        notes.push(doubt.note(count, d, o.kind));
    } else if o.kind != Kind::Spots && count >= 10 {
        let mut sol: Vec<f64> = all.iter().filter_map(|o| o.solidity).collect();
        let irregular = median(&mut sol).is_some_and(|s| s < 0.8);
        if large * 4 > count || irregular {
            notes.push(format!(
                "{} of {count} objects are over twice the median size{}: touching objects were not all separated, or the stain marks more than {}; check a picture (preview marks=objects) and set diameter_um or another channel or stain",
                large,
                if irregular { " and most are irregular" } else { "" },
                kind_name(o.kind)
            ));
        }
    }
    if count == 0 {
        notes.push(format!(
            "no {} found above the threshold; check a picture, or set diameter_um, threshold or polarity",
            kind_name(o.kind)
        ));
    }
    let max_list = o.max_objects.unwrap_or(DEFAULT_MAX_OBJECTS);
    let truncated = count > max_list;
    all.truncate(max_list);
    let d_um = pixel_um.map(|p| round4(d * p));
    Ok(Objects {
        kind: o.kind,
        measured,
        region: r,
        searched_um2: searched_um2.map(round4),
        expected_diameter_px: round4(d),
        expected_diameter_um: d_um,
        expected_diameter_from: from.into(),
        polarity: if signal.dark || signal.deconvolved() {
            Polarity::Dark
        } else {
            Polarity::Bright
        },
        threshold: round4(f64::from(plan.threshold)),
        threshold_method: method_name,
        split: plan.split,
        count,
        confidence,
        fit,
        touching_edge: touching,
        density_per_mm2: density,
        area_fraction: round4(covered as f64 / searched.max(1) as f64),
        large,
        area_px: area_px.map(round_spread),
        area_um2: area_um2.map(round_spread),
        diameter_um: diameter_um_spread.map(round_spread),
        channels,
        objects: all,
        truncated,
    })
}

fn round4(v: f64) -> f64 {
    if !v.is_finite() || v == 0.0 {
        return v;
    }
    let d = 4 - 1 - v.abs().log10().floor() as i32;
    if d <= 0 {
        return v.round();
    }
    let m = 10f64.powi(d.min(12));
    (v * m).round() / m
}

fn round_spread(s: Spread) -> Spread {
    Spread {
        min: round4(s.min),
        median: round4(s.median),
        mean: round4(s.mean),
        max: round4(s.max),
    }
}

/// Which objects are clearly brighter in a channel: Otsu's split of the object means when they
/// fall in two well-separated groups, else those above the background by five robust
/// standard deviations of the background (and at least a tenth of the way to the brightest
/// objects, for backgrounds without noise).
fn positive(means: &[f64], bg: &[f32]) -> Option<Positive> {
    if means.is_empty() {
        return None;
    }
    let m32: Vec<f32> = means.iter().map(|v| *v as f32).collect();
    let bg_med = sg::quantile(bg, 0.5)?;
    let dev: Vec<f32> = bg.iter().map(|v| (v - bg_med).abs()).collect();
    let bg_sd = 1.4826 * sg::quantile(&dev, 0.5)?;
    let top = sg::quantile(&m32, 0.95)?;
    let floor = f64::from(bg_med + (5.0 * bg_sd).max(0.1 * (top - bg_med)).max(f32::EPSILON));
    let (threshold, method) = match sg::otsu(&m32) {
        // two groups, the upper one above the background
        Some((t, sep)) if sep >= 0.75 && means.len() >= 8 && f64::from(t) > floor => {
            (f64::from(t), "otsu")
        }
        _ => (floor, "background"),
    };
    let count = means.iter().filter(|m| **m > threshold).count();
    Some(Positive {
        threshold: round4(threshold),
        method: if count == 0 {
            "none".into()
        } else {
            method.into()
        },
        count,
        fraction: round4(count as f64 / means.len() as f64),
    })
}

/// Read the counted channel and every measured channel of one tile.
fn tile_data(
    ds: &mut dyn crate::reader::Dataset,
    tg: &Target<'_>,
    level: u32,
    c: u32,
    all: &[u32],
    r: Region,
    signal: &Signal,
) -> Result<TileData> {
    let g = read(ds, tg, level, c, r)?;
    let comps = grid_f32(&g);
    let measured = if comps.len() >= 3 {
        if signal.dark
            || matches!(
                signal.stain,
                Some(Stain::Hematoxylin | Stain::Eosin | Stain::Dab)
            )
        {
            let i0 = if signal.i0.iter().all(|v| *v <= 0.0) {
                [255.0; 3]
            } else {
                signal.i0
            };
            stains(&comps, i0).to_vec()
        } else {
            comps.iter().take(3).cloned().collect()
        }
    } else {
        let mut m = Vec::with_capacity(all.len());
        for &k in all {
            if k == c {
                m.push(comps[0].clone());
            } else {
                m.push(grid_f32(&read(ds, tg, level, k, r)?).swap_remove(0));
            }
        }
        m
    };
    Ok(TileData { comps, measured })
}

/// Largest spot diameter in pixels: spots are small, and the Laplacian of Gaussian that finds
/// them costs about the diameter per pixel.
const MAX_SPOT_PX: f64 = 64.0;

/// Check the numbers of a request before anything is read: each must be a finite number, and
/// sizes positive.
pub(crate) fn validate(o: &ObjectsRequest) -> Result<()> {
    let positive = [
        ("diameter_um", o.diameter_um),
        ("diameter_px", o.diameter_px),
        ("min_area_um2", o.min_area_um2),
        ("max_area_um2", o.max_area_um2),
    ];
    for (name, v) in positive {
        if let Some(v) = v
            && !(v.is_finite() && v > 0.0)
        {
            return Err(usage(format!(
                "{name} must be a positive number (got {v}); leave it out for the default"
            )));
        }
    }
    if let Some(t) = o.threshold
        && !(t.is_finite() && t.abs() < f64::from(f32::MAX))
    {
        return Err(usage(format!(
            "threshold must be a finite number (got {t}); leave it out to choose one from the image"
        )));
    }
    if let (Some(lo), Some(hi)) = (o.min_area_um2, o.max_area_um2)
        && hi < lo
    {
        return Err(usage(format!(
            "max_area_um2 ({hi}) is below min_area_um2 ({lo}): no object could be kept"
        )));
    }
    Ok(())
}

/// The largest diameter (pixels) objects of `kind` can have in an area of `w × h` pixels.
fn largest_diameter(kind: Kind, w: usize, h: usize) -> f64 {
    let side = w.min(h).max(1) as f64;
    if kind == Kind::Spots {
        side.min(MAX_SPOT_PX)
    } else {
        side
    }
}

/// The expected diameter in pixels and where it came from. `area` is the whole area searched
/// and `probe` the part of it in `s`.
fn diameter(
    o: &ObjectsRequest,
    s: &[f32],
    probe: Region,
    area: Region,
    pixel_um: Option<f64>,
    signal: &Signal,
    notes: &mut Vec<String>,
) -> Result<(f64, &'static str)> {
    let cap = largest_diameter(o.kind, area.width as usize, area.height as usize);
    let given = |d: f64, what: &str| -> Result<(f64, &'static str)> {
        if d <= cap {
            return Ok((d, "given"));
        }
        Err(usage(if o.kind == Kind::Spots && cap == MAX_SPOT_PX {
            format!(
                "{what} makes spots {d:.0} px across; spots are at most {MAX_SPOT_PX} px: for larger objects use kind=nuclei or cells, or read a coarser level"
            )
        } else {
            format!(
                "{what} makes objects {d:.0} px across, more than the area searched ({} x {} px) holds: give a smaller diameter or a larger region",
                area.width, area.height
            )
        }))
    };
    if let Some(d) = o.diameter_um {
        let Some(p) = pixel_um else {
            return Err(usage(
                "diameter_um needs the pixel size, which this image does not record; give diameter_px instead",
            ));
        };
        return given(d / p, "diameter_um");
    }
    if let Some(d) = o.diameter_px {
        return given(d, "diameter_px");
    }
    // a default from the pixel size: a wrong pixel size must not make it absurd
    let derived = |d: f64, notes: &mut Vec<String>| -> f64 {
        if d <= cap {
            return d;
        }
        notes.push(format!(
            "the recorded pixel size ({} µm) makes typical {} {d:.0} px across, more than the area searched allows; used {cap:.0} px (set diameter_px if the pixel size is wrong)",
            pixel_um.map_or_else(String::new, |p| format!("{p:.3e}")),
            kind_name(o.kind)
        ));
        cap
    };
    // typical sizes and the range a measurement may fall in, in µm
    let (typical, lo, hi) = match o.kind {
        Kind::Nuclei => (10.0, 3.0, 30.0),
        Kind::Cells => (20.0, 6.0, 150.0),
        Kind::Spots => (0.5, 0.1, 3.0),
    };
    if o.kind == Kind::Spots {
        return Ok(match pixel_um {
            Some(p) => (derived((typical / p).max(2.0), notes), "default"),
            None => (3.0f64.min(cap), "default"),
        });
    }
    let (w, h) = (probe.width as usize, probe.height as usize);
    let (range, typical_px) = match pixel_um {
        Some(p) => ((lo / p, hi / p), Some(typical / p)),
        None => ((0.0, f64::INFINITY), None),
    };
    match (
        measure_diameter(s, w, h, o.kind, signal, range, typical_px),
        pixel_um,
    ) {
        (Some((d, false)), _) => Ok((d, "measured")),
        (Some((d, true)), _) => Ok((derived(d, notes), "default")),
        (None, Some(p)) => {
            notes.push(format!(
                "could not measure the {} in the image; used the typical {typical} µm (set diameter_um to override)",
                kind_name(o.kind)
            ));
            Ok((derived(typical / p, notes), "default"))
        }
        (None, None) => {
            notes.push("could not measure the object size and the image has no pixel size; used 20 px (set diameter_px)".into());
            Ok((20f64.min(cap), "default"))
        }
    }
}

fn kind_name(k: Kind) -> &'static str {
    match k {
        Kind::Nuclei => "nuclei",
        Kind::Cells => "cells",
        Kind::Spots => "spots",
    }
}

/// The tile at the centre of `r` (all of `r` when it is counted in one piece).
fn centre_tile(r: Region) -> Region {
    if u64::from(r.width) * u64::from(r.height) <= ONE_PIECE {
        return r;
    }
    let w = r.width.min(TILE);
    let h = r.height.min(TILE);
    Region::new(r.x + (r.width - w) / 2, r.y + (r.height - h) / 2, w, h)
}

/// One tile: the core it owns and the larger rectangle read around it.
#[derive(Debug, Clone, Copy)]
struct Tile {
    core: Region,
    read: Region,
}

impl Tile {
    /// The core in the coordinates of the rectangle read.
    fn core_in_read(&self) -> Region {
        Region::new(
            self.core.x - self.read.x,
            self.core.y - self.read.y,
            self.core.width,
            self.core.height,
        )
    }
}

trait ContainsPx {
    fn contains_px(&self, x: u32, y: u32) -> bool;
}

impl ContainsPx for Region {
    fn contains_px(&self, x: u32, y: u32) -> bool {
        x >= self.x && y >= self.y && x - self.x < self.width && y - self.y < self.height
    }
}

/// Split `r` into tiles: one when it holds at most [`ONE_PIECE`] pixels, else cores of
/// [`TILE`] pixels a side, each read with a margin of three object diameters (clipped to `r`)
/// so that the objects a core owns are found as they would be in one piece.
fn tiles(r: Region, d: f64) -> Vec<Tile> {
    if u64::from(r.width) * u64::from(r.height) <= ONE_PIECE {
        return vec![Tile { core: r, read: r }];
    }
    let m = (3.0 * d).ceil().clamp(16.0, 1024.0) as u32;
    let mut out = Vec::new();
    let mut y = r.y;
    while y < r.y + r.height {
        let th = TILE.min(r.y + r.height - y);
        let mut x = r.x;
        while x < r.x + r.width {
            let tw = TILE.min(r.x + r.width - x);
            let core = Region::new(x, y, tw, th);
            let rx0 = x.saturating_sub(m).max(r.x);
            let ry0 = y.saturating_sub(m).max(r.y);
            let rx1 = (x + tw + m).min(r.x + r.width);
            let ry1 = (y + th + m).min(r.y + r.height);
            out.push(Tile {
                core,
                read: Region::new(rx0, ry0, rx1 - rx0, ry1 - ry0),
            });
            x += tw;
        }
        y += th;
    }
    out
}

/// Label a plane held in memory: `comps` one plane (or three RGB components), `w × h`, with
/// the pixel size in µm when known. For tests and evaluation against annotated images: the
/// label image (objects 1, 2, …; 0 = background), the expected diameter used, in pixels, the
/// objects' fit and the count's confidence (see `Objects::fit` and `Objects::confidence`).
#[doc(hidden)]
pub fn label_plane(
    comps: &[Vec<f32>],
    w: usize,
    h: usize,
    pixel_um: Option<f64>,
    o: &ObjectsRequest,
) -> Result<(Vec<u32>, f64, f64, CountConfidence)> {
    if comps.is_empty() || w == 0 || h == 0 || comps.iter().any(|c| c.len() != w * h) {
        return Err(usage("label_plane: each component needs w × h values"));
    }
    validate(o)?;
    let mut notes = Vec::new();
    let (signal, _) = signal_for(comps, o, &mut notes)?;
    let s = signal.of(comps);
    let background = !signal.deconvolved();
    let full = Region::full(w as u32, h as u32);
    let (d, _) = diameter(o, &s, full, full, pixel_um, &signal, &mut notes)?;
    let mut plan = Plan::new(o.kind, d, background, o.method);
    plan.split &= o.split.unwrap_or(true);
    plan.threshold = if let Some(t) = o.threshold {
        t as f32
    } else {
        let (ws, sw, _, k) = working(&s, w, h, &plan);
        let f = scaled(&plan, k).flatten(&ws, sw, ws.len() / sw.max(1));
        settle_threshold(&s, w, h, &plan, &f).ok_or_else(flat)?.0
    };
    let lab = label_tile(&s, w, h, &plan).0;
    let (f, doubt) = assess(o.kind, &shapes(&lab, w, h), d, (w * h) as f64);
    let confidence = if doubt.is_some() {
        CountConfidence::Low
    } else {
        CountConfidence::High
    };
    Ok((lab, d, f.unwrap_or(0.0), confidence))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::measure::{MeasureRequest, measure};
    use crate::model::{ChannelInfo, CheckReport, FileInfo, ImageInfo, LsEntry, PhysicalSize};
    use crate::pixel::Plane;
    use crate::reader::{Dataset, PlaneIndex};
    use crate::{PixelType, ProvenanceMap};

    /// A small random-number generator for reproducible noise.
    struct Lcg(u64);
    impl Lcg {
        fn next(&mut self) -> f32 {
            self.0 = self
                .0
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            ((self.0 >> 40) as f32) / (1u64 << 24) as f32 - 0.5
        }
    }

    /// A `w × h` plane with discs `(cx, cy, r, value)` on `background`, plus noise.
    fn discs(
        w: usize,
        h: usize,
        d: &[(f32, f32, f32, f32)],
        background: f32,
        noise: f32,
    ) -> Vec<f32> {
        let mut rng = Lcg(7);
        (0..w * h)
            .map(|i| {
                let (x, y) = ((i % w) as f32 + 0.5, (i / w) as f32 + 0.5);
                let mut v = background;
                for &(cx, cy, r, val) in d {
                    if (x - cx).hypot(y - cy) <= r {
                        v = val;
                    }
                }
                v + noise * rng.next()
            })
            .collect()
    }

    fn count(lab: &[u32]) -> usize {
        let mut v: Vec<u32> = lab.iter().copied().filter(|l| *l > 0).collect();
        v.sort_unstable();
        v.dedup();
        v.len()
    }

    /// Nine nuclei of radius 10: a separate grid of six, and a chain of three that touch.
    fn nuclei() -> Vec<(f32, f32, f32, f32)> {
        let mut d = Vec::new();
        for (i, cx) in [30.0, 80.0, 130.0].into_iter().enumerate() {
            d.push((cx, 30.0, 10.0, 200.0 + 20.0 * i as f32));
            d.push((cx, 80.0, 10.0, 150.0));
        }
        d.push((40.0, 140.0, 10.0, 180.0));
        d.push((59.0, 140.0, 10.0, 190.0));
        d.push((78.0, 141.0, 10.0, 170.0));
        d
    }

    #[test]
    fn counts_and_splits_bright_nuclei() {
        let (w, h) = (180, 180);
        let plane = discs(w, h, &nuclei(), 20.0, 10.0);
        for o in [
            ObjectsRequest::default(),
            ObjectsRequest {
                diameter_px: Some(20.0),
                ..ObjectsRequest::default()
            },
        ] {
            let (lab, d, _, _) = label_plane(std::slice::from_ref(&plane), w, h, None, &o).unwrap();
            assert!((12.0..30.0).contains(&d), "{d}");
            assert_eq!(count(&lab), 9, "diameter {d}");
        }
        // kept together without the watershed
        let o = ObjectsRequest {
            diameter_px: Some(20.0),
            split: Some(false),
            ..ObjectsRequest::default()
        };
        assert_eq!(count(&label_plane(&[plane], w, h, None, &o).unwrap().0), 7);
    }

    #[test]
    fn finds_dark_nuclei_on_a_bright_background() {
        let (w, h) = (180, 180);
        let d: Vec<_> = nuclei()
            .into_iter()
            .map(|(x, y, r, v)| (x, y, r, 250.0 - v))
            .collect();
        let plane = discs(w, h, &d, 230.0, 8.0);
        let (lab, _, _, _) = label_plane(&[plane], w, h, None, &ObjectsRequest::default()).unwrap();
        assert_eq!(count(&lab), 9);
    }

    #[test]
    fn finds_hematoxylin_nuclei_in_stained_tissue() {
        // pink (eosin) tissue with purple (hematoxylin) nuclei, on glass at the top
        let (w, h) = (180, 180);
        let mut r = vec![0f32; w * h];
        let mut g = vec![0f32; w * h];
        let mut b = vec![0f32; w * h];
        let inside = discs(
            w,
            h,
            &nuclei()
                .iter()
                .map(|n| (n.0, n.1, n.2, 1.0))
                .collect::<Vec<_>>(),
            0.0,
            0.0,
        );
        let mut rng = Lcg(3);
        for i in 0..w * h {
            let (cr, cg, cb) = if i / w < 8 {
                (245.0, 245.0, 245.0)
            } else if inside[i] > 0.5 {
                (90.0, 60.0, 150.0)
            } else {
                (235.0, 150.0, 200.0)
            };
            r[i] = cr + 6.0 * rng.next();
            g[i] = cg + 6.0 * rng.next();
            b[i] = cb + 6.0 * rng.next();
        }
        let o = ObjectsRequest::default();
        let mut notes = Vec::new();
        let (sig, name) = signal_for(&[r.clone(), g.clone(), b.clone()], &o, &mut notes).unwrap();
        assert_eq!(name, "hematoxylin");
        assert!(notes.is_empty(), "{notes:?}");
        assert!(sig.deconvolved());
        let (lab, _, _, _) = label_plane(&[r, g, b], w, h, None, &o).unwrap();
        assert_eq!(count(&lab), 9);
    }

    #[test]
    fn finds_spots_above_the_noise() {
        let (w, h) = (120, 120);
        let mut d = Vec::new();
        for i in 0..5 {
            for j in 0..4 {
                d.push((15.0 + 22.0 * i as f32, 15.0 + 28.0 * j as f32, 1.5, 300.0));
            }
        }
        let plane = discs(w, h, &d, 100.0, 20.0);
        let o = ObjectsRequest {
            kind: Kind::Spots,
            ..ObjectsRequest::default()
        };
        let (lab, _, _, _) = label_plane(&[plane], w, h, None, &o).unwrap();
        assert_eq!(count(&lab), 20);
    }

    /// Nuclei like DAPI at high magnification: discs `(cx, cy, r)` of a middle level with
    /// bright chromocentres scattered inside and a dark band of chromatin across each, on a
    /// dark background with noise. `gap` puts a dark line along `x = gap` (between two
    /// touching nuclei), at the background level.
    fn textured(w: usize, h: usize, nuclei: &[(f32, f32, f32)], gap: Option<f32>) -> Vec<f32> {
        let mut rng = Lcg(11);
        // chromocentres: offsets within the unit disc, the same pattern in every nucleus
        let spots: Vec<(f32, f32)> = (0..40)
            .map(|_| (1.6 * rng.next(), 1.6 * rng.next()))
            .filter(|(x, y)| x.hypot(*y) < 0.8)
            .collect();
        (0..w * h)
            .map(|i| {
                let (x, y) = ((i % w) as f32 + 0.5, (i / w) as f32 + 0.5);
                let mut v = 20.0;
                for (k, &(cx, cy, r)) in nuclei.iter().enumerate() {
                    if (x - cx).hypot(y - cy) > r {
                        continue;
                    }
                    v = 120.0;
                    if spots
                        .iter()
                        .any(|(sx, sy)| (x - cx - sx * r).hypot(y - cy - sy * r) < 0.1 * r)
                    {
                        v = 240.0;
                    }
                    // a dark band through the middle, at a different angle in each nucleus
                    let a = 0.7 * k as f32;
                    if ((x - cx) * a.sin() - (y - cy) * a.cos()).abs() < 0.05 * r {
                        v = 60.0;
                    }
                }
                if gap.is_some_and(|g| (x - g).abs() < 1.5) && v > 20.0 {
                    v = 25.0;
                }
                v + 8.0 * rng.next()
            })
            .collect()
    }

    #[test]
    fn texture_does_not_cut_nuclei() {
        // six separate textured nuclei, 60 px across
        let (w, h) = (300, 200);
        let mut n = Vec::new();
        for cx in [50.0, 150.0, 250.0] {
            for cy in [50.0, 150.0] {
                n.push((cx, cy, 30.0));
            }
        }
        let plane = textured(w, h, &n, None);
        for o in [
            ObjectsRequest::default(),
            ObjectsRequest {
                diameter_px: Some(60.0),
                ..ObjectsRequest::default()
            },
        ] {
            let (lab, d, _, _) = label_plane(std::slice::from_ref(&plane), w, h, None, &o).unwrap();
            assert_eq!(count(&lab), 6, "diameter {d}");
        }
    }

    #[test]
    fn touching_textured_nuclei_are_cut_apart() {
        // two pairs of textured nuclei: one pair touches along a dark gap, the other
        // overlaps at a narrow waist
        let (w, h) = (300, 200);
        let n = [
            (50.0, 60.0, 30.0),
            (108.0, 60.0, 30.0),
            (180.0, 140.0, 30.0),
            (232.0, 140.0, 30.0),
        ];
        let plane = textured(w, h, &n, Some(79.0));
        let o = ObjectsRequest {
            diameter_px: Some(60.0),
            ..ObjectsRequest::default()
        };
        let (lab, _, _, _) = label_plane(&[plane], w, h, None, &o).unwrap();
        assert_eq!(count(&lab), 4);
        // each nucleus is one object, apart from its partner
        let at = |x: usize, y: usize| lab[y * w + x];
        for (a, b) in [((50, 60), (108, 60)), ((180, 140), (232, 140))] {
            assert_ne!(at(a.0, a.1), 0);
            assert_ne!(at(a.0, a.1), at(b.0, b.1));
        }
    }

    #[test]
    fn irregular_objects_have_low_fit() {
        // thin streaks, nothing like round nuclei of the size asked for
        let (w, h) = (160, 160);
        let plane: Vec<f32> = (0..w * h)
            .map(|i| if (i % w) % 16 < 2 { 200.0 } else { 10.0 })
            .collect();
        let o = ObjectsRequest {
            diameter_px: Some(12.0),
            ..ObjectsRequest::default()
        };
        let (_, _, f, c) = label_plane(&[plane], w, h, None, &o).unwrap();
        assert!(f < LOW_FIT, "{f}");
        assert_eq!(c, CountConfidence::Low);
    }

    /// `n` discs of radius `r` in a row across the middle of a `w × w` plane, `height` above a
    /// background of 100 with noise of standard deviation about 10.
    fn sparse(w: usize, n: usize, r: f32, height: f32) -> Vec<f32> {
        let d: Vec<_> = (0..n)
            .map(|i| (100.0 + 180.0 * i as f32, w as f32 / 2.0, r, 100.0 + height))
            .collect();
        discs(w, w, &d, 100.0, 35.0)
    }

    #[test]
    fn sparse_objects_on_noise_are_counted() {
        // five 12 px nuclei cover 0.05% of a noisy 1024 × 1024 plane: Otsu's threshold on the
        // usual histogram range split the noise (34 to 38 000 objects)
        let w = 1024;
        let plane = sparse(w, 5, 6.0, 1000.0);
        for method in [
            ThresholdMethod::Auto,
            ThresholdMethod::Otsu,
            ThresholdMethod::Triangle,
        ] {
            let o = ObjectsRequest {
                diameter_px: Some(12.0),
                method,
                ..ObjectsRequest::default()
            };
            let (lab, _, _, c) = label_plane(std::slice::from_ref(&plane), w, w, None, &o).unwrap();
            assert_eq!(count(&lab), 5, "{method:?}");
            assert_eq!(c, CountConfidence::High, "{method:?}");
        }
        let (lab, d, _, _) = label_plane(
            std::slice::from_ref(&plane),
            w,
            w,
            None,
            &ObjectsRequest::default(),
        )
        .unwrap();
        assert_eq!(count(&lab), 5, "measured diameter {d}");
        // one nucleus on a clean, zero background
        let one = discs(512, 512, &[(256.0, 256.0, 5.0, 1000.0)], 0.0, 0.0);
        let o = ObjectsRequest {
            diameter_px: Some(10.0),
            ..ObjectsRequest::default()
        };
        let (lab, _, _, _) = label_plane(&[one], 512, 512, None, &o).unwrap();
        assert_eq!(count(&lab), 1);
        // noise alone: whatever is found has low confidence
        let noise = discs(512, 512, &[], 100.0, 35.0);
        let (lab, _, _, c) = label_plane(&[noise], 512, 512, None, &o).unwrap();
        assert!(
            count(&lab) <= 1 || c == CountConfidence::Low,
            "{}",
            count(&lab)
        );
    }

    #[test]
    fn a_threshold_inside_the_noise_has_low_confidence() {
        let w = 512;
        let plane = sparse(w, 2, 6.0, 1000.0);
        let o = ObjectsRequest {
            diameter_px: Some(12.0),
            threshold: Some(0.0),
            ..ObjectsRequest::default()
        };
        let (lab, _, _, c) = label_plane(&[plane], w, w, None, &o).unwrap();
        assert!(count(&lab) > 10, "{}", count(&lab));
        assert_eq!(c, CountConfidence::Low);
        // the reasons, from object sizes and solidities
        let specks = vec![(35.0, 0.9); 20];
        assert_eq!(
            assess(Kind::Nuclei, &specks, 12.0, 1e6).1,
            Some(Doubt::Specks)
        );
        let crowded = vec![(113.0, 0.95); 100];
        assert_eq!(
            assess(Kind::Nuclei, &crowded, 12.0, 5000.0).1,
            Some(Doubt::Crowded)
        );
        assert_eq!(assess(Kind::Nuclei, &crowded, 12.0, 1e6).1, None);
    }

    #[test]
    fn object_options_must_be_finite_and_positive() {
        let plane = discs(64, 64, &[(32.0, 32.0, 6.0, 100.0)], 0.0, 1.0);
        let bad = [
            ObjectsRequest {
                diameter_px: Some(f64::NAN),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                diameter_px: Some(-3.0),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                max_area_um2: Some(f64::NAN),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                max_area_um2: Some(0.0),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                min_area_um2: Some(f64::INFINITY),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                min_area_um2: Some(50.0),
                max_area_um2: Some(10.0),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                threshold: Some(f64::NAN),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                threshold: Some(1e300),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                diameter_um: Some(f64::NEG_INFINITY),
                ..ObjectsRequest::default()
            },
        ];
        for o in bad {
            let e = label_plane(std::slice::from_ref(&plane), 64, 64, Some(0.5), &o).unwrap_err();
            assert!(matches!(e, Error::Usage(_)), "{o:?} {e}");
        }
        // through measure: a max area under the smallest object kept would count nothing
        let mut ds = TwoChannels::new();
        let info = ds.info().unwrap();
        let req = MeasureRequest {
            objects: Some(ObjectsRequest {
                max_area_um2: Some(0.01),
                ..ObjectsRequest::default()
            }),
            ..MeasureRequest::default()
        };
        assert!(matches!(
            measure(&mut ds, &info, &req).unwrap_err(),
            Error::Usage(_)
        ));
    }

    #[test]
    fn huge_diameters_are_refused_or_capped_quickly() {
        let plane = discs(64, 64, &[(32.0, 32.0, 2.0, 1000.0)], 0.0, 1.0);
        for kind in [Kind::Spots, Kind::Nuclei, Kind::Cells] {
            for d in [65.0, 500.0, 2000.0, 1e13, f64::MAX] {
                let o = ObjectsRequest {
                    kind,
                    diameter_px: Some(d),
                    ..ObjectsRequest::default()
                };
                let t = std::time::Instant::now();
                let e = label_plane(std::slice::from_ref(&plane), 64, 64, None, &o).unwrap_err();
                assert!(matches!(e, Error::Usage(_)), "{kind:?} {d} {e}");
                assert!(t.elapsed().as_secs() < 5);
            }
        }
        // spots are at most 64 px across, whatever the area
        let big = discs(300, 300, &[(150.0, 150.0, 2.0, 1000.0)], 0.0, 1.0);
        let o = ObjectsRequest {
            kind: Kind::Spots,
            diameter_px: Some(100.0),
            ..ObjectsRequest::default()
        };
        assert!(label_plane(std::slice::from_ref(&big), 300, 300, None, &o).is_err());
        // a default from an absurd pixel size is capped
        for (kind, p) in [
            (Kind::Spots, 1e-9),
            (Kind::Nuclei, 1e-9),
            (Kind::Spots, 1e9),
            (Kind::Nuclei, 1e9),
        ] {
            let o = ObjectsRequest {
                kind,
                ..ObjectsRequest::default()
            };
            let t = std::time::Instant::now();
            let r = label_plane(std::slice::from_ref(&big), 300, 300, Some(p), &o);
            if let Ok((_, d, _, _)) = r {
                assert!(d <= 300.0, "{kind:?} {p} {d}");
            }
            assert!(t.elapsed().as_secs() < 20, "{kind:?} {p}");
        }
        // the shrink factor of an enormous plan stays bounded
        let p = Plan::new(Kind::Nuclei, 1e13, true, ThresholdMethod::Auto);
        let q = scaled(&p, working_factor(&p));
        assert!(q.min_area >= 1);
    }

    #[test]
    fn odd_planes_fail_cleanly() {
        let kinds = [
            ObjectsRequest::default(),
            ObjectsRequest {
                kind: Kind::Spots,
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                diameter_px: Some(2.0),
                ..ObjectsRequest::default()
            },
            ObjectsRequest {
                method: ThresholdMethod::Local,
                ..ObjectsRequest::default()
            },
        ];
        for (w, h) in [(1, 1000), (1000, 1), (1, 1), (2, 2), (3, 300), (5, 5)] {
            let ramp: Vec<f32> = (0..w * h).map(|i| (i % 7) as f32).collect();
            let nan = vec![f32::NAN; w * h];
            let inf = vec![f32::INFINITY; w * h];
            let mixed: Vec<f32> = ramp
                .iter()
                .enumerate()
                .map(|(i, v)| match i % 3 {
                    0 => f32::NAN,
                    1 => f32::NEG_INFINITY,
                    _ => *v,
                })
                .collect();
            for plane in [ramp, nan, inf, mixed] {
                for o in &kinds {
                    // an answer or a clean error, never a panic
                    let _ = label_plane(std::slice::from_ref(&plane), w, h, None, o);
                }
            }
        }
    }

    #[test]
    fn flat_and_tiny_planes_fail_cleanly() {
        let o = ObjectsRequest::default();
        assert!(label_plane(&[vec![5.0; 100]], 10, 10, None, &o).is_err());
        assert!(label_plane(&[vec![1.0]], 1, 1, None, &o).is_err());
        assert!(label_plane(&[vec![1.0; 3]], 2, 2, None, &o).is_err());
        assert!(label_plane(&[], 0, 0, None, &o).is_err());
        let mut nan = discs(40, 40, &[(20.0, 20.0, 6.0, 100.0)], 0.0, 1.0);
        nan[5] = f32::NAN;
        let _ = label_plane(&[nan], 40, 40, None, &o);
    }

    #[test]
    fn requests_reject_unknown_options() {
        let e = serde_json::from_str::<ObjectsRequest>(r#"{"min_area_px": 4}"#);
        assert!(e.is_err());
        let o: ObjectsRequest =
            serde_json::from_str(r#"{"kind": "spots", "diameter_um": 0.4}"#).unwrap();
        assert_eq!(o.kind, Kind::Spots);
    }

    /// Two 16-bit channels: DAPI nuclei in channel 1, a marker in half of them in channel 0.
    pub(crate) struct TwoChannels {
        pub w: usize,
        pub h: usize,
        pub planes: [Vec<f32>; 2],
    }

    impl TwoChannels {
        pub(crate) fn new() -> TwoChannels {
            let (w, h) = (180, 180);
            let n = nuclei();
            let dapi = discs(w, h, &n, 100.0, 20.0);
            let marked: Vec<_> = n
                .iter()
                .enumerate()
                .map(|(i, d)| (d.0, d.1, d.2, if i % 2 == 0 { 3000.0 } else { 200.0 }))
                .collect();
            let marker = discs(w, h, &marked, 200.0, 30.0);
            TwoChannels {
                w,
                h,
                planes: [marker, dapi],
            }
        }

        fn file_info(&self) -> FileInfo {
            let mut im = ImageInfo::new(0, self.w as u32, self.h as u32, PixelType::Uint16);
            im.size_c = 2;
            im.physical_size = PhysicalSize::micrometres(Some(0.5), Some(0.5), None);
            im.channels = vec![
                ChannelInfo {
                    index: 0,
                    name: Some("Ki67".into()),
                    ..ChannelInfo::default()
                },
                ChannelInfo {
                    index: 1,
                    name: Some("DAPI".into()),
                    ..ChannelInfo::default()
                },
            ];
            FileInfo {
                path: "two.tif".into(),
                size_bytes: 1,
                format: crate::model::FormatDescriptor {
                    id: "tiff".into(),
                    name: "TIFF".into(),
                    vendor: String::new(),
                    extensions: vec![],
                    family: "microscopy".into(),
                    can_read: true,
                    can_write: false,
                    confidence: crate::provenance::Confidence::High,
                    known_gaps: vec![],
                },
                format_version: None,
                images: vec![im.finish()],
                tables: vec![],
                spectra: vec![],
                traces: vec![],
                plane_count: 2,
                notes: vec![],
            }
        }
    }

    impl Dataset for TwoChannels {
        fn info(&self) -> Result<FileInfo> {
            Ok(self.file_info())
        }
        fn vendor_metadata(&self) -> Result<serde_json::Value> {
            Ok(serde_json::Value::Null)
        }
        fn provenance(&self) -> ProvenanceMap {
            ProvenanceMap::new()
        }
        fn entries(&self) -> Result<Vec<LsEntry>> {
            Ok(vec![])
        }
        fn read_plane(&mut self, _: u32, i: PlaneIndex) -> Result<Plane> {
            let data = self.planes[i.c as usize]
                .iter()
                .flat_map(|v| (v.clamp(0.0, 65535.0) as u16).to_le_bytes())
                .collect();
            Ok(Plane {
                width: self.w as u32,
                height: self.h as u32,
                pixel_type: PixelType::Uint16,
                samples_per_pixel: 1,
                data,
            })
        }
        fn check(&mut self) -> Result<CheckReport> {
            Ok(CheckReport::new("tiff", "two.tif"))
        }
    }

    #[test]
    fn one_call_counts_nuclei_and_marker_positive_cells() {
        let mut ds = TwoChannels::new();
        let info = ds.info().unwrap();
        let req = MeasureRequest {
            objects: Some(ObjectsRequest::default()),
            ..MeasureRequest::default()
        };
        let out = measure(&mut ds, &info, &req).unwrap();
        let o = out.objects.unwrap();
        assert_eq!(o.measured, "c=1 DAPI");
        assert_eq!(o.count, 9);
        assert_eq!(o.confidence, CountConfidence::High, "fit {:?}", o.fit);
        assert_eq!(o.objects.len(), 9);
        assert_eq!(o.channels.len(), 2);
        let ki67 = o.channels[0].positive.as_ref().unwrap();
        assert_eq!(ki67.count, 5, "{ki67:?}");
        assert!(
            o.channels[1].positive.is_none(),
            "the counted channel has no positive call"
        );
        // 10 px radius at 0.5 µm: about 10 µm across
        let d = o.diameter_um.unwrap().median;
        assert!((8.0..12.0).contains(&d), "{d}");
        assert!(o.density_per_mm2.unwrap() > 0.0);
        // numbered in reading order
        assert!(o.objects.windows(2).all(|p| p[0].y <= p[1].y + 12.0));
        // in a polygon around the top row only
        let req = MeasureRequest {
            polygon: Some(vec![[0.0, 0.0], [180.0, 0.0], [180.0, 55.0], [0.0, 55.0]]),
            objects: Some(ObjectsRequest {
                diameter_um: Some(10.0),
                ..ObjectsRequest::default()
            }),
            ..MeasureRequest::default()
        };
        let o = measure(&mut ds, &info, &req).unwrap().objects.unwrap();
        assert_eq!(o.count, 3);
        assert_eq!(o.expected_diameter_from, "given");
    }

    #[test]
    fn tiles_count_each_object_once() {
        let r = Region::new(0, 0, 5000, 3000);
        let t = tiles(r, 20.0);
        assert_eq!(t.len(), 6);
        let covered: u64 = t
            .iter()
            .map(|t| u64::from(t.core.width) * u64::from(t.core.height))
            .sum();
        assert_eq!(covered, 5000 * 3000);
        assert!(
            t.iter()
                .all(|t| t.read.x <= t.core.x && t.read.width >= t.core.width)
        );
        assert_eq!(tiles(Region::new(0, 0, 2000, 2000), 20.0).len(), 1);
    }
}