diffct 2.5.2__py3-none-any.whl → 2.5.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
diffct/__init__.py CHANGED
@@ -15,6 +15,11 @@ from .projectors import (
15
15
  )
16
16
 
17
17
  from .operators import Projector
18
+ from .clinical import (ClinicalScan, ClinicalScanProbe, ClinicalGeometry, read_dicom_ct_pd,
19
+ probe_dicom_ct_pd, clinical_geometry)
20
+ from .mayo import (CTImageSeries, Mayo2020Case, MayoChallenge2016Case, attenuation_to_hu,
21
+ hu_to_attenuation, discover_mayo_2020_cases, discover_mayo_challenge_2016_cases,
22
+ load_mayo_case, read_dicom_ct_images)
18
23
  from .storage import TensorStore, NpyStore
19
24
  from .surfaces import ParameterizedSurface
20
25
  from .reconstruction import (
@@ -64,10 +69,25 @@ try:
64
69
  except ImportError:
65
70
  pass
66
71
 
67
- __version__ = '2.5.2'
72
+ __version__ = '2.5.4'
68
73
 
69
74
  __all__ = [
70
75
  'Projector',
76
+ 'ClinicalScan',
77
+ 'ClinicalScanProbe',
78
+ 'ClinicalGeometry',
79
+ 'read_dicom_ct_pd',
80
+ 'probe_dicom_ct_pd',
81
+ 'clinical_geometry',
82
+ 'CTImageSeries',
83
+ 'Mayo2020Case',
84
+ 'MayoChallenge2016Case',
85
+ 'attenuation_to_hu',
86
+ 'hu_to_attenuation',
87
+ 'discover_mayo_2020_cases',
88
+ 'discover_mayo_challenge_2016_cases',
89
+ 'load_mayo_case',
90
+ 'read_dicom_ct_images',
71
91
  'TensorStore',
72
92
  'NpyStore',
73
93
  'ParameterizedSurface',
diffct/_solver_state.py CHANGED
@@ -1,10 +1,14 @@
1
1
  """Bounded solver state, owned reductions and complete checkpoint publication."""
2
2
 
3
+ from contextlib import contextmanager, suppress
4
+ from enum import Enum
3
5
  import hashlib
4
6
  import json
5
7
  import math
6
8
  import numbers
9
+ import os
7
10
  from pathlib import Path
11
+ import shutil
8
12
 
9
13
  import torch
10
14
  import torch.distributed as dist
@@ -44,6 +48,25 @@ def agreement(operator, error=None, token=None, *, cache_key=None):
44
48
  mismatch=mismatch)
45
49
 
46
50
 
51
+ @contextmanager
52
+ def solver_io_phase(operator):
53
+ """Agree local solver I/O failures across ranks before the next collective."""
54
+ world = getattr(operator, "world_size", 1)
55
+ if world == 1:
56
+ yield
57
+ return
58
+ error = None
59
+ try:
60
+ yield
61
+ except Exception as caught:
62
+ error = caught
63
+ partition = getattr(operator, "_partition", None)
64
+ if partition is not None:
65
+ partition.preflight(error)
66
+ else:
67
+ preflight(error, process_group=operator.process_group, world_size=world)
68
+
69
+
47
70
  def owns_values(operator, kind):
48
71
  """Select one copy of each physical ray or voxel for scalar reductions."""
49
72
  partition = getattr(operator, "partition", "views")
@@ -70,42 +93,58 @@ def scalar_sum(operator, value, kind, *, return_tensor=False):
70
93
  return float(value)
71
94
 
72
95
 
73
- def squared_norm(operator, value, kind, elements=1048576, *, return_tensor=False):
96
+ def _accumulate_scaled_block(peak, total, block):
97
+ if not block.numel():
98
+ return peak, total
99
+ block_peak = block.detach().abs().amax()
100
+ safe = torch.where(block_peak > 0, block_peak, torch.ones_like(block_peak))
101
+ combined = torch.maximum(peak, block_peak)
102
+ guard = torch.where(combined > 0, combined, torch.ones_like(combined))
103
+ updated = (total * (peak / guard).square()
104
+ + (block.detach() / safe).square().sum() * (block_peak / guard).square())
105
+ return combined, updated
106
+
107
+
108
+ def _scaled_squared_norm(store, elements, device):
109
+ # FP32 devices (MPS): squares of large measurements overflow and tiny
110
+ # geometries underflow, so every block is rescaled by its peak and the
111
+ # running sum follows the largest peak seen. All block math stays on the
112
+ # device; the two closing scalar reads fit the per-iteration reduction
113
+ # budget, and their product leaves FP32 before it can overflow.
114
+ peak = torch.zeros((), device=device, dtype=torch.float32)
115
+ total = torch.zeros((), device=device, dtype=torch.float32)
116
+ for selected in _fragments(tuple(store.shape), elements):
117
+ peak, total = _accumulate_scaled_block(peak, total, store.read(selected))
118
+ return peak.item() ** 2 * total.item()
119
+
120
+
121
+ def _local_squared_norm(operator, value, kind, elements=1048576):
74
122
  store = TensorStore(value) if isinstance(value, torch.Tensor) else value
75
123
  # Scale every block by its own peak before squaring and track the
76
124
  # running maximum on the device: unscaled FP32 squares overflow for
77
125
  # large measurements and underflow for tiny geometries.
78
126
  device = getattr(store, "device", torch.device("cpu"))
79
127
  if _work_dtype(device) == torch.float64:
80
- total = torch.zeros((), dtype=torch.float64, device=device)
128
+ local = torch.zeros((), dtype=torch.float64, device=device)
81
129
  if owns_values(operator, kind):
82
130
  for selected in _fragments(tuple(store.shape), elements):
83
131
  # Clone even an FP64 view: norms must never alter caller measurements.
84
132
  block = store.read(selected).to(dtype=torch.float64).clone()
85
133
  # Preserve the block reductions and their sequential FP64 order.
86
- total.add_(block.square_().sum().to(device=total.device))
87
- return scalar_sum(operator, total, kind, return_tensor=return_tensor)
88
- # FP32 devices (MPS): squares of large measurements overflow and tiny
89
- # geometries underflow, so every block is rescaled by its peak and the
90
- # running sum follows the largest peak seen. All block math stays on the
91
- # device; the two closing scalar reads fit the per-iteration reduction
92
- # budget, and their product leaves FP32 before it can overflow.
93
- peak = torch.zeros((), device=device, dtype=torch.float32)
94
- total = torch.zeros((), device=device, dtype=torch.float32)
95
- if owns_values(operator, kind):
96
- for selected in _fragments(tuple(store.shape), elements):
97
- block = store.read(selected)
98
- if not block.numel():
99
- continue
100
- block_peak = block.detach().abs().amax()
101
- safe = torch.where(block_peak > 0, block_peak, torch.ones_like(block_peak))
102
- combined = torch.maximum(peak, block_peak)
103
- guard = torch.where(combined > 0, combined, torch.ones_like(combined))
104
- total = (total * (peak / guard).square()
105
- + (block.detach() / safe).square().sum() * (block_peak / guard).square())
106
- peak = combined
107
- return scalar_sum(operator, peak.item() ** 2 * total.item(), kind,
108
- return_tensor=return_tensor)
134
+ local.add_(block.square_().sum().to(device=local.device))
135
+ return local
136
+ return _scaled_squared_norm(store, elements, device) if owns_values(operator, kind) else 0.0
137
+
138
+
139
+ def squared_norm(operator, value, kind, elements=1048576, *, return_tensor=False, before=None):
140
+ if isinstance(value, torch.Tensor) and before is None:
141
+ local = _local_squared_norm(operator, value, kind, elements)
142
+ else:
143
+ with solver_io_phase(operator):
144
+ if before is not None:
145
+ before()
146
+ local = _local_squared_norm(operator, value, kind, elements)
147
+ return scalar_sum(operator, local, kind, return_tensor=return_tensor)
109
148
 
110
149
 
111
150
  def copy_blocks(source, target, elements):
@@ -116,7 +155,8 @@ def copy_blocks(source, target, elements):
116
155
  def fill_blocks(target, elements):
117
156
  for selected in _fragments(tuple(target.shape), elements):
118
157
  shape = tuple(part.stop - part.start for part in selected)
119
- target.write(selected, torch.zeros(shape, dtype=target.dtype))
158
+ # An explicit device keeps a caller's torch.set_default_device out of solver state.
159
+ target.write(selected, torch.zeros(shape, dtype=target.dtype, device=getattr(target, "device", "cpu")))
120
160
 
121
161
 
122
162
  def update_blocks(target, source, factor, elements, scale=1.):
@@ -138,6 +178,82 @@ def fingerprint(value, elements):
138
178
  return digest.hexdigest()
139
179
 
140
180
 
181
+ # Prime modulus: 16-bit word products and reduced block sums fit int64.
182
+ _MODULUS = 2 ** 31 - 1
183
+
184
+
185
+ def _logical_positions(shape, selected, device):
186
+ position = torch.zeros(tuple(part.stop - part.start for part in selected),
187
+ dtype=torch.int64, device=device)
188
+ for axis, part in enumerate(selected):
189
+ index = torch.arange(part.start, part.stop, dtype=torch.int64, device=device)
190
+ index.mul_(math.prod(shape[axis + 1:]))
191
+ position.add_(index.view([-1 if other == axis else 1 for other in range(len(shape))]))
192
+ del index
193
+ return position.reshape(-1)
194
+
195
+
196
+ def _block_syndromes(block, position, size):
197
+ integer = {1: torch.int8, 2: torch.int16, 4: torch.int32, 8: torch.int64}[block.element_size()]
198
+ flat = torch.empty(block.numel(), dtype=block.dtype, device=block.device)
199
+ flat.copy_(block.reshape(-1))
200
+ bits = flat.view(integer).to(dtype=torch.int64)
201
+ del flat
202
+ for shift in range(0, block.element_size() * 8, 16):
203
+ word = (bits >> shift).bitwise_and_(65535)
204
+ yield word.sum().remainder_(_MODULUS)
205
+ divisor = 1
206
+ while divisor <= size:
207
+ digit = position.div(divisor, rounding_mode="floor").remainder_(_MODULUS)
208
+ yield digit.mul_(word).remainder_(_MODULUS).sum().remainder_(_MODULUS)
209
+ del digit
210
+ divisor *= _MODULUS
211
+ del word
212
+
213
+
214
+ def _checksum_block_elements(shape, dtype, elements):
215
+ size, digits = math.prod(shape), 1
216
+ while size >= _MODULUS:
217
+ size //= _MODULUS
218
+ digits += 1
219
+ lanes = max(1, torch.empty((), dtype=dtype).element_size() // 2)
220
+ # Count all buffers conservatively as int64 slots: five block buffers plus
221
+ # before/old/new scalar syndromes and reduction scratch. Tiny budgets need
222
+ # an unavoidable constant workspace even with one-element blocks.
223
+ scalars = 3 * lanes * (1 + digits) + 4
224
+ return max(1, (elements - scalars) // 5)
225
+
226
+
227
+ def _checksum(value, elements):
228
+ """Separate distance-three codes for each 16-bit lane of logical elements.
229
+
230
+ Each lane has at most two changed words when at most two elements change.
231
+ Its sum and position-weighted sum cannot both cancel modulo the prime.
232
+ Position digits distinguish even iterates larger than the modulus. Only
233
+ scalar syndromes survive a block; no iterate snapshot or host copy is kept.
234
+ """
235
+ store = TensorStore(value.detach()) if isinstance(value, torch.Tensor) else value
236
+ shape, total = tuple(store.shape), ()
237
+ for selected in _fragments(shape, _checksum_block_elements(shape, store.dtype, elements)):
238
+ block = store.read(selected).detach()
239
+ position = _logical_positions(shape, selected, block.device)
240
+ sums = _block_syndromes(block, position, math.prod(shape))
241
+ total = tuple((old + new).remainder_(_MODULUS) for old, new in zip(total, sums)) if total else tuple(sums)
242
+ del block, position, sums
243
+ return total
244
+
245
+
246
+ def _checksum_changed(before, after):
247
+ changed = False
248
+ for old, new in zip(before, after):
249
+ changed = (old != new) | changed
250
+ return bool(changed)
251
+
252
+
253
+ def _layout(value):
254
+ return getattr(value, "device", None), value.dtype, tuple(value.shape)
255
+
256
+
141
257
  def _effective_surface(operator, frames, elements):
142
258
  """Hash the actual physical pixel rays, without materializing a volume."""
143
259
  surface = getattr(operator, "detector_surface", None)
@@ -282,43 +398,242 @@ def load_checkpoint(operator, directory, expected, iterations, elements, names):
282
398
  return saved, states
283
399
 
284
400
 
285
- def save_checkpoint(operator, directory, states, metadata, iteration, history, measurement_norm, elements, **scalars):
286
- error, manifest, rank = None, {}, None
401
+ class _CheckpointPhase(str, Enum):
402
+ INIT = "init"
403
+ STAGING = "staging"
404
+ STAGE_AGREE = "stage_agree"
405
+ PUBLISHING = "publishing"
406
+ PUBLISH_AGREE = "publish_agree"
407
+ COMMITTED = "committed"
408
+ CLEANUP = "cleanup"
409
+ ABORTED = "aborted"
410
+
411
+ def __str__(self):
412
+ return self.value
413
+
414
+
415
+ _CHECKPOINT_TRANSITIONS = {
416
+ _CheckpointPhase.INIT: (_CheckpointPhase.STAGING,),
417
+ _CheckpointPhase.STAGING: (_CheckpointPhase.STAGE_AGREE,),
418
+ _CheckpointPhase.STAGE_AGREE: (_CheckpointPhase.PUBLISHING, _CheckpointPhase.CLEANUP),
419
+ _CheckpointPhase.PUBLISHING: (_CheckpointPhase.PUBLISH_AGREE,),
420
+ _CheckpointPhase.PUBLISH_AGREE: (_CheckpointPhase.COMMITTED, _CheckpointPhase.CLEANUP),
421
+ _CheckpointPhase.CLEANUP: (_CheckpointPhase.ABORTED,),
422
+ _CheckpointPhase.COMMITTED: (),
423
+ _CheckpointPhase.ABORTED: (),
424
+ }
425
+
426
+
427
+ def _close_npy_store(store):
428
+ array = getattr(store, "_array", None)
429
+ if array is None:
430
+ return
431
+ mmap = getattr(array, "_mmap", None)
432
+ if mmap is not None:
433
+ mmap.close()
434
+ store._array = None
435
+
436
+
437
+ def _mkdir_tracked(step, created=None):
438
+ """Create missing directories up to ``step``, recording only newly created paths."""
439
+ if created is None:
440
+ created = []
441
+ missing = []
442
+ current = step
443
+ depth = 0
444
+ while current != current.parent and not current.exists():
445
+ missing.append((depth, current))
446
+ current = current.parent
447
+ depth += 1
448
+ for level, path in reversed(missing):
449
+ try:
450
+ path.mkdir()
451
+ except FileExistsError:
452
+ if not path.is_dir():
453
+ raise
454
+ else:
455
+ created.append((level, path))
456
+ return created
457
+
458
+
459
+ def _cleanup_parent_dirs(created_dirs, world, group, *, local_cleanup_failed=False):
460
+ """Remove attempt-created empty parent directories bottom-up using rmdir only."""
461
+ levels = max((depth + 1 for depth, _ in created_dirs), default=0)
462
+ any_cleanup_failed = bool(local_cleanup_failed)
463
+ if world > 1:
464
+ levels, failed = control_status(
465
+ (levels, int(any_cleanup_failed)), process_group=group, world_size=world,
466
+ )
467
+ any_cleanup_failed = bool(failed)
468
+ by_depth = dict(created_dirs)
469
+ for depth in range(levels):
470
+ if depth in by_depth:
471
+ with suppress(OSError):
472
+ by_depth[depth].rmdir()
473
+ if world > 1:
474
+ control_status((0,), process_group=group, world_size=world)
475
+ return any_cleanup_failed
476
+
477
+
478
+ def _format_cleanup_error(caught):
479
+ detail = str(caught)
480
+ if (isinstance(caught, OSError) and caught.errno is None
481
+ and caught.strerror is None and caught.args):
482
+ message = str(caught.args[0])
483
+ if message and message not in detail:
484
+ detail = f"{message} ({detail})"
485
+ return f"{type(caught).__name__}: {detail}"
486
+
487
+
488
+ def _cleanup_rank_dir(rank_dir, rank):
287
489
  try:
288
- step = Path(directory).resolve() / f"step-{iteration:06d}"
289
- step.mkdir(parents=True, exist_ok=True)
290
- rank = step / f"rank-{getattr(operator, 'rank', 0):05d}"
291
- if rank.exists():
292
- # Replacing a published step in place could destroy it on a
293
- # failed write, and ranks cannot roll back together.
294
- raise ValueError(f"checkpoint {rank} already exists; use a new checkpoint_directory "
295
- "or pass resume= to continue from it")
296
- rank.mkdir()
297
- for name, source in states.items():
298
- source = TensorStore(source.detach()) if isinstance(source, torch.Tensor) else source
299
- target = NpyStore.create(rank / f"{name}.npy", source.shape, dtype=source.dtype)
300
- copy_blocks(source, target, elements)
301
- target.flush()
302
- manifest[name] = dict(shape=list(source.shape), dtype=str(source.dtype), fingerprint=fingerprint(target, elements))
303
- except (OSError, ValueError, TypeError) as caught:
304
- error = caught
305
- # All owned states on every rank are written and flushed before any rank
306
- # atomically publishes the metadata marking a completed iteration.
307
- agreement(operator, error, (iteration, history))
308
- error = None
490
+ shutil.rmtree(rank_dir)
491
+ except FileNotFoundError:
492
+ pass
493
+ except Exception as caught:
494
+ return rank, str(rank_dir), _format_cleanup_error(caught)
309
495
  try:
310
- document = dict(metadata, iteration=iteration, residual_history=history,
311
- measurement_norm=measurement_norm, states=manifest, **scalars)
312
- temporary = rank / "metadata.tmp"
313
- with temporary.open("x", encoding="utf-8") as file:
314
- json.dump(document, file)
315
- file.flush()
316
- temporary.replace(rank / "metadata.json")
496
+ os.lstat(rank_dir)
497
+ except FileNotFoundError:
498
+ return None
317
499
  except Exception as caught:
318
- error = caught
319
- # A failed metadata write/rename must stop every rank before another
320
- # projection or callback can enter a numerical collective.
321
- agreement(operator, error, iteration)
500
+ return rank, str(rank_dir), _format_cleanup_error(caught)
501
+ return rank, str(rank_dir), "rank directory still exists after cleanup"
502
+
503
+
504
+ class _CheckpointAttempt:
505
+ """Explicit lifecycle state machine for one collective checkpoint save."""
506
+
507
+ def __init__(self, operator=None, directory=None, iteration=None):
508
+ self.phase = _CheckpointPhase.INIT
509
+ self.operator = operator
510
+ self.directory = directory
511
+ self.iteration = iteration
512
+ self.created_dirs = []
513
+ self.rank_dir = None
514
+ self.created_rank = False
515
+ self.manifest = {}
516
+
517
+ def transition(self, target):
518
+ try:
519
+ target_phase = _CheckpointPhase(target)
520
+ except ValueError as error:
521
+ raise RuntimeError(
522
+ f"illegal checkpoint phase {target!r} from {self.phase.value!r}"
523
+ ) from error
524
+ if target_phase not in _CHECKPOINT_TRANSITIONS[self.phase]:
525
+ raise RuntimeError(
526
+ f"illegal checkpoint transition from {self.phase.value!r} to {target_phase.value!r}"
527
+ )
528
+ self.phase = target_phase
529
+ return self.phase
530
+
531
+ def stage(self, states, elements):
532
+ self.transition(_CheckpointPhase.STAGING)
533
+ try:
534
+ step = Path(self.directory).resolve() / f"step-{self.iteration:06d}"
535
+ _mkdir_tracked(step, self.created_dirs)
536
+ rank = step / f"rank-{getattr(self.operator, 'rank', 0):05d}"
537
+ self.rank_dir = rank
538
+ if rank.exists() or rank.is_symlink():
539
+ # Replacing a published step in place could destroy it on a
540
+ # failed write, and ranks cannot roll back together.
541
+ raise ValueError(f"checkpoint {rank} already exists; use a new checkpoint_directory "
542
+ "or pass resume= to continue from it")
543
+ rank.mkdir()
544
+ self.created_rank = True
545
+ for name, source in states.items():
546
+ source = TensorStore(source.detach()) if isinstance(source, torch.Tensor) else source
547
+ target = NpyStore.create(rank / f"{name}.npy", source.shape, dtype=source.dtype)
548
+ try:
549
+ copy_blocks(source, target, elements)
550
+ target.flush()
551
+ digest = fingerprint(target, elements)
552
+ finally:
553
+ _close_npy_store(target)
554
+ self.manifest[name] = dict(shape=list(source.shape), dtype=str(source.dtype), fingerprint=digest)
555
+ except Exception as caught:
556
+ return caught
557
+ return None
558
+
559
+ def _abort(self, agreed_error):
560
+ cleanup_report = self.cleanup()
561
+ if cleanup_report is not None:
562
+ raise RuntimeError(
563
+ f"{agreed_error}; checkpoint cleanup failed, leftover checkpoint path(s): {cleanup_report}"
564
+ ) from agreed_error
565
+
566
+ def agree_stage(self, error, history):
567
+ # All owned states on every rank are written and flushed before any rank
568
+ # atomically publishes the metadata marking a completed iteration.
569
+ self.transition(_CheckpointPhase.STAGE_AGREE)
570
+ try:
571
+ agreement(self.operator, error, (self.iteration, history))
572
+ except Exception as agreed_error:
573
+ self._abort(agreed_error)
574
+ raise
575
+
576
+ def publish(self, metadata, history, measurement_norm, scalars):
577
+ self.transition(_CheckpointPhase.PUBLISHING)
578
+ try:
579
+ document = dict(metadata, iteration=self.iteration, residual_history=history,
580
+ measurement_norm=measurement_norm, states=self.manifest, **scalars)
581
+ temporary = self.rank_dir / "metadata.tmp"
582
+ with temporary.open("x", encoding="utf-8") as file:
583
+ json.dump(document, file)
584
+ file.flush()
585
+ temporary.replace(self.rank_dir / "metadata.json")
586
+ except Exception as caught:
587
+ return caught
588
+ return None
589
+
590
+ def agree_publish(self, error):
591
+ # A failed metadata write/rename must stop every rank before another
592
+ # projection or callback can enter a numerical collective.
593
+ self.transition(_CheckpointPhase.PUBLISH_AGREE)
594
+ try:
595
+ agreement(self.operator, error, self.iteration)
596
+ except Exception as agreed_error:
597
+ self._abort(agreed_error)
598
+ raise
599
+ self.commit()
600
+
601
+ def commit(self):
602
+ self.transition(_CheckpointPhase.COMMITTED)
603
+
604
+ def cleanup(self):
605
+ self.transition(_CheckpointPhase.CLEANUP)
606
+ rank = getattr(self.operator, "rank", 0)
607
+ world = getattr(self.operator, "world_size", 1)
608
+ group = getattr(self.operator, "process_group", None)
609
+ local_failure = (
610
+ _cleanup_rank_dir(self.rank_dir, rank)
611
+ if self.created_rank and self.rank_dir is not None else None
612
+ )
613
+ any_failed = _cleanup_parent_dirs(
614
+ self.created_dirs, world, group, local_cleanup_failed=local_failure is not None,
615
+ )
616
+ self.transition(_CheckpointPhase.ABORTED)
617
+ if not any_failed:
618
+ return None
619
+ if world == 1:
620
+ failures = [local_failure]
621
+ else:
622
+ failures = [None] * world
623
+ dist.all_gather_object(failures, local_failure, group=group)
624
+ return "; ".join(
625
+ f"rank {failed_rank} ({path}): {detail}"
626
+ for entry in failures if entry is not None
627
+ for failed_rank, path, detail in (entry,)
628
+ )
629
+
630
+
631
+ def save_checkpoint(operator, directory, states, metadata, iteration, history, measurement_norm, elements, **scalars):
632
+ attempt = _CheckpointAttempt(operator, directory, iteration)
633
+ stage_error = attempt.stage(states, elements)
634
+ attempt.agree_stage(stage_error, history)
635
+ publish_error = attempt.publish(metadata, history, measurement_norm, scalars)
636
+ attempt.agree_publish(publish_error)
322
637
 
323
638
 
324
639
  def callbacks_enabled(operator, callback):
@@ -333,10 +648,12 @@ def callback_stop(operator, callback, iteration, residual, volume, *, readonly=F
333
648
  error, stop = None, False
334
649
  try:
335
650
  if callback is not None:
336
- before = (fingerprint(volume, block_elements), getattr(volume, "device", None)) if readonly else None
651
+ if readonly:
652
+ layout, before = _layout(volume), _checksum(volume, block_elements)
337
653
  stop = callback(iteration, residual, volume) is False
338
- if readonly and ((isinstance(volume, torch.Tensor) and not torch.is_floating_point(volume))
339
- or (fingerprint(volume, block_elements), getattr(volume, "device", None)) != before):
654
+ # Layout is host metadata; the storage comparison reads back one flag.
655
+ if readonly and (_layout(volume) != layout or (
656
+ _checksum_changed(before, _checksum(volume, block_elements)))):
340
657
  raise ValueError("CGLS callback iterate is read-only")
341
658
  except Exception as caught:
342
659
  error = caught
diffct/analytical.py CHANGED
@@ -107,7 +107,13 @@ def angular_integration_weights(angles, redundant_full_scan=True):
107
107
  handles their redundancy at the sinogram-filtering stage. Leave
108
108
  ``redundant_full_scan=True`` for automatic fan/cone scan classification.
109
109
  Setting it to ``False`` explicitly disables the full-turn ``1/2`` factor.
110
- Parker and angular quadrature share the same periodic-scan decision.
110
+
111
+ Angles are in radians and weights are returned in input order. For a
112
+ short scan wrapped modulo ``2*pi``, the gap outside the acquisition must
113
+ be clearly more than twice every other gap. If the sorted range looks
114
+ like a full turn, that isolated gap marks the scan boundary instead.
115
+ A full turn with a similarly large missing sector is ambiguous from
116
+ angles alone. Pass continuous (unwrapped) angles to ``parker_weights``.
111
117
  FP16 and BF16 angles are promoted to FP32; FP64 angles retain their precision.
112
118
  """
113
119
  if angles.dtype not in (torch.float32, torch.float64):
@@ -133,6 +139,19 @@ def angular_integration_weights(angles, redundant_full_scan=True):
133
139
  span = angles_sorted[-1] - angles_sorted[0]
134
140
  period = _angular_scan_period(span, median_step)
135
141
 
142
+ if period == 2.0 * math.pi and n > 2:
143
+ turn = angles.new_tensor(period)
144
+ closure = turn - span
145
+ gaps, indices = diffs.topk(2)
146
+ other_gap = torch.maximum(gaps[1], closure)
147
+ # Keep endpoint-included turns and turns with a single missing view periodic.
148
+ if (closure > 0) & (gaps[0] > 2.0 * other_gap + 1e-4):
149
+ cut = int(indices[0].item())
150
+ diffs = torch.cat((diffs[cut + 1:], closure[None], diffs[:cut]))
151
+ sort_idx = sort_idx.roll(-cut - 1)
152
+ span = turn - gaps[0]
153
+ period = _angular_scan_period(span, torch.median(diffs))
154
+
136
155
  w = torch.zeros(n, device=device, dtype=angles.dtype)
137
156
  if period is not None:
138
157
  closure = torch.clamp(angles.new_tensor(period) - span, min=0.0)
@@ -231,7 +250,7 @@ def parker_weights(angles, num_detectors, detector_spacing, sdd, detector_offset
231
250
  span = angles_sorted[-1] - angles_sorted[0]
232
251
  median_step = torch.median(angles_sorted[1:] - angles_sorted[:-1])
233
252
  # Full-scan detection depends on acquired angles, not detector fan width.
234
- # Use exactly the quadrature's classification, including its tolerance.
253
+ # Use the same periodic-scan tolerance as angular quadrature.
235
254
  if _angular_scan_period(span, median_step) == 2.0 * math.pi:
236
255
  # Already a full scan — no Parker needed.
237
256
  return torch.ones((n_ang, num_detectors), device=device, dtype=angles.dtype)
@@ -125,7 +125,7 @@ class AnalyticalExecution:
125
125
  self.window if self.filter_response is None else None, self.pad_factor,
126
126
  bool(self.short_scan), schema, acquisition,
127
127
  None if self.isocenter is None else tuple(self.isocenter.tolist()))
128
- except (ValueError, TypeError, RuntimeError, OSError) as caught:
128
+ except Exception as caught:
129
129
  error = caught
130
130
  self.partition.preflight(error, metadata)
131
131
  self._admit_native(kwargs.get("view_chunk_size"), kwargs.get("volume_chunk_shape"))
@@ -438,7 +438,7 @@ class AnalyticalExecution:
438
438
  if (isinstance(option, torch.Tensor) and isinstance(output_tensor, torch.Tensor)
439
439
  and _tensor_overlap(option, output_tensor)):
440
440
  raise ValueError("analytical weights and output stores overlap")
441
- except (ValueError, TypeError, RuntimeError, OSError) as caught:
441
+ except Exception as caught:
442
442
  error = caught
443
443
  self.partition.preflight(error)
444
444
  self.source = source