Spaces:
Sleeping

mosta02 commited on
Commit
284eab6
Β·
verified Β·
1 Parent(s): 7af445c

Upload centerline_extraction.py

Browse files
Files changed (1) hide show
  1. centerline_extraction.py +235 -135
centerline_extraction.py CHANGED
@@ -14,6 +14,7 @@ ABDOMEN_LABELS = ['Celiac Trunk', 'Superior Mesenteric', 'Renal', 'Renal']
14
 
15
  MAX_ABDOMEN_BIFURCATIONS = 4 # Maximum number of abdominal bifurcations to identify
16
  CLUSTER_MAX_GAP_MM = 50.0 # Maximum vertical gap (mm) within the abdominal cluster
 
17
  ILIAC_REGION_FRACTION = 0.25 # Bottom fraction of z-range considered iliac
18
  BRANCH_RADIUS_FRACTION = 0.35 # Branches below this radius fraction are noise
19
  REFERENCE_OFFSET_MM = 30.0 # Default reference point placed this many mm above the Celiac trunk
@@ -1464,71 +1465,134 @@ def _bfs_flood_none_segments(segments, point_to_segments):
1464
 
1465
 
1466
  # ══════════════════════════════════════════════════════════════════════
1467
- # SUB-STEP: detect iliac cutoff point
1468
  # ══════════════════════════════════════════════════════════════════════
1469
 
1470
- def _detect_iliac_cutoff(segments, valid_bifs, all_bifurcations, point_to_segments):
1471
- """Find the aortic bifurcation into the iliac legs and relabel any mislabeled
1472
- Aorta segments below it.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1473
 
1474
  Returns ``iliac_cutoff`` dict or ``None``.
1475
-
1476
- Strategy
1477
- --------
1478
- Primary: lowest-Z junction in *valid_bifs* that has both a confirmed-Aorta
1479
- arm AND an Artery arm (the iliac Y after correct labeling).
1480
-
1481
- Fall-back A: lowest-Z junction in valid_bifs with only a confirmed-Aorta arm
1482
- (both iliac legs still mislabeled). The relabeling sweep then fixes them.
1483
-
1484
- Fall-back B: same search over the full *all_bifurcations* list (catches
1485
- injected fork points that produce < 3 direction clusters and are excluded
1486
- from valid_bifs).
1487
  """
1488
- both_cands = []
1489
- aorta_only_cands = []
 
 
 
 
 
 
 
 
 
1490
 
1491
- for bif_id, (bif, connections) in valid_bifs.items():
1492
- seg_indices = [c['seg_idx'] for c in connections]
1493
- has_conf = any(segments[si].get('confirmed_aorta') for si in seg_indices)
1494
- has_art = any(segments[si]['label'] == 'Artery' for si in seg_indices)
1495
- if has_conf and has_art:
1496
- both_cands.append(bif)
1497
- elif has_conf:
1498
- aorta_only_cands.append(bif)
1499
-
1500
- candidates = both_cands if both_cands else aorta_only_cands
1501
-
1502
- if not candidates:
1503
- extra_aorta_only = []
1504
- for bif in all_bifurcations:
1505
- if bif['id'] in valid_bifs:
1506
- continue
1507
- seg_indices = list(point_to_segments.get(bif['id'], []))
1508
- has_conf = any(segments[si].get('confirmed_aorta') for si in seg_indices)
1509
- has_art = any(segments[si]['label'] == 'Artery' for si in seg_indices)
1510
- if has_conf and has_art:
1511
- candidates.append(bif)
1512
- elif has_conf:
1513
- extra_aorta_only.append(bif)
1514
- if not candidates and extra_aorta_only:
1515
- candidates = extra_aorta_only
1516
-
1517
- if not candidates:
1518
  return None
1519
 
1520
- best = min(candidates, key=lambda b: b['z'])
1521
- iliac_cutoff = {
1522
- 'x': float(best['x']), 'y': float(best['y']),
1523
- 'z': float(best['z']), 'radius': float(best['radius']),
1524
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1525
 
1526
- # Relabeling sweep: fix Aorta segments entirely below the cutoff plane
1527
- cutoff_z = iliac_cutoff['z']
1528
- for seg in segments:
1529
- if seg['label'] == 'Aorta' and seg['points']:
1530
- if max(pt['z'] for pt in seg['points']) <= cutoff_z:
1531
- apply_label(seg, 'Artery')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1532
 
1533
  return iliac_cutoff
1534
 
@@ -1540,7 +1604,7 @@ def _detect_iliac_cutoff(segments, valid_bifs, all_bifurcations, point_to_segmen
1540
  def label_aorta_vs_arteries(segments, all_bifurcations, point_to_segments, precomputed_junction_arms_cache=None):
1541
  """Label every segment as 'Aorta' or 'Artery'.
1542
 
1543
- Returns ``(artery_bifs, validated_bif_points, iliac_cutoff, debug_junctions)``.
1544
 
1545
  *debug_junctions* is a list of per-junction dicts usable by the frontend to
1546
  visualise and inspect every labeling decision:
@@ -1551,10 +1615,10 @@ def label_aorta_vs_arteries(segments, all_bifurcations, point_to_segments, preco
1551
  n_keep_raw – n_keep before guards
1552
  n_keep_final – n_keep after guards
1553
  guard – 'none' | 'guard1' | 'guard2' | 'case_d'
1554
- is_iliac_cutoff – True for the chosen iliac Y junction
1555
  """
1556
  if not all_bifurcations:
1557
- return [], [], None, []
1558
 
1559
  # Step 1: reset (segment-level only; per-point labels are no longer used)
1560
  for seg in segments:
@@ -1658,23 +1722,8 @@ def label_aorta_vs_arteries(segments, all_bifurcations, point_to_segments, preco
1658
  # Step 3: BFS fill
1659
  _bfs_flood_none_segments(segments, point_to_segments)
1660
 
1661
- # Step 4: iliac cutoff
1662
- iliac_cutoff = _detect_iliac_cutoff(segments, valid_bifs, all_bifurcations, point_to_segments)
1663
-
1664
- # Mark the chosen junction in debug output
1665
- if iliac_cutoff:
1666
- ic_z = iliac_cutoff['z']
1667
- # Find the debug entry closest to that z (within 1 mm)
1668
- best_match = min(
1669
- debug_junctions,
1670
- key=lambda d: abs(d['z'] - ic_z),
1671
- default=None,
1672
- )
1673
- if best_match and abs(best_match['z'] - ic_z) < 1.0:
1674
- best_match['is_iliac_cutoff'] = True
1675
-
1676
  validated_bif_points = [bif for (bif, _conns) in valid_bifs.values()]
1677
- return _collect_artery_bifurcation_info(segments, valid_bifs), validated_bif_points, iliac_cutoff, debug_junctions
1678
 
1679
 
1680
  def _collect_artery_bifurcation_info(segments, valid_bifs):
@@ -2050,7 +2099,7 @@ def _orient_artery_segments(segments):
2050
  # Build Frontend response JSON
2051
  def build_response(centerlines_vtk, segments, abdomen_bifuractions, reference_point,
2052
  all_bifurcations=None, iliac_cutoff=None, debug_junctions=None,
2053
- has_thoracic=False, has_iliac=False):
2054
  bounds = centerlines_vtk.GetBounds()
2055
 
2056
  # Orient artery segments so points run bifurcation β†’ endpoint.
@@ -2106,75 +2155,118 @@ def build_response(centerlines_vtk, segments, abdomen_bifuractions, reference_po
2106
  'debug_junctions': debug_junctions or [],
2107
  'has_thoracic': has_thoracic,
2108
  'has_iliac': has_iliac,
 
2109
  }
2110
 
2111
 
2112
  def _detect_thoracic(centerlines_vtk):
2113
- """Return True if the dataset contains the thoracic aorta (aortic arch).
2114
 
2115
- Strategy β€” curvature analysis:
2116
- The hallmark of a thoracic scan is the aortic arch: a near-180Β° U-turn
2117
- that produces very high centerline curvature (radius of curvature β‰ˆ 20-40mm
2118
- ↔ curvature β‰ˆ 0.025-0.05 /mm) and that lies in the **superior 30%** of the
 
2119
  scan's Z-extent.
2120
 
2121
- ``vtkvmtkCenterlineGeometry`` (already used elsewhere in the pipeline) is
2122
- invoked here to add a ``Curvature`` point array if one is not present.
2123
- The function is tolerant of any exceptions; on failure it returns False.
 
 
 
 
 
 
 
 
 
 
 
 
 
2124
  """
 
 
2125
  try:
2126
- # Compute geometry on the fly if Curvature array is absent
2127
- curvature_array = centerlines_vtk.GetPointData().GetArray("Curvature")
2128
- if curvature_array is not None:
2129
- pts = centerlines_vtk.GetPoints()
2130
- else:
2131
- geom = vtkvmtk.vtkvmtkCenterlineGeometry()
2132
- geom.SetInputData(centerlines_vtk)
2133
- geom.SetLengthArrayName("Length")
2134
- geom.SetCurvatureArrayName("Curvature")
2135
- geom.SetTorsionArrayName("Torsion")
2136
- geom.SetTortuosityArrayName("Tortuosity")
2137
- geom.SetFrenetTangentArrayName("FrenetTangent")
2138
- geom.SetFrenetNormalArrayName("FrenetNormal")
2139
- geom.SetFrenetBinormalArrayName("FrenetBinormal")
2140
- geom.Update()
2141
- geom_out = geom.GetOutput()
2142
- curvature_array = geom_out.GetPointData().GetArray("Curvature")
2143
- pts = geom_out.GetPoints()
2144
-
2145
- if curvature_array is None or pts is None:
2146
- return False
2147
-
2148
- n_pts = pts.GetNumberOfPoints()
2149
- if n_pts == 0:
2150
- return False
2151
-
2152
- z_coords = [pts.GetPoint(i)[2] for i in range(n_pts)]
2153
- z_min, z_max = min(z_coords), max(z_coords)
2154
- z_range = z_max - z_min
2155
-
2156
- # Need at least 100mm of z-range to have a meaningful thoracic region
2157
  if z_range < 100.0:
2158
- return False
 
 
2159
 
2160
- # Only inspect points in the top 30% to target the arch region
2161
- z_arch_start = z_min + 0.70 * z_range
2162
 
2163
- # Curvature threshold: radius of curvature < 50 mm β†’ ΞΊ > 0.02 /mm
2164
- # The aortic arch typically has RoC = 20–40 mm (ΞΊ = 0.025–0.05 /mm).
2165
- # Straight abdominal aorta has ΞΊ < 0.005 /mm even with mild tortuous anatomy.
2166
- CURVATURE_THRESHOLD = 0.05
2167
 
2168
- for i in range(n_pts):
2169
- if z_coords[i] >= z_arch_start:
2170
- if curvature_array.GetValue(i) > CURVATURE_THRESHOLD:
2171
- return True
2172
 
2173
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2174
 
2175
  except Exception as e:
2176
- print(f" Thoracic arch detection error (non-fatal): {e}")
2177
- return False
2178
 
2179
 
2180
  # Main Pipeline for extracting centerline data, labeling bifurcations and arteries, computing ostium and reference point positions
@@ -2227,16 +2319,23 @@ def extract_centerline_data(centerlines, branch_junctions=None):
2227
  print(f" Bifurcations total={len(all_bifurcations)}, "
2228
  f"real branch points (3+ clusters)={len(junction_arms_cache)}")
2229
 
2230
- # Label Aorta vs Artery at every validated bifurcation; also detects iliac cutoff.
2231
- artery_bifs, validated_bifs, iliac_cutoff, debug_junctions = label_aorta_vs_arteries(
2232
  segments, all_bifurcations, point_to_segments,
2233
  precomputed_junction_arms_cache=junction_arms_cache)
2234
 
 
 
 
 
 
 
 
 
 
2235
  print(f" iliac_cutoff={'FOUND at z='+str(round(iliac_cutoff['z'],1)) if iliac_cutoff else 'not detected'}")
2236
 
2237
- has_iliac = iliac_cutoff is not None
2238
- has_thoracic = _detect_thoracic(centerlines)
2239
- print(f" has_thoracic={has_thoracic}")
2240
 
2241
  # Reference point: iliac cutoff if detected, otherwise aorta centroid
2242
  reference_point = compute_reference_point(segments, iliac_cutoff)
@@ -2247,7 +2346,8 @@ def extract_centerline_data(centerlines, branch_junctions=None):
2247
  response = build_response(centerlines, segments, artery_bifs, reference_point,
2248
  junction_points, iliac_cutoff=iliac_cutoff,
2249
  debug_junctions=debug_junctions,
2250
- has_thoracic=has_thoracic, has_iliac=has_iliac)
 
2251
  return response
2252
 
2253
 
 
14
 
15
  MAX_ABDOMEN_BIFURCATIONS = 4 # Maximum number of abdominal bifurcations to identify
16
  CLUSTER_MAX_GAP_MM = 50.0 # Maximum vertical gap (mm) within the abdominal cluster
17
+ THORACIC_GAP_MM = 80.0 # Minimum gap (mm) separating the thoracic artery cluster from the abdominal cluster
18
  ILIAC_REGION_FRACTION = 0.25 # Bottom fraction of z-range considered iliac
19
  BRANCH_RADIUS_FRACTION = 0.35 # Branches below this radius fraction are noise
20
  REFERENCE_OFFSET_MM = 30.0 # Default reference point placed this many mm above the Celiac trunk
 
1465
 
1466
 
1467
  # ══════════════════════════════════════════════════════════════════════
1468
+ # SUB-STEP: classify artery junctions into thoracic / abdomen / iliac zones
1469
  # ══════════════════════════════════════════════════════════════════════
1470
 
1471
+ def _classify_arteries_by_zone(debug_junctions, segments, has_thoracic):
1472
+ """Classify artery junctions into thoracic / abdomen zones, determine the
1473
+ iliac cutoff, and relabel segments accordingly.
1474
+
1475
+ Algorithm
1476
+ ---------
1477
+ 1. Filter ``debug_junctions`` to those with at least one 'Artery' arm.
1478
+ 2. Sort descending by Z (superior β†’ inferior).
1479
+ 3. Compute ``gap_to_next_mm`` for each (Z spacing to the next artery junction).
1480
+ 4. If ``has_thoracic``:
1481
+ - Walk downward collecting thoracic junctions until gap β‰₯ THORACIC_GAP_MM.
1482
+ - Continue collecting abdomen junctions (≀ MAX_ABDOMEN_BIFURCATIONS) until
1483
+ gap β‰₯ CLUSTER_MAX_GAP_MM.
1484
+ If NOT ``has_thoracic``:
1485
+ - Collect abdomen junctions from the top (≀ MAX_ABDOMEN_BIFURCATIONS) until
1486
+ gap β‰₯ CLUSTER_MAX_GAP_MM.
1487
+ 5. Last abdomen junction β†’ iliac cutoff.
1488
+ 6. Annotate each debug_junction with ``artery_type`` ('thoracic'/'abdomen'/'iliac'/None),
1489
+ ``gap_to_next_mm``, and ``is_iliac_cutoff``.
1490
+ 7. Relabel segments:
1491
+ - 'Artery' with max_z ≀ iliac_cutoff_z β†’ 'Left Iliac Artery' / 'Right Iliac Artery'
1492
+ - 'Artery' with avg_z above the thoracic boundary β†’ 'Thoracic Artery' (if has_thoracic)
1493
 
1494
  Returns ``iliac_cutoff`` dict or ``None``.
 
 
 
 
 
 
 
 
 
 
 
 
1495
  """
1496
+ # Initialise per-junction fields (reset any legacy values from earlier steps)
1497
+ for j in debug_junctions:
1498
+ j['artery_type'] = None
1499
+ j['gap_to_next_mm'] = None
1500
+ j['is_iliac_cutoff'] = False
1501
+
1502
+ # Artery junctions: those where at least one arm ended up labelled 'Artery'
1503
+ artery_idxs = [
1504
+ i for i, j in enumerate(debug_junctions)
1505
+ if 'Artery' in (j.get('arm_labels_after') or [])
1506
+ ]
1507
 
1508
+ if not artery_idxs:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1509
  return None
1510
 
1511
+ # Sort descending by Z (highest = most superior)
1512
+ artery_idxs.sort(key=lambda i: debug_junctions[i]['z'], reverse=True)
1513
+
1514
+ # Compute Z-gap to the next artery junction below each one
1515
+ for k, idx in enumerate(artery_idxs):
1516
+ if k + 1 < len(artery_idxs):
1517
+ nxt_idx = artery_idxs[k + 1]
1518
+ gap = debug_junctions[idx]['z'] - debug_junctions[nxt_idx]['z']
1519
+ debug_junctions[idx]['gap_to_next_mm'] = round(gap, 1)
1520
+ # else: last junction has no successor β†’ gap_to_next_mm stays None
1521
+
1522
+ # ── zone classification ────────────────────────────────────────────
1523
+ thoracic_zone = [] # debug_junction indices classified as thoracic
1524
+ abdomen_zone = [] # debug_junction indices classified as abdomen
1525
+ ptr = 0
1526
+ n = len(artery_idxs)
1527
+
1528
+ if has_thoracic:
1529
+ # Phase 1: collect thoracic junctions until a big gap (or end of list)
1530
+ while ptr < n:
1531
+ idx = artery_idxs[ptr]
1532
+ thoracic_zone.append(idx)
1533
+ gap = debug_junctions[idx]['gap_to_next_mm']
1534
+ ptr += 1
1535
+ if gap is None or gap >= THORACIC_GAP_MM:
1536
+ break # thoracic-abdomen gap found
1537
+
1538
+ # Phase 2 (always): collect abdomen junctions after the thoracic cluster
1539
+ while ptr < n and len(abdomen_zone) < MAX_ABDOMEN_BIFURCATIONS:
1540
+ idx = artery_idxs[ptr]
1541
+ abdomen_zone.append(idx)
1542
+ gap = debug_junctions[idx]['gap_to_next_mm']
1543
+ ptr += 1
1544
+ if gap is None or gap >= CLUSTER_MAX_GAP_MM:
1545
+ break # abdomen cluster ends here
1546
+
1547
+ # ── annotate debug_junctions ──────────────────────────────────────
1548
+ for idx in thoracic_zone:
1549
+ debug_junctions[idx]['artery_type'] = 'thoracic'
1550
+ for idx in abdomen_zone:
1551
+ debug_junctions[idx]['artery_type'] = 'abdomen'
1552
+
1553
+ # ── iliac cutoff = last abdomen junction ──────────────────────────
1554
+ iliac_cutoff = None
1555
+ if abdomen_zone:
1556
+ last_idx = abdomen_zone[-1]
1557
+ lj = debug_junctions[last_idx]
1558
+ debug_junctions[last_idx]['is_iliac_cutoff'] = True
1559
+ iliac_cutoff = {
1560
+ 'x': float(lj['x']), 'y': float(lj['y']),
1561
+ 'z': float(lj['z']), 'radius': float(lj['radius']),
1562
+ }
1563
+
1564
+ # Mark remaining junctions below the cutoff as 'iliac' type
1565
+ if iliac_cutoff:
1566
+ cutoff_z = iliac_cutoff['z']
1567
+ for j in debug_junctions:
1568
+ if j['artery_type'] is None and j['z'] < cutoff_z:
1569
+ j['artery_type'] = 'iliac'
1570
 
1571
+ # ── relabel segments ──────────────────────────────────────────────
1572
+ # Iliac: 'Artery' segments that lie entirely below the iliac cutoff Z
1573
+ if iliac_cutoff:
1574
+ cutoff_z = iliac_cutoff['z']
1575
+ for seg in segments:
1576
+ if seg.get('label') == 'Artery' and seg.get('points'):
1577
+ if max(pt['z'] for pt in seg['points']) <= cutoff_z:
1578
+ avg_x = sum(pt['x'] for pt in seg['points']) / len(seg['points'])
1579
+ apply_label(seg, 'Left Iliac Artery' if avg_x > 0 else 'Right Iliac Artery')
1580
+
1581
+ # Thoracic: 'Artery' segments whose average Z sits above the midpoint of the
1582
+ # thoracic-abdomen gap (reliable because the gap is β‰₯ THORACIC_GAP_MM)
1583
+ if has_thoracic and thoracic_zone:
1584
+ if abdomen_zone:
1585
+ z_min_thoracic = min(debug_junctions[i]['z'] for i in thoracic_zone)
1586
+ z_max_abdomen = max(debug_junctions[i]['z'] for i in abdomen_zone)
1587
+ z_boundary = (z_min_thoracic + z_max_abdomen) / 2.0
1588
+ else:
1589
+ z_min_thoracic = min(debug_junctions[i]['z'] for i in thoracic_zone)
1590
+ z_boundary = z_min_thoracic - 20.0 # fallback: 20 mm below lowest thoracic junction
1591
+ for seg in segments:
1592
+ if seg.get('label') == 'Artery' and seg.get('points'):
1593
+ avg_z = sum(pt['z'] for pt in seg['points']) / len(seg['points'])
1594
+ if avg_z > z_boundary:
1595
+ apply_label(seg, 'Thoracic Artery')
1596
 
1597
  return iliac_cutoff
1598
 
 
1604
  def label_aorta_vs_arteries(segments, all_bifurcations, point_to_segments, precomputed_junction_arms_cache=None):
1605
  """Label every segment as 'Aorta' or 'Artery'.
1606
 
1607
+ Returns ``(artery_bifs, validated_bif_points, debug_junctions)``.
1608
 
1609
  *debug_junctions* is a list of per-junction dicts usable by the frontend to
1610
  visualise and inspect every labeling decision:
 
1615
  n_keep_raw – n_keep before guards
1616
  n_keep_final – n_keep after guards
1617
  guard – 'none' | 'guard1' | 'guard2' | 'case_d'
1618
+ is_iliac_cutoff – set after zone classification by _classify_arteries_by_zone
1619
  """
1620
  if not all_bifurcations:
1621
+ return [], [], []
1622
 
1623
  # Step 1: reset (segment-level only; per-point labels are no longer used)
1624
  for seg in segments:
 
1722
  # Step 3: BFS fill
1723
  _bfs_flood_none_segments(segments, point_to_segments)
1724
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1725
  validated_bif_points = [bif for (bif, _conns) in valid_bifs.values()]
1726
+ return _collect_artery_bifurcation_info(segments, valid_bifs), validated_bif_points, debug_junctions
1727
 
1728
 
1729
  def _collect_artery_bifurcation_info(segments, valid_bifs):
 
2099
  # Build Frontend response JSON
2100
  def build_response(centerlines_vtk, segments, abdomen_bifuractions, reference_point,
2101
  all_bifurcations=None, iliac_cutoff=None, debug_junctions=None,
2102
+ has_thoracic=False, has_iliac=False, thoracic_info=None):
2103
  bounds = centerlines_vtk.GetBounds()
2104
 
2105
  # Orient artery segments so points run bifurcation β†’ endpoint.
 
2155
  'debug_junctions': debug_junctions or [],
2156
  'has_thoracic': has_thoracic,
2157
  'has_iliac': has_iliac,
2158
+ 'thoracic_info': thoracic_info,
2159
  }
2160
 
2161
 
2162
  def _detect_thoracic(centerlines_vtk):
2163
+ """Detect if the dataset contains the thoracic aorta (aortic arch).
2164
 
2165
+ Strategy β€” Z-direction reversal per centerline cell:
2166
+ The hallmark of the aortic arch is a near-180Β° U-turn in the superior
2167
+ portion of the scan. This manifests as a Z-reversal: along a single
2168
+ centerline cell the Z-coordinate first *increases* (ascending aorta) then
2169
+ *decreases* (descending aorta), or vice-versa, within the top 30% of the
2170
  scan's Z-extent.
2171
 
2172
+ For abdominal-only scans the centerline is nearly monotone in Z β€” no
2173
+ reversal occurs. This criterion is robust against noisy VMTK curvature
2174
+ spikes that would mislead a magnitude threshold.
2175
+
2176
+ Parameters
2177
+ ----------
2178
+ MIN_ARCH_SPAN_MM : minimum Z-span of the reversal region to avoid
2179
+ miscounting tiny wiggles as arches (~40 mm).
2180
+ TOP_FRACTION : fraction of z-range to treat as the "arch zone".
2181
+
2182
+ Returns
2183
+ -------
2184
+ dict with keys:
2185
+ detected : bool β€” True if thoracic aorta detected
2186
+ reversal_mm : float β€” largest Z-reversal found in the arch zone (mm)
2187
+ arch_zone_z : float β€” Z threshold below which the arch zone begins
2188
  """
2189
+ import sys as _sys
2190
+ _null = {'detected': False, 'reversal_mm': 0.0, 'arch_zone_z': 0.0}
2191
  try:
2192
+ pts = centerlines_vtk.GetPoints()
2193
+ if pts is None or pts.GetNumberOfPoints() == 0:
2194
+ return _null
2195
+
2196
+ n_pts = pts.GetNumberOfPoints()
2197
+ z_all = [pts.GetPoint(i)[2] for i in range(n_pts)]
2198
+ z_min = min(z_all)
2199
+ z_max = max(z_all)
2200
+ z_range = z_max - z_min
2201
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2202
  if z_range < 100.0:
2203
+ print(f" [thoracic diag] z_range={z_range:.1f}mm < 100mm β†’ no thoracic",
2204
+ file=_sys.stderr)
2205
+ return _null
2206
 
2207
+ TOP_FRACTION = 0.30 # inspect top 30% of Z extent
2208
+ MIN_ARCH_SPAN_MM = 40.0 # reversal must span >= 40 mm
2209
 
2210
+ z_arch_start = z_max - TOP_FRACTION * z_range # upper 30%
 
 
 
2211
 
2212
+ n_cells = centerlines_vtk.GetNumberOfCells()
2213
+ best_reversal = 0.0 # diagnostic: largest confirmed reversal found
 
 
2214
 
2215
+ for cell_idx in range(n_cells):
2216
+ cell = centerlines_vtk.GetCell(cell_idx)
2217
+ cell_pts = cell.GetPoints()
2218
+ if cell_pts is None:
2219
+ continue
2220
+ n_cell = cell_pts.GetNumberOfPoints()
2221
+
2222
+ # Extract Z of points that lie inside the arch zone
2223
+ arch_z = [cell_pts.GetPoint(j)[2] for j in range(n_cell)
2224
+ if cell_pts.GetPoint(j)[2] >= z_arch_start]
2225
+
2226
+ if len(arch_z) < 4:
2227
+ continue
2228
+
2229
+ peak_z = max(arch_z)
2230
+ trough_z = min(arch_z)
2231
+
2232
+ # Case 1: dome (ascending β†’ arch peak β†’ descending)
2233
+ dome_span = min(peak_z - arch_z[0], peak_z - arch_z[-1])
2234
+ # Case 2: inverse dome (descending β†’ bottom β†’ ascending)
2235
+ inv_span = min(arch_z[0] - trough_z, arch_z[-1] - trough_z)
2236
+
2237
+ reversal = max(dome_span, inv_span)
2238
+ if reversal > best_reversal:
2239
+ best_reversal = reversal
2240
+
2241
+ if reversal >= MIN_ARCH_SPAN_MM:
2242
+ print(
2243
+ f" [thoracic diag] z_range={z_range:.1f}mm "
2244
+ f"arch_zone z>={z_arch_start:.1f} "
2245
+ f"cell={cell_idx} arch_pts={len(arch_z)} "
2246
+ f"reversal={reversal:.1f}mm >= {MIN_ARCH_SPAN_MM}mm => THORACIC DETECTED",
2247
+ file=_sys.stderr
2248
+ )
2249
+ return {
2250
+ 'detected': True,
2251
+ 'reversal_mm': round(reversal, 1),
2252
+ 'arch_zone_z': round(z_arch_start, 1),
2253
+ }
2254
+
2255
+ print(
2256
+ f" [thoracic diag] z_range={z_range:.1f}mm "
2257
+ f"arch_zone z>={z_arch_start:.1f} best_reversal={best_reversal:.1f}mm "
2258
+ f"< {MIN_ARCH_SPAN_MM}mm => no thoracic",
2259
+ file=_sys.stderr
2260
+ )
2261
+ return {
2262
+ 'detected': False,
2263
+ 'reversal_mm': round(best_reversal, 1),
2264
+ 'arch_zone_z': round(z_arch_start, 1),
2265
+ }
2266
 
2267
  except Exception as e:
2268
+ print(f" Thoracic arch detection error (non-fatal): {e}", file=_sys.stderr)
2269
+ return _null
2270
 
2271
 
2272
  # Main Pipeline for extracting centerline data, labeling bifurcations and arteries, computing ostium and reference point positions
 
2319
  print(f" Bifurcations total={len(all_bifurcations)}, "
2320
  f"real branch points (3+ clusters)={len(junction_arms_cache)}")
2321
 
2322
+ # Label Aorta vs Artery at every validated bifurcation.
2323
+ artery_bifs, validated_bifs, debug_junctions = label_aorta_vs_arteries(
2324
  segments, all_bifurcations, point_to_segments,
2325
  precomputed_junction_arms_cache=junction_arms_cache)
2326
 
2327
+ # Detect thoracic arch (Z-reversal); returns a dict with 'detected', 'reversal_mm', 'arch_zone_z'
2328
+ thoracic_result = _detect_thoracic(centerlines)
2329
+ has_thoracic = thoracic_result['detected']
2330
+ print(f" has_thoracic={has_thoracic} reversal_mm={thoracic_result['reversal_mm']}")
2331
+
2332
+ # Classify artery junctions into thoracic / abdomen zones, determine iliac cutoff,
2333
+ # annotate debug_junctions, and relabel segments (Thoracic Artery / Iliac Artery).
2334
+ iliac_cutoff = _classify_arteries_by_zone(debug_junctions, segments, has_thoracic)
2335
+
2336
  print(f" iliac_cutoff={'FOUND at z='+str(round(iliac_cutoff['z'],1)) if iliac_cutoff else 'not detected'}")
2337
 
2338
+ has_iliac = iliac_cutoff is not None
 
 
2339
 
2340
  # Reference point: iliac cutoff if detected, otherwise aorta centroid
2341
  reference_point = compute_reference_point(segments, iliac_cutoff)
 
2346
  response = build_response(centerlines, segments, artery_bifs, reference_point,
2347
  junction_points, iliac_cutoff=iliac_cutoff,
2348
  debug_junctions=debug_junctions,
2349
+ has_thoracic=has_thoracic, has_iliac=has_iliac,
2350
+ thoracic_info=thoracic_result)
2351
  return response
2352
 
2353