def run_subject(sub, maskname="graymatter-bin_mask", settings=projectSettings, options=analysisSettings, logger=None): mask = pu.load_img(paths["root"], "derivatives", sub, "masks", "{}.nii.gz".format(maskname)) fmri_data, labels, bg_image = load_betas(settings, sub, t="cope-LSS", center=True, scale=False, logger=logger) selector = labels[labels.AB == 1].sort_values(["SubRel", "TrialTag"]) fmri_data = pu.index_img(fmri_data, selector.index) options["searchlight"]["rdm_metric"] = "correlation" results = pa.searchlight_rsa( fmri_data, model_rdms[(model_rdms.type == "full")].dropna(axis=1).values[:, 2:], m=mask, write=False, logger=logger, **options["searchlight"]) pu.data_to_img(results.scores_, bg_image).to_filename( os.path.join(paths["root"], "analysis", sub, "multivariate", "rsa", "{}_{}_AB_corr_rsaSearchlight.nii.gz".format(sub, maskname))) return results
def run_subject(sub, modelname, maskname="grayMatter-bin_mask", settings=projectSettings, options=analysisSettings, logger=None): # fmri_data, labels, bg_image, mask = load_data_lss(sub, maskname, # t=contrastSettings[modelname]["t"], # normalize=False, logger=logger) fmri_data, labels, bg_image = load_betas(settings, sub, t=options["t"], logger=logger) mask = pu.load_img(os.path.join( paths['root'], 'derivatives', sub, 'masks', settings["templates"]["masks"].format(maskname)), logger=logger) fmri_data = pu.mask_img(fmri_data, mask, logger=logger) conditionSelector = np.where( labels[contrastSettings[modelname]["label"]] != "None") op = StandardScaler() scaledData = pa.op_by_label(fmri_data, labels['chunks'], op, logger=logger) # analysis # output order: CD2AB, AB2CD cv = LeaveOneGroupOut() fmri_data = pu.unmask_img(scaledData[conditionSelector], mask, logger=logger) result = pa.searchlight( fmri_data, labels.iloc[conditionSelector][contrastSettings[modelname]["label"]], m=mask, cv=cv, groups=labels.iloc[conditionSelector][contrastSettings[modelname] ["grouping"]], logger=logger, **options['searchlight']) outpath = os.path.join(paths["root"], "analysis", sub, "multivariate", "searchlight", "{}-{}-cvsl.nii.gz".format(sub, modelname)) pu.data_to_img(result.scores_, bg_image, logger=logger).to_filename(outpath) return result
def run_subject(sub, maskname="graymatter-bin_mask", settings=projectSettings, options=analysisSettings, logger=None): mask = pu.load_img(paths["root"], "derivatives", sub, "masks", "{}.nii.gz".format(maskname), logger=logger) fmri_data, labels, bg_image = load_betas(settings, sub, t="cope-LSS", logger=logger) selector = labels[(labels.CD == 1) & (labels.Match == "1")] fmri_data = pu.index_img(fmri_data, selector.index) options["searchlight"]["estimator"] = Pipeline(steps=[ # ( # "variance_threshold", # VarianceThreshold()), ("scaling", StandardScaler()), # ("feature_select", SelectPercentile(f_classif, percentile=20)), # ("feature_select", SelectKBest(f_classif, k=100)), ("svm", LinearSVC(C=0.05)) # ("plr", LogisticRegression(C=0.05, penalty="l1", tol=0.01)) ]) # analysis # output order: CD2AB, AB2CD cv = LeaveOneGroupOut() result = pa.searchlight(fmri_data, selector.CDMainRel, m=mask, cv=cv, groups=selector['chunks'], write=False, logger=logger, **options['searchlight']) outpath = os.path.join(paths["root"], "analysis", sub, "multivariate", "searchlight", "lss", "{}_CDMatch-MainRel-cvsl.nii.gz".format(sub)) pu.data_to_img(result.scores_, bg_image, logger=logger).to_filename(outpath) return result
def __init__(self, sub, mask_file=None, settings=analysisSettings["searchlight"], phase="AB", logger=None, phase_equals=True, phase_val=1, permutations=0): self.logger = logger self.sub = sub self.phase = phase self.target = "{}MainRel".format(phase.upper()) self.mask = pu.load_img(mask_file, logger=logger) if mask_file else None self.fmri_data, self.labels, self.bg_image = load_betas(projectSettings, sub, t="cope-LSS", center=True, scale=False, logger=logger) self.select_data(phase, phase_equals, phase_val) self.init_sl(settings) self.permutations = permutations if self.permutations > 0: self.outpath = os.path.join(paths["root"], "analysis", sub, "multivariate", "searchlight", "permutation", "{}_{}-cvsl.nii.gz".format(sub, phase)) else: self.outpath = os.path.join(paths["root"], "analysis", sub, "multivariate", "searchlight", "{}_{}-cvsl.nii.gz".format(sub, phase))
def main(_): maskname = "graymatter-bin_mask" if FLAGS.debug: return # for sub in ["sub-01", "sub-02"]: if FLAGS.subject: subjects = [FLAGS.subject] else: subjects = projectSettings["subjects"] for sub in subjects: logging.info("Starting subject {}".format(sub)) mask = pu.load_img(paths["root"], "derivatives", sub, "masks", "{}.nii.gz".format(maskname)) fmri_data, labels, _ = load_betas(projectSettings, sub, t="cope-LSS", center=True, scale=False) # TODO : add logic here to define models too if FLAGS.phase == "AB": selector = labels.AB == 1 tag_key = "ABTag" elif FLAGS.phase == "CD": selector = labels.CD == 1 tag_key = "CDTag" elif FLAGS.phase == "CDMatch": selector = (labels.CD == 1) & (labels.Match == "1") tag_key = "CDTag" elif FLAGS.phase == "CDNoMatch": selector = (labels.CD == 1) & (labels.Match == "0") tag_key = "CDTag" fmri_data = pu.mask_img(fmri_data, mask) if FLAGS.betas: if FLAGS.average: val_trials = labels[labels.CD == 1] val_trials = val_trials.sort_values(tag_key) val_fmri_data = fmri_data[val_trials.index] val_fmri_data = (val_fmri_data[::2] + val_fmri_data[1::2]) / 2 val_labels = val_trials.iloc[::2] else: val_trials = labels[(labels.CD == 1) & (labels.Match == "1")] val_fmri_data = fmri_data[val_trials.index] val_labels = labels.loc[val_trials.index] trials = labels[selector] if FLAGS.average: trials = trials.sort_values(tag_key) fmri_data = fmri_data[trials.index] fmri_data = (fmri_data[::2] + fmri_data[1::2]) / 2 labels = trials.iloc[::2] else: fmri_data = fmri_data[trials.index] labels = labels.loc[trials.index] cv = CV_LIB.get(FLAGS.cv, KFold)(FLAGS.n_folds) # groups = trials["SubRel"] if FLAGS.cv == "relation" else trials["chunks"] groups = labels["SubRel"] if FLAGS.cv == "relation" else labels[ "chunks"] # groups = trials["MainRel"] if FLAGS.cv == "relation" else trials["chunks"] # model = Ridge(alpha=0.1) # model = ElasticNet(alpha=0.1) model = ElasticNet(alpha=FLAGS.alpha) # model = Ridge(alpha=FLAGS.alpha) scoring = make_scorer(corrcoef) for mname, model_df in zip( model_names, [bart_df, w2vd_df, w2vc_df ]): #, bartnorm_df, bartpower_df, bart270_df]): if len(model_df) > 144: model_df = model_df.iloc[::2] logging.info("Running {}".format(mname)) features = model_df.loc[[tag for tag in labels[tag_key]], :] if FLAGS.dists: features["dists"] = np.concatenate([ rsa.pdist( model_df.iloc.loc[[t.split("::")[0], t.split("::")[1]]], metric="cosine") for t in trials.TrialTag ]) # result = Parallel(n_jobs=MAX_CPU)(delayed(run_voxel)(v, features, fmri_data) for v in range(fmri_data.shape[1])) if FLAGS.betas: val_features = model_df.loc[ [tag for tag in val_labels["CDTag"]], :] results = Parallel(n_jobs=MAX_CPU)( delayed(get_betas)(v, model, features, fmri_data, val_features, val_fmri_data) for v in range(fmri_data.shape[1])) result, preds = list(zip(*results)) result = np.array(result).T pu.unmask_img(result, mask).to_filename( os.path.join( paths["root"], "analysis", sub, "encoding", "{}_{}_{}_{}_encoding-betas.nii.gz".format( sub, mname, "cope-LSS", FLAGS.phase))) preds = np.array(preds) pu.unmask_img(preds, mask).to_filename( os.path.join( paths["root"], "analysis", sub, "encoding", "{}_{}_{}_{}_pred-CD.nii.gz".format( sub, mname, "cope-LSS", FLAGS.phase))) if FLAGS.cv: result = Parallel(n_jobs=MAX_CPU)( delayed(run_cv_voxel)(v, model, features, fmri_data, cv, groups, scoring, FLAGS.permutations) for v in range(fmri_data.shape[1])) result = np.array(result) if FLAGS.permutations: pu.unmask_img(result[:, 0], mask).to_filename( os.path.join( paths["root"], "analysis", sub, "encoding", "{}_{}_{}_{}_cv-{}.nii.gz".format( sub, mname, "cope-LSS", FLAGS.phase, FLAGS.cv))) pu.unmask_img(result[:, 1], mask).to_filename( os.path.join( paths["root"], "analysis", sub, "encoding", "{}_{}_{}_{}_cv-{}_pval.nii.gz".format( sub, mname, "cope-LSS", FLAGS.phase, FLAGS.cv))) else: pu.unmask_img(result, mask).to_filename( os.path.join( paths["root"], "analysis", sub, "encoding", "{}_{}_{}_{}_cv-{}.nii.gz".format( sub, mname, "cope-LSS", FLAGS.phase, FLAGS.cv)))