File size: 60,560 Bytes
a8e0542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared vector helpers for the geology and landform layers (the same code on Mars and Earth).

Everything here works in longitude/latitude degrees (east-positive, [-180, 180)) and measures on the
body: the Mars sphere (R = 3,396,190 m) or the WGS84 ellipsoid. The two are never mixed: every
function that measures takes a :class:`Body` (or a planet name) and nothing falls back to a default.

Contents
--------
* :func:`normalise_mars_lonlat`      source longitude/latitude conventions -> east-positive planetocentric.
* :class:`Body`                      distance/azimuth/destination/area on the sphere or the ellipsoid.
* :func:`lonlat_polygon`, :func:`split_line_antimeridian`   antimeridian- and pole-safe geometry.
* :func:`spherical_disc`             a disc of given area on the body (MGD3 dune fields).
* :func:`cell_fractions`             per-cell area fractions by class (pixel-centre rasterisation).
* :class:`Lines`, :func:`resample_lines`, :func:`line_length_per_cell`.
* :class:`Features`, :func:`nearest_distance_km`   nearest distance to lines/polygons, <= 0.25 km.
* :func:`neighbours_within_km`, :func:`count_within_km`   fixed great-circle radius counts.
* :class:`Graph`, :func:`strahler`, :func:`prune_graph`, :func:`prune_network`   channel networks.
* :func:`load_dune_vocab`            the reviewed dune type crosswalk, with the guard.
* :func:`wkb_line_parts`             read line WKB without shapely, dropping 1-vertex parts.
"""
from __future__ import annotations

import csv
import math
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np
import shapely
from pyproj import Geod
from scipy.sparse import coo_matrix, csr_matrix
from scipy.sparse.csgraph import connected_components, dijkstra
from scipy.spatial import cKDTree
from shapely import STRtree
from shapely.geometry import MultiPolygon, Polygon, box
from sklearn.neighbors import BallTree

from . import _cellmap
from . import driver
from planetary_grid import PLANETS  # noqa: E402  (driver put pipeline/ on sys.path)

# --------------------------------------------------------------------------
# constants
# --------------------------------------------------------------------------

MARS_RADIUS_M = 3396190.0                      # the sphere of the grid, the valleys and MGD3
# IAU 2000 Mars ellipsoid; only used to convert planetographic latitude to planetocentric
MARS_IAU_A_M = 3396190.0
MARS_IAU_B_M = 3376200.0

RES_PER_DEG = {'mars': 256, 'earth': 512}     # raster resolution of cell_fractions: 1/256 deg, 1/512 deg
LINE_DENSIFY_M = 250.0                         # line_length_per_cell
NEAREST_SPACING_M = 400.0                      # candidate vertex spacing: half of it bounds the refine error
DEFAULT_VERTEX_SPACING_M = 460.0               # 15 arc-seconds, the HydroRIVERS flow grid

DUNE_SHARED_TYPES = ('crescentic', 'linear', 'dome', 'star', 'sand_sheet', 'other')
# Enzo, 2026-11-13: sand sheets and "other" do not count toward dune_frac, on both planets.
DUNE_COUNTED_TYPES = ('crescentic', 'linear', 'dome', 'star')


class VocabularyError(ValueError):
    """The dune type crosswalk is unreviewed or uses a type outside the shared vocabulary."""


# --------------------------------------------------------------------------
# coordinate conventions
# --------------------------------------------------------------------------

def normalise_mars_lonlat(lon, lat, lon_dir: str = 'east', lon_range: str = '0-360',
                          lat_type: str = 'planetocentric'):
    """Convert a source's Mars coordinates to east-positive [-180, 180) planetocentric degrees.

    ``lon_dir``   'east' or 'west' (planetographic longitude is west-positive).
    ``lon_range`` '0-360' or '-180-180': what the source promises; a value outside it raises (a wrong
                  declaration is usually a wrong source reading), 'any' skips the check.
    ``lat_type``  'planetocentric' (unchanged) or 'planetographic' (tan phi_c = (b/a)^2 tan phi_g on
                  the IAU 2000 ellipsoid a = 3396.19 km, b = 3376.20 km).
    Scalars in, scalars out; arrays in, arrays out.
    """
    scalar = np.ndim(lon) == 0 and np.ndim(lat) == 0
    lon = np.asarray(lon, dtype=np.float64)
    lat = np.asarray(lat, dtype=np.float64)
    if lon_dir not in ('east', 'west'):
        raise ValueError(f"lon_dir must be 'east' or 'west', got {lon_dir!r}")
    limits = {'0-360': (0.0, 360.0), '-180-180': (-180.0, 180.0), 'any': (-np.inf, np.inf)}
    if lon_range not in limits:
        raise ValueError(f"lon_range must be one of {sorted(limits)}, got {lon_range!r}")
    lo, hi = limits[lon_range]
    finite = np.isfinite(lon)
    if np.any(finite & ((lon < lo - 1e-9) | (lon > hi + 1e-9))):
        raise ValueError(f'longitude outside the declared range {lon_range}')
    if np.any(np.isfinite(lat) & (np.abs(lat) > 90 + 1e-9)):
        raise ValueError('latitude outside [-90, 90]')
    east = -lon if lon_dir == 'west' else lon
    east = (east + 180.0) % 360.0 - 180.0
    east = np.where(east == 0, 0.0, east)            # no negative zero
    if lat_type == 'planetocentric':
        centric = lat.copy()
    elif lat_type == 'planetographic':
        ratio = (MARS_IAU_B_M / MARS_IAU_A_M) ** 2
        with np.errstate(invalid='ignore'):
            centric = np.degrees(np.arctan(ratio * np.tan(np.radians(lat))))
        centric = np.where(np.abs(lat) >= 90, np.sign(lat) * 90.0, centric)
    else:
        raise ValueError(f"lat_type must be 'planetocentric' or 'planetographic', got {lat_type!r}")
    if scalar:
        return float(east), float(centric)
    return east, centric


# --------------------------------------------------------------------------
# the body: sphere (Mars) or ellipsoid (Earth)
# --------------------------------------------------------------------------

def _unit(lon, lat):
    lam, phi = np.radians(lon), np.radians(lat)
    c = np.cos(phi)
    return np.stack([c * np.cos(lam), c * np.sin(lam), np.sin(phi)], axis=-1)


def _interp(lon1, lat1, lon2, lat2, t):
    """Points at fraction ``t`` along the great circle from point 1 to point 2 (arrays)."""
    v1, v2 = _unit(lon1, lat1), _unit(lon2, lat2)
    t = np.asarray(t, dtype=np.float64)
    omega = np.arccos(np.clip((v1 * v2).sum(-1), -1.0, 1.0))
    small = omega < 1e-9
    so = np.where(small, 1.0, np.sin(omega))
    a = np.where(small, 1.0 - t, np.sin((1.0 - t) * omega) / so)
    b = np.where(small, t, np.sin(t * omega) / so)
    v = a[..., None] * v1 + b[..., None] * v2
    v /= np.linalg.norm(v, axis=-1, keepdims=True)
    return np.degrees(np.arctan2(v[..., 1], v[..., 0])), np.degrees(np.arcsin(np.clip(v[..., 2], -1, 1)))


class Body:
    """Distances, azimuths, destinations and areas on a planet's reference surface."""

    def __init__(self, planet: str):
        if planet not in PLANETS:
            raise ValueError(f'unknown planet {planet!r}')
        conf = PLANETS[planet]
        self.planet = planet
        self.a, self.b = float(conf['a_m']), float(conf['b_m'])
        self.sphere = self.a == self.b
        self.geod = Geod(a=self.a, b=self.b)
        self.e2 = 1.0 - (self.b / self.a) ** 2
        self.e = math.sqrt(self.e2)
        if self.sphere:
            self.mean_radius_m = self.a
            self.authalic_radius_m = self.a
            self.min_deg_km = self.a * math.pi / 180 / 1000       # shortest km per degree of latitude
        else:
            self.mean_radius_m = (2 * self.a + self.b) / 3
            self._qp = 1.0 + (1.0 - self.e2) / self.e * math.atanh(self.e)
            self.authalic_radius_m = self.a * math.sqrt(self._qp / 2.0)
            self.min_deg_km = self.a * (1.0 - self.e2) * math.pi / 180 / 1000   # at the equator

    def __repr__(self) -> str:
        return f'Body({self.planet})'

    # -- geodesy -------------------------------------------------------------
    def inv(self, lon1, lat1, lon2, lat2):
        """(forward azimuth in degrees from north, distance in metres); arrays broadcast."""
        lon1, lat1, lon2, lat2 = np.broadcast_arrays(*(np.asarray(x, dtype=np.float64)
                                                        for x in (lon1, lat1, lon2, lat2)))
        shape = lon1.shape
        if lon1.size == 0:
            return np.empty(shape), np.empty(shape)
        if self.sphere:
            p1, p2 = np.radians(lat1), np.radians(lat2)
            dl = np.radians(lon2 - lon1)
            h = np.sin((p2 - p1) / 2) ** 2 + np.cos(p1) * np.cos(p2) * np.sin(dl / 2) ** 2
            dist = 2 * self.a * np.arcsin(np.sqrt(np.clip(h, 0.0, 1.0)))
            az = np.degrees(np.arctan2(np.sin(dl) * np.cos(p2),
                                       np.cos(p1) * np.sin(p2) - np.sin(p1) * np.cos(p2) * np.cos(dl)))
            return az, dist
        az, _, dist = self.geod.inv(lon1.ravel(), lat1.ravel(), lon2.ravel(), lat2.ravel())
        return np.asarray(az).reshape(shape), np.asarray(dist).reshape(shape)

    def dist_m(self, lon1, lat1, lon2, lat2):
        return self.inv(lon1, lat1, lon2, lat2)[1]

    def fwd(self, lon, lat, az_deg, dist_m):
        """Destination (lon, lat) from a start, an azimuth (degrees from north) and a distance."""
        lon, lat, az, dist = np.broadcast_arrays(*(np.asarray(x, dtype=np.float64)
                                                   for x in (lon, lat, az_deg, dist_m)))
        shape = lon.shape
        if self.sphere:
            delta = dist / self.a
            p1, l1, th = np.radians(lat), np.radians(lon), np.radians(az)
            sp2 = np.sin(p1) * np.cos(delta) + np.cos(p1) * np.sin(delta) * np.cos(th)
            p2 = np.arcsin(np.clip(sp2, -1, 1))
            l2 = l1 + np.arctan2(np.sin(th) * np.sin(delta) * np.cos(p1),
                                 np.cos(delta) - np.sin(p1) * sp2)
            return (np.degrees(l2) + 180.0) % 360.0 - 180.0, np.degrees(p2)
        lo, la, _ = self.geod.fwd(lon.ravel(), lat.ravel(), az.ravel(), dist.ravel())
        return np.asarray(lo).reshape(shape), np.asarray(la).reshape(shape)

    # -- area ------------------------------------------------------------------
    def _sin_authalic(self, lat_deg):
        s = np.sin(np.radians(lat_deg))
        if self.sphere:
            return s
        q = (1.0 - self.e2) * (s / (1.0 - self.e2 * s * s) + np.arctanh(self.e * s) / self.e)
        return q / self._qp

    def area_m2(self, geom) -> float:
        """Area of a polygon given in canonical lon/lat (edges straight in lon/lat), on the body.

        Exact for rectangles aligned with meridians and parallels; polygon edges are integrated with
        Simpson's rule, which is far below 0.1 % for edges of a few degrees.
        """
        total = 0.0
        for poly in shapely.get_parts(geom):
            if not isinstance(poly, Polygon) or poly.is_empty:
                continue
            poly = shapely.geometry.polygon.orient(poly, 1.0)      # exterior CCW, holes CW
            for ring in [poly.exterior, *poly.interiors]:
                c = np.asarray(ring.coords)
                lon1, lat1, lon2, lat2 = c[:-1, 0], c[:-1, 1], c[1:, 0], c[1:, 1]
                latm = (lat1 + lat2) / 2
                s = (self._sin_authalic(lat1) + 4 * self._sin_authalic(latm) + self._sin_authalic(lat2)) / 6
                total += -float(np.sum(s * (lon2 - lon1)) * math.pi / 180) * self.authalic_radius_m ** 2
        return total

    def area_km2(self, geom) -> float:
        return self.area_m2(geom) / 1e6

    def cap_area_km2(self, radius_km: float) -> float:
        """Area of the spherical cap of the given great-circle radius (sphere: exact; Earth: authalic)."""
        r = self.authalic_radius_m if not self.sphere else self.a
        return 2 * math.pi * r * r * (1 - math.cos(radius_km * 1000 / r)) / 1e6


_BODIES: dict[str, Body] = {}


def body(planet) -> Body:
    if isinstance(planet, Body):
        return planet
    if planet not in _BODIES:
        _BODIES[planet] = Body(planet)
    return _BODIES[planet]


# --------------------------------------------------------------------------
# antimeridian and pole safe geometry
# --------------------------------------------------------------------------

def _unwrap_lon(lon):
    return np.unwrap(np.asarray(lon, dtype=np.float64), period=360.0)


def lonlat_polygon(shell, holes=()):
    """A lon/lat polygon as canonical planar geometry in [-180, 180] x [-90, 90].

    ``shell`` is an (n, 2) array of (lon, lat) whose consecutive vertices are less than 180 degrees
    apart in longitude (so a jump from 179 to -179 is a crossing, not a long edge). A ring that goes
    once around the pole (its unwrapped longitude changes by 360) is closed through that pole. Pieces
    are cut at +-180 so the result can be rasterised and tested in the plane. Returns a Polygon or
    MultiPolygon (possibly empty).
    """
    pts = _ring_unwrapped(shell)
    poly = Polygon(pts)
    if not poly.is_valid:
        poly = shapely.make_valid(poly)
    for hole in holes:
        h = _ring_unwrapped(hole)
        mid = (pts[:, 0].min() + pts[:, 0].max()) / 2
        h[:, 0] += 360.0 * np.round((mid - h[:, 0].mean()) / 360.0)
        poly = poly.difference(Polygon(h))
    return _cut_at_antimeridian(poly)


def _ring_unwrapped(coords) -> np.ndarray:
    c = np.asarray(coords, dtype=np.float64)[:, :2].copy()
    if len(c) > 1 and np.allclose(c[0], c[-1]):
        c = c[:-1]
    lon = _unwrap_lon(np.append(c[:, 0], c[0, 0]))             # unwrap including the closing step
    net = lon[-1] - lon[0]
    lon = lon[:-1]
    out = np.column_stack([lon, c[:, 1]])
    if abs(net) > 180.0:                                      # the ring winds once around a pole
        pole = 90.0 if c[:, 1].mean() >= 0 else -90.0
        arrive = lon[0] + net                                 # the closing step lands one turn away
        out = np.vstack([out, [arrive, c[0, 1]], [arrive, pole], [lon[0], pole]])
    return out


def _cut_at_antimeridian(poly):
    minx, _, maxx, _ = poly.bounds
    if minx >= -180.0 and maxx <= 180.0:
        return poly
    pieces = []
    for k in range(int(math.floor((minx + 180.0) / 360.0)), int(math.floor((maxx + 180.0) / 360.0)) + 1):
        clip = poly.intersection(box(-180.0 + 360.0 * k, -90.0, 180.0 + 360.0 * k, 90.0))
        if clip.is_empty:
            continue
        clip = shapely.affinity.translate(clip, xoff=-360.0 * k)
        pieces.extend(g for g in shapely.get_parts(clip) if isinstance(g, Polygon) and g.area > 0)
    if not pieces:
        return Polygon()
    return pieces[0] if len(pieces) == 1 else MultiPolygon(pieces)


def split_line_antimeridian(coords) -> list[np.ndarray]:
    """Cut a lon/lat polyline at +-180: each piece stays in [-180, 180] and ends on the meridian."""
    c = np.asarray(coords, dtype=np.float64)[:, :2]
    lon = _unwrap_lon(c[:, 0])
    lat = c[:, 1]
    cell = np.floor((lon + 180.0) / 360.0).astype(int)
    pieces, cur_lon, cur_lat = [], [lon[0]], [lat[0]]
    for i in range(1, len(lon)):
        a, b = cell[i - 1], cell[i]
        if a != b:
            step = 1 if b > a else -1
            for k in range(a, b, step):
                edge = -180.0 + 360.0 * (k + 1) if step > 0 else -180.0 + 360.0 * k
                f = (edge - lon[i - 1]) / (lon[i] - lon[i - 1])
                la = lat[i - 1] + f * (lat[i] - lat[i - 1])
                cur_lon.append(edge)
                cur_lat.append(la)
                pieces.append((k, np.array(cur_lon), np.array(cur_lat)))
                cur_lon, cur_lat = [edge], [la]
        cur_lon.append(lon[i])
        cur_lat.append(lat[i])
    pieces.append((cell[-1], np.array(cur_lon), np.array(cur_lat)))
    return [np.column_stack([lo - 360.0 * k, la]) for k, lo, la in pieces if len(lo) >= 2]


def spherical_disc(lon: float, lat: float, area_km2: float, planet='mars', n: int = 180):
    """(ring, geometry): a disc of the given area on the body centred on (lon, lat).

    ``ring`` is the (n+1, 2) lon/lat ring (unwrapped as built, useful for boundary distances) and
    ``geometry`` the canonical planar polygon (cut at +-180, closed through the pole when the disc
    contains it). The disc is a spherical cap: area = 2 pi R^2 (1 - cos rho). Sphere only.
    """
    b = body(planet)
    if not b.sphere:
        raise ValueError('spherical_disc is defined for the Mars sphere')
    rho = math.acos(1.0 - area_km2 * 1e6 / (2 * math.pi * b.a ** 2))
    az = np.linspace(0.0, 360.0, n, endpoint=False)
    lo, la = b.fwd(np.full(n, lon), np.full(n, lat), az, np.full(n, rho * b.a))
    ring = np.column_stack([lo, la])
    ring = np.vstack([ring, ring[:1]])
    # the cap contains a pole when its edge passes beyond it: the ring then winds around the pole
    return ring, lonlat_polygon(ring)


# --------------------------------------------------------------------------
# group cells and per-cell class fractions
# --------------------------------------------------------------------------

@dataclass
class GroupCells:
    grid: object
    bands: list
    counts: np.ndarray        # columns per band of the group
    offsets: np.ndarray       # first row of each band inside the group (len = bands + 1)
    band: np.ndarray
    col: np.ndarray
    lat_min: np.ndarray
    lat_max: np.ndarray
    lon_min: np.ndarray
    lon_max: np.ndarray
    clat: np.ndarray
    clon: np.ndarray
    area_km2: np.ndarray

    @property
    def n(self) -> int:
        return len(self.band)


def group_cells(grid, band_group: int) -> GroupCells:
    """The cells of a band group in grid order (same order and values as ``driver.cells_table``)."""
    bands = driver.group_bands(grid, band_group)
    arr = np.asarray(bands, dtype=np.int64)
    counts = grid.column_counts[arr].astype(np.int64)
    offsets = np.concatenate(([0], np.cumsum(counts)))
    band = np.repeat(arr, counts)
    col = np.concatenate([np.arange(c, dtype=np.int64) for c in counts])
    width = np.repeat(360.0 / counts, counts)
    lat_min, lat_max = grid.edges_deg[band], grid.edges_deg[band + 1]
    lon_min = -180.0 + width * col
    lon_max = lon_min + width
    area = np.repeat(grid.strip_area_m2()[arr] / counts / 1e6, counts)
    return GroupCells(grid, bands, counts, offsets, band, col, lat_min, lat_max, lon_min, lon_max,
                      (lat_min + lat_max) / 2, (lon_min + lon_max) / 2, area)


@dataclass
class CellFractions:
    codes: list
    frac: np.ndarray          # (n_cells, n_codes): area fraction of each class in each cell
    covered: np.ndarray       # (n_cells,): fraction of the cell covered by any geometry
    cells: GroupCells


def _band_rows(lat_a: float, lat_b: float, res: int) -> np.ndarray:
    """Raster rows (global row index, row 0 at lat 90) whose pixel centre lies in [lat_a, lat_b)."""
    lo = int(math.floor((90.0 - lat_b) * res - 0.5)) + 1
    hi = int(math.floor((90.0 - lat_a) * res - 0.5))
    return np.arange(lo, hi + 1)


def cell_fractions(band_group: int, geoms, class_codes, *, planet='mars', grid=None, res: int | None = None,
                   weights=None) -> CellFractions:
    """Area fraction of every cell of a band group covered by each class of ``geoms``.

    ``geoms``        canonical planar polygons (see :func:`lonlat_polygon`).
    ``class_codes``  one code per geometry; the result has one column per distinct code, in sorted order.
    ``weights``      optional per-geometry share in [0, 1] (a field whose area is split between types).

    Each band is rasterised at pixel centres (Mars 1/256 deg ~ 231 m, Earth 1/512 deg ~ 217 m); a pixel
    belongs to a cell by its centre, using the grid's own rule. Pixels are weighted by cos(latitude), so
    a fraction is the area share inside the cell. Grouping per cell uses bincount.
    """
    from rasterio import features as rfeatures
    from rasterio.transform import Affine

    b = body(planet)
    grid = grid or driver.planet_grid(b.planet)
    res = int(res or RES_PER_DEG[b.planet])
    cells = group_cells(grid, band_group)
    geoms = list(geoms)
    codes_list = list(class_codes)
    if len(geoms) != len(codes_list):
        raise ValueError('geoms and class_codes differ in length')
    wts = np.ones(len(geoms)) if weights is None else np.asarray(list(weights), dtype=np.float64)
    codes = sorted(set(codes_list), key=lambda c: (str(type(c)), c))
    code_index = {c: i for i, c in enumerate(codes)}
    frac = np.zeros((cells.n, len(codes)))
    covered = np.zeros(cells.n)
    if not geoms:
        return CellFractions(codes, frac, covered, cells)
    tree = STRtree(geoms)
    gcode = np.array([code_index[c] for c in codes_list])
    width_px = 360 * res
    for bi, band in enumerate(cells.bands):
        lat_a, lat_b = float(grid.edges_deg[band]), float(grid.edges_deg[band + 1])
        hit = tree.query(box(-180.0, lat_a, 180.0, lat_b))
        if len(hit) == 0:
            continue
        rows = _band_rows(lat_a, lat_b, res)
        if len(rows) == 0:
            continue
        n = int(cells.counts[bi])
        lat_rows = 90.0 - (rows + 0.5) / res
        w = np.cos(np.radians(lat_rows))
        sw = w.sum()
        colcell = np.minimum(np.floor((np.arange(width_px) + 0.5) / width_px * n).astype(np.int64), n - 1)
        denom = sw * np.bincount(colcell, minlength=n)
        top = 90.0 - rows[0] / res
        lo_cell = cells.offsets[bi]
        groups = {k: [] for k in range(len(codes))}
        for g in hit:
            groups[int(gcode[g])].append(int(g))
        union_shapes = []
        for k, members in groups.items():
            if not members:
                continue
            bounds = shapely.bounds(np.array([geoms[g] for g in members]))
            j0 = max(0, int(math.floor((bounds[:, 0].min() + 180.0) * res)))
            j1 = min(width_px, int(math.ceil((bounds[:, 2].max() + 180.0) * res)) + 1)
            if j1 <= j0:
                continue
            transform = Affine(1.0 / res, 0, -180.0 + j0 / res, 0, -1.0 / res, top)
            shapes = [(geoms[g], float(wts[g])) for g in members if wts[g] > 0]
            if not shapes:
                continue
            img = rfeatures.rasterize(shapes, out_shape=(len(rows), j1 - j0), transform=transform,
                                      fill=0.0, dtype='float32')
            colsum = (img * w[:, None]).sum(axis=0)
            num = np.bincount(colcell[j0:j1], weights=colsum, minlength=n)
            frac[lo_cell:lo_cell + n, k] = np.minimum(num / np.maximum(denom, 1e-300), 1.0)
            union_shapes.extend((geoms[g], 1.0) for g in members if wts[g] > 0)
        if len(codes) == 1:
            covered[lo_cell:lo_cell + n] = frac[lo_cell:lo_cell + n, 0]
        elif union_shapes:
            bounds = shapely.bounds(np.array([s for s, _ in union_shapes]))
            j0 = max(0, int(math.floor((bounds[:, 0].min() + 180.0) * res)))
            j1 = min(width_px, int(math.ceil((bounds[:, 2].max() + 180.0) * res)) + 1)
            transform = Affine(1.0 / res, 0, -180.0 + j0 / res, 0, -1.0 / res, top)
            img = rfeatures.rasterize(union_shapes, out_shape=(len(rows), j1 - j0), transform=transform,
                                      fill=0, dtype='uint8')
            colsum = (img * w[:, None]).sum(axis=0)
            num = np.bincount(colcell[j0:j1], weights=colsum, minlength=n)
            covered[lo_cell:lo_cell + n] = np.minimum(num / np.maximum(denom, 1e-300), 1.0)
    return CellFractions(codes, frac, covered, cells)


# --------------------------------------------------------------------------
# polylines: resampling and length per cell
# --------------------------------------------------------------------------

@dataclass
class Lines:
    """Many polylines in flat arrays: vertex ``offsets[i]:offsets[i + 1]`` belong to line ``i``."""
    lon: np.ndarray
    lat: np.ndarray
    offsets: np.ndarray

    @classmethod
    def from_list(cls, arrays) -> 'Lines':
        arrays = [np.asarray(a, dtype=np.float64)[:, :2] for a in arrays]
        if any(len(a) < 2 for a in arrays):
            raise ValueError('every line needs at least 2 vertices (drop 1-vertex parts first)')
        offsets = np.concatenate(([0], np.cumsum([len(a) for a in arrays]))).astype(np.int64)
        if arrays:
            flat = np.concatenate(arrays)
            return cls(flat[:, 0].copy(), flat[:, 1].copy(), offsets)
        return cls(np.empty(0), np.empty(0), offsets)

    @property
    def n_lines(self) -> int:
        return len(self.offsets) - 1

    @property
    def line_id(self) -> np.ndarray:
        return np.repeat(np.arange(self.n_lines), np.diff(self.offsets))

    def to_list(self) -> list[np.ndarray]:
        return [np.column_stack([self.lon[a:b], self.lat[a:b]])
                for a, b in zip(self.offsets[:-1], self.offsets[1:])]

    def select(self, mask_or_idx) -> 'Lines':
        idx = np.arange(self.n_lines)[mask_or_idx]
        return Lines.from_list([np.column_stack([self.lon[self.offsets[i]:self.offsets[i + 1]],
                                                 self.lat[self.offsets[i]:self.offsets[i + 1]]]) for i in idx])

    def segments(self):
        """(index of the first vertex of every segment, parent line of every segment)."""
        lid = self.line_id
        ok = lid[:-1] == lid[1:] if len(lid) > 1 else np.zeros(0, dtype=bool)
        i = np.nonzero(ok)[0]
        return i, lid[i]

    def length_m(self, planet) -> np.ndarray:
        """Length of every line on the body, summed over its segments."""
        b = body(planet)
        i, lid = self.segments()
        seg = b.dist_m(self.lon[i], self.lat[i], self.lon[i + 1], self.lat[i + 1])
        return np.bincount(lid, weights=seg, minlength=self.n_lines)


def resample_lines(lines: Lines, spacing_m: float, planet) -> Lines:
    """Resample every line to a uniform ground vertex spacing (measured on the body).

    Vertices are placed every ``length / round(length / spacing)`` metres along the original path, so
    wiggles finer than the spacing are cut off. The same generalisation runs on Mars and Earth before
    any channel length is measured.
    """
    b = body(planet)
    n_lines = lines.n_lines
    if n_lines == 0:
        return lines
    i, lid = lines.segments()
    seg = np.zeros(len(lines.lon) - 1)
    seg[i] = b.dist_m(lines.lon[i], lines.lat[i], lines.lon[i + 1], lines.lat[i + 1])
    cum = np.concatenate(([0.0], np.cumsum(seg)))
    start = cum[lines.offsets[:-1]]
    total = cum[lines.offsets[1:] - 1] - start
    m = np.maximum(1, np.rint(total / spacing_m)).astype(np.int64)
    counts = m + 1
    li = np.repeat(np.arange(n_lines), counts)
    j = np.arange(counts.sum()) - np.repeat(np.cumsum(counts) - counts, counts)
    s = start[li] + total[li] * j / m[li]
    vi = np.searchsorted(cum, s, side='right') - 1
    vi = np.clip(vi, lines.offsets[li], lines.offsets[li + 1] - 2)
    seglen = cum[vi + 1] - cum[vi]
    t = np.where(seglen > 0, (s - cum[vi]) / np.where(seglen > 0, seglen, 1.0), 0.0).clip(0.0, 1.0)
    lon, lat = _interp(lines.lon[vi], lines.lat[vi], lines.lon[vi + 1], lines.lat[vi + 1], t)
    # keep the original end points exactly
    first = np.cumsum(counts) - counts
    last = first + counts - 1
    lon[first], lat[first] = lines.lon[lines.offsets[:-1]], lines.lat[lines.offsets[:-1]]
    lon[last], lat[last] = lines.lon[lines.offsets[1:] - 1], lines.lat[lines.offsets[1:] - 1]
    return Lines(lon, lat, np.concatenate(([0], np.cumsum(counts))).astype(np.int64))


def densify_lines(lines: Lines, max_m: float, planet) -> Lines:
    """Insert vertices so that no segment is longer than ``max_m`` on the body; originals are kept."""
    b = body(planet)
    i, lid = lines.segments()
    if len(i) == 0:
        return lines
    seg = b.dist_m(lines.lon[i], lines.lat[i], lines.lon[i + 1], lines.lat[i + 1])
    n = np.maximum(1, np.ceil(seg / max_m)).astype(np.int64)
    rep = np.repeat(np.arange(len(i)), n)
    j = np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)
    t = j / n[rep]
    lon, lat = _interp(lines.lon[i][rep], lines.lat[i][rep], lines.lon[i + 1][rep], lines.lat[i + 1][rep], t)
    line_of_seg = lid[rep]
    per_line = np.bincount(line_of_seg, minlength=lines.n_lines) + 1
    # one extra closing vertex per line
    out_counts = per_line
    out_lon = np.empty(out_counts.sum())
    out_lat = np.empty(out_counts.sum())
    out_off = np.concatenate(([0], np.cumsum(out_counts))).astype(np.int64)
    # positions of the interpolated vertices: line start + running index within the line
    first_of_line = np.concatenate(([0], np.cumsum(np.bincount(line_of_seg, minlength=lines.n_lines))[:-1]))
    pos = out_off[line_of_seg] + (np.arange(len(rep)) - first_of_line[line_of_seg])
    out_lon[pos], out_lat[pos] = lon, lat
    out_lon[out_off[1:] - 1] = lines.lon[lines.offsets[1:] - 1]
    out_lat[out_off[1:] - 1] = lines.lat[lines.offsets[1:] - 1]
    return Lines(out_lon, out_lat, out_off)


def _subsegments(lines: Lines, max_m: float, planet):
    """Midpoints and lengths (m) of the pieces of every segment cut to <= ``max_m`` on the body."""
    b = body(planet)
    i, lid = lines.segments()
    if len(i) == 0:
        z = np.empty(0)
        return z, z, z, np.empty(0, dtype=np.int64)
    seg = b.dist_m(lines.lon[i], lines.lat[i], lines.lon[i + 1], lines.lat[i + 1])
    n = np.maximum(1, np.ceil(seg / max_m)).astype(np.int64)
    rep = np.repeat(np.arange(len(i)), n)
    j = np.arange(n.sum()) - np.repeat(np.cumsum(n) - n, n)
    t = (j + 0.5) / n[rep]
    mlon, mlat = _interp(lines.lon[i][rep], lines.lat[i][rep], lines.lon[i + 1][rep], lines.lat[i + 1][rep], t)
    return mlon, mlat, (seg / n)[rep], lid[rep]


def line_length_per_cell(band_group: int, lines: Lines, *, planet='mars', grid=None,
                         max_segment_m: float = LINE_DENSIFY_M, weights=None) -> np.ndarray:
    """Length (km) of the lines inside every cell of a band group, measured on the body.

    Lines are cut into pieces of at most ``max_segment_m``; each piece goes to the cell holding its
    midpoint (the grid's lookup rule) and counts its geodesic (Earth) or great-circle (Mars) length.
    ``weights`` optionally scales each line (e.g. 0/1 keep flags).
    """
    b = body(planet)
    grid = grid or driver.planet_grid(b.planet)
    cells = group_cells(grid, band_group)
    mlon, mlat, length, lid = _subsegments(lines, max_segment_m, b)
    rows = _cellmap.group_rows(grid, cells.bands, mlat, mlon)
    if weights is not None:
        length = length * np.asarray(weights, dtype=np.float64)[lid]
    return _cellmap.cell_sum(rows, length, cells.n) / 1000.0


# --------------------------------------------------------------------------
# nearest distance to lines and polygons
# --------------------------------------------------------------------------

@dataclass
class Features:
    """Boundary vertices (densified) with their neighbours along the line, plus optional polygons.

    Each row is self-contained (it carries the coordinates of its previous and next vertex), so the
    table can be sliced by latitude without losing the segments. Rows are sorted by latitude.
    """
    lon: np.ndarray
    lat: np.ndarray
    plon: np.ndarray
    plat: np.ndarray
    nlon: np.ndarray
    nlat: np.ndarray
    has_prev: np.ndarray
    has_next: np.ndarray
    polygons: list | None = None
    _tree: object = field(default=None, repr=False)

    @property
    def n(self) -> int:
        return len(self.lon)

    @classmethod
    def from_lines(cls, lines: Lines, planet, spacing_m: float = NEAREST_SPACING_M, polygons=None) -> 'Features':
        dense = densify_lines(lines, spacing_m, planet)
        lon, lat = dense.lon, dense.lat
        n = len(lon)
        lid = dense.line_id
        has_prev = np.zeros(n, dtype=bool)
        has_next = np.zeros(n, dtype=bool)
        if n > 1:
            same = lid[:-1] == lid[1:]
            has_prev[1:] = same
            has_next[:-1] = same
        plon, plat = np.roll(lon, 1), np.roll(lat, 1)
        nlon, nlat = np.roll(lon, -1), np.roll(lat, -1)
        order = np.argsort(lat, kind='stable')
        return cls(lon[order], lat[order], plon[order], plat[order], nlon[order], nlat[order],
                   has_prev[order], has_next[order], polygons=polygons)

    @classmethod
    def from_rings(cls, rings, planet, polygons=None, spacing_m: float = NEAREST_SPACING_M) -> 'Features':
        rings = [np.asarray(r)[:, :2] for r in rings if len(r) >= 2]
        return cls.from_lines(Lines.from_list(rings), planet, spacing_m, polygons=polygons)

    def slice_lat(self, lat0: float, lat1: float) -> 'Features':
        s = slice(int(np.searchsorted(self.lat, lat0, side='left')),
                  int(np.searchsorted(self.lat, lat1, side='right')))
        return Features(self.lon[s], self.lat[s], self.plon[s], self.plat[s], self.nlon[s], self.nlat[s],
                        self.has_prev[s], self.has_next[s], polygons=self.polygons)

    def contains(self, lon, lat) -> np.ndarray:
        """True for points inside any polygon (planar test in canonical lon/lat)."""
        lon = np.asarray(lon, dtype=np.float64)
        out = np.zeros(len(lon), dtype=bool)
        if not self.polygons:
            return out
        if self._tree is None:
            self._tree = STRtree(self.polygons)
        pts = shapely.points(lon, np.asarray(lat, dtype=np.float64))
        hit = self._tree.query(pts, predicate='within')
        out[hit[0]] = True
        return out


def _point_segment_m(b: Body, plon, plat, alon, alat, blon, blat):
    """Distance (m) from points to the segments a-b, in the azimuthal frame centred on each point."""
    az_a, da = b.inv(plon, plat, alon, alat)
    az_b, db = b.inv(plon, plat, blon, blat)
    ax, ay = da * np.sin(np.radians(az_a)), da * np.cos(np.radians(az_a))
    bx, by = db * np.sin(np.radians(az_b)), db * np.cos(np.radians(az_b))
    dx, dy = bx - ax, by - ay
    den = dx * dx + dy * dy
    t = np.where(den > 0, -(ax * dx + ay * dy) / np.where(den > 0, den, 1.0), 0.0).clip(0.0, 1.0)
    return np.hypot(ax + t * dx, ay + t * dy)


def _nearest_in(b: Body, clon, clat, feats: Features, k: int, chunk: int) -> np.ndarray:
    """Exact distance (m) from points to the nearest of ``feats``' segments (inf if feats is empty)."""
    out = np.full(len(clon), np.inf)
    if feats.n == 0 or len(clon) == 0:
        return out
    tree = BallTree(np.radians(np.column_stack([feats.lat, feats.lon])), metric='haversine')
    kk = min(k, feats.n)
    for s in range(0, len(clon), chunk):
        lo, la = clon[s:s + chunk], clat[s:s + chunk]
        _, idx = tree.query(np.radians(np.column_stack([la, lo])), k=kk)
        best = np.full(len(lo), np.inf)
        for c in range(kk):
            v = idx[:, c]
            d = b.dist_m(lo, la, feats.lon[v], feats.lat[v])
            prev = feats.has_prev[v]
            nxt = feats.has_next[v]
            d_prev = _point_segment_m(b, lo, la, feats.plon[v], feats.plat[v], feats.lon[v], feats.lat[v])
            d_next = _point_segment_m(b, lo, la, feats.lon[v], feats.lat[v], feats.nlon[v], feats.nlat[v])
            d = np.minimum(d, np.where(prev, d_prev, np.inf))
            d = np.minimum(d, np.where(nxt, d_next, np.inf))
            best = np.minimum(best, d)
        out[s:s + chunk] = best
    return out


def nearest_distance_km(clon, clat, features: Features, planet, *, k: int = 4, window_deg: float | None = None,
                        chunk: int = 50000) -> np.ndarray:
    """Distance (km) from each point to the nearest feature, 0 for points inside a polygon.

    Candidates come from a haversine BallTree over the densified boundary vertices (spacing
    <= 400 m, so the nearest vertex is within 0.2 km of the true closest point); each candidate is
    refined exactly against its two adjacent segments: great circle on the Mars sphere, pyproj
    Geod inverse on WGS84. Error <= 0.25 km. ``window_deg`` limits the BallTree to vertices within
    that many degrees of latitude of the points, doubling it until the answer is provably final.
    """
    b = body(planet)
    clon = np.asarray(clon, dtype=np.float64)
    clat = np.asarray(clat, dtype=np.float64)
    out = np.full(len(clon), np.inf)
    if len(clon) and features.n:
        if window_deg is None:
            out = _nearest_in(b, clon, clat, features, k, chunk)
        else:
            pending = np.arange(len(clon))
            w = float(window_deg)
            while len(pending):
                lat0, lat1 = clat[pending].min() - w, clat[pending].max() + w
                sub = features.slice_lat(lat0, lat1)
                d = _nearest_in(b, clon[pending], clat[pending], sub, k, chunk)
                final = (d <= w * b.min_deg_km * 1000.0) | (lat0 <= -90.0 and lat1 >= 90.0)
                out[pending[final]] = d[final]
                pending = pending[~final]
                if len(pending) and w >= 180.0:
                    # whole planet already searched: the remaining answers are final
                    out[pending] = d[~final]
                    break
                w *= 2.0
    inside = features.contains(clon, clat) if len(clon) else np.zeros(0, dtype=bool)
    out[inside] = 0.0
    return out / 1000.0


def channel_cells(band_group: int, lines: Lines, order, *, planet='mars', grid=None,
                  max_segment_m: float = LINE_DENSIFY_M):
    """(length_km, max_order) per cell of a band group for ordered channel lines.

    Length is measured on the body with :func:`line_length_per_cell`'s rule; ``max_order`` is the
    highest Strahler order among the pieces that fall in the cell (0 where there is none).
    """
    b = body(planet)
    grid = grid or driver.planet_grid(b.planet)
    cells = group_cells(grid, band_group)
    mlon, mlat, length, lid = _subsegments(lines, max_segment_m, b)
    rows = _cellmap.group_rows(grid, cells.bands, mlat, mlon)
    ok = rows >= 0
    length_km = np.bincount(rows[ok], weights=length[ok], minlength=cells.n) / 1000.0
    max_order = np.zeros(cells.n, dtype=np.int16)
    if ok.any():
        np.maximum.at(max_order, rows[ok], np.asarray(order, dtype=np.int16)[lid[ok]])
    return length_km, max_order


def nearest_distance_windowed(clon, clat, load_features, planet, *, w0: float = 2.0, k: int = 4):
    """Nearest distance (km) when the features come from a loader ``load_features(lat0, lat1)``.

    The window around the points starts at ``w0`` degrees of latitude and doubles until the answer is
    final: anything outside the window is at least ``w`` degrees of latitude away. Use it when the
    features are too many to hold for the whole planet (HydroRIVERS).
    """
    b = body(planet)
    clon = np.asarray(clon, dtype=np.float64)
    clat = np.asarray(clat, dtype=np.float64)
    out = np.full(len(clon), np.inf)
    pending = np.arange(len(clon))
    w = float(w0)
    while len(pending):
        lat0, lat1 = clat[pending].min() - w, clat[pending].max() + w
        feats = load_features(lat0, lat1)
        d = _nearest_in(b, clon[pending], clat[pending], feats, k, 50000)
        whole = lat0 <= -90.0 and lat1 >= 90.0
        final = (d <= w * b.min_deg_km * 1000.0) | whole
        out[pending[final]] = d[final]
        pending = pending[~final]
        w *= 2.0
    return out / 1000.0


# --------------------------------------------------------------------------
# fixed-radius neighbours
# --------------------------------------------------------------------------

def neighbours_within_km(clon, clat, plon, plat, r_km: float, planet, *, chunk: int = 20000):
    """Points within a fixed great-circle radius of each centre, as CSR (indptr, indices, dist_km).

    The radius is in kilometres on the body, never in cells, so results do not depend on the grid.
    Mars distances are exact great circles; Earth candidates are filtered with the Geod inverse.
    """
    b = body(planet)
    clon, clat = np.asarray(clon, dtype=np.float64), np.asarray(clat, dtype=np.float64)
    plon, plat = np.asarray(plon, dtype=np.float64), np.asarray(plat, dtype=np.float64)
    indptr = np.zeros(len(clon) + 1, dtype=np.int64)
    if len(plon) == 0 or len(clon) == 0:
        return indptr, np.empty(0, dtype=np.int64), np.empty(0)
    tree = BallTree(np.radians(np.column_stack([plat, plon])), metric='haversine')
    margin = 1.0 if b.sphere else 1.01
    idx_parts, dist_parts, counts = [], [], np.zeros(len(clon), dtype=np.int64)
    for s in range(0, len(clon), chunk):
        lo, la = clon[s:s + chunk], clat[s:s + chunk]
        ind = tree.query_radius(np.radians(np.column_stack([la, lo])),
                                r=margin * r_km * 1000.0 / b.mean_radius_m)
        for j, v in enumerate(ind):
            if len(v):
                d = b.dist_m(lo[j], la[j], plon[v], plat[v]) / 1000.0
                keep = d <= r_km
                v, d = v[keep], d[keep]
            else:
                d = np.empty(0)
            counts[s + j] = len(v)
            idx_parts.append(v.astype(np.int64))
            dist_parts.append(d)
    indptr[1:] = np.cumsum(counts)
    return indptr, np.concatenate(idx_parts) if idx_parts else np.empty(0, np.int64), \
        np.concatenate(dist_parts) if dist_parts else np.empty(0)


def count_within_km(clon, clat, plon, plat, r_km: float = 50.0, planet='mars') -> np.ndarray:
    """Number of points within ``r_km`` (great circle on the body) of each centre."""
    indptr, _, _ = neighbours_within_km(clon, clat, plon, plat, r_km, planet)
    return np.diff(indptr)


# --------------------------------------------------------------------------
# channel networks: Strahler order and pruning
# --------------------------------------------------------------------------

@dataclass
class Graph:
    """Directed edges ``src -> dst`` (downstream) between integer nodes, with a length in km."""
    src: np.ndarray
    dst: np.ndarray
    length_km: np.ndarray

    @property
    def n_edges(self) -> int:
        return len(self.src)


def strahler(graph: Graph) -> np.ndarray:
    """Strahler order of every edge of a directed graph (sources are order 1)."""
    e = graph.n_edges
    order = np.zeros(e, dtype=np.int16)
    if e == 0:
        return order
    nodes, inv = np.unique(np.concatenate([graph.src, graph.dst]), return_inverse=True)
    src, dst = inv[:e], inv[e:]
    n = len(nodes)
    indeg = np.bincount(dst, minlength=n)
    in_sort = np.argsort(dst, kind='stable')
    in_ptr = np.concatenate(([0], np.cumsum(indeg)))
    out_sort = np.argsort(src, kind='stable')
    out_ptr = np.concatenate(([0], np.cumsum(np.bincount(src, minlength=n))))
    remaining = indeg.copy()
    frontier = np.nonzero(remaining == 0)[0]
    done_nodes = 0
    while len(frontier):
        done_nodes += len(frontier)
        o = np.ones(len(frontier), dtype=np.int64)
        has_in = indeg[frontier] > 0
        if has_in.any():
            f = frontier[has_in]
            cnt = indeg[f]
            edges = in_sort[np.concatenate([np.arange(in_ptr[v], in_ptr[v + 1]) for v in f])]
            vals = order[edges].astype(np.int64)
            starts = np.concatenate(([0], np.cumsum(cnt)[:-1]))
            mx = np.maximum.reduceat(vals, starts)
            ties = np.add.reduceat((vals == np.repeat(mx, cnt)).astype(np.int64), starts)
            o[has_in] = mx + (ties >= 2)
        out_cnt = out_ptr[frontier + 1] - out_ptr[frontier]
        if out_cnt.sum() == 0:
            break
        out_edges = out_sort[np.concatenate([np.arange(out_ptr[v], out_ptr[v + 1]) for v in frontier])]
        order[out_edges] = np.repeat(o, out_cnt)
        np.subtract.at(remaining, dst[out_edges], 1)
        nxt = np.unique(dst[out_edges])
        frontier = nxt[remaining[nxt] == 0]
    order[order == 0] = 1            # edges on a cycle (no topological order): treat as headwaters
    return order


def strahler_forest(graph: Graph, rank) -> np.ndarray:
    """Strahler order when the graph may be braided: each node drains through one edge only.

    ``rank[node]`` is the distance of a node to its outlet. Every node keeps its outgoing edge that
    leads to the lowest-ranked node (ties: lowest edge index); the kept edges form a forest, which
    :func:`strahler` numbers. The other edges (braids, distributaries) get the order of the edge their
    start node drains through, so loops do not inflate the order.
    """
    e = graph.n_edges
    rank = np.asarray(rank, dtype=np.float64)
    idx = np.lexsort((np.arange(e), rank[graph.dst], graph.src))
    first = np.concatenate(([True], graph.src[idx][1:] != graph.src[idx][:-1]))
    chosen = idx[first]
    order_chosen = strahler(Graph(graph.src[chosen], graph.dst[chosen], graph.length_km[chosen]))
    order = np.zeros(e, dtype=np.int16)
    order[chosen] = order_chosen
    by_node = {}
    by_node.update(zip(graph.src[chosen].tolist(), order_chosen.tolist()))
    rest = np.setdiff1d(np.arange(e), chosen, assume_unique=True)
    if len(rest):
        order[rest] = [by_node[int(v)] for v in graph.src[rest]]
    return order


def prune_graph(graph: Graph, L_min_km: float = 20.0, upland_km2=None,
                upland_min_km2: float | None = None) -> np.ndarray:
    """Boolean keep-mask over the edges after the shared channel rules.

    1. optional start threshold: edges with ``upland_km2 < upland_min_km2`` are dropped first;
    2. repeatedly drop source segments shorter than ``L_min_km``. A segment runs source -> confluence,
       confluence -> confluence or confluence -> outlet; nodes with exactly one edge in and one out
       are not confluences, so edges chain through them (and chains lengthen when a branch is dropped);
    3. drop connected systems whose total length is below ``L_min_km``.
    """
    e = graph.n_edges
    keep = np.ones(e, dtype=bool)
    if e == 0:
        return keep
    if upland_min_km2 is not None:
        if upland_km2 is None:
            raise ValueError('upland_min_km2 needs upland_km2 per edge')
        keep &= np.asarray(upland_km2, dtype=np.float64) >= upland_min_km2
    nodes, inv = np.unique(np.concatenate([graph.src, graph.dst]), return_inverse=True)
    src, dst, length = inv[:e], inv[e:], np.asarray(graph.length_km, dtype=np.float64)
    n = len(nodes)
    while True:
        idx = np.nonzero(keep)[0]
        if len(idx) == 0:
            break
        s, d, ln = src[idx], dst[idx], length[idx]
        indeg = np.bincount(d, minlength=n)
        outdeg = np.bincount(s, minlength=n)
        through = (indeg == 1) & (outdeg == 1)
        in_edge = np.full(n, -1, dtype=np.int64)
        out_edge = np.full(n, -1, dtype=np.int64)
        in_edge[d] = np.arange(len(idx))
        out_edge[s] = np.arange(len(idx))
        link = np.nonzero(through)[0]
        a, c = in_edge[link], out_edge[link]
        m = len(idx)
        graph_links = csr_matrix((np.ones(len(a)), (a, c)), shape=(m, m))
        _, label = connected_components(graph_links, directed=False)
        seg_len = np.bincount(label, weights=ln)
        is_source_edge = indeg[s] == 0
        source_seg = np.zeros(label.max() + 1, dtype=bool)
        source_seg[label[is_source_edge]] = True
        drop_seg = source_seg & (seg_len < L_min_km)
        drop = drop_seg[label]
        if not drop.any():
            break
        keep[idx[drop]] = False
    idx = np.nonzero(keep)[0]
    if len(idx):
        m = len(idx)
        adj = coo_matrix((np.ones(m), (src[idx], dst[idx])), shape=(n, n))
        _, comp = connected_components(adj, directed=False)
        comp_len = np.bincount(comp[src[idx]], weights=length[idx], minlength=comp.max() + 1)
        keep[idx[comp_len[comp[src[idx]]] < L_min_km]] = False
    return keep


@dataclass
class Network:
    """The pruned channel network: kept polylines with their Strahler order."""
    lines: list                # list of (n, 2) lon/lat arrays
    order: np.ndarray          # Strahler order per kept line
    length_km: np.ndarray      # length of each kept line on the body (after resampling)
    source_line: np.ndarray    # index of the input line each kept line comes from
    n_input_edges: int = 0
    n_self_loops: int = 0
    params: dict = field(default_factory=dict)


def topology_graph(next_down, length_km) -> Graph:
    """Directed graph from a downstream index: line i runs node i -> node ``next_down[i]`` (-1: an outlet)."""
    nd = np.asarray(next_down, dtype=np.int64)
    n = len(nd)
    src = np.arange(n, dtype=np.int64)
    dst = np.where(nd >= 0, nd, n + np.arange(n, dtype=np.int64))
    return Graph(src, dst, np.asarray(length_km, dtype=np.float64))


def prune_and_order(graph: Graph, L_min_km: float = 20.0, upland_km2=None,
                    upland_min_km2: float | None = None):
    """(keep mask, Strahler order of the kept edges) for a directed graph: the shared channel rules."""
    keep = prune_graph(graph, L_min_km, upland_km2, upland_min_km2)
    order = strahler(Graph(graph.src[keep], graph.dst[keep], graph.length_km[keep]))
    return keep, order


def _snap_nodes(res: Lines, snap_km: float, planet):
    """Edges between snapped nodes for undirected polylines.

    Endpoints within ``snap_km`` of an endpoint of another line merge into one node; an endpoint
    within ``snap_km`` of an interior vertex of another line joins that vertex, which splits that line
    there (a confluence). Returns (node id per vertex, sorted node vertex indices per line).
    """
    b = body(planet)
    n_v = len(res.lon)
    lid = res.line_id
    first = res.offsets[:-1]
    last = res.offsets[1:] - 1
    endpoint = np.zeros(n_v, dtype=bool)
    endpoint[first] = True
    endpoint[last] = True
    xyz = _unit(res.lon, res.lat)
    chord = 2 * math.sin(snap_km * 1000.0 / (2 * b.mean_radius_m))
    tree = cKDTree(xyz)
    ends = np.concatenate([first, last])
    ends = np.unique(ends)
    lists = tree.query_ball_point(xyz[ends], r=chord)
    pa, pb = [], []
    cut = np.zeros(n_v, dtype=bool)
    for e, near in zip(ends, lists):
        near = np.asarray([v for v in near if lid[v] != lid[e]], dtype=np.int64)
        if len(near) == 0:
            continue
        is_end = endpoint[near]
        for v in near[is_end]:                      # endpoint meets endpoint: one node
            pa.append(e)
            pb.append(v)
        inner = near[~is_end]
        if len(inner):
            # a tributary ending on the side of another line: that line is split at the nearest vertex,
            # unless the line's own end is within the snap distance (then the endpoints already merged)
            p = lid[inner]
            clear = (np.linalg.norm(xyz[first[p]] - xyz[e], axis=1) > chord) & \
                    (np.linalg.norm(xyz[last[p]] - xyz[e], axis=1) > chord)
            inner = inner[clear]
            if len(inner):
                v = inner[np.argmin(np.linalg.norm(xyz[inner] - xyz[e], axis=1))]
                pa.append(e)
                pb.append(v)
                cut[v] = True
    parent = np.arange(n_v)
    if pa:
        adj = coo_matrix((np.ones(len(pa)), (np.asarray(pa), np.asarray(pb))), shape=(n_v, n_v))
        _, labels = connected_components(adj, directed=False)
        parent = labels
    else:
        parent = np.arange(n_v)
    return parent, endpoint | cut


def _orient_undirected(src, dst, length, node_lon, node_lat):
    """Orient undirected edges toward a root per connected system (longest-path end, lowest lat/lon)."""
    n = len(node_lon)
    m = len(src)
    w = np.maximum(length, 1e-9)
    adj = csr_matrix((np.concatenate([w, w]), (np.concatenate([src, dst]), np.concatenate([dst, src]))), shape=(n, n))
    ncomp, comp = connected_components(adj, directed=False)
    first_node = np.full(ncomp, -1, dtype=np.int64)
    first_node[comp[::-1]] = np.arange(n)[::-1]

    def farthest(sources):
        dist = dijkstra(adj, directed=False, indices=sources, min_only=True)
        dist = np.where(np.isfinite(dist), dist, -1.0)
        order = np.lexsort((dist, comp))
        last_of_comp = order[np.searchsorted(comp[order], np.arange(ncomp), side='right') - 1]
        return last_of_comp, dist

    u, _ = farthest(first_node)
    v, _ = farthest(u)
    # root: the lower of the two diameter ends by (lat, lon): deterministic, no flow direction in the data
    pick_u = (node_lat[u] < node_lat[v]) | ((node_lat[u] == node_lat[v]) & (node_lon[u] <= node_lon[v]))
    root = np.where(pick_u, u, v)
    dist = dijkstra(adj, directed=False, indices=root, min_only=True)
    flip = (dist[src] < dist[dst]) | ((dist[src] == dist[dst]) & (src > dst))
    new_src = np.where(flip, dst, src)
    new_dst = np.where(flip, src, dst)
    return new_src, new_dst, dist


def prune_network(lines, L_min_km: float = 20.0, snap_km: float = 1.0, vertex_spacing_m: float = 460.0,
                  upland_min_km2: float | None = None, *, planet='mars', upland_km2=None,
                  next_down=None) -> Network:
    """Resample, build the graph, prune and number a set of channel polylines (both planets).

    ``lines``        list of (n, 2) lon/lat arrays.
    ``next_down``    optional index (into ``lines``) of the line each line flows into, -1 for outlets
                     (HydroRIVERS NEXT_DOWN). With it the graph follows that topology and nothing is
                     snapped or split. Without it, endpoints within ``snap_km`` are snapped, tributaries
                     that end on another line split it at the confluence, and the network is oriented
                     toward the end of its longest path (the valley data carry no flow direction).
    ``upland_km2``   optional upstream area per line; with ``upland_min_km2`` the start threshold.
    Then: drop source segments < ``L_min_km`` repeatedly and systems < ``L_min_km``, and recompute
    Strahler order on what is left. Identical on both planets.
    """
    b = body(planet)
    params = {'L_min_km': L_min_km, 'snap_km': snap_km, 'vertex_spacing_m': vertex_spacing_m,
              'upland_min_km2': upland_min_km2, 'planet': b.planet,
              'topology': 'next_down' if next_down is not None else 'snapped_endpoints_oriented_to_root'}
    raw = Lines.from_list(lines)
    res = resample_lines(raw, vertex_spacing_m, b)
    up_in = None if upland_km2 is None else np.asarray(upland_km2, dtype=np.float64)
    if next_down is not None:
        nd = np.asarray(next_down, dtype=np.int64)
        n = len(nd)
        length = res.length_m(b) / 1000.0
        topo = topology_graph(nd, length)
        src, dst = topo.src, topo.dst
        polylines = res.to_list()
        edge_line = np.arange(n)
        up = up_in
        loops = 0
    else:
        node_of, is_node = _snap_nodes(res, snap_km, b)
        polylines, src_l, dst_l, edge_line = [], [], [], []
        for li in range(res.n_lines):
            a, z = res.offsets[li], res.offsets[li + 1]
            cuts = np.nonzero(is_node[a:z])[0]
            cuts = np.union1d(cuts, [0, z - a - 1])
            for c0, c1 in zip(cuts[:-1], cuts[1:]):
                sl = slice(a + c0, a + c1 + 1)
                polylines.append(np.column_stack([res.lon[sl], res.lat[sl]]))
                src_l.append(node_of[a + c0])
                dst_l.append(node_of[a + c1])
                edge_line.append(li)
        src, dst = np.asarray(src_l, dtype=np.int64), np.asarray(dst_l, dtype=np.int64)
        edge_line = np.asarray(edge_line, dtype=np.int64)
        length = Lines.from_list(polylines).length_m(b) / 1000.0 if polylines else np.empty(0)
        loop = src == dst
        loops = int(loop.sum())
        if loops:
            ok = ~loop
            polylines = [p for p, o in zip(polylines, ok) if o]
            src, dst, length, edge_line = src[ok], dst[ok], length[ok], edge_line[ok]
        up = None if up_in is None else up_in[edge_line]
        if len(src):
            nodes, inv = np.unique(np.concatenate([src, dst]), return_inverse=True)
            src, dst = inv[:len(src)], inv[len(src):]
            nlon = np.zeros(len(nodes))
            nlat = np.zeros(len(nodes))
            for p, s_, d_ in zip(polylines, src, dst):
                nlon[s_], nlat[s_] = p[0]
                nlon[d_], nlat[d_] = p[-1]
            src, dst, rank = _orient_undirected(src, dst, length, nlon, nlat)
            # reverse the stored polylines of flipped edges so every polyline runs downstream
            for i, p in enumerate(polylines):
                if not np.allclose(p[0], [nlon[src[i]], nlat[src[i]]]):
                    polylines[i] = p[::-1]
    graph = Graph(src, dst, length)
    if next_down is not None:
        keep, order = prune_and_order(graph, L_min_km, up, upland_min_km2)
    else:
        keep = prune_graph(graph, L_min_km, up, upland_min_km2)
        order = strahler_forest(Graph(src[keep], dst[keep], length[keep]), rank) if keep.any() \
            else np.zeros(0, dtype=np.int16)
    return Network([p for p, k in zip(polylines, keep) if k], order, length[keep], edge_line[keep],
                   n_input_edges=len(src), n_self_loops=loops, params=params)


# --------------------------------------------------------------------------
# dune type vocabulary
# --------------------------------------------------------------------------

def load_dune_vocab(path: str | Path) -> dict:
    """Read ``dune_type_vocab.csv`` into ``{(source, class): shared_type}``.

    Raises :class:`VocabularyError` if any row lacks ``reviewed_by`` or ``reviewed_at``, or has a
    ``shared_type`` outside crescentic, linear, dome, star, sand_sheet, other. The file is a judgement
    made by a person: the code never fills it in.
    """
    path = Path(path)
    with open(path, newline='') as fh:
        rows = list(csv.DictReader(fh))
    if not rows:
        raise VocabularyError(f'{path.name}: no rows')
    vocab: dict = {}
    for line, row in enumerate(rows, start=2):
        who = (row.get('reviewed_by') or '').strip()
        when = (row.get('reviewed_at') or '').strip()
        if not who or not when:
            raise VocabularyError(f'{path.name} line {line} ({row.get("source")},{row.get("source_class")}): '
                                  f'reviewed_by / reviewed_at are empty; the crosswalk must be reviewed first')
        shared = (row.get('shared_type') or '').strip()
        if shared not in DUNE_SHARED_TYPES:
            raise VocabularyError(f'{path.name} line {line}: shared_type {shared!r} is not one of '
                                  f'{list(DUNE_SHARED_TYPES)}')
        key = ((row.get('source') or '').strip(), (row.get('source_class') or '').strip())
        if key in vocab:
            raise VocabularyError(f'{path.name} line {line}: duplicate row for {key}')
        vocab[key] = shared
    return vocab


# --------------------------------------------------------------------------
# WKB lines without shapely
# --------------------------------------------------------------------------

def wkb_line_parts(wkb: bytes) -> tuple[list[np.ndarray], int]:
    """Parts of a (Multi)LineString WKB as (n, 2) arrays; parts with fewer than 2 vertices are dropped.

    Returns (parts, number_dropped). Used for the Mars valleys, where 10 features carry a 1-vertex
    part that shapely refuses to build.
    """
    parts: list[np.ndarray] = []
    dropped = 0
    view = memoryview(wkb)
    pos = 0

    def header(p):
        little = view[p] == 1
        end = '<' if little else '>'
        t = int(np.frombuffer(view[p + 1:p + 5], dtype=end + 'u4')[0])
        z = bool(t & 0x80000000) or (t & 0x0FFFFFFF) // 1000 in (1, 3)
        m = bool(t & 0x40000000) or (t & 0x0FFFFFFF) // 1000 in (2, 3)
        return end, (t & 0x0FFFFFFF) % 1000, 2 + int(z) + int(m), p + 5

    def read_line(p, end, ndim):
        nonlocal dropped
        n = int(np.frombuffer(view[p:p + 4], dtype=end + 'u4')[0])
        p += 4
        arr = np.frombuffer(view[p:p + 8 * ndim * n], dtype=end + 'f8').reshape(n, ndim)[:, :2]
        p += 8 * ndim * n
        if n >= 2:
            parts.append(np.array(arr, dtype=np.float64))
        else:
            dropped += 1
        return p

    end, kind, ndim, pos = header(pos)
    if kind == 2:
        read_line(pos, end, ndim)
    elif kind == 5:
        count = int(np.frombuffer(view[pos:pos + 4], dtype=end + 'u4')[0])
        pos += 4
        for _ in range(count):
            e2, k2, nd2, pos = header(pos)
            if k2 != 2:
                raise ValueError('MultiLineString holds a non-line part')
            pos = read_line(pos, e2, nd2)
    else:
        raise ValueError(f'WKB geometry type {kind} is not a line')
    return parts, dropped