Example #1
0
def project_on_surface(subject, volume_file, surf_output_fname, target_subject=None, overwrite_surf_data=False,
                       modality='fmri', subjects_dir='', mmvt_dir='', **kargs):
    if target_subject is None:
        target_subject = subject
    if subjects_dir == '':
        subjects_dir = utils.get_link_dir(utils.get_links_dir(), 'subjects', 'SUBJECTS_DIR')
    if mmvt_dir == '':
        mmvt_dir = utils.get_link_dir(utils.get_links_dir(), 'mmvt')
    utils.make_dir(op.join(mmvt_dir, subject, 'fmri'))
    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['SUBJECT'] = subject
    for hemi in utils.HEMIS:
        if not op.isfile(surf_output_fname.format(hemi=hemi)) or overwrite_surf_data:
            print('project {} to {}'.format(volume_file, hemi))
            if modality != 'pet':
                surf_data = project_volume_data(volume_file, hemi, subject_id=subject, surf="pial", smooth_fwhm=3,
                    target_subject=target_subject, output_fname=surf_output_fname.format(hemi=hemi))
            else:
                surf_data = project_pet_volume_data(subject, volume_file, hemi, surf_output_fname.format(hemi=hemi))
            nans = np.sum(np.isnan(surf_data))
            if nans > 0:
                print('there are {} nans in {} surf data!'.format(nans, hemi))
        surf_data = np.squeeze(nib.load(surf_output_fname.format(hemi=hemi)).get_data())
        output_fname = op.join(mmvt_dir, subject, modality, '{}_{}'.format(modality, op.basename(
            surf_output_fname.format(hemi=hemi))))
        npy_output_fname = op.splitext(output_fname)[0]
        if not op.isfile('{}.npy'.format(npy_output_fname)) or overwrite_surf_data:
            print('Saving surf data in {}.npy'.format(npy_output_fname))
            utils.make_dir(utils.get_parent_fol(npy_output_fname))
            np.save(npy_output_fname, surf_data)
Example #2
0
def main(args):
    # 1) Create links
    if utils.should_run(args, 'create_links'):
        links_created = create_links(args.links, args.gui)
        if not links_created:
            print('Not all the links were created! Make sure all the links are created before running MMVT.')

    # 2) Copy resources files
    if utils.should_run(args, 'copy_resources_files'):
        links_dir = utils.get_links_dir(args.links)
        mmvt_root_dir = utils.get_link_dir(links_dir, 'mmvt')
        resource_file_exist = copy_resources_files(mmvt_root_dir)
        if not resource_file_exist:
            print('Not all the resources files were copied to the MMVT folder.\n'.format(mmvt_root_dir) +
                  'Please copy them manually from the mmvt_code/resources folder')

    # 3) Install the addon in Blender (depends on resources and links)
    if utils.should_run(args, 'install_addon'):
        from src.mmvt_addon.scripts import install_addon
        install_addon.wrap_blender_call()

    # 4) Install dependencies from requirements.txt (created using pipreqs)
    if utils.should_run(args, 'install_reqs'):
        install_reqs()
        print('Finish!')
Example #3
0
def create_seghead(subject, subjects_dir=None, print_only=False, **kargs):
    if subjects_dir is None:
        subjects_dir = utils.get_link_dir(utils.get_links_dir(), 'subjects',
                                          'SUBJECTS_DIR')
    os.environ['SUBJECTS_DIR'] = subjects_dir
    rs = utils.partial_run_script(locals(), print_only=print_only)
    rs(mkheadsurf)
Example #4
0
def get_links():
    links_dir = utils.get_links_dir()
    subjects_dir = utils.get_link_dir(links_dir, 'subjects', 'SUBJECTS_DIR')
    freesurfer_home = utils.get_link_dir(links_dir, 'freesurfer',
                                         'FREESURFER_HOME')
    mmvt_dir = utils.get_link_dir(links_dir, 'mmvt')
    return subjects_dir, mmvt_dir, freesurfer_home
Example #5
0
def pre_blender_call(args):
    from src.mmvt_addon import load_results_panel
    from src.preproc import fMRI as fmri
    from src.utils import preproc_utils as pu
    from src.utils import utils

    user_fol = op.join(pu.MMVT_DIR, args.subject)
    nii_fname = args.nii
    if not op.isfile(args.nii):
        args.nii = op.join(user_fol, 'fmri', nii_fname)
    if not op.isfile(args.nii):
        fmri_fol = op.join(utils.get_link_dir(utils.get_links_dir(), 'fMRI'),
                           args.subject)
        args.nii = op.join(fmri_fol, nii_fname)
    if not op.isfile(args.nii):
        raise Exception("Can't find the nii file!")
    fmri_file_template, _, _ = load_results_panel.load_surf_files(
        args.nii, run_fmri_preproc=False, user_fol=user_fol)
    preproc_args = fmri.read_cmd_args(
        dict(subject=args.subject,
             atlas=args.atlas,
             function='load_surf_files',
             fmri_file_template=fmri_file_template,
             ignore_missing=True))
    ret = pu.run_on_subjects(preproc_args, fmri.main)
    if ret:
        load_results_panel.clean_nii_temp_files(fmri_file_template, user_fol)
        args.fmri_file_template = fmri_file_template
    else:
        raise Exception("Couldn't load the surface files!")
    return args
Example #6
0
def calc_dipoles_rois(subject, atlas='laus125', overwrite=False, n_jobs=4):
    links_dir = utils.get_links_dir()
    subjects_dir = utils.get_link_dir(links_dir, 'subjects')
    mmvt_dir = utils.get_link_dir(links_dir, 'mmvt')
    diploes_rois_output_fname = op.join(mmvt_dir, subject, 'meg', 'dipoles_rois.pkl')
    if op.isfile(diploes_rois_output_fname) and not overwrite:
        diploes_rois = utils.load(diploes_rois_output_fname)
        for dip in diploes_rois.keys():
            diploes_rois[dip]['cortical_probs'] *= 1/sum(diploes_rois[dip]['cortical_probs'])
            diploes_rois[dip]['subcortical_probs'] = []
            diploes_rois[dip]['subcortical_rois'] = []
        # coritcal_labels = set(utils.flat_list_of_lists([diploes_rois[k]['cortical_rois'] for k in diploes_rois.keys()]))
        utils.save(diploes_rois, diploes_rois_output_fname)
        return True

    diploes_input_fname = op.join(mmvt_dir, subject, 'meg', 'dipoles.pkl')
    if not op.isfile(diploes_input_fname):
        print('No dipoles file!')
        return False

    labels = lu.read_labels(subject, subjects_dir, atlas, n_jobs=n_jobs)
    labels = list([{'name': label.name, 'hemi': label.hemi, 'vertices': label.vertices}
                   for label in labels])
    if len(labels) == 0:
        print('Can\'t find the labels for atlas {}!'.format(atlas))
        return False

    # find the find_rois package
    mmvt_code_fol = utils.get_mmvt_code_root()
    ela_code_fol = op.join(utils.get_parent_fol(mmvt_code_fol), 'electrodes_rois')
    if not op.isdir(ela_code_fol) or not op.isfile(op.join(ela_code_fol, 'find_rois', 'main.py')):
        print("Can't find ELA folder!")
        print('git pull https://github.com/pelednoam/electrodes_rois.git')
        return False

    # load the find_rois package
    try:
        import sys
        if ela_code_fol not in sys.path:
            sys.path.append(ela_code_fol)
        from find_rois import main as ela
    except:
        print('Can\'t load find_rois package!')
        utils.print_last_error_line()
        return False

    dipoles_dict = utils.load(diploes_input_fname)
    diploles_names, dipoles_pos = [], []
    for cluster_name, dipoles in dipoles_dict.items():
        for begin_t, _, x, y, z, _, _, _, _, _ in dipoles:
            dipole_name = '{}_{}'.format(cluster_name, begin_t) if len(dipoles) > 1 else cluster_name
            diploles_names.append(dipole_name.replace(' ', ''))
            dipoles_pos.append([k * 1e3 for k in [x, y, z]])
    dipoles_rois = ela.identify_roi_from_atlas(
        atlas, labels, diploles_names, dipoles_pos, approx=3, elc_length=0, hit_only_cortex=True,
        subjects_dir=subjects_dir, subject=subject, n_jobs=n_jobs)
    # Convert the list to a dict
    dipoles_rois_dict = {dipoles_rois['name']: dipoles_rois for dipoles_rois in dipoles_rois}
    utils.save(dipoles_rois_dict, diploes_rois_output_fname)
Example #7
0
def combine_images(fol,
                   movie_name,
                   frame_rate=10,
                   start_number=-1,
                   images_prefix='',
                   images_format='',
                   images_type='',
                   ffmpeg_cmd='',
                   movie_name_full_path=False,
                   debug=False,
                   copy_files=False,
                   add_reverse_frames=False,
                   **kwargs):
    if ffmpeg_cmd == '':
        ffmpeg_dir = utils.get_link_dir(utils.get_links_dir(), 'ffmpeg')
        ffmpeg_dir = op.join(ffmpeg_dir,
                             'bin') if utils.is_windows() else ffmpeg_dir
        ffmpeg_cmd = op.join(ffmpeg_dir,
                             'ffmpeg') if op.isdir(ffmpeg_dir) else 'ffmpeg'
    print('ffmpeg_cmd: {}'.format(ffmpeg_cmd))
    images_type, images_prefix, images_format, images_format_len, start_number = find_images_props(
        fol, start_number, images_prefix, images_format, images_type)
    if movie_name == '' and images_prefix != '':
        movie_name = images_prefix
    elif movie_name == '':
        movie_name = 'output_video'
    org_fol = fol
    if utils.is_windows() or copy_files:
        fol = change_frames_names(fol, images_prefix, images_type,
                                  images_format_len)
    if add_reverse_frames:
        add_reverse_frames_fol(fol, images_prefix, images_type)
    images_prefix = op.join(fol, images_prefix)
    if not movie_name_full_path:
        movie_name = op.join(fol, movie_name)
    combine_images_cmd = '{ffmpeg_cmd} -framerate {frame_rate} '
    if start_number != 1:
        # You might want to use a static ffmpeg if your ffmepg version doesn't support the start_number flag, like:
        # ffmpeg_cmd = '~/space1/Downloads/ffmpeg-git-static/ffmpeg'
        combine_images_cmd += '-start_number {start_number} '
    # Not working in windows:
    # combine_images_cmd += '-pattern_type glob -i "*.{images_type}" '
    combine_images_cmd += '-i {images_prefix}{images_format}.{images_type} '
    # http://stackoverflow.com/questions/20847674/ffmpeg-libx264-height-not-divisible-by-2
    combine_images_cmd += '-vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" '
    combine_images_cmd += '-c:v libx264 -r 30 -pix_fmt yuv420p {movie_name}.mp4'
    if debug:
        combine_images_cmd += ' -loglevel debug'
    rs = utils.partial_run_script(locals())
    rs(combine_images_cmd)
    with open(op.join(org_fol, 'combine_images_cmd.txt'), 'w') as f:
        f.write(combine_images_cmd.format(**locals()))
    return '{}.mp4'.format(movie_name)
Example #8
0
def create_links(links_fol_name='links', gui=True):
    #todo: Work only on linux (maybe mac also)
    if gui:
        from tkinter.filedialog import askdirectory
    links_fol = utils.get_links_dir(links_fol_name)
    utils.make_dir(links_fol)
    links_names = ['mmvt', 'subjects', 'blender', 'meg', 'fMRI', 'electrodes', 'freesurfer']
    all_links_exist = np.all([op.islink(op.join(links_fol, link_name)) for link_name in links_names])
    if all_links_exist:
        return True
    if os.environ.get('FREESURFER_HOME', '') == '':
        print('Please source FreeSurfer and rerun')
        return
    print('Where do you want to put the blend files? ')
    mmvt_fol = askdirectory() if gui else input()
    create_real_folder(mmvt_fol)
    print('Where do you want to store the FreeSurfer recon-all files neccessary for MMVT?\n' +
          'It prefered to create a local folder, because MMVT is going to save files to this directory: ')
    subjects_fol = askdirectory() if gui else input()
    create_real_folder(subjects_fol)
    freesurfer_fol = os.environ['FREESURFER_HOME']
    create_real_folder(freesurfer_fol)
    print('Where did you install Blender? ')
    blender_fol = askdirectory() if gui else input()
    create_real_folder(blender_fol)
    print('Where do you want to put the MEG files (Enter/Cancel if you are not going to use MEG data): ')
    meg_fol = askdirectory() if gui else input()
    create_real_folder(meg_fol)
    print('Where do you want to put the fMRI files (Enter/Cancel if you are not going to use fMRI data): ')
    fmri_fol = askdirectory() if gui else input()
    create_real_folder(fmri_fol)
    print('Where do you want to put the electrodes files (Enter/Cancel if you are not going to use electrodes data): ')
    electrodes_fol = askdirectory() if gui else input()
    create_real_folder(electrodes_fol)

    for real_fol, link_name in zip([mmvt_fol, subjects_fol, blender_fol, meg_fol, fmri_fol, electrodes_fol, freesurfer_fol],
            links_names):
        try:
            if not op.islink(op.join(links_fol, link_name)):
                os.symlink(real_fol, op.join(links_fol, link_name))
            # Add the default task in meg folder
            if link_name == 'meg' and real_fol != utils.get_resources_fol():
                utils.make_dir(op.join(real_fol, 'default'))
        except:
            print('Error with folder {} and link {}'.format(real_fol, link_name))
            print(traceback.format_exc())
    return np.all([op.islink(op.join(links_fol, link_name)) for link_name in links_names])
Example #9
0
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)
Example #10
0
def main():
    import argparse
    from src.utils import args_utils as au
    parser = argparse.ArgumentParser(description='MMVT Setup')
    parser.add_argument('-l', '--links', help='links folder name', required=False, default='links')
    parser.add_argument('-g', '--gui', help='choose folders using gui', required=False, default='1', type=au.is_true)
    args = utils.Bag(au.parse_parser(parser))

    links_created = create_links(args.links, args.gui)
    if not links_created:
        print('Not all the links were created! Make sure all the links are created before running MMVT.')
    else:
        links_dir = utils.get_links_dir()
        mmvt_root_dir = op.join(links_dir, 'mmvt')
        resource_file_exist = copy_resources_files(mmvt_root_dir)
        if not resource_file_exist:
            print('Not all the resources files were copied to the MMVT () folder.\n'.format(mmvt_root_dir) +
                  'Please copy them manually from the mmvt_code/resources folder')
        else:
            print('Finish!')
Example #11
0
def get_links():
    links_dir = utils.get_links_dir()
    subjects_dir = utils.get_link_dir(links_dir, 'subjects', 'SUBJECTS_DIR')
    freesurfer_home = utils.get_link_dir(links_dir, 'freesurfer', 'FREESURFER_HOME')
    mmvt_dir = utils.get_link_dir(links_dir, 'mmvt')
    return subjects_dir, mmvt_dir, freesurfer_home
Example #12
0
import os
import os.path as op
from collections import defaultdict
import glob
import traceback

from src.utils import utils
from src.utils import args_utils as au

LINKS_DIR = utils.get_links_dir()
SUBJECTS_DIR = utils.get_link_dir(LINKS_DIR, 'subjects', 'SUBJECTS_DIR')
MMVT_DIR = op.join(LINKS_DIR, 'mmvt')


def run_on_subjects(args, main_func, subjects_itr=None, subject_func=None):
    if subjects_itr is None:
        subjects_itr = args.subject
    subjects_flags, subjects_errors = {}, {}
    args.n_jobs = utils.get_n_jobs(args.n_jobs)
    args.sftp_password = utils.get_sftp_password(
        args.subject, SUBJECTS_DIR, args.necessary_files, args.sftp_username, args.overwrite_fs_files) \
        if args.sftp else ''
    if '*' in args.subject:
        args.subject = [utils.namebase(fol) for fol in glob.glob(op.join(SUBJECTS_DIR, args.subject))]
    os.environ['SUBJECTS_DIR'] = SUBJECTS_DIR
    for tup in subjects_itr:
        subject = get_subject(tup, subject_func)
        utils.make_dir(op.join(MMVT_DIR, subject, 'mmvt'))
        remote_subject_dir = utils.build_remote_subject_dir(args.remote_subject_dir, subject)
        print('****************************************************************')
        print('subject: {}, atlas: {}'.format(subject, args.atlas))
Example #13
0
import os.path as op
import os
import sys
import mne
from mne.datasets import sample

from src.utils import utils

MMVT_DIR = op.join(utils.get_links_dir(), 'mmvt')

code_root_fol = os.environ['MMVT_CODE']
if code_root_fol not in sys.path:
    sys.path.append(code_root_fol)

from src.mmvt_addon.scripts import run_mmvt
mmvt = run_mmvt.run('sample', run_in_background=False, debug=True)

data_path = sample.data_path()

raw_fname_sample = data_path + '/MEG/sample/sample_audvis_raw.fif'
fwd_fname_sample = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'

subjects_dir_sample = data_path + '/subjects'

# Read the forward solutions with surface orientation
fwd_sample = mne.read_forward_solution(fwd_fname_sample)
mne.convert_forward_solution(fwd_sample, surf_ori=True, copy=False)
eeg_map = mne.sensitivity_map(fwd_sample, ch_type='eeg', mode='fixed')
mmvt.coloring.plot_stc(eeg_map, threshold=0)
# eeg_map.save(op.join(MMVT_DIR, 'sample', 'meg', 'eeg_sensitivity_map'))
# eeg_map.plot(time_label='Gradiometer sensitivity', subjects_dir=subjects_dir_sample)
Example #14
0
def create_links(links_fol_name='links', gui=True):
    links_fol = utils.get_links_dir(links_fol_name)
    utils.make_dir(links_fol)
    links_names = ['mmvt', 'subjects', 'blender', 'meg', 'fMRI', 'electrodes', 'freesurfer']
    all_links_exist = np.all([op.islink(op.join(links_fol, link_name)) for link_name in links_names])
    if all_links_exist:
        return True
    if not utils.is_link(op.join(links_fol, 'freesurfer')):
        if not utils.is_windows():
            if os.environ.get('FREESURFER_HOME', '') == '':
                print('If you have FreeSurfer installed, please source it and rerun')
                cont = input("Do you want to continue (y/n)?") # If you choose to continue, you'll need to create a link to FreeSurfer manually")
                if cont.lower() != 'y':
                    return
            else:
                freesurfer_fol = os.environ['FREESURFER_HOME']
                create_real_folder(freesurfer_fol)
    if not utils.is_link(op.join(links_fol, 'mmvt')):
        ret = utils.message_box('Please select where do you want to put the blend files? ', TITLE)
        if ret == 1:
            mmvt_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(mmvt_fol)
            utils.create_folder_link(mmvt_fol, op.join(links_fol, 'mmvt'))
    if not utils.is_link(op.join(links_fol, 'subjects')):
        ret = utils.message_box('Please select where do you want to store the FreeSurfer recon-all files neccessary for MMVT?\n' +
              'It prefered to create a local folder, because MMVT is going to save files to this directory: ', TITLE)
        if ret == 1:
            subjects_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(subjects_fol)
            utils.create_folder_link(subjects_fol, op.join(links_fol, 'subjects'))
    if not utils.is_link(op.join(links_fol, 'blender')):
        ret = utils.message_box('Please select where did you install Blender? ')
        if ret == 1:
            blender_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(blender_fol)
            utils.create_folder_link(blender_fol, op.join(links_fol, 'blender'))
    if not utils.is_link(op.join(links_fol, 'meg')):
        ret = utils.message_box('Please select where do you want to put the MEG files (Enter/Cancel if you are not going to use MEG data): ', TITLE)
        if ret == 1:
            meg_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(meg_fol)
            utils.create_folder_link(meg_fol, op.join(links_fol, 'meg'))
            if meg_fol != utils.get_resources_fol():
                utils.make_dir(op.join(meg_fol, 'default'))
    if not utils.is_link(op.join(links_fol, 'fMRI')):
        ret = utils.message_box('Please select where do you want to put the fMRI files (Enter/Cancel if you are not going to use fMRI data): ', TITLE)
        if ret == 1:
            fmri_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(fmri_fol)
            utils.create_folder_link(fmri_fol, op.join(links_fol, 'fMRI'))
    if not utils.is_link(op.join(links_fol, 'electrodes')):
        ret = utils.message_box('Please select where do you want to put the electrodes files (Enter/Cancel if you are not going to use electrodes data): ', TITLE)
        if ret == 1:
            electrodes_fol = utils.choose_folder_gui() if gui else input()
            create_real_folder(electrodes_fol)
            utils.create_folder_link(electrodes_fol, op.join(links_fol, 'electrodes'))

    # for real_fol, link_name in zip([mmvt_fol, subjects_fol, blender_fol, meg_fol, fmri_fol, electrodes_fol, freesurfer_fol],
    #         links_names):
    #     try:
    #         # utils.create_folder_link(real_fol, op.join(links_fol, link_name))
    #         # if not op.islink(op.join(links_fol, link_name)):
    #         #     os.symlink(real_fol, op.join(links_fol, link_name))
    #         # Add the default task in meg folder
    #         if link_name == 'meg' and real_fol != utils.get_resources_fol():
    #             utils.make_dir(op.join(real_fol, 'default'))
    #     except:
    #         print('Error with folder {} and link {}'.format(real_fol, link_name))
    #         print(traceback.format_exc())
    return np.all([utils.is_link(op.join(links_fol, link_name)) for link_name in links_names])
Example #15
0
import os.path as op
import numpy as np
from src.utils import utils
from src.utils import freesurfer_utils as fu
from src.preproc import meg

LINKS_DIR = utils.get_links_dir()
FMRI_DIR = utils.get_link_dir(utils.get_links_dir(), 'fMRI')
MMVT_DIR = utils.get_link_dir(LINKS_DIR, 'mmvt')
SUBJECTS_DIR = utils.get_link_dir(LINKS_DIR, 'subjects', 'SUBJECTS_DIR')


def morph_fmri(morph_from, morph_to, nii_template):
    utils.make_dir(op.join(MMVT_DIR, morph_to, 'fmri'))
    for hemi in utils.HEMIS:
        fu.surf2surf(
            morph_from, morph_to, hemi,
            op.join(MMVT_DIR, morph_from, 'fmri',
                    nii_template.format(hemi=hemi)),
            op.join(MMVT_DIR, morph_to, 'fmri',
                    nii_template.format(hemi=hemi)))


def morph_stc(subject,
              events,
              morph_to_subject,
              inverse_method='dSPM',
              grade=5,
              smoothing_iterations=None,
              overwrite=False,
              n_jobs=6):
Example #16
0
import numpy as np
import os.path as op
import glob
import time
import traceback

from src.utils import utils
from src.utils import labels_utils as lu

links_dir = utils.get_links_dir()
SUBJECTS_DIR = utils.get_link_dir(links_dir, 'subjects', 'SUBJECTS_DIR')
MMVT_DIR = utils.get_link_dir(
    links_dir,
    'mmvt',
)


def mode(arr):
    return np.bincount(arr).argmax()
    #from collections import Counter
    #return Counter(arr).most_common(1)


# @utils.profileit(root_folder=op.join(MMVT_DIR, 'profileit'))
def parcelate(subject,
              atlas,
              hemi,
              surface_type,
              vertices_labels_ids_lookup=None,
              overwrite_vertices_labels_lookup=False):
    output_fol = op.join(MMVT_DIR, subject, 'labels',
Example #17
0
from functools import partial
import os.path as op
import shutil
import mne
import scipy.io as sio
import scipy
from collections import defaultdict, OrderedDict, Iterable
import matplotlib.pyplot as plt

from src.utils import utils
from src.mmvt_addon import colors_utils as cu
from src.utils import matlab_utils as mu
from src.utils import preproc_utils as pu

SUBJECTS_DIR, MMVT_DIR, FREESURFER_HOME = pu.get_links()
ELECTRODES_DIR = utils.get_link_dir(utils.get_links_dir(), 'electrodes')
HEMIS = utils.HEMIS
STAT_AVG, STAT_DIFF = range(2)
STAT_NAME = {STAT_DIFF: 'diff', STAT_AVG: 'avg'}
DEPTH, GRID = range(2)


def montage_to_npy(montage_file, output_file):
    sfp = mne.channels.read_montage(montage_file)
    np.savez(output_file, pos=np.array(sfp.pos), names=sfp.ch_names)


def electrodes_csv_to_npy(ras_file, output_file, bipolar=False, delimiter=','):
    data = np.genfromtxt(ras_file, dtype=str, delimiter=delimiter)
    data = fix_str_items_in_csv(data)
    # Check if the electrodes coordinates has a header
Example #18
0
import os.path as op
import scipy.io as sio
import argparse
import numpy as np
from src.preproc import electrodes as elecs
from src.utils import utils
from src.utils import args_utils as au
from src.utils import preproc_utils as pu
from src.utils import matlab_utils as mu

ELECTRODES_DIR = utils.get_link_dir(utils.get_links_dir(), 'electrodes')


def read_electrodes_coordiantes_from_specific_xlsx_sheet(subject, bipolar):
    args = elecs.read_cmd_args(['-s', subject, '-b', str(bipolar)])
    args.ras_xls_sheet_name = 'RAS_Snapped'
    elecs.main(subject, args)


def save_msit_single_trials_data(subject, bipolar):
    args = elecs.read_cmd_args(['-s', subject, '-b', str(bipolar)])
    args.task = 'MSIT'
    args.function = 'create_electrode_data_file'
    args.input_matlab_fname = 'electrodes_data_trials.mat'
    args.electrodes_names_field = 'electrodes'
    args.field_cond_template = '{}'
    elecs.main(subject, args)


def load_edf_data_seizure(args):
    args = elecs.read_cmd_args(
Example #19
0
import os
import os.path as op
from pizco import Proxy

os.chdir(os.environ['MMVT_CODE'])
from src.mmvt_addon.scripts import run_mmvt
from src.utils import utils

subject, atlas = 'DC', 'laus250'
run_mmvt.run(subject, atlas, run_in_background=False, debug=False)
mmvt = Proxy('tcp://127.0.0.1:8001')
meg_dir = utils.get_link_dir(utils.get_links_dir(), 'meg')
stc_fname = op.join(meg_dir, subject, 'left-MNE-1-15-lh.stc')
mmvt.plot_stc(stc_fname, 1270, threshold=0.1)
Example #20
0
import os.path as op
import glob
from src.utils import utils

FFMPEG_DIR = utils.get_link_dir(utils.get_links_dir(), 'ffmpeg')
FFMPEG_DIR = op.join(FFMPEG_DIR, 'bin') if utils.is_windows() else FFMPEG_DIR
FFMPEG_CMD = op.join(FFMPEG_DIR,
                     'ffmpeg') if op.isdir(FFMPEG_DIR) else 'ffmpeg'

# from moviepy.config import change_settings
# change_settings({"IMAGEMAGICK_BINARY": r"/usr/bin/convert"})

# https://www.vultr.com/docs/install-imagemagick-on-centos-6
# https://github.com/BVLC/caffe/issues/3884


def check_movipy():
    try:
        import moviepy.config as conf
        if conf.try_cmd([conf.FFMPEG_BINARY])[0]:
            print("MoviePy : ffmpeg successfully found.")
        else:
            print("MoviePy : can't find or access ffmpeg.")

        if conf.try_cmd([conf.IMAGEMAGICK_BINARY])[0]:
            print("MoviePy : ImageMagick successfully found.")
        else:
            print("MoviePy : can't find or access ImageMagick.")
    except:
        print("Can't import moviepy")
Example #21
0
import os.path as op
import glob
from src.utils import utils

FFMPEG_DIR = op.join(utils.get_links_dir(), 'ffmpeg')
FFMPEG_CMD = op.join(FFMPEG_DIR,
                     'ffmpeg') if op.isdir(FFMPEG_DIR) else 'ffmpeg'

# from moviepy.config import change_settings
# change_settings({"IMAGEMAGICK_BINARY": r"/usr/bin/convert"})

# https://www.vultr.com/docs/install-imagemagick-on-centos-6
# https://github.com/BVLC/caffe/issues/3884


def check_movipy():
    import moviepy.config as conf
    if conf.try_cmd([conf.FFMPEG_BINARY])[0]:
        print("MoviePy : ffmpeg successfully found.")
    else:
        print("MoviePy : can't find or access ffmpeg.")

    if conf.try_cmd([conf.IMAGEMAGICK_BINARY])[0]:
        print("MoviePy : ImageMagick successfully found.")
    else:
        print("MoviePy : can't find or access ImageMagick.")


def cut_movie(movie_fol, movie_name, out_movie_name, subclips_times):
    from moviepy import editor
    # subclips_times [(3, 4), (6, 17), (38, 42)]
Example #22
0
from pymesh import obj
import os.path as op
from src.utils import utils

MMVT_DIR = utils.get_link_dir(utils.get_links_dir(), 'mmvt')


def create_eeg_mesh_from_obj(subject, obj_fname):
    mesh_ply_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_helmet.ply')
    # mesh = obj.Obj(obj_fname)
    # verts, faces = mesh.vertices, mesh.faces
    verts, faces = utils.read_obj_file(obj_fname)
    utils.write_ply_file(verts, faces, mesh_ply_fname)
    faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_faces_verts.npy')
    utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname, True,
                               utils.namebase(faces_verts_out_fname))

def recreate_mesh_faces_verts(subject, ply_fname):
    verts, faces = utils.read_ply_file(ply_fname)
    faces_verts_out_fname = op.join(MMVT_DIR, subject, 'eeg', 'eeg_faces_verts.npy')
    utils.calc_ply_faces_verts(verts, faces, faces_verts_out_fname, True,
                               utils.namebase(faces_verts_out_fname))


if __name__ == '__main__':
    subject = 'ep001'
    # create_eeg_mesh_from_obj(subject, '/homes/5/npeled/space1/mmvt/ep001/eeg/eeg_helmet.obj')
    recreate_mesh_faces_verts(subject, '/homes/5/npeled/space1/mmvt/ep001/eeg/eeg_helmet.ply')
    print('Finish!')
Example #23
0
import os.path as op
import numpy as np
from itertools import product

try:
    import mplcursors
    MPLCURSORS_EXIST = True
except:
    MPLCURSORS_EXIST = False

from src.preproc import eeg
from src.preproc import meg
from src.utils import utils
from src.examples.epilepsy import utils as epi_utils

LINKS_DIR = utils.get_links_dir()
MMVT_DIR = utils.get_link_dir(LINKS_DIR, 'mmvt')
MEG_DIR = utils.get_link_dir(LINKS_DIR, 'meg')
EEG_DIR = utils.get_link_dir(LINKS_DIR, 'eeg')
SUBJECTS_DIR = utils.get_link_dir(LINKS_DIR, 'subjects')


def plot_topomaps(subject, modality, windows, bad_channels, parallel=True):
    figs_fol = utils.make_dir(
        op.join(MMVT_DIR, subject, 'epilepsy-figures', 'topomaps'))
    params = [(subject, modality, window_fname, bad_channels, figs_fol)
              for window_fname in windows]
    utils.run_parallel(_plot_topomaps_parallel, params,
                       len(windows) if parallel else 1)

Example #24
0
import os.path as op
import glob
from src.utils import utils

FFMPEG_DIR = op.join(utils.get_links_dir(), 'ffmpeg')
FFMPEG_CMD = op.join(FFMPEG_DIR, 'ffmpeg') if op.isdir(FFMPEG_DIR) else 'ffmpeg'

# from moviepy.config import change_settings
# change_settings({"IMAGEMAGICK_BINARY": r"/usr/bin/convert"})

# https://www.vultr.com/docs/install-imagemagick-on-centos-6
# https://github.com/BVLC/caffe/issues/3884


def check_movipy():
    import moviepy.config as conf
    if conf.try_cmd([conf.FFMPEG_BINARY])[0]:
        print("MoviePy : ffmpeg successfully found.")
    else:
        print("MoviePy : can't find or access ffmpeg.")

    if conf.try_cmd([conf.IMAGEMAGICK_BINARY])[0]:
        print("MoviePy : ImageMagick successfully found.")
    else:
        print("MoviePy : can't find or access ImageMagick.")


def cut_movie(movie_fol, movie_name, out_movie_name, subclips_times):
    from moviepy import editor
    # subclips_times [(3, 4), (6, 17), (38, 42)]
    video = editor.VideoFileClip(op.join(movie_fol, movie_name))