Repository navigation
Expand file tree
/
Copy pathtracks.py
More file actions
3003 lines (2760 loc) · 130 KB
/
Copy pathtracks.py
File metadata and controls
3003 lines (2760 loc) · 130 KB
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
import colorsys
import dbm
import importlib
import itertools
import json
import math
import multiprocessing as mp
import os
import pickle
import shutil
import struct
from pathlib import Path
import tempfile
import kornia
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image, ImageDraw
from scipy.spatial import cKDTree
from tqdm import tqdm
import prefetch
from dt_targets import snap_dt_target, strip_dt_target_in_sample_frame
from spiral_progress import progress_or_null
from service_http import sha256_file
from loss_maps import diagnostics_enabled, record_loss_samples
import geom_utils
from sample_spiral import (
get_theta_and_radii,
get_theta_crossing_step_adjustments,
radius_from_unwrapped_shifted,
unwrap_shifted_radii,
)
TRACK_CROSSING_CACHE_VERSION = 1
TRACK_CROSSING_CACHE_SUFFIX = '.crossings.npz'
TRACK_STORE_SUFFIX = '.vctracks'
TRACK_STORE_VERSION = 1
TRACK_STORE_MAGIC = b'VCTRK01\0'
_DB_DIGEST_MEMO = {}
def _load_native_track_crossings():
"""Load the optional native crossing kernel shipped with Spiral."""
if os.environ.get('VC_DISABLE_NATIVE_TRACK_CROSSINGS') == '1':
return None
try:
return importlib.import_module('vc_spiral.track_crossings')
except ImportError:
return None
def _load_native_track_store():
"""Load the mmap-backed packed-track extension shipped with Spiral."""
try:
return importlib.import_module('vc_spiral.track_store')
except ImportError:
return None
def _flatten_tracks(tracks):
"""Concatenate ragged (n_i, 3) tracks into float32 points plus int64 offsets."""
lengths = np.fromiter(
(len(track) for track in tracks), dtype=np.int64, count=len(tracks))
offsets = np.empty(len(lengths) + 1, dtype=np.int64)
offsets[0] = 0
np.cumsum(lengths, out=offsets[1:])
flat = np.concatenate(
[np.asarray(track, dtype=np.float32) for track in tracks], axis=0)
return flat, offsets
class PackedTrackCollection:
"""A ragged track collection backed by a few contiguous native arrays."""
def __init__(
self, coordinates, offsets, source_ids, family_codes,
arclengths, tortuosities, *, store_path=None, rows=None):
self.coordinates = np.asarray(coordinates, dtype=np.float32)
self.offsets = np.asarray(offsets, dtype=np.int64)
self.source_ids = np.asarray(source_ids, dtype=np.uint64)
self.family_codes = np.asarray(family_codes, dtype=np.int8)
self.arclengths = np.asarray(arclengths, dtype=np.float64)
self.tortuosities = np.asarray(tortuosities, dtype=np.float64)
self.store_path = None if store_path is None else Path(store_path)
self.rows = (np.arange(len(self.source_ids), dtype=np.int64)
if rows is None else np.asarray(rows, dtype=np.int64))
if self.offsets.shape != (len(self.source_ids) + 1,):
raise ValueError('packed track offsets are not parallel to metadata')
if (self.family_codes.shape != self.source_ids.shape
or self.arclengths.shape != self.source_ids.shape
or self.tortuosities.shape != self.source_ids.shape):
raise ValueError('packed track metadata arrays are not parallel')
def __len__(self):
return len(self.rows)
def __getitem__(self, index):
if isinstance(index, slice):
return self.subset(np.arange(len(self), dtype=np.int64)[index])
row = int(self.rows[index])
return self.coordinates[self.offsets[row]:self.offsets[row + 1]]
def subset(self, indices):
indices = np.asarray(indices, dtype=np.int64)
return PackedTrackCollection(
self.coordinates, self.offsets, self.source_ids,
self.family_codes, self.arclengths, self.tortuosities,
store_path=self.store_path, rows=self.rows[indices])
@property
def selected_source_ids(self):
return self.source_ids[self.rows]
@property
def selected_family_codes(self):
return self.family_codes[self.rows]
@property
def selected_arclengths(self):
return self.arclengths[self.rows]
@property
def selected_tortuosities(self):
return self.tortuosities[self.rows]
@property
def selected_lengths(self):
return self.offsets[self.rows + 1] - self.offsets[self.rows]
def materialize(self, workers=None):
identity = (len(self.rows) == len(self.source_ids)
and np.array_equal(
self.rows, np.arange(len(self.rows), dtype=np.int64)))
if identity:
return self.coordinates, self.offsets
native = _load_native_track_store()
if native is not None and hasattr(native, 'compact'):
result = native.compact(
self.coordinates, self.offsets, self.rows,
workers=min(32, os.cpu_count() or 1)
if workers is None else int(workers))
return (np.asarray(result['coordinates']),
np.asarray(result['offsets']))
return _flatten_tracks([self[index] for index in range(len(self))])
def as_packed_polylines(self):
"""Return contiguous coordinates and offsets for bulk geometry output."""
return self.materialize()
class _NativeCrossingProgress:
"""Present native phase counters as one honest tqdm bar at a time."""
def __init__(self, enabled):
self.enabled = bool(enabled)
self.phase = None
self.progress = None
self.completed = 0
def __call__(self, phase, completed, total):
if not self.enabled:
return
completed = int(completed)
total = int(total)
if phase != self.phase:
self.close()
self.phase = phase
self.completed = 0
units = {
'radix sorting packed voxel keys': 'passes',
'finding exact crossings': 'points',
'sorting crossing events': 'events',
'computing track arclengths': 'tracks',
'consolidating track pairs': 'pairs',
'encoding crossing CSR': 'pairs',
}
self.progress = tqdm(
total=total, desc=phase, unit=units.get(phase, 'items'))
if self.progress.total != total:
self.progress.total = total
self.progress.refresh()
self.progress.update(max(0, completed - self.completed))
self.completed = completed
if completed >= total:
self.close()
def close(self):
if self.progress is not None:
self.progress.close()
self.progress = None
self.phase = None
self.completed = 0
_SQLITE_MAGIC = b'SQLite format 3\x00'
def _is_sqlite_dbm(path):
# dbm.sqlite3 (the default dbm backend since Python 3.13) writes a plain
# SQLite file; dbm.whichdb() cannot identify it on interpreters that lack
# the dbm.sqlite3 module.
try:
with open(path, 'rb') as stream:
return stream.read(len(_SQLITE_MAGIC)) == _SQLITE_MAGIC
except OSError:
return False
class _SQLiteTrackDBM:
"""Read-only view of a dbm.sqlite3 store, independent of interpreter version.
Uses the same single-table schema as CPython's Lib/dbm/sqlite3.py
(``Dict(key BLOB, value BLOB)``) and only the read operations the track
loaders need.
"""
def __init__(self, path):
import sqlite3
# Complete, checkpointed stores need no reader-created sidecars. An
# existing WAL may hold committed pages, so retain normal SQLite
# locking and WAL reads while it is present.
# SQLite opens a symlink's target; check that target's WAL as well.
path = Path(path).resolve()
uri = path.as_uri() + '?mode=ro'
if not Path(str(path) + '-wal').exists():
uri += '&immutable=1'
self._connection = sqlite3.connect(uri, uri=True)
def keys(self):
return [key for (key,) in self._connection.execute('SELECT key FROM Dict')]
def __getitem__(self, key):
if isinstance(key, str):
key = key.encode()
row = self._connection.execute(
'SELECT value FROM Dict WHERE key = CAST(? AS BLOB)', (key,)).fetchone()
if row is None:
raise KeyError(key)
return row[0]
def __len__(self):
return self._connection.execute('SELECT COUNT(key) FROM Dict').fetchone()[0]
def close(self):
self._connection.close()
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
def open_tracks_dbm(path):
"""Open a tracks DBM read-only, including SQLite-backed stores on every Python version."""
text = os.fspath(path)
if _is_sqlite_dbm(text):
return _SQLiteTrackDBM(text)
return dbm.open(text, 'r')
def normalize_tracks_dbm_path(path):
"""Return the logical DBM path, accepting a common ``.db`` backing path."""
text = os.fspath(path)
if dbm.whichdb(text) or _is_sqlite_dbm(text):
return text
if text.endswith('.db') and dbm.whichdb(text[:-3]):
return text[:-3]
raise FileNotFoundError(f'not a readable DBM logical path: {path}')
def track_crossing_cache_path(path):
"""Return the conventional exact-crossing sidecar path for a tracks DBM."""
return Path(normalize_tracks_dbm_path(path) + TRACK_CROSSING_CACHE_SUFFIX)
def _tracks_db_signature(path):
"""Fingerprint the portable set of files backing a logical DBM."""
logical = Path(normalize_tracks_dbm_path(path))
candidates = [
logical,
*[Path(str(logical) + suffix)
for suffix in ('.db', '.dat', '.dir', '.bak', '.pag')],
]
result = []
seen = set()
for candidate in candidates:
try:
resolved = candidate.resolve()
if resolved in seen or not candidate.is_file():
continue
seen.add(resolved)
stat = candidate.stat()
result.append((candidate.name, stat.st_size, stat.st_mtime_ns))
except OSError:
continue
if not result:
raise FileNotFoundError(f'could not stat DBM backing files for {path}')
return sorted(result)
def _db_signatures_match(stored, expected):
"""Compare a stored DBM signature with the current one.
Signatures are ``(name, size, mtime_ns)`` per backing file. Downloads and
copies routinely lose the sub-second part of mtime (HTTP Last-Modified has
one-second resolution), which made every cache shipped alongside a dataset
look stale after download even though name and size matched. Name and size
must match exactly. mtime must match exactly, except that when one side is
a whole second (a copy that dropped the sub-second part) the seconds must
match. Two nanosecond mtimes still have to agree, so an edit within the
same second on a local file is still detected.
"""
if not isinstance(stored, list) or len(stored) != len(expected):
return False
try:
for item, want in zip(stored, expected):
if not isinstance(item, (list, tuple)) or len(item) != 3:
return False
if item[0] != want[0] or int(item[1]) != int(want[1]):
return False
have, need = int(item[2]), int(want[2])
if have != need:
truncated = have % 1_000_000_000 == 0 or need % 1_000_000_000 == 0
if not truncated or have // 1_000_000_000 != need // 1_000_000_000:
return False
except (TypeError, ValueError):
return False # malformed metadata (e.g. null entries): treat as stale
return True
def _tracks_db_digest(path, signature):
"""Hash the backing files listed in a ``(name, size, mtime_ns)`` signature.
Returns ``{name: 'sha256:<hex>'}``, or ``None`` if a file no longer has
the size and mtime recorded in ``signature`` once it has been read. Each
file is hashed at most once per process for a given path, size and mtime.
"""
folder = Path(normalize_tracks_dbm_path(path)).parent
digests = {}
for name, size, mtime_ns in signature:
file_path = folder / name
key = (os.fspath(file_path.resolve()), int(size), int(mtime_ns))
if key not in _DB_DIGEST_MEMO:
digest = sha256_file(file_path)
stat = file_path.stat()
if (stat.st_size, stat.st_mtime_ns) != key[1:]:
return None
_DB_DIGEST_MEMO[key] = 'sha256:' + digest
digests[name] = _DB_DIGEST_MEMO[key]
return digests
def _db_contents_match(stored, stored_digest, path, expected):
"""Whether a DBM that fails ``_db_signatures_match`` still has the same bytes.
Copies and downloads that stamp a new mtime (``cp``, ``curl`` without
``-R``, Python ``requests``) fail the mtime check although the files are
identical. When the sidecar recorded content digests, names and sizes must
match and every backing file must hash the same. Size alone is not enough:
SQLite-backed DBMs (``dbm.sqlite3``, Python >= 3.14) rarely change size
when edited. Sidecars without digests keep the mtime rule.
"""
if stored_digest is None or not isinstance(stored, list):
return False
try:
if [[str(name), int(size)] for name, size, _mtime in stored] != [
[name, size] for name, size, _mtime in expected]:
return False
except (TypeError, ValueError):
return False
return _tracks_db_digest(path, expected) == stored_digest
def track_store_path(path):
"""Return the conventional packed-store directory beside a tracks DBM."""
return Path(normalize_tracks_dbm_path(path) + TRACK_STORE_SUFFIX)
def write_packed_track_store(
path, destination=None, *, force=False, show_progress=True):
"""Stream a legacy pickle DBM into the mmap-friendly packed track format."""
logical = normalize_tracks_dbm_path(path)
destination = (track_store_path(logical) if destination is None
else Path(destination))
if destination.exists() and not force:
raise FileExistsError(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(
prefix=f'.{destination.name}.', dir=destination.parent))
length_batches = []
source_id_batches = []
family_code_batches = []
z_bound_batches = []
arclength_batches = []
tortuosity_batches = []
point_count = 0
try:
with (open_tracks_dbm(logical) as database,
(temporary / 'coordinates.i32').open('wb') as coordinate_stream):
keys = sorted(database.keys())
for key_ordinal, key in enumerate(tqdm(
keys, desc='packing track store', unit='keys',
disable=not show_progress)):
entries = pickle.loads(database[key])
nonempty = np.fromiter(
(index for index, entry in enumerate(entries) if len(entry)),
dtype=np.int64)
if not len(nonempty):
continue
lengths = np.fromiter(
(len(entries[index]) for index in nonempty),
dtype=np.int64, count=len(nonempty))
coordinates = np.concatenate([
np.asarray(entries[index]) for index in nonempty])
if coordinates.ndim != 2 or coordinates.shape[1] != 3:
raise ValueError(
f'track DBM key {key!r} contains invalid coordinates')
if (not np.issubdtype(coordinates.dtype, np.integer)
and (not np.isfinite(coordinates).all()
or not np.all(coordinates == np.rint(coordinates)))):
raise ValueError(
f'track DBM key {key!r} contains non-integral coordinates')
coordinates = np.asarray(coordinates, dtype='<i4')
coordinates.tofile(coordinate_stream)
starts = np.empty(len(lengths), dtype=np.int64)
starts[0] = 0
np.cumsum(lengths[:-1], out=starts[1:])
z_values = coordinates[:, 0]
z_bounds = np.column_stack((
np.minimum.reduceat(z_values, starts),
np.maximum.reduceat(z_values, starts),
)).astype('<i4', copy=False)
steps = np.empty(len(coordinates), dtype=np.float64)
steps[0] = 0.0
deltas = np.subtract(
coordinates[1:], coordinates[:-1], dtype=np.float64)
steps[1:] = np.linalg.norm(deltas, axis=1)
steps[starts] = 0.0
arclengths = np.add.reduceat(steps, starts)
chords = np.linalg.norm(
coordinates[starts + lengths - 1].astype(np.float64)
- coordinates[starts].astype(np.float64), axis=1)
tortuosities = np.full(len(lengths), np.inf, dtype=np.float64)
np.divide(
arclengths, chords, out=tortuosities, where=chords > 0)
prefix = key.decode().split(':', 1)[0]
family_code = 0 if prefix == 'h' else (
1 if prefix in ('vx', 'vy') else -1)
length_batches.append(lengths)
source_id_batches.append(
(np.uint64(key_ordinal) << np.uint64(32))
| nonempty.astype(np.uint64, copy=False))
family_code_batches.append(np.full(
len(nonempty), family_code, dtype=np.int8))
z_bound_batches.append(z_bounds)
arclength_batches.append(arclengths)
tortuosity_batches.append(tortuosities)
point_count += len(coordinates)
lengths = (np.concatenate(length_batches)
if length_batches else np.empty(0, dtype=np.int64))
track_count = len(lengths)
offsets = np.empty(track_count + 1, dtype='<i8')
offsets[0] = 0
np.cumsum(lengths, out=offsets[1:])
if int(offsets[-1]) != point_count:
raise RuntimeError('packed track point count changed while writing')
source_ids = (np.concatenate(source_id_batches).astype('<u8', copy=False)
if source_id_batches else np.empty(0, dtype='<u8'))
family_codes = (np.concatenate(family_code_batches)
if family_code_batches else np.empty(0, dtype=np.int8))
z_bounds = (np.concatenate(z_bound_batches).astype('<i4', copy=False)
if z_bound_batches else np.empty((0, 2), dtype='<i4'))
arclengths = (np.concatenate(arclength_batches).astype('<f8', copy=False)
if arclength_batches else np.empty(0, dtype='<f8'))
tortuosities = (
np.concatenate(tortuosity_batches).astype('<f8', copy=False)
if tortuosity_batches else np.empty(0, dtype='<f8'))
offsets.tofile(temporary / 'offsets.i64')
source_ids.tofile(temporary / 'source_ids.u64')
family_codes.tofile(temporary / 'family_codes.i8')
z_bounds.tofile(temporary / 'z_bounds.i32')
arclengths.tofile(temporary / 'arclengths.f64')
tortuosities.tofile(temporary / 'tortuosities.f64')
with (temporary / 'header.bin').open('wb') as stream:
stream.write(struct.pack(
'<8sIIQQ4Q', TRACK_STORE_MAGIC, TRACK_STORE_VERSION, 64,
track_count, point_count, 0, 0, 0, 0))
stream.flush()
os.fsync(stream.fileno())
signature = _tracks_db_signature(logical)
metadata = {
'version': TRACK_STORE_VERSION,
'source_db_signature': [list(item) for item in signature],
'source_db_digest': _tracks_db_digest(logical, signature),
'track_count': track_count,
'point_count': point_count,
}
with (temporary / 'metadata.json').open('w', encoding='utf-8') as stream:
json.dump(metadata, stream, indent=2, sort_keys=True)
stream.flush()
os.fsync(stream.fileno())
if destination.exists():
if not force:
raise FileExistsError(destination)
if destination.is_dir():
shutil.rmtree(destination)
else:
destination.unlink()
os.replace(temporary, destination)
temporary = None
print(
f'wrote packed track store {destination}: {track_count} tracks, '
f'{point_count} points')
return destination
finally:
if temporary is not None and temporary.exists():
shutil.rmtree(temporary, ignore_errors=True)
def _packed_store_if_current(path):
"""Return an adjacent packed store only when it matches the source DBM."""
store = track_store_path(path)
if not store.is_dir():
return None
try:
with (store / 'metadata.json').open('r', encoding='utf-8') as stream:
metadata = json.load(stream)
if metadata.get('version') != TRACK_STORE_VERSION:
return None
expected = [list(item) for item in _tracks_db_signature(path)]
stored = metadata.get('source_db_signature')
if not (_db_signatures_match(stored, expected)
or _db_contents_match(stored, metadata.get('source_db_digest'),
path, expected)):
return None
return store
except (OSError, ValueError, KeyError, json.JSONDecodeError):
return None
def validate_track_sampling_config(config):
"""Validate and normalize the optional session-scoped track policies."""
weights = config.get('track_length_bin_weights')
if weights is not None:
if not isinstance(weights, (list, tuple)) or len(weights) != 3:
raise ValueError('track_length_bin_weights must be null or [short, medium, long]')
if any(isinstance(value, bool) or not isinstance(value, (int, float))
or not math.isfinite(float(value)) or float(value) < 0
for value in weights):
raise ValueError('track_length_bin_weights values must be finite and non-negative')
weights = np.asarray(weights, dtype=np.float64)
if float(weights.sum()) <= 0:
raise ValueError('track_length_bin_weights must contain at least one positive value')
weights = weights / weights.sum()
max_tortuosity = config.get('track_max_tortuosity')
if max_tortuosity is not None:
if (isinstance(max_tortuosity, bool)
or not isinstance(max_tortuosity, (int, float))
or not math.isfinite(float(max_tortuosity))
or float(max_tortuosity) < 1.0):
raise ValueError('track_max_tortuosity must be null or a finite number >= 1')
max_tortuosity = float(max_tortuosity)
max_crossings = config.get('track_max_track_crossing_per_step', 0)
if (isinstance(max_crossings, bool) or not isinstance(max_crossings, (int, float))
or not math.isfinite(float(max_crossings))
or not float(max_crossings).is_integer() or int(max_crossings) < 0):
raise ValueError('max_track_crossing_per_step must be a non-negative integer')
crossing_precompute_max = config.get('track_crossing_precompute_max', 8)
if (isinstance(crossing_precompute_max, bool)
or not isinstance(crossing_precompute_max, (int, float))
or not math.isfinite(float(crossing_precompute_max))
or not float(crossing_precompute_max).is_integer()
or int(crossing_precompute_max) < 0):
raise ValueError('track_crossing_precompute_max must be a non-negative integer')
# Existing profiles may already request more than the default ceiling.
# Honor that initial value by preparing at least as many slots; the
# resident session still rejects later Run requests above what it prepared.
crossing_precompute_max = max(
int(crossing_precompute_max), int(max_crossings))
sample_spacings = {}
for key, default in (
('track_min_sample_spacing', 20.0),
('track_max_sample_spacing', 60.0)):
value = config.get(key, default)
if (isinstance(value, bool)
or not isinstance(value, (int, float))
or not math.isfinite(float(value))
or float(value) <= 0):
raise ValueError(f'{key} must be a finite number > 0')
sample_spacings[key] = float(value)
if (sample_spacings['track_min_sample_spacing']
> sample_spacings['track_max_sample_spacing']):
raise ValueError(
'track_min_sample_spacing must be <= track_max_sample_spacing')
return {
'length_bin_weights': weights,
'max_tortuosity': max_tortuosity,
'max_crossings': int(max_crossings),
'crossing_precompute_max': crossing_precompute_max,
'min_sample_spacing': sample_spacings['track_min_sample_spacing'],
'max_sample_spacing': sample_spacings['track_max_sample_spacing'],
}
def _polyline_arclengths(tracks):
return np.asarray([
np.linalg.norm(np.diff(np.asarray(track, dtype=np.float64), axis=0), axis=1).sum()
if len(track) >= 2 else 0.0
for track in tracks
], dtype=np.float64)
def _track_tortuosities(tracks, arclengths):
chords = np.asarray([
np.linalg.norm(np.asarray(track[-1], dtype=np.float64)
- np.asarray(track[0], dtype=np.float64))
if len(track) >= 2 else 0.0
for track in tracks
], dtype=np.float64)
result = np.full(len(tracks), np.inf, dtype=np.float64)
np.divide(arclengths, chords, out=result, where=chords > 0)
return result
def filter_tracks_to_outer_shell(
tracks, shell_envelope, track_families=None, max_points_per_chunk=500_000,
return_indices=False):
"""Drop tracks whose two endpoints are outside the shell envelope."""
if shell_envelope is None or not tracks:
result = (tracks, track_families)
if return_indices:
return (*result, np.arange(len(tracks), dtype=np.int64))
return result
if track_families is not None and len(track_families) != len(tracks):
raise ValueError('track_families must be parallel to tracks')
if isinstance(tracks, PackedTrackCollection):
keep = np.zeros(len(tracks), dtype=bool)
tracks_per_chunk = max(1, int(max_points_per_chunk) // 2)
for start in range(0, len(tracks), tracks_per_chunk):
local_rows = np.arange(
start, min(start + tracks_per_chunk, len(tracks)),
dtype=np.int64)
rows = tracks.rows[local_rows]
begin = tracks.offsets[rows]
end = tracks.offsets[rows + 1] - 1
endpoints = np.stack((
tracks.coordinates[begin], tracks.coordinates[end]), axis=1)
with torch.no_grad():
target_radius, radius, _confidence, _valid = shell_envelope.lookup(
torch.from_numpy(endpoints.reshape(-1, 3)))
endpoint_inside = (radius <= target_radius).view(-1, 2).any(dim=1)
keep[local_rows] = endpoint_inside.cpu().numpy()
kept_indices = np.flatnonzero(keep)
filtered_tracks = tracks.subset(kept_indices)
filtered_families = (
np.asarray(track_families)[kept_indices]
if track_families is not None else None)
print(
f'outer-shell track filter: kept {len(filtered_tracks)} / {len(tracks)} '
f'tracks; excluded {len(tracks) - len(filtered_tracks)} entirely '
'outside tracks (packed)')
result = (filtered_tracks, filtered_families)
if return_indices:
return (*result, kept_indices)
return result
keep = np.zeros(len(tracks), dtype=bool)
nonempty = np.asarray(
[index for index, track in enumerate(tracks) if len(track)], dtype=np.int64)
tracks_per_chunk = max(1, int(max_points_per_chunk) // 2)
for start in range(0, len(nonempty), tracks_per_chunk):
batch_indices = nonempty[start:start + tracks_per_chunk]
endpoints = np.stack([
np.stack([tracks[index][0], tracks[index][-1]])
for index in batch_indices
]).astype(np.float32, copy=False)
with torch.no_grad():
target_radius, radius, _confidence, _valid = shell_envelope.lookup(
torch.from_numpy(endpoints.reshape(-1, 3)))
endpoint_inside = (radius <= target_radius).view(-1, 2).any(dim=1)
keep[batch_indices] = endpoint_inside.cpu().numpy()
kept_indices = np.flatnonzero(keep)
filtered_tracks = [tracks[index] for index in kept_indices]
filtered_families = (
[track_families[index] for index in kept_indices]
if track_families is not None else None)
print(
f'outer-shell track filter: kept {len(filtered_tracks)} / {len(tracks)} tracks; '
f'excluded {len(tracks) - len(filtered_tracks)} entirely outside tracks'
)
result = (filtered_tracks, filtered_families)
if return_indices:
return (*result, kept_indices)
return result
def _length_bin_probabilities(arclengths, weights, device):
edges = np.quantile(arclengths, [1 / 3, 2 / 3])
bin_ids = (arclengths > edges[0]).astype(np.int64)
bin_ids += (arclengths > edges[1]).astype(np.int64)
counts = np.bincount(bin_ids, minlength=3)
available_weights = np.where(counts > 0, weights, 0.0)
if available_weights.sum() <= 0:
raise ValueError(
'track_length_bin_weights assign no probability to the non-empty length bins')
available_weights /= available_weights.sum()
probabilities = available_weights[bin_ids] / counts[bin_ids]
print(
'track length bins: '
f'short <= {edges[0]:.1f} ({counts[0]}), '
f'medium <= {edges[1]:.1f} ({counts[1]}), long ({counts[2]}); '
f'effective weights {available_weights.tolist()}'
)
return torch.as_tensor(probabilities, dtype=torch.float32, device=device)
def configure_prepared_track_sampling(prepared_tracks, config):
"""Apply Run-scoped track policies to an already prepared track pool."""
if prepared_tracks is None:
return
current = {
'track_length_bin_weights': prepared_tracks.get('length_bin_weights'),
'track_max_track_crossing_per_step': prepared_tracks.get('active_max_crossings', 0),
'track_crossing_precompute_max': prepared_tracks.get(
'crossing_precompute_max', 0),
}
current.update({
key: config[key] for key in current
if key in config
})
policy = validate_track_sampling_config(current)
if 'track_length_bin_weights' in config:
weights = policy['length_bin_weights']
if weights is None:
prepared_tracks.pop('sampling_probabilities', None)
prepared_tracks.pop('sampling_probabilities_cpu', None)
prepared_tracks['length_bin_weights'] = None
else:
probabilities = _length_bin_probabilities(
prepared_tracks['arclengths_cpu'], weights,
prepared_tracks['device'])
prepared_tracks['sampling_probabilities'] = probabilities
prepared_tracks['sampling_probabilities_cpu'] = np.asarray(
probabilities.detach().cpu(), dtype=np.float64)
prepared_tracks['length_bin_weights'] = weights.tolist()
maximum = policy['max_crossings']
prepared_maximum = prepared_tracks.get('crossing_precompute_max', 0)
if maximum > prepared_maximum:
raise ValueError(
f'max_track_crossing_per_step={maximum} exceeds the session\'s '
f'prepared crossing ceiling ({prepared_maximum}); reload with a larger '
'track_crossing_precompute_max')
prepared_tracks['active_max_crossings'] = maximum
def _track_tangent(track, raw_index, radius_voxels=12.0):
point = np.asarray(track[raw_index], dtype=np.float64)
left = raw_index
while left > 0 and np.linalg.norm(np.asarray(track[left], dtype=np.float64) - point) < radius_voxels:
left -= 1
right = raw_index
while (right + 1 < len(track)
and np.linalg.norm(np.asarray(track[right], dtype=np.float64) - point) < radius_voxels):
right += 1
vector = np.asarray(track[right], dtype=np.float64) - np.asarray(track[left], dtype=np.float64)
norm = np.linalg.norm(vector)
return vector / norm if norm else None
def _pack_track_points(
points, chunk_size=2_000_000, show_progress=False, destination=None):
"""Pack zyx coordinates without materialising an (N, 3) int64 copy.
Track pools routinely contain tens of millions of float32 points. Casting
the complete array to int64 used more memory than the coordinates
themselves and created another similarly sized temporary while combining
the columns. Fill the packed output a chunk at a time instead.
"""
points = np.asarray(points)
if points.ndim != 2 or points.shape[1] != 3:
raise ValueError('track points must have shape (N, 3)')
if destination is None:
packed = np.empty(len(points), dtype=np.uint64)
else:
packed = np.asarray(destination)
if packed.dtype != np.uint64 or packed.shape != (len(points),):
raise ValueError(
'packed track destination must be a uint64 vector parallel to points')
chunk_size = max(1, int(chunk_size))
coordinate_limit = 1 << 20
shift_z = np.uint64(40)
shift_y = np.uint64(20)
chunks = range(0, len(points), chunk_size)
if show_progress:
chunks = tqdm(
chunks, total=math.ceil(len(points) / chunk_size),
desc='packing track coordinates', unit='chunks')
for start in chunks:
stop = min(start + chunk_size, len(points))
source = points[start:stop]
if (not np.all(np.isfinite(source)) or np.any(source < 0)
or np.any(source >= coordinate_limit)):
raise ValueError(
'track coordinates must lie in [0, 2**20) for crossing pairing')
destination = packed[start:stop]
np.copyto(destination, source[:, 0], casting='unsafe')
destination <<= shift_z
temporary = source[:, 1].astype(np.uint64)
temporary <<= shift_y
destination |= temporary
np.copyto(temporary, source[:, 2], casting='unsafe')
destination |= temporary
return packed
def _pack_track_collection(
tracks, offsets, show_progress=False, chunk_size=2_000_000):
"""Pack a ragged track collection without concatenating its coordinates."""
packed = np.empty(int(offsets[-1]), dtype=np.uint64)
chunk_size = max(1, int(chunk_size))
progress = tqdm(
total=len(tracks), desc='packing track coordinates', unit='tracks',
disable=not show_progress)
track_begin = 0
try:
while track_begin < len(tracks):
point_begin = int(offsets[track_begin])
point_limit = point_begin + chunk_size
track_end = int(np.searchsorted(
offsets, point_limit, side='right')) - 1
track_end = max(track_begin + 1, min(track_end, len(tracks)))
point_end = int(offsets[track_end])
if track_end == track_begin + 1:
coordinates = tracks[track_begin]
else:
coordinates = np.concatenate(
tracks[track_begin:track_end], axis=0)
_pack_track_points(
coordinates, destination=packed[point_begin:point_end])
progress.update(track_end - track_begin)
track_begin = track_end
finally:
progress.close()
return packed
_CROSSING_WORKER_STATE = None
_CROSSING_DISK_WORKER_STATE = None
def _find_crossing_events_chunk(group_range):
"""Scan a bounded range of the sorted packed-coordinate index."""
if _CROSSING_WORKER_STATE is None:
raise RuntimeError('crossing worker state is not initialized')
(tracks, families, offsets, packed, order,
angle_cutoff) = _CROSSING_WORKER_STATE
position_begin, position_end = group_range
flat_indices = order[position_begin:position_end]
sorted_packed = packed[flat_indices]
boundaries = np.flatnonzero(sorted_packed[1:] != sorted_packed[:-1]) + 1
starts = np.r_[0, boundaries]
stops = np.r_[boundaries, len(sorted_packed)]
shared = stops - starts >= 2
starts = starts[shared]
stops = stops[shared]
tangent_cache = {}
raw_events = {}
for start, stop in zip(starts, stops):
group_flat_indices = flat_indices[int(start):int(stop)]
track_ids = np.searchsorted(
offsets[1:], group_flat_indices, side='right')
local_indices = group_flat_indices - offsets[track_ids]
unique = {}
for track_id, local_index in zip(track_ids, local_indices):
track_id = int(track_id)
local_index = int(local_index)
previous = unique.get(track_id)
if previous is None or local_index < previous:
unique[track_id] = local_index
if len(unique) < 2:
continue
for first, second in itertools.combinations(unique, 2):
if (families[first] is None or families[second] is None
or families[first] == families[second]):
continue
first_index, second_index = unique[first], unique[second]
first_key, second_key = (first, first_index), (second, second_index)
if first_key not in tangent_cache:
tangent_cache[first_key] = _track_tangent(tracks[first], first_index)
if second_key not in tangent_cache:
tangent_cache[second_key] = _track_tangent(tracks[second], second_index)
first_tangent = tangent_cache[first_key]
second_tangent = tangent_cache[second_key]
if first_tangent is None or second_tangent is None:
continue
if abs(float(np.dot(first_tangent, second_tangent))) > angle_cutoff:
continue
raw_events.setdefault((first, second), []).append(
(first_index, second_index))
return position_end - position_begin, raw_events
def _crossing_events_to_csr(
raw_events, tracks, source_ids, show_progress=False):
"""Consolidate exact-voxel events into the cached partner CSR."""
crossing_track_ids = set(itertools.chain.from_iterable(raw_events))
needed_local_indices = {track_id: set() for track_id in crossing_track_ids}
for (first, second), events in raw_events.items():
needed_local_indices[first].update(event[0] for event in events)
needed_local_indices[second].update(event[1] for event in events)
event_positions = {}
track_arclengths = {}
for track_id, local_indices in needed_local_indices.items():
cumulative = np.r_[0.0, np.cumsum(np.linalg.norm(
np.diff(np.asarray(tracks[track_id], dtype=np.float64), axis=0),
axis=1))]
event_positions[track_id] = {
local_index: float(cumulative[local_index])
for local_index in local_indices
}
track_arclengths[track_id] = float(cumulative[-1])
del needed_local_indices
adjacency = {}
accepted_events = 0
pair_iterator = raw_events.items()
if show_progress:
pair_iterator = tqdm(
pair_iterator, total=len(raw_events),
desc='consolidating track pairs', unit='pairs')
for (first, second), events in pair_iterator:
events.sort()
clusters = []
cluster = []
for event in events:
if (cluster and abs(event[0] - cluster[-1][0]) <= 4
and abs(event[1] - cluster[-1][1]) <= 4):
cluster.append(event)
else:
if cluster:
clusters.append(cluster)
cluster = [event]
if cluster:
clusters.append(cluster)
representatives = [cluster[len(cluster) // 2] for cluster in clusters]
best = None
for first_index, second_index in representatives:
first_position = event_positions[first][first_index]
second_position = event_positions[second][second_index]
clearance = min(
first_position, track_arclengths[first] - first_position,
second_position, track_arclengths[second] - second_position,
)
candidate = (
clearance, first_position, second_position,
first_index, second_index,
)
if best is None or candidate > best:
best = candidate
(clearance, first_position, second_position,
best_first_index, best_second_index) = best
adjacency.setdefault(first, []).append((
second, first_position, clearance,
best_first_index, best_second_index,
))
adjacency.setdefault(second, []).append((
first, second_position, clearance,
best_second_index, best_first_index,
))
accepted_events += len(representatives)
del raw_events, event_positions, track_arclengths
counts = np.zeros(len(tracks), dtype=np.int64)
for track_id, candidates in adjacency.items():
counts[track_id] = len(candidates)
csr_offsets = np.empty(len(tracks) + 1, dtype=np.int64)
csr_offsets[0] = 0
np.cumsum(counts, out=csr_offsets[1:])
partner_slots = int(csr_offsets[-1])
partners = np.empty(partner_slots, dtype=np.int32)
self_local = np.empty(partner_slots, dtype=np.int32)
partner_local = np.empty(partner_slots, dtype=np.int32)
positions = np.empty(partner_slots, dtype=np.float64)
clearances = np.empty(partner_slots, dtype=np.float64)
track_iterator = adjacency.items()
if show_progress:
track_iterator = tqdm(