def _load_rsMRI_tmseries(self, sid, parpath=None): """ Load rsMRI time series of one participant """ if parpath is None: parpath = self.parpath rsMRI = np.zeros((1200, 59412)) indicator = 0 # Load LR1 try: rsMRI_tmp, _ = cifti.read(pjoin(parpath, sid, 'MNINonLinear', 'Results', 'rfMRI_REST1_LR', 'rfMRI_REST1_LR_Atlas_hp2000_clean.dtseries.nii')) except IOError: indicator+=1 try: rsMRI+=rsMRI_tmp[:,:59412] except (ValueError,UnboundLocalError): pass print('.LR1') # Load RL1 try: rsMRI_tmp, _ = cifti.read(pjoin(parpath, sid, 'MNINonLinear', 'Results', 'rfMRI_REST1_RL', 'rfMRI_REST1_RL_Atlas_hp2000_clean.dtseries.nii')) except IOError: indicator+=1 try: rsMRI+=rsMRI_tmp[:,:59412] except (ValueError,UnboundLocalError): pass print('.RL1') # Load LR2 try: rsMRI_tmp, _ = cifti.read(pjoin(parpath, sid, 'MNINonLinear', 'Results', 'rfMRI_REST2_LR', 'rfMRI_REST2_LR_Atlas_hp2000_clean.dtseries.nii')) except IOError: indicator+=1 try: rsMRI+=rsMRI_tmp[:,:59412] except (ValueError,UnboundLocalError): pass print('.LR2') # Load RL2 try: rsMRI_tmp, _ = cifti.read(pjoin(parpath, sid, 'MNINonLinear', 'Results', 'rfMRI_REST2_RL', 'rfMRI_REST2_RL_Atlas_hp2000_clean.dtseries.nii')) except IOError: indicator+=1 try: rsMRI+=rsMRI_tmp[:,:59412] except (ValueError,UnboundLocalError): pass print('.RL2') rsMRI = rsMRI/(4-indicator) return rsMRI
def load_myelin(self, myelinpath=None, outpath=None): """ Method to load myelination and extract the averaged signals in each ROIs. Please call load_mask before it. Parameters: ------------ myelinpath[str]: parent path of myelination """ print('Myelin extraction....') if myelinpath is None: myelinpath = self.parpath myelin_value = [] for i, sj in enumerate(self.sessid): myelinmap_tmp, _ = cifti.read(pjoin(myelinpath, sj, 'MNINonLinear', 'fsaverage_LR32k', sj+'.MyelinMap_BC_MSMAll.32k_fs_LR.dscalar.nii')) myelinmap_tmp = myelinmap_tmp[:,:59412] myelinlang_tmp = surf_tools.get_signals(myelinmap_tmp, self.langroi[i,:], roilabels=self.langlbl) myelinlang_tmp = np.array(myelinlang_tmp) myelinmath_tmp = surf_tools.get_signals(myelinmap_tmp, self.mathroi[i,:], roilabels=self.mathlbl) myelinmath_tmp = np.array(myelinmath_tmp) myelinvalue_tmp = np.concatenate((myelinlang_tmp, myelinmath_tmp), axis=0)[:,0] myelin_value.append(myelinvalue_tmp) myelin_value = np.array(myelin_value) self.myelin_value = myelin_value if outpath is not None: np.save(pjoin(outpath, 'myelin_value.npy'), myelin_value) return myelin_value
def load_activation(self, actpath=None, outpath=None): """ Method to load myelination and extract the averaged signals in each ROIs. Please call load_mask before it. Parameters: ------------ myelinpath[str]: parent path of myelination """ print('Activation extraction....') if actpath is None: actpath = self.parpath act_value = [] for i, sj in enumerate(self.sessid): actmap_tmp, _ = cifti.read(pjoin(actpath, sj, 'MNINonLinear', 'Results', 'tfMRI_LANGUAGE', 'tfMRI_LANGUAGE_hp200_s4_level2_MSMAll.feat', 'GrayordinatesStats', 'cope3.feat', 'zstat1.dtseries.nii')) actmap_tmp = actmap_tmp[:,:59412] actlang_tmp = surf_tools.get_signals(-1.0*actmap_tmp, self.langroi[i,:], roilabels=self.langlbl) actlang_tmp = np.array(actlang_tmp) actmath_tmp = surf_tools.get_signals(actmap_tmp, self.mathroi[i,:], roilabels=self.mathlbl) actmath_tmp = np.array(actmath_tmp) actvalue_tmp = np.concatenate((actlang_tmp, actmath_tmp), axis=0)[:,0] act_value.append(actvalue_tmp) act_value = np.array(act_value) self.act_value = act_value if outpath is not None: np.save(pjoin(outpath, 'act_value.npy'), act_value) return act_value
def __init__(self, output_dir, cifti_file, parcel_file, parcel_name, seed_ROI_name, level, pipeline, ICAstring, vol_fmritcs, confound, smoothing, regname, fmriname, fmrifoldername, seed_analysis_output): ''' Class initialization for seed based analysis. The primary purpose of this class is to: 1) Performs tests on arguments cifti_file and parcel_file to ensure inputted arguments are in the expected format 2) Intialize important variables that will be used for downstream child classes 'regression' and 'connectivity' ''' # path that data will be written to self.output_dir = output_dir # inputted cifti file self.cifti_file = cifti_file if len(self.cifti_file) > 0: self.shortfmriname = self.cifti_file.split("/")[-2] # inputted atlas/parcellation file self.parcel_file = parcel_file # shorthand name chosen for parcel file self.parcel_name = parcel_name # seed ROI name used for analysis self.seed_ROI_name = seed_ROI_name # level of analysis to be done self.level = level #arguments that may change depending on analysis level self.pipeline = pipeline self.ICAstring = ICAstring self.vol_fmritcs = vol_fmritcs self.confound = confound self.smoothing = smoothing self.regname = regname self.fmriname = fmriname self.fmrifoldername = fmrifoldername self.seed_analysis_output = seed_analysis_output # create output folder if it does not exist if not os.path.isdir(self.output_dir): os.makedirs(self.output_dir) # read parcel labels into list to query later read_parcel_file = cifti.read(self.parcel_file) parcel_file_label_tuple = read_parcel_file[1][0][0][1] parcel_labels = [] for value in parcel_file_label_tuple: if not '???' in parcel_file_label_tuple[value][0]: parcel_labels.append(parcel_file_label_tuple[value][0]) self.parcel_labels = parcel_labels # do tests on cifti file and load if self.level == 1: self.cifti_tests() # inputted argument 'seed_ROI_name' is a list, if longer than 1 parse otherwise do not if type(self.seed_ROI_name) == list: if len(self.seed_ROI_name) > 1: separator = "-" self.seed_ROI_string = separator.join(self.seed_ROI_name) else: self.seed_ROI_string = self.seed_ROI_name[0] else: self.seed_ROI_string = self.seed_ROI_name
def medial_wall_mask(self): if self._median_wall is None: file_path = manager.get_full_path( self.asset_category, file_names[TopoName.MEDIAL_WALL][self.space]) self._median_wall = cifti.read(file_path)[0].squeeze() return self._median_wall
def load_raw_file(file: StorageFile, space: Space): data = cifti.read(file.loadable_path)[0].T if space == Space.K59: fs = 1.0 elif space == Space.K32: fs = 1000 / 720 else: raise ValueError( f"{space} is not defined in loading a single raw file") return data, fs
def load(self): if not self.loaded: mask, (lbl_axis, brain_axis) = cifti.read(self.file_full_path) mask = np.squeeze(mask) lbl_dict = lbl_axis.label.item() regions = np.asarray( [lbl_dict[key][0] for key in list(lbl_dict.keys())])[1:] networks = [x.split("_")[2] for x in regions] unique_networks = np.unique(networks) self._data = TemplateData(mask, unique_networks, networks, regions, brain_axis)
def load(self): if not self.loaded: mask, (lbl_axis, brain_axis) = cifti.read(self.file_full_path) mask = np.squeeze(mask) lbl_dict = lbl_axis.label.item() regions = np.asarray([lbl_dict[x][0] for x in np.unique(mask)])[1:] networks = [ "".join(x.split("_")[0].split("-")[:-1]) for x in regions ] unique_networks = np.unique(networks) self._data = TemplateData(mask, unique_networks, networks, regions, brain_axis)
def _load_surface_cifti(self, datapath): """ """ data, header = cifti.read(datapath) vxidx = header[1].get_element assert (data.shape[1] == 59412) | (data.shape[1] == 91282), "Not in fsLR_32k space." vxid_left = [vxidx(i)[1] for i in range(29696)] vxid_right = [vxidx(i)[1] for i in range(29696,59412)] data_left = np.zeros((data.shape[0], 32492)) data_right = np.zeros((data.shape[0], 32492)) data_left[:,vxid_left] = data[:,:29696] data_right[:,vxid_right] = data[:,29696:59412] return data_left, data_right
def open_cifti(path): """ A wrapper to the cifti.read method, that also allows handling files not in cifti-2 format (using wb_command convert_to_CIFTI2 command) :param path: a path to a .nii file :return: arr, (axis, bm) - see cifti.read documentation """ try: arr, (series, bm) = cifti.read(path) return arr.astype(np.float32), (series, bm) except ValueError as ve: if str(ve) == 'Only CIFTI-2 files are supported': with TemporaryDirectory() as tmp_dir: cifti2path = os.path.join(tmp_dir, os.path.basename(path)) cmd_utils.convert_to_CIFTI2(path, cifti2path) arr, (ax, bm) = cifti.read(cifti2path) arr2 = np.copy(arr) del arr return arr2.astype(np.float32), (ax, bm) except FileNotFoundError as fnfe: raise PitecaError(fnfe.strerror, path)
def load_mask(self, mask_parpath): """ Load mask ---------- mask_parpath[list]: two elements """ # Load mask langroi, _ = cifti.read(mask_parpath[0]) mathroi, _ = cifti.read(mask_parpath[1]) langroi = langroi[:,:59412] mathroi = mathroi[:,:59412] if langroi.shape[0] == 1: self.langroi = np.tile(langroi, (self.subjnum, 1)) else: self.langroi = langroi if mathroi.shape[0] == 1: self.mathroi = np.tile(mathroi, (self.subjnum, 1)) else: self.mathroi = mathroi # Get mask labels self.langlbl = np.unique(langroi[langroi!=0]) self.mathlbl = np.unique(mathroi[mathroi!=0]) self.region_num = len(self.langlbl) + len(self.mathlbl)
def map_regions_pc_cole(): no_color = (1.0, 1.0, 1.0, 0.0) tpt = tpt_cole img, (lbl, brain) = cifti.read(tpt.file_full_path) regions = lbl.label.item() for h in [HierarchyName.EXTENDED_PERIPHERY_CORE, HierarchyName.RESTRICTED_PERIPHERY_CORE]: hierarchy = tpt.net_hierarchy(h) cp_out = {} img_out = np.zeros(img.shape) found_regions = {} for index, (name, c) in regions.items(): if index == 0 or index > 360: cp_out[index] = name, no_color continue net, lh = name.split("_") net_parts = net.split("-") net, rgn = ("".join(net_parts[:2]), net_parts[2]) if len(net_parts) == 3 else net_parts is_p = net in hierarchy["P"] is_c = net in (hierarchy["RC"] if "RC" in hierarchy else hierarchy["EC"]) if rgn not in found_regions: new_index = len(found_regions) + 1 found_regions[rgn] = new_index if is_p: color = PC_colors_tuple[0] elif is_c: color = PC_colors_tuple[1] else: color = no_color print(f"{net} without color in {lbl}") cp_out[new_index] = rgn, color else: new_index = found_regions[rgn] img_out[img == index] = new_index # noinspection PyTypeChecker cifti.write(f"figures/cole.{lbl}.dlabel.nii", img_out, (cifti.Label([cp_out]), brain)) os.system(f"wb_command -cifti-separate figures/cole.{lbl}.dlabel.nii COLUMN " f"-label CORTEX_LEFT figures/cole.{lbl}.L.label.gii " f"-label CORTEX_RIGHT figures/cole.{lbl}.R.label.gii") os.system(f"wb_command -label-to-border " f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.L.surf.gii')} " f"figures/cole.{lbl}.L.label.gii figures/cole.{lbl}.L.border") os.system(f"wb_command -label-to-border " f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.R.surf.gii')} " f"figures/cole.{lbl}.R.label.gii figures/cole.{lbl}.R.border")
def load(self): if self.loaded: return self.template() voxels = cifti.read( self.file_full_path)[0][:, self.medial_wall_mask == 0].squeeze() mask_no_wall = self.template.data.mask[self.medial_wall_mask == 0] topo = DataFrame({ "region": Series(dtype=str), "network": Series(dtype=str), "gradient": Series(dtype=float) }) for i, (reg, net) in enumerate( zip(self.template.data.regions, self.template.data.networks)): topo.loc[i, :] = reg, net, voxels[mask_no_wall == i + 1].mean() self._data = topo
def load(self): if self.loaded: return self.template() voxels = cifti.read(self.file_full_path)[0][:, self.medial_wall_mask == 0] mask_no_wall = self.template.data.mask[self.medial_wall_mask == 0] topo = DataFrame({ "region": Series(dtype=str), "network": Series(dtype=str), "coord_x": Series(dtype=float), "coord_y": Series(dtype=float), "coord_z": Series(dtype=float) }) for i, (reg, net) in enumerate( zip(self.template.data.regions, self.template.data.networks)): x, y, z = voxels[:, mask_no_wall == i + 1].mean(axis=1) topo.loc[i, :] = reg, net, x, y, z self._data = topo
def load_brainimg(imgpath, ismask=False): """ Load brain image identified by its suffix suffix now support Nifti: .nii.gz freesurfer: .mgz, .mgh cifti: .dscalar.nii, .dlabel.nii, .dtseries.nii Parameters: ------------ imgpath: brain image data path Returns: ------------ brain_img[np.array]: data of brain image header[header]: header of brain image """ imgname = os.path.basename(imgpath) imgsuffix = imgname.split('.')[1:] imgsuffix = '.'.join(imgsuffix) if imgsuffix == 'nii.gz': brain_img = nib.load(imgpath).get_data() if not ismask: brain_img = np.transpose(brain_img, (3, 0, 1, 2)) header = nib.load(imgpath).header elif imgsuffix == 'mgz' or imgsuffix == 'mgh': brain_img = nib.freesurfer.load(imgpath).get_data() if not ismask: brain_img = np.transpose(brain_img, (3, 0, 1, 2)) header = nib.freesurfer.load(imgpath).header elif imgsuffix == 'dscalar.nii' or imgsuffix == 'dlabel.nii' or imgsuffix == 'dtseries.nii': brain_img, header = cifti.read(imgpath) if not ismask: brain_img = brain_img[..., None, None] else: brain_img = brain_img[..., None] else: raise Exception( 'Not support this format of brain image data, please contact with author to update this function.' ) return brain_img, header
def map_nets_sh2007(): tpt = tpt_sh img, (lbl, brain) = cifti.read(tpt.file_full_path) regions = lbl.label.item() net_out = {} img_out = np.zeros(img.shape) nets = tpt.net_order palette = tpt.net_colors for index, (name, c) in regions.items(): if index == 0: net_out[index] = name, c continue network = name.split("_")[2] net_index = nets.index(network) + 1 if net_index not in net_out: net_out[net_index] = network, palette[net_index - 1] + [1, ] img_out[img == index] = net_index # noinspection PyTypeChecker cifti.write(f"figures/sh7nets.dlabel.nii", img_out, (cifti.Label([net_out]), brain))
def load_thickness(self, thickpath=None, outpath=None): """ Method to load thickness and extract the averaged signals in each ROIs. """ print('Thickness extraction....') if thickpath is None: thickpath = self.parpath thick_value = [] for i, sj in enumerate(self.sessid): thickmap_tmp, _ = cifti.read(pjoin(thickpath, sj, 'MNINonLinear', 'fsaverage_LR32k', sj+'.thickness_MSMAll.32k_fs_LR.dscalar.nii')) thickmap_tmp = thickmap_tmp[:,:59412] thicklang_tmp = surf_tools.get_signals(thickmap_tmp, self.langroi[i,:], roilabels=self.langlbl) thicklang_tmp = np.array(thicklang_tmp) thickmath_tmp = surf_tools.get_signals(thickmap_tmp, self.mathroi[i,:], roilabels=self.mathlbl) thickmath_tmp = np.array(thickmath_tmp) thickvalue_tmp = np.concatenate((thicklang_tmp, thickmath_tmp), axis=0)[:,0] thick_value.append(thickvalue_tmp) thick_value = np.array(thick_value) self.thick_value = thick_value if outpath is not None: np.save(pjoin(outpath, 'thick_value.npy'), thick_value) return thick_value
def map_regions_pc_sh2007(): tpt = tpt_sh img, (lbl, brain) = cifti.read(tpt.file_full_path) regions = lbl.label.item() hierarch = tpt.net_hierarchy(HierarchyName.PERIPHERY_CORE) cp_out = {} img_out = np.zeros(img.shape) found_regions = {} for index, (name, c) in regions.items(): if index == 0: cp_out[index] = name, c continue parts = name.split("_") lr, network, rgn, num = parts[1], parts[2], parts[-2], parts[-1] cp = 0 if network in hierarch["P"] else 1 if rgn not in found_regions: new_index = len(found_regions) + 1 found_regions[rgn] = new_index cp_out[new_index] = rgn, PC_colors_tuple[cp] else: new_index = found_regions[rgn] img_out[img == index] = new_index # noinspection PyTypeChecker cifti.write(f"figures/sh7cp.dlabel.nii", img_out, (cifti.Label([cp_out]), brain)) os.system(f"wb_command -cifti-separate figures/sh7cp.dlabel.nii COLUMN " f"-label CORTEX_LEFT figures/sh7cp.L.label.gii " f"-label CORTEX_RIGHT figures/sh7cp.R.label.gii") os.system(f"wb_command -label-to-border " f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.L.surf.gii')} " f"figures/sh7cp.L.label.gii figures/sh7cp.L.border") os.system(f"wb_command -label-to-border " f"{get_full_path(AssetCategory.HCP1200, 'anat.midthickness.32k.R.surf.gii')} " f"figures/sh7cp.R.label.gii figures/sh7cp.R.border")
def map_nets_cole(): tpt = tpt_cole img, (lbl, brain) = cifti.read(tpt.file_full_path) regions = lbl.label.item() net_out = {} img_out = np.zeros(img.shape) nets = tpt.net_order palette = tpt.net_colors for index, (name, c) in regions.items(): if index == 0: net_out[index] = name, c continue network, lh = name.split("_") net_parts = network.split("-") network, rgn = ("".join(net_parts[:2]), net_parts[2]) if len(net_parts) == 3 else net_parts net_index = nets.index(network) + 1 if net_index not in net_out: net_out[net_index] = network, palette[net_index - 1] + [1, ] img_out[img == index] = net_index # noinspection PyTypeChecker cifti.write(f"figures/colenets.dlabel.nii", img_out, (cifti.Label([net_out]), brain))
####################### # Define structure name per hemisphere to extract from cifti data: brainstruct = {'L':'CIFTI_STRUCTURE_CORTEX_LEFT','R':'CIFTI_STRUCTURE_CORTEX_RIGHT'} # Load connectivity targets and mask: targimg = {} targts = [] maskimg = {} targets = {} subimg = {} subds = [] zdss = [] ind = {} for ses in ['LR','RL']: cname = '%s/%s/rfMRI_REST1_%s/rfMRI_REST1_%s_10k_Atlas_MSMAll_clean_24nuisance.reg_lin.trend_filt_sm6.dtseries.nii' % (tempdir,sub,ses,ses) tmpimg =cifti.read(cname) zds = tmpimg[0] zscore(zds,chunks_attr=None) nverts = zds.shape[1] zdss.append(zds) for hemi in ['L', 'R']: # Mask: tmpmask = gifti_dataset( '%s/outgoing/%s.HCP_10k_mask.func.gii' % (tempdir,hemi)) maskimg[hemi] = np.where(tmpmask.samples != 0)[1] # Connectivity Targets: tmptargs = gifti_dataset( '%s/resources/700_data/%s.700_to_10k_conn_targs.func.gii' % (tempdir, hemi)) tmptargs = tmptargs[:, maskimg[hemi]] targimg[hemi] = np.where(tmptargs.samples != 0)[1] # Extract hemi data: