Repository navigation
Expand file tree
/
Copy pathrun.py
More file actions
239 lines (201 loc) · 8.9 KB
/
Copy pathrun.py
File metadata and controls
239 lines (201 loc) · 8.9 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
#!/usr/bin/env python3
"""
Branchseed CLI — thin wrapper only. Calls the pipeline stages in order and
always writes a valid JSON output, even on failure.
Usage (exact form required by the brief):
python run.py --image image.nii.gz --aorta-mask aorta_mask.nii.gz --output prediction.json
Also accepts plain .nii for --image / --aorta-mask.
"""
import argparse
import os
import time
import traceback
import numpy as np
import yaml
from src.io_geom import load_case
from src.intensity import profile_aorta
from src.candidates import candidate_mask
from src.aorta_frame import AortaFrame, build_frame, clock_and_arclen
from src.instances import find_raw_branches
from src.geometry import measure
from src.gate import accept, dedup
from src.report import write_prediction_json
def parse_args() -> argparse.Namespace:
"""Parse the required CLI arguments.
Returns:
argparse.Namespace with `image`, `aorta_mask`, `output`, and
`config` (defaults to config/default.yaml).
"""
parser = argparse.ArgumentParser(description="Branchseed: detect aortic daughter branches.")
parser.add_argument("--image", required=True, help="Path to the CT volume (.nii or .nii.gz), HU.")
parser.add_argument("--aorta-mask", required=True, dest="aorta_mask", help="Path to the binary aorta mask (.nii or .nii.gz).")
parser.add_argument("--output", required=True, help="Path to write the prediction JSON to.")
parser.add_argument("--config", default="config/default.yaml", help="Path to the YAML config (default: config/default.yaml).")
return parser.parse_args()
def load_config(config_path: str) -> dict:
"""Load the YAML config used by every pipeline stage.
Args:
config_path: path to a YAML file (see config/default.yaml).
Returns:
dict of config values. No numeric literal may be used in src/
outside of this dict.
"""
with open(config_path, "r") as f:
return yaml.safe_load(f)
def _local_tangent(frame: AortaFrame, xyz_mm: np.ndarray) -> np.ndarray:
"""Unit tangent of the aortic centreline nearest a given physical point.
Args:
frame: `AortaFrame` from `aorta_frame.build_frame`.
xyz_mm: physical point (x, y, z) in mm (typically a branch ostium).
Returns:
np.ndarray, shape (3,), unit vector along `frame.centreline_mm`
(superior -> inferior ordering) at the point nearest `xyz_mm`, via a
local finite difference. Zero vector if the centreline has fewer
than two points or the local segment is degenerate.
"""
centre = frame.centreline_mm
if centre.shape[0] < 2:
return np.zeros(3)
idx = int(np.argmin(np.linalg.norm(centre - xyz_mm[np.newaxis, :], axis=1)))
lo = max(idx - 1, 0)
hi = min(idx + 1, centre.shape[0] - 1)
tangent = centre[hi] - centre[lo]
norm = np.linalg.norm(tangent)
return tangent / norm if norm > 1e-9 else np.zeros(3)
def _takeoff_angle_deg(direction: np.ndarray, tangent: np.ndarray) -> float:
"""Angle in degrees between a branch direction and the local aortic axis."""
norm_d = np.linalg.norm(direction)
norm_t = np.linalg.norm(tangent)
if norm_d < 1e-9 or norm_t < 1e-9:
return float("nan")
cos_t = float(np.clip(np.dot(direction, tangent) / (norm_d * norm_t), -1.0, 1.0))
return float(np.degrees(np.arccos(cos_t)))
def empty_result(case_id: str, warnings: list) -> dict:
"""Build the minimal valid prediction JSON payload (no detections).
Args:
case_id: identifier for the case (derived from the input filename
when the pipeline fails before a `Case` is available).
warnings: list of str, human-readable failure descriptions.
Returns:
dict matching the required schema, with an empty `daughters` list
and an empty `excluded_candidates` list, per §5.9 ("wrap every case
in a try/except that, on any failure, still writes a valid file
with an empty daughters list and a warnings field").
"""
return {
"case_id": case_id,
"parent": {"instance_id": "aorta"},
"daughters": [],
"excluded_candidates": [],
"meta": {"runtime_s": 0.0, "a_med_hu": None, "t_vessel_hu": None, "warnings": warnings},
}
def _notify(on_stage, name: str) -> None:
"""Call `on_stage(name)` if set, never letting it raise into the caller.
Args:
on_stage: optional callable taking one str stage-name argument, or
None.
name: the stage name to report.
"""
if on_stage is None:
return
try:
on_stage(name)
except Exception: # noqa: BLE001 - a progress callback must never fail a run
pass
def run_case(image_path: str, mask_path: str, cfg: dict, on_stage=None) -> dict:
"""Run the full pipeline (stages 1-9) on one case.
Args:
image_path: path to the CT volume.
mask_path: path to the binary aorta mask.
cfg: parsed config dict.
on_stage: optional callable(str) invoked with a stage name
("load", "profile", "candidates", "frame", "instances",
"geometry", "export") immediately before that stage runs.
Purely additive/optional; used by webapp/jobs.py to drive a
live progress UI. Any exception it raises is swallowed.
Returns:
dict matching the required prediction schema (§5.10). Never raises;
any internal failure is caught and converted into `empty_result`
with a populated `warnings` list, so the CLI always writes valid
output.
"""
t0 = time.time()
warnings = []
case_id = os.path.basename(os.path.dirname(image_path)) or image_path.split("/")[-1].split(".")[0]
try:
_notify(on_stage, "load")
case = load_case(image_path, mask_path, cfg)
case_id = case.case_id
_notify(on_stage, "profile")
profile = profile_aorta(case, cfg)
_notify(on_stage, "candidates")
cand = candidate_mask(case, profile, cfg)
_notify(on_stage, "frame")
frame = build_frame(case, cfg)
_notify(on_stage, "instances")
raw_branches = find_raw_branches(case, cand, frame, profile, cfg)
_notify(on_stage, "geometry")
accepted = []
for raw in raw_branches:
# A single degenerate candidate (e.g. too few voxels for the
# MCP path solver to find any route to its own extent target)
# must never crash the whole case -- log it as a rejection and
# keep processing every other candidate.
try:
geom = measure(case, raw, frame, profile, cfg)
except Exception as exc: # noqa: BLE001 - per-candidate robustness
if cfg.get("log_rejections"):
warnings.append(f"rejected: measure_failed ({exc})")
continue
keep, reason = accept(raw, geom, profile, cfg)
if keep:
accepted.append((raw, geom))
elif cfg.get("log_rejections"):
warnings.append(f"rejected: {reason}")
accepted = dedup(accepted, cfg)
_notify(on_stage, "export")
daughters = []
for i, (raw, geom) in enumerate(accepted):
clock_hours, arclen_mm = clock_and_arclen(frame, geom.ostium_mm)
tangent = _local_tangent(frame, geom.ostium_mm)
takeoff_deg = _takeoff_angle_deg(geom.direction, tangent)
daughters.append(
{
"instance_id": f"branch_{i + 1:03d}",
"parent_instance_id": "aorta",
"ostium_xyz_mm": geom.ostium_mm.tolist(),
"seed_xyz_mm": geom.seed_mm.tolist(),
"radius_mm": float(geom.radius_mm),
"direction_xyz": geom.direction.tolist(),
"confidence": 1.0,
"clock_position": float(clock_hours),
"arclen_from_top_mm": float(arclen_mm),
"takeoff_angle_deg": takeoff_deg,
}
)
return {
"case_id": case_id,
"parent": {"instance_id": "aorta"},
"daughters": daughters,
"excluded_candidates": frame.excluded,
"meta": {
"runtime_s": time.time() - t0,
"a_med_hu": profile.a_med,
"t_vessel_hu": profile.t_vessel,
"warnings": warnings,
},
}
except Exception: # noqa: BLE001 - per-case robustness is a hard requirement
warnings.append(traceback.format_exc())
result = empty_result(case_id, warnings)
result["meta"]["runtime_s"] = time.time() - t0
return result
def main() -> None:
args = parse_args()
cfg = load_config(args.config)
result = run_case(args.image, args.aorta_mask, cfg)
write_prediction_json(
result["case_id"], result["daughters"], result["excluded_candidates"], result["meta"], args.output,
)
if __name__ == "__main__":
main()