def __init__(self, mvp, mask_type='unilateral', mask_threshold=0): if mask_type is 'unilateral': mask_dir = op.join(roi_dir, 'unilateral') mask_list = glob.glob(op.join(mask_dir, '*.nii.gz')) elif mask_type is 'bilateral': mask_dir = op.join(roi_dir, 'bilateral') mask_list = glob.glob(op.join(mask_dir, '*.nii.gz')) # If patterns are in epi-space, transform mni-masks to # subject specific epi-space if it doesn't exist already if mvp.ref_space == 'epi': epi_dir = op.join(op.dirname(mvp.directory), 'epi_masks', mask_type) reg_dir = op.join(mvp.directory, 'reg') print('Transforming mni-masks to epi (if necessary).') self.mask_list = convert2epi(mask_list, reg_dir, epi_dir) self.orig_mask = mvp.voxel_idx self.orig_shape = mvp.mask_shape self.orig_threshold = mvp.mask_threshold self.mask_threshold = mask_threshold _ = [ os.remove(f) for f in glob.glob(op.join(os.getcwd(), '*flirt.mat')) ]
def fit(self, X=None, y=None): """ Fits RoiIndexer. Parameters ---------- X : ndarray Numeric (float) array of shape = [n_samples, n_features] y : List of str List or ndarray with floats corresponding to labels """ # If it's not an existing file, it's meant as a query for the internal # atlases if not op.isfile(self.mask): # Remove spaces because otherwise fsl might crash basename = self.mask.replace(' ', '_').replace(',', '') basename = basename.replace('(', '_').replace(')', '_') basename = basename.replace("'", '') mask, mask_name = load_roi_mask(basename, threshold=self.mask_threshold, **self.load_roi_args) if mask is None: raise ValueError( "Could not find a mask for %s (given mask %s)" % (basename, self.mask)) self.mask = mask self.mask_name = mask_name # Check if epi-transformed mask already exists: if self.ref_space == 'epi': if not isinstance(self.mask, str): fn = op.join(self.reg_dir, self.mask_name + '.nii.gz') img = nib.Nifti1Image(self.mask.astype(int), affine=self.affine) nib.save(img, fn) self.mask = fn epi_name = op.basename(self.mask).split('.')[0] epi_exists = glob( op.join(self.reg_dir, '*%s_epi.nii.gz' % epi_name)) if epi_exists: self.mask = epi_exists[0] else: self.mask = convert2epi(self.mask, self.reg_dir, self.reg_dir) roi_idx = nib.load(self.mask).get_data() > self.mask_threshold overlap = np.zeros(self.data_shape).ravel() overlap[roi_idx.ravel()] += 1 overlap[self.orig_mask] += 1 self.idx_ = (overlap == 2)[self.orig_mask] return self
def fit(self, X=None, y=None): """ Fits RoiIndexer. Parameters ---------- X : ndarray Numeric (float) array of shape = [n_samples, n_features] y : List of str List or ndarray with floats corresponding to labels """ # Check if epi-mask already exists: if self.ref_space == 'epi': if op.basename(self.mask)[0:2] in ['L_', 'R_']: laterality = 'unilateral' else: laterality = 'bilateral' epi_dir = op.join(self.mvp.directory, 'epi_masks', laterality) if not op.isdir(epi_dir): os.makedirs(epi_dir) epi_name = op.basename(self.mask)[:-7] epi_exists = glob.glob(op.join(epi_dir, '*%s*.nii.gz' % epi_name)) if epi_exists: self.mask = epi_exists[0] else: reg_dir = op.join(self.mvp.directory, 'reg') self.mask = convert2epi(self.mask, reg_dir, epi_dir)[0] roi_idx = nib.load(self.mask).get_data() > self.mask_threshold overlap = np.zeros(self.mvp.mask_shape).ravel() overlap[roi_idx.ravel()] += 1 overlap[self.orig_mask] += 1 self.idx_ = (overlap == 2)[self.orig_mask] return self
def _load_fsl(self, src): if not op.isdir(src): msg = "The feat-directory '%s' doesn't seem to exist." % src raise ValueError(msg) if self.read_labels: design = op.join(src, 'design.con') contrast_labels_current = self._extract_labels(design_file=design) self.contrast_labels.extend(contrast_labels_current) if self.common_mask is not None: if self.ref_space == 'epi': reg_dir = op.join(src, 'reg') self.common_mask = convert2epi(self.common_mask, reg_dir, reg_dir) if self.voxel_idx is None: self._update_mask_info(self.common_mask) if self.ref_space == 'epi': stat_dir = op.join(src, 'stats') elif self.ref_space == 'mni': stat_dir = op.join(src, 'reg_standard') else: raise ValueError('Specify valid reference-space (ref_space)') if self.ref_space == 'mni' and not op.isdir(stat_dir): stat_dir = op.join(src, 'stats') transform2mni = True else: transform2mni = False copes = sort_numbered_list(glob(op.join(stat_dir, 'cope*.gz'))) varcopes = sort_numbered_list(glob(op.join(stat_dir, 'varcope*.gz'))) # Transform (var)copes if ref_space is 'mni' but files are in 'epi'. if transform2mni: copes.extend(varcopes) out_dir = op.join(src, 'reg_standard') transformed_files = convert2mni(copes, reg_dir, out_dir) half = int(len(transformed_files) / 2) copes = transformed_files[:half] varcopes = transformed_files[half:] _ = [copes.pop(idx) for idx in sorted(self.remove_idx, reverse=True)] _ = [varcopes.pop(ix) for ix in sorted(self.remove_idx, reverse=True)] n_stat = len(copes) if not n_stat == len(contrast_labels_current) and self.read_labels: msg = 'The number of trials (%i) do not match the number of ' \ 'class labels (%i)' % (n_stat, len(self.contrast_labels)) raise ValueError(msg) if self.common_mask is None: # set attributes if no mask was given tmp = nib.load(copes[0]) self.affine = tmp.affine self.nifti_header = tmp.header self.mask_shape = tmp.shape self.voxel_idx = np.arange(np.prod(tmp.shape)) # Pre-allocate mvp_data = np.zeros((n_stat, self.voxel_idx.size)) # Load in data (COPEs) for i, path in enumerate(copes): cope_img = nib.load(path) mvp_data[i, :] = cope_img.get_data().ravel()[self.voxel_idx] if self.beta2tstat: for i, varcope in enumerate(varcopes): var = nib.load(varcope).get_data() var_sq = np.sqrt(var.ravel()[self.voxel_idx]) mvp_data[i, :] = np.divide(mvp_data[i, :], var_sq) mvp_data[np.isnan(mvp_data)] = 0 self.X.append(mvp_data) # The following attributes are added for compatibility with MvpResults self.data_shape = cope_img.shape self.data_name = ['MvpWithin'] self.featureset_id = np.zeros(mvp_data.shape[1], dtype=np.uint32)
def __init__(self, mvp, preproc_pipe='default', base_clf=None, meta_clf=None, mask_type='unilateral', proba=True, folds=10, meta_fs='univar', meta_gs=None, n_cores=1): self.mvp = copy(mvp) self.mvp.X = None self.n_class = mvp.n_class self.mask_type = mask_type self.proba = proba self.n_cores = n_cores if preproc_pipe == 'default': scaler = StandardScaler() transformer = MeanEuclidean(cutoff=1, normalize=False) preproc_pipe = Pipeline([('transformer', transformer), ('scaler', scaler)]) if base_clf is None: base_clf = SVC(C=1.0, kernel='linear', probability=True, decision_function_shape='ovo') self.base_clf = base_clf base_pipe = preproc_pipe.steps base_pipe.extend([('base_clf', self.base_clf)]) self.base_pipe = Pipeline(base_pipe) self.base_pipes = [] if meta_clf is None: meta_clf = LogisticRegression(multi_class='multinomial', C=0.1, solver='lbfgs') self.meta_fs = meta_fs meta_pipe = Pipeline([('selector', meta_fs), ('scaler', scaler), ('meta_clf', meta_clf)]) if meta_gs is not None: params = dict(selector__cutoff=meta_gs) meta_pipe = GridSearchCV(meta_pipe, params, error_score=0) self.meta_pipe = meta_pipe # Glob masks if mask_type not in ['unilateral', 'bilateral']: # It is assumed that a directory with masks is inputted self.masks = glob.glob(op.join(mask_type, '*nii.gz')) else: mask_dir = op.join(roi_dir, mask_type) self.masks = glob.glob(op.join(mask_dir, '*nii.gz')) if not self.masks: raise ValueError('No masks found in specified directory!') if mvp.ref_space == 'epi': for i, mask in enumerate(self.masks): if op.basename(mask)[0:2] in ['L_', 'R_']: laterality = 'unilateral' else: laterality = 'bilateral' main_dir = op.dirname(mvp.directory) epi_dir = op.join(main_dir, 'epi_masks', laterality) if not op.isdir(epi_dir): os.makedirs(epi_dir) epi_name = op.basename(mask)[:-7] epi_exists = glob.glob( op.join(epi_dir, '*%s*.nii.gz' % epi_name)) if epi_exists: self.masks[i] = epi_exists[0] else: reg_dir = op.join(mvp.directory, 'reg') self.masks[i] = convert2epi(mask, reg_dir, epi_dir)[0] self.folds = folds # Metrics self.train_roi_scores = None self.test_roi_scores = None self.stack_dir = op.join(op.dirname(mvp.directory), 'stack_dir') if not op.isdir(self.stack_dir): os.makedirs(self.stack_dir) else: _ = [ os.remove(f) for f in glob.glob(op.join(self.stack_dir, '*.npy')) ]
from skbold.core import convert2epi import os.path as op base_dir = '/media/lukas/data/PatternAnalysis/week_1/' mask = op.join(base_dir, 'Left_Amygdala_mask.nii.gz') reg_dir = op.join(base_dir, 'sub-0037_workingmemory_WITHIN.feat', 'reg') convert2epi(mask, reg_dir=reg_dir)