csttool 0.5.0__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.
Files changed (93) hide show
  1. csttool/__init__.py +2 -0
  2. csttool/batch/__init__.py +23 -0
  3. csttool/batch/batch.py +389 -0
  4. csttool/batch/modules/__init__.py +5 -0
  5. csttool/batch/modules/discover.py +195 -0
  6. csttool/batch/modules/locking.py +76 -0
  7. csttool/batch/modules/logging_setup.py +91 -0
  8. csttool/batch/modules/manifest.py +100 -0
  9. csttool/batch/modules/report.py +176 -0
  10. csttool/batch/modules/validation.py +128 -0
  11. csttool/bids/__init__.py +19 -0
  12. csttool/bids/output.py +372 -0
  13. csttool/cli/__init__.py +834 -0
  14. csttool/cli/commands/__init__.py +0 -0
  15. csttool/cli/commands/batch.py +212 -0
  16. csttool/cli/commands/check.py +9 -0
  17. csttool/cli/commands/check_dataset.py +214 -0
  18. csttool/cli/commands/doctor.py +250 -0
  19. csttool/cli/commands/extract.py +563 -0
  20. csttool/cli/commands/fetch_data.py +253 -0
  21. csttool/cli/commands/import_cmd.py +325 -0
  22. csttool/cli/commands/metrics.py +310 -0
  23. csttool/cli/commands/preprocess.py +43 -0
  24. csttool/cli/commands/run.py +810 -0
  25. csttool/cli/commands/track.py +209 -0
  26. csttool/cli/commands/validate.py +220 -0
  27. csttool/cli/utils.py +282 -0
  28. csttool/data/LICENSES/FSL_LICENSE.txt +47 -0
  29. csttool/data/LICENSES/MNI152_LICENSE.txt +15 -0
  30. csttool/data/__init__.py +27 -0
  31. csttool/data/loader.py +303 -0
  32. csttool/data/manifest.py +146 -0
  33. csttool/data/mni152/MNI152_T1_1mm.nii.gz +0 -0
  34. csttool/extract/__init__.py +11 -0
  35. csttool/extract/modules/__init__.py +39 -0
  36. csttool/extract/modules/bidirectional_filtering.py +356 -0
  37. csttool/extract/modules/coordinate_validation.py +250 -0
  38. csttool/extract/modules/create_roi_masks.py +448 -0
  39. csttool/extract/modules/diagnostic.py +37 -0
  40. csttool/extract/modules/endpoint_filtering.py +442 -0
  41. csttool/extract/modules/passthrough_filtering.py +522 -0
  42. csttool/extract/modules/registration.py +976 -0
  43. csttool/extract/modules/roi_seeded_tracking.py +483 -0
  44. csttool/extract/modules/save_extract_outputs.py +0 -0
  45. csttool/extract/modules/visualizations.py +1089 -0
  46. csttool/extract/modules/warp_atlas_to_subject.py +642 -0
  47. csttool/ingest/__init__.py +339 -0
  48. csttool/ingest/modules/__init__.py +62 -0
  49. csttool/ingest/modules/analyze_series.py +500 -0
  50. csttool/ingest/modules/assess_quality.py +413 -0
  51. csttool/ingest/modules/convert_series.py +380 -0
  52. csttool/ingest/modules/save_ingest_outputs.py +348 -0
  53. csttool/ingest/modules/scan_study.py +291 -0
  54. csttool/metrics/__init__.py +77 -0
  55. csttool/metrics/modules/__init__.py +32 -0
  56. csttool/metrics/modules/bilateral_analysis.py +376 -0
  57. csttool/metrics/modules/reports.py +687 -0
  58. csttool/metrics/modules/templates/report.css +382 -0
  59. csttool/metrics/modules/templates/report.html.j2 +216 -0
  60. csttool/metrics/modules/unilateral_analysis.py +458 -0
  61. csttool/metrics/modules/visualizations.py +812 -0
  62. csttool/preprocess/__init__.py +42 -0
  63. csttool/preprocess/modules/__init__.py +23 -0
  64. csttool/preprocess/modules/background_segmentation.py +63 -0
  65. csttool/preprocess/modules/denoise.py +78 -0
  66. csttool/preprocess/modules/gibbs_unringing.py +47 -0
  67. csttool/preprocess/modules/load_dataset.py +125 -0
  68. csttool/preprocess/modules/perform_motion_correction.py +55 -0
  69. csttool/preprocess/modules/reslice_voxels.py +46 -0
  70. csttool/preprocess/modules/save_preprocessed.py +136 -0
  71. csttool/preprocess/modules/visualizations.py +725 -0
  72. csttool/preprocess/preprocess.py +242 -0
  73. csttool/reproducibility/__init__.py +14 -0
  74. csttool/reproducibility/context.py +56 -0
  75. csttool/reproducibility/provenance.py +120 -0
  76. csttool/reproducibility/tolerance.py +185 -0
  77. csttool/tracking/__init__.py +19 -0
  78. csttool/tracking/modules/__init__.py +45 -0
  79. csttool/tracking/modules/estimate_directions.py +129 -0
  80. csttool/tracking/modules/fit_tensors.py +103 -0
  81. csttool/tracking/modules/load_and_mask.py +57 -0
  82. csttool/tracking/modules/run_tractography.py +79 -0
  83. csttool/tracking/modules/save_tracking_outputs.py +181 -0
  84. csttool/tracking/modules/seed_and_stop.py +70 -0
  85. csttool/tracking/modules/visualizations.py +780 -0
  86. csttool/validation/__init__.py +30 -0
  87. csttool/validation/bundle_comparison.py +414 -0
  88. csttool/validation/visualization.py +114 -0
  89. csttool-0.5.0.dist-info/METADATA +167 -0
  90. csttool-0.5.0.dist-info/RECORD +93 -0
  91. csttool-0.5.0.dist-info/WHEEL +4 -0
  92. csttool-0.5.0.dist-info/entry_points.txt +2 -0
  93. csttool-0.5.0.dist-info/licenses/LICENSE +21 -0
csttool/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __all__ = ["__version__"]
2
+ __version__ = "0.5.0"
@@ -0,0 +1,23 @@
1
+ """
2
+ Batch processing package for csttool.
3
+
4
+ Provides multi-subject batch processing capabilities with BIDS-compliant
5
+ input discovery and output organization.
6
+ """
7
+
8
+ from .batch import run_batch, BatchConfig, SubjectSpec, SubjectResult
9
+ from .modules.discover import discover_subjects, detect_input_type
10
+ from .modules.manifest import load_manifest, save_manifest_template
11
+ from .modules.report import generate_batch_reports
12
+
13
+ __all__ = [
14
+ "run_batch",
15
+ "BatchConfig",
16
+ "SubjectSpec",
17
+ "SubjectResult",
18
+ "discover_subjects",
19
+ "detect_input_type",
20
+ "load_manifest",
21
+ "save_manifest_template",
22
+ "generate_batch_reports",
23
+ ]
csttool/batch/batch.py ADDED
@@ -0,0 +1,389 @@
1
+ import os
2
+ import sys
3
+ import time
4
+ import signal
5
+ import json
6
+ import shutil
7
+ import hashlib
8
+ import logging
9
+ import argparse
10
+ import multiprocessing
11
+ from pathlib import Path
12
+ from dataclasses import dataclass, field, asdict
13
+ from typing import List, Optional, Literal, Dict, Any
14
+ from datetime import datetime
15
+
16
+ from .modules.locking import acquire_subject_lock, release_lock
17
+ from .modules.logging_setup import setup_subject_logger
18
+
19
+ try:
20
+ from csttool import __version__
21
+ except ImportError:
22
+ __version__ = "unknown"
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ # Error Categories
27
+ class ErrorCategory:
28
+ INPUT_MISSING = "INPUT_MISSING"
29
+ VALIDATION = "VALIDATION"
30
+ PIPELINE_FAILED = "PIPELINE_FAILED"
31
+ TIMEOUT = "TIMEOUT"
32
+ SYSTEM = "SYSTEM"
33
+
34
+ @dataclass
35
+ class SubjectSpec:
36
+ """Specification for a single subject/session to iterate over."""
37
+ subject_id: str
38
+ session_id: Optional[str]
39
+ input_path: Path
40
+ input_type: Literal["nifti", "dicom"]
41
+ bval_path: Optional[Path] = None
42
+ bvec_path: Optional[Path] = None
43
+ json_path: Optional[Path] = None
44
+ series_uid: Optional[str] = None
45
+ options: Dict[str, Any] = field(default_factory=dict)
46
+
47
+ @dataclass
48
+ class BatchConfig:
49
+ """Configuration for the entire batch run."""
50
+ out: Path
51
+ force: bool = False
52
+ timeout_minutes: int = 120
53
+ keep_work: bool = False
54
+ # Pipeline overrides
55
+ denoise_method: str = "patch2self"
56
+ preprocessing: bool = True
57
+ generate_pdf: bool = False
58
+ # ... any other arguments that cmd_run accepts
59
+
60
+ @dataclass
61
+ class SubjectResult:
62
+ """Result of a single subject/session processing attempt."""
63
+ subject_id: str
64
+ session_id: Optional[str]
65
+ status: Literal["success", "failed", "skipped"]
66
+ error_category: Optional[str] = None
67
+ duration_seconds: float = 0.0
68
+ error: Optional[str] = None
69
+ log_path: Optional[Path] = None
70
+ outputs: Optional[Dict[str, str]] = None
71
+
72
+ def compute_config_hash(config: BatchConfig) -> str:
73
+ """
74
+ Computes a stable hash of the batch configuration.
75
+ Used to detect if settings have changed since a previous run.
76
+ """
77
+ # Exclude non-config fields like 'force' or 'keep_work' if they don't affect output data
78
+ # Actually, almost everything in BatchConfig affects output except force/keep_work/timeout.
79
+ data = asdict(config)
80
+ excluded = {'force', 'keep_work', 'timeout_minutes'}
81
+ filtered = {k: str(v) for k, v in data.items() if k not in excluded}
82
+
83
+ config_json = json.dumps(filtered, sort_keys=True)
84
+ return hashlib.sha256(config_json.encode('utf-8')).hexdigest()
85
+
86
+ def is_subject_completed(subject: SubjectSpec, output_dir: Path, expected_hash: str) -> bool:
87
+ """Checks if a subject has already been successfully completed with the same config."""
88
+ done_file = output_dir / "_done.json"
89
+ if not done_file.exists():
90
+ return False
91
+
92
+ try:
93
+ with open(done_file, 'r') as f:
94
+ data = json.load(f)
95
+ return data.get("config_hash") == expected_hash
96
+ except Exception:
97
+ return False
98
+
99
+ def promote_outputs(work_dir: Path, final_dir: Path, done_marker: Dict[str, Any]) -> None:
100
+ """
101
+ Atomically promote outputs from _work/ to final location.
102
+ The _done.json file is written LAST to ensure atomicity.
103
+ """
104
+ final_dir.mkdir(parents=True, exist_ok=True)
105
+
106
+ # 1. Rename output files/directories
107
+ # We move them from _work/ to final_dir
108
+ for item in work_dir.iterdir():
109
+ if item.name == "_done.json": # Reserved
110
+ continue
111
+
112
+ target = final_dir / item.name
113
+ # If target exists (e.g. from a previous partial success), remove it
114
+ if target.exists():
115
+ if target.is_dir():
116
+ shutil.rmtree(target)
117
+ else:
118
+ target.unlink()
119
+
120
+ os.rename(item, target)
121
+
122
+ # 2. Write _done.json atomically (write to .tmp then rename)
123
+ done_file = final_dir / "_done.json"
124
+ tmp_done = final_dir / "_done.json.tmp"
125
+
126
+ with open(tmp_done, 'w') as f:
127
+ json.dump(done_marker, f, indent=2)
128
+
129
+ os.rename(tmp_done, done_file)
130
+
131
+ def _get_subject_output_dir(base_out: Path, sub_id: str, ses_id: Optional[str]) -> Path:
132
+ """Returns the final output directory for a subject/session."""
133
+ path = base_out / sub_id
134
+ if ses_id:
135
+ path = path / ses_id
136
+ return path
137
+
138
+ # Global for signal handling
139
+ _current_child: Optional[multiprocessing.Process] = None
140
+
141
+ def run_subject_with_timeout(
142
+ subject: SubjectSpec,
143
+ config: BatchConfig,
144
+ log_path: Path
145
+ ) -> SubjectResult:
146
+ """
147
+ Runs a single subject in an isolated child process with a timeout.
148
+ """
149
+ global _current_child
150
+
151
+ queue = multiprocessing.Queue()
152
+ _current_child = multiprocessing.Process(
153
+ target=_run_subject_worker,
154
+ args=(subject, config, log_path, queue)
155
+ )
156
+
157
+ start_time = time.time()
158
+ _current_child.start()
159
+
160
+ # Wait for completion or timeout
161
+ _current_child.join(timeout=config.timeout_minutes * 60)
162
+
163
+ if _current_child.is_alive():
164
+ # Timeout occurred
165
+ logger.warning(f"Timeout: Subject {subject.subject_id} exceeded {config.timeout_minutes}m")
166
+ _current_child.terminate()
167
+ _current_child.join(timeout=30) # Grace period
168
+ if _current_child.is_alive():
169
+ _current_child.kill()
170
+ _current_child.join()
171
+
172
+ _current_child = None
173
+ return SubjectResult(
174
+ subject_id=subject.subject_id,
175
+ session_id=subject.session_id,
176
+ status="failed",
177
+ error_category=ErrorCategory.TIMEOUT,
178
+ duration_seconds=time.time() - start_time,
179
+ error=f"Processing exceeded {config.timeout_minutes} minute limit",
180
+ log_path=log_path
181
+ )
182
+
183
+ # Check if process exited normally
184
+ exit_code = _current_child.exitcode
185
+ _current_child = None
186
+
187
+ if exit_code != 0:
188
+ return SubjectResult(
189
+ subject_id=subject.subject_id,
190
+ session_id=subject.session_id,
191
+ status="failed",
192
+ error_category=ErrorCategory.SYSTEM,
193
+ duration_seconds=time.time() - start_time,
194
+ error=f"Child process exited with code {exit_code}",
195
+ log_path=log_path
196
+ )
197
+
198
+ # Get result from queue
199
+ try:
200
+ # Wait a bit for the queue to populate
201
+ return queue.get(timeout=5)
202
+ except Exception as e:
203
+ return SubjectResult(
204
+ subject_id=subject.subject_id,
205
+ session_id=subject.session_id,
206
+ status="failed",
207
+ error_category=ErrorCategory.SYSTEM,
208
+ duration_seconds=time.time() - start_time,
209
+ error=f"Failed to retrieve result from worker: {e}",
210
+ log_path=log_path
211
+ )
212
+
213
+ def _run_subject_worker(
214
+ subject: SubjectSpec,
215
+ config: BatchConfig,
216
+ log_path: Path,
217
+ queue: multiprocessing.Queue
218
+ ) -> None:
219
+ """
220
+ Entry point for child process.
221
+ Sets up logging and runs the actual pipeline.
222
+ """
223
+ # 1. Setup isolated logger
224
+ subj_logger = setup_subject_logger(
225
+ subject.subject_id, subject.session_id, log_path, verbose=True
226
+ )
227
+
228
+ start_time = time.time()
229
+
230
+ try:
231
+ # 2. Prepare output directory
232
+ base_out = _get_subject_output_dir(config.out, subject.subject_id, subject.session_id)
233
+ work_dir = base_out / "_work"
234
+ work_dir.mkdir(parents=True, exist_ok=True)
235
+
236
+ # 3. Create arg namespace for cmd_run proxy
237
+ # We'll use a simplified version of cmd_run logic directly
238
+ # to avoid argparse dependency inside the worker.
239
+ from csttool.cli.commands.run import cmd_run
240
+
241
+ # Merge global options with per-subject options
242
+ merged_options = asdict(config)
243
+ merged_options.update(subject.options)
244
+
245
+ # Construct Namespace compatible with cmd_run
246
+ args = argparse.Namespace()
247
+ for k, v in merged_options.items():
248
+ setattr(args, k, v)
249
+
250
+ # Ensure correct input paths are set
251
+ setattr(args, 'subject_id', subject.subject_id)
252
+ setattr(args, 'session_id', subject.session_id)
253
+ setattr(args, 'out', work_dir)
254
+
255
+ if subject.input_type == "nifti":
256
+ setattr(args, 'nifti', subject.input_path)
257
+ setattr(args, 'dicom', None)
258
+ else:
259
+ setattr(args, 'dicom', subject.input_path)
260
+ setattr(args, 'nifti', None)
261
+ setattr(args, 'series', None)
262
+ setattr(args, 'series_uid', subject.series_uid)
263
+
264
+ # 4. Execute pipeline
265
+ # cmd_run prints to stdout, which console handler of subj_logger catches
266
+ # if verbose is set. Actually cmd_run uses print(), which doesn't go through logging.
267
+ # We might need to redirect stdout if we want it in the structured log.
268
+ # For v1, we assume SubjectLogger's StreamHandler handles plain prints if they are redirected.
269
+ # sys.stdout = StreamLogger(subj_logger, logging.INFO) # optional
270
+
271
+ cmd_run(args)
272
+
273
+ # 5. Success
274
+ duration = time.time() - start_time
275
+ queue.put(SubjectResult(
276
+ subject_id=subject.subject_id,
277
+ session_id=subject.session_id,
278
+ status="success",
279
+ duration_seconds=duration,
280
+ log_path=log_path
281
+ ))
282
+
283
+ except Exception as e:
284
+ subj_logger.error(f"Pipeline failed: {e}", exc_info=True)
285
+ queue.put(SubjectResult(
286
+ subject_id=subject.subject_id,
287
+ session_id=subject.session_id,
288
+ status="failed",
289
+ error_category=ErrorCategory.PIPELINE_FAILED,
290
+ error=str(e),
291
+ duration_seconds=time.time() - start_time,
292
+ log_path=log_path
293
+ ))
294
+
295
+ def run_batch(
296
+ subjects: List[SubjectSpec],
297
+ config: BatchConfig,
298
+ verbose: bool = False
299
+ ) -> List[SubjectResult]:
300
+ """
301
+ Main batch processing orchestrator.
302
+ Handles resume logic, per-subject locks, and output promotion.
303
+ """
304
+ config_hash = compute_config_hash(config)
305
+ results = []
306
+
307
+ # Setup signal handling for the main orchestrator
308
+ def _sig_handler(signum, frame):
309
+ logger.warning(f"Batch interrupted by signal {signum}. Shutting down...")
310
+ # Close the current child if it exists
311
+ if _current_child and _current_child.is_alive():
312
+ _current_child.terminate()
313
+ sys.exit(1)
314
+
315
+ signal.signal(signal.SIGINT, _sig_handler)
316
+ signal.signal(signal.SIGTERM, _sig_handler)
317
+
318
+ logger.info(f"Starting batch processing for {len(subjects)} subjects")
319
+ logger.info(f"Output directory: {config.out}")
320
+ if verbose:
321
+ logger.info(f"Config hash: {config_hash[:8]}")
322
+
323
+ for subj_spec in subjects:
324
+ final_dir = _get_subject_output_dir(config.out, subj_spec.subject_id, subj_spec.session_id)
325
+
326
+ # 1. Check if already completed
327
+ if not config.force and is_subject_completed(subj_spec, final_dir, config_hash):
328
+ if verbose:
329
+ logger.info(f"Skipping {subj_spec.subject_id}: Already completed")
330
+ results.append(SubjectResult(
331
+ subject_id=subj_spec.subject_id,
332
+ session_id=subj_spec.session_id,
333
+ status="skipped"
334
+ ))
335
+ continue
336
+
337
+ # 2. Acquire subject lock
338
+ try:
339
+ lock = acquire_subject_lock(final_dir)
340
+ except Exception as e:
341
+ logger.error(f"Could not acquire lock for {subj_spec.subject_id}: {e}")
342
+ results.append(SubjectResult(
343
+ subject_id=subj_spec.subject_id,
344
+ session_id=subj_spec.session_id,
345
+ status="failed",
346
+ error_category=ErrorCategory.SYSTEM,
347
+ error=f"Locking failed: {e}"
348
+ ))
349
+ continue
350
+
351
+ try:
352
+ # 3. Setup log path
353
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
354
+ log_name = f"{subj_spec.subject_id}"
355
+ if subj_spec.session_id:
356
+ log_name += f"_{subj_spec.session_id}"
357
+ log_path = final_dir / "logs" / f"{log_name}_{timestamp}.log"
358
+
359
+ # 4. Run subject in isolated process
360
+ res = run_subject_with_timeout(subj_spec, config, log_path)
361
+
362
+ # 5. Handle output promotion or failure move
363
+ work_dir = final_dir / "_work"
364
+ if res.status == "success":
365
+ logger.info(f"✓ {subj_spec.subject_id}: Success in {res.duration_seconds:.1f}s")
366
+ done_marker = {
367
+ "csttool_version": __version__,
368
+ "config_hash": config_hash,
369
+ "completed_at": datetime.now().isoformat(),
370
+ "duration_seconds": res.duration_seconds,
371
+ "outputs": {}
372
+ }
373
+ promote_outputs(work_dir, final_dir, done_marker)
374
+ if not config.keep_work:
375
+ if work_dir.exists():
376
+ shutil.rmtree(work_dir)
377
+ else:
378
+ logger.error(f"✗ {subj_spec.subject_id}: Failed ({res.error_category})")
379
+ failed_dir = final_dir / "_failed_attempts" / f"{timestamp}_{res.error_category}"
380
+ failed_dir.mkdir(parents=True, exist_ok=True)
381
+ if work_dir.exists():
382
+ os.rename(work_dir, failed_dir / "_work")
383
+
384
+ results.append(res)
385
+
386
+ finally:
387
+ release_lock(lock)
388
+
389
+ return results
@@ -0,0 +1,5 @@
1
+ """
2
+ Batch processing modules for csttool.
3
+
4
+ Individual submodules for batch processing functionality.
5
+ """
@@ -0,0 +1,195 @@
1
+ import re
2
+ from pathlib import Path
3
+ from typing import List, Dict, Optional, Literal, Tuple
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ def sanitize_subject_id(subject_id: str) -> str:
9
+ """
10
+ Sanitize subject ID to prevent path traversal attacks.
11
+ Only allows alphanumeric, hyphen, and underscore.
12
+ """
13
+ if not subject_id:
14
+ raise ValueError("Subject ID cannot be empty")
15
+
16
+ if not re.match(r'^[a-zA-Z0-9\-_]+$', subject_id):
17
+ raise ValueError(
18
+ f"Invalid subject ID: '{subject_id}'. "
19
+ "Only alphanumeric characters, hyphens, and underscores are allowed."
20
+ )
21
+ return subject_id
22
+
23
+ def discover_subjects(
24
+ bids_dir: Path,
25
+ subject_pattern: str = "sub-*",
26
+ session_pattern: str = "ses-*",
27
+ include_subjects: Optional[List[str]] = None,
28
+ exclude_subjects: Optional[List[str]] = None
29
+ ) -> List[Dict]:
30
+ """
31
+ Auto-discover subjects and sessions in a BIDS directory.
32
+
33
+ Returns:
34
+ List of dicts with 'id', 'session', 'dir'
35
+ """
36
+ subjects = []
37
+ bids_path = Path(bids_dir)
38
+
39
+ if not bids_path.is_dir():
40
+ raise ValueError(f"BIDS directory not found: {bids_dir}")
41
+
42
+ # Iterate over subject directories
43
+ for sub_dir in sorted(bids_path.glob(subject_pattern)):
44
+ if not sub_dir.is_dir():
45
+ continue
46
+
47
+ sub_id = sub_dir.name
48
+
49
+ # Apply include/exclude filters
50
+ if include_subjects:
51
+ if not any(re.match(p, sub_id) for p in include_subjects):
52
+ continue
53
+ if exclude_subjects:
54
+ if any(re.match(p, sub_id) for p in exclude_subjects):
55
+ continue
56
+
57
+ # Check for sessions
58
+ ses_dirs = sorted(sub_dir.glob(session_pattern))
59
+
60
+ if ses_dirs:
61
+ for ses_dir in ses_dirs:
62
+ if not ses_dir.is_dir():
63
+ continue
64
+ subjects.append({
65
+ "id": sub_id,
66
+ "session": ses_dir.name,
67
+ "dir": ses_dir
68
+ })
69
+ else:
70
+ # No sessions - check for dwi directory directly under subject
71
+ # or just assume the subject directory is the container
72
+ subjects.append({
73
+ "id": sub_id,
74
+ "session": None,
75
+ "dir": sub_dir
76
+ })
77
+
78
+ return subjects
79
+
80
+ def detect_input_type(dwi_dir: Path) -> Tuple[Literal["nifti", "dicom"], Path]:
81
+ """
82
+ Detect whether a directory contains NIfTI or DICOM data.
83
+ Priority: NIfTI > DICOM
84
+ """
85
+ # Look for dwi subfolder first (BIDS convention)
86
+ search_dirs = [dwi_dir / "dwi", dwi_dir]
87
+
88
+ for s_dir in search_dirs:
89
+ if not s_dir.is_dir():
90
+ continue
91
+
92
+ # 1. NIfTI check
93
+ nifti_files = sorted(s_dir.glob("*_dwi.nii.gz"))
94
+ if not nifti_files:
95
+ nifti_files = sorted(s_dir.glob("*.nii.gz"))
96
+
97
+ if nifti_files:
98
+ return "nifti", nifti_files[0]
99
+
100
+ # 2. DICOM check (look for .dcm files)
101
+ if any(s_dir.glob("*.dcm")) or any(s_dir.glob("*.DCM")):
102
+ return "dicom", s_dir
103
+
104
+ # Check for extensionless DICOMs
105
+ for f in s_dir.iterdir():
106
+ if f.is_file() and not f.name.startswith('.'):
107
+ # Basic magic number check without pydicom dependency if possible
108
+ try:
109
+ with open(f, 'rb') as fd:
110
+ fd.seek(128)
111
+ if fd.read(4) == b'DICM':
112
+ return "dicom", s_dir
113
+ except Exception:
114
+ pass
115
+ break
116
+
117
+ raise FileNotFoundError(f"No NIfTI or DICOM data found in {dwi_dir}")
118
+
119
+ def find_bval_bvec(nifti_path: Path) -> Tuple[Optional[Path], Optional[Path]]:
120
+ """Find matching .bval and .bvec files for a NIfTI file."""
121
+ # Try typical BIDS naming: sub-X_ses-Y_dwi.nii.gz -> sub-X_ses-Y_dwi.bval
122
+ base = str(nifti_path).replace('.nii.gz', '').replace('.nii', '')
123
+ bval = Path(f"{base}.bval")
124
+ bvec = Path(f"{base}.bvec")
125
+
126
+ return (bval if bval.exists() else None,
127
+ bvec if bvec.exists() else None)
128
+
129
+ def find_json_sidecar(nifti_path: Path) -> Optional[Path]:
130
+ """Find matching .json sidecar for a NIfTI file."""
131
+ base = str(nifti_path).replace('.nii.gz', '').replace('.nii', '')
132
+ json_path = Path(f"{base}.json")
133
+ return json_path if json_path.exists() else None
134
+
135
+ def detect_dicom_series(dicom_dir: Path) -> List[Dict]:
136
+ """
137
+ Scan DICOM directory and return unique series information.
138
+ Requires pydicom.
139
+ """
140
+ try:
141
+ import pydicom
142
+ except ImportError:
143
+ logger.warning("pydicom not installed; cannot detect DICOM series.")
144
+ return []
145
+
146
+ series = {}
147
+
148
+ # Scan files to group by series
149
+ for f in dicom_dir.iterdir():
150
+ if not f.is_file() or f.name.startswith('.'):
151
+ continue
152
+
153
+ try:
154
+ # stop_before_pixels=True makes this much faster
155
+ ds = pydicom.dcmread(str(f), stop_before_pixels=True)
156
+ uid = getattr(ds, 'SeriesInstanceUID', None)
157
+ if not uid:
158
+ continue
159
+
160
+ if uid not in series:
161
+ series[uid] = {
162
+ "uid": uid,
163
+ "description": str(getattr(ds, 'SeriesDescription', 'Unknown')),
164
+ "number": int(getattr(ds, 'SeriesNumber', 0)),
165
+ "file_count": 0
166
+ }
167
+ series[uid]["file_count"] += 1
168
+ except Exception:
169
+ continue
170
+
171
+ return sorted(list(series.values()), key=lambda x: x['number'])
172
+
173
+ def validate_single_series(dicom_dir: Path, series_uid: Optional[str] = None) -> str:
174
+ """
175
+ Ensure unambiguous DICOM series selection.
176
+ If multiple series exist and no UID is provided, raises ValueError.
177
+ """
178
+ series_list = detect_dicom_series(dicom_dir)
179
+
180
+ if not series_list:
181
+ raise ValueError(f"No valid DICOM series found in {dicom_dir}")
182
+
183
+ if series_uid:
184
+ if any(s['uid'] == series_uid for s in series_list):
185
+ return series_uid
186
+ raise ValueError(f"Specified Series UID '{series_uid}' not found in {dicom_dir}")
187
+
188
+ if len(series_list) > 1:
189
+ msg = f"Multiple DICOM series found in {dicom_dir}:\n"
190
+ for s in series_list:
191
+ msg += f" - {s['uid']} ({s['description']}, {s['file_count']} files)\n"
192
+ msg += "Specify 'series_uid' in manifest to select one."
193
+ raise ValueError(msg)
194
+
195
+ return series_list[0]['uid']
@@ -0,0 +1,76 @@
1
+ import os
2
+ import json
3
+ import socket
4
+ import logging
5
+ from pathlib import Path
6
+ from dataclasses import dataclass
7
+ from datetime import datetime
8
+ from typing import Optional
9
+
10
+ from filelock import FileLock, Timeout
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class LockError(Exception):
16
+ """Raised when a lock cannot be acquired."""
17
+ pass
18
+
19
+
20
+ @dataclass
21
+ class Lock:
22
+ """Represents an acquired filesystem lock."""
23
+ lock_file: Path
24
+ _filelock: object # filelock.FileLock instance
25
+
26
+
27
+ def _acquire_lock(lock_path: Path, name: str = "Batch") -> Lock:
28
+ """Acquire an advisory filesystem lock using filelock (cross-platform)."""
29
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
30
+
31
+ fl = FileLock(str(lock_path) + ".filelock")
32
+ try:
33
+ fl.acquire(timeout=0)
34
+ except Timeout:
35
+ try:
36
+ metadata = json.loads(lock_path.read_text())
37
+ info = (f"held by PID {metadata.get('pid')} "
38
+ f"on {metadata.get('hostname')} "
39
+ f"since {metadata.get('started_at')}")
40
+ except Exception:
41
+ info = "held by another process"
42
+ raise LockError(f"{name} lock {lock_path} {info}")
43
+
44
+ try:
45
+ metadata = {
46
+ "pid": os.getpid(),
47
+ "hostname": socket.gethostname(),
48
+ "started_at": datetime.now().isoformat(),
49
+ }
50
+ lock_path.write_text(json.dumps(metadata, indent=2))
51
+ except Exception as exc:
52
+ logger.warning(f"Failed to write metadata to lock file {lock_path}: {exc}")
53
+
54
+ return Lock(lock_file=lock_path, _filelock=fl)
55
+
56
+
57
+ def acquire_batch_lock(output_dir: Path) -> Lock:
58
+ """Acquire global batch lock in output root."""
59
+ return _acquire_lock(output_dir / "batch.lock", name="Batch")
60
+
61
+
62
+ def acquire_subject_lock(subject_dir: Path) -> Lock:
63
+ """Acquire per-subject lock in subject output directory."""
64
+ return _acquire_lock(subject_dir / ".lock", name="Subject")
65
+
66
+
67
+ def release_lock(lock: Optional[Lock]) -> None:
68
+ """Release the lock and remove the lock file."""
69
+ if lock is None:
70
+ return
71
+ try:
72
+ lock._filelock.release()
73
+ lock.lock_file.unlink(missing_ok=True)
74
+ Path(str(lock.lock_file) + ".filelock").unlink(missing_ok=True)
75
+ except Exception as exc:
76
+ logger.error(f"Error releasing lock {lock.lock_file}: {exc}")