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.
- csttool/__init__.py +2 -0
- csttool/batch/__init__.py +23 -0
- csttool/batch/batch.py +389 -0
- csttool/batch/modules/__init__.py +5 -0
- csttool/batch/modules/discover.py +195 -0
- csttool/batch/modules/locking.py +76 -0
- csttool/batch/modules/logging_setup.py +91 -0
- csttool/batch/modules/manifest.py +100 -0
- csttool/batch/modules/report.py +176 -0
- csttool/batch/modules/validation.py +128 -0
- csttool/bids/__init__.py +19 -0
- csttool/bids/output.py +372 -0
- csttool/cli/__init__.py +834 -0
- csttool/cli/commands/__init__.py +0 -0
- csttool/cli/commands/batch.py +212 -0
- csttool/cli/commands/check.py +9 -0
- csttool/cli/commands/check_dataset.py +214 -0
- csttool/cli/commands/doctor.py +250 -0
- csttool/cli/commands/extract.py +563 -0
- csttool/cli/commands/fetch_data.py +253 -0
- csttool/cli/commands/import_cmd.py +325 -0
- csttool/cli/commands/metrics.py +310 -0
- csttool/cli/commands/preprocess.py +43 -0
- csttool/cli/commands/run.py +810 -0
- csttool/cli/commands/track.py +209 -0
- csttool/cli/commands/validate.py +220 -0
- csttool/cli/utils.py +282 -0
- csttool/data/LICENSES/FSL_LICENSE.txt +47 -0
- csttool/data/LICENSES/MNI152_LICENSE.txt +15 -0
- csttool/data/__init__.py +27 -0
- csttool/data/loader.py +303 -0
- csttool/data/manifest.py +146 -0
- csttool/data/mni152/MNI152_T1_1mm.nii.gz +0 -0
- csttool/extract/__init__.py +11 -0
- csttool/extract/modules/__init__.py +39 -0
- csttool/extract/modules/bidirectional_filtering.py +356 -0
- csttool/extract/modules/coordinate_validation.py +250 -0
- csttool/extract/modules/create_roi_masks.py +448 -0
- csttool/extract/modules/diagnostic.py +37 -0
- csttool/extract/modules/endpoint_filtering.py +442 -0
- csttool/extract/modules/passthrough_filtering.py +522 -0
- csttool/extract/modules/registration.py +976 -0
- csttool/extract/modules/roi_seeded_tracking.py +483 -0
- csttool/extract/modules/save_extract_outputs.py +0 -0
- csttool/extract/modules/visualizations.py +1089 -0
- csttool/extract/modules/warp_atlas_to_subject.py +642 -0
- csttool/ingest/__init__.py +339 -0
- csttool/ingest/modules/__init__.py +62 -0
- csttool/ingest/modules/analyze_series.py +500 -0
- csttool/ingest/modules/assess_quality.py +413 -0
- csttool/ingest/modules/convert_series.py +380 -0
- csttool/ingest/modules/save_ingest_outputs.py +348 -0
- csttool/ingest/modules/scan_study.py +291 -0
- csttool/metrics/__init__.py +77 -0
- csttool/metrics/modules/__init__.py +32 -0
- csttool/metrics/modules/bilateral_analysis.py +376 -0
- csttool/metrics/modules/reports.py +687 -0
- csttool/metrics/modules/templates/report.css +382 -0
- csttool/metrics/modules/templates/report.html.j2 +216 -0
- csttool/metrics/modules/unilateral_analysis.py +458 -0
- csttool/metrics/modules/visualizations.py +812 -0
- csttool/preprocess/__init__.py +42 -0
- csttool/preprocess/modules/__init__.py +23 -0
- csttool/preprocess/modules/background_segmentation.py +63 -0
- csttool/preprocess/modules/denoise.py +78 -0
- csttool/preprocess/modules/gibbs_unringing.py +47 -0
- csttool/preprocess/modules/load_dataset.py +125 -0
- csttool/preprocess/modules/perform_motion_correction.py +55 -0
- csttool/preprocess/modules/reslice_voxels.py +46 -0
- csttool/preprocess/modules/save_preprocessed.py +136 -0
- csttool/preprocess/modules/visualizations.py +725 -0
- csttool/preprocess/preprocess.py +242 -0
- csttool/reproducibility/__init__.py +14 -0
- csttool/reproducibility/context.py +56 -0
- csttool/reproducibility/provenance.py +120 -0
- csttool/reproducibility/tolerance.py +185 -0
- csttool/tracking/__init__.py +19 -0
- csttool/tracking/modules/__init__.py +45 -0
- csttool/tracking/modules/estimate_directions.py +129 -0
- csttool/tracking/modules/fit_tensors.py +103 -0
- csttool/tracking/modules/load_and_mask.py +57 -0
- csttool/tracking/modules/run_tractography.py +79 -0
- csttool/tracking/modules/save_tracking_outputs.py +181 -0
- csttool/tracking/modules/seed_and_stop.py +70 -0
- csttool/tracking/modules/visualizations.py +780 -0
- csttool/validation/__init__.py +30 -0
- csttool/validation/bundle_comparison.py +414 -0
- csttool/validation/visualization.py +114 -0
- csttool-0.5.0.dist-info/METADATA +167 -0
- csttool-0.5.0.dist-info/RECORD +93 -0
- csttool-0.5.0.dist-info/WHEEL +4 -0
- csttool-0.5.0.dist-info/entry_points.txt +2 -0
- csttool-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import json
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Optional
|
|
7
|
+
|
|
8
|
+
class JsonLinesFormatter(logging.Formatter):
|
|
9
|
+
"""Formats log records as JSON objects, one per line."""
|
|
10
|
+
def format(self, record):
|
|
11
|
+
log_entry = {
|
|
12
|
+
"timestamp": datetime.fromtimestamp(record.created).isoformat(),
|
|
13
|
+
"level": record.levelname,
|
|
14
|
+
"name": record.name,
|
|
15
|
+
"message": record.getMessage(),
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
# Add exception info if present
|
|
19
|
+
if record.exc_info:
|
|
20
|
+
log_entry["exception"] = self.formatException(record.exc_info)
|
|
21
|
+
|
|
22
|
+
# Add extra attributes if passed via extra={}
|
|
23
|
+
# We look for attributes that aren't standard LogRecord attributes
|
|
24
|
+
standard_attrs = {
|
|
25
|
+
'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename',
|
|
26
|
+
'funcName', 'levelname', 'levelno', 'lineno', 'module',
|
|
27
|
+
'msecs', 'message', 'msg', 'name', 'pathname', 'process',
|
|
28
|
+
'processName', 'relativeCreated', 'stack_info', 'thread', 'threadName'
|
|
29
|
+
}
|
|
30
|
+
for key, value in record.__dict__.items():
|
|
31
|
+
if key not in standard_attrs:
|
|
32
|
+
log_entry[key] = value
|
|
33
|
+
|
|
34
|
+
return json.dumps(log_entry)
|
|
35
|
+
|
|
36
|
+
def setup_subject_logger(
|
|
37
|
+
subject_id: str,
|
|
38
|
+
session_id: Optional[str],
|
|
39
|
+
log_path: Path,
|
|
40
|
+
level: str = "INFO",
|
|
41
|
+
verbose: bool = False
|
|
42
|
+
) -> logging.Logger:
|
|
43
|
+
"""
|
|
44
|
+
Sets up an isolated logger for a specific subject/session attempt.
|
|
45
|
+
|
|
46
|
+
Outputs structured JSON Lines to the log_path and plain text to stdout if verbose.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
subject_id: Identifier for the subject
|
|
50
|
+
session_id: Optional identifier for the session
|
|
51
|
+
log_path: Full path to the log file to create
|
|
52
|
+
level: Logging level (default: INFO)
|
|
53
|
+
verbose: If True, also output to stdout
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
A configured logging.Logger instance
|
|
57
|
+
"""
|
|
58
|
+
# Create parent directories for the log file
|
|
59
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
60
|
+
|
|
61
|
+
# Create a unique logger name for this subject run
|
|
62
|
+
logger_name = f"csttool.batch.{subject_id}"
|
|
63
|
+
if session_id:
|
|
64
|
+
logger_name += f".{session_id}"
|
|
65
|
+
|
|
66
|
+
logger = logging.getLogger(logger_name)
|
|
67
|
+
logger.setLevel(level)
|
|
68
|
+
|
|
69
|
+
# Prevent propagation to root logger to maintain isolation
|
|
70
|
+
logger.propagate = False
|
|
71
|
+
|
|
72
|
+
# Remove any existing handlers
|
|
73
|
+
if logger.hasHandlers():
|
|
74
|
+
logger.handlers.clear()
|
|
75
|
+
|
|
76
|
+
# 1. File Handler (JSON Lines)
|
|
77
|
+
file_handler = logging.FileHandler(log_path)
|
|
78
|
+
file_handler.setFormatter(JsonLinesFormatter())
|
|
79
|
+
logger.addHandler(file_handler)
|
|
80
|
+
|
|
81
|
+
# 2. Console Handler (Plain text, optional)
|
|
82
|
+
if verbose:
|
|
83
|
+
console_handler = logging.StreamHandler(sys.stdout)
|
|
84
|
+
fmt = f"[%(levelname)s] {subject_id}"
|
|
85
|
+
if session_id:
|
|
86
|
+
fmt += f"/{session_id}"
|
|
87
|
+
fmt += ": %(message)s"
|
|
88
|
+
console_handler.setFormatter(logging.Formatter(fmt))
|
|
89
|
+
logger.addHandler(console_handler)
|
|
90
|
+
|
|
91
|
+
return logger
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import List, Dict, Tuple, Any, Optional
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
|
|
6
|
+
@dataclass
|
|
7
|
+
class StudyInfo:
|
|
8
|
+
"""General metadata and global options for a batch run."""
|
|
9
|
+
name: str = "Unnamed Study"
|
|
10
|
+
description: str = ""
|
|
11
|
+
global_options: Dict[str, Any] = field(default_factory=dict)
|
|
12
|
+
|
|
13
|
+
def load_manifest(path: Path) -> Tuple[StudyInfo, List[Dict[str, Any]]]:
|
|
14
|
+
"""
|
|
15
|
+
Load and parse a JSON manifest file.
|
|
16
|
+
|
|
17
|
+
Returns:
|
|
18
|
+
Tuple of (StudyInfo, List of subject configurations)
|
|
19
|
+
|
|
20
|
+
Raises:
|
|
21
|
+
ValueError if manifest is invalid or missing required fields.
|
|
22
|
+
"""
|
|
23
|
+
if not path.exists():
|
|
24
|
+
raise FileNotFoundError(f"Manifest file not found: {path}")
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
with open(path, 'r') as f:
|
|
28
|
+
data = json.load(f)
|
|
29
|
+
except json.JSONDecodeError as e:
|
|
30
|
+
raise ValueError(f"Failed to parse manifest JSON: {e}")
|
|
31
|
+
|
|
32
|
+
if not isinstance(data, dict):
|
|
33
|
+
raise ValueError("Manifest must be a JSON object")
|
|
34
|
+
|
|
35
|
+
# extract study info
|
|
36
|
+
study = StudyInfo(
|
|
37
|
+
name=data.get("name", "Unnamed Study"),
|
|
38
|
+
description=data.get("description", ""),
|
|
39
|
+
global_options=data.get("options", {})
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
subjects_data = data.get("subjects", [])
|
|
43
|
+
if not isinstance(subjects_data, list):
|
|
44
|
+
raise ValueError("'subjects' field in manifest must be a list")
|
|
45
|
+
|
|
46
|
+
subjects = []
|
|
47
|
+
for i, s_data in enumerate(subjects_data):
|
|
48
|
+
if not isinstance(s_data, dict):
|
|
49
|
+
raise ValueError(f"Subject at index {i} must be an object")
|
|
50
|
+
|
|
51
|
+
if "id" not in s_data:
|
|
52
|
+
raise ValueError(f"Subject at index {i} is missing required 'id'")
|
|
53
|
+
|
|
54
|
+
# Check for exclusivity of nifti/dicom
|
|
55
|
+
has_nifti = "nifti" in s_data
|
|
56
|
+
has_dicom = "dicom" in s_data
|
|
57
|
+
|
|
58
|
+
if not has_nifti and not has_dicom:
|
|
59
|
+
raise ValueError(f"Subject '{s_data['id']}' must specify either 'nifti' or 'dicom'")
|
|
60
|
+
if has_nifti and has_dicom:
|
|
61
|
+
raise ValueError(f"Subject '{s_data['id']}' cannot specify both 'nifti' and 'dicom'")
|
|
62
|
+
|
|
63
|
+
# Standardize subject entry
|
|
64
|
+
sub_entry = {
|
|
65
|
+
"id": str(s_data["id"]),
|
|
66
|
+
"session": s_data.get("session"),
|
|
67
|
+
"nifti": Path(s_data["nifti"]) if has_nifti else None,
|
|
68
|
+
"dicom": Path(s_data["dicom"]) if has_dicom else None,
|
|
69
|
+
"series_uid": s_data.get("series_uid"),
|
|
70
|
+
"options": s_data.get("options", {})
|
|
71
|
+
}
|
|
72
|
+
subjects.append(sub_entry)
|
|
73
|
+
|
|
74
|
+
return study, subjects
|
|
75
|
+
|
|
76
|
+
def save_manifest_template(path: Path) -> None:
|
|
77
|
+
"""Generates a template manifest JSON file for users."""
|
|
78
|
+
template = {
|
|
79
|
+
"name": "Example Study",
|
|
80
|
+
"description": "Template manifest for csttool batch processing",
|
|
81
|
+
"options": {
|
|
82
|
+
"denoise_method": "patch2self",
|
|
83
|
+
"generate_pdf": True
|
|
84
|
+
},
|
|
85
|
+
"subjects": [
|
|
86
|
+
{
|
|
87
|
+
"id": "sub-001",
|
|
88
|
+
"session": "ses-01",
|
|
89
|
+
"nifti": "/path/to/sub-001_ses-01_dwi.nii.gz"
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
"id": "sub-002",
|
|
93
|
+
"dicom": "/path/to/sub-002/dicom/",
|
|
94
|
+
"series_uid": "1.2.840.113619.2.55.3..."
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
with open(path, 'w') as f:
|
|
100
|
+
json.dump(template, f, indent=2)
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List, Dict, Any
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
# Standard headers aligned with single-subject report
|
|
9
|
+
METRICS_HEADERS = [
|
|
10
|
+
# Batch metadata
|
|
11
|
+
"subject_id", "session_id", "status", "error_category",
|
|
12
|
+
"duration_seconds", "error",
|
|
13
|
+
|
|
14
|
+
# Morphology
|
|
15
|
+
"left_n_streamlines", "right_n_streamlines",
|
|
16
|
+
"left_mean_length_mm", "right_mean_length_mm",
|
|
17
|
+
"left_tract_volume_mm3", "right_tract_volume_mm3",
|
|
18
|
+
"volume_laterality_index", "streamline_count_laterality_index"
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
# Add headers for all scalars and regions dynamically to ensure consistency
|
|
22
|
+
_SCALARS = ['fa', 'md', 'rd', 'ad']
|
|
23
|
+
_REGIONS = ['pontine', 'plic', 'precentral']
|
|
24
|
+
|
|
25
|
+
for scalar in _SCALARS:
|
|
26
|
+
METRICS_HEADERS.extend([
|
|
27
|
+
f"left_{scalar}_mean", f"left_{scalar}_std",
|
|
28
|
+
f"right_{scalar}_mean", f"right_{scalar}_std",
|
|
29
|
+
f"{scalar}_laterality_index"
|
|
30
|
+
])
|
|
31
|
+
for region in _REGIONS:
|
|
32
|
+
METRICS_HEADERS.extend([
|
|
33
|
+
f"left_{scalar}_{region}",
|
|
34
|
+
f"right_{scalar}_{region}",
|
|
35
|
+
f"{scalar}_{region}_laterality_index"
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
def generate_batch_reports(results: List[Any], output_dir: Path):
|
|
41
|
+
"""
|
|
42
|
+
Orchestrates the generation of all batch-level reports.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
results: List of SubjectResult objects
|
|
46
|
+
output_dir: Path to the batch output root
|
|
47
|
+
"""
|
|
48
|
+
write_batch_metrics_csv(results, output_dir)
|
|
49
|
+
write_batch_summary_json(results, output_dir)
|
|
50
|
+
|
|
51
|
+
def write_batch_metrics_csv(results: List[Any], output_dir: Path):
|
|
52
|
+
"""
|
|
53
|
+
Writes a CSV aggregate of all subject metrics.
|
|
54
|
+
Numeric cells are empty for failed or skipped subjects.
|
|
55
|
+
"""
|
|
56
|
+
csv_path = output_dir / "batch_metrics.csv"
|
|
57
|
+
|
|
58
|
+
rows = []
|
|
59
|
+
for res in results:
|
|
60
|
+
# Standard fields always populated
|
|
61
|
+
row = {
|
|
62
|
+
"subject_id": res.subject_id,
|
|
63
|
+
"session_id": res.session_id or "",
|
|
64
|
+
"status": res.status,
|
|
65
|
+
"error_category": res.error_category or "",
|
|
66
|
+
"duration_seconds": round(res.duration_seconds, 1),
|
|
67
|
+
"error": res.error or ""
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
# If success, attempt to extract metrics from the per-subject JSON
|
|
71
|
+
if res.status == "success":
|
|
72
|
+
try:
|
|
73
|
+
# Construct path to the subject's JSON report
|
|
74
|
+
subj_path = output_dir / res.subject_id
|
|
75
|
+
if res.session_id:
|
|
76
|
+
subj_path = subj_path / res.session_id
|
|
77
|
+
|
|
78
|
+
metrics_file = subj_path / "metrics" / f"{res.subject_id}_bilateral_metrics.json"
|
|
79
|
+
|
|
80
|
+
if metrics_file.exists():
|
|
81
|
+
with open(metrics_file, 'r') as f:
|
|
82
|
+
data = json.load(f)
|
|
83
|
+
m = data.get("metrics", {})
|
|
84
|
+
|
|
85
|
+
if 'left' in m and 'right' in m:
|
|
86
|
+
left = m['left']
|
|
87
|
+
right = m['right']
|
|
88
|
+
asym = m['asymmetry']
|
|
89
|
+
|
|
90
|
+
# Morphology
|
|
91
|
+
row.update({
|
|
92
|
+
'left_n_streamlines': left['morphology']['n_streamlines'],
|
|
93
|
+
'right_n_streamlines': right['morphology']['n_streamlines'],
|
|
94
|
+
'left_mean_length_mm': left['morphology']['mean_length'],
|
|
95
|
+
'right_mean_length_mm': right['morphology']['mean_length'],
|
|
96
|
+
'left_tract_volume_mm3': left['morphology']['tract_volume'],
|
|
97
|
+
'right_tract_volume_mm3': right['morphology']['tract_volume'],
|
|
98
|
+
'volume_laterality_index': asym['volume']['laterality_index'],
|
|
99
|
+
'streamline_count_laterality_index': asym['streamline_count']['laterality_index'],
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
# Scalars (Global)
|
|
103
|
+
for scalar in _SCALARS:
|
|
104
|
+
if scalar in left:
|
|
105
|
+
row.update({
|
|
106
|
+
f'left_{scalar}_mean': left[scalar]['mean'],
|
|
107
|
+
f'left_{scalar}_std': left[scalar]['std'],
|
|
108
|
+
f'right_{scalar}_mean': right[scalar]['mean'],
|
|
109
|
+
f'right_{scalar}_std': right[scalar]['std'],
|
|
110
|
+
f'{scalar}_laterality_index': asym[scalar]['laterality_index'],
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
# Localized Metrics
|
|
114
|
+
if 'pontine' in left[scalar]: # check if localized metrics exist
|
|
115
|
+
for region in _REGIONS:
|
|
116
|
+
# Values
|
|
117
|
+
l_val = left[scalar].get(region, 0.0)
|
|
118
|
+
r_val = right[scalar].get(region, 0.0)
|
|
119
|
+
row[f'left_{scalar}_{region}'] = l_val
|
|
120
|
+
row[f'right_{scalar}_{region}'] = r_val
|
|
121
|
+
|
|
122
|
+
# LI for region
|
|
123
|
+
li_key = f'{scalar}_{region}'
|
|
124
|
+
if li_key in asym:
|
|
125
|
+
row[f'{scalar}_{region}_laterality_index'] = asym[li_key]['laterality_index']
|
|
126
|
+
|
|
127
|
+
except Exception as e:
|
|
128
|
+
logger.warning(f"Could not extract metrics for {res.subject_id}: {e}")
|
|
129
|
+
|
|
130
|
+
rows.append(row)
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
with open(csv_path, 'w', newline='') as f:
|
|
134
|
+
writer = csv.DictWriter(f, fieldnames=METRICS_HEADERS, restval="")
|
|
135
|
+
writer.writeheader()
|
|
136
|
+
writer.writerows(rows)
|
|
137
|
+
logger.info(f"✓ Batch metrics CSV: {csv_path}")
|
|
138
|
+
except Exception as e:
|
|
139
|
+
logger.error(f"Failed to write batch_metrics.csv: {e}")
|
|
140
|
+
|
|
141
|
+
def write_batch_summary_json(results: List[Any], output_dir: Path):
|
|
142
|
+
"""
|
|
143
|
+
Writes a versioned JSON summary of the entire batch run.
|
|
144
|
+
Contains summary counters and individual status records.
|
|
145
|
+
"""
|
|
146
|
+
summary_path = output_dir / "batch_summary.json"
|
|
147
|
+
|
|
148
|
+
counts = {
|
|
149
|
+
"total": len(results),
|
|
150
|
+
"success": sum(1 for r in results if r.status == "success"),
|
|
151
|
+
"failed": sum(1 for r in results if r.status == "failed"),
|
|
152
|
+
"skipped": sum(1 for r in results if r.status == "skipped")
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
summary = {
|
|
156
|
+
"schema_version": "1.0.0",
|
|
157
|
+
"generated_at": datetime.now().isoformat(),
|
|
158
|
+
"summary": counts,
|
|
159
|
+
"results": [
|
|
160
|
+
{
|
|
161
|
+
"subject_id": r.subject_id,
|
|
162
|
+
"session_id": r.session_id,
|
|
163
|
+
"status": r.status,
|
|
164
|
+
"error_category": r.error_category,
|
|
165
|
+
"duration_seconds": round(r.duration_seconds, 1),
|
|
166
|
+
"error": r.error
|
|
167
|
+
} for r in results
|
|
168
|
+
]
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
try:
|
|
172
|
+
with open(summary_path, 'w') as f:
|
|
173
|
+
json.dump(summary, f, indent=2)
|
|
174
|
+
logger.info(f"✓ Batch summary JSON: {summary_path}")
|
|
175
|
+
except Exception as e:
|
|
176
|
+
logger.error(f"Failed to write batch_summary.json: {e}")
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List, Literal, Optional, Any
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .locking import acquire_batch_lock, release_lock, LockError
|
|
9
|
+
from .discover import sanitize_subject_id
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class PreflightError:
|
|
15
|
+
"""Represents an error found during batch preflight validation."""
|
|
16
|
+
category: Literal["SYSTEM", "INPUT", "CONFIG"]
|
|
17
|
+
message: str
|
|
18
|
+
subject_id: Optional[str] = None
|
|
19
|
+
|
|
20
|
+
def validate_batch_preflight(subjects: List[Any], config: Any) -> List[PreflightError]:
|
|
21
|
+
"""
|
|
22
|
+
Run comprehensive preflight checks before starting batch processing.
|
|
23
|
+
|
|
24
|
+
Checks:
|
|
25
|
+
- Environment (dependencies)
|
|
26
|
+
- Concurrency (batch lock)
|
|
27
|
+
- Output directory (writable, disk space)
|
|
28
|
+
- Inputs (existence, duplicates, BIDS naming)
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
List of PreflightError objects. Empty if all checks pass.
|
|
32
|
+
"""
|
|
33
|
+
errors = []
|
|
34
|
+
|
|
35
|
+
# 1. Environment Check
|
|
36
|
+
# We reuse the existing cmd_check logic
|
|
37
|
+
try:
|
|
38
|
+
from csttool.cli.commands.check import cmd_check
|
|
39
|
+
import argparse
|
|
40
|
+
import sys
|
|
41
|
+
from io import StringIO
|
|
42
|
+
|
|
43
|
+
# Capture stdout to avoid cluttering during internal validation
|
|
44
|
+
old_stdout = sys.stdout
|
|
45
|
+
sys.stdout = StringIO()
|
|
46
|
+
try:
|
|
47
|
+
check_ok = cmd_check(argparse.Namespace())
|
|
48
|
+
finally:
|
|
49
|
+
sys.stdout = old_stdout
|
|
50
|
+
|
|
51
|
+
if not check_ok:
|
|
52
|
+
errors.append(PreflightError(
|
|
53
|
+
"SYSTEM",
|
|
54
|
+
"Required dependencies are missing. Run 'csttool check' for details."
|
|
55
|
+
))
|
|
56
|
+
except Exception as e:
|
|
57
|
+
errors.append(PreflightError("SYSTEM", f"Failed to run environment check: {e}"))
|
|
58
|
+
|
|
59
|
+
# 2. Concurrent Batch Lock
|
|
60
|
+
try:
|
|
61
|
+
lock = acquire_batch_lock(config.out)
|
|
62
|
+
release_lock(lock)
|
|
63
|
+
except LockError as e:
|
|
64
|
+
errors.append(PreflightError("SYSTEM", str(e)))
|
|
65
|
+
except Exception as e:
|
|
66
|
+
# If output dir doesn't exist yet, locking might fail
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
# 3. Output Directory
|
|
70
|
+
out_dir = Path(config.out)
|
|
71
|
+
if out_dir.exists():
|
|
72
|
+
if not os.access(out_dir, os.W_OK):
|
|
73
|
+
errors.append(PreflightError("SYSTEM", f"Output directory is not writable: {out_dir}"))
|
|
74
|
+
else:
|
|
75
|
+
try:
|
|
76
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
except Exception as e:
|
|
78
|
+
errors.append(PreflightError("SYSTEM", f"Cannot create output directory: {e}"))
|
|
79
|
+
|
|
80
|
+
# Heuristic disk space check
|
|
81
|
+
if out_dir.exists():
|
|
82
|
+
try:
|
|
83
|
+
_, _, free = shutil.disk_usage(out_dir)
|
|
84
|
+
# Estimate 2GB per subject as a safe heuristic for CST pipeline
|
|
85
|
+
estimated_required = len(subjects) * 2 * 1024 * 1024 * 1024
|
|
86
|
+
if free < estimated_required:
|
|
87
|
+
errors.append(PreflightError(
|
|
88
|
+
"SYSTEM",
|
|
89
|
+
f"Insufficient disk space. Estimated {estimated_required/1e9:.1f} GB required, "
|
|
90
|
+
f"{free/1e9:.1f} GB available."
|
|
91
|
+
))
|
|
92
|
+
except Exception:
|
|
93
|
+
pass # Could not check disk usage - not fatal
|
|
94
|
+
|
|
95
|
+
# 4. Input Validation
|
|
96
|
+
seen_combinations = set()
|
|
97
|
+
for s in subjects:
|
|
98
|
+
# BIDS naming check
|
|
99
|
+
try:
|
|
100
|
+
sanitize_subject_id(s.subject_id)
|
|
101
|
+
except ValueError as e:
|
|
102
|
+
errors.append(PreflightError("INPUT", str(e), s.subject_id))
|
|
103
|
+
|
|
104
|
+
# Duplicate subject/session check
|
|
105
|
+
key = (s.subject_id, getattr(s, 'session_id', None))
|
|
106
|
+
if key in seen_combinations:
|
|
107
|
+
errors.append(PreflightError(
|
|
108
|
+
"CONFIG",
|
|
109
|
+
f"Duplicate subject/session combination: {s.subject_id}/{key[1]}",
|
|
110
|
+
s.subject_id
|
|
111
|
+
))
|
|
112
|
+
seen_combinations.add(key)
|
|
113
|
+
|
|
114
|
+
# File/Directory existence
|
|
115
|
+
if s.input_type == "nifti":
|
|
116
|
+
if not s.input_path.exists():
|
|
117
|
+
errors.append(PreflightError("INPUT", f"NIfTI file not found: {s.input_path}", s.subject_id))
|
|
118
|
+
if s.bval_path and not s.bval_path.exists():
|
|
119
|
+
errors.append(PreflightError("INPUT", f"bval file not found: {s.bval_path}", s.subject_id))
|
|
120
|
+
if s.bvec_path and not s.bvec_path.exists():
|
|
121
|
+
errors.append(PreflightError("INPUT", f"bvec file not found: {s.bvec_path}", s.subject_id))
|
|
122
|
+
elif s.input_type == "dicom":
|
|
123
|
+
if not s.input_path.is_dir():
|
|
124
|
+
errors.append(PreflightError("INPUT", f"DICOM directory not found: {s.input_path}", s.subject_id))
|
|
125
|
+
# Optional: deep check of DICOM files count?
|
|
126
|
+
# already partially handled in discover.detect_input_type
|
|
127
|
+
|
|
128
|
+
return errors
|
csttool/bids/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from .output import (
|
|
2
|
+
write_dataset_description,
|
|
3
|
+
update_participants_tsv,
|
|
4
|
+
write_participants_json,
|
|
5
|
+
bids_filename,
|
|
6
|
+
write_derivative_sidecar,
|
|
7
|
+
sanitize_bids_label,
|
|
8
|
+
parse_dicom_age,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"write_dataset_description",
|
|
13
|
+
"update_participants_tsv",
|
|
14
|
+
"write_participants_json",
|
|
15
|
+
"bids_filename",
|
|
16
|
+
"write_derivative_sidecar",
|
|
17
|
+
"sanitize_bids_label",
|
|
18
|
+
"parse_dicom_age",
|
|
19
|
+
]
|