|
| 1 | +#%% import |
| 2 | +import pyrootutils |
| 3 | +import numpy as np |
| 4 | +import traceback |
| 5 | +import pandas as pd |
| 6 | +import os |
| 7 | + |
| 8 | +pyrootutils.setup_root(__file__, indicator=".project-root", pythonpath=True) |
| 9 | +from src.utils.spharmnet.lib.io import read_annot, read_feat, read_mesh |
| 10 | +from src.utils.spharmnet.lib.sphere import TriangleSearch |
| 11 | + |
| 12 | + |
| 13 | +# %% extract patch data from surface |
| 14 | +def get_patch_data( |
| 15 | + ico_v: np.array, |
| 16 | + triangle_mesh_indices: pd.DataFrame, |
| 17 | + in_ch: list[str] = ["area", "sphere", "thickness", "volume", "curv", "sulc", "inflated.H"], |
| 18 | + annot_file: str = "aparc", |
| 19 | + sub: str = "data/freesurfer/sub-IXI031", |
| 20 | + hemi: str = "lh", |
| 21 | +) -> tuple[str, dict[np.array], list]: |
| 22 | + |
| 23 | + # paths |
| 24 | + surf_dir = sub / "surf" |
| 25 | + label_dir = sub / "label" |
| 26 | + |
| 27 | + # load native sphere |
| 28 | + # ------------------------------------------------------------------------------ |
| 29 | + try: |
| 30 | + sphere_path = os.path.join(surf_dir, hemi + "." + "sphere") |
| 31 | + native_v, native_f = read_mesh(sphere_path) |
| 32 | + except FileNotFoundError as e: |
| 33 | + print(f"\tsub: {sub} | Error: File {sphere_path} not found.") |
| 34 | + # raise e # Re-raise the exception to see the full traceback |
| 35 | + return None, None, None, None |
| 36 | + except Exception as e: |
| 37 | + print(f"\tsub: {sub} | An error occurred while reading the mesh:\n{e}") |
| 38 | + traceback.print_exc() |
| 39 | + return None, None, None, None |
| 40 | + try: |
| 41 | + tree = TriangleSearch(native_v, native_f) |
| 42 | + triangle_idx, bary_coeff = tree.query(ico_v) |
| 43 | + except Exception as e: |
| 44 | + print(f"\tsub: {sub} | An error occurred during triangle search and query:\n{e}") |
| 45 | + traceback.print_exc() |
| 46 | + return None, None, None, None |
| 47 | + |
| 48 | + # extract sphere features |
| 49 | + # ------------------------------------------------------------------------------ |
| 50 | + try: |
| 51 | + feat_patches = {feat_name: None for feat_name in in_ch} |
| 52 | + for feat_name in in_ch: |
| 53 | + # load surface feature |
| 54 | + feat_path = os.path.join(surf_dir, hemi + "." + feat_name) |
| 55 | + try: |
| 56 | + feat = read_feat(feat_path) # feat: features (115231, 1) |
| 57 | + except Exception as feat_read_error: |
| 58 | + print(f"\tsub: {sub} | Error reading feature '{feat_name}' from '{feat_path}': {feat_read_error}") |
| 59 | + traceback.print_exc() |
| 60 | + return None, None, None, None |
| 61 | + |
| 62 | + # remesh surf feature: 115231 -> 40962 |
| 63 | + try: |
| 64 | + feat_remesh = np.multiply(feat[native_f[triangle_idx]], bary_coeff).sum( |
| 65 | + -1 |
| 66 | + ) # feat_remesh: features (40962, 1) |
| 67 | + assert feat_remesh.shape[0] == ico_v.shape[0], f"feat_remesh.shape[0] != ico_v.shape[0]" |
| 68 | + except Exception as feat_processing_error: |
| 69 | + print(f"\tsub: {sub} | Error processing feature '{feat_name}': {feat_processing_error}") |
| 70 | + traceback.print_exc() |
| 71 | + return None, None, None, None |
| 72 | + |
| 73 | + # extract triangle patches |
| 74 | + try: |
| 75 | + data = feat_remesh[triangle_mesh_indices.values].T # num_patches x num_vertices |
| 76 | + feat_patches[feat_name] = data |
| 77 | + except Exception as feat_extract_error: |
| 78 | + print(f"\tsub: {sub} | Error extracting feature '{feat_name}': {feat_extract_error}") |
| 79 | + traceback.print_exc() |
| 80 | + return None, None, None, None |
| 81 | + |
| 82 | + except Exception as e: |
| 83 | + print(f"\tsub: {sub} | An error occurred during feature extraction:\n{e}") |
| 84 | + traceback.print_exc() |
| 85 | + return None, None, None, None |
| 86 | + |
| 87 | + # extract labels |
| 88 | + # ------------------------------------------------------------------------------ |
| 89 | + try: |
| 90 | + # laod annotation |
| 91 | + num_vert = native_v.shape[0] |
| 92 | + label_arr = np.zeros(num_vert, dtype=np.int16) |
| 93 | + annot = os.path.join(label_dir, hemi + "." + annot_file + ".annot") |
| 94 | + try: |
| 95 | + vertices, label, sturcture_ls, structureID_ls = read_annot( |
| 96 | + annot |
| 97 | + ) # vertices: vertex indices (115231,), label: labels (115231,), sturcture_ls: structure names (36,), structureID_ls: structure IDs (36,) |
| 98 | + except Exception as annot_read_error: |
| 99 | + print(f"\tsub: {sub} | Error reading annotation from '{annot}': {annot_read_error}") |
| 100 | + traceback.print_exc() |
| 101 | + return None, None, None, None |
| 102 | + |
| 103 | + # remesh roi label: 115231 -> 40962 |
| 104 | + try: |
| 105 | + label = [structureID_ls.index(l) if l in structureID_ls else 0 for l in label] |
| 106 | + label_arr[vertices] = label |
| 107 | + label_remesh = label_arr[ |
| 108 | + native_f[triangle_idx, np.argmax(bary_coeff, axis=1)] |
| 109 | + ] # label_remesh: labels (40962,) |
| 110 | + assert label_remesh.shape[0] == ico_v.shape[0], "label_remesh.shape[0] != ico_v.shape[0]" |
| 111 | + except Exception as label_processing_error: |
| 112 | + print(f"\tsub: {sub} | Error processing label: {label_processing_error}") |
| 113 | + traceback.print_exc() |
| 114 | + return None, None, None, None |
| 115 | + |
| 116 | + # extract triangle patches |
| 117 | + try: |
| 118 | + label_remesh = label_remesh[triangle_mesh_indices.values].T # num_patches x num_vertices |
| 119 | + except Exception as label_extract_error: |
| 120 | + print(f"\tsub: {sub} | Error extracting label: {label_extract_error}") |
| 121 | + traceback.print_exc() |
| 122 | + return None, None, None, None |
| 123 | + |
| 124 | + except Exception as e: |
| 125 | + print(f"\tsub: {sub} | An error occurred during label extraction:\n{e}") |
| 126 | + traceback.print_exc() |
| 127 | + return None, None, None, None |
| 128 | + |
| 129 | + # extract structure map |
| 130 | + structure_map = list(enumerate(sturcture_ls)) |
| 131 | + return sub, feat_patches, label_remesh, structure_map |
| 132 | + |
| 133 | + |
| 134 | +#%% calcualte running stats |
| 135 | +class RunningStats: |
| 136 | + def __init__(self): |
| 137 | + self.N = 0 |
| 138 | + self.mean = 0.0 |
| 139 | + self.M2 = 0.0 |
| 140 | + |
| 141 | + def update(self, data): |
| 142 | + self.N += 1 |
| 143 | + self.mean += np.mean(data) |
| 144 | + self.M2 += np.mean(data**2) |
| 145 | + |
| 146 | + def get_mean(self): |
| 147 | + return self.mean / self.N |
| 148 | + |
| 149 | + def get_std(self): |
| 150 | + mean = self.mean / self.N |
| 151 | + m2 = self.M2 / self.N |
| 152 | + return np.sqrt(m2 - mean**2) |
| 153 | +# %% |
0 commit comments