From 478a7a9f0f9f1e26a757e9cbb280e7543a941ea0 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Fri, 12 Jun 2026 16:32:41 +0100 Subject: [PATCH 01/11] Add LV histogram by AHA segment (wip) Function runs from analysis_histograms_aha.py Possible issues with aligning reader and mask --- src/cardiotensor/analysis/analysis_utils.py | 2580 +++++++++++++++++ .../scripts/analysis_histograms_aha.py | 183 ++ 2 files changed, 2763 insertions(+) create mode 100644 src/cardiotensor/analysis/analysis_utils.py create mode 100644 src/cardiotensor/scripts/analysis_histograms_aha.py diff --git a/src/cardiotensor/analysis/analysis_utils.py b/src/cardiotensor/analysis/analysis_utils.py new file mode 100644 index 00000000..58dde3d0 --- /dev/null +++ b/src/cardiotensor/analysis/analysis_utils.py @@ -0,0 +1,2580 @@ +# -*- coding: utf-8 -*- +""" +Created on Fri Dec 12 11:37:23 2025 + +@author: A Cook +""" + + +import os + +import numpy as np +from PIL import Image +import matplotlib.pyplot as plt + + +import cv2 + +from matplotlib.patches import Wedge + +from scipy.stats import circmean, circstd +from scipy.ndimage import gaussian_filter1d +from scipy.optimize import curve_fit +from scipy import ndimage as ndi +from scipy.ndimage import map_coordinates + +from skimage import measure +from skimage.morphology import remove_small_objects, remove_small_holes, closing, opening, disk, erosion +from skimage.io import imread +from skimage import exposure + +from astropy import stats + +from sklearn.metrics import r2_score + + +def get_septum_point(lv_mask): + """ + Manually select a septum point from an LV mask. + + Parameters + ---------- + lv_mask : str + Directory containing LV mask slices. + + Returns + ------- + np.ndarray + Septum point as (z, y, x). + """ + + # Load volume + files = sorted( + f for f in os.listdir(lv_mask) + if f.lower().endswith((".tif", ".tiff", ".jp2")) + ) + + if not files: + raise ValueError("Directory contains no TIFF or JP2 images") + + slices = [] + for f in files: + img = Image.open(os.path.join(lv_mask, f)) + slices.append(np.array(img)) + + vol = np.stack(slices, axis=0) + + # Find slice with largest LV area + zsum = vol.sum(axis=(1, 2)) + mid = int(np.argmax(zsum)) + + # Display slice and collect click + clicked = [] + + fig, ax = plt.subplots(figsize=(6, 6)) + ax.imshow(vol[mid], cmap="gray") + ax.set_title( + f"Click once on the septum (slice {mid})" + ) + + def onclick(event): + if event.xdata is None or event.ydata is None: + return + + clicked.append( + np.array([ + mid, + int(round(event.ydata)), + int(round(event.xdata)) + ]) + ) + + plt.close(fig) + + fig.canvas.mpl_connect("button_press_event", onclick) + plt.show() + + if not clicked: + raise RuntimeError("No click recorded") + + return clicked[0] + + +def load_volume(img_dir): + #Load TIFF/JP2 stack into 3D numpy array + files = sorted([f for f in os.listdir(img_dir) if f.lower().endswith(('.tif','.tiff','.jp2'))]) + if not files: + raise ValueError(f"No images found in {img_dir}") + slices = [] + for f in files: + img = Image.open(os.path.join(img_dir, f)) + slices.append(np.array(img)) + vol = np.stack(slices, axis=0) + return vol + + +def create_aha_mask( + lv_mask_path, + axis_points, + septum_point, + images_path, + aha_factor, + return_radial_map=False, +): + """ + Create a 17-segment AHA mask from an LV mask. + + Parameters + ---------- + lv_mask_path : str + Path to LV mask volume. + axis_points : list + [MV_point, Apex_point] from config file. + septum_point : array-like + Septum reference point. + images_path : str + Path to image stack (used to determine downsampling). + aha_factor : float + AHA scaling factor. + return_radial_map : bool, optional + If True, also returns the radial subdivision map. + + Returns + ------- + segment_map : ndarray + 17-segment AHA mask. + segment_radial_map : ndarray, optional + Segment map with radial quartiles encoded as seg*10 + radial_group. + """ + + # -------------------------------------------------- + # Determine downsampling + # -------------------------------------------------- + files_lv = sorted( + f for f in os.listdir(lv_mask_path) + if f.lower().endswith((".tif", ".tiff", ".jp2")) + ) + files_img = sorted( + f for f in os.listdir(images_path) + if f.lower().endswith((".tif", ".tiff", ".jp2")) + ) + + # Avoid zero division or zero scaling when image and mask slice counts differ greatly. + # Compute ratio and ensure integer scaling factor >= 1 + mask_ratio = float(len(files_img)) / max(1, float(len(files_lv))) + mask_factor = max(1, int(round(mask_ratio))) + + # Compute downsample as aha_factor / mask_factor, at least 1 + try: + downsample = int(max(1, round(float(aha_factor) / float(mask_factor)))) + except Exception: + downsample = 1 + + # -------------------------------------------------- + # Load and resample LV mask + # -------------------------------------------------- + lv_mask_vol = load_volume(lv_mask_path) + lv_mask_vol_d = resample( + lv_mask_vol, + zoom=1 / downsample, + order=0, + ) + + # -------------------------------------------------- + # Long-axis definition + # -------------------------------------------------- + MV_d = np.array(axis_points[0])[::-1] / aha_factor + Apex_d = np.array(axis_points[1])[::-1] / aha_factor + + axis_vec = MV_d - Apex_d + axis_vec /= np.linalg.norm(axis_vec) + + coords = np.array(np.nonzero(lv_mask_vol_d)).T + centroid = (MV_d + Apex_d) / 2 + + septum_point = np.asarray(septum_point) + + # -------------------------------------------------- + # Long-axis projections + # -------------------------------------------------- + projections = coords @ axis_vec + + # Discard extreme percentiles to guard againts noise and outliers in the mask + pmin = np.percentile(projections, 2) + pmax = np.percentile(projections, 98) + length = pmax - pmin + + basal_thresh = pmin + 2 * length / 3.0 + mid_thresh = pmin + length / 3.0 + + # -------------------------------------------------- + # Septum reference angle + # -------------------------------------------------- + septum_vec = septum_point - centroid + + pts2d, u, v = project_to_plane( + coords, + centroid, + axis_vec, + ) + + septum_point2d = np.array([ + np.dot(septum_vec, u), + np.dot(septum_vec, v) + ]) + + ref_angle = np.arctan2( + septum_point2d[1], + septum_point2d[0] + ) + + angles = np.arctan2(pts2d[:, 1], pts2d[:, 0]) + + angles_rel = (angles - ref_angle) % (2 * np.pi) + angles_rel = (angles_rel + 2 * np.pi / 3) % (2 * np.pi) + + # -------------------------------------------------- + # Create segment map + # -------------------------------------------------- + segment_map = np.zeros( + lv_mask_vol_d.shape, + dtype=np.uint16 + ) + + def assign_segment(mask_idx, seg): + segment_map[tuple(coords[mask_idx].T)] = seg + + basal_idx = np.where(projections >= basal_thresh)[0] + + mid_idx = np.where( + (projections >= mid_thresh) & + (projections < basal_thresh) + )[0] + + apical_idx = np.where( + (projections < mid_thresh) & + (projections >= pmin + 0.02 * length) + )[0] + + apex_idx = np.where( + projections < (pmin + 0.02 * length) + )[0] + + def sectors_from_indices(indices, n_sectors, start_seg): + sector_width = 2 * np.pi / n_sectors + + for s in range(n_sectors): + a0 = s * sector_width + a1 = (s + 1) * sector_width + + mask_idx = indices[ + (angles_rel[indices] >= a0) & + (angles_rel[indices] < a1) + ] + + assign_segment(mask_idx, start_seg + s) + + # Basal: 1–6 + sectors_from_indices(basal_idx, 6, 1) + + # Mid: 7–12 + sectors_from_indices(mid_idx, 6, 7) + + # Apical: 13–16 + sector_width = 2 * np.pi / 4 + + for s in range(4): + a0 = s * sector_width + a1 = (s + 1) * sector_width + + mask_idx = apical_idx[ + (angles_rel[apical_idx] >= a0) & + (angles_rel[apical_idx] < a1) + ] + + assign_segment(mask_idx, 13 + s) + + # Apex: 17 + if apex_idx.size > 0: + assign_segment(apex_idx, 17) + + if not return_radial_map: + return segment_map + + # -------------------------------------------------- + # Radial quartile subdivision + # -------------------------------------------------- + dists = np.linalg.norm(coords - centroid, axis=1) + + segment_radial_map = np.zeros_like( + segment_map, + dtype=np.uint16 + ) + + for seg_id in range(1, 18): + + seg_idx = np.where( + segment_map[tuple(coords.T)] == seg_id + )[0] + + if len(seg_idx) == 0: + continue + + seg_dists = dists[seg_idx] + + q25, q50, q75 = np.percentile( + seg_dists, + [25, 50, 75] + ) + + for voxel_idx, d in zip(seg_idx, seg_dists): + + if d <= q25: + radial_group = 1 + elif d <= q50: + radial_group = 2 + elif d <= q75: + radial_group = 3 + else: + radial_group = 4 + + segment_radial_map[ + tuple(coords[voxel_idx]) + ] = seg_id * 10 + radial_group + + return segment_map, segment_radial_map + +def resample( + vol, + target_shape=None, + zoom=None, + order=0, + TwoD=False, + is_mask=False +): + """ + Resample 2D or 3D volume. + + Parameters + ---------- + vol : ndarray + Input array. + target_shape : tuple, optional + Desired output shape. + zoom : float or tuple, optional + Zoom factor(s). + order : int + Interpolation order (ignored for masks). + TwoD : bool + If True, treat input as 2D. + is_mask : bool + If True, use nearest-neighbour mask-safe resampling. + + Returns + ------- + ndarray + Resampled volume. + """ + dtype = vol.dtype + vol = np.asarray(vol).astype(dtype) + + # ------------------ Determine zoom factors ------------------ + if TwoD: + if target_shape is not None: + zoom_factors = ( + target_shape[0] / vol.shape[0], + target_shape[1] / vol.shape[1] + ) + elif zoom is not None: + zoom_factors = (zoom, zoom) + else: + raise ValueError("resample requires target_shape or zoom") + else: + if target_shape is not None: + zoom_factors = ( + target_shape[0] / vol.shape[0], + target_shape[1] / vol.shape[1], + target_shape[2] / vol.shape[2] + ) + elif zoom is not None: + zoom_factors = (zoom, zoom, zoom) + else: + raise ValueError("resample requires target_shape or zoom") + + # ------------------ MASK SAFE PATH ------------------ + if is_mask: + if not TwoD: + raise ValueError("Mask resampling currently supports 2D only") + + new_h = int(round(vol.shape[0] * zoom_factors[0])) + new_w = int(round(vol.shape[1] * zoom_factors[1])) + + res = cv2.resize( + vol, + (new_w, new_h), + interpolation=cv2.INTER_NEAREST + ) + + return res.astype(vol.dtype) + + # ------------------ IMAGE PATH ------------------ + #vol = vol.astype(np.float32) + vol = vol.astype(dtype) + return ndi.zoom(vol, zoom_factors, order=order) + + + + +def project_to_plane(points, origin, normal): + #Project 3D points to plane defined by two vectors. Returns 2D coordinates in plane basis. + + # build orthonormal basis u,v for plane + normal = normal / np.linalg.norm(normal) + + # choose arbitrary vector not parallel to normal + arbitrary = np.array([1.0,0.0,0.0]) + if np.allclose(np.abs(np.dot(arbitrary, normal)), 1.0, atol=1e-3): + arbitrary = np.array([0.0,1.0,0.0]) + u = np.cross(normal, arbitrary) + u = u / np.linalg.norm(u) + v = np.cross(normal, u) + v = v / np.linalg.norm(v) + rel = points - origin + x = rel @ u + y = rel @ v + return np.column_stack([x, y]), u, v + + +def newAxes(vector1, vector2=None): + vector1 = np.asarray(vector1, dtype=float) + vector1 /= np.linalg.norm(vector1) + + if vector2 is None: + # Choose a safe arbitrary axis + if abs(vector1[1]) < 0.9: + tmp = np.array([0, 1, 0]) + else: + tmp = np.array([1, 0, 0]) + + perp1 = np.cross(vector1, tmp) + else: + perp1 = np.asarray(vector2, dtype=float) + + perp1 /= np.linalg.norm(perp1) + + perp2 = np.cross(vector1, perp1) + perp2 /= np.linalg.norm(perp2) + + return vector1, perp1, perp2 + + + +def newDimensions(vector, dimensions): + depth, height, width = dimensions + + # Compute perpendicular axes + yax = np.array([0, 1, 0]) + perp1 = np.cross(vector, yax) + perp1 /= np.linalg.norm(perp1) + perp2 = np.cross(vector, perp1) + perp2 /= np.linalg.norm(perp2) + + # Original volume corners (z, y, x) + corners = np.array([ + [0, 0, 0], + [0, 0, width], + [0, height, 0], + [0, height, width], + [depth, 0, 0], + [depth, 0, width], + [depth, height, 0], + [depth, height, width] + ]) + + # Center the volume + centre = np.array([depth // 2, height // 2, width // 2]) + shifted = corners - centre # shape (8, 3) + + # Project into new coordinate system + new_coords = np.dot(shifted, np.vstack([vector, perp2, perp1]).T) # shape (8, 3) + + # Find bounding box in new coordinates + mins = np.min(new_coords, axis=0) + maxs = np.max(new_coords, axis=0) + sizes = maxs - mins + + # Output dimensions: depth, height, width + out_d = int(np.ceil(sizes[0])) + out_h = int(np.ceil(sizes[1])) + out_w = int(np.ceil(sizes[2])) + + print(out_d, out_h, out_w) + return np.array([out_d, out_h, out_w]) + + + +def stackSubset(folder, index, vector): + # Open the first file in the folder to work out the dimensions + files = sorted([f for f in os.listdir(folder) if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff'))]) + im = imread(os.path.join(folder, files[0]))# + depth = len(files) + height, width = im.shape + dimensions = [depth, height, width] + newDims = newDimensions(vector, dimensions) + + # Work out size of subset required + rang = newDims[0] - dimensions[0] + + half = int(round(rang / 1.2)) + + p1 = index - half + p2 = index + half + + start = min(p1, p2) + end = max(p1, p2) + + # clamp to valid index range + start = max(start, 0) + end = min(end, len(files) - 1) + + print(start, end) + print(rang) + + # Open necessary images + stack = [imread(os.path.join(folder, f)) for f in files[start:end]] + stack = np.stack(stack, axis=0) + print('Stack loaded') + + return stack, dimensions, newDims + + + +def getRange(folder, index, vector): + # Open the first file in the folder to work out the dimensions + files = sorted([f for f in os.listdir(folder) if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff'))]) + im = imread(os.path.join(folder, files[0]))# + depth = len(files) + height, width = im.shape + dimensions = [depth, height, width] + newDims = newDimensions(vector, dimensions) + + # Work out size of subset required + rang = newDims[0] - dimensions[0] + + half = int(round(rang / 1.2)) + + p1 = index - half + p2 = index + half + + start = min(p1, p2) + end = max(p1, p2) + + + print(start, end) + print(rang) + + # Open necessary images + stack = [imread(os.path.join(folder, f)) for f in files[start:end]] + stack = np.stack(stack, axis=0) + print('Stack loaded') + + return np.array([start, end]), dimensions, newDims + + + + +def ResliceOneSlice(vector, c_new, in_folder=None, stack=None): + """ + Reslice an oblique slice through a given 3D point c_new (z, y, x), + loading only a Z-subset where possible. + """ + + # --- build slice frame --- + n, perp1, perp2 = newAxes(vector) + + if in_folder is not None: + + # --- load one image to get volume shape --- + files = sorted( + f for f in os.listdir(in_folder) + if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff')) + ) + im0 = imread(os.path.join(in_folder, files[0])) + depth = len(files) + height, width = im0.shape + dimensions = [depth, height, width] + + # --- output slice size --- + out_d, out_h, out_w = newDimensions(n, dimensions) + + # --- compute required Z slab --- + z_radius = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(c_new[0] - z_radius)) + z_max = int(np.ceil(c_new[0] + z_radius)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + stack = np.stack( + [ + imread(os.path.join(in_folder, files[z])) + for z in range(z_min_clamped, z_max_clamped + 1) + ], + axis=0 + ) + z_offset = z_min_clamped + + else: + depth, height, width = stack.shape + dimensions = [depth, height, width] + + # --- output slice size --- + out_d, out_h, out_w = newDimensions(n, dimensions) + + # --- compute required Z slab --- + z_radius = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(c_new[0] - z_radius)) + z_max = int(np.ceil(c_new[0] + z_radius)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + z_offset = z_min_clamped + z_offset = 0 + + + # --- slice center in stack coordinates --- + s_centre = np.array([ + c_new[0] - z_offset, + c_new[1], + c_new[2] + ], dtype=float) + + # --- sample coordinates --- + coords = [] + for y in range(out_h): + for x in range(out_w): + offset = ( + (x - out_w // 2) * perp1 + + (y - out_h // 2) * -perp2 + ) + coords.append(s_centre + offset) + + coords = np.array(coords).T # (3, N) + + slice_vals = map_coordinates( + stack, + coords, + order=0, + mode="constant", + cval=0.0 + ).reshape(out_h, out_w) + + # --- geometry (volume coordinates!) --- + slice_geometry = { + "slice_center_3d": np.asarray(c_new, dtype=float), + "axis_x_3d": perp1.astype(float), + "axis_y_3d": (-perp2).astype(float), + "normal_3d": n.astype(float), + "width": out_w, + "height": out_h, + "z_slab": (z_min_clamped, z_max_clamped), + } + + return slice_vals, slice_geometry + + +def ResliceMultipleSlices(vector, centers, in_folder=None, stack=None): + """ + Reslice multiple oblique slices through given 3D points (z, y, x), + using the same axis vector. Loads one volume slab containing all slices. + + Parameters + ---------- + vector : array-like + Normal vector of the slices. + centers : list of array-like + List of slice centers (z, y, x) in volume coordinates. + in_folder : str, optional + Folder containing image stack (if stack not provided). + stack : np.ndarray, optional + Preloaded volume (depth, height, width). + + Returns + ------- + slices : list of np.ndarray + List of resliced 2D slices. + geometries : list of dict + List of slice geometry dictionaries for each slice. + """ + + n, perp1, perp2 = newAxes(vector) + centers = np.array(centers, dtype=float) + + # --- Load volume slab if folder is provided --- + if in_folder is not None: + files = sorted( + f for f in os.listdir(in_folder) + if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff')) + ) + im0 = imread(os.path.join(in_folder, files[0])) + depth, height, width = len(files), *im0.shape + dimensions = [depth, height, width] + + # Determine slice output size + out_d, out_h, out_w = newDimensions(n, dimensions) + + # Determine Z slab needed to cover all slices + z_offsets = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(np.min(centers[:, 0]) - z_offsets)) + z_max = int(np.ceil(np.max(centers[:, 0]) + z_offsets)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + stack = np.stack( + [imread(os.path.join(in_folder, files[z])) + for z in range(z_min_clamped, z_max_clamped + 1)], + axis=0 + ) + z_offset = z_min_clamped + + else: + depth, height, width = stack.shape + dimensions = [depth, height, width] + out_d, out_h, out_w = newDimensions(n, dimensions) + z_offset = 0 + + slices = [] + geometries = [] + + # --- Reslice each center --- + for c_new in centers: + s_centre = np.array([ + c_new[0] - z_offset, + c_new[1], + c_new[2] + ], dtype=float) + + # Compute sample coordinates + coords = [] + for y in range(out_h): + for x in range(out_w): + offset = (x - out_w // 2) * perp1 + (y - out_h // 2) * -perp2 + coords.append(s_centre + offset) + coords = np.array(coords).T # (3, N) + + slice_vals = map_coordinates( + stack, + coords, + order=0, + mode="constant", + cval=0.0 + ).reshape(out_h, out_w) + + slices.append(slice_vals) + + slice_geometry = { + "slice_center_3d": c_new.astype(float), + "axis_x_3d": perp1.astype(float), + "axis_y_3d": (-perp2).astype(float), + "normal_3d": n.astype(float), + "width": out_w, + "height": out_h, + "z_slab": (z_min_clamped, z_max_clamped), + } + geometries.append(slice_geometry) + + return slices, geometries + +# Two vector reslice for long axis - septum point and MV axis +def Reslice3Points(p1, p2, p3, in_folder=None, stack=None): + """ + Reslice using either 3 points (p1, p2 define main axis, p3 defines plane) + + Points are (z, y, x) + """ + + # --- build slice frame --- + + p1 = np.asarray(p1, dtype=float) + p2 = np.asarray(p2, dtype=float) + p3 = np.asarray(p3, dtype=float) + + # main axis (replaces vector) + perp1 = p2 - p1 + perp1 = perp1 / np.linalg.norm(perp1) + + # second in-plane vector from p3 + v2 = p3 - p1 + + # normal + n = np.cross(perp1, v2) + norm_n = np.linalg.norm(n) + if norm_n < 1e-6: + raise ValueError("Points are collinear or too close") + + n = n / norm_n + + # orthogonal second axis + perp2 = np.cross(n, perp1) + perp2 = perp2 / np.linalg.norm(perp2) + + # center = midpoint of p1->p2 projected into plane + c_new = (p1 + p2) / 2.0 + + + # --- load data / dimensions --- + if in_folder is not None: + + files = sorted( + f for f in os.listdir(in_folder) + if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff')) + ) + + im0 = imread(os.path.join(in_folder, files[0])) + depth = len(files) + height, width = im0.shape + dimensions = [depth, height, width] + + out_d, out_h, out_w = newDimensions(n, dimensions) + + # --- compute required Z slab --- + z_radius = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(c_new[0] - z_radius)) + z_max = int(np.ceil(c_new[0] + z_radius)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + stack = np.stack( + [ + imread(os.path.join(in_folder, files[z])) + for z in range(z_min_clamped, z_max_clamped + 1) + ], + axis=0 + ) + + z_offset = z_min_clamped + + else: + depth, height, width = stack.shape + dimensions = [depth, height, width] + + out_d, out_h, out_w = newDimensions(n, dimensions) + + z_radius = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(c_new[0] - z_radius)) + z_max = int(np.ceil(c_new[0] + z_radius)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + z_offset = z_min_clamped + + # --- slice center in stack coords --- + s_centre = np.array([ + c_new[0] - z_offset, + c_new[1], + c_new[2] + ], dtype=float) + + # --- sample coordinates --- + coords = [] + for y in range(out_h): + for x in range(out_w): + offset = ( + (x - out_w // 2) * perp1 + + (y - out_h // 2) * -perp2 + ) + coords.append(s_centre + offset) + + coords = np.array(coords).T + + slice_vals = map_coordinates( + stack, + coords, + order=0, + mode="constant", + cval=0.0 + ).reshape(out_h, out_w) + + # --- geometry --- + slice_geometry = { + "slice_center_3d": np.asarray(c_new, dtype=float), + "axis_x_3d": perp1.astype(float), + "axis_y_3d": (-perp2).astype(float), + "normal_3d": n.astype(float), + "width": out_w, + "height": out_h, + "z_slab": (z_min_clamped, z_max_clamped), + } + + return slice_vals, slice_geometry + + + +def line_xy_at_z(p0, p1, z): + """ + p0, p1: (x, y, z) endpoints of the line + z: target z value + + returns: (x, y) at that z + """ + p0 = np.asarray(p0, dtype=float) + p1 = np.asarray(p1, dtype=float) + + z0, z1 = p0[2], p1[2] + + if z0 == z1: + raise ValueError("Line is parallel to z-plane (z0 == z1)") + + t = (z - z0) / (z1 - z0) + + x = p0[0] + t * (p1[0] - p0[0]) + y = p0[1] + t * (p1[1] - p0[1]) + + return x, y + + +def project_3d_to_slice(p3d, geom): + """ + Project a 3D point into 2D slice coordinates using slice geometry. + """ + p3d = np.asarray(p3d, dtype=float) + + centre = geom["slice_center_3d"] + axis_x = geom["axis_x_3d"] + axis_y = geom["axis_y_3d"] + out_w = geom["width"] + out_h = geom["height"] + + # Vector from slice center to point + v = p3d - centre + + # Project onto slice axes + x = np.dot(v, axis_x) + out_w / 2 + y = np.dot(v, axis_y) + out_h / 2 + + return x, y + + + +def crop_from_mask(mask, border=5): + """ + Compute crop slices that remove all-zero rows/cols, + keeping a small border. + """ + rows = np.any(mask > 0, axis=1) + cols = np.any(mask > 0, axis=0) + + rmin, rmax = np.where(rows)[0][[0, -1]] + cmin, cmax = np.where(cols)[0][[0, -1]] + + rmin = max(rmin - border, 0) + cmin = max(cmin - border, 0) + rmax = min(rmax + border + 1, mask.shape[0]) + cmax = min(cmax + border + 1, mask.shape[1]) + + return slice(rmin, rmax), slice(cmin, cmax) + +def normalise_percentile(img, p_low=1, p_high=99, out_range=(0, 1)): + img = img.astype(np.float32) + + lo = np.nanpercentile(img, p_low) + hi = np.nanpercentile(img, p_high) + + img_n = (img - lo) / (hi - lo) + img_n = np.clip(img_n, 0, 1) + + out_lo, out_hi = out_range + return img_n * (out_hi - out_lo) + out_lo + +################################# Transumral PLots + + + +def get_epi_contour(mask2d, close_radius=2, shrink_radius=2): + se_close = disk(close_radius) + closed = closing(mask2d, se_close) + closed = remove_small_objects(closed.astype(bool), 500).astype(np.uint8) + + # Optional shrink + if shrink_radius > 0: + se_shrink = disk(shrink_radius) + closed = erosion(closed, se_shrink).astype(np.uint8) + + # Find contour + contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if not contours: + return None, closed + + cnt = max(contours, key=cv2.contourArea) + return cnt.squeeze(), closed + + +def get_epi_contour(mask2d): + H, W = mask2d.shape + scale = max(int(0.002 * min(H, W)), 2) + + closed = closing(mask2d, disk(6 * scale)) + closed = remove_small_objects(closed.astype(bool), 0.001 * H * W) + closed = closed.astype(np.uint8) + + contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if not contours: + return None, closed + + cnt = max(contours, key=cv2.contourArea) + return cnt.squeeze(), closed + + +def get_endo_contour(mask2d, epi_cnt): + H, W = mask2d.shape + scale = max(int(0.002 * min(H, W)), 2) + + # Epicardial mask + epi_mask = np.zeros_like(mask2d, dtype=np.uint8) + cv2.fillPoly(epi_mask, [epi_cnt.astype(int)], 1) + + # Inside myocardium + inside = mask2d * epi_mask + + # Candidate cavity + mask2d[mask2d>0] = 1 + inv = (1 - mask2d) + inv[epi_mask == 0] = 0 + inv = remove_small_objects(inv.astype(bool), 0.0005 * H * W) + inv = inv.astype(np.uint8) + + # Smooth cavity + inv = closing(inv, disk(3 * scale)) + inv = opening(inv, disk(scale)) + inv = remove_small_holes(inv.astype(bool), area_threshold=0.0005 * H * W) + inv = inv.astype(np.uint8) + + + # Extract contours + contours, _ = cv2.findContours(inv, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + if not contours: + return None, inv + + + # Epicardial centroid + epi_center = epi_cnt.mean(axis=0) + + # Choose cavity: closest centroid to epi center + best_cnt = None + best_dist = np.inf + + for cnt in contours: + area = cv2.contourArea(cnt) + if area < 0.001 * cv2.contourArea(epi_cnt): + continue # too small to be LV + + center = cnt.squeeze().mean(axis=0) + dist = np.linalg.norm(center - epi_center) + + # Reject anything touching epicardium + #if any(cv2.pointPolygonTest(epi_cnt, tuple(pt[0]), False) >= 0 for pt in cnt): + # continue + + if dist < best_dist: + best_dist = dist + best_cnt = cnt + + if best_cnt is None: + return None, inv + + return best_cnt.squeeze(), inv + + +def trim_lines(lines, epi_pts, endo_pts=None, centroid2d=None): + trimmed_lines = [] + + # Prepare epicardial contour + epi_cnt = epi_pts.astype(np.float32).reshape(-1, 1, 2) + + for start, end in lines: + xs = np.linspace(start[0], end[0], 1000) + ys = np.linspace(start[1], end[1], 1000) + points = np.column_stack([xs, ys]) + + # Determine start and end points for trimming + if endo_pts is not None: + endo_cnt = endo_pts.astype(np.float32).reshape(-1, 1, 2) + # First point inside endo + mask_endo = np.array([cv2.pointPolygonTest(endo_cnt, (y,x), False)>=0 for y,x in points]) + if np.any(mask_endo): + start_pt = points[np.argmin(mask_endo)] + else: + start_pt = points[0] if centroid2d is None else centroid2d + else: + start_pt = points[0] if centroid2d is None else centroid2d + + # Last point inside epi + mask_epi = np.array([cv2.pointPolygonTest(epi_cnt, (y,x), False)>=0 for y,x in points]) + if np.any(mask_epi): + end_pt = points[np.argmax(mask_epi[::-1] != 0)] # last True point + end_pt = points[len(points)-1 - np.argmax(mask_epi[::-1])] + else: + continue # skip line if it doesn't reach epicardium + + trimmed_lines.append((tuple(start_pt), tuple(end_pt))) + + return trimmed_lines + + + +def trim_lines(lines, epi_pts, endo_pts=None, centroid2d=None): + trimmed_lines = [] + + epi_cnt = epi_pts.astype(np.float32).reshape(-1, 1, 2) + + for start, end in lines: + xs = np.linspace(start[0], end[0], 1000) + ys = np.linspace(start[1], end[1], 1000) + points = np.column_stack([xs, ys]) + + # Check inside epicardium + mask_epi = np.array([ + cv2.pointPolygonTest(epi_cnt, (float(y), float(x)), False) >= 0 + for x, y in points + ]) + + if not np.any(mask_epi): + continue # no intersection at all + + # --- Find continuous True segments --- + segments = [] + in_segment = False + seg_start = 0 + + for i, val in enumerate(mask_epi): + if val and not in_segment: + in_segment = True + seg_start = i + elif not val and in_segment: + segments.append((seg_start, i)) + in_segment = False + + if in_segment: + segments.append((seg_start, len(mask_epi))) + + # --- Choose best segment --- + # Typically the longest segment inside epi + seg_lengths = [end - start for start, end in segments] + best_seg_idx = np.argmax(seg_lengths) + seg_start, seg_end = segments[best_seg_idx] + + trimmed_segment = points[seg_start:seg_end] + + if len(trimmed_segment) < 2: + continue + + start_pt = tuple(trimmed_segment[0]) + end_pt = tuple(trimmed_segment[-1]) + + # Optional: enforce endocardium trimming (inner boundary) + if endo_pts is not None: + endo_cnt = endo_pts.astype(np.float32).reshape(-1, 1, 2) + mask_endo = np.array([ + cv2.pointPolygonTest(endo_cnt, (float(y), float(x)), False) >= 0 + for x, y in trimmed_segment + ]) + + if np.any(mask_endo): + first_inside = np.argmax(mask_endo) + start_pt = tuple(trimmed_segment[first_inside]) + + trimmed_lines.append((start_pt, end_pt)) + + return trimmed_lines + +def trim_lines(lines, epi_pts, endo_pts=None, centroid2d=None): + trimmed_lines = [] + + # Prepare epicardial contour + epi_cnt = epi_pts.astype(np.float32).reshape(-1, 1, 2) + + for start, end in lines: + xs = np.linspace(start[0], end[0], 1000) + ys = np.linspace(start[1], end[1], 1000) + points = np.column_stack([xs, ys]) + + mask_epi = np.array([cv2.pointPolygonTest(epi_cnt, (y,x), False)>=0 for y,x in points]) + + # Determine start and end points for trimming + if endo_pts is not None: + endo_cnt = endo_pts.astype(np.float32).reshape(-1, 1, 2) + mask_endo = np.array([cv2.pointPolygonTest(endo_cnt, (y,x), False)>=0 for y,x in points[mask_epi]]) + # First point inside endo + if np.any(mask_endo): + start_pt = points[np.argmin(mask_endo)] + else: + start_pt = points[np.argmax(mask_epi)] + #start_pt = points[0] if centroid2d is None else centroid2d + else: + start_pt = points[np.argmax(mask_epi)] + #start_pt = points[0] if centroid2d is None else centroid2d + + # Last point inside epi + if np.any(mask_epi): + end_pt = points[np.argmax(mask_epi[::-1] != 0)] # last True point + end_pt = points[len(points)-1 - np.argmax(mask_epi[::-1])] + else: + continue # skip line if it doesn't reach epicardium + + trimmed_lines.append((tuple(start_pt), tuple(end_pt))) + + return trimmed_lines + + +def filter_lines_by_length(lines, tol_frac=0.5): + """ + Remove lines whose length is outside median ± tol_frac * median. + + Parameters + ---------- + lines : list of ((x1,y1), (x2,y2)) + Trimmed line segments. + tol_frac : float + Fraction of median length to tolerate (default 0.5). + + Returns + ------- + filtered_lines : list + Lines within allowed length range. + """ + + if len(lines) == 0: + return [] + + # Compute lengths + lengths = np.array([ + np.linalg.norm(np.asarray(p2) - np.asarray(p1)) + for p1, p2 in lines + ]) + + med = np.median(lengths) + lo = med * (1.0 - tol_frac) + hi = med * (1.0 + tol_frac) + + # Filter + filtered_lines = [ + line for line, L in zip(lines, lengths) + if lo <= L <= hi + ] + + return filtered_lines + + + + +def profile_intensities(img_helix, radial_lines, factor=1.0): + """ + Profiles intensities from helical image along radial lines. + + Parameters: + img_helix (ndarray): The helical angle image. + radial_lines(list): List of (start, end) tuples corresponding to radial lines + factor (float): Scaling factor for line coordinates. + + Returns: + dict: Grouped intensity profiles by region name. + """ + #img_helix = np.nan_to_num(img_helix, nan=0.0) + + intensity_profiles = [] + good_lines = [] + for i, (start_pt, end_pt) in enumerate(radial_lines): + print(f"Measuring line {i+1}/{len(radial_lines)}") + + # Scale and flip (x, y) → (row, col) = (y, x) + start = [start_pt[1] * factor, start_pt[0] * factor] # (row, col) + end = [end_pt[1] * factor, end_pt[0] * factor] + + intensity_profile = measure.profile_line(img_helix, start, end, order=0, mode='constant', cval=np.nan) + + n_points = len(intensity_profile) + if n_points == 0 or (np.count_nonzero(np.isnan( intensity_profile)) / n_points) > 0.1: + continue + else: + good_lines.append([start_pt, end_pt]) + + # Convert to helical angle + #angle_profile = (intensity_profile * 180 / 255) - 90 + + intensity_profile = np.asarray(intensity_profile, dtype=float) + + angle_profile = np.where( + (intensity_profile != 0) & (~np.isnan(intensity_profile)), + (intensity_profile * 180 / 255) - 90, + np.nan + ) + + intensity_profiles.append(angle_profile) + + return intensity_profiles, good_lines + + + + + +def transmuralSampling(centres, vector, slices=None, seg_map=None, centroids = None, mask_factor=None, n_radial=50, route_slices=None): + + all_profiles = [] + all_good_lines = [] + all_segments_assigned = [] + all_route_slices = [] + + if centroids is None: + centroids = np.zeros(len(centres)) + + if route_slices is None: + route_slices = np.zeros(len(centres)) + + for slic, C, centroid, route_idx in zip(slices, centres, centroids, route_slices): + + # ------------------- Extract 2D Mask Slice ------------------- + if seg_map is None: + continue + else: + mf = mask_factor if mask_factor is not None else 1 + C_new = C / mf + + mask2d_sml, tmp = ResliceOneSlice(vector, C_new, stack=seg_map) + mask2d = resample(mask2d_sml, target_shape=slic.shape, TwoD=True, order=0, is_mask=True) + + plt.imshow(mask2d_sml) + plt.show() + + plt.imshow(mask2d) + plt.show() + + mask_slice = slic > 0 + mask2d[~mask_slice] = 0 + + + # ------------------- Epicardium ------------------- + epi_cnt, epi_closed = get_epi_contour(mask2d) + if epi_cnt is None: + continue + + # Convert epi contour to same 2D coordinate system as pts2d + epi_pts = np.column_stack([epi_cnt[:,0], + epi_cnt[:,1]]) + + # ------------------- Endocardium ------------------- + endo_cnt, endo_clean = get_endo_contour(mask2d, epi_cnt) + if endo_cnt is not None: + endo_pts = np.column_stack([endo_cnt[:,0], + endo_cnt[:,1]]) + else: + endo_pts = None + + # ------------------- Verification ------------------- + + fig, ax = plt.subplots(1,3, figsize=(15,5)) + ax[0].imshow(mask2d, cmap='gray') + ax[0].set_title("Raw Mask Slice") + + ax[1].imshow(epi_closed, cmap='gray') + ax[1].plot(epi_cnt[:,0], epi_cnt[:,1], 'r-') + ax[1].set_title("Epicardium") + + ax[2].imshow(endo_clean, cmap='gray') + if endo_pts is not None: + ax[2].plot(endo_cnt[:,0], endo_cnt[:,1], 'b-') + ax[2].set_title("Endocardium") + plt.show() + + # ------------------- Compute Centroid if not given------------------- + if centroid == 0: + if endo_pts is not None: + centroid2d = (epi_pts.mean(axis=0) + endo_pts.mean(axis=0)) / 2 + else: + centroid2d = epi_pts.mean(axis=0) + + #centroid2d = centroid2d[::-1] + else: + centroid2d = np.array(centroid) + + # ------------------- Radial lines from centroid ------------------- + + n_radial = 48 # number of radial lines + angles = np.linspace(0, 2*np.pi, n_radial, endpoint=False) + + mean_radius = np.mean(np.linalg.norm(epi_pts - centroid2d[None,:], axis=1)) + L = mean_radius * 2 # extend a bit beyond epicardium + + p1_list, p2_list = [], [] + for theta in angles: + direction = np.array([np.cos(theta), np.sin(theta)]) + p1_list.append(centroid2d) # start at center + p2_list.append(centroid2d + direction*L) # extend outwards + + + # ------------------- Trim using Epicardium ------------------- + trimmed_lines = trim_lines(list(zip(p1_list,p2_list)), epi_pts, endo_pts, centroid2d) + trimmed_lines = filter_lines_by_length(trimmed_lines, tol_frac=0.5) + + # ------------------- Sample HA along radial lines ------------------- + profiles, good_lines = profile_intensities(slic, trimmed_lines) + + all_profiles.extend(profiles) + all_good_lines.extend(good_lines) + + # Segment assignment + segments_assigned = [] + + mx = [] + my = [] + + p1x = [] + p1y = [] + + p2x = [] + p2y = [] + + route_slices = [] + for (pt1, pt2) in good_lines: + pt1 = np.asarray(pt1, dtype=float) + pt2 = np.asarray(pt2, dtype=float) + mid_pt = 0.5 * (pt1 + pt2) # [x, y] + + p1x.append(pt1[0]) + p1y.append(pt1[1]) + + p2x.append(pt2[0]) + p2y.append(pt2[1]) + + scale_x = mask2d_sml.shape[1] / slic.shape[1] + scale_y = mask2d_sml.shape[0] / slic.shape[0] + + mid_pt_sml = np.array([ + mid_pt[0] * scale_x, + mid_pt[1] * scale_y + ]) + + mx.append(mid_pt_sml[0]) + my.append(mid_pt_sml[1]) + + seg = mask2d_sml[int(mid_pt_sml[1]), int(mid_pt_sml[0])] + segments_assigned.append(seg) + + #seg = mask2d[int(mid_pt[1]), int(mid_pt[0])] + #segments_assigned.append(seg) + + route_slices.append(route_idx) + + all_segments_assigned.extend(segments_assigned) + all_route_slices.extend(route_slices) + + plt.imshow(mask2d_sml) + plt.scatter(mx, my, color='g') + plt.show() + + plt.imshow(mask2d) + plt.scatter(p1x, p1y, color='r') + plt.scatter(p2x, p2y, color='b') + plt.show() + + # ------------------- Plot 2D slice ------------------- + + plt.figure(figsize=(7,7)) + img = plt.imshow(slic, origin='upper', aspect='equal') + for p1,p2 in good_lines: + plt.plot([p1[0],p2[0]],[p1[1],p2[1]],'r-') + plt.plot(epi_pts[:,0], epi_pts[:,1],'b-', lw=2) + cbar = plt.colorbar(img) + + # Set ticks in LUT space (0–255) + lut_ticks = np.linspace(0, 255, 7) + + # Convert ticks to physical angle space (-90..90) + angle_ticks = np.linspace(-90, 90, 7) + + cbar.set_ticks(lut_ticks) + cbar.set_ticklabels([f"{a:.0f}" for a in angle_ticks]) + cbar.set_label("HA (deg)") + + plt.title(f"Slic {np.round(C_new[0])} HA with Radial Lines") + plt.show() + + + return all_profiles, all_good_lines, all_segments_assigned, all_route_slices + + + +def plot_transmural_slice(profiles, savepath=None): + # -------------------------- + # Pad profiles to equal size + # -------------------------- + max_len = max(len(p) for p in profiles) + # Pad front to line up with epicardium + #padded = [np.pad(p, (max_len - len(p), 0), mode="constant", constant_values=np.nan) for p in profiles] + padded = [np.pad(p, (max_len - len(p), 0), mode="constant", constant_values=np.nan) for p in profiles] + data = np.vstack(padded) # shape (Nprofiles × Ndepth) + + # -------------------------- + # Circular stats on [-90°, 90°] + # -------------------------- + data_rad = np.deg2rad(data) + + mean_rad = circmean( + data_rad, axis=0, + low=-np.pi/2, high=np.pi/2, + nan_policy="omit" + ) + + std_rad = circstd( + data_rad, axis=0, + low=-np.pi/2, high=np.pi/2, + nan_policy="omit" + ) + + # Range 0–1 for transmural depth + r = np.linspace(0, 1, data.shape[1]) + + # ------------------------------------------------- + # Convert mean/stdev to polar angles in [0, 2π]: + # -90° → 0° + # +90° → 180° + # then map [0°, 180°] to full polar circle by doubling + # ------------------------------------------------- + mean_deg = np.rad2deg(mean_rad) + theta = np.deg2rad((mean_deg + 90) * 2) + + data2pi = np.deg2rad((data + 90) * 2) + + upper = np.deg2rad((mean_deg + np.rad2deg(std_rad) + 90) * 2) + lower = np.deg2rad((mean_deg - np.rad2deg(std_rad) + 90) * 2) + + # =========================== + # POLAR PLOT + # =========================== + fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=(6, 6)) + + # Tick labels for -90 → +90 + ticks_360 = np.arange(0, 360, 30) + ticks_labels = [f"{int((t/2)-90)}°" for t in ticks_360] + + ax.set_thetagrids(ticks_360, labels=ticks_labels) + + # Mean + ax.plot(theta, r, "k", label="Mean Angle") + for p in data2pi: + ax.scatter(p, r, color='g', marker="x", alpha= 0.2) + + # Std band + #ax.fill_betweenx(r, lower, upper, alpha=0.3, color="gray") + + ax.set_title("Polar Projection of Helical Angles", fontsize=14) + ax.set_ylim(0, 1) + ax.set_theta_zero_location("N") + ax.set_theta_direction(-1) + + fig.tight_layout() + if savepath != None: + plt.savefig(savepath + '_Ptransmural_lateral.pdf', dpi=1000) + plt.show() + + + # =========================== + # LINEAR PLOT + # =========================== + mean_deg = np.rad2deg(mean_rad) + std_deg = np.rad2deg(std_rad) + + fig, ax = plt.subplots(figsize=(14, 6)) + + ax.plot(r, mean_deg, "k-x", label="Mean") + ax.fill_between(r, mean_deg - std_deg, mean_deg + std_deg, + color="gray", alpha=0.4, label="±1 SD") + + ax.set_xlabel("Transmural depth (0 = endo, 1 = epi)") + ax.set_ylabel("Helical angle (°)") + ax.set_title("Transmural Helical Angle (Linear Plot)") + ax.grid(True) + ax.set_ylim(-90,90) + ax.legend() + + fig.tight_layout() + if savepath != None: + plt.savefig(savepath + '_Ltransmural_lateral.pdf', dpi=1000) + plt.show() + + mask = ~np.isnan(mean_deg) + + r = r[mask] + mean_deg = mean_deg[mask] + + return r, mean_deg + + + + +# Models +def flat_model(x, c): + return c * np.ones_like(x) + +def linear_model(x, m, b): + return m*x + b + +def find_best_breakpoint(x, y, min_size=20): + """ + Finds breakpoint where data transitions from flat to downward slope. + min_size = minimum number of points allowed in each segment + """ + n = len(x) + best_sse = np.inf + best_idx = None + best_params = None + + # try each possible breakpoint + for i in range(min_size, n - min_size): + # segment 1: flat + x1, y1 = x[:i], y[:i] + popt1, _ = curve_fit(flat_model, x1, y1) + y1_pred = flat_model(x1, *popt1) + sse1 = np.sum((y1 - y1_pred)**2) + + # segment 2: linear + x2, y2 = x[i:], y[i:] + popt2, _ = curve_fit(linear_model, x2, y2) + y2_pred = linear_model(x2, *popt2) + sse2 = np.sum((y2 - y2_pred)**2) + + total_sse = sse1 + sse2 + + # keep best candidate + if total_sse < best_sse: + best_sse = total_sse + best_idx = i + best_params = (popt1, popt2) + + return best_idx, best_params + + + + + + +def wrap_angles(y): + """ + Wrap angles (in degrees) to [-180, 180) + so that 90° == -90° in distance calculations. + """ + return np.degrees(np.angle(np.exp(1j * np.radians(y)))) + + + + + +def fast_linear_fit(x, y): + """Analytical least squares fit for y = mx + b.""" + n = len(x) + sx = np.sum(x) + sy = np.sum(y) + sxx = np.sum(x*x) + sxy = np.sum(x*y) + + denom = n*sxx - sx*sx + if denom == 0: + return 0.0, np.mean(y) + + m = (n*sxy - sx*sy) / denom + b = (sy - m*sx) / n + return m, b + + + + + + +############### Introduce constrained wrapping + + + +def constrained_unwrap( + p, + period=np.pi, + max_range=np.deg2rad(350), + step=0.05, + max_frac=0.95 +): + p = np.asarray(p) + + mask = ~np.isnan(p) + p_valid = p[mask] + + if len(p_valid) == 0: + return p.copy() + + frac = 0.5 + + while frac <= max_frac: + thresh = frac * period + out = np.copy(p_valid) + + # incremental unwrap + for i in range(1, len(out)): + dp = out[i] - out[i - 1] + + if dp > thresh: + out[i] -= period + elif dp < -thresh: + out[i] += period + + # range check + if (np.nanmax(out) - np.nanmin(out)) <= max_range: + result = np.full_like(p, np.nan) + result[mask] = out + return result + + frac += step + + # fallback + result = np.full_like(p, np.nan) + result[mask] = out + return result + +def wrap_pi_deg(y): + """ + Wrap angles (degrees) to [-90, 90) + consistent with π-periodicity. + """ + return (y + 90) % 180 - 90 + + +def find_two_breakpoints( + x, y, + min_slope_size=100, + w_slope=1.5, + w_flat=0.1, + penalty_strength=0.2 +): + + n = len(x) + max_tail = int(0.5 * n) # 50% limit for 3rd flat section + + best_loss = np.inf + best_breaks = None + best_params = None + + i_candidates = np.linspace(1, n-2, 100, dtype=int) + + for i in i_candidates: + + valid_j_range = np.arange(i + min_slope_size, n) + if len(valid_j_range) == 0: + continue + + j_candidates = np.linspace(valid_j_range[0], valid_j_range[-1], 100, dtype=int) + + for j in j_candidates: + + # enforce max size of segment 3 + if (n - j) > max_tail: + continue + + #### SEGMENT 1 (flat) + y1 = y[:i] + if len(y1): + c1 = np.degrees(np.angle(np.mean(np.exp(1j*np.radians(y1))))) + SSE1 = np.sum((wrap_pi_deg(y1 - c1))**2) + SST1 = np.sum((wrap_pi_deg(y1 - np.mean(y1)))**2) + else: + SSE1 = 0 + SST1 = 0 + c1 = 0 + + #### SEGMENT 2 (slope) + x2 = x[i:j] + y2 = y[i:j] + + if len(x2) < 2: + continue + + # unwrap angles for linear fit + #y2_unwrapped = np.rad2deg(constrained_unwrap(np.deg2rad(y2))) + + y2_unwrapped = y2 + + m, b = fast_linear_fit(x2, y2_unwrapped) + + # enforce negative slope + if m > 0: + m = 0 + + y2_pred = m*x2 + b + + SSE2 = np.sum((y2_unwrapped - y2_pred)**2) + SST2 = np.sum((y2_unwrapped - np.mean(y2_unwrapped))**2) + + r2 = 1 - SSE2/SST2 if SST2 > 0 else -np.inf + + # refit unconstrained if fit is terrible + if r2 < 0: + m, b = fast_linear_fit(x2, y2_unwrapped) + y2_pred = m*x2 + b + SSE2 = np.sum((y2_unwrapped - y2_pred)**2) + + #### SEGMENT 3 (flat) + y3 = y[j:] + if len(y3): + c3 = np.degrees(np.angle(np.mean(np.exp(1j*np.radians(y3))))) + SSE3 = np.sum((wrap_pi_deg(y3 - c3))**2) + SST3 = np.sum((wrap_pi_deg(y3 - np.mean(y3)))**2) + else: + SSE3 = 0 + SST3 = 0 + c3 = 0 + + #### slope length penalty + + + R2_2 = 1 - SSE2 / SST2 + + R2_1 = 1 - SSE1 / SST1 if SST1 > 0 else 1 + R2_3 = 1 - SSE3 / SST3 if SST3 > 0 else 1 + + L = j-i + penalty = penalty_strength * L * (n / L)**2 + + L1 = len(y1) + L2 = len(y2) + L3 = len(y3) + + loss = ( + w_slope * L2 * (1 - R2_2) + + w_flat * (L1 * (1 - R2_1) + L3 * (1 - R2_3)) + + penalty + ) + + print(f'E Slope: {w_slope * L2 * (1 - R2_2)}, E Flat: {w_flat * (L1 * (1 - R2_1) + L3 * (1 - R2_3))}, Penalty: {penalty},') + + if loss < best_loss: + best_loss = loss + best_breaks = (i, j) + best_params = ((c1,), (m, b), (c3,)) + + return best_breaks, best_params + + +def process_transmural_profiles( + profiles, + target_len=None, + plot=False +): + + """ + Resample, unwrap, fit flat→slope→flat model, and circularly average profiles. + Returns transmural coordinate, circular mean/std, and R² values for slope fits. + """ + + max_len = max(len(p) for p in profiles) + padded_profiles = [np.pad(p, (max_len - len(p), 0), mode="constant", constant_values=np.nan) for p in profiles] + + pp_rad = np.deg2rad(padded_profiles) + + # --- circular statistics --- + mean_rad = circmean( + pp_rad, + axis=0, + low=-np.pi/2, + high=np.pi/2, + nan_policy="omit" + ) + + std_rad = circstd( + pp_rad, + axis=0, + low=-np.pi/2, + high=np.pi/2, + nan_policy="omit" + ) + + if target_len != None: + + x = np.linspace(0, 1, target_len) + x_orig = np.linspace(0, 1, len(mean_rad)) + + mask_o = ~np.isnan(mean_rad) #interp can't handle nan + mask_s = ~np.isnan(std_rad) + + p_unwrapped = constrained_unwrap(mean_rad[mask_o], period=np.pi) + + mask_u = ~np.isnan(p_unwrapped) + + p_resampled = np.interp(x, x_orig[mask_o], p_unwrapped[mask_u]) + st_resampled = np.interp(x, x_orig[mask_o], std_rad[mask_s]) + + rewrapped = (p_resampled + np.pi/2) % (np.pi) - np.pi/2 # Rewrap to [-π/2, +π/2] + + mean_deg = np.rad2deg(rewrapped) + std_deg = np.rad2deg(st_resampled) + + unwrapped_mean = np.rad2deg(p_resampled) + + else: + x = np.linspace(0, 1, len(mean_rad)) + + mean_deg = np.rad2deg(mean_rad) + std_deg = np.rad2deg(std_rad) + + unwrapped_mean = np.rad2deg(constrained_unwrap(np.deg2rad(mean_deg), period=np.pi)) + + mask = ~np.isnan(unwrapped_mean) + + y = unwrapped_mean + + y_mid = y[int(0.4*len(y)):int(0.8*len(y))] + + while y_mid.mean() < -90 or y_mid.mean() > 90: + y_mid = y[int(0.4*len(y)):int(0.8*len(y))] + if y_mid.mean() < -90: + y += 180 + elif y_mid.mean() > 90: + y -= 180 + + # --- breakpoint fitting --- + + (b1, b2), (flat1_params, slope_params, flat2_params) = find_two_breakpoints( + x, + y[mask], + ) + + mask = mask = ~np.isnan(mean_deg) + + if plot != False: + + c1 = flat1_params[0] + m, b = slope_params + c3 = flat2_params[0] + + # Generate fitted segments + y_fit1 = flat_model(x[:b1], c1) + y_fit2 = linear_model(x[b1:b2], m, b) + y_fit3 = flat_model(x[b2:], c3) + + r2 = r2_score(y[b1:b2], y_fit2) + + plt.figure(figsize=(12,6)) + + plt.plot(x, y, 'k.', markersize=3) + + plt.plot(x[:b1], y_fit1, 'r-', linewidth=2) + plt.plot(x[b1:b2], y_fit2, 'b-', linewidth=2, label=f"Slope gradient {m:.3f}") + plt.plot(x[b2:], y_fit3, 'g-', linewidth=2) + + plt.axvline(x[b1], color='r', linestyle='--', label=f"Break 1 = {x[b1]:.3f}") + plt.axvline(x[b2], color='g', linestyle='--', label=f"Break 2 = {x[b2]:.3f}") + + plt.xlabel("Transmural depth") + plt.ylabel("Helical angle") + plt.title(f"{plot}, R2 = {r2}") + plt.legend() + plt.grid(True) + plt.show() + + return ( + x[mask], + mean_deg[mask], + std_deg[mask], + (b1, b2), + (flat1_params, slope_params, flat2_params) + ) + + +def inspect_segment_fraction( + heart_id, + segment, + df_Mega, + period=np.pi +): + + # --- load data --- + mask_global = ( + (df_Mega["heart"] == heart_id) & + (df_Mega["segment"] == segment) + ) + + df = df_Mega[mask_global].copy() + if df.empty: + print("No data found") + return + + df = df.sort_values("depth").reset_index() + + t_depth = df["depth"].to_numpy() + y = df["HA"].to_numpy() + + + # --- fractional init --- + b1_frac = df["s_compact_start"].iloc[0] + b2_frac = df["s_compact_end"].iloc[0] + + n = len(t_depth) + + shift_mask = np.zeros(n, dtype=bool) + shift_sign = 0 + + + while True: + + y_plot = y.copy() + + n = len(t_depth) + b1 = int(b1_frac * n) + b2 = int(b2_frac * n) + + + # apply shift safely (mapped to local df index) + if shift_sign != 0: + local_mask = np.zeros(n, dtype=bool) + local_mask[:] = shift_mask[df.index] + y_plot[local_mask] += shift_sign * 180 + + # --- fit --- + c1 = np.mean(y_plot[:b1]) + c3 = np.mean(y_plot[b2:]) + + m, c = fast_linear_fit(t_depth[b1:b2], y_plot[b1:b2]) + + y_fit = linear_model(t_depth[b1:b2], m, c) + + r2 = r2_score(y_plot[b1:b2], y_fit) + + # --- plot --- + plt.figure(figsize=(12, 6)) + + plt.plot(t_depth, y_plot, 'k.', markersize=3) + plt.plot(t_depth[:b1], np.full(b1, c1), 'r-') + plt.plot(t_depth[b1:b2], y_fit, 'b-') + plt.plot(t_depth[b2:], np.full(len(t_depth)-b2, c3), 'g-') + + plt.axvline(t_depth[b1], color='r', linestyle='--') + plt.axvline(t_depth[b2], color='g', linestyle='--') + + plt.title(f"Heart {heart_id}, Segment {segment}, R2={r2:.3f}") + plt.xlabel("Depth") + plt.ylabel("HA") + plt.minorticks_on() + plt.grid(True, which='both') + plt.show() + + cmd = input("Command (b1/b2/shift+/shift-/clear/commit/exit): ") + + if cmd == "exit": + break + + elif cmd == "b1": + b1_frac = float(input("b1 fraction (0-1): ")) + + elif cmd == "b2": + b2_frac = float(input("b2 fraction (0-1): ")) + + elif cmd == "shift+": + a, b = map(float, input("a:b (0-1): ").split(":")) + shift_mask[:] = False + idx = slice(int(a*n), int(b*n)) + shift_mask[df.index[idx]] = True + shift_sign = +1 + + elif cmd == "shift-": + a, b = map(float, input("a:b (0-1): ").split(":")) + shift_mask[:] = False + idx = slice(int(a*n), int(b*n)) + shift_mask[df.index[idx]] = True + shift_sign = -1 + + elif cmd == "clear": + shift_mask[:] = False + shift_sign = 0 + + elif cmd == "commit": + + # --- recompute final y --- + y_commit = y.copy() + + if shift_sign != 0: + y_commit[shift_mask] += shift_sign * 180 + + # --- write back using original indices --- + idx = df["index"].values # original df_Mega indices + + df_Mega.loc[idx, "HA"] = y_commit + + df_Mega.loc[idx, "s_compact_start"] = b1_frac + df_Mega.loc[idx, "s_compact_end"] = b2_frac + df_Mega.loc[idx, "s_m"] = m + df_Mega.loc[idx, "s_c"] = c + df_Mega.loc[idx, "s_r2"] = r2 + + print(f"Committed heart {heart_id}, segment {segment}") + + + +################################ Histograms + + +def histogram(folder=None, files=None, start=0, end=None, mask=None, seg_map=None, factor=1, rdr=None): + """ + Compute histograms either from a folder of image files or from a DataReader `rdr`. + + Parameters + ---------- + folder : str or None + Path to folder with image slices (used if `rdr` is None). + files : list or None + Precomputed list of filenames (optional). + start, end : int + Slice range to process. + mask : ndarray or None + Binary mask volume (indexed by slice) to apply. + seg_map : ndarray or None + Segment map volume (indexed by slice) to compute per-segment histograms. + factor : int + Scale factor when mapping mask/seg_map indices to image indices. + rdr : DataReader or None + If provided, stream slices from this reader instead of reading files from disk. + + Returns + ------- + bins : ndarray + Histogram counts. If `seg_map` provided returns shape (n_segments, 256), + else returns shape (256,). + unique_segments : ndarray or None + Array of segment labels when `seg_map` provided, else None. + """ + + unique_segments = None + + # Determine slice loader + def load_slice(idx): + if rdr is not None: + return rdr.load_volume(start_index=idx, end_index=idx + 1)[0] + else: + return imread(os.path.join(folder, files[idx])) + + # If using folder, build file list + if rdr is None: + if files is None: + files = sorted([f for f in os.listdir(folder) if f.lower().endswith(('.tif', '.tiff', '.jp2'))]) + if end is None: + end = len(files) + else: + # rdr provided + Z = rdr.shape[0] + if end is None: + end = Z + + # Branch by mask/segment/none + if mask is not None: + bins = np.zeros(256, dtype=np.int64) + for i in range(start, end): + im = load_slice(i).astype(np.uint8) + im_mask = resample(mask[int(i // factor)], target_shape=im.shape, TwoD=True) + vals = im[im_mask > 0] + vals = vals[~np.isnan(vals)] + if vals.size: + bins += np.bincount(vals, minlength=256) + elif seg_map is not None: + unique_segments = np.unique(seg_map) + unique_segments = unique_segments[unique_segments != 0] + bins = np.zeros((len(unique_segments), 256), dtype=np.int64) + for i in range(start, end): + im = load_slice(i).astype(np.uint8) + im_mask = resample(seg_map[int(i // factor)], target_shape=im.shape, TwoD=True) + for si, s in enumerate(unique_segments): + mask_loc = (im_mask == s) + if not mask_loc.any(): + continue + vals = im[mask_loc] + vals = vals[~np.isnan(vals)] + if vals.size: + bins[si] += np.bincount(vals, minlength=256) + else: + bins = np.zeros(256, dtype=np.int64) + for i in range(start, end): + im = load_slice(i).astype(np.uint8) + vals = im[~np.isnan(im)] + if vals.size: + bins += np.bincount(vals, minlength=256) + + return bins, unique_segments + + + +def plot_segment_histogram( + bins, + segments, + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=False, + circular_mean=False, + xlab = 'Value', + ylab = 'Count', + title=None +): + + # -------------------- + # Combine selected segments + # -------------------- + seg_idx = [s - 1 for s in segments] + hist = bins[seg_idx].sum(axis=0) + + # Crop histogram to negate masking artifacts + hist[0] = hist[1] + hist[-1] = hist[-2] + + # -------------------- + # X axis mapping + # -------------------- + x = np.linspace(value_range[0], value_range[1], hist.size) + + # -------------------- + # Normalize + # -------------------- + if normalize and hist.sum() > 0: + hist = hist / hist.sum() + + # -------------------- + # Smoothing + # -------------------- + if smooth_sigma > 0: + hist = gaussian_filter1d(hist, sigma=smooth_sigma) + + # -------------------- + # Plot + # -------------------- + fig, ax = plt.subplots() + ax.plot(x, hist, linewidth=2) + ax.set_xlabel(xlab) + ax.set_ylabel(ylab) + + if title: + ax.set_title(title) + + # -------------------- + # Mean line + # -------------------- + if show_mean: + if circular_mean: + # Convert to radians + scale_rad = np.linspace(0,2*np.pi, 256) + scale_mean_val = np.rad2deg(stats.circmean(scale_rad, weights=hist)) + f = (value_range[1] - value_range[0]) / 360 + cmean_val = scale_mean_val*f + value_range[0] + if cmean_val < value_range[0]: + cmean_val += f*360 + ax.axvline(cmean_val, linestyle='--', linewidth=2, label=f"Circlar Mean = {cmean_val:.2f}") + mean_val = np.average(x, weights=hist) + ax.axvline(mean_val, linestyle='-', linewidth=2, label=f"Mean = {mean_val:.2f}") + else: + mean_val = np.average(x, weights=hist) + ax.axvline(mean_val, linestyle='-', linewidth=2, label=f"Mean = {mean_val:.2f}") + ax.legend() + + plt.show() + + return fig + +def plot_segment_histogram_labels( + bins, + segments, + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=False, + circular_mean=False, + xlab='Value', + ylab='Count', + title=None, + ax=None # <-- add this +): + + # -------------------- + # Combine selected segments + # -------------------- + rows = bins[np.isin(bins[:, 0], segments)] + hist = rows[:, 1:].sum(axis=0) + + # Crop histogram to negate masking artifacts + hist[0] = hist[1] + hist[-1] = hist[-2] + + # -------------------- + # X axis mapping + # -------------------- + x = np.linspace(value_range[0], value_range[1], hist.size) + + # -------------------- + # Normalize + # -------------------- + if normalize and hist.sum() > 0: + hist = hist / hist.sum() + + # -------------------- + # Smoothing + # -------------------- + if smooth_sigma > 0: + hist = gaussian_filter1d(hist, sigma=smooth_sigma) + + # -------------------- + # Plot (use provided axis) + # -------------------- + if ax is None: + fig, ax = plt.subplots() + else: + fig = ax.figure + + ax.plot(x, hist, linewidth=2) + ax.set_xlabel(xlab) + ax.set_ylabel(ylab) + + if title: + ax.set_title(title) + + # -------------------- + # Mean line + # -------------------- + if show_mean and hist.sum() > 0: + if circular_mean: + scale_rad = np.linspace(0, 2*np.pi, 256) + scale_mean_val = np.rad2deg(stats.circmean(scale_rad, weights=hist)) + f = (value_range[1] - value_range[0]) / 360 + cmean_val = scale_mean_val * f + value_range[0] + if cmean_val < value_range[0]: + cmean_val += f * 360 + + ax.axvline(cmean_val, linestyle='--', linewidth=2, label=f"Circ Mean = {cmean_val:.2f}") + + mean_val = np.average(x, weights=hist) + ax.axvline(mean_val, linestyle='-', linewidth=2, label=f"Mean = {mean_val:.2f}") + ax.legend() + + return fig + + + +def segment_means_from_histogram( + bins, + value_range=(-90, 90), + circular=False +): + """ + bins : ndarray (17, 256) + Histogram counts per segment + + value_range : tuple + Mapping of bin index -> physical values + + circular : bool + Use circular mean (for angles) + + Returns + ------- + means : ndarray (17,) + """ + means = np.full(17, np.nan) + + # Physical x-axis + x = np.linspace(value_range[0], value_range[1], bins.shape[1]) + + for s in range(17): + hist = bins[s] + + # Crop histogram to negate masking artifacts + hist[0] = hist[1] + hist[-1] = hist[-2] + + if hist.sum() == 0: + continue + + if circular: + scale_rad = np.linspace(0, 2*np.pi, hist.shape[1], endpoint=False) + scale_mean_val = np.rad2deg(stats.circmean(scale_rad, weights=hist)) + f = (value_range[1] - value_range[0]) / 360 + cmean_val = scale_mean_val*f + value_range[0] + if cmean_val < value_range[0]: + cmean_val += f*360 + means[s] = cmean_val + else: + means[s] = np.average(x, weights=hist) + + return means + + +def bullseye_plot( + seg_means, + value_range=(-90, 90), + cmap='viridis', + title="Mean HA", + cbar_label="HA Mean", + figsize=(8, 8) +): + """ + Create an AHA-style 17-segment bullseye plot. + + Parameters + ---------- + seg_means : array-like (17,) + Mean value per segment (NaN allowed) + + value_range : tuple + (vmin, vmax) for color normalization + + cmap : str or Colormap + Matplotlib colormap + + title : str + Figure title + + cbar_label : str + Colorbar label + + figsize : tuple + Figure size + + Returns + ------- + fig, ax : matplotlib Figure and Axes + """ + + seg_means = np.asarray(seg_means) + if seg_means.size != 17: + raise ValueError("seg_means must have length 17") + + cmap = plt.cm.get_cmap(cmap) + norm = plt.Normalize(*value_range) + + # -------------------- + # Helpers + # -------------------- + def add_wedge(ax, r_in, r_out, theta1, theta2, value): + color = cmap(norm(value)) if not np.isnan(value) else "lightgray" + w = Wedge( + center=(0, 0), + r=r_out, + theta1=theta1, + theta2=theta2, + width=(r_out - r_in), + facecolor=color, + edgecolor='white', + linewidth=2 + ) + ax.add_patch(w) + + def polar_to_xy(r, theta_deg): + theta = np.deg2rad(theta_deg) + return r * np.cos(theta), r * np.sin(theta) + + # -------------------- + # Figure + # -------------------- + fig, ax = plt.subplots(figsize=figsize, subplot_kw={'aspect': 'equal'}) + + # Radii + r1, r2, r3, r4 = 1.0, 2.0, 3.0, 4.0 + + # -------------------- + # Basal + Mid rings + # -------------------- + angles = np.linspace(60, 420, 7) + + for i in range(6): + add_wedge(ax, r3, r4, angles[i], angles[i+1], seg_means[i]) # basal + add_wedge(ax, r2, r3, angles[i], angles[i+1], seg_means[6 + i]) # mid + + # -------------------- + # Apical ring + # -------------------- + angles_apex = np.linspace(45, 405, 5) + for i in range(4): + add_wedge(ax, r1, r2, angles_apex[i], angles_apex[i+1], seg_means[12 + i]) + + # -------------------- + # Apex + # -------------------- + apex_color = cmap(norm(seg_means[16])) if not np.isnan(seg_means[16]) else "lightgray" + ax.add_patch(plt.Circle((0, 0), r1, color=apex_color, ec='white', lw=2)) + + # -------------------- + # Labels + # -------------------- + for i in range(6): + ax.text(*polar_to_xy(3.5, (angles[i] + angles[i+1]) / 2), + str(i + 1), ha='center', va='center', fontsize=12, color='white') + ax.text(*polar_to_xy(2.5, (angles[i] + angles[i+1]) / 2), + str(7 + i), ha='center', va='center', fontsize=12, color='white') + + for i in range(4): + ax.text(*polar_to_xy(1.5, (angles_apex[i] + angles_apex[i+1]) / 2), + str(13 + i), ha='center', va='center', fontsize=12, color='white') + + ax.text(0, 0, "17", ha='center', va='center', fontsize=14, color='white') + + # -------------------- + # Colorbar + # -------------------- + sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap) + sm.set_array([]) + + cax = fig.add_axes([0.88, 0.15, 0.03, 0.7]) + cbar = plt.colorbar(sm, cax=cax) + cbar.set_label(cbar_label) + + # -------------------- + # Final layout + # -------------------- + ax.set_title(title, fontsize=16) + ax.set_xlim(-4.2, 4.2) + ax.set_ylim(-4.2, 4.2) + ax.axis('off') + + return fig, ax + + +## CLAHE for image visualisation +def auto_contrast(image, plo=2, phigh=98, clip_limit=0.03): + """ + Auto-contrast with percentile clipping and CLAHE for synchrotron images. + """ + image = image.astype(np.float32) + + # percentile clipping + lo, hi = np.percentile(image, (plo, phigh)) + image = np.clip(image, lo, hi) + + # normalize to 0-1 for CLAHE + image = (image - lo) / (hi - lo) + + # CLAHE + image = exposure.equalize_adapthist(image, clip_limit=clip_limit) + + return image + diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py new file mode 100644 index 00000000..db088691 --- /dev/null +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -0,0 +1,183 @@ +#!/usr/bin/env python3 +""" +analysis_histograms_aha.py + +Compute histograms of angle volumes (HA) per AHA 17-segment map. +Uses `create_aha_mask` and `resample` from `cardiotensor.analysis.analysis_utils`. + +Example: + analysis_histograms_aha.py params.conf --lv-mask /path/to/lv_mask --outdir ./aha_hists +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import numpy as np +import matplotlib.pyplot as plt + +from cardiotensor.utils.DataReader import DataReader +from cardiotensor.utils.utils import read_conf_file +import cardiotensor.analysis.analysis_utils as utils +import csv + + +def script() -> None: + ap = argparse.ArgumentParser(description="AHA-segmented histograms") + ap.add_argument("input", type=Path, help=".conf file or directory to make histogram of") + ap.add_argument("--hist-type", type=str, default="HA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") + ap.add_argument("--lv-mask", type=Path, required=True, help="LV mask directory (slices)") + ap.add_argument("--axis-points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") + ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") + ap.add_argument("--outdir", type=Path, default=None) + ap.add_argument("--write_csv", type=bool, default=True, help="If true record histogram values in a CSV file in the output directory") + ap.add_argument("--plot", type=bool, default=True, help="Whether to plot and save histograms") + ap.add_argument("--divide-radial", type=bool, default=False, help="Whether to divide segments radially into 4 layers") + args = ap.parse_args() + + # Resolve config/base + if args.input.suffix.lower() == ".conf": + params = read_conf_file(args.input) + # When a .conf is provided, image data (histograms) live under OUTPUT_PATH/ + output_base = Path(params.get("OUTPUT_PATH")) + images_path = str(output_base / args.hist_type) + cfg_axis = params.get("AXIS_POINTS", []) + # Place output in existing file structure + output_base = Path(params.get("OUTPUT_PATH")) + default_out = output_base / "Analysis" + elif args.input.is_dir(): + images_path = str(args.input) + cfg_axis = [] + default_out = Path("./aha_histograms") + else: + raise ValueError("Input must be a .conf or a directory") + + ## Use requested output directory or default + outdir = args.outdir if args.outdir is not None else default_out + outdir.mkdir(parents=True, exist_ok=True) + + # HA directory discovery + ha_dir = Path(images_path) # fallback + ha_rdr = DataReader(ha_dir) + + # Axis points + if args.axis_points: + try: + p1s, p2s = args.axis_points.split(";") + axis_points = [tuple(map(float, p1s.split(","))), tuple(map(float, p2s.split(",")))] + except Exception: + raise ValueError("--axis-points must be 'z1,y1,x1;z2,y2,x2'") + else: + axis_points = cfg_axis if cfg_axis else None + + # Septum + if args.septum: + sept = tuple(map(float, args.septum.split(","))) + else: + # interactive picker (will open a matplotlib window) + sept = utils.get_septum_point(str(args.lv_mask)) + + if axis_points is None or len(axis_points) < 2: + raise ValueError("Axis points must be provided either in .conf or via --axis-points") + + print("Creating AHA mask") + # Made at the same scale as the LV mask + # Radial map controls whether or not transmural depth is divided into 4 + if args.divide_radial: + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), axis_points, sept, str(images_path), 1, return_radial_map=True + ) + seg_map_to_use = seg_radial_map + else: + seg_map = utils.create_aha_mask( + str(args.lv_mask), axis_points, sept, str(images_path), 1, return_radial_map=False + ) + seg_map_to_use = seg_map + + # Resample segment map to HA reader shape + target_shape = tuple(ha_rdr.shape) + seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0, TwoD=False, is_mask=False) + + ## Find slices with data - only open these + slice_has_data = np.any(seg_resampled != 0, axis=(1, 2)) + start= np.argmax(slice_has_data) + end = len(slice_has_data) - 1 - np.argmax(slice_has_data[::-1]) + + # Use histogram utility to compute per-segment 0-255 bins from the DataReader + print("Computing per-segment histograms") + bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) + + if unique_segments is None: + print("No segments found in segment map, exiting.") + return + + # Write histogram data to a csv file for future analysis + if args.write_csv: + csv_filename = outdir / 'histogram.csv' + fieldnames = ( + ['VALUE'] + + [f'SEGMENT-{zone}' + for zone in unique_segments] + ) + entries = [] + for value in range(256): # histogram bins + row = {'VALUE': value} + for i, seg in enumerate(unique_segments): # segments + row[f'SEGMENT-{seg}'] = bins[i, value] + entries.append(row) + + with open(csv_filename, mode='w', newline='') as file: + writer = csv.DictWriter(file, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(entries) + + # PLot per-segment histogram + if args.plot: + # Build an array for 17 AHA segments. If radial subdivision is present + # (4 layers per segment) aggregate the four radial parts into the + # corresponding base AHA segment. + bins17 = np.zeros((17, bins.shape[1]), dtype=bins.dtype) + if args.divide_radial: + # unique_segments are expected to contain labels like 11,12,13,14 + # for segment 1, and 101..104 for segment 10. Map by arithmetic: + # base_label = segment * 10, radial parts = base_label + 1..4 + unique_ints = [int(u) for u in unique_segments] + for s in range(1, 18): + base = s * 10 + for r in range(1, 5): + label = base + r + if label in unique_ints: + idx = unique_ints.index(label) + bins17[s - 1] += bins[idx] + else: + for i, s in enumerate(unique_segments): + if 1 <= int(s) <= 17: + bins17[int(s) - 1] = bins[i] + + # Plot each segment histogram + for seg_id in range(1, 18): + fig = utils.plot_segment_histogram( + bins17, + segments=[seg_id], + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=False, + circular_mean=False, + xlab='HA (deg)', + ylab='Frequency', + title=f'AHA Segment {seg_id} HA histogram' + ) + + out_png = outdir / f"hist_AHA_segment_{seg_id}.png" + out_pdf = outdir / f"hist_AHA_segment_{seg_id}.pdf" + fig.savefig(out_png, bbox_inches="tight") + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + print(f"Saved segment {seg_id} histograms to {out_png} / {out_pdf}") + + print(f"Done. Figures in {outdir}") + + +if __name__ == "__main__": + script() From ed8f0b4e5ebdbc855b63f58d157c21f3cdead553 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Thu, 18 Jun 2026 17:00:08 +0100 Subject: [PATCH 02/11] Added Histogram of RV segments Plots are still failing, but csv writes correctly so downstream analysis can still be done without recomputing histogram. --- src/cardiotensor/analysis/analysis_utils.py | 981 +++++++++++++++++- .../scripts/analysis_histograms_aha.py | 47 +- .../scripts/analysis_histograms_aha_rv.py | 322 ++++++ .../scripts/analysis_transmural.py | 178 ++++ 4 files changed, 1510 insertions(+), 18 deletions(-) create mode 100644 src/cardiotensor/scripts/analysis_histograms_aha_rv.py create mode 100644 src/cardiotensor/scripts/analysis_transmural.py diff --git a/src/cardiotensor/analysis/analysis_utils.py b/src/cardiotensor/analysis/analysis_utils.py index 58dde3d0..52f8823b 100644 --- a/src/cardiotensor/analysis/analysis_utils.py +++ b/src/cardiotensor/analysis/analysis_utils.py @@ -15,7 +15,8 @@ import cv2 -from matplotlib.patches import Wedge +from matplotlib.patches import Wedge, Circle +from matplotlib.patches import Patch from scipy.stats import circmean, circstd from scipy.ndimage import gaussian_filter1d @@ -32,6 +33,8 @@ from sklearn.metrics import r2_score +import pyvista as pv + def get_septum_point(lv_mask): """ @@ -100,6 +103,81 @@ def onclick(event): return clicked[0] + + +def get_RV_mask(MV, AX, heart_mask, lv_mask): + + """Return the right-ventricle mask (heart_mask minus lv_mask), + clipped by the plane perpendicular to the long-axis vector that + intersects the mitral valve point `MV`. + + Parameters + ---------- + MV, AX : array-like + Mitral valve and apex points (z,y,x) in same coordinate system as masks. + heart_mask : ndarray or path-like + Whole-heart mask volume or path to folder (will be resampled to lv_mask shape). + lv_mask : ndarray + Left-ventricle mask volume. + + Returns + ------- + rv_mask : ndarray + Binary mask of the RV clipped at the MV plane (voxels on the "apex" + side of the MV are kept). + """ + + axis_vec = np.asarray(MV, dtype=float) - np.asarray(AX, dtype=float) + axis_vec = axis_vec / np.linalg.norm(axis_vec) + + # Ensure masks have same shape + if heart_mask.shape != lv_mask.shape: + heart_mask = resample(heart_mask, target_shape=lv_mask.shape, order=0, TwoD=False) + + # RV = heart - LV (assumes binary masks) + rv_mask = (heart_mask > 0).astype(np.uint8) - (lv_mask > 0).astype(np.uint8) + rv_mask = np.clip(rv_mask, 0, 1).astype(np.uint8) + + # Clip RV mask at plane through MV with normal axis_vec + # Build coordinates of all voxels (z,y,x) + nz, ny, nx = rv_mask.shape + zz, yy, xx = np.meshgrid(np.arange(nz), np.arange(ny), np.arange(nx), indexing='ij') + coords = np.stack([zz, yy, xx], axis=-1).reshape(-1, 3) + + # Compute signed distance along axis_vec from MV + MV = np.asarray(MV, dtype=float) + rel = coords - MV + signed = rel @ axis_vec + + # Keep voxels on apex side of MV (signed <= 0) + keep = signed <= 0 + + rv_flat = rv_mask.ravel() + rv_flat[~keep] = 0 + rv_mask = rv_flat.reshape(rv_mask.shape) + + # ------------------------------------------------------------ + # 3D mesh of mask + vol_pad = np.pad(rv_mask.astype(np.uint8), 1, mode='constant') + verts, faces, norms, vals = measure.marching_cubes(vol_pad, 0.5) + + faces = np.hstack([np.full((faces.shape[0],1),3), faces]).astype(np.int64) + mesh = pv.PolyData(verts, faces) + + # ------------------------------------------------------------ + # Plot + pl = pv.Plotter() + pl.add_mesh(mesh, color="lightgray", opacity=0.6) + + pl.add_axes() + pl.show_grid() + pl.show() + + + return rv_mask + + + def load_volume(img_dir): #Load TIFF/JP2 stack into 3D numpy array files = sorted([f for f in os.listdir(img_dir) if f.lower().endswith(('.tif','.tiff','.jp2'))]) @@ -118,8 +196,597 @@ def create_aha_mask( axis_points, septum_point, images_path, - aha_factor, return_radial_map=False, + additional_downsample=1, + rv=False, + rv_mask_path=None, + heart_mask_path=None +): + """ + Create a 17-segment AHA mask from an LV mask. + + Parameters + ---------- + lv_mask_path : str + Path to LV mask volume. + axis_points : list + [MV_point, Apex_point] from config file. + septum_point : array-like + Septum reference point. + images_path : str + Path to image stack (used to determine downsampling). + return_radial_map : bool, optional + If True, also returns the radial subdivision map. + + Returns + ------- + segment_map : ndarray + 17-segment AHA mask. + segment_radial_map : ndarray, optional + Segment map with radial quartiles encoded as seg*10 + radial_group. + """ + + # -------------------------------------------------- + # Determine downsampling + # -------------------------------------------------- + files_lv = sorted( + f for f in os.listdir(lv_mask_path) + if f.lower().endswith((".tif", ".tiff", ".jp2")) + ) + files_img = sorted( + f for f in os.listdir(images_path) + if f.lower().endswith((".tif", ".tiff", ".jp2")) + ) + + # Avoid zero division or zero scaling when image and mask slice counts differ greatly. + # Compute ratio and ensure integer scaling factor >= 1 + mask_ratio = float(len(files_img)) / max(1, float(len(files_lv))) + mask_factor = max(1, int(round(mask_ratio))) + + # Compute downsample as aha_factor / mask_factor, at least 1 + try: + downsample = int(max(1, round(float(additional_downsample) * float(mask_factor)))) + except Exception: + downsample = mask_factor + + # -------------------------------------------------- + # Load and resample LV mask + # -------------------------------------------------- + lv_mask_vol = load_volume(lv_mask_path) + lv_mask_vol_d = resample( + lv_mask_vol, + zoom=1 / additional_downsample, + order=0, + ) + + # -------------------------------------------------- + # Long-axis definition + # -------------------------------------------------- + MV_d = np.array(axis_points[0])[::-1] / downsample + Apex_d = np.array(axis_points[1])[::-1] / downsample + + axis_vec = MV_d - Apex_d + axis_vec /= np.linalg.norm(axis_vec) + + coords = np.array(np.nonzero(lv_mask_vol_d)).T + centroid = (MV_d + Apex_d) / 2 + + septum_point = np.asarray(septum_point) / additional_downsample + + # -------------------------------------------------- + # Create RV mask if requested + # -------------------------------------------------- + if rv== True: + if rv_mask_path is None: + if heart_mask_path is None: + raise ValueError("If rv=True, either rv_mask or heart_mask must be provided.") + else: + heart_mask = load_volume(heart_mask_path) + rv_mask = get_RV_mask(MV_d, Apex_d, heart_mask, lv_mask_vol_d) + else: + rv_mask = load_volume(rv_mask_path) + # Ensure rv_mask has same shape as lv_mask_vol_ + if rv_mask.shape != lv_mask_vol_d.shape: + rv_mask = resample(rv_mask, target_shape=lv_mask_vol_d.shape, order=0, TwoD=False, is_mask=True) + + + # -------------------------------------------------- + # Long-axis projections + # -------------------------------------------------- + projections = coords @ axis_vec + + # Discard extreme percentiles to guard againts noise and outliers in the mask + pmin = np.percentile(projections, 2) + pmax = np.percentile(projections, 98) + length = pmax - pmin + + basal_thresh = pmin + 2 * length / 3.0 + mid_thresh = pmin + length / 3.0 + + # -------------------------------------------------- + # Septum reference angle + # -------------------------------------------------- + septum_vec = septum_point - centroid + + pts2d, u, v = project_to_plane( + coords, + centroid, + axis_vec, + ) + + septum_point2d = np.array([ + np.dot(septum_vec, u), + np.dot(septum_vec, v) + ]) + + ref_angle = np.arctan2( + septum_point2d[1], + septum_point2d[0] + ) + + angles = np.arctan2(pts2d[:, 1], pts2d[:, 0]) + + angles_rel = (angles - ref_angle) % (2 * np.pi) + angles_rel = (angles_rel + 2 * np.pi / 3) % (2 * np.pi) + + # -------------------------------------------------- + # Create segment map + # -------------------------------------------------- + segment_map = np.zeros( + lv_mask_vol_d.shape, + dtype=np.uint16 + ) + + def assign_segment(mask_idx, seg): + segment_map[tuple(coords[mask_idx].T)] = seg + + basal_idx = np.where(projections >= basal_thresh)[0] + + mid_idx = np.where( + (projections >= mid_thresh) & + (projections < basal_thresh) + )[0] + + apical_idx = np.where( + (projections < mid_thresh) & + (projections >= pmin + 0.02 * length) + )[0] + + apex_idx = np.where( + projections < (pmin + 0.02 * length) + )[0] + + def sectors_from_indices(indices, n_sectors, start_seg): + sector_width = 2 * np.pi / n_sectors + + for s in range(n_sectors): + a0 = s * sector_width + a1 = (s + 1) * sector_width + + mask_idx = indices[ + (angles_rel[indices] >= a0) & + (angles_rel[indices] < a1) + ] + + assign_segment(mask_idx, start_seg + s) + + # Basal: 1–6 + sectors_from_indices(basal_idx, 6, 1) + + # Mid: 7–12 + sectors_from_indices(mid_idx, 6, 7) + + # Apical: 13–16 + sector_width = 2 * np.pi / 4 + + for s in range(4): + a0 = s * sector_width + a1 = (s + 1) * sector_width + + mask_idx = apical_idx[ + (angles_rel[apical_idx] >= a0) & + (angles_rel[apical_idx] < a1) + ] + + assign_segment(mask_idx, 13 + s) + + # Apex: 17 + if apex_idx.size > 0: + assign_segment(apex_idx, 17) + + + # ================================================== + # RV segmentation (segments 18-26) + # ================================================== + + if rv: + + rv_coords = np.array(np.nonzero(rv_mask)).T + + if len(rv_coords) > 0: + + # ------------------------------------------ + # Long-axis coordinate + # ------------------------------------------ + + rv_proj = rv_coords @ axis_vec + + rv_pmin = np.percentile(rv_proj, 2) + rv_pmax = np.percentile(rv_proj, 98) + + mid_proj = 0.5 * (rv_pmin + rv_pmax) + + rv_length = rv_pmax - rv_pmin + + rv_basal_thresh = rv_pmin + 2 * rv_length / 3 + rv_mid_thresh = rv_pmin + rv_length / 3 + + # ------------------------------------------ + # Short-axis anatomical basis + # ------------------------------------------ + + long_axis = axis_vec + + lv_vec = septum_vec + + # project LV direction into short-axis plane + e0 = ( + lv_vec + - np.dot(lv_vec, long_axis) * long_axis + ) + + e0 /= np.linalg.norm(e0) + + # perpendicular direction in short-axis plane + e1 = np.cross(long_axis, e0) + e1 /= np.linalg.norm(e1) + + # ------------------------------------------ + # RV angular coordinate + # ------------------------------------------ + + #rv_centroid = rv_coords.mean(axis=0) + + rv_centroid = ( + septum_point + + ( + mid_proj + - np.dot(septum_point, long_axis) + ) * long_axis + ) + + rv_rel = rv_coords - rv_centroid + + x = rv_rel @ e1 + y = rv_rel @ e0 + + rv_angles = np.arctan2(y, x) + rv_angles = rv_angles % (2 * np.pi) + + # ------------------------------------------ + # Longitudinal regions + # ------------------------------------------ + + rv_basal_idx = np.where( + rv_proj >= rv_basal_thresh + )[0] + + rv_mid_idx = np.where( + (rv_proj >= rv_mid_thresh) & + (rv_proj < rv_basal_thresh) + )[0] + + rv_apical_idx = np.where( + rv_proj < rv_mid_thresh + )[0] + + # ------------------------------------------ + # Sector assignment + # ------------------------------------------ + + def assign_rv_region( + indices, + start_seg + ): + """ + Six 60° sectors are first defined. + + sector 0 -> seg 1 + sector 1 -> seg 2 + sector 2 -> seg 3 + + sector 3 + half sector 4 -> seg 3 + + half sector 4 + sector 5 -> seg 1 + """ + + if len(indices) == 0: + return + + theta = rv_angles[indices] + + seg_local = np.full( + theta.shape, + -1, + dtype=np.int32 + ) + + pi3 = np.pi / 3 + + + # sector 0 + seg_local[ + (theta >= 0) & + (theta < pi3) + ] = 0 + + # sector 1 + seg_local[ + (theta >= pi3) & + (theta < 2*pi3) + ] = 1 + + # sector 2 + seg_local[ + (theta >= 2*pi3) & + (theta < 3*pi3) + ] = 2 + + # sector 3 + first half sector 4 + seg_local[ + (theta >= 3*pi3) & + (theta < 4.5*pi3) + ] = 2 + + # second half sector 4 + sector 5 + seg_local[ + (theta >= 4.5*pi3) & + (theta < 6*pi3) + ] = 0 + + for local_seg in range(3): + + mask_idx = indices[ + seg_local == local_seg + ] + + if len(mask_idx) == 0: + continue + + segment_map[ + tuple(rv_coords[mask_idx].T) + ] = start_seg + local_seg + + # basal: 18-20 + assign_rv_region( + rv_basal_idx, + 18 + ) + + # mid: 21-23 + assign_rv_region( + rv_mid_idx, + 21 + ) + + # apical: 24-26 + assign_rv_region( + rv_apical_idx, + 24 + ) + + # -------------------------------------------------- + # Radial quartile subdivision + # -------------------------------------------------- + + if return_radial_map: + dists = np.linalg.norm(coords - centroid, axis=1) + + lv_segment_radial_map = np.zeros_like( + segment_map, + dtype=np.uint16 + ) + + for seg_id in range(1, 18): + + seg_idx = np.where( + segment_map[tuple(coords.T)] == seg_id + )[0] + + if len(seg_idx) == 0: + continue + + seg_dists = dists[seg_idx] + + q25, q50, q75 = np.percentile( + seg_dists, + [25, 50, 75] + ) + + for voxel_idx, d in zip(seg_idx, seg_dists): + + if d <= q25: + radial_group = 1 + elif d <= q50: + radial_group = 2 + elif d <= q75: + radial_group = 3 + else: + radial_group = 4 + + lv_segment_radial_map[ + tuple(coords[voxel_idx]) + ] = seg_id * 10 + radial_group + + if rv: + + rv_dists = np.linalg.norm(rv_coords - rv_centroid, axis=1) + + rv_segment_radial_map = np.zeros_like( + segment_map, + dtype=np.uint16 + ) + + for seg_id in range(18, 27): + + seg_idx = np.where( + segment_map[tuple(rv_coords.T)] == seg_id + )[0] + + if len(seg_idx) == 0: + continue + + seg_dists = rv_dists[seg_idx] + + q25, q50, q75 = np.percentile( + seg_dists, + [25, 50, 75] + ) + + for voxel_idx, d in zip(seg_idx, seg_dists): + + if d <= q25: + radial_group = 1 + elif d <= q50: + radial_group = 2 + elif d <= q75: + radial_group = 3 + else: + radial_group = 4 + + rv_segment_radial_map[ + tuple(rv_coords[voxel_idx]) + ] = seg_id * 10 + radial_group + + # Combine LV and RV radial maps + segment_radial_map = lv_segment_radial_map + rv_segment_radial_map + + else: + segment_radial_map = lv_segment_radial_map + + #---------------------------------------------- + # Visualisation + #---------------------------------------------- + + if rv: + max_seg = 26 + else: + max_seg = 17 + + def _get_segment_colors(n): + # Prefer a categorical colormap for up to 20 colors, fall back to HSV for more + try: + if n <= 20: + cmap = plt.get_cmap('tab20', n) + colors = cmap(np.linspace(0, 1, n, endpoint=False))[:, :3] + else: + colors = plt.cm.hsv(np.linspace(0, 1, n, endpoint=False))[:, :3] + except Exception: + colors = plt.cm.hsv(np.linspace(0, 1, n, endpoint=False))[:, :3] + return colors + + segment_colors = _get_segment_colors(max_seg) + + n_slices = 20 + + # Step 1: project voxels along long axis + apex_dir = -axis_vec + + # combine LV and RV coordinates if RV exists so projections and + # slice extraction operate on a single coordinate array + if rv: + combined_coords = np.vstack([coords, rv_coords]) + combined_centroid = combined_coords.mean(axis=0) + else: + combined_coords = coords + combined_centroid = centroid + + projections_norm = (combined_coords - combined_centroid) @ apex_dir + slice1 = np.percentile(projections_norm, 2) + slicen = np.percentile(projections_norm, 98) + slice_positions = np.linspace(slice1, slicen, n_slices) + + # Step 2: find two orthonormal vectors perpendicular to apex_dir + v = apex_dir / np.linalg.norm(apex_dir) + if abs(v[0]) < abs(v[1]): + u1 = np.array([0, -v[2], v[1]]) + else: + u1 = np.array([-v[2], 0, v[0]]) + u1 /= np.linalg.norm(u1) + u2 = np.cross(v, u1) + u2 /= np.linalg.norm(u2) + + # Step 3: extract slices + slices_rgb = [] + for s in slice_positions: + + # select voxels near the slice plane (from combined coords) + dist = np.abs(projections_norm - s) + plane_idx = np.where(dist < 2)[0] + plane_coords = combined_coords[plane_idx] + + if len(plane_coords) == 0: + continue + + # project to 2D plane + pts2d = np.column_stack([ + (plane_coords - combined_centroid) @ u1, + (plane_coords - combined_centroid) @ u2 + ]) + x = np.round(pts2d[:,0] - pts2d[:,0].min()).astype(int) + y = np.round(pts2d[:,1] - pts2d[:,1].min()).astype(int) + + # create RGB slice (use float colors in 0-1 range) + shape = (y.max()+1, x.max()+1, 3) + rgb = np.zeros(shape, dtype=float) + # ensure integer indexing into the segment map + seg_idx0 = plane_coords[:, 0].astype(int) + seg_idx1 = plane_coords[:, 1].astype(int) + seg_idx2 = plane_coords[:, 2].astype(int) + seg_ids = segment_map[seg_idx0, seg_idx1, seg_idx2] + for seg_id in range(1, max_seg + 1): + mask = seg_ids == seg_id + if not np.any(mask): + continue + # use only RGB channels (ignore alpha) and values are 0-1 from colormap + rgb[y[mask], x[mask]] = segment_colors[seg_id-1][:3] + slices_rgb.append(rgb) + + # Step 4: plot slices in 2 rows with legend + rows = 2 + cols = (len(slices_rgb)+1)//2 + fig, axes = plt.subplots(rows, cols, figsize=(3*cols, 3*rows)) + axes = axes.flatten() + + for i, rgb in enumerate(slices_rgb): + axes[i].imshow(rgb) + axes[i].set_title(f"Slice {i+1}") + axes[i].axis('off') + + for j in range(i+1, len(axes)): + axes[j].axis('off') + + # Legend + # segment_colors values are floats in 0-1 from the colormap; use RGB channels + patches = [Patch(facecolor=segment_colors[i][:3], label=f"Seg {i+1}") for i in range(max_seg)] + fig.legend(handles=patches, loc='upper right', bbox_to_anchor=(1.1, 0.95), title="AHA Segments") + + plt.tight_layout() + plt.show() + + if not return_radial_map: + return segment_map, None + + return segment_map, segment_radial_map + + +def create_aha_mask_17( + lv_mask_path, + axis_points, + septum_point, + images_path, + return_radial_map=False, + additional_downsample=1 ): """ Create a 17-segment AHA mask from an LV mask. @@ -134,8 +801,6 @@ def create_aha_mask( Septum reference point. images_path : str Path to image stack (used to determine downsampling). - aha_factor : float - AHA scaling factor. return_radial_map : bool, optional If True, also returns the radial subdivision map. @@ -166,9 +831,9 @@ def create_aha_mask( # Compute downsample as aha_factor / mask_factor, at least 1 try: - downsample = int(max(1, round(float(aha_factor) / float(mask_factor)))) + downsample = int(max(1, round(float(additional_downsample) * float(mask_factor)))) except Exception: - downsample = 1 + downsample = mask_factor # -------------------------------------------------- # Load and resample LV mask @@ -176,15 +841,15 @@ def create_aha_mask( lv_mask_vol = load_volume(lv_mask_path) lv_mask_vol_d = resample( lv_mask_vol, - zoom=1 / downsample, + zoom=1 / additional_downsample, order=0, ) # -------------------------------------------------- # Long-axis definition # -------------------------------------------------- - MV_d = np.array(axis_points[0])[::-1] / aha_factor - Apex_d = np.array(axis_points[1])[::-1] / aha_factor + MV_d = np.array(axis_points[0])[::-1] / downsample + Apex_d = np.array(axis_points[1])[::-1] / downsample axis_vec = MV_d - Apex_d axis_vec /= np.linalg.norm(axis_vec) @@ -192,7 +857,7 @@ def create_aha_mask( coords = np.array(np.nonzero(lv_mask_vol_d)).T centroid = (MV_d + Apex_d) / 2 - septum_point = np.asarray(septum_point) + septum_point = np.asarray(septum_point) / additional_downsample # -------------------------------------------------- # Long-axis projections @@ -342,8 +1007,89 @@ def sectors_from_indices(indices, n_sectors, start_seg): tuple(coords[voxel_idx]) ] = seg_id * 10 + radial_group + n_slices = 20 + + # 17-segment discrete colours (RGB) + segment_colors = np.array([ + [166,206,227],[31,120,180],[178,223,138],[51,160,44],[251,154,153], + [227,26,28],[253,191,111],[255,127,0],[202,178,214],[106,61,154], + [255,255,153],[177,89,40],[141,211,199],[255,255,179],[190,186,218], + [251,128,114],[128,177,211] + ], dtype=np.uint8) + + # Step 1: project voxels along long axis + + apex_dir = -axis_vec + + projections_norm = (coords - centroid) @ apex_dir + slice1 = np.percentile(projections_norm, 2) + slicen = np.percentile(projections_norm, 98) + slice_positions = np.linspace(slice1, slicen, n_slices) + + # Step 2: find two orthonormal vectors perpendicular to apex_dir + v = apex_dir / np.linalg.norm(apex_dir) + if abs(v[0]) < abs(v[1]): + u1 = np.array([0, -v[2], v[1]]) + else: + u1 = np.array([-v[2], 0, v[0]]) + u1 /= np.linalg.norm(u1) + u2 = np.cross(v, u1) + u2 /= np.linalg.norm(u2) + + # Step 3: extract slices + slices_rgb = [] + for s in slice_positions: + + # select voxels near the slice plane + dist = np.abs(projections_norm - s) + plane_idx = np.where(dist < 2)[0] + plane_coords = coords[plane_idx] + + if len(plane_coords) == 0: + continue + + # project to 2D plane + pts2d = np.column_stack([ + (plane_coords - centroid) @ u1, + (plane_coords - centroid) @ u2 + ]) + x = np.round(pts2d[:,0] - pts2d[:,0].min()).astype(int) + y = np.round(pts2d[:,1] - pts2d[:,1].min()).astype(int) + + # create RGB slice + shape = (y.max()+1, x.max()+1, 3) + rgb = np.zeros(shape, dtype=np.uint16) + seg_ids = segment_map[plane_coords[:,0], plane_coords[:,1], plane_coords[:,2]] + for seg_id in range(1, 18): + mask = seg_ids == seg_id + rgb[y[mask], x[mask]] = segment_colors[seg_id-1] + slices_rgb.append(rgb) + + # Step 4: plot slices in 2 rows with legend + rows = 2 + cols = (len(slices_rgb)+1)//2 + fig, axes = plt.subplots(rows, cols, figsize=(3*cols, 3*rows)) + axes = axes.flatten() + + for i, rgb in enumerate(slices_rgb): + axes[i].imshow(rgb) + axes[i].set_title(f"Slice {i+1}") + axes[i].axis('off') + + for j in range(i+1, len(axes)): + axes[j].axis('off') + + # Legend + patches = [Patch(facecolor=segment_colors[i]/255, label=f"Seg {i+1}") for i in range(17)] + fig.legend(handles=patches, loc='upper right', bbox_to_anchor=(1.1, 0.95), title="AHA Segments") + + plt.tight_layout() + plt.show() + return segment_map, segment_radial_map + + def resample( vol, target_shape=None, @@ -799,6 +1545,61 @@ def ResliceMultipleSlices(vector, centers, in_folder=None, stack=None): return slices, geometries + + +def GetResliceGeometry(vector, centers, in_folder=None, stack=None): + n, perp1, perp2 = newAxes(vector) + centers = np.array(centers, dtype=float) + + # --- Load volume slab if folder is provided --- + if in_folder is not None: + files = sorted( + f for f in os.listdir(in_folder) + if f.lower().endswith(('.png', '.jpg', '.tif', '.tiff')) + ) + im0 = imread(os.path.join(in_folder, files[0])) + depth, height, width = len(files), *im0.shape + dimensions = [depth, height, width] + + # Determine slice output size + out_d, out_h, out_w = newDimensions(n, dimensions) + + # Determine Z slab needed to cover all slices + z_offsets = ( + abs(perp1[0]) * (out_w / 2) + + abs(perp2[0]) * (out_h / 2) + ) + + z_min = int(np.floor(np.min(centers[:, 0]) - z_offsets)) + z_max = int(np.ceil(np.max(centers[:, 0]) + z_offsets)) + + z_min_clamped = max(0, z_min) + z_max_clamped = min(depth - 1, z_max) + + else: + depth, height, width = stack.shape + dimensions = [depth, height, width] + out_d, out_h, out_w = newDimensions(n, dimensions) + + geometries = [] + + # --- Reslice each center --- + for c_new in centers: + slice_geometry = { + "slice_center_3d": c_new.astype(float), + "axis_x_3d": perp1.astype(float), + "axis_y_3d": (-perp2).astype(float), + "normal_3d": n.astype(float), + "width": out_w, + "height": out_h, + "z_slab": (z_min_clamped, z_max_clamped), + } + geometries.append(slice_geometry) + + return geometries + + + # Two vector reslice for long axis - septum point and MV axis def Reslice3Points(p1, p2, p3, in_folder=None, stack=None): """ @@ -2238,13 +3039,25 @@ def plot_segment_histogram( circular_mean=False, xlab = 'Value', ylab = 'Count', - title=None + title=None, + divide_radial=False, ): # -------------------- # Combine selected segments # -------------------- - seg_idx = [s - 1 for s in segments] + if divide_radial: + ##divide radial must be true + seg_idx = [] + for s in segments: + base = s // 10 + r = s % 10 + idx = (base - 1) * 4 + r -1 + seg_idx.append(idx) + + else: + seg_idx = [s - 1 for s in segments] + hist = bins[seg_idx].sum(axis=0) # Crop histogram to negate masking artifacts @@ -2558,6 +3371,150 @@ def polar_to_xy(r, theta_deg): return fig, ax +def bullseye_plot_ext( + all_values, + value_range=(-90, 90), + cmap="viridis", + title=" ", + figsize=(8, 8), +): + """ + Publication-grade AHA LV + RV schematic matching clinical 26-segment layout. + """ + + all_values = np.asarray(all_values) + if all_values.size != 26: + raise ValueError("all_values must have 26 elements") + + lv_values = all_values[:17] + rv_values = all_values[17:26] + + if lv_values.size != 17: + raise ValueError("lv_values must have 17 elements") + if rv_values.size != 9: + raise ValueError("rv_values must have 9 elements") + + cmap = plt.cm.get_cmap(cmap) + norm = plt.Normalize(*value_range) + + fig, ax = plt.subplots(figsize=figsize) + ax.set_aspect("equal") + + # ------------------------------------------------------- + # Helper + # ------------------------------------------------------- + def add_wedge(r_in, r_out, t1, t2, val): + color = cmap(norm(val)) if not np.isnan(val) else "lightgray" + ax.add_patch( + Wedge( + (0, 0), + r_out, + t1, + t2, + width=r_out - r_in, + facecolor=color, + edgecolor="white", + linewidth=1.5, + ) + ) + + # ------------------------------------------------------- + # LV geometry (standard AHA bullseye) + # ------------------------------------------------------- + r_apex, r_mid, r_basal, r_outer = 1.0, 2.0, 3.0, 4.0 + + angles = np.linspace(60, 420, 7) + + # basal + mid + for i in range(6): + add_wedge(r_basal, r_outer, angles[i], angles[i + 1], lv_values[i]) + add_wedge(r_mid, r_basal, angles[i], angles[i + 1], lv_values[6 + i]) + + # apical ring + angles_apex = np.linspace(45, 405, 5) + for i in range(4): + add_wedge( + r_apex, + r_mid, + angles_apex[i], + angles_apex[i + 1], + lv_values[12 + i], + ) + + # apex + ax.add_patch( + Circle( + (0, 0), + r_apex, + facecolor=cmap(norm(lv_values[16])), + edgecolor="white", + linewidth=1.5, + ) + ) + + # ------------------------------------------------------- + # RV geometry (CURVED ATTACHMENT — matches your image) + # ------------------------------------------------------- + + # RV occupies septal side of LV basal ring (~180° arc) + rv_start = 120 # adjust if your septum orientation differs + rv_end = 240 + + rv_angles = np.linspace(rv_start, rv_end, 4) + + r_rv_inner = r_outer + r_rv_outer = r_outer + 1.2 + + # 3 radial levels: basal / mid / apical RV + # each has 3 angular segments + + for level in range(3): + r_in = r_outer + level * 0.4 + r_out = r_outer + (level + 1) * 0.4 + + for i in range(3): + val = rv_values[level * 3 + i] + + add_wedge( + r_in, + r_out, + rv_angles[i], + rv_angles[i + 1], + val, + ) + + # optional labels + theta = np.deg2rad((rv_angles[i] + rv_angles[i + 1]) / 2) + r_text = (r_in + r_out) / 2 + ax.text( + r_text * np.cos(theta), + r_text * np.sin(theta), + str(level * 3 + i + 18), + ha="center", + va="center", + fontsize=8, + color="black", + ) + + # ------------------------------------------------------- + # Colorbar + # ------------------------------------------------------- + sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap) + sm.set_array([]) + + cax = fig.add_axes([0.88, 0.15, 0.03, 0.7]) + plt.colorbar(sm, cax=cax).set_label("Value") + + # ------------------------------------------------------- + # Layout + # ------------------------------------------------------- + ax.set_xlim(-4.5, 5.5) + ax.set_ylim(-4.5, 4.5) + ax.axis("off") + ax.set_title(title) + + return fig, ax + ## CLAHE for image visualisation def auto_contrast(image, plo=2, phigh=98, clip_limit=0.03): diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index db088691..374edc88 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -33,6 +33,9 @@ def script() -> None: ap.add_argument("--write_csv", type=bool, default=True, help="If true record histogram values in a CSV file in the output directory") ap.add_argument("--plot", type=bool, default=True, help="Whether to plot and save histograms") ap.add_argument("--divide-radial", type=bool, default=False, help="Whether to divide segments radially into 4 layers") + ap.add_argument("--mask_downsample", type=int, default=1, help="Downsampling factor for the LV mask to speed up processing (default: 1, no downsampling)") + ap.add_argument("--rv", type=bool, default=False, help="Whether to include RV segments (1-26) in the analysis (default: False, only LV segments 1-17)") + ap.add_argument("--rv-mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") args = ap.parse_args() # Resolve config/base @@ -82,16 +85,48 @@ def script() -> None: print("Creating AHA mask") # Made at the same scale as the LV mask + # RV is optional, if mask not provided the RV will be ignored # Radial map controls whether or not transmural depth is divided into 4 + if args.rv: + if args.rv_mask == None: + # Calculate an RV mask from the myomapping mask and the LV + heart_mask = params.get("HEART_MASK", None) + + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + rv=True, + heart_mask_path=heart_mask + ) + else: + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + rv=True, + rv_mask_path=str(args.rv_mask) + ) + + else: + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + ) + if args.divide_radial: - seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), axis_points, sept, str(images_path), 1, return_radial_map=True - ) seg_map_to_use = seg_radial_map else: - seg_map = utils.create_aha_mask( - str(args.lv_mask), axis_points, sept, str(images_path), 1, return_radial_map=False - ) seg_map_to_use = seg_map # Resample segment map to HA reader shape diff --git a/src/cardiotensor/scripts/analysis_histograms_aha_rv.py b/src/cardiotensor/scripts/analysis_histograms_aha_rv.py new file mode 100644 index 00000000..bfce66a3 --- /dev/null +++ b/src/cardiotensor/scripts/analysis_histograms_aha_rv.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python3 +""" +analysis_histograms_aha.py + +Compute histograms of angle volumes (HA) per AHA 17-segment map. +Uses `create_aha_mask` and `resample` from `cardiotensor.analysis.analysis_utils`. + +Example: + analysis_histograms_aha.py params.conf --lv-mask /path/to/lv_mask --outdir ./aha_hists +""" + +from __future__ import annotations + +import argparse +from pathlib import Path +import numpy as np +import matplotlib.pyplot as plt + +from cardiotensor.utils.DataReader import DataReader +from cardiotensor.utils.utils import read_conf_file +import cardiotensor.analysis.analysis_utils as utils +import csv +from cardiotensor.colormaps.helix_angle import helix_angle_cmap + + +def script() -> None: + ap = argparse.ArgumentParser(description="AHA-segmented histograms") + ap.add_argument("input", type=Path, help=".conf file or directory to make histogram of") + ap.add_argument("--hist-type", type=str, default="HA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") + ap.add_argument("--lv-mask", type=Path, required=True, help="LV mask directory (slices)") + ap.add_argument("--axis-points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") + ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") + ap.add_argument("--outdir", type=Path, default=None) + ap.add_argument("--write_csv", type=bool, default=True, help="If true record histogram values in a CSV file in the output directory") + ap.add_argument("--plot", type=bool, default=True, help="Whether to plot and save histograms") + ap.add_argument("--divide-radial", type=bool, default=False, help="Whether to divide segments radially into 4 layers") + ap.add_argument("--mask_downsample", type=int, default=1, help="Downsampling factor for the LV mask to speed up processing (default: 1, no downsampling)") + ap.add_argument("--rv", type=bool, default=False, help="Whether to include RV segments (1-26) in the analysis (default: False, only LV segments 1-17)") + ap.add_argument("--rv-mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") + args = ap.parse_args() + + # Resolve config/base + if args.input.suffix.lower() == ".conf": + params = read_conf_file(args.input) + # When a .conf is provided, image data (histograms) live under OUTPUT_PATH/ + output_base = Path(params.get("OUTPUT_PATH")) + images_path = str(output_base / args.hist_type) + cfg_axis = params.get("AXIS_POINTS", []) + # Place output in existing file structure + output_base = Path(params.get("OUTPUT_PATH")) + default_out = output_base / "Analysis" + elif args.input.is_dir(): + images_path = str(args.input) + cfg_axis = [] + default_out = Path("./aha_histograms") + else: + raise ValueError("Input must be a .conf or a directory") + + ## Use requested output directory or default + outdir = args.outdir if args.outdir is not None else default_out + outdir.mkdir(parents=True, exist_ok=True) + + # HA directory discovery + ha_dir = Path(images_path) # fallback + ha_rdr = DataReader(ha_dir) + + # Axis points + if args.axis_points: + try: + p1s, p2s = args.axis_points.split(";") + axis_points = [tuple(map(float, p1s.split(","))), tuple(map(float, p2s.split(",")))] + except Exception: + raise ValueError("--axis-points must be 'z1,y1,x1;z2,y2,x2'") + else: + axis_points = cfg_axis if cfg_axis else None + + # Septum + if args.septum: + sept = tuple(map(float, args.septum.split(","))) + else: + # interactive picker (will open a matplotlib window) + sept = utils.get_septum_point(str(args.lv_mask)) + + if axis_points is None or len(axis_points) < 2: + raise ValueError("Axis points must be provided either in .conf or via --axis-points") + + print("Creating AHA mask") + # Made at the same scale as the LV mask + # RV is optional, if mask not provided the RV will be ignored + # Radial map controls whether or not transmural depth is divided into 4 + if args.rv: + if args.rv_mask == None: + # Calculate an RV mask from the myomapping mask and the LV + heart_mask = params.get("MASK_PATH", None) + + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + rv=True, + heart_mask_path=heart_mask + ) + else: + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + rv=True, + rv_mask_path=str(args.rv_mask) + ) + + else: + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + ) + + if args.divide_radial: + seg_map_to_use = seg_radial_map + else: + seg_map_to_use = seg_map + + # Resample segment map to HA reader shape + target_shape = tuple(ha_rdr.shape) + seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0, TwoD=False, is_mask=False) + + ## Find slices with data - only open these + slice_has_data = np.any(seg_resampled != 0, axis=(1, 2)) + start= np.argmax(slice_has_data) + end = len(slice_has_data) - 1 - np.argmax(slice_has_data[::-1]) + + # Use histogram utility to compute per-segment 0-255 bins from the DataReader + print("Computing per-segment histograms") + bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) + + if unique_segments is None: + print("No segments found in segment map, exiting.") + return + + # Write histogram data to a csv file for future analysis + if args.write_csv: + csv_filename = outdir / 'histogram.csv' + fieldnames = ( + ['VALUE'] + + [f'SEGMENT-{zone}' + for zone in unique_segments] + ) + entries = [] + for value in range(256): # histogram bins + row = {'VALUE': value} + for i, seg in enumerate(unique_segments): # segments + row[f'SEGMENT-{seg}'] = bins[i, value] + entries.append(row) + + with open(csv_filename, mode='w', newline='') as file: + writer = csv.DictWriter(file, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(entries) + + + if args.plot: + + if args.rv: + max_segs = 26 + else: + max_segs = 17 + + + if args.divide_radial: + bins_short = np.zeros((max_segs, bins.shape[1]), dtype=bins.dtype) + + # unique_segments are expected to contain labels like 11,12,13,14 + # for segment 1, and 101..104 for segment 10. Map by arithmetic: + # base_label = segment * 10, radial parts = base_label + 1..4 + unique_ints = [int(u) for u in unique_segments] + for s in range(1, 18): + base = s * 10 + for r in range(1, 5): + label = base + r + if label in unique_ints: + idx = unique_ints.index(label) + bins_short[s - 1] += bins[idx] + else: + bins_short = bins + + + if args.rv: + all_means = utils.segment_means_from_histogram(bins_short, circular=True) + LV_means = all_means[:17] + + ext_bullseye = utils.bullseye_plot_ext(all_means, + title='Helical Angle ', + cmap=helix_angle_cmap + ) + ext_pdf = outdir / "bullseye_ext.pdf" + LV_bullseye.savefig(ext_pdf, bbox_inches="tight") + plt.close(ext_bullseye) + + LV_bullseye = utils.bullseye_plot(LV_means, + title='LV Helical Angle', + cmap=helix_angle_cmap + ) + out_pdf = outdir / "bullseye_LV.pdf" + LV_bullseye.savefig(out_pdf, bbox_inches="tight") + plt.close(LV_bullseye) + + else: + LV_means = utils.segment_means_from_histogram(bins_short, circular=True) + LV_bullseye = utils.bullseye_plot(LV_means, + title='LV Helical Angle', + cmap=helix_angle_cmap + ) + out_pdf = outdir / "bullseye_LV.pdf" + LV_bullseye.savefig(out_pdf, bbox_inches="tight") + plt.close(LV_bullseye) + + lv_segs = [1, 4, 5, 6, 7, 10, 11, 12, 13, 15, 16, 17] + septum_segs = [2, 3, 8, 9, 14] + rv_segs = np.arange(18, 27) + + if args.divide_radial: + + ## LV + base_segs = lv_segs + lv_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + lv_segs.append(label) + + ## Septum + base_segs = septum_segs + septum_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + septum_segs.append(label) + ## RV + if args.rv: + base_segs = rv_segs + rv_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + rv_segs.append(label) + + # Plot overall histogram + fig = utils.plot_segment_histogram( + bins, + segments=lv_segs, + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=True, + circular_mean=True, + xlab='HA (deg)', + ylab='Frequency', + title='LV Histogram', + divide_radial=args.divide_radial + ) + + out_pdf = outdir / "hist_LV.pdf" + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + + + fig = utils.plot_segment_histogram( + bins, + segments=septum_segs, + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=True, + circular_mean=True, + xlab='HA (deg)', + ylab='Frequency', + title='Septum Histogram', + divide_radial=args.divide_radial + ) + + out_pdf = outdir / "hist_septum.pdf" + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + + if args.rv: + fig = utils.plot_segment_histogram( + bins, + segments=rv_segs, + value_range=(-90, 90), + smooth_sigma=0, + normalize=False, + show_mean=True, + circular_mean=True, + xlab='HA (deg)', + ylab='Frequency', + title='RV Histogram', + divide_radial=args.divide_radial + ) + + out_pdf = outdir / "hist_RV.pdf" + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + + + print(f"Done. Figures in {outdir}") + + +if __name__ == "__main__": + script() diff --git a/src/cardiotensor/scripts/analysis_transmural.py b/src/cardiotensor/scripts/analysis_transmural.py new file mode 100644 index 00000000..9537a8ce --- /dev/null +++ b/src/cardiotensor/scripts/analysis_transmural.py @@ -0,0 +1,178 @@ + +from __future__ import annotations + +import argparse +from pathlib import Path +import numpy as np +import matplotlib.pyplot as plt + +from cardiotensor.utils.DataReader import DataReader +from cardiotensor.utils.utils import read_conf_file +import cardiotensor.analysis.analysis_utils as utils +import csv +from cardiotensor.colormaps.helix_angle import helix_angle_cmap + + +def script() -> None: + ap = argparse.ArgumentParser(description="AHA-segmented histograms") + ap.add_argument("input", type=Path, help=".conf file or directory of images to sample") + ap.add_argument("--sample", type=str, default="HA", help="Data for transmural analysis (e.g., 'HA', 'FA', 'IA)") + ap.add_argument("--lv-mask", type=Path, required=True, help="LV mask directory (slices)") + ap.add_argument("--axis-points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") + ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") + ap.add_argument("--outdir", type=Path, default=None) + ap.add_argument("--write_csv", type=bool, default=True, help="If true record intensity profiles in a CSV file in the output directory") + ap.add_argument("--plot", type=bool, default=True, help="Plot mean_intensity profile") + ap.add_argument("--mask_downsample", type=int, default=1, help="Downsampling factor for the LV mask to speed up processing (default: 1, no downsampling)") + ap.add_argument("--nslices", type=int, default=5, help="Number of slices to sample") + ap.add_argument("--slice_idxs", type=int, default=None, help="Specify slice indices for sampling. If not provided, slices will be evenly spaced across the LV mask.") + args = ap.parse_args() + + # Resolve config/base + if args.input.suffix.lower() == ".conf": + params = read_conf_file(args.input) + # When a .conf is provided, image data (histograms) live under OUTPUT_PATH/ + output_base = Path(params.get("OUTPUT_PATH")) + images_path = str(output_base / args.sample) + cfg_axis = params.get("AXIS_POINTS", []) + # Place output in existing file structure + output_base = Path(params.get("OUTPUT_PATH")) + default_out = output_base / "Analysis" + elif args.input.is_dir(): + images_path = str(args.input) + cfg_axis = [] + default_out = Path("./transmral_analysis") + else: + raise ValueError("Input must be a .conf or a directory") + + ## Use requested output directory or default + outdir = args.outdir if args.outdir is not None else default_out + outdir.mkdir(parents=True, exist_ok=True) + + # HA directory discovery + ha_dir = Path(images_path) # fallback + ha_rdr = DataReader(ha_dir) + + # Axis points + if args.axis_points: + try: + p1s, p2s = args.axis_points.split(";") + axis_points = [tuple(map(float, p1s.split(","))), tuple(map(float, p2s.split(",")))] + except Exception: + raise ValueError("--axis-points must be 'z1,y1,x1;z2,y2,x2'") + else: + axis_points = cfg_axis if cfg_axis else None + + # Septum + if args.septum: + sept = tuple(map(float, args.septum.split(","))) + else: + # interactive picker (will open a matplotlib window) + sept = utils.get_septum_point(str(args.lv_mask)) + + if axis_points is None or len(axis_points) < 2: + raise ValueError("Axis points must be provided either in .conf or via --axis-points") + + print("Creating AHA mask") + seg_map, _ = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=False, + additional_downsample=args.mask_downsample, + ) + + # Resample segment map to HA reader shape + target_shape = tuple(ha_rdr.shape) + seg_resampled = utils.resample(seg_map, target_shape=target_shape, order=0, TwoD=False, is_mask=False) + + axis_vec = np.asarray(params['AXIS_POINTS'][0], dtype=float) - np.asarray(params['AXIS_POINTS'][1], dtype=float) + axis_vec = axis_vec / np.linalg.norm(axis_vec) + + mask_factor = np.round(seg_resampled.shape[0] / seg_map.shape[0]) + + if not slice_idxs: + slice_idxs = np.linspace(params['AXIS_POINTS'][0][2], params['AXIS_POINTS'][1][2], 12)[1:-1] + + ## Search for existing reslices + search_dir = outdir / "Analysis" / "Reslices" + search_dir.mkdir(parents=True, exist_ok=True) + + # Ensure slice_idxs is a list + if np.isscalar(slice_idxs): + slice_idxs = [slice_idxs] + slice_idxs = list(slice_idxs) + + # Look for files named like reslice_* in search_dir. Load any found + # and build `slices` as the list of indices missing from search_dir. + slices = [] # indices to gather (not present on disk) + reslices = {} # idx -> loaded array + for idx in slice_idxs: + # Format index for filename matching: prefer integer if close + try: + fidx = int(idx) if float(idx).is_integer() else str(idx) + except Exception: + fidx = str(idx) + + matches = list(search_dir.glob(f"reslice_{fidx}*")) + if matches: + p = matches[0] + try: + if p.suffix.lower() == ".npy": + reslices[idx] = np.load(p) + else: + reslices[idx] = plt.imread(p) + except Exception: + try: + reslices[idx] = np.load(p) + except Exception: + reslices[idx] = None + else: + slices.append(idx) + + + C_news = [] + C_masks = [] + C_reslice = [] + C_done = [] + xm = seg_resampled.shape[2] //2 + ym = seg_resampled.shape[1] //2 + + for i in slice_idxs: + x, y = utils.line_xy_at_z(params['AXIS_POINTS'][0], params['AXIS_POINTS'][1], i) + + C = np.array([i, ym, xm], dtype=float) + P = np.array([i, y, x], dtype=float) + + t = np.dot(P - C, axis_vec) + C_new = C + t * axis_vec + + C_news.append(C_new) + C_masks.append(C_new/mask_factor) + + + if i in slices: + C_reslice.append(C_new) + else: + C_done.append(C_new) + + new_slices, geom = utils.ResliceMultipleSlices(axis_vec, C_reslice, images_path) + + for C_done in zip(C_done): + geo = utils.get_geom(axis_vec, C_reslice, images_path) + + for idx, slice in zip(slices, new_slices): + reslices[idx] = slice + + + + centroids = [] + for s, geom in zip(slice_idxs, geom): + centroid_slice = utils.line_xy_at_z(params['AXIS_POINTS'][0], params['AXIS_POINTS'][1], s) + centroids.append(utils.project_3d_to_slice([s, centroid_slice[1], centroid_slice[0]], geom)) + + t_profiles = {} + t_profiles['PROFILE'], t_profiles['LINES'], t_profiles['SEGMENTS'], t_profiles['INDICES'] = utils.transmuralSampling(C_news, axis_vec, slices=list(reslices.values()), centroids=centroids, mask_factor=mask_factor, seg_map=seg_map, route_slices=slice_idxs) + + \ No newline at end of file From 3c1d395cfabb33ec3ba9c6bcab86fcea6c1626df Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Fri, 19 Jun 2026 15:37:54 +0100 Subject: [PATCH 03/11] Added plot of RV/LV aha model Can plot directly from csv file using draw_aha_model. --- src/cardiotensor/analysis/analysis_utils.py | 340 +------- .../scripts/analysis_histograms_aha.py | 152 +++- .../scripts/analysis_histograms_aha_rv.py | 322 -------- src/cardiotensor/scripts/draw_aha_model.py | 741 ++++++++++++++++++ 4 files changed, 894 insertions(+), 661 deletions(-) delete mode 100644 src/cardiotensor/scripts/analysis_histograms_aha_rv.py create mode 100644 src/cardiotensor/scripts/draw_aha_model.py diff --git a/src/cardiotensor/analysis/analysis_utils.py b/src/cardiotensor/analysis/analysis_utils.py index 52f8823b..beeb67e0 100644 --- a/src/cardiotensor/analysis/analysis_utils.py +++ b/src/cardiotensor/analysis/analysis_utils.py @@ -157,6 +157,7 @@ def get_RV_mask(MV, AX, heart_mask, lv_mask): rv_mask = rv_flat.reshape(rv_mask.shape) # ------------------------------------------------------------ + """ # 3D mesh of mask vol_pad = np.pad(rv_mask.astype(np.uint8), 1, mode='constant') verts, faces, norms, vals = measure.marching_cubes(vol_pad, 0.5) @@ -172,7 +173,7 @@ def get_RV_mask(MV, AX, heart_mask, lv_mask): pl.add_axes() pl.show_grid() pl.show() - + """ return rv_mask @@ -3058,7 +3059,7 @@ def plot_segment_histogram( else: seg_idx = [s - 1 for s in segments] - hist = bins[seg_idx].sum(axis=0) + hist = bins[:, seg_idx].sum(axis=1) # Crop histogram to negate masking artifacts hist[0] = hist[1] @@ -3097,14 +3098,19 @@ def plot_segment_histogram( # -------------------- if show_mean: if circular_mean: - # Convert to radians - scale_rad = np.linspace(0,2*np.pi, 256) - scale_mean_val = np.rad2deg(stats.circmean(scale_rad, weights=hist)) - f = (value_range[1] - value_range[0]) / 360 - cmean_val = scale_mean_val*f + value_range[0] - if cmean_val < value_range[0]: - cmean_val += f*360 - ax.axvline(cmean_val, linestyle='--', linewidth=2, label=f"Circlar Mean = {cmean_val:.2f}") + angles = np.linspace(value_range[0], value_range[1], hist.size, endpoint=False) + theta = np.deg2rad(2*angles) + + z = np.sum(hist * np.exp(1j*theta)) + cmean = np.rad2deg(np.angle(z))/2 + + # wrap into [-90,90) + if cmean < -90: + cmean += 180 + elif cmean >= 90: + cmean -= 180 + + ax.axvline(cmean, linestyle='--', linewidth=2, label=f"Circlar Mean = {cmean:.2f}") mean_val = np.average(x, weights=hist) ax.axvline(mean_val, linestyle='-', linewidth=2, label=f"Mean = {mean_val:.2f}") else: @@ -3115,6 +3121,7 @@ def plot_segment_histogram( plt.show() return fig + def plot_segment_histogram_labels( bins, @@ -3193,14 +3200,13 @@ def plot_segment_histogram_labels( return fig - def segment_means_from_histogram( bins, value_range=(-90, 90), circular=False ): """ - bins : ndarray (17, 256) + bins : ndarray (256, no_segs) Histogram counts per segment value_range : tuple @@ -3211,15 +3217,15 @@ def segment_means_from_histogram( Returns ------- - means : ndarray (17,) + means : dict """ - means = np.full(17, np.nan) + means = {} # Physical x-axis - x = np.linspace(value_range[0], value_range[1], bins.shape[1]) + x = np.linspace(value_range[0], value_range[1], bins.shape[0]) - for s in range(17): - hist = bins[s] + for s in range(bins.shape[1]): + hist = bins[:,s] # Crop histogram to negate masking artifacts hist[0] = hist[1] @@ -3229,309 +3235,15 @@ def segment_means_from_histogram( continue if circular: - scale_rad = np.linspace(0, 2*np.pi, hist.shape[1], endpoint=False) + scale_rad = np.linspace(0, 2*np.pi, len(hist), endpoint=False) scale_mean_val = np.rad2deg(stats.circmean(scale_rad, weights=hist)) f = (value_range[1] - value_range[0]) / 360 cmean_val = scale_mean_val*f + value_range[0] if cmean_val < value_range[0]: cmean_val += f*360 - means[s] = cmean_val + means[s+1] = cmean_val else: - means[s] = np.average(x, weights=hist) + means[s+1] = np.average(x, weights=hist) return means - -def bullseye_plot( - seg_means, - value_range=(-90, 90), - cmap='viridis', - title="Mean HA", - cbar_label="HA Mean", - figsize=(8, 8) -): - """ - Create an AHA-style 17-segment bullseye plot. - - Parameters - ---------- - seg_means : array-like (17,) - Mean value per segment (NaN allowed) - - value_range : tuple - (vmin, vmax) for color normalization - - cmap : str or Colormap - Matplotlib colormap - - title : str - Figure title - - cbar_label : str - Colorbar label - - figsize : tuple - Figure size - - Returns - ------- - fig, ax : matplotlib Figure and Axes - """ - - seg_means = np.asarray(seg_means) - if seg_means.size != 17: - raise ValueError("seg_means must have length 17") - - cmap = plt.cm.get_cmap(cmap) - norm = plt.Normalize(*value_range) - - # -------------------- - # Helpers - # -------------------- - def add_wedge(ax, r_in, r_out, theta1, theta2, value): - color = cmap(norm(value)) if not np.isnan(value) else "lightgray" - w = Wedge( - center=(0, 0), - r=r_out, - theta1=theta1, - theta2=theta2, - width=(r_out - r_in), - facecolor=color, - edgecolor='white', - linewidth=2 - ) - ax.add_patch(w) - - def polar_to_xy(r, theta_deg): - theta = np.deg2rad(theta_deg) - return r * np.cos(theta), r * np.sin(theta) - - # -------------------- - # Figure - # -------------------- - fig, ax = plt.subplots(figsize=figsize, subplot_kw={'aspect': 'equal'}) - - # Radii - r1, r2, r3, r4 = 1.0, 2.0, 3.0, 4.0 - - # -------------------- - # Basal + Mid rings - # -------------------- - angles = np.linspace(60, 420, 7) - - for i in range(6): - add_wedge(ax, r3, r4, angles[i], angles[i+1], seg_means[i]) # basal - add_wedge(ax, r2, r3, angles[i], angles[i+1], seg_means[6 + i]) # mid - - # -------------------- - # Apical ring - # -------------------- - angles_apex = np.linspace(45, 405, 5) - for i in range(4): - add_wedge(ax, r1, r2, angles_apex[i], angles_apex[i+1], seg_means[12 + i]) - - # -------------------- - # Apex - # -------------------- - apex_color = cmap(norm(seg_means[16])) if not np.isnan(seg_means[16]) else "lightgray" - ax.add_patch(plt.Circle((0, 0), r1, color=apex_color, ec='white', lw=2)) - - # -------------------- - # Labels - # -------------------- - for i in range(6): - ax.text(*polar_to_xy(3.5, (angles[i] + angles[i+1]) / 2), - str(i + 1), ha='center', va='center', fontsize=12, color='white') - ax.text(*polar_to_xy(2.5, (angles[i] + angles[i+1]) / 2), - str(7 + i), ha='center', va='center', fontsize=12, color='white') - - for i in range(4): - ax.text(*polar_to_xy(1.5, (angles_apex[i] + angles_apex[i+1]) / 2), - str(13 + i), ha='center', va='center', fontsize=12, color='white') - - ax.text(0, 0, "17", ha='center', va='center', fontsize=14, color='white') - - # -------------------- - # Colorbar - # -------------------- - sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap) - sm.set_array([]) - - cax = fig.add_axes([0.88, 0.15, 0.03, 0.7]) - cbar = plt.colorbar(sm, cax=cax) - cbar.set_label(cbar_label) - - # -------------------- - # Final layout - # -------------------- - ax.set_title(title, fontsize=16) - ax.set_xlim(-4.2, 4.2) - ax.set_ylim(-4.2, 4.2) - ax.axis('off') - - return fig, ax - -def bullseye_plot_ext( - all_values, - value_range=(-90, 90), - cmap="viridis", - title=" ", - figsize=(8, 8), -): - """ - Publication-grade AHA LV + RV schematic matching clinical 26-segment layout. - """ - - all_values = np.asarray(all_values) - if all_values.size != 26: - raise ValueError("all_values must have 26 elements") - - lv_values = all_values[:17] - rv_values = all_values[17:26] - - if lv_values.size != 17: - raise ValueError("lv_values must have 17 elements") - if rv_values.size != 9: - raise ValueError("rv_values must have 9 elements") - - cmap = plt.cm.get_cmap(cmap) - norm = plt.Normalize(*value_range) - - fig, ax = plt.subplots(figsize=figsize) - ax.set_aspect("equal") - - # ------------------------------------------------------- - # Helper - # ------------------------------------------------------- - def add_wedge(r_in, r_out, t1, t2, val): - color = cmap(norm(val)) if not np.isnan(val) else "lightgray" - ax.add_patch( - Wedge( - (0, 0), - r_out, - t1, - t2, - width=r_out - r_in, - facecolor=color, - edgecolor="white", - linewidth=1.5, - ) - ) - - # ------------------------------------------------------- - # LV geometry (standard AHA bullseye) - # ------------------------------------------------------- - r_apex, r_mid, r_basal, r_outer = 1.0, 2.0, 3.0, 4.0 - - angles = np.linspace(60, 420, 7) - - # basal + mid - for i in range(6): - add_wedge(r_basal, r_outer, angles[i], angles[i + 1], lv_values[i]) - add_wedge(r_mid, r_basal, angles[i], angles[i + 1], lv_values[6 + i]) - - # apical ring - angles_apex = np.linspace(45, 405, 5) - for i in range(4): - add_wedge( - r_apex, - r_mid, - angles_apex[i], - angles_apex[i + 1], - lv_values[12 + i], - ) - - # apex - ax.add_patch( - Circle( - (0, 0), - r_apex, - facecolor=cmap(norm(lv_values[16])), - edgecolor="white", - linewidth=1.5, - ) - ) - - # ------------------------------------------------------- - # RV geometry (CURVED ATTACHMENT — matches your image) - # ------------------------------------------------------- - - # RV occupies septal side of LV basal ring (~180° arc) - rv_start = 120 # adjust if your septum orientation differs - rv_end = 240 - - rv_angles = np.linspace(rv_start, rv_end, 4) - - r_rv_inner = r_outer - r_rv_outer = r_outer + 1.2 - - # 3 radial levels: basal / mid / apical RV - # each has 3 angular segments - - for level in range(3): - r_in = r_outer + level * 0.4 - r_out = r_outer + (level + 1) * 0.4 - - for i in range(3): - val = rv_values[level * 3 + i] - - add_wedge( - r_in, - r_out, - rv_angles[i], - rv_angles[i + 1], - val, - ) - - # optional labels - theta = np.deg2rad((rv_angles[i] + rv_angles[i + 1]) / 2) - r_text = (r_in + r_out) / 2 - ax.text( - r_text * np.cos(theta), - r_text * np.sin(theta), - str(level * 3 + i + 18), - ha="center", - va="center", - fontsize=8, - color="black", - ) - - # ------------------------------------------------------- - # Colorbar - # ------------------------------------------------------- - sm = plt.cm.ScalarMappable(norm=norm, cmap=cmap) - sm.set_array([]) - - cax = fig.add_axes([0.88, 0.15, 0.03, 0.7]) - plt.colorbar(sm, cax=cax).set_label("Value") - - # ------------------------------------------------------- - # Layout - # ------------------------------------------------------- - ax.set_xlim(-4.5, 5.5) - ax.set_ylim(-4.5, 4.5) - ax.axis("off") - ax.set_title(title) - - return fig, ax - - -## CLAHE for image visualisation -def auto_contrast(image, plo=2, phigh=98, clip_limit=0.03): - """ - Auto-contrast with percentile clipping and CLAHE for synchrotron images. - """ - image = image.astype(np.float32) - - # percentile clipping - lo, hi = np.percentile(image, (plo, phigh)) - image = np.clip(image, lo, hi) - - # normalize to 0-1 for CLAHE - image = (image - lo) / (hi - lo) - - # CLAHE - image = exposure.equalize_adapthist(image, clip_limit=clip_limit) - - return image - diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index 374edc88..d4630440 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -20,6 +20,9 @@ from cardiotensor.utils.utils import read_conf_file import cardiotensor.analysis.analysis_utils as utils import csv +from cardiotensor.colormaps.helix_angle import helix_angle_cmap + +import draw_aha_model as aha def script() -> None: @@ -90,7 +93,7 @@ def script() -> None: if args.rv: if args.rv_mask == None: # Calculate an RV mask from the myomapping mask and the LV - heart_mask = params.get("HEART_MASK", None) + heart_mask = params.get("MASK_PATH", None) seg_map, seg_radial_map = utils.create_aha_mask( str(args.lv_mask), @@ -166,53 +169,152 @@ def script() -> None: writer.writeheader() writer.writerows(entries) - # PLot per-segment histogram + if args.plot: - # Build an array for 17 AHA segments. If radial subdivision is present - # (4 layers per segment) aggregate the four radial parts into the - # corresponding base AHA segment. - bins17 = np.zeros((17, bins.shape[1]), dtype=bins.dtype) - if args.divide_radial: + + if args.rv: + max_segs = 26 + else: + max_segs = 17 + + if args.divide_radial: + bins_short = np.zeros((bins.shape[0], max_segs), dtype=bins.dtype) + # unique_segments are expected to contain labels like 11,12,13,14 # for segment 1, and 101..104 for segment 10. Map by arithmetic: # base_label = segment * 10, radial parts = base_label + 1..4 unique_ints = [int(u) for u in unique_segments] - for s in range(1, 18): + for s in range(1, max_segs+1): base = s * 10 for r in range(1, 5): label = base + r if label in unique_ints: idx = unique_ints.index(label) - bins17[s - 1] += bins[idx] + bins_short[:,s - 1] += bins[:,idx] + else: + bins_short = bins + + + if args.rv: + all_means = utils.segment_means_from_histogram(bins_short, circular=True) + LV_means = {i: all_means[i] for i in range(1, 18)} + + aha.draw_aha_model(all_means, + model=26, + value_range=(-90,90), + cmap=helix_angle_cmap, + colorbar_label='Mean Helical Angle (°)') + aha.draw_aha_model(LV_means, + model=17, + value_range=(-90,90), + cmap=helix_angle_cmap, + colorbar_label='Mean Helical Angle (°)') + else: - for i, s in enumerate(unique_segments): - if 1 <= int(s) <= 17: - bins17[int(s) - 1] = bins[i] + LV_means = utils.segment_means_from_histogram(bins_short, circular=True) + + aha.draw_aha_model(LV_means, + model=17, + value_range=(-90,90), + cmap=helix_angle_cmap, + colorbar_label='Mean Helical Angle (°)') + + lv_segs = [1, 4, 5, 6, 7, 10, 11, 12, 13, 15, 16, 17] + septum_segs = [2, 3, 8, 9, 14] + rv_segs = np.arange(18, 27) + + if args.divide_radial: + + ## LV + base_segs = lv_segs + lv_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + lv_segs.append(label) + + ## Septum + base_segs = septum_segs + septum_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + septum_segs.append(label) + ## RV + if args.rv: + base_segs = rv_segs + rv_segs = [] + for s in base_segs: + base = s * 10 + for r in range(1, 5): + label = base + r + rv_segs.append(label) + + # Plot overall histogram + fig = utils.plot_segment_histogram( + bins, + segments=lv_segs, + value_range=(-90, 90), + smooth_sigma=0, + normalize=True, + show_mean=True, + circular_mean=True, + xlab='HA (deg)', + ylab='Frequency', + title='LV Histogram', + divide_radial=args.divide_radial + ) + + out_pdf = outdir / "hist_LV.pdf" + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + - # Plot each segment histogram - for seg_id in range(1, 18): + fig = utils.plot_segment_histogram( + bins, + segments=septum_segs, + value_range=(-90, 90), + smooth_sigma=0, + normalize=True, + show_mean=True, + circular_mean=True, + xlab='HA (deg)', + ylab='Frequency', + title='Septum Histogram', + divide_radial=args.divide_radial + ) + + out_pdf = outdir / "hist_septum.pdf" + fig.savefig(out_pdf, bbox_inches="tight") + plt.close(fig) + + if args.rv: fig = utils.plot_segment_histogram( - bins17, - segments=[seg_id], + bins, + segments=rv_segs, value_range=(-90, 90), smooth_sigma=0, - normalize=False, - show_mean=False, - circular_mean=False, + normalize=True, + show_mean=True, + circular_mean=True, xlab='HA (deg)', ylab='Frequency', - title=f'AHA Segment {seg_id} HA histogram' + title='RV Histogram', + divide_radial=args.divide_radial ) - out_png = outdir / f"hist_AHA_segment_{seg_id}.png" - out_pdf = outdir / f"hist_AHA_segment_{seg_id}.pdf" - fig.savefig(out_png, bbox_inches="tight") + out_pdf = outdir / "hist_RV.pdf" fig.savefig(out_pdf, bbox_inches="tight") plt.close(fig) - print(f"Saved segment {seg_id} histograms to {out_png} / {out_pdf}") - print(f"Done. Figures in {outdir}") + + print(f"Done. Figures in {outdir}") if __name__ == "__main__": script() + + + diff --git a/src/cardiotensor/scripts/analysis_histograms_aha_rv.py b/src/cardiotensor/scripts/analysis_histograms_aha_rv.py deleted file mode 100644 index bfce66a3..00000000 --- a/src/cardiotensor/scripts/analysis_histograms_aha_rv.py +++ /dev/null @@ -1,322 +0,0 @@ -#!/usr/bin/env python3 -""" -analysis_histograms_aha.py - -Compute histograms of angle volumes (HA) per AHA 17-segment map. -Uses `create_aha_mask` and `resample` from `cardiotensor.analysis.analysis_utils`. - -Example: - analysis_histograms_aha.py params.conf --lv-mask /path/to/lv_mask --outdir ./aha_hists -""" - -from __future__ import annotations - -import argparse -from pathlib import Path -import numpy as np -import matplotlib.pyplot as plt - -from cardiotensor.utils.DataReader import DataReader -from cardiotensor.utils.utils import read_conf_file -import cardiotensor.analysis.analysis_utils as utils -import csv -from cardiotensor.colormaps.helix_angle import helix_angle_cmap - - -def script() -> None: - ap = argparse.ArgumentParser(description="AHA-segmented histograms") - ap.add_argument("input", type=Path, help=".conf file or directory to make histogram of") - ap.add_argument("--hist-type", type=str, default="HA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") - ap.add_argument("--lv-mask", type=Path, required=True, help="LV mask directory (slices)") - ap.add_argument("--axis-points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") - ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") - ap.add_argument("--outdir", type=Path, default=None) - ap.add_argument("--write_csv", type=bool, default=True, help="If true record histogram values in a CSV file in the output directory") - ap.add_argument("--plot", type=bool, default=True, help="Whether to plot and save histograms") - ap.add_argument("--divide-radial", type=bool, default=False, help="Whether to divide segments radially into 4 layers") - ap.add_argument("--mask_downsample", type=int, default=1, help="Downsampling factor for the LV mask to speed up processing (default: 1, no downsampling)") - ap.add_argument("--rv", type=bool, default=False, help="Whether to include RV segments (1-26) in the analysis (default: False, only LV segments 1-17)") - ap.add_argument("--rv-mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") - args = ap.parse_args() - - # Resolve config/base - if args.input.suffix.lower() == ".conf": - params = read_conf_file(args.input) - # When a .conf is provided, image data (histograms) live under OUTPUT_PATH/ - output_base = Path(params.get("OUTPUT_PATH")) - images_path = str(output_base / args.hist_type) - cfg_axis = params.get("AXIS_POINTS", []) - # Place output in existing file structure - output_base = Path(params.get("OUTPUT_PATH")) - default_out = output_base / "Analysis" - elif args.input.is_dir(): - images_path = str(args.input) - cfg_axis = [] - default_out = Path("./aha_histograms") - else: - raise ValueError("Input must be a .conf or a directory") - - ## Use requested output directory or default - outdir = args.outdir if args.outdir is not None else default_out - outdir.mkdir(parents=True, exist_ok=True) - - # HA directory discovery - ha_dir = Path(images_path) # fallback - ha_rdr = DataReader(ha_dir) - - # Axis points - if args.axis_points: - try: - p1s, p2s = args.axis_points.split(";") - axis_points = [tuple(map(float, p1s.split(","))), tuple(map(float, p2s.split(",")))] - except Exception: - raise ValueError("--axis-points must be 'z1,y1,x1;z2,y2,x2'") - else: - axis_points = cfg_axis if cfg_axis else None - - # Septum - if args.septum: - sept = tuple(map(float, args.septum.split(","))) - else: - # interactive picker (will open a matplotlib window) - sept = utils.get_septum_point(str(args.lv_mask)) - - if axis_points is None or len(axis_points) < 2: - raise ValueError("Axis points must be provided either in .conf or via --axis-points") - - print("Creating AHA mask") - # Made at the same scale as the LV mask - # RV is optional, if mask not provided the RV will be ignored - # Radial map controls whether or not transmural depth is divided into 4 - if args.rv: - if args.rv_mask == None: - # Calculate an RV mask from the myomapping mask and the LV - heart_mask = params.get("MASK_PATH", None) - - seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, - additional_downsample=args.mask_downsample, - rv=True, - heart_mask_path=heart_mask - ) - else: - seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, - additional_downsample=args.mask_downsample, - rv=True, - rv_mask_path=str(args.rv_mask) - ) - - else: - seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, - additional_downsample=args.mask_downsample, - ) - - if args.divide_radial: - seg_map_to_use = seg_radial_map - else: - seg_map_to_use = seg_map - - # Resample segment map to HA reader shape - target_shape = tuple(ha_rdr.shape) - seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0, TwoD=False, is_mask=False) - - ## Find slices with data - only open these - slice_has_data = np.any(seg_resampled != 0, axis=(1, 2)) - start= np.argmax(slice_has_data) - end = len(slice_has_data) - 1 - np.argmax(slice_has_data[::-1]) - - # Use histogram utility to compute per-segment 0-255 bins from the DataReader - print("Computing per-segment histograms") - bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) - - if unique_segments is None: - print("No segments found in segment map, exiting.") - return - - # Write histogram data to a csv file for future analysis - if args.write_csv: - csv_filename = outdir / 'histogram.csv' - fieldnames = ( - ['VALUE'] + - [f'SEGMENT-{zone}' - for zone in unique_segments] - ) - entries = [] - for value in range(256): # histogram bins - row = {'VALUE': value} - for i, seg in enumerate(unique_segments): # segments - row[f'SEGMENT-{seg}'] = bins[i, value] - entries.append(row) - - with open(csv_filename, mode='w', newline='') as file: - writer = csv.DictWriter(file, fieldnames=fieldnames) - writer.writeheader() - writer.writerows(entries) - - - if args.plot: - - if args.rv: - max_segs = 26 - else: - max_segs = 17 - - - if args.divide_radial: - bins_short = np.zeros((max_segs, bins.shape[1]), dtype=bins.dtype) - - # unique_segments are expected to contain labels like 11,12,13,14 - # for segment 1, and 101..104 for segment 10. Map by arithmetic: - # base_label = segment * 10, radial parts = base_label + 1..4 - unique_ints = [int(u) for u in unique_segments] - for s in range(1, 18): - base = s * 10 - for r in range(1, 5): - label = base + r - if label in unique_ints: - idx = unique_ints.index(label) - bins_short[s - 1] += bins[idx] - else: - bins_short = bins - - - if args.rv: - all_means = utils.segment_means_from_histogram(bins_short, circular=True) - LV_means = all_means[:17] - - ext_bullseye = utils.bullseye_plot_ext(all_means, - title='Helical Angle ', - cmap=helix_angle_cmap - ) - ext_pdf = outdir / "bullseye_ext.pdf" - LV_bullseye.savefig(ext_pdf, bbox_inches="tight") - plt.close(ext_bullseye) - - LV_bullseye = utils.bullseye_plot(LV_means, - title='LV Helical Angle', - cmap=helix_angle_cmap - ) - out_pdf = outdir / "bullseye_LV.pdf" - LV_bullseye.savefig(out_pdf, bbox_inches="tight") - plt.close(LV_bullseye) - - else: - LV_means = utils.segment_means_from_histogram(bins_short, circular=True) - LV_bullseye = utils.bullseye_plot(LV_means, - title='LV Helical Angle', - cmap=helix_angle_cmap - ) - out_pdf = outdir / "bullseye_LV.pdf" - LV_bullseye.savefig(out_pdf, bbox_inches="tight") - plt.close(LV_bullseye) - - lv_segs = [1, 4, 5, 6, 7, 10, 11, 12, 13, 15, 16, 17] - septum_segs = [2, 3, 8, 9, 14] - rv_segs = np.arange(18, 27) - - if args.divide_radial: - - ## LV - base_segs = lv_segs - lv_segs = [] - for s in base_segs: - base = s * 10 - for r in range(1, 5): - label = base + r - lv_segs.append(label) - - ## Septum - base_segs = septum_segs - septum_segs = [] - for s in base_segs: - base = s * 10 - for r in range(1, 5): - label = base + r - septum_segs.append(label) - ## RV - if args.rv: - base_segs = rv_segs - rv_segs = [] - for s in base_segs: - base = s * 10 - for r in range(1, 5): - label = base + r - rv_segs.append(label) - - # Plot overall histogram - fig = utils.plot_segment_histogram( - bins, - segments=lv_segs, - value_range=(-90, 90), - smooth_sigma=0, - normalize=False, - show_mean=True, - circular_mean=True, - xlab='HA (deg)', - ylab='Frequency', - title='LV Histogram', - divide_radial=args.divide_radial - ) - - out_pdf = outdir / "hist_LV.pdf" - fig.savefig(out_pdf, bbox_inches="tight") - plt.close(fig) - - - fig = utils.plot_segment_histogram( - bins, - segments=septum_segs, - value_range=(-90, 90), - smooth_sigma=0, - normalize=False, - show_mean=True, - circular_mean=True, - xlab='HA (deg)', - ylab='Frequency', - title='Septum Histogram', - divide_radial=args.divide_radial - ) - - out_pdf = outdir / "hist_septum.pdf" - fig.savefig(out_pdf, bbox_inches="tight") - plt.close(fig) - - if args.rv: - fig = utils.plot_segment_histogram( - bins, - segments=rv_segs, - value_range=(-90, 90), - smooth_sigma=0, - normalize=False, - show_mean=True, - circular_mean=True, - xlab='HA (deg)', - ylab='Frequency', - title='RV Histogram', - divide_radial=args.divide_radial - ) - - out_pdf = outdir / "hist_RV.pdf" - fig.savefig(out_pdf, bbox_inches="tight") - plt.close(fig) - - - print(f"Done. Figures in {outdir}") - - -if __name__ == "__main__": - script() diff --git a/src/cardiotensor/scripts/draw_aha_model.py b/src/cardiotensor/scripts/draw_aha_model.py new file mode 100644 index 00000000..9d29336d --- /dev/null +++ b/src/cardiotensor/scripts/draw_aha_model.py @@ -0,0 +1,741 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Standalone drawing/test script for an AHA-style 17- or 26-segment model. + +Run: + python draw_aha26_model.py + +Import: + from draw_aha26_model import draw_aha_model + +The geometry constants near the top are intentionally easy to tweak while you +match the RV shape to a reference image. +""" + + +import argparse +from pathlib import Path + +import matplotlib.pyplot as plt +import numpy as np +from matplotlib import colors as mcolors +from matplotlib.path import Path as MplPath +from matplotlib.patches import Circle, PathPatch, Wedge +import cardiotensor.analysis.analysis_utils as utils + +import pandas as pd + + +# ============================================================================= +# TWEAK THESE TO MATCH YOUR REFERENCE +# ============================================================================= +LV_CENTER = (0.55, 0.0) +LV_OUTER_RADIUS = 4.0 + +# Segment order starts at the top and goes counter-clockwise, matching the +# common AHA bullseye layout: 1 top, 2 upper-left, 3 lower-left, 4 bottom, etc. +LV_RING_DEFS = [ + (range(1, 7), 3.0, 4.0, np.linspace(60, 420, 7)), + (range(7, 13), 2.0, 3.0, np.linspace(60, 420, 7)), + (range(13, 17), 1.0, 2.0, np.linspace(45, 405, 5)), +] + +# Angle (degrees from the +x axis) at which the outermost RV free wall attaches to the LV. +RV_INSERTION_ANGLE = 90.0 + +# How far the outermost RV free wall extends to the LEFT (horizontal semi-axis). +RV_OUTER_RX = 7 + +# Four concentric half-ellipse boundaries, outermost → innermost. +# Each entry: (insertion_angle_deg, rx) +# insertion_angle_deg : where the ellipse tips touch the LV outer circle +# rx : horizontal semi-axis (width of the half-ellipse) +# Decrease insertion_angle and rx for each successive inner boundary so the +# nested half-ellipses have smaller, lower insertion points — matching the picture. +RV_HALF_ELLIPSES = [ + (90.0, 6.5), # free-wall outer boundary (outer edge of band 18-20) + (60.0, 7.4), # divider between bands 18-20 and 21-23 + (50.0, 7.2), # divider between bands 21-23 and 24-26 + (50.0, 4), # septal inner boundary (inner edge of band 24-26) +] + +# Per-band row separators: each entry is (segments, outer_lvl, inner_lvl, (angle1, angle2)) +# angle1/angle2 are radial directions from LV center (degrees from +x) that cut the band +# into top / middle / bottom rows. Tune each band independently. +RV_SEPARATOR_SAMPLES = 2400 +RV_BAND_DEFS = [ + ((18, 19, 20), 0, 1, (162.0, 198.0)), # outer band + ((21, 22, 23), 1, 2, (167.0, 193.0)), # middle band + ((24, 25, 26), 2, 3, (173.0, 187.0)), # inner band +] +RV_LABEL_LV_CLEARANCE = 0.10 + +FIGSIZE = (9.0, 6.5) +DEFAULT_MODEL = 26 +OUTPUT_PATH = None +SHOW_FIGURE = True +# ============================================================================= + + +DEFAULT_SEGMENT_COLORS = { + 1: "#4154b3", + 2: "#ed4b52", + 3: "#ef6a45", + 4: "#233b9f", + 5: "#112f91", + 6: "#1b3c99", + 7: "#1e8d88", + 8: "#223fb3", + 9: "#4bc4d1", + 10: "#28d84e", + 11: "#b5f0b7", + 12: "#1e8d88", + 13: "#d6e53a", + 14: "#e8df2f", + 15: "#b9df32", + 16: "#c7e83e", + 17: "#f2de36", + 18: "#f16f2a", + 19: "#f7a53a", + 20: "#f7ce82", + 21: "#aa541b", + 22: "#bf7623", + 23: "#d79b43", + 24: "#6d3d18", + 25: "#83511e", + 26: "#a56828", +} + + + +def _rv_insertion_xy() -> tuple[float, float]: + """Top RV-LV insertion point (x, y) relative to LV_CENTER. Bottom is (x, -y).""" + theta = np.deg2rad(RV_INSERTION_ANGLE) + return LV_OUTER_RADIUS * np.cos(theta), LV_OUTER_RADIUS * np.sin(theta) + + +def _rv_ellipse_curve(t: np.ndarray | float, angle_deg: float, rx: float) -> np.ndarray: + """Left half-ellipse whose tips lie on the LV outer circle at ±angle_deg from +x. + t=0 → top tip, t=0.5 → leftmost point, t=1 → bottom tip.""" + t = np.asarray(t, dtype=float) + angle = np.deg2rad(angle_deg) + cx = LV_OUTER_RADIUS * np.cos(angle) # x of the ellipse centre + ry = LV_OUTER_RADIUS * np.sin(angle) # vertical semi-axis = y of top tip + phi = np.pi / 2.0 + t * np.pi # sweeps π/2 → π → 3π/2 + x = cx + rx * np.cos(phi) + y = ry * np.sin(phi) + return np.column_stack((np.atleast_1d(x), np.atleast_1d(y))) + + +def _lv_arc(from_deg: float, to_deg: float, n: int = 18) -> np.ndarray: + """Arc of the LV outer circle from from_deg to to_deg (degrees from +x axis).""" + thetas = np.linspace(np.deg2rad(from_deg), np.deg2rad(to_deg), n) + x = LV_OUTER_RADIUS * np.cos(thetas) + y = LV_OUTER_RADIUS * np.sin(thetas) + return np.column_stack((x, y)) + + +def _rv_separator_t( + ellipse_level: int, + separator_angle_deg: float, +) -> float: + """Find where a straight RV row separator intersects one half-ellipse.""" + angle_deg, rx = RV_HALF_ELLIPSES[ellipse_level] + t_values = np.linspace(0.0, 1.0, RV_SEPARATOR_SAMPLES) + points = _rv_ellipse_curve(t_values, angle_deg, rx) + theta = np.deg2rad(separator_angle_deg) + direction = np.array([np.cos(theta), np.sin(theta)]) + cross = np.abs(direction[0] * points[:, 1] - direction[1] * points[:, 0]) + along = points @ direction + cross = np.where(along > 0.0, cross, np.inf) + return float(t_values[np.argmin(cross)]) + + +def _rv_separator_t_pair( + outer_lvl: int, + inner_lvl: int, + separator_angle_deg: float, +) -> tuple[float, float]: + """Return (t_out, t_in): the separator hits the outer ellipse at the point + closest to separator_angle_deg from the LV center, then follows the inward + normal of the outer ellipse to find where it crosses the inner ellipse.""" + t_out = _rv_separator_t(outer_lvl, separator_angle_deg) + + angle_out, rx_out = RV_HALF_ELLIPSES[outer_lvl] + angle_in, rx_in = RV_HALF_ELLIPSES[inner_lvl] + angle_out_rad = np.deg2rad(angle_out) + angle_in_rad = np.deg2rad(angle_in) + cx_out = LV_OUTER_RADIUS * np.cos(angle_out_rad) + ry_out = LV_OUTER_RADIUS * np.sin(angle_out_rad) + cx_in = LV_OUTER_RADIUS * np.cos(angle_in_rad) + ry_in = LV_OUTER_RADIUS * np.sin(angle_in_rad) + + phi = np.pi / 2.0 + t_out * np.pi + x0 = cx_out + rx_out * np.cos(phi) + y0 = ry_out * np.sin(phi) + + # Inward normal to the outer ellipse at (x0, y0): -∇f / |∇f| + nx_raw = -np.cos(phi) / rx_out + ny_raw = -np.sin(phi) / ry_out + mag = np.hypot(nx_raw, ny_raw) + nx, ny = nx_raw / mag, ny_raw / mag + + # Intersect the normal line with the inner ellipse + A = (nx / rx_in) ** 2 + (ny / ry_in) ** 2 + B = 2.0 * ((x0 - cx_in) * nx / rx_in ** 2 + y0 * ny / ry_in ** 2) + C = ((x0 - cx_in) / rx_in) ** 2 + (y0 / ry_in) ** 2 - 1.0 + disc = B ** 2 - 4.0 * A * C + if disc < 0: + return t_out, _rv_separator_t(inner_lvl, separator_angle_deg) + + s1 = (-B + np.sqrt(disc)) / (2.0 * A) + s2 = (-B - np.sqrt(disc)) / (2.0 * A) + positives = sorted(s for s in (s1, s2) if s > 1e-9) + if not positives: + return t_out, _rv_separator_t(inner_lvl, separator_angle_deg) + + s_hit = positives[0] + x_hit = x0 + s_hit * nx + y_hit = y0 + s_hit * ny + + # Convert hit point to t on inner ellipse + cos_phi_in = np.clip((x_hit - cx_in) / rx_in, -1.0, 1.0) + sin_phi_in = y_hit / ry_in + phi_in = np.arctan2(sin_phi_in, cos_phi_in) + if phi_in < np.pi / 2.0 - 1e-9: + phi_in += 2.0 * np.pi + t_in = float(np.clip((phi_in - np.pi / 2.0) / np.pi, 0.0, 1.0)) + return t_out, t_in + + +def _rv_segment_path( + center: tuple[float, float], + row1: int, + row2: int, + outer_lvl: int, + inner_lvl: int, + sep_angles: tuple, +) -> MplPath: + """Closed path for one RV segment bounded by two nested half-ellipses. + Row separators are perpendicular to the outer ellipse at the cut point.""" + N = 50 + angle_out, rx_out = RV_HALF_ELLIPSES[outer_lvl] + angle_in, rx_in = RV_HALF_ELLIPSES[inner_lvl] + + if row1 == 0: + t1_out, t1_in = 0.0, 0.0 + else: + t1_out, t1_in = _rv_separator_t_pair(outer_lvl, inner_lvl, sep_angles[row1 - 1]) + + if row2 == len(sep_angles) + 1: + t2_out, t2_in = 1.0, 1.0 + else: + t2_out, t2_in = _rv_separator_t_pair(outer_lvl, inner_lvl, sep_angles[row2 - 1]) + + outer_arc = _rv_ellipse_curve(np.linspace(t1_out, t2_out, N), angle_out, rx_out) + inner_arc = _rv_ellipse_curve(np.linspace(t2_in, t1_in, N), angle_in, rx_in) + + # Bottom edge: at t=1 both tips are on the LV circle -> connect via LV arc + bottom_conn = ( + _lv_arc(-angle_out, -angle_in)[1:] + if row2 == len(sep_angles) + 1 + else None + ) + # Top edge: same at t=0 + top_conn = _lv_arc(angle_in, angle_out)[1:] if row1 == 0 else None + + parts = [outer_arc] + if bottom_conn is not None: + parts.append(bottom_conn) + parts.append(inner_arc) + if top_conn is not None: + parts.append(top_conn) + + cx, cy = center + vertices = np.vstack(parts + [outer_arc[:1]]) + vertices = vertices + np.array([cx, cy]) + codes = [MplPath.MOVETO] + [MplPath.LINETO] * (len(vertices) - 2) + [MplPath.CLOSEPOLY] + return MplPath(vertices, codes) + + +def _outside_lv( + points: np.ndarray, + center: tuple[float, float], + clearance: float = 0.0, +) -> np.ndarray: + """Return boolean mask: True where each point lies outside (or on) the LV outer circle. + + Parameters + ---------- + points : (N, 2) array of (x, y) coordinates in data space. + center : (x, y) of the LV center, matching LV_CENTER. + clearance : extra margin added to LV_OUTER_RADIUS before the distance test. + """ + center_xy = np.asarray(center, dtype=float) + distances = np.linalg.norm(points - center_xy, axis=1) + return distances >= LV_OUTER_RADIUS + clearance + + +def _rv_label_position( + path: MplPath, + center: tuple[float, float], +) -> tuple[float, float]: + """Find a good (x, y) position for a text label inside an RV segment patch. + + Samples a grid inside the segment bounding box, keeps only points that are + (a) inside the segment path, (b) on the RV side (left of LV center), and + (c) outside the LV outer circle. Returns the grid point closest to the + centroid of those visible candidates. Falls back to progressively looser + criteria, and ultimately to the raw vertex centroid, if no candidate passes. + + Parameters + ---------- + path : closed MplPath describing one RV segment (in data coordinates). + center : (x, y) of the LV center, used to exclude the LV interior. + + Returns + ------- + (x, y) in data coordinates. + """ + xmin, ymin = path.vertices.min(axis=0) + xmax, ymax = path.vertices.max(axis=0) + x_values = np.linspace(xmin, xmax, 80) + y_values = np.linspace(ymin, ymax, 80) + xx, yy = np.meshgrid(x_values, y_values) + points = np.column_stack((xx.ravel(), yy.ravel())) + in_segment = path.contains_points(points) + rv_side = points[:, 0] <= center[0] - 0.05 + visible = in_segment & rv_side & _outside_lv(points, center, RV_LABEL_LV_CLEARANCE) + if not np.any(visible): + visible = in_segment & rv_side & _outside_lv(points, center) + if not np.any(visible): + visible = in_segment & _outside_lv(points, center) + + if np.any(visible): + visible_points = points[visible] + centroid = visible_points.mean(axis=0) + closest = np.argmin(np.sum((visible_points - centroid) ** 2, axis=1)) + return tuple(visible_points[closest]) + + centroid = path.vertices[:-1].mean(axis=0) + return tuple(centroid) + + +def _value_color( + segment: int, + values: dict[int, float] | None, + cmap, + norm, + segment_colors: dict[int, str], +): + """Resolve the fill color for one segment. + + If *values* contains an entry for *segment*, maps the scalar through *cmap*/*norm*. + Otherwise falls back to the hex string in *segment_colors*, or grey if absent. + """ + if values is not None and segment in values: + return cmap(norm(values[segment])) + return segment_colors.get(segment, "#d9d9d9") + + +def _text_color(facecolor) -> str: + """Return 'black' or 'white' for legible text on top of *facecolor*.""" + rgba = mcolors.to_rgba(facecolor) + luminance = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2] + return "black" if luminance > 0.58 else "white" + + +def _polar_to_xy( + center: tuple[float, float], + radius: float, + theta_deg: float, +) -> tuple[float, float]: + """Convert polar coordinates to Cartesian (x, y) offset from *center*. + + Parameters + ---------- + center : (x, y) origin in data coordinates. + radius : radial distance from center. + theta_deg : angle in degrees measured counter-clockwise from the +x axis. + """ + theta = np.deg2rad(theta_deg) + return center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta) + + +def draw_lv( + ax, + values: dict[int, float] | None, + cmap, + norm, + segment_colors: dict[int, str], + center: tuple[float, float], + show_labels: bool = True, +): + """Draw all LV segments (1–17) onto *ax*. + + Segments 1–16 are Wedge patches arranged in three concentric rings defined + by LV_RING_DEFS. Segment 17 (apex) is a filled Circle at *center*. + + Parameters + ---------- + ax : Matplotlib Axes to draw on. + values : mapping {segment: scalar} used for colormap coloring, or + None to use *segment_colors*. + cmap : Matplotlib colormap (returned by plt.get_cmap). + norm : Matplotlib Normalize instance matching *cmap*. + segment_colors: fallback {segment: hex_color} dict when *values* is None + or a segment has no entry in *values*. + center : (x, y) of the LV center in data coordinates (= LV_CENTER). + show_labels : if True, draw the segment number text inside each patch. + """ + for segments, r_in, r_out, angles in LV_RING_DEFS: + for i, segment in enumerate(segments): + theta1 = angles[i] + theta2 = angles[i + 1] + facecolor = _value_color(segment, values, cmap, norm, segment_colors) + ax.add_patch( + Wedge( + center, + r_out, + theta1=theta1, + theta2=theta2, + width=r_out - r_in, + facecolor=facecolor, + edgecolor="#202020", + linewidth=1.3, + ) + ) + if show_labels: + x, y = _polar_to_xy(center, (r_in + r_out) / 2, (theta1 + theta2) / 2) + ax.text( + x, + y, + str(segment), + ha="center", + va="center", + fontsize=9, + weight="bold", + color=_text_color(facecolor), + ) + + facecolor = _value_color(17, values, cmap, norm, segment_colors) + ax.add_patch( + Circle(center, 1.0, facecolor=facecolor, edgecolor="#202020", linewidth=1.3) + ) + if show_labels: + ax.text( + center[0], + center[1], + "17", + ha="center", + va="center", + fontsize=10, + weight="bold", + color=_text_color(facecolor), + ) + + +def draw_rv( + ax, + values: dict[int, float] | None, + cmap, + norm, + segment_colors: dict[int, str], + center: tuple[float, float], + show_labels: bool = True, +): + """Draw all RV segments (18–26) onto *ax*. + + The RV is represented as three depth bands (outer 18-20, middle 21-23, + inner 24-26), each bounded by a pair of concentric half-ellipses defined + in RV_HALF_ELLIPSES. Each band is divided into top/middle/bottom rows + by perpendicular-to-ellipse separators whose angles are specified per band + in RV_BAND_DEFS. + + Parameters + ---------- + ax : Matplotlib Axes to draw on. + values : mapping {segment: scalar} used for colormap coloring, or + None to use *segment_colors*. + cmap : Matplotlib colormap (returned by plt.get_cmap). + norm : Matplotlib Normalize instance matching *cmap*. + segment_colors: fallback {segment: hex_color} dict when *values* is None + or a segment has no entry in *values*. + center : (x, y) of the LV center in data coordinates (= LV_CENTER). + show_labels : if True, draw the segment number text inside each patch, + placed outside the LV circle using _rv_label_position. + """ + for segments, outer_lvl, inner_lvl, sep_angles in RV_BAND_DEFS: + for i, segment in enumerate(segments): + facecolor = _value_color(segment, values, cmap, norm, segment_colors) + path = _rv_segment_path(center, i, i + 1, outer_lvl, inner_lvl, sep_angles) + ax.add_patch( + PathPatch( + path, + facecolor=facecolor, + edgecolor="#202020", + linewidth=1.3, + joinstyle="round", + ) + ) + if show_labels: + x, y = _rv_label_position(path, center) + ax.text( + x, + y, + str(segment), + ha="center", + va="center", + fontsize=8, + weight="bold", + color=_text_color(facecolor), + zorder=4, + ) + + +def _validate_model(model: int | str) -> int: + model = int(model) + if model not in (17, 26): + raise ValueError(f"model must be 17 or 26, got {model}") + return model + + +def draw_aha_model( + values: dict[int, float] | None = None, + csv: str = None, + ax=None, + *, + model: int | str = DEFAULT_MODEL, + cmap_name: str = "viridis", + cmap=None, + value_range: tuple[float, float] = (0.0, 1.0), + segment_colors: dict[int, str] | None = None, + show_labels: bool = True, + show_lv_rv_labels: bool = True, + show_colorbar: bool = True, + colorbar_label: str | None = None, + title: str | None = "AHA 26 Model", +): + """Draw an AHA 17- or 26-segment bullseye model. + + This is the main entry point. It creates (or reuses) a Matplotlib figure, + draws the LV (and optionally the RV), and returns the figure and axes. + + Parameters + ---------- + values : dict[int, float] or None + Optional mapping of segment number → scalar value. When provided the + segments are colored by mapping the scalar through *cmap_name* and + *value_range*. Segments absent from *values* fall back to + *segment_colors*. Pass None (default) to use only *segment_colors*. + csv: string or None + Path to csv file containing histogram data. Assumes data encoded as 8 bit. + ax : matplotlib.axes.Axes or None + Axes to draw on. If None a new figure of size FIGSIZE is created. + model : 17 or 26 + ``17`` draws only the LV (segments 1–17). + ``26`` draws the LV plus the RV (segments 18–26). + cmap_name : str + Name of any Matplotlib colormap, used when *values* is provided. + Default ``"viridis"``. For helix-angle data ``"twilight_shifted"`` + works well. + cmap : colourmap + Provide a colourmap directly instead of using one form matplotlib + value_range : (float, float) + (vmin, vmax) passed to ``plt.Normalize``. Scalars outside this range + are clipped by the colormap. Default ``(0.0, 1.0)``. + segment_colors : dict[int, str] or None + Per-segment fallback colors as ``{segment_number: "#rrggbb"}``. + Merged with DEFAULT_SEGMENT_COLORS (caller values take precedence). + Pass None to use only DEFAULT_SEGMENT_COLORS. + show_labels : bool + Draw segment-number text inside each patch. Default True. + show_lv_rv_labels : bool + Draw the "LV" and "RV" annotations (only meaningful for model 26). + show_colorbar : bool + Attach a colorbar to the figure when *values* is provided. + colorbar_label : str or None + Label shown next to the colorbar axis. + title : str or None + Figure title. Pass None to suppress. + + Returns + ------- + fig : matplotlib.figure.Figure + ax : matplotlib.axes.Axes + + Examples + -------- + # Plain color map with default colors + fig, ax = draw_aha_model(model=26) + + # Color each segment by a fractional anisotropy value + fa_values = {1: 0.42, 2: 0.55, ..., 26: 0.38} + fig, ax = draw_aha_model(fa_values, model=26, + cmap_name="viridis", value_range=(0, 1), + colorbar_label="FA") + plt.show() + """ + model = _validate_model(model) + segment_colors = dict(DEFAULT_SEGMENT_COLORS if segment_colors is None else segment_colors) + if not cmap: + cmap = plt.get_cmap(cmap_name) + norm = plt.Normalize(*value_range) + + if ax is None: + fig, ax = plt.subplots(figsize=FIGSIZE) + else: + fig = ax.figure + + if not values: + ## Load a histogram from a csv file + if csv: + hist= pd.read_csv(csv) + hist.drop(columns=['VALUE'], inplace=True) + + hist.columns = [ + int(c.removeprefix('SEGMENT-')) if c.startswith('SEGMENT-') else c + for c in hist.columns + ] + + # Concatenate radial division + if max(hist.columns) > model: + raw_values = {} + + for s in range(1, model + 1): + raw_values[s] = np.zeros(len(hist)) + + base = s * 10 + for r in range(1, 5): + label = base + r + if label in hist.columns: + raw_values[s] += hist[label].to_numpy() + else: + raw_values = {k: hist[k].to_numpy() for k in hist.columns} + + hist_array = np.column_stack([raw_values[k] for k in sorted(raw_values)]) + values = utils.segment_means_from_histogram(hist_array, circular=True) + + + + if model == 26: + draw_rv(ax, values, cmap, norm, segment_colors, LV_CENTER, show_labels=show_labels) + draw_lv(ax, values, cmap, norm, segment_colors, LV_CENTER, show_labels=show_labels) + + if show_lv_rv_labels and model == 26: + x_ins, y_ins = _rv_insertion_xy() + ax.text( + LV_CENTER[0] + x_ins - RV_OUTER_RX * 0.45, + LV_CENTER[1] + y_ins * 0.95, + "RV", fontsize=12, weight="bold", + ) + ax.text(LV_CENTER[0] + 3.35, LV_CENTER[1] + 3.35, "LV", fontsize=12, weight="bold") + + if title: + ax.set_title(title, fontsize=15, weight="bold") + ax.set_aspect("equal") + if model == 26: + x_ins, _ = _rv_insertion_xy() + rv_left = x_ins - RV_OUTER_RX + ax.set_xlim(LV_CENTER[0] + rv_left - 0.6, LV_CENTER[0] + 4.35) + ax.set_ylim(LV_CENTER[1] - 4.25, LV_CENTER[1] + 4.25) + else: + ax.set_xlim(LV_CENTER[0] - 4.25, LV_CENTER[0] + 4.25) + ax.set_ylim(LV_CENTER[1] - 4.25, LV_CENTER[1] + 4.25) + ax.axis("off") + + if values is not None and show_colorbar: + sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm) + sm.set_array([]) + cbar = fig.colorbar(sm, ax=ax, fraction=0.045, pad=0.04) + if colorbar_label: + cbar.set_label(colorbar_label) + + fig.tight_layout() + return fig, ax + + + +def fake_values_for_model(model: int | str, kind: str = "fa") -> dict[int, float]: + """Create deterministic fake scalar values for testing segment coloring. + + Parameters + ---------- + model : 17 or 26 + Which model to generate values for (determines segment count). + kind : ``"fa"`` or ``"ha"`` + ``"fa"`` → linearly spaced values in [0, 1] (fractional anisotropy range). + ``"ha"`` → linearly spaced values in [-90, 90] (helix-angle range). + + Returns + ------- + dict[int, float] mapping each segment number to a scalar. + """ + model = _validate_model(model) + segments = list(range(1, model + 1)) + if kind == "ha": + values = np.linspace(-90.0, 90.0, len(segments)) + elif kind == "fa": + values = np.linspace(0.0, 1.0, len(segments)) + else: + raise ValueError(f"kind must be 'fa' or 'ha', got {kind}") + return dict(zip(segments, values)) + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Draw/test the AHA 17/26 model geometry.") + parser.add_argument("--model", choices=("17", "26"), default=str(DEFAULT_MODEL)) + parser.add_argument("--fake-values", choices=("none", "fa", "ha"), default="none") + parser.add_argument("--output", default=OUTPUT_PATH) + parser.add_argument("--no-show", action="store_true") + parser.add_argument("--no-save", action="store_true") + parser.add_argument("--no-title", action="store_true") + parser.add_argument("--no-colorbar", action="store_true") + parser.add_argument("--csv", default=False) + parser.add_argument("--value-range", nargs = 2, type=float, default=[0.0, 1.0]) + return parser.parse_args() + + +def main() -> None: + args = parse_args() + model = _validate_model(args.model) + values = None + cmap_name = "viridis" + value_range = (0.0, 1.0) + colorbar_label = None + title = None if args.no_title else f"AHA {model} Model" + + if args.fake_values != "none": + values = fake_values_for_model(model, args.fake_values) + title = None if args.no_title else f"AHA {model} Model - fake {args.fake_values.upper()}" + colorbar_label = f"Fake {args.fake_values.upper()} value" + if args.fake_values == "ha": + cmap_name = "twilight_shifted" + value_range = (-90.0, 90.0) + + fig, _ = draw_aha_model( + values=values, + csv = args.csv, + model=model, + cmap_name=cmap_name, + value_range=args.value_range, + show_colorbar=not args.no_colorbar, + colorbar_label=colorbar_label, + title=title, + ) + + if not args.no_save: + output = Path(args.output or f"aha{model}_model_test.png") + fig.savefig(output, dpi=300, bbox_inches="tight") + print(f"Saved: {output.resolve()}") + + if SHOW_FIGURE and not args.no_show: + print("Opening figure. Close the plot window to finish.") + plt.show() + + plt.close(fig) + + +if __name__ == "__main__": + main() From 26e9ad503401f9618b43426e8fa786a2b05b6bf8 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Fri, 19 Jun 2026 15:43:40 +0100 Subject: [PATCH 04/11] Correct transposition error --- src/cardiotensor/scripts/analysis_histograms_aha.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index d4630440..86e8a19c 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -143,8 +143,11 @@ def script() -> None: # Use histogram utility to compute per-segment 0-255 bins from the DataReader print("Computing per-segment histograms") - bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) + # Swap rows and columns of bins - address this in calculation/analysis + bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) + bins = bins.transpose() + if unique_segments is None: print("No segments found in segment map, exiting.") return From bf169c25676ec3250a07028740d0dfd7d8cf991e Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Fri, 19 Jun 2026 15:44:36 +0100 Subject: [PATCH 05/11] Correct transposition error --- src/cardiotensor/scripts/analysis_histograms_aha.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index 86e8a19c..d37bfbe2 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -146,7 +146,6 @@ def script() -> None: # Swap rows and columns of bins - address this in calculation/analysis bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) - bins = bins.transpose() if unique_segments is None: print("No segments found in segment map, exiting.") @@ -173,6 +172,8 @@ def script() -> None: writer.writerows(entries) + # Correct transposition error + bins = bins.transpose() if args.plot: if args.rv: From 50ff2b120f5795f031617e51c48698e3da3e2639 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Tue, 23 Jun 2026 16:47:05 +0100 Subject: [PATCH 06/11] Fix function argument handling --- .../scripts/analysis_histograms_aha.py | 182 ++++++++++-------- 1 file changed, 105 insertions(+), 77 deletions(-) diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index d37bfbe2..a3370528 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -28,17 +28,26 @@ def script() -> None: ap = argparse.ArgumentParser(description="AHA-segmented histograms") ap.add_argument("input", type=Path, help=".conf file or directory to make histogram of") - ap.add_argument("--hist-type", type=str, default="HA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") - ap.add_argument("--lv-mask", type=Path, required=True, help="LV mask directory (slices)") - ap.add_argument("--axis-points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") + ap.add_argument("--hist_type", type=str, default="FA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") + ap.add_argument("--lv_mask", type=Path, required=True, help="LV mask directory (slices)") + ap.add_argument("--axis_points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") ap.add_argument("--outdir", type=Path, default=None) - ap.add_argument("--write_csv", type=bool, default=True, help="If true record histogram values in a CSV file in the output directory") - ap.add_argument("--plot", type=bool, default=True, help="Whether to plot and save histograms") - ap.add_argument("--divide-radial", type=bool, default=False, help="Whether to divide segments radially into 4 layers") + + # `--write_csv` and `--plot` default to True; provide `--no-` flags to disable + ap.add_argument("--write_csv", dest="write_csv", action="store_true", default=True, help="Record histogram values in a CSV file in the output directory (default: enabled)") + ap.add_argument("--no-write_csv", dest="write_csv", action="store_false", help="Disable writing CSV output") + + ap.add_argument("--plot", dest="plot", action="store_true", default=True, help="Plot and save histograms (default: enabled)") + ap.add_argument("--no-plot", dest="plot", action="store_false", help="Disable plotting/saving histograms") + + # Flags that default to False use store_true + ap.add_argument("--divide_radial", action="store_true", default=False, help="Divide segments radially into 4 layers") ap.add_argument("--mask_downsample", type=int, default=1, help="Downsampling factor for the LV mask to speed up processing (default: 1, no downsampling)") - ap.add_argument("--rv", type=bool, default=False, help="Whether to include RV segments (1-26) in the analysis (default: False, only LV segments 1-17)") - ap.add_argument("--rv-mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") + ap.add_argument("--rv", action="store_true", default=False, help="Include RV segments (1-26) in the analysis") + ap.add_argument("--rv_mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") + ap.add_argument("--value_range", nargs=2, type=float, default=[0.0, 1.0]) + ap.add_argument("--circular", action="store_true", default=False, help="Use circular statistics for plotting (default: False)") args = ap.parse_args() # Resolve config/base @@ -91,41 +100,41 @@ def script() -> None: # RV is optional, if mask not provided the RV will be ignored # Radial map controls whether or not transmural depth is divided into 4 if args.rv: - if args.rv_mask == None: + if args.rv_mask is None: # Calculate an RV mask from the myomapping mask and the LV heart_mask = params.get("MASK_PATH", None) seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, additional_downsample=args.mask_downsample, rv=True, - heart_mask_path=heart_mask + heart_mask_path=heart_mask, ) else: seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, additional_downsample=args.mask_downsample, rv=True, - rv_mask_path=str(args.rv_mask) + rv_mask_path=str(args.rv_mask), ) else: - seg_map, seg_radial_map = utils.create_aha_mask( - str(args.lv_mask), - axis_points, - sept, - str(images_path), - return_radial_map=args.divide_radial, - additional_downsample=args.mask_downsample, - ) + seg_map, seg_radial_map = utils.create_aha_mask( + str(args.lv_mask), + axis_points, + sept, + str(images_path), + return_radial_map=args.divide_radial, + additional_downsample=args.mask_downsample, + ) if args.divide_radial: seg_map_to_use = seg_radial_map @@ -134,16 +143,16 @@ def script() -> None: # Resample segment map to HA reader shape target_shape = tuple(ha_rdr.shape) - seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0, TwoD=False, is_mask=False) + seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0) ## Find slices with data - only open these slice_has_data = np.any(seg_resampled != 0, axis=(1, 2)) - start= np.argmax(slice_has_data) + start = np.argmax(slice_has_data) end = len(slice_has_data) - 1 - np.argmax(slice_has_data[::-1]) - + # Use histogram utility to compute per-segment 0-255 bins from the DataReader print("Computing per-segment histograms") - + # Swap rows and columns of bins - address this in calculation/analysis bins, unique_segments = utils.histogram(rdr=ha_rdr, start=int(start), end=int(end), seg_map=seg_resampled, factor=1) @@ -153,20 +162,20 @@ def script() -> None: # Write histogram data to a csv file for future analysis if args.write_csv: - csv_filename = outdir / 'histogram.csv' + csv_filename = outdir / "histogram.csv" fieldnames = ( - ['VALUE'] + - [f'SEGMENT-{zone}' - for zone in unique_segments] + ["VALUE"] + + [f"SEGMENT-{zone}" + for zone in unique_segments] ) entries = [] for value in range(256): # histogram bins - row = {'VALUE': value} + row = {"VALUE": value} for i, seg in enumerate(unique_segments): # segments - row[f'SEGMENT-{seg}'] = bins[i, value] + row[f"SEGMENT-{seg}"] = bins[i, value] entries.append(row) - - with open(csv_filename, mode='w', newline='') as file: + + with open(csv_filename, mode="w", newline="") as file: writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerows(entries) @@ -176,53 +185,75 @@ def script() -> None: bins = bins.transpose() if args.plot: + val_range = args.value_range + circ = args.circular + hist_type = args.hist_type + + if hist_type == 'HA' or hist_type == 'IA': + cmap = helix_angle_cmap + else: + cmap = plt.get_cmap('viridis') + if args.rv: max_segs = 26 else: max_segs = 17 - - if args.divide_radial: + + if args.divide_radial: bins_short = np.zeros((bins.shape[0], max_segs), dtype=bins.dtype) # unique_segments are expected to contain labels like 11,12,13,14 # for segment 1, and 101..104 for segment 10. Map by arithmetic: # base_label = segment * 10, radial parts = base_label + 1..4 unique_ints = [int(u) for u in unique_segments] - for s in range(1, max_segs+1): + for s in range(1, max_segs + 1): base = s * 10 for r in range(1, 5): label = base + r if label in unique_ints: idx = unique_ints.index(label) - bins_short[:,s - 1] += bins[:,idx] - else: + bins_short[:, s - 1] += bins[:, idx] + else: bins_short = bins if args.rv: - all_means = utils.segment_means_from_histogram(bins_short, circular=True) + all_means = utils.segment_means_from_histogram(bins_short, circular=circ) LV_means = {i: all_means[i] for i in range(1, 18)} - - aha.draw_aha_model(all_means, + + figr, _ = aha.draw_aha_model(all_means, model=26, - value_range=(-90,90), - cmap=helix_angle_cmap, - colorbar_label='Mean Helical Angle (°)') - aha.draw_aha_model(LV_means, + value_range=val_range, + cmap=cmap, + colorbar_label=f'Mean {hist_type}') + + out_pdf = outdir / "hist_bullseye_26seg.pdf" + figr.savefig(out_pdf, bbox_inches="tight") + plt.close(figr) + + + figl, _ = aha.draw_aha_model(LV_means, model=17, - value_range=(-90,90), - cmap=helix_angle_cmap, - colorbar_label='Mean Helical Angle (°)') - + value_range=val_range, + cmap=cmap, + colorbar_label=f'Mean {hist_type}') + + out_pdf = outdir / "hist_bullseye_17seg.pdf" + figl.savefig(out_pdf, bbox_inches="tight") + plt.close(figl) else: - LV_means = utils.segment_means_from_histogram(bins_short, circular=True) - - aha.draw_aha_model(LV_means, + LV_means = utils.segment_means_from_histogram(bins_short, circular=circ) + + figl, _ = aha.draw_aha_model(LV_means, model=17, - value_range=(-90,90), - cmap=helix_angle_cmap, - colorbar_label='Mean Helical Angle (°)') - + value_range=val_range, + cmap=cmap, + colorbar_label=f'Mean {hist_type}') + + out_pdf = outdir / "hist_bullseye_17seg.pdf" + figl.savefig(out_pdf, bbox_inches="tight") + plt.close(figl) + lv_segs = [1, 4, 5, 6, 7, 10, 11, 12, 13, 15, 16, 17] septum_segs = [2, 3, 8, 9, 14] rv_segs = np.arange(18, 27) @@ -237,7 +268,7 @@ def script() -> None: for r in range(1, 5): label = base + r lv_segs.append(label) - + ## Septum base_segs = septum_segs septum_segs = [] @@ -260,12 +291,12 @@ def script() -> None: fig = utils.plot_segment_histogram( bins, segments=lv_segs, - value_range=(-90, 90), + value_range=val_range, smooth_sigma=0, normalize=True, show_mean=True, - circular_mean=True, - xlab='HA (deg)', + circular_mean=circ, + xlab=f'{hist_type}', ylab='Frequency', title='LV Histogram', divide_radial=args.divide_radial @@ -279,12 +310,12 @@ def script() -> None: fig = utils.plot_segment_histogram( bins, segments=septum_segs, - value_range=(-90, 90), + value_range=val_range, smooth_sigma=0, normalize=True, show_mean=True, - circular_mean=True, - xlab='HA (deg)', + circular_mean=circ, + xlab=f'{hist_type}', ylab='Frequency', title='Septum Histogram', divide_radial=args.divide_radial @@ -298,12 +329,12 @@ def script() -> None: fig = utils.plot_segment_histogram( bins, segments=rv_segs, - value_range=(-90, 90), + value_range=val_range, smooth_sigma=0, normalize=True, show_mean=True, - circular_mean=True, - xlab='HA (deg)', + circular_mean=circ, + xlab=f'{hist_type}', ylab='Frequency', title='RV Histogram', divide_radial=args.divide_radial @@ -319,6 +350,3 @@ def script() -> None: if __name__ == "__main__": script() - - - From e0a6cf377776ebcdb5eca83aee84ff37d0e3f282 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Tue, 23 Jun 2026 16:51:21 +0100 Subject: [PATCH 07/11] Update analysis_histograms_aha.py --- src/cardiotensor/scripts/analysis_histograms_aha.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index a3370528..3901bca3 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -227,6 +227,7 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') + plt.show() out_pdf = outdir / "hist_bullseye_26seg.pdf" figr.savefig(out_pdf, bbox_inches="tight") plt.close(figr) @@ -238,6 +239,7 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') + plt.show() out_pdf = outdir / "hist_bullseye_17seg.pdf" figl.savefig(out_pdf, bbox_inches="tight") plt.close(figl) @@ -250,6 +252,7 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') + plt.show() out_pdf = outdir / "hist_bullseye_17seg.pdf" figl.savefig(out_pdf, bbox_inches="tight") plt.close(figl) From 9d1e39cd691409b255deb6e81c8ef78965d4f6f9 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Thu, 25 Jun 2026 15:07:59 +0100 Subject: [PATCH 08/11] Created function call and added no pop-up mode --- pyproject.toml | 1 + src/cardiotensor/analysis/analysis_utils.py | 19 +++++-- .../scripts/analysis_histograms_aha.py | 49 ++++++++++++------- 3 files changed, 47 insertions(+), 22 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 4e7b196a..5a499dc9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,6 +76,7 @@ git = [ [project.scripts] cardio-analysis = "cardiotensor.scripts.gui_analysis_tool:script" cardio-analysis-histo = "cardiotensor.scripts.analysis_histograms:script" +cardio-analysis-histo-aha = "cardiotensor.scripts.analysis_histograms_aha:script" cardio-analysis-streamlines = "cardiotensor.scripts.analysis_streamlines:script" cardio-generate-streamlines = "cardiotensor.scripts.generate_streamlines:script" cardio-tensor = "cardiotensor.scripts.compute_orientation:script" diff --git a/src/cardiotensor/analysis/analysis_utils.py b/src/cardiotensor/analysis/analysis_utils.py index beeb67e0..b56f9f48 100644 --- a/src/cardiotensor/analysis/analysis_utils.py +++ b/src/cardiotensor/analysis/analysis_utils.py @@ -201,7 +201,9 @@ def create_aha_mask( additional_downsample=1, rv=False, rv_mask_path=None, - heart_mask_path=None + heart_mask_path=None, + headless=False, + savepath=None ): """ Create a 17-segment AHA mask from an LV mask. @@ -428,7 +430,7 @@ def sectors_from_indices(indices, n_sectors, start_seg): long_axis = axis_vec - lv_vec = septum_vec + lv_vec = septum_vec / np.linalg.norm(septum_vec) # project LV direction into short-axis plane e0 = ( @@ -771,9 +773,14 @@ def _get_segment_colors(n): # segment_colors values are floats in 0-1 from the colormap; use RGB channels patches = [Patch(facecolor=segment_colors[i][:3], label=f"Seg {i+1}") for i in range(max_seg)] fig.legend(handles=patches, loc='upper right', bbox_to_anchor=(1.1, 0.95), title="AHA Segments") + + if not headless: + plt.tight_layout() + plt.show() - plt.tight_layout() - plt.show() + if savepath: + out_pdf = savepath / f"aha_map_slices.pdf" + fig.savefig(out_pdf, bbox_inches="tight") if not return_radial_map: return segment_map, None @@ -3042,6 +3049,7 @@ def plot_segment_histogram( ylab = 'Count', title=None, divide_radial=False, + headless= False ): # -------------------- @@ -3118,7 +3126,8 @@ def plot_segment_histogram( ax.axvline(mean_val, linestyle='-', linewidth=2, label=f"Mean = {mean_val:.2f}") ax.legend() - plt.show() + if not headless: + plt.show() return fig diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index 3901bca3..c9e33eba 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -22,7 +22,7 @@ import csv from cardiotensor.colormaps.helix_angle import helix_angle_cmap -import draw_aha_model as aha +import cardiotensor.scripts.draw_aha_model as aha def script() -> None: @@ -31,7 +31,7 @@ def script() -> None: ap.add_argument("--hist_type", type=str, default="FA", help="Type of histogram to compute (e.g., 'HA', 'FA', 'IA)") ap.add_argument("--lv_mask", type=Path, required=True, help="LV mask directory (slices)") ap.add_argument("--axis_points", type=str, default=None, help="Override axis points as 'z1,y1,x1;z2,y2,x2'") - ap.add_argument("--septum", type=str, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") + ap.add_argument("--septum", nargs=3, type=float, default=None, help="Septum point 'z,y,x' (optional interactive if omitted)") ap.add_argument("--outdir", type=Path, default=None) # `--write_csv` and `--plot` default to True; provide `--no-` flags to disable @@ -48,6 +48,7 @@ def script() -> None: ap.add_argument("--rv_mask", type=Path, default=None, help="Path to RV mask directory (slices) (default: None)") ap.add_argument("--value_range", nargs=2, type=float, default=[0.0, 1.0]) ap.add_argument("--circular", action="store_true", default=False, help="Use circular statistics for plotting (default: False)") + ap.add_argument("--headless", action="store_true", default=False, help="Disable popups for batch processing") args = ap.parse_args() # Resolve config/base @@ -75,6 +76,9 @@ def script() -> None: ha_dir = Path(images_path) # fallback ha_rdr = DataReader(ha_dir) + #Folder to make histogram from + hist_type = args.hist_type + # Axis points if args.axis_points: try: @@ -87,7 +91,7 @@ def script() -> None: # Septum if args.septum: - sept = tuple(map(float, args.septum.split(","))) + sept = args.septum else: # interactive picker (will open a matplotlib window) sept = utils.get_septum_point(str(args.lv_mask)) @@ -113,6 +117,8 @@ def script() -> None: additional_downsample=args.mask_downsample, rv=True, heart_mask_path=heart_mask, + headless=args.headless, + savepath=outdir ) else: seg_map, seg_radial_map = utils.create_aha_mask( @@ -124,6 +130,8 @@ def script() -> None: additional_downsample=args.mask_downsample, rv=True, rv_mask_path=str(args.rv_mask), + headless=args.headless, + savepath=outdir ) else: @@ -134,6 +142,8 @@ def script() -> None: str(images_path), return_radial_map=args.divide_radial, additional_downsample=args.mask_downsample, + headless=args.headless, + savepath=outdir ) if args.divide_radial: @@ -162,7 +172,7 @@ def script() -> None: # Write histogram data to a csv file for future analysis if args.write_csv: - csv_filename = outdir / "histogram.csv" + csv_filename = outdir / f"histogram_{hist_type}.csv" fieldnames = ( ["VALUE"] + [f"SEGMENT-{zone}" @@ -187,7 +197,6 @@ def script() -> None: val_range = args.value_range circ = args.circular - hist_type = args.hist_type if hist_type == 'HA' or hist_type == 'IA': cmap = helix_angle_cmap @@ -227,8 +236,9 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') - plt.show() - out_pdf = outdir / "hist_bullseye_26seg.pdf" + if not args.headless: + plt.show() + out_pdf = outdir / f"hist_bullseye_26seg_{hist_type}.pdf" figr.savefig(out_pdf, bbox_inches="tight") plt.close(figr) @@ -239,8 +249,9 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') - plt.show() - out_pdf = outdir / "hist_bullseye_17seg.pdf" + if not args.headless: + plt.show() + out_pdf = outdir / f"hist_bullseye_17seg_{hist_type}.pdf" figl.savefig(out_pdf, bbox_inches="tight") plt.close(figl) else: @@ -252,8 +263,9 @@ def script() -> None: cmap=cmap, colorbar_label=f'Mean {hist_type}') - plt.show() - out_pdf = outdir / "hist_bullseye_17seg.pdf" + if not args.headless: + plt.show() + out_pdf = outdir / f"hist_bullseye_17seg_{hist_type}.pdf" figl.savefig(out_pdf, bbox_inches="tight") plt.close(figl) @@ -302,10 +314,11 @@ def script() -> None: xlab=f'{hist_type}', ylab='Frequency', title='LV Histogram', - divide_radial=args.divide_radial + divide_radial=args.divide_radial, + headless = args.headless ) - out_pdf = outdir / "hist_LV.pdf" + out_pdf = outdir / f"hist_LV_{hist_type}.pdf" fig.savefig(out_pdf, bbox_inches="tight") plt.close(fig) @@ -321,10 +334,11 @@ def script() -> None: xlab=f'{hist_type}', ylab='Frequency', title='Septum Histogram', - divide_radial=args.divide_radial + divide_radial=args.divide_radial, + headless = args.headless ) - out_pdf = outdir / "hist_septum.pdf" + out_pdf = outdir / f"hist_septum_{hist_type}.pdf" fig.savefig(out_pdf, bbox_inches="tight") plt.close(fig) @@ -340,10 +354,11 @@ def script() -> None: xlab=f'{hist_type}', ylab='Frequency', title='RV Histogram', - divide_radial=args.divide_radial + divide_radial=args.divide_radial, + headless = args.headless ) - out_pdf = outdir / "hist_RV.pdf" + out_pdf = outdir / f"hist_RV_{hist_type}.pdf" fig.savefig(out_pdf, bbox_inches="tight") plt.close(fig) From 17e01c3e5d691ee855e89e66608a66d384cebaa9 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Wed, 1 Jul 2026 11:44:44 +0100 Subject: [PATCH 09/11] Reverse RV seg assignment --- src/cardiotensor/analysis/analysis_utils.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/cardiotensor/analysis/analysis_utils.py b/src/cardiotensor/analysis/analysis_utils.py index b56f9f48..ead27cb5 100644 --- a/src/cardiotensor/analysis/analysis_utils.py +++ b/src/cardiotensor/analysis/analysis_utils.py @@ -521,7 +521,7 @@ def assign_rv_region( seg_local[ (theta >= 0) & (theta < pi3) - ] = 0 + ] = 2 # sector 1 seg_local[ @@ -533,19 +533,19 @@ def assign_rv_region( seg_local[ (theta >= 2*pi3) & (theta < 3*pi3) - ] = 2 + ] = 0 # sector 3 + first half sector 4 seg_local[ (theta >= 3*pi3) & (theta < 4.5*pi3) - ] = 2 + ] = 0 # second half sector 4 + sector 5 seg_local[ (theta >= 4.5*pi3) & (theta < 6*pi3) - ] = 0 + ] = 2 for local_seg in range(3): From 3e2c94cadb35e25e5bc31b41546b63abeac70b55 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Thu, 12 Nov 2026 11:40:39 +0000 Subject: [PATCH 10/11] Write segmentation mask --- .../scripts/analysis_histograms_aha.py | 26 ++++++++++++++++++- .../scripts/analysis_transmural.py | 4 ++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/cardiotensor/scripts/analysis_histograms_aha.py b/src/cardiotensor/scripts/analysis_histograms_aha.py index c9e33eba..d615d2cc 100644 --- a/src/cardiotensor/scripts/analysis_histograms_aha.py +++ b/src/cardiotensor/scripts/analysis_histograms_aha.py @@ -12,6 +12,7 @@ from __future__ import annotations import argparse +import os from pathlib import Path import numpy as np import matplotlib.pyplot as plt @@ -19,6 +20,7 @@ from cardiotensor.utils.DataReader import DataReader from cardiotensor.utils.utils import read_conf_file import cardiotensor.analysis.analysis_utils as utils +from cardiotensor.utils.image_io import write_tif import csv from cardiotensor.colormaps.helix_angle import helix_angle_cmap @@ -49,6 +51,8 @@ def script() -> None: ap.add_argument("--value_range", nargs=2, type=float, default=[0.0, 1.0]) ap.add_argument("--circular", action="store_true", default=False, help="Use circular statistics for plotting (default: False)") ap.add_argument("--headless", action="store_true", default=False, help="Disable popups for batch processing") + ap.add_argument("--volume_output", action="store_true", default=False, help="Save map of downsampledsegmentation mask") + ap.add_argument("--volume_output_only", action="store_true", default=False, help="Save only the downsampled segmentation mask (quit before histograms)") args = ap.parse_args() # Resolve config/base @@ -151,6 +155,22 @@ def script() -> None: else: seg_map_to_use = seg_map + ## Save segmentation mask if requested + if args.volume_output or args.volume_output_only: + savepath = outdir / "Segmentation_mask" + savepath.mkdir(parents=True, exist_ok=True) + + for idx, slic in enumerate(seg_map_to_use): + out = savepath / f"segmentation_mask_{idx:06d}.tiff" + write_tif(str(out), slic) + + if args.volume_output_only: + print(f"Segmentation mask saved to {savepath}. Exiting as requested.") + return + + + + # Resample segment map to HA reader shape target_shape = tuple(ha_rdr.shape) seg_resampled = utils.resample(seg_map_to_use, target_shape=target_shape, order=0) @@ -301,7 +321,11 @@ def script() -> None: for r in range(1, 5): label = base + r rv_segs.append(label) - + + + + + # Plot overall histogram fig = utils.plot_segment_histogram( bins, diff --git a/src/cardiotensor/scripts/analysis_transmural.py b/src/cardiotensor/scripts/analysis_transmural.py index 9537a8ce..903c927b 100644 --- a/src/cardiotensor/scripts/analysis_transmural.py +++ b/src/cardiotensor/scripts/analysis_transmural.py @@ -159,8 +159,10 @@ def script() -> None: new_slices, geom = utils.ResliceMultipleSlices(axis_vec, C_reslice, images_path) + + ########################### To do: Match up geometry for C_done in zip(C_done): - geo = utils.get_geom(axis_vec, C_reslice, images_path) + geo = utils.GetResliceGeometry(axis_vec, C_reslice, images_path) for idx, slice in zip(slices, new_slices): reslices[idx] = slice From 92d831698c114c3ffaef86065f4d1f845ac44e42 Mon Sep 17 00:00:00 2001 From: lchestnutt Date: Thu, 12 Nov 2026 16:15:37 +0000 Subject: [PATCH 11/11] Restrict pool type to process Thread is not accepted for GPU use in structure_tensor package --- .../orientation_computation_functions.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/cardiotensor/orientation/orientation_computation_functions.py b/src/cardiotensor/orientation/orientation_computation_functions.py index ea942cbf..5223a072 100644 --- a/src/cardiotensor/orientation/orientation_computation_functions.py +++ b/src/cardiotensor/orientation/orientation_computation_functions.py @@ -258,7 +258,20 @@ def update_with_total(self, n=1, total=None): print("--- Flushing memory-mapped tensor outputs every 16 blocks") def run_structure_tensor(selected_devices: list[str]): + # CuPy requires a process pool rather than a thread pool. + use_cuda = any( + str(device).lower().startswith("cuda:") + for device in selected_devices + ) + + pool_type = "process" if use_cuda else None + with TqdmTotal(desc="Computing structure tensors", unit="block") as t: + kwargs = {} + + if pool_type is not None: + kwargs["pool_type"] = pool_type + return parallel_structure_tensor_analysis( volume, sigma, @@ -270,6 +283,7 @@ def run_structure_tensor(selected_devices: list[str]): eigenvectors=eigenvector_output, eigenvalues=eigenvalue_output, progress_callback_fn=t.update_with_total, + **kwargs, ) try: