def export_into_csv(template_system, mmvt_dir, bipolar=False, prefix='', input_fname=''): template = 'fsaverage' if template_system == 'ras' else 'colin27' if template_system == 'mni' else template_system if input_fname == '': input_name = '{}electrodes{}_positions.npz'.format( prefix, '_bipolar' if bipolar else '') input_fname = op.join(mmvt_dir, template, 'electrodes', input_name) electrodes_dict = utils.Bag(np.load(input_fname)) fol = utils.make_dir(op.join(MMVT_DIR, template, 'electrodes')) csv_fname = op.join( fol, '{}{}_{}RAS.csv'.format(prefix, template, 'bipolar_' if bipolar else '')) print('Writing csv file to {}'.format(csv_fname)) with open(csv_fname, 'w') as csv_file: wr = csv.writer(csv_file, quoting=csv.QUOTE_NONE) wr.writerow(['Electrode Name', 'R', 'A', 'S']) for elc_name, elc_coords in zip(electrodes_dict.names, electrodes_dict.pos): wr.writerow([ elc_name, *['{:.2f}'.format(x) for x in elc_coords.squeeze()] ]) fol = utils.make_dir(op.join(MMVT_DIR, template, 'electrodes')) csv_fname2 = op.join(fol, utils.namebase_with_ext(csv_fname)) if csv_fname != csv_fname2: utils.copy_file(csv_fname, csv_fname2) print('export_into_csv: {}'.format( op.isfile(csv_fname) and op.isfile(csv_fname2))) return csv_fname
def calc_subject_evoked_response(subject, root_fol, task, atlas, events_id, fname_format, fwd_fol, neccesary_files, remote_subjects_dir, fsaverage, raw_cleaning_method, inverse_method, indices=None, overwrite_epochs=False, overwrite_evoked=False, positive=True, moving_average_win_size=100): meg.init_globals(subject, fname_format=fname_format, raw_cleaning_method=raw_cleaning_method, subjects_meg_dir=SUBJECTS_MEG_DIR, task=task, subjects_mri_dir=SUBJECTS_DIR, BLENDER_ROOT_DIR=BLENDER_ROOT_DIR, files_includes_cond=True, fwd_no_cond=True) epochs_fname = '{}_arc_rer_{}-epo.fif'.format(subject, raw_cleaning_method) events_fname = '{}_arc_rer_{}-epo.csv'.format(subject, raw_cleaning_method) if indices is None: indices = find_events_indices(op.join(root_fol, events_fname)) if not indices is None: utils.make_dir(op.join(SUBJECTS_MEG_DIR, task, subject)) utils.make_dir(op.join(SUBJECTS_DIR, subject, 'mmvt')) utils.make_dir(op.join(BLENDER_ROOT_DIR, subject)) # utils.prepare_subject_folder( # neccesary_files, subject, remote_subjects_dir, SUBJECTS_DIR, print_traceback=False) # anatomy_preproc.freesurfer_surface_to_blender_surface(subject, overwrite=False) # anatomy_preproc.create_annotation_file_from_fsaverage(subject, atlas, fsaverage, False, False, False, True) # calc_evoked(indices, op.join(root_fol, epochs_fname), overwrite_epochs, overwrite_evoked) fwd_fname = '{}_arc_rer_tsss-fwd.fif'.format(subject) if not op.isfile(op.join(SUBJECTS_MEG_DIR, task, subject, fwd_fname)): utils.copy_file(op.join(fwd_fol, fwd_fname), op.join(SUBJECTS_MEG_DIR, task, subject, fwd_fname)) # meg_preproc.calc_inverse_operator(events_id, calc_for_cortical_fwd=True, calc_for_sub_cortical_fwd=False) # stcs = meg_preproc.calc_stc_per_condition(events_id, inverse_method) stcs = None for hemi in utils.HEMIS: meg.calc_labels_avg_per_condition( atlas, hemi, 'pial', events_id, labels_from_annot=False, labels_fol='', stcs=stcs, positive=positive, moving_average_win_size=moving_average_win_size, inverse_method=inverse_method, do_plot=True)
def create_annot_from_mad(args): remote_subject_dir_template = '/mnt/cashlab/Original Data/MG/{subject}/{subject}_Notes_and_Images/{subject}_SurferOutput' for subject in args.subject: remote_subject_dir = remote_subject_dir_template.format(subject=subject) if utils.both_hemi_files_exist(op.join(remote_subject_dir, 'label', '{hemi}.aparc.DKTatlas.annot')): print('{} has already both annot files!'.format(subject)) continue args = anat.read_cmd_args(dict( subject=subject.lower(), atlas=args.atlas, remote_subject_dir=remote_subject_dir_template, function='create_annotation', ignore_missing=True, )) pu.run_on_subjects(args, anat.main) if not utils.both_hemi_files_exist(op.join(SUBJECTS_DIR, subject.lower(), 'label', '{hemi}.aparc.DKTatlas.annot')): print('Couldn\'t create annot files for {}!'.format(subject)) continue local_annot_fol = utils.make_dir(op.join(SUBJECTS_DIR, 'annot_files', subject.lower())) for hemi in utils.HEMIS: local_annot_fname = op.join(SUBJECTS_DIR, subject.lower(), 'label', '{}.aparc.DKTatlas.annot'.format(hemi)) remote_annot_fname = op.join(remote_subject_dir, 'label', '{}.aparc.DKTatlas.annot'.format(hemi)) local_temp_annot_fname = op.join(local_annot_fol, '{}.aparc.DKTatlas.annot'.format(hemi)) if not op.isfile(remote_annot_fname): if op.isfile(local_annot_fname): utils.copy_file(local_annot_fname, local_temp_annot_fname) else: print('Can\'t copy {} for {}, it doesn\'t exist!'.format(local_annot_fname, subject))
def get_data_and_header(subject, modality): # print('Loading header and data for {}, {}'.format(subject, modality)) if modality == 'mri': fname = op.join(MMVT_DIR, subject, 'freeview', 'T1.mgz') if not op.isfile(fname): subjects_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'T1.mgz') if op.isfile(subjects_fname): utils.copy_file(subjects_fname, fname) else: print("Can't find subject's T1.mgz!") return False elif modality == 'ct': fname = op.join(MMVT_DIR, subject, 'freeview', 'ct.mgz') if not op.isfile(fname): subjects_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'ct.mgz') if op.isfile(subjects_fname): utils.copy_file(subjects_fname, fname) else: print("Can't find subject's CT! ({})".format(fname)) return False else: print('create_slices: The modality {} is not supported!') return False header = nib.load(fname) data = header.get_data() percentiles_fname = op.join(MMVT_DIR, subject, 'freeview', '{}_1_99_precentiles.npy'.format(modality)) if not op.isfile(percentiles_fname): precentiles = np.percentile(data, (1, 99)) np.save(percentiles_fname, precentiles) return header, data
def change_frames_names(fol, images_prefix, images_type, images_format_len, new_fol_name='new_images'): import shutil images = glob.glob( op.join(fol, '{}*.{}'.format(images_prefix, images_type))) images.sort(key=lambda x: int(utils.namebase(x)[len(images_prefix):])) images_formats = { 1: '{0:0>1}', 2: '{0:0>2}', 3: '{0:0>3}', 4: '{0:0>4}', 5: '{0:0>5}' } root = op.join(op.sep.join(images[0].split(op.sep)[:-1])) new_fol = op.join(root, new_fol_name) utils.delete_folder_files(new_fol) utils.make_dir(new_fol) for num, image_fname in enumerate(images): num_str = images_formats[images_format_len].format(num + 1) new_image_fname = op.join( new_fol, '{}{}.{}'.format(images_prefix, num_str, images_type)) print('{} -> {}'.format(image_fname, new_image_fname)) utils.copy_file(image_fname, new_image_fname) return new_fol
def copy_T1(subject): for brain_file in ['T1.mgz', 'orig.mgz']: blender_brain_file = op.join(BLENDER_ROOT_DIR, subject, 'freeview', brain_file) subject_brain_file = op.join(SUBJECTS_DIR, subject, 'mri', brain_file) if not op.isfile(blender_brain_file): utils.copy_file(subject_brain_file, blender_brain_file)
def copy_files(fol, raw_file, eve_fname): if not op.isfile(op.join(fol, utils.namebase_with_ext(raw_file))): utils.copy_file(raw_file, fol) if not op.isfile(op.join(fol, utils.namebase_with_ext(eve_fname))): utils.copy_file(eve_fname, fol) raw_file = op.join(fol, utils.namebase_with_ext(raw_file)) eve_fname = op.join(fol, utils.namebase_with_ext(eve_fname)) return raw_file, eve_fname
def copy_T1(subject): files_exist = True for brain_file in ['T1.mgz', 'orig.mgz']: blender_brain_file = op.join(MMVT_DIR, subject, 'freeview', brain_file) subject_brain_file = op.join(SUBJECTS_DIR, subject, 'mri', brain_file) if not op.isfile(blender_brain_file): utils.copy_file(subject_brain_file, blender_brain_file) files_exist = files_exist and op.isfile(blender_brain_file) return files_exist
def copy_evokes(task, root_fol, target_subject, raw_cleaning_method): hc_subjects_epo_filess = glob.glob(op.join(root_fol, 'hc*arc*epo.fif')) for subject_epo_fname in hc_subjects_epo_filess: subject = utils.namebase(subject_epo_fname).split('_')[0] events_fname = '{}_arc_rer_{}-epo.csv'.format(subject, raw_cleaning_method) indices = find_events_indices(op.join(root_fol, events_fname)) if not indices is None: for hemi in utils.HEMIS: utils.copy_file(op.join(SUBJECTS_MEG_DIR, task, subject, 'labels_data_{}.npz'.format(hemi)), op.join(BLENDER_ROOT_DIR, target_subject, 'meg_evoked_files', '{}_labels_data_{}.npz'.format(subject, hemi)))
def main(region, atlas_fol, colin_T1_fname, overwrite=False): for hemi in ['lh', 'rh']: region_fname = op.join(atlas_fol, hemi, '{}.nii.gz'.format(region)) prepare_mask_file(region_fname, overwrite=overwrite) mask_to_srf(atlas_fol, region, hemi, op.join(SUBJECTS_DIR, 'colin27', 'mri', 'norm.mgz')) region_vox2ras_tkr = tu.get_vox2ras_tkr(region_fname) shifted_vox2tk_ras = calc_shifted_vox2tk_ras(region_fname, colin_T1_fname) convert_to_ply(op.join(atlas_fol, 'tmp', '{}_{}.srf'.format(region, hemi)), op.join(atlas_fol, 'tmp', '{}_{}.ply'.format(region, hemi)), region_vox2ras_tkr, shifted_vox2tk_ras) utils.copy_file(op.join(atlas_fol, 'tmp', '{}_{}.ply'.format(region, hemi)), op.join(MMVT_DIR, 'colin27', 'subcortical', '{}_{}.ply'.format(region, hemi)))
def duplicate_frames(fol, multiplier=50, pics_type='png'): import shutil pics = get_pics(fol, pics_type) new_fol = '{}_dup'.format(fol) utils.delete_folder_files(new_fol) pic_ind = 0 utils.copy_file(op.join(fol, 'data.pkl'), op.join(new_fol, 'data.pkl')) for t, pic in enumerate(pics): for _ in range(multiplier): new_pic_name = op.join(new_fol, '{}_t{}.{}'.format(pic_ind, t, pics_type)) utils.copy_file(pic, new_pic_name) pic_ind += 1
def get_data_and_header(subject, mmvt_dir, subjects_dir, ct_name='ct_reg_to_mr.mgz'): fname = op.join(mmvt_dir, subject, 'ct', ct_name) if not op.isfile(fname): subjects_fname = op.join(subjects_dir, subject, 'mri', ct_name) if op.isfile(subjects_fname): utils.copy_file(subjects_fname, fname) else: print("Can't find subject's CT! ({})".format(fname)) return None, None print('get_data_and_header: loading {}'.format(fname)) header = nib.load(fname) data = header.get_data() return data, header
def convert_darpa_ct(args): bads, goods = [], [] if args.print_only: args.ignore_missing = True args.subject = pu.decode_subjects(args.subject) for subject in args.subject: local_ct_fol = utils.make_dir(op.join(pu.SUBJECTS_DIR, subject, 'ct')) ct_fname = op.join(local_ct_fol, 'ct', 'ct_org.mgz') if op.isfile(ct_fname) and not args.overwrite: goods.append(subject) continue darpa_subject = subject[:2].upper() + subject[2:] files = glob.glob(op.join( f'/homes/5/npeled/space1/Angelique/recon-alls/{darpa_subject}/', '**', 'ct.*'), recursive=True) if len(files) > 0: for fname in files: output_fname = op.join(local_ct_fol, utils.namebase_with_ext(fname)) print('Coping {} to {}'.format(fname, output_fname)) utils.copy_file(fname, output_fname) goods.append(subject) continue fols = glob.glob( op.join('/space/huygens/1/users/kara', f'{darpa_subject}_CT*')) ct_raw_input_fol = fols[0] if len(fols) == 1 else '' if not op.isdir(ct_raw_input_fol): fols = glob.glob(op.join( f'/homes/5/npeled/space1/Angelique/recon-alls/{darpa_subject}/', '**', f'{darpa_subject}_CT*'), recursive=True) ct_raw_input_fol = fols[0] if len(fols) == 1 else '' if not op.isdir(ct_raw_input_fol): bads.append(subject) continue args = ct.read_cmd_args( utils.Bag(subject=subject, function='convert_ct_to_mgz', ct_raw_input_fol=ct_raw_input_fol, print_only=args.print_only, ignore_missing=args.ignore_missing, overwrite=args.overwrite, ask_before=args.ask_before)) ret = pu.run_on_subjects(args, ct.main) if ret: goods.append(subject) else: bads.append(subject) print('Good subjects:\n {}'.format(goods)) print('Bad subjects:\n {}'.format(bads))
def average_all_evoked_responses(root_fol, moving_average_win_size=100, do_plot=False): import matplotlib.pyplot as plt for hemi in utils.HEMIS: print(hemi) if do_plot: plt.figure() evoked_files = glob.glob(op.join(root_fol, 'hc*labels_data_{}.npz'.format(hemi))) all_data = None all_data_win = None for evoked_ind, evoked_fname in enumerate(evoked_files): print(evoked_fname) f = np.load(evoked_fname) data = f['data'] # labels x time x conditions print(data.shape) if all_data is None: all_data = np.zeros((*data.shape, len(evoked_files))) for cond_ind in range(data.shape[2]): print(cond_ind) for label_ind in range(data.shape[0]): x = data[label_ind, :, cond_ind] x *= np.sign(x[np.argmax(np.abs(x))]) all_data[label_ind, :, cond_ind, evoked_ind] = x win_avg = utils.moving_avg(all_data[:, :, cond_ind, evoked_ind], moving_average_win_size) win_avg = win_avg[:, :-moving_average_win_size] if do_plot: for label_data in win_avg: plt.plot(label_data) if all_data_win is None: all_data_win = np.zeros((*win_avg.shape, data.shape[2], len(evoked_files))) all_data_win[:, :, cond_ind, evoked_ind] = win_avg if do_plot: plt.savefig(op.join(root_fol, 'evoked_win_{}_{}.jpg'.format(hemi, moving_average_win_size, hemi))) plt.close() mean_evoked = np.mean(all_data, 3) mean_win_evoked = np.mean(all_data_win, 3) np.savez(op.join(root_fol, 'healthy_labels_data_{}.npz'.format(hemi)), data=mean_evoked, names=f['names'], conditions=f['conditions']) np.savez(op.join(root_fol, 'healthy_labels_data_win_{}_{}.npz'.format(moving_average_win_size, hemi)), data=mean_win_evoked, names=f['names'], conditions=f['conditions']) np.savez(op.join(root_fol, 'healthy_labels_all_data_win_{}_{}.npz'.format(moving_average_win_size, hemi)), data=all_data_win, names=f['names'], conditions=f['conditions']) utils.copy_file(op.join(root_fol, 'healthy_labels_data_win_{}_{}.npz'.format(moving_average_win_size, hemi)), op.join(root_fol, 'healthy_labels_data_{}.npz'.format(hemi))) if do_plot: plt.figure() for label_data in mean_win_evoked: plt.plot(label_data) plt.savefig(op.join(root_fol, 'avg_evoked_win_{}_{}.jpg'.format(hemi, moving_average_win_size, hemi))) plt.close()
def register_to_mr(subject, ct_fol='', ct_name='', nnv_ct_name='', register_ct_name='', threshold=-200, cost_function='nmi', overwrite=False, print_only=False): if ct_name == '': ct_name = 'ct_org.mgz' if nnv_ct_name == '': nnv_ct_name = 'ct_no_large_negative_values.mgz' if register_ct_name == '': register_ct_name = 'ct_reg_to_mr.mgz' ct_mmvt_fol = utils.make_dir(op.join(MMVT_DIR, subject, 'ct')) t1_fname = op.join(SUBJECTS_DIR, subject, 'mri', 'T1.mgz') if op.isfile(op.join(ct_mmvt_fol, register_ct_name)) and not overwrite: print('freeview -v "{}" "{}":colormap=Heat'.format( t1_fname, op.join(ct_mmvt_fol, register_ct_name))) return True if op.isfile(op.join(SUBJECTS_DIR, subject, 'ct', ct_name)): utils.copy_file(op.join(SUBJECTS_DIR, subject, 'ct', ct_name), op.join(MMVT_DIR, subject, 'ct', ct_name)) if not op.isdir(ct_fol): ct_fol = utils.make_dir(op.join(MMVT_DIR, subject, 'ct')) print('Removing large negative values: {} -> {}'.format( op.join(ct_fol, ct_name), op.join(ct_mmvt_fol, nnv_ct_name))) if not print_only: nnv_ct_fname = ctu.remove_large_negative_values_from_ct( op.join(ct_fol, ct_name), op.join(ct_mmvt_fol, nnv_ct_name), threshold, overwrite) ctu.register_ct_to_mr_using_mutual_information(subject, SUBJECTS_DIR, nnv_ct_fname, op.join( ct_mmvt_fol, register_ct_name), lta_name='', overwrite=overwrite, cost_function=cost_function, print_only=print_only) print('freeview -v {} {}'.format(t1_fname, op.join(ct_mmvt_fol, register_ct_name))) return True if print_only else op.isfile( op.join(ct_mmvt_fol, register_ct_name))
def create_lut_file_for_atlas(subject, atlas): if not utils.both_hemi_files_exist( op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format( '{hemi}', atlas))): print('No annot file was found for {}!'.format(atlas)) print( 'Run python -m src.preproc.anatomy -s {} -a {} -f create_surfaces,create_annotation' .format(subject, atlas)) return False # Read the subcortical segmentation from the freesurfer lut new_lut_fname = op.join(SUBJECTS_DIR, subject, 'label', '{}ColorLUT.txt'.format(atlas)) mmvt_lut_fname = op.join(MMVT_DIR, subject, 'freeview', '{}ColorLUT.txt'.format(atlas)) # if op.isfile(mmvt_lut_fname) and not args.overwrite_aseg_file: # return lut = utils.read_freesurfer_lookup_table(get_colors=True) lut_new = [[l[0], l[1].astype(str), l[2], l[3], l[4], l[5]] for l in lut if l[0] < 1000] for hemi, offset in zip(['lh', 'rh'], [1000, 2000]): if hemi == 'lh': lut_new.append([offset, 'ctx-lh-unknown', 25, 5, 25, 0]) else: lut_new.append([offset, 'ctx-rh-unknown', 25, 5, 25, 0]) _, ctab, names = _read_annot( op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format(hemi, atlas))) names = [name.astype(str) for name in names] for index, (label, cval) in enumerate(zip(names, ctab)): r, g, b, a, _ = cval lut_new.append([index + offset + 1, label, r, g, b, a]) lut_new.sort(key=lambda x: x[0]) # Add the values above 3000 for l in [l for l in lut if l[0] >= 3000]: lut_new.append([l[0], l[1].astype(str), l[2], l[3], l[4], l[5]]) with open(new_lut_fname, 'w') as fp: csv_writer = csv.writer(fp, delimiter='\t') csv_writer.writerows(lut_new) # np.savetxt(new_lut_fname, lut_new, delimiter='\t', fmt="%s") utils.make_dir(op.join(MMVT_DIR, subject, 'freeview')) utils.copy_file(new_lut_fname, mmvt_lut_fname) lut_npz_fname = utils.change_fname_extension(mmvt_lut_fname, 'npz') x = np.genfromtxt(mmvt_lut_fname, dtype=np.str) np.savez(lut_npz_fname, names=x[:, 1], ids=x[:, 0].astype(int)) return op.isfile(mmvt_lut_fname) and op.isfile(lut_npz_fname)
def main(html_template_fname, scan_fol, patient_name, task_name, mrn, scan_date, img_prefix=None, report_name_suffix='', output_fname=''): if utils.get_parent_fol(html_template_fname) != scan_fol: utils.copy_file(html_template_fname, scan_fol) if output_fname == '': output_fname = op.join(scan_fol, '{}{}.pdf'.format(mrn, '_{}'.format(report_name_suffix) \ if report_name_suffix != '' else '')) new_html_fname = utils.change_fname_extension(output_fname, 'html') if img_prefix == 'auto': img_prefix = utils.find_common_start([utils.namebase(f) for f in glob.glob(op.join(scan_fol, '*.png'))]) img_prefix = img_prefix[:-1] if img_prefix[-1] == '_' else img_prefix img_prefix = img_prefix[:-2] if img_prefix[-2:] == '_l' else img_prefix html = read_html(html_template_fname) html = replace_fields(html, patient_name, task_name, mrn, scan_date, img_prefix) create_new_html(html, new_html_fname) create_pdf(new_html_fname, output_fname) os.remove(op.join(scan_fol, utils.namebase_with_ext(html_template_fname)))
def copy_fmri_ts_files(subjects, delete_previous_files=True): FMRI_DIR = utils.get_link_dir(utils.get_links_dir(), 'fMRI') for sub in subjects: # ts_files = glob.glob(op.join(ts_root_fol, sub, 'rest', 'laus125_*.txt')) ts_files = glob.glob( op.join(ts_root_fol, '{}_laus125_*.txt'.format(sub))) if len(ts_files) == 0: print('No ts files for {}!'.format(sub)) for ts_file in ts_files: target_fname = op.join(FMRI_DIR, sub, utils.namebase_with_ext(ts_file)) if delete_previous_files: for old_fname in glob.glob( op.join(FMRI_DIR, sub, '*laus125_*.txt')): os.remove(old_fname) print('Copy {} to {}'.format(ts_file, target_fname)) utils.copy_file(ts_file, target_fname)
def read_meg_layouts(_args, remote_raw_fname=''): args = copy.copy(_args) bad_subjects = [] output_fol = utils.make_dir(op.join(MMVT_DIR, 'sensors')) subjects = args.subject for subject in subjects: args.subject = [subject] _, _, trans_fname = get_meg_empty_fnames(subject, args.remote_meg_dir, args) if remote_raw_fname == '': remote_raw_fname = op.join( args.raw_rest_remote_fol, subject, '{}_Resting_meg_ica-raw.fif'.format(subject)) if not op.isfile(remote_raw_fname): print('No Cor fname: {}!!!'.format(remote_raw_fname)) continue meg_args = meg.read_cmd_args( utils.Bag(subject=subject, data_per_task=False, remote_subject_dir=args.remote_subject_dir, raw_fname=remote_raw_fname, function='read_sensors_layout', trans_fname=trans_fname, overwrite_sensors=True, read_info_file=False, n_jobs=args.n_jobs)) meg.call_main(meg_args) for sensor_type in ['mag', 'planar1', 'planar2']: sensors_fname = op.join( MMVT_DIR, subject, 'meg', 'meg_{}_sensors_positions.npz'.format(sensor_type)) if not op.isfile(sensors_fname): bad_subjects.append(subject) break utils.make_dir(op.join(output_fol, subject)) output_fname = op.join(output_fol, subject, utils.namebase_with_ext(sensors_fname)) if not op.isfile(output_fname): utils.copy_file(sensors_fname, output_fname) print('{}/{} subjects with no sensors:'.format(len(bad_subjects), len(args.subject))) print(bad_subjects)
def calc_hesheng_surf(subject, atlas): subject_fol = op.join(fmri.MMVT_DIR, subject, 'fmri') if not (utils.both_hemi_files_exist(op.join(subject_fol, 'fmri_hesheng_{hemi}.npy')) and op.isfile(op.join(subject_fol, 'hesheng_minmax.pkl'))): # Copy and rename Hesheng's files hesheng_fnames = glob.glob(op.join( hesheng_surf_fol.format(subject=subject), hesheng_template.format(subject=subject))) for fname in hesheng_fnames: hemi = lu.get_label_hemi_invariant_name(utils.namebase(fname)) target_file = op.join(fmri.FMRI_DIR, subject, 'hesheng_{}.nii.gz'.format(hemi)) mgz_target_file = utils.change_fname_extension(target_file, 'mgz') if not op.isfile(mgz_target_file): utils.copy_file(fname, target_file) fu.nii_gz_to_mgz(target_file) os.remove(target_file) # Load Hesheng's files args = fmri.read_cmd_args(dict( subject=subject, atlas=atlas, function='load_surf_files', overwrite_surf_data=True, fmri_file_template='hesheng_{hemi}.mgz')) pu.run_on_subjects(args, fmri.main)
def get_subjects_files(args): ''' -f get_subjects_files -s "file:/homes/5/npeled/space1/Documents/memory_task/subjects.txt" ''' subjects = pu.decode_subjects(args.subject) for subject in subjects: subject_fol = op.join(fmri.FMRI_DIR, subject) # data_fol = '/cluster/neuromind/douw/scans/adults/{}/surf'.format(subject) data_fol = '/cluster/neuromind/douw/scans/adults/{}/bold'.format(subject) # template = '*.{}_bld*_rest_reorient_skip_faln_mc_g1000000000_bpss_resid_fsaverage6_sm6.nii.gz'.format(subject) template = '{}_*_rest.nii'.format(subject) files = glob.glob(op.join(data_fol, '**', template), recursive=True) # if len(files) % 2 == 0: if len(files) >= 1: utils.make_dir(subject_fol) for fname in files: # hemi = 'rh' if 'rh' in fname.split(op.sep)[-1] else 'lh' # output_fname = op.join(subject_fol, 'rest.sm6.fsaverage6.{}.mgz'.format(hemi)) output_fname = op.join(subject_fol, 'rest.nii') if not op.isfile(output_fname): utils.copy_file(fname, output_fname) else: print('{} already exist!'.format(output_fname)) else: print("Couldn't find the files for {}!".format(subject))
def create_aparc_aseg_file(subject, atlas, overwrite_aseg_file=False, print_only=False, args={}): if not utils.both_hemi_files_exist( op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format( '{hemi}', atlas))): print('No annot file was found for {}!'.format(atlas)) print( 'Run python -m src.preproc.anatomy -s {} -a {} -f create_surfaces,create_annotation' .format(subject, atlas)) return False # aparc_aseg_fname ret = fu.create_aparc_aseg_file(subject, atlas, SUBJECTS_DIR, overwrite_aseg_file, print_only, mmvt_args=args) if isinstance(ret, Iterable): ret, aparc_aseg_fname = ret if not ret: return False aparc_aseg_file = utils.namebase_with_ext(aparc_aseg_fname) utils.make_dir(op.join(MMVT_DIR, subject, 'freeview')) blender_file = op.join(MMVT_DIR, subject, 'freeview', aparc_aseg_file) utils.remove_file(blender_file) utils.copy_file(aparc_aseg_fname, blender_file) atlas_mat_fname = utils.change_fname_extension(blender_file, 'npy') if not op.isfile(atlas_mat_fname) or overwrite_aseg_file: d = nib.load(blender_file) x = d.get_data() np.save(atlas_mat_fname, x) return op.isfile(blender_file) and op.isfile(atlas_mat_fname)
def copy_T1(subject): for brain_file in ['T1.mgz', 'orig.mgz']: blender_brain_file = op.join(MMVT_DIR, subject, 'freeview', brain_file) subject_brain_file = op.join(SUBJECTS_DIR, subject, 'mri', brain_file) if not op.isfile(blender_brain_file): utils.copy_file(subject_brain_file, blender_brain_file)