示例#1
0
    def _format_arg(self, name, spec, value):

        import os
        import shutil

        cur_dir = os.getcwd()

        new_value = []
        if name == 'in_file':
            if isinstance(value, list):

                print("A list for in_file")
                for in_file in value:
                    print(in_file)

                    # copy en local
                    shutil.copy(in_file, cur_dir)

                    new_value.append(os.path.join(cur_dir, in_file))

            else:
                print("Not a list for in_file {}".format(value))
                shutil.copy(value, cur_dir)

                path, fname, ext = split_f(value)
                new_value = os.path.join(cur_dir, fname + ext)
                print(new_value)

            value = new_value

        elif name == 'out_file':
            if isinstance(value, list):
                print("A list for out_file")
                print("out_file:", value)

                for out_file in value[:1]:
                    print(out_file)

                    path, fname, ext = split_f(out_file)
                    new_value.append(
                        os.path.join(cur_dir, fname + "_Nwarp" + ext))

                for i in range(1, 4):
                    new_value.append(
                        os.path.join(cur_dir, "tmp_%02d.nii.gz" % i))

                print("after out_file:", new_value)

            else:
                print("Not a list for out_file {}".format(value))

                path, fname, ext = split_f(value)
                new_value = os.path.abspath(fname + "_Nwarp" + ext)
                print(new_value)

            self.new_value = new_value
            value = new_value

        return super(NwarpApplyPriors, self)._format_arg(name, spec, value)
示例#2
0
    def _gen_outfilename(self):
        from nipype.utils.filemanip import split_filename as split_f

        _, in_brain, _ = split_f(self.inputs.inb_file)
        _, ref, _ = split_f(self.inputs.refb_file)

        if isdefined(self.inputs.xp):
            outname = self.inputs.xp
        else:
            outname = in_brain + "_FLIRT-to_" + ref
        return outname
示例#3
0
    def _list_outputs(self):

        import os
        from nipype.utils.filemanip import split_filename as split_f

        outputs = self._outputs().get()

        t1_path, t1_fname, ext = split_f(self.inputs.t1_file)
        t2_path, t2_fname, ext = split_f(self.inputs.t2_file)

        if self.inputs.c:
            # !!!!warning, in Regis bash, only .nii.gz are handled
            outputs["t1_cropped_file"] = os.path.abspath(
                t1_fname + self.inputs.cs + ".nii.gz")

            if self.inputs.aT2:
                outputs["t2_cropped_file"] = os.path.abspath(
                    t2_fname + self.inputs.opt_as + self.inputs.cs + ".nii.gz")
            else:
                outputs["t2_cropped_file"] = os.path.abspath(
                    t2_fname + self.inputs.cs + ".nii.gz")

            outputs["t1_brain_file"] = os.path.abspath(
                t1_fname + self.inputs.opt_os + self.inputs.cs + ".nii.gz")
            outputs["t2_brain_file"] = os.path.abspath(
                t2_fname + self.inputs.opt_os + self.inputs.cs + ".nii.gz")

            if self.inputs.m:
                # !!!!warning, in Regis bash, only .nii.gz are handled
                outputs["mask_file"] = os.path.abspath(
                    t1_fname + self.inputs.opt_os + self.inputs.ms +
                    self.inputs.cs + ".nii.gz")

        else:

            outputs["t1_brain_file"] = os.path.abspath(
                t1_fname + self.inputs.opt_os + ".nii.gz")
            outputs["t2_brain_file"] = os.path.abspath(
                t2_fname + self.inputs.opt_os + ".nii.gz")

            if self.inputs.m:
                # !!!!warning, in Regis bash, only .nii.gz are handled
                outputs["mask_file"] = os.path.abspath(
                    t1_fname + self.inputs.opt_os + self.inputs.ms + ".nii.gz")

        if self.inputs.aT2:
            outputs["t2_coreg_file"] = os.path.abspath(
                t2_fname + self.inputs.opt_as + ".nii.gz")

        return outputs
def convert_ds_to_raw_fif(ds_file):
    import os
    import os.path as op
    
    from nipype.utils.filemanip import split_filename as split_f
    from mne.io import read_raw_ctf
    
    
    subj_path,basename,ext = split_f(ds_file)
    print subj_path,basename,ext
    raw = read_raw_ctf(ds_file)
    #raw_fif_file = os.path.abspath(basename + "_raw.fif")
    
    #raw.save(raw_fif_file)
    #return raw_fif_file

    
    raw_fif_file = os.path.join(subj_path,basename + "_raw.fif")
    if not op.isfile(raw_fif_file):
        raw = read_raw_ctf(ds_file)
        raw.save(raw_fif_file)
    else:
        print '*** RAW FIF file %s exists!!!' % raw_fif_file
        
    return raw_fif_file
示例#5
0
def _is_trans(raw_fname, trans_fname_template=None):
    """Check if coregistration file."""
    data_path, raw_fname, ext = split_f(raw_fname)

    if not trans_fname_template:
        raw_fname_4trans = raw_fname
        raw_fname_4trans = raw_fname_4trans.replace('_', '*')
        raw_fname_4trans = raw_fname_4trans.replace('-', '*')
        raw_fname_4trans = raw_fname_4trans.replace('filt', '*')
        raw_fname_4trans = raw_fname_4trans.replace('dsamp', '*')
        raw_fname_4trans = raw_fname_4trans.replace('ica', '*')
        raw_fname_4trans = raw_fname_4trans.replace('raw', '*')

        trans_fpath = op.join(data_path, '%s*trans.fif' % raw_fname_4trans)
    else:
        trans_fpath = op.join(data_path, trans_fname_template)

    trans_files = glob.glob(trans_fpath)
    assert len(trans_files) == 1, "Error, should be only one trans file"

    trans_fname = trans_files[0]

    print(('\n*** coregistration file %s found!!!\n' % trans_fname))

    print (trans_fname)

    if not op.isfile(trans_fname):
        raise RuntimeError('*** coregistration file %s NOT found!!!'
                        % trans_fname)

    return trans_fname
示例#6
0
def get_MRI_sbj_dir(dcm_file):
    from nipype.utils.filemanip import split_filename as split_f
    import os.path as op
    
    MRI_sbj_dir, basename, ext = split_f(dcm_file)
    struct_filename = op.join(MRI_sbj_dir, 'struct.nii.gz')
    return struct_filename
示例#7
0
def plot_coclass_matrix_labels_range(coclass_matrix_file,labels_file,list_value_range):

    import numpy as np
    import os
    
    from nipype.utils.filemanip import split_filename as split_f
    
    from dmgraphanalysis.utils_plot import plot_ranged_cormat
    #from dmgraphanalysis.utils_plot import plot_cormat
    
    print 'loading labels'
    labels = [line.strip() for line in open(labels_file)]
    
    np_labels = np.array(labels,dtype = 'string')
    
    #print np_labels
    
    #print coclass_mat.shape
    
    print 'loading coclass'
    coclass_mat = np.load(coclass_matrix_file)
    
    
    print 'plotting heatmap'
    
    path,fname,ext = split_f(coclass_matrix_file)
    
    plot_coclass_matrix_file =  os.path.abspath('heatmap_' + fname + '.eps')
    
    plot_ranged_cormat(plot_coclass_matrix_file,coclass_mat,labels,fix_full_range = list_value_range)
    
    return plot_coclass_matrix_file
def _is_trans(raw_fname, trans_fname_template=None):
    """Check if coregistration file."""
    data_path, raw_fname, ext = split_f(raw_fname)

    if not trans_fname_template:
        raw_fname_4trans = raw_fname
        raw_fname_4trans = raw_fname_4trans.replace('_', '*')
        raw_fname_4trans = raw_fname_4trans.replace('-', '*')
        raw_fname_4trans = raw_fname_4trans.replace('filt', '*')
        raw_fname_4trans = raw_fname_4trans.replace('dsamp', '*')
        raw_fname_4trans = raw_fname_4trans.replace('ica', '*')
        raw_fname_4trans = raw_fname_4trans.replace('raw', '*')

        trans_fpath = op.join(data_path, '%s*trans.fif' % raw_fname_4trans)
    else:
        trans_fpath = op.join(data_path, trans_fname_template)

    for trans_fname in glob.glob(trans_fpath):
        print(('\n*** coregistration file %s found!!!\n' % trans_fname))

    if not op.isfile(trans_fname):
        raise RuntimeError('*** coregistration file %s NOT found!!!' %
                           trans_fname)

    return trans_fname
示例#9
0
def plot_igraph_coclass_matrix(coclass_matrix_file,gm_mask_coords_file,threshold):

    import numpy as np
    import os
    import pylab as pl
    
    from dmgraphanalysis.plot_igraph import plot_igraph_3D_int_mat
    
    from nipype.utils.filemanip import split_filename as split_f
    
    print 'loading coclass_matrix'
    coclass_matrix = np.load(coclass_matrix_file)
    
    path,fname,ext = split_f(coclass_matrix_file)
    
    
    print 'loading gm mask corres'
    
    gm_mask_coords = np.loadtxt(gm_mask_coords_file)
    
    print gm_mask_coords.shape
        
        
    print 'plotting igraph'
    
    coclass_matrix[coclass_matrix < threshold] = 0
    
    plot_igraph_3D_coclass_matrix_file = os.path.abspath('plot_igraph_3D_coclass_matrix.eps')
    
    plot_igraph_3D_int_mat(coclass_matrix,gm_mask_coords,plot_igraph_3D_coclass_matrix_file)
    
    return plot_igraph_3D_coclass_matrix_file    
示例#10
0
def preprocess_fif(fif_file, l_freq=None, h_freq=None, down_sfreq=None):
    """Filter and downsample data"""

    import os
    from mne.io import read_raw_fif
    from mne import pick_types
    from nipype.utils.filemanip import split_filename as split_f

    _, basename, ext = split_f(fif_file)

    raw = read_raw_fif(fif_file, preload=True)

    filt_str, down_str = '', ''

    select_sensors = pick_types(raw.info, meg=True, ref_meg=False, eeg=False)

    if l_freq or h_freq:
        raw.filter(l_freq=l_freq, h_freq=h_freq,
                   picks=select_sensors, fir_design='firwin')
        filt_str = '_filt'

    if down_sfreq:
        raw.resample(sfreq=down_sfreq, npad=0, stim_picks=select_sensors)
        down_str = '_dsamp'

    savename = os.path.abspath(basename + filt_str + down_str + ext)
    raw.save(savename)
    return savename
 def _run_interface(self, runtime):
             
     print 'in plot_coclass'
     
     coclass_matrix_file = self.inputs.coclass_matrix_file
     labels_file = self.inputs.labels_file
     list_value_range = self.inputs.list_value_range
         
     
     print 'loading coclass'
     coclass_mat = np.load(coclass_matrix_file)
     
     
     if isdefined(labels_file):
         
         print 'loading labels'
         labels = [line.strip() for line in open(labels_file)]
         
     else :
         labels = []
         
     if not isdefined(list_value_range):
     
         list_value_range = [np.amin(coclass_mat),np.amax(coclass_mat)]
     
     print 'plotting heatmap'
     
     path,fname,ext = split_f(coclass_matrix_file)
     
     plot_coclass_matrix_file =  os.path.abspath('heatmap_' + fname + '.eps')
     
     plot_ranged_cormat(plot_coclass_matrix_file,coclass_mat,labels,fix_full_range = list_value_range)
     
     return runtime
示例#12
0
    def _format_arg(self, name, spec, value):

        import os
        import shutil

        cur_dir = os.getcwd()

        new_value = []
        if name == 'in_file':
            for in_file in value:
                print(in_file)

                # copy en local
                shutil.copy(in_file, cur_dir)

                new_value.append(os.path.join(cur_dir, in_file))

            value = new_value

        elif name == 'out_file':
            for out_file in value[:1]:
                print(out_file)

                path, fname, ext = split_f(out_file)
                # out_files.append(os.path.join(path,fname + "_Nwarp" + ext))
                new_value.append(os.path.join(cur_dir, fname + "_Nwarp" + ext))

            for i in range(1, 4):
                new_value.append(os.path.join(cur_dir, "tmp_%02d.nii.gz" % i))
            value = new_value

        return super(NwarpApplyPriors, self)._format_arg(name, spec, value)
示例#13
0
def split_indexed_mask(nii_file, background_val=0):

    import os
    import nibabel as nib
    import numpy as np
    from nipype.utils.filemanip import split_filename as split_f

    path, fname, ext = split_f(nii_file)

    nii = nib.load(nii_file)

    nii_data = nii.get_data()

    list_split_files = []

    for index in np.unique(nii_data):
        if index == background_val:
            continue

        split_file = os.path.abspath("{}_{}{}".format(fname, index, ext))

        split_data = np.zeros(shape=nii_data.shape)
        split_data[nii_data == index] = 1

        nib.save(
            nib.Nifti1Image(split_data, header=nii.header, affine=nii.affine),
            split_file)

        list_split_files.append(split_file)

    return list_split_files
示例#14
0
def convert_ds_to_raw_fif(ds_file):
    """CTF .ds to .fif and save result in pipeline folder structure."""
    import os
    import os.path as op

    from nipype.utils.filemanip import split_filename as split_f
    from mne.io import read_raw_ctf

    _, basename, ext = split_f(ds_file)
    # print(subj_path, basename, ext)
    raw = read_raw_ctf(ds_file)
    # raw_fif_file = os.path.abspath(basename + "_raw.fif")

    # raw.save(raw_fif_file)
    # return raw_fif_file

    raw_fif_file = os.path.abspath(basename + "_raw.fif")

    if not op.isfile(raw_fif_file):
        raw = read_raw_ctf(ds_file)
        raw.save(raw_fif_file)
    else:
        print(('*** RAW FIF file %s exists!!!' % raw_fif_file))

    return raw_fif_file
示例#15
0
    def _format_arg(self, name, spec, value):
        import os
        import shutil

        cur_path = os.path.abspath("")

        print("***** In formating args for ", name)

        # all the files have to be in local and
        if name == 'brain_file' or name == 'brainmask_file':
            # requires local copy
            shutil.copy(value, cur_path)
            value = os.path.split(value)[1]

        elif name == 'priors':

            new_value = []

            print("***** Copying prior files in cur dir:", value)

            for prior_file in value:
                shutil.copy(prior_file, cur_path)
                new_value.append(os.path.split(prior_file)[1])

            print("After copying:", new_value)

            value = "tmp_%02d_allineate_hd.nii.gz"

        elif name == 'out_pref':

            pth, fname, ext = split_f(self.inputs.brain_file)
            value = fname + '_'
            self.inputs.out_pref = value

        return super(AtroposN4, self)._format_arg(name, spec, value)
示例#16
0
def create_epochs(fif_file, ep_length):
    """Split raw .fif file into epochs of
    length ep_length with rejection criteria"""

    import os
    from mne.io import Raw
    from mne import Epochs
    from mne import pick_types
    from nipype.utils.filemanip import split_filename as split_f

    # flat = dict(mag=0.1e-12, grad=1e-13)
    # reject = dict(mag=6e-12, grad=25e-11)
    flat = None
    reject = None

    raw = Raw(fif_file)
    picks = pick_types(raw.info, ref_meg=False, eeg=False)
    if raw.times[-1] >= ep_length:
        events = create_events(raw, ep_length)
    else:
        raise Exception('File {} is too short!'.format(fif_file))

    epochs = Epochs(raw, events=events, tmin=0, tmax=ep_length,
                    preload=True, picks=picks, proj=False,
                    flat=flat, reject=reject)

    _, base, ext = split_f(fif_file)
    savename = os.path.abspath(base + '-epo' + ext)
    epochs.save(savename)
    return savename
示例#17
0
    def _list_outputs(self):

        from nipype.utils.filemanip import split_filename as split_f

        outputs = self._outputs().get()

        path, fname, ext = split_f(self.inputs.T1_file)

        outputs["aff_file"] = os.path.abspath(fname + "_affine" + ext)

        # TODO will require some checks
        # outputs["warpinv_file"] = os.path.abspath(
        # fname + "_shft_WARPINV.nii")
        outputs["warpinv_file"] = os.path.abspath(fname + "_WARPINV.nii.gz")

        outputs["warp_file"] = os.path.abspath(fname + "_WARP.nii.gz")

        # outputs["warpinv_file"] = os.path.abspath(
        #    fname + "_shft_WARPINV" + ext)

        outputs["transfo_file"] = os.path.abspath(
            fname + "_composite_linear_to_NMT.1D")
        outputs["inv_transfo_file"] = os.path.abspath(
            fname + "_composite_linear_to_NMT_inv.1D")

        return outputs
def compute_noise_cov(cov_fname, raw):
    import os.path as op

    from mne import compute_raw_covariance, pick_types, write_cov
    from nipype.utils.filemanip import split_filename as split_f
    from neuropype_ephy.preproc import create_reject_dict

    print '***** COMPUTE RAW COV *****' + cov_fname

    if not op.isfile(cov_fname):

        data_path, basename, ext = split_f(raw.info['filename'])
        fname = op.join(data_path, '%s-cov.fif' % basename)

        reject = create_reject_dict(raw.info)
#        reject = dict(mag=4e-12, grad=4000e-13, eog=250e-6)

        picks = pick_types(raw.info, meg=True, ref_meg=False, exclude='bads')

        noise_cov = compute_raw_covariance(raw, picks=picks, reject=reject)

        write_cov(fname, noise_cov)

    else:
        print '*** NOISE cov file %s exists!!!' % cov_fname

    return cov_fname
示例#19
0
def _save_psd_img(data_fname, psds, freqs, is_epoched=False, method=''):

    import os
    import matplotlib.pyplot as plt
    import numpy as np

    from nipype.utils.filemanip import split_filename as split_f

    data_path, basename, ext = split_f(data_fname)
    psds_img_fname = basename + '-psds.png'
    psds_img_fname = os.path.abspath(psds_img_fname)

    # save PSD as img
    f, ax = plt.subplots()
    psds = 10 * np.log10(psds)
    if is_epoched:
        psds_mean = psds.mean(0).mean(0)
        psds_std = psds.mean(0).std(0)
    else:
        psds_mean = psds.mean(0)
        psds_std = psds.std(0)

    ax.plot(freqs, psds_mean, color='g')
    ax.fill_between(freqs,
                    psds_mean - psds_std,
                    psds_mean + psds_std,
                    color='g',
                    alpha=.5)
    ax.set(title='{} PSD'.format(method),
           xlabel='Frequency',
           ylabel='Power Spectral Density (dB)')

    print(('*** save {} ***'.format(psds_img_fname)))
    plt.savefig(psds_img_fname)
示例#20
0
def _read_hdf5(filename, dataset_name='dataset', transpose=False):
    """
    Read hdf5 file

    Inputs
        filename : str
            hdf5 filename
        dataset_name : str
            name of dataset to create
        transpose: bool
            if the data needs to be transpose or not
    Outputs
        data : array, shape (n_vertices, n_times)
            raw data for whose the dataset is created
    """

    hf = h5py.File(filename, 'r')
    data = hf[dataset_name][()]

    if transpose:
        data = np.transpose(data)

    old_path, basename, ext = split_f(filename)
    npy_filename = os.path.abspath(basename + '.npy')
    print(npy_filename)
    np.save(npy_filename, data, allow_pickle=True)
    return npy_filename
    def get_MRI_sbj_dir(dcm_file):
        from nipype.utils.filemanip import split_filename as split_f
        import os.path as op

        MRI_sbj_dir, basename, ext = split_f(dcm_file)
        struct_filename = op.join(MRI_sbj_dir, 'struct.nii.gz')
        return struct_filename
示例#22
0
    def _run_interface(self, runtime):

        coclass_matrix_file = self.inputs.coclass_matrix_file
        labels_file = self.inputs.labels_file
        list_value_range = self.inputs.list_value_range

        coclass_mat = np.load(coclass_matrix_file)

        if isdefined(labels_file):

            labels = [line.strip() for line in open(labels_file)]

        else:
            labels = []

        if not isdefined(list_value_range):
            list_value_range = [np.amin(coclass_mat), np.amax(coclass_mat)]

        path, fname, ext = split_f(coclass_matrix_file)
        plot_coclass_matrix_file = os.path.abspath('heatmap_' + fname + '.eps')
        plot_ranged_cormat(plot_coclass_matrix_file,
                           coclass_mat,
                           labels,
                           fix_full_range=list_value_range)
        return runtime
示例#23
0
def _create_epochs(fif_file, ep_length):
    """Split raw .fif file into epochs.

    Splitted epochs have a length ep_length with rejection criteria.
    """
    flat = None
    reject = None

    raw = read_raw_fif(fif_file)
    picks = pick_types(raw.info, ref_meg=False, eeg=False)
    if raw.times[-1] >= ep_length:
        events = _create_events(raw, ep_length)
    else:
        raise Exception('File {} is too short!'.format(fif_file))

    epochs = Epochs(raw,
                    events=events,
                    tmin=0,
                    tmax=ep_length,
                    preload=True,
                    picks=picks,
                    proj=False,
                    flat=flat,
                    reject=reject,
                    baseline=None)

    _, base, ext = split_f(fif_file)
    savename = os.path.abspath(base + '-epo' + ext)
    epochs.save(savename)
    return savename
示例#24
0
def is_trans(raw_fname):
    """Check if coregistration file."""
    import glob
    import os.path as op

    from nipype.utils.filemanip import split_filename as split_f

    data_path, raw_fname, ext = split_f(raw_fname)

    # check if the co-registration file was created
    # if not raise an runtime error
    # i_ica = raw_fname.find('ica')
    # if i_ica != -1:
    #     raw_fname = raw_fname[:i_ica]

    raw_fname_4trans = raw_fname
    raw_fname_4trans = raw_fname_4trans.replace('_', '*')
    raw_fname_4trans = raw_fname_4trans.replace('-', '*')
    raw_fname_4trans = raw_fname_4trans.replace('filt', '*')
    raw_fname_4trans = raw_fname_4trans.replace('dsamp', '*')
    raw_fname_4trans = raw_fname_4trans.replace('ica', '*')

    trans_fname = op.join(data_path, '%s*trans.fif' % raw_fname_4trans)
    for trans_fname in glob.glob(trans_fname):
        print(('\n*** coregistration file %s found!!!\n' % trans_fname))

    if not op.isfile(trans_fname):
        raise RuntimeError('*** coregistration file %s NOT found!!!' %
                           trans_fname)

    return trans_fname
示例#25
0
def compute_ROI_nii_from_ROI_coords_files(ref_img_file,
                                          MNI_coords_file,
                                          labels_file,
                                          neighbourhood=1):
    """
    Export single file VOI binary nii image
    """
    ref_image = nib.load(ref_img_file)
    ref_image_data = ref_image.get_data()
    ref_image_data_shape = ref_image_data.shape
    ref_image_data_sform = ref_image.get_sform()

    ROI_MNI_coords_list = np.array(np.loadtxt(MNI_coords_file),
                                   dtype='int').tolist()

    ROI_labels = [lign.strip() for lign in open(labels_file)]

    # transform MNI coords to numpy coords
    mni_sform_inv = np.linalg.inv(ref_image_data_sform)

    ROI_coords = np.array([
        _coord_transform(x, y, z, mni_sform_inv)
        for x, y, z in ROI_MNI_coords_list
    ],
                          dtype="int64")

    for i, ROI_coord in enumerate(ROI_coords):

        ROI_coords_labelled_mask = np.zeros(shape=ref_image_data_shape,
                                            dtype='int64')

        neigh_range = list(range(-neighbourhood, neighbourhood + 1))

        for relative_coord in iter.product(neigh_range, repeat=3):

            neigh_x, neigh_y, neigh_z = ROI_coord + relative_coord

            print(neigh_x, neigh_y, neigh_z)

            if check_np_dimension(
                    ROI_coords_labelled_mask.shape,
                    np.array([neigh_x, neigh_y, neigh_z], dtype='int64')):

                ROI_coords_labelled_mask[neigh_x, neigh_y, neigh_z] = 1

        print(ROI_coords_labelled_mask)

        path, fname, ext = split_f(MNI_coords_file)

        ROI_coords_labelled_mask_file = os.path.join(
            path, "ROI_{}-neigh_{}_2.nii".format(ROI_labels[i],
                                                 str(neighbourhood)))

        # save ROI_coords_labelled_mask
        nib.save(
            nib.Nifti1Image(ROI_coords_labelled_mask, ref_image.affine,
                            ref_image.header), ROI_coords_labelled_mask_file)

    return ROI_coords_labelled_mask_file
示例#26
0
    def _run_interface(self, runtime):

        raw_filename = self.inputs.raw_filename
        cov_fname_in = self.inputs.cov_fname_in
        is_epoched = self.inputs.is_epoched
        is_evoked = self.inputs.is_evoked
        events_id = self.inputs.events_id
        t_min = self.inputs.t_min
        t_max = self.inputs.t_max

        data_path, basename, ext = split_f(raw_filename)

        self.cov_fname_out = op.join(data_path, '%s-cov.fif' % basename)

        # Check if a noise cov matrix was already computed
        if not op.isfile(cov_fname_in):
            if is_epoched and is_evoked:
                raw = read_raw_fif(raw_filename)
                events = find_events(raw)

                if not op.isfile(self.cov_fname_out):
                    print(('\n*** COMPUTE COV FROM EPOCHS ***\n' +
                           self.cov_fname_out))

                    reject = _create_reject_dict(raw.info)
                    picks = pick_types(raw.info,
                                       meg=True,
                                       ref_meg=False,
                                       exclude='bads')

                    epochs = Epochs(raw,
                                    events,
                                    events_id,
                                    t_min,
                                    t_max,
                                    picks=picks,
                                    baseline=(None, 0),
                                    reject=reject)

                    # TODO method='auto'? too long!!!
                    noise_cov = compute_covariance(epochs,
                                                   tmax=0,
                                                   method='diagonal_fixed')
                    write_cov(self.cov_fname_out, noise_cov)
                else:
                    print(('\n *** NOISE cov file %s exists!!! \n' %
                           self.cov_fname_out))
            else:
                # Compute noise cov matrix from empty room data
                self.cov_fname_out = compute_noise_cov(
                    op.join(data_path, cov_fname_in), raw_filename)

        else:
            print(
                ('\n *** NOISE cov file {} exists!!! \n'.format(cov_fname_in)))
            self.cov_fname_out = cov_fname_in

        return runtime
示例#27
0
 def _list_outputs(self):
     
     outputs = self._outputs().get()
     
     path, fname, ext = split_f(self.inputs.Pajek_net_file)
 
     #outputs["rada_log_file"] = os.path.abspath(fname + '.log')
 
     return outputs
示例#28
0
def plot_coclass_matrix(coclass_matrix_file):

    import numpy as np
    import os
    import matplotlib.pyplot as plt
    import pylab as pl
    
    from nipype.utils.filemanip import split_filename as split_f
    
    print 'loading sum_coclass_matrix'
    
    sum_coclass_matrix = np.load(coclass_matrix_file)
    
    path,fname,ext = split_f(coclass_matrix_file)
    
    print 'plotting heatmap'
    
    plot_heatmap_coclass_matrix_file =  os.path.abspath('heatmap_' + fname + '.eps')
    
    #fig1 = figure.Figure()
    fig1 = plt.figure()
    ax = fig1.add_subplot(1,1,1)
    im = ax.matshow(sum_coclass_matrix)
    im.set_cmap('spectral')
    fig1.colorbar(im)
    
    fig1.savefig(plot_heatmap_coclass_matrix_file)
    
    plt.close(fig1)
    #fig1.close()
    del fig1
    
    
    ############# histogram 
    
    print 'plotting distance matrix histogram'
     
    #plt.figure()
    
    #plt.figure.Figure()
    
    
    plot_hist_coclass_matrix_file = os.path.abspath('hist_coclass_matrix.eps')
    
    #fig2 = figure.Figure()
    fig2 = plt.figure()
    ax = fig2.add_subplot(1,1,1)
    y, x = np.histogram(sum_coclass_matrix, bins = 100)
    ax.plot(x[:-1],y)
    #ax.bar(x[:-1],y, width = y[1]-y[0])
    fig2.savefig(plot_hist_coclass_matrix_file)
    
    plt.close(fig2)
    #fig2.close()
    del fig2
    
    return plot_hist_coclass_matrix_file,plot_heatmap_coclass_matrix_file
 def _list_outputs(self):
     
     outputs = self._outputs().get()
     
     path, fname, ext = split_f(self.inputs.Pajek_net_file)
 
     outputs["rada_log_file"] = os.path.abspath(fname + '.log')
 
     return outputs
 def _list_outputs(self):
     
     outputs = self._outputs().get()
     
     path,fname,ext = split_f(self.inputs.coclass_matrix_file)
     
     outputs["plot_coclass_matrix_file"] = os.path.abspath('heatmap_' + fname + '.eps')
     
     return outputs
示例#31
0
def compute_ts_inv_sol(raw, fwd_filename, cov_fname, snr, inv_method, aseg):
    """Compute ts inverse solution."""
    import os.path as op
    import numpy as np
    import mne
    from mne.minimum_norm import make_inverse_operator, apply_inverse_raw
    from nipype.utils.filemanip import split_filename as split_f

    print(('***** READ FWD SOL %s *****' % fwd_filename))
    forward = mne.read_forward_solution(fwd_filename)

    # Convert to surface orientation for cortically constrained
    # inverse modeling
    if not aseg:
        forward = mne.convert_forward_solution(forward, surf_ori=True)

    lambda2 = 1.0 / snr**2

    # compute inverse operator
    print('***** COMPUTE INV OP *****')
    inverse_operator = make_inverse_operator(raw.info,
                                             forward,
                                             cov_fname,
                                             loose=0.2,
                                             depth=0.8)

    # apply inverse operator to the time windows [t_start, t_stop]s
    # TEST
    t_start = 0  # sec
    t_stop = 3  # sec
    start, stop = raw.time_as_index([t_start, t_stop])
    print(('***** APPLY INV OP ***** [%d %d]sec' % (t_start, t_stop)))
    stc = apply_inverse_raw(raw,
                            inverse_operator,
                            lambda2,
                            inv_method,
                            label=None,
                            start=start,
                            stop=stop,
                            pick_ori=None)

    print('***')
    print(('stc dim ' + str(stc.shape)))
    print('***')

    subj_path, basename, ext = split_f(raw.info['filename'])
    data = stc.data

    print(('data dim ' + str(data.shape)))

    # save results in .npy file that will be the input for spectral node
    print('***** SAVE SOL *****')
    ts_file = op.abspath(basename + '.npy')
    np.save(ts_file, data)

    return ts_file
示例#32
0
    def _list_outputs(self):

        import os
        from nipype.utils.filemanip import split_filename as split_f

        outputs = self._outputs().get()

        path, fname, ext = split_f(self.inputs.t1_restored_file)
        outputs["brain_file"] = os.path.abspath(fname + '_brain' + ext)
        return outputs
示例#33
0
    def _list_outputs(self):

        outputs = self._outputs().get()

        path, fname, ext = split_f(self.inputs.coclass_matrix_file)

        outputs["plot_coclass_matrix_file"] = os.path.abspath('heatmap_' +
                                                              fname + '.eps')

        return outputs
示例#34
0
def _get_raw_array(raw_fname, save_data=True):
    """Read a raw data from **.fif** file and save the data time series, the
    sensors coordinates and labels in .npy and .txt files.

    Parameters
    ----------
    raw_fname : str
        pathname of the raw data to read

    Returns
    -------
    array_file : str
        pathname of the numpy file (.npy) containing the data read from
        raw_fname
    channel_coords_file : str
        pathname of .txt file containing the channels coordinates
    channel_names_file : str
        pathname of .txt file containing the channels labels
    sfreq : float
        sampling frequency
    """
    raw = read_raw_fif(raw_fname, preload=True)
    subj_path, basename, ext = split_f(raw_fname)
    select_sensors = mne.pick_types(raw.info,
                                    meg=True,
                                    ref_meg=False,
                                    exclude='bads')

    # save electrode locations
    sens_loc = [raw.info['chs'][i]['loc'][:3] for i in select_sensors]
    sens_loc = np.array(sens_loc)

    channel_coords_file = os.path.abspath('correct_channel_coords.txt')
    np.savetxt(channel_coords_file, sens_loc, fmt=str("%s"))

    # save electrode names
    ch_names = np.array([raw.ch_names[pos] for pos in select_sensors],
                        dtype='str')

    channel_names_file = os.path.abspath('correct_channel_names.txt')
    np.savetxt(channel_names_file, ch_names, fmt=str('%s'))

    if save_data:
        data, times = raw[select_sensors, :]
        print((data.shape))

        array_file = os.path.abspath(basename + '.npy')
        np.save(array_file, data)
        print('\n *** TS FILE {} *** \n'.format(array_file))
    else:
        array_file = None
    print('*** raw.info[sfreq] = {}'.format(raw.info['sfreq']))

    return array_file, channel_coords_file, channel_names_file, raw.info[
        'sfreq']  # noqa
示例#35
0
def _get_fwd_filename(raw_fpath, aseg, spacing):

    data_path, raw_fname, ext = split_f(raw_fpath)
    fwd_filename = raw_fname + '-' + spacing
    if aseg:
        fwd_filename += '-aseg'

    fwd_filename = op.join(data_path, fwd_filename + '-fwd.fif')

    print(('\n *** fwd_filename {} ***\n'.format(fwd_filename)))
    return fwd_filename
示例#36
0
 def _list_outputs(self):
     
     outputs = self._outputs().get()
     
     net_List_file = self.inputs.net_List_file
     
     path, fname, ext = split_f(net_List_file)
 
     outputs["Pajek_net_file"] = os.path.abspath(fname + '.net')
 
     return outputs
示例#37
0
 def _list_outputs(self):
     
     outputs = self._outputs().get()
     
     net_List_file = self.inputs.net_List_file
     
     path, fname, ext = split_f(net_List_file)
 
     outputs["Pajek_net_file"] = os.path.abspath(fname + '.net')
 
     return outputs
示例#38
0
    def _get_fwd_filename(self, raw_info, aseg, spacing):

        data_path, raw_fname, ext = split_f(raw_info)
        fwd_filename = '%s-%s' % (raw_fname, spacing)
        if aseg:
            fwd_filename += '-aseg'

        fwd_filename = op.join(data_path, fwd_filename + '-fwd.fif')

        print(('\n *** fwd_filename %s ***\n' % fwd_filename))
        return fwd_filename
示例#39
0
def split_fif_into_eo_ec(fif_file, lCondStart, lCondEnd, first_samp, cond):
  # import mne
  import os
  from nipype.utils.filemanip import split_filename as split_f
  from mne.io import Raw
  subj_path, basename, ext = split_f(fif_file)
  # raw1 = raw.crop(tmin=10, tmax=30)
  # print("I did smth")
# --------------- Delete later ----------------------- #
  subj_name = subj_path[-5:]
  results_dir = subj_path[:-6]
  results_dir += '2016'
  subj_path = results_dir + '/' + subj_name
  if not os.path.exists(subj_path):
      os.makedirs(subj_path)
########################################################

  print(fif_file)
  Raw_fif = Raw(fif_file, preload=True)
  # first_samp_time = Raw_fif.index_as_time(Raw_fif.first_samp)
  lRaw_cond = []
  # print("I did smth")

  if cond == 'eo':
    eo_ec_split_fif = subj_path + '/' + basename + '_eo'
  elif cond == 'ec':
    eo_ec_split_fif = subj_path + '/' + basename + '_ec'

  for i in range(len(lCondStart)):
    tmin = lCondStart[i] - first_samp
    tmax = lCondEnd[i] - first_samp
    # To make sure, that my eo-ec time intervals are inside the recording
    if i == 0:
      tmin += 0.5
    if i == range(len(lCondStart))[-1]:
      tmax -= 0.5
    ####################################
    # print("tmin = ")
    # print(tmin)
    # print("tmax = ")
    # print(tmax)
    fif_cropped = Raw_fif.crop(tmin=tmin, tmax=tmax)
    cropped_filename = eo_ec_split_fif + '_' + str(i) + ext
    fif_cropped.save(cropped_filename, overwrite=True)
    lRaw_cond.append(fif_cropped)

  Raw_cond = lRaw_cond[0]
  Raw_cond.append(lRaw_cond[1:])

  print(eo_ec_split_fif)
  eo_ec_split_fif = eo_ec_split_fif + ext
  Raw_cond.save(eo_ec_split_fif, overwrite=True)
  return eo_ec_split_fif
示例#40
0
def merge_masks(mask_csf_file,
                mask_wm_file,
                mask_gm_file,
                index_csf=1,
                index_gm=2,
                index_wm=3):

    import nibabel as nib
    import numpy as np
    import os.path as op

    from nipype.utils.filemanip import split_filename as split_f

    # csf (and init indexed_mask)
    path, fname, ext = split_f(mask_csf_file)

    mask_csf = nib.load(mask_csf_file)

    mask_csf_data = mask_csf.get_data()

    indexed_mask_data = np.zeros(shape=mask_csf_data.shape)

    indexed_mask_data[mask_csf_data == 1] = index_csf

    # gm
    mask_gm = nib.load(mask_gm_file)

    mask_gm_data = mask_gm.get_data()

    assert np.all(indexed_mask_data.shape == mask_gm_data.shape)

    indexed_mask_data[mask_gm_data == 1] = index_gm

    # wm
    mask_wm = nib.load(mask_wm_file)

    mask_wm_data = mask_wm.get_data()

    assert np.all(indexed_mask_data.shape == mask_wm_data.shape)

    indexed_mask_data[mask_wm_data == 1] = index_wm

    # creating indexed_mask
    indexed_mask = nib.Nifti1Image(dataobj=indexed_mask_data,
                                   affine=mask_csf.affine,
                                   header=mask_csf.header)

    # saving indexed_mask_file
    indexed_mask_file = op.abspath(fname + "_indexed_mask" + ext)

    nib.save(indexed_mask, indexed_mask_file)

    return indexed_mask_file
示例#41
0
def average_align(list_img):

    import os
    import nibabel as nib
    import numpy as np

    from nipype.utils.filemanip import split_filename as split_f
    import nipype.interfaces.fsl as fsl

    print("average_align:", list_img)

    if isinstance(list_img, list):

        assert len(list_img) > 0, "Error, list should have at least one file"

        if len(list_img) == 1:
            assert os.path.exists(list_img[0])
            av_img_file = list_img[0]
        else:

            img_0 = nib.load(list_img[0])
            path, fname, ext = split_f(list_img[0])

            list_data = [img_0.get_data()]
            for i, img in enumerate(list_img[1:]):

                print("running flirt on {}".format(img))
                flirt = fsl.FLIRT(dof=6)
                flirt.inputs.in_file = img
                flirt.inputs.reference = list_img[0]
                flirt.inputs.interp = "sinc"
                flirt.inputs.no_search = True
                out_file = flirt.run().outputs.out_file
                print(out_file)

                data = nib.load(out_file).get_data()
                list_data.append(data)

            avg_data = np.mean(np.array(list_data), axis=0)
            print(avg_data.shape)

            av_img_file = os.path.abspath("avg_" + fname + ext)
            nib.save(
                nib.Nifti1Image(avg_data,
                                header=img_0.get_header(),
                                affine=img_0.get_affine()), av_img_file)

    else:
        assert os.path.exists(list_img)
        av_img_file = list_img

    return av_img_file
示例#42
0
    def _get_fwd_filename(self, raw_info, aseg, spacing):

        data_path, raw_fname, ext = split_f(raw_info['filename'])

        if aseg == traits.Undefined:
            fwd_filename = op.join(data_path, '%s-%s-fwd.fif'
                                   % (raw_fname, spacing))
        else:
            fwd_filename = op.join(data_path, '%s-%s-aseg-fwd.fif'
                                   % (raw_fname, spacing))

        print '*** fwd_filename %s ***' % fwd_filename
        return fwd_filename
示例#43
0
def get_ext_file(raw_file):
    from nipype.utils.filemanip import split_filename as split_f

    subj_path, basename, ext = split_f(raw_file)

    print raw_file
    is_ds = False
    if ext is 'ds':
        is_ds = True
        return is_ds
    elif ext is 'fif':
        return is_ds
    else:
        raise RuntimeError('only fif and ds file format!!!')
示例#44
0
    def _get_fwd_filename(self, raw_info, aseg, spacing, is_blind):

        data_path, raw_fname, ext = split_f(raw_info['filename'])

        fwd_filename = '%s-%s' % (raw_fname, spacing)
        if is_blind:
            fwd_filename += '-blind'
        if aseg:
            fwd_filename += '-aseg'

        fwd_filename = op.join(data_path, fwd_filename + '-fwd.fif')

        print '\n *** fwd_filename %s ***\n' % fwd_filename
        return fwd_filename
示例#45
0
def is_trans(raw_info):
    import os.path as op

    from nipype.utils.filemanip import split_filename as split_f

    data_path, raw_fname, ext = split_f(raw_info['filename'])

    # check if the co-registration file was created
    # if not raise an runtime error
    trans_fname = op.join(data_path, '%s-trans.fif' % raw_fname)
    if not op.isfile(trans_fname):
        raise RuntimeError('*** coregistration file %s NOT found!!!'
                           % trans_fname)

    return trans_fname
示例#46
0
def import_mat_to_conmat(mat_file,orig_channel_names_file,orig_channel_coords_file):

    import os
    import numpy as np

    import mne

    from mne.io import RawArray	
    from nipype.utils.filemanip import split_filename as split_f

    from scipy.io import loadmat

    subj_path,basename,ext = split_f(mat_file)

    mat = loadmat(mat_file)

    #field_name = basename.split('_')[0]
    #field_name = basename.split('_')[1]
    #print field_name
    print mat["mat_x"].shape


    raw_data = np.array(mat["mat_x"],dtype = "f")
    print raw_data
    print raw_data.shape

    conmat_file = os.path.abspath(basename +".npy")

    np.save(conmat_file,raw_data)

    correct_channel_coords = np.loadtxt(orig_channel_coords_file)
    
    print correct_channel_coords
    
    
    correct_channel_names = np.loadtxt(orig_channel_coords_file)
    
    print correct_channel_names
    
    ### save channel coords
    channel_coords_file = os.path.abspath("correct_channel_coords.txt")
    np.savetxt(channel_coords_file ,correct_channel_coords , fmt = '%s')

    ### save channel names
    channel_names_file = os.path.abspath("correct_channel_names.txt")
    np.savetxt(channel_names_file,correct_channel_names , fmt = '%s')

    return conmat_file,channel_coords_file,channel_names_file
def compute_ts_inv_sol(raw, fwd_filename, cov_fname, snr, inv_method, aseg):
    import os.path as op
    import numpy as np
    import mne
    from mne.minimum_norm import make_inverse_operator, apply_inverse_raw
    from nipype.utils.filemanip import split_filename as split_f

    print '***** READ FWD SOL %s *****' % fwd_filename
    forward = mne.read_forward_solution(fwd_filename)

    # Convert to surface orientation for cortically constrained
    # inverse modeling
    if not aseg:
        forward = mne.convert_forward_solution(forward, surf_ori=True)

    lambda2 = 1.0 / snr ** 2

    # compute inverse operator
    print '***** COMPUTE INV OP *****'
    inverse_operator = make_inverse_operator(raw.info, forward, cov_fname,
                                             loose=0.2, depth=0.8)

    # apply inverse operator to the time windows [t_start, t_stop]s
    # TEST
    t_start = 0  # sec
    t_stop = 3  # sec
    start, stop = raw.time_as_index([t_start, t_stop])
    print '***** APPLY INV OP ***** [%d %d]sec' % (t_start, t_stop)
    stc = apply_inverse_raw(raw, inverse_operator, lambda2, inv_method,
                            label=None,
                            start=start, stop=stop, pick_ori=None)

    print '***'
    print 'stc dim ' + str(stc.shape)
    print '***'

    subj_path, basename, ext = split_f(raw.info['filename'])
    data = stc.data

    print 'data dim ' + str(data.shape)

    # save results in .npy file that will be the input for spectral node
    print '***** SAVE SOL *****'
    ts_file = op.abspath(basename + '.npy')
    np.save(ts_file, data)

    return ts_file
示例#48
0
def community_list_Louvain(Louvain_bin_file,Louvain_conf_file,louvain_bin_path):
    
    import os
    from nipype.utils.filemanip import split_filename as split_f
    
    #path, fname, ext = '','',''
    path, fname, ext = split_f(Louvain_bin_file)
    
    Louvain_mod_file = os.path.abspath(fname + '.mod')
    
    cmd = os.path.join(louvain_bin_path,'community') + ' ' + Louvain_bin_file + ' ' +  Louvain_conf_file + ' > ' + Louvain_mod_file
    
    print "executing command " + cmd
    
    os.system(cmd)
    
    return Louvain_mod_file
示例#49
0
def import_tsmat_to_ts(tsmat_file,data_field_name = 'F', good_channels_field_name = 'ChannelFlag'):
    #,orig_channel_names_file,orig_channel_coords_file):

    import os
    import numpy as np

    import mne

    from mne.io import RawArray	
    from nipype.utils.filemanip import split_filename as split_f

    from scipy.io import loadmat
    print tsmat_file
        
    subj_path,basename,ext = split_f(tsmat_file)

    mat = loadmat(tsmat_file)

    raw_data = np.array(mat[data_field_name],dtype = "f")
    print raw_data.shape

    if good_channels_field_name != None:
        
        print "Using good channels to sort channels"
        good_channels = np.array(mat[good_channels_field_name])
        print good_channels.shape
        
        
        good_channels = good_channels.reshape(good_channels.shape[0])
        print good_channels.shape
        
        
        good_data = raw_data[good_channels == 1,:]
        
        print good_data.shape
        
    else:
        print "No channel sorting" 
        good_data = raw_data
        
    #### save data
    print good_data.shape
    
    ts_file = os.path.abspath("tsmat.npy")
    np.save(ts_file,good_data)
    return ts_file
示例#50
0
def plot_order_coclass_matrix_labels(coclass_matrix_file,node_order_vect_file,labels_file):

    import numpy as np
    import os
    
    from nipype.utils.filemanip import split_filename as split_f
    
    from dmgraphanalysis.utils_plot import plot_cormat
    
    print 'loading labels'
    labels = [line.strip() for line in open(labels_file)]
    
    np_labels = np.array(labels,dtype = 'string')
    
    #print np_labels
    
    #print coclass_mat.shape
    
    print 'loading coclass'
    coclass_mat = np.load(coclass_matrix_file)
    
    print 'loading node order'
    
    node_order_vect = np.array(np.loadtxt(node_order_vect_file),dtype = 'int')
    
    print 'reordering labels'
    #print node_order_vect
    np_reordered_labels = np_labels[node_order_vect]
    
    list_reordered_labels = np_reordered_labels.tolist()
    
    print 'reordering coclass'
    
    mat = coclass_mat[node_order_vect,: ]
    
    reordered_coclass_mat = mat[:, node_order_vect]
    
    path,fname,ext = split_f(coclass_matrix_file)
    
    print 'plotting reorder heatmap'
    
    plot_reordered_coclass_matrix_file =  os.path.abspath('reordered_heatmap_' + fname + '.eps')
    
    plot_cormat(plot_reordered_coclass_matrix_file,reordered_coclass_mat,list_reordered_labels)
    
    return plot_reordered_coclass_matrix_file
 def _run_interface(self, runtime):
             
     radatools_path = self.inputs.radatools_path
     net_List_file = self.inputs.net_List_file
     
     
     path, fname, ext = split_f(net_List_file)
 
     Pajek_net_file = os.path.abspath(fname + '.net')
 
     cmd = os.path.join(radatools_path,'01-Prepare_Network','List_To_Net.exe') + ' ' + net_List_file + ' ' + Pajek_net_file + ' U'
     
     print "defining command " + cmd
 
     os.system(cmd)
 
     return runtime
    def _run_interface(self, runtime):

        raw_filename = self.inputs.raw_filename
        cov_fname_in = self.inputs.cov_fname_in
        is_epoched = self.inputs.is_epoched
        is_evoked = self.inputs.is_evoked
        events_id = self.inputs.events_id
        t_min = self.inputs.t_min
        t_max = self.inputs.t_max

        if cov_fname_in == '' or not op.exists(cov_fname_in):

            if is_epoched and is_evoked:
                raw = Raw(raw_filename)
                events = find_events(raw)

                data_path, basename, ext = split_f(raw.info['filename'])
                self.cov_fname_out = op.join(data_path, '%s-cov.fif' % basename)

                if not op.exists(self.cov_fname_out):
                    print '\n*** COMPUTE COV FROM EPOCHS ***\n' + self.cov_fname_out

                    reject = create_reject_dict(raw.info)
    
                    picks = pick_types(raw.info, meg=True, ref_meg=False,
                                       exclude='bads')

                    epochs = Epochs(raw, events, events_id, t_min, t_max,
                                    picks=picks, baseline=(None, 0),
                                    reject=reject)

                    # TODO method='auto'? too long!!!
                    noise_cov = compute_covariance(epochs, tmax=0,
                                                   method='diagonal_fixed')
                    write_cov(self.cov_fname_out, noise_cov)
                else:
                    print '\n *** NOISE cov file %s exists!!! \n' % self.cov_fname_out
            else:
                '\n *** NO EPOCH DATA \n'

        else:
            print '\n *** NOISE cov file %s exists!!! \n' % cov_fname_in
            self.cov_fname_out = cov_fname_in

        return runtime
示例#53
0
def prep_radatools(List_net_file,radatools_prep_path):

    import os
    
    from nipype.utils.filemanip import split_filename as split_f
    
    #path, fname, ext = '','',''
    path, fname, ext = split_f(List_net_file)
    
    Pajek_net_file = os.path.abspath(fname + '.net')
    
    cmd = os.path.join(radatools_prep_path,'List_To_Net.exe') + ' ' + List_net_file + ' ' +  Pajek_net_file + ' U' 
    
    print "executing command " + cmd
    
    os.system(cmd)
    
    return Pajek_net_file
示例#54
0
def import_amplmat_to_ts(tsmat_file):
    #,orig_channel_names_file,orig_channel_coords_file):

    import os
    import numpy as np

    import mne

    from mne.io import RawArray	
    from nipype.utils.filemanip import split_filename as split_f

    from scipy.io import loadmat

    print tsmat_file
        
    subj_path,basename,ext = split_f(tsmat_file)

    mat = loadmat(tsmat_file)

    #field_name = basename.split('_')[0]
    #field_name = basename.split('_')[1]
    #print field_name

    raw_data = np.array(mat['F'],dtype = "f")
    print raw_data.shape

    good_channels = np.array(mat['ChannelFlag'])

    good_channels = good_channels.reshape(good_channels.shape[0])

    print "Good channels:"
    print good_channels.shape

    good_data = raw_data[good_channels == 1,:]

    print good_data.shape

    #### save data 
    ts_file = os.path.abspath("amplmat.npy")

    np.save(ts_file,good_data)
    #np.save(ts_file,raw_data)

    return ts_file
示例#55
0
def import_mat_to_conmat(mat_file, data_field_name='F',
                         orig_channel_names_file=None,
                         orig_channel_coords_file=None):

    import os
    import numpy as np
    from nipype.utils.filemanip import split_filename as split_f

    from scipy.io import loadmat

    subj_path, basename, ext = split_f(mat_file)

    mat = loadmat(mat_file)

    print mat[data_field_name].shape

    raw_data = np.array(mat[data_field_name], dtype='f')
    print raw_data
    print raw_data.shape

    ts_file = os.path.abspath(basename + '.npy')
    np.save(ts_file, raw_data)

    if orig_channel_names_file is not None:
        correct_channel_coords = np.loadtxt(orig_channel_coords_file)
        print correct_channel_coords

        # save channel coords
        channel_coords_file = os.path.abspath('correct_channel_coords.txt')
        np.savetxt(channel_coords_file, correct_channel_coords, fmt='%s')

    if orig_channel_coords_file is not None:
        correct_channel_names = np.loadtxt(orig_channel_coords_file)
        print correct_channel_names

        # save channel names
        channel_names_file = os.path.abspath('correct_channel_names.txt')
        np.savetxt(channel_names_file, correct_channel_names, fmt='%s')

    if orig_channel_names_file is not None and orig_channel_coords_file is not None:
        return ts_file, channel_coords_file, channel_names_file
    else:
        return ts_file
 def _run_interface(self, runtime):
             
     radatools_path = self.inputs.radatools_path
     Pajek_net_file = self.inputs.Pajek_net_file
     
     optim_seq = self.inputs.optim_seq
     
     path, fname, ext = split_f(Pajek_net_file)
 
     rada_lol_file = os.path.abspath(fname + '.lol')
     rada_log_file = os.path.abspath(fname + '.log')
     
     cmd = os.path.join(radatools_path,'02-Find_Communities','Communities_Detection.exe')  + ' v ' + optim_seq + ' ' + Pajek_net_file + ' ' + rada_lol_file + ' > ' + rada_log_file
     
     print "defining command " + cmd
 
     os.system(cmd)
 
     return runtime
 def _run_interface(self, runtime):
             
     radatools_path = self.inputs.radatools_path
     Pajek_net_file = self.inputs.Pajek_net_file
     
     optim_seq = self.inputs.optim_seq
     
     path, fname, ext = split_f(Pajek_net_file)
 
     rada_log_file = os.path.abspath(fname + '.log')
     
     cmd = os.path.join(radatools_path,'04-Other_Tools','Network_Properties.exe') + ' ' + Pajek_net_file + ' ' + optim_seq + ' > ' + rada_log_file
     
     #+ ' > '+ rada_res_file
     
     print "defining command " + cmd
 
     os.system(cmd)
 
     return runtime
示例#58
0
def community_radatools(Pajek_net_file,optim_seq,radatools_comm_path):
    
    import os
    
    from nipype.utils.filemanip import split_filename as split_f
    
    #path, fname, ext = '','',''
    path, fname, ext = split_f(Pajek_net_file)
    
    rada_lol_file = os.path.abspath(fname + '.lol')
    rada_log_file = os.path.abspath(fname + '.log')
    
    #cmd = os.path.join(radatools_comm_path,'Communities_Detection.exe') + ' v WS f 1 ' + Pajek_net_file + ' ' + rada_lol_file + ' > ' + rada_log_file
    cmd = os.path.join(radatools_comm_path,'Communities_Detection.exe') + ' v ' + optim_seq + ' ' + Pajek_net_file + ' ' + rada_lol_file + ' > ' + rada_log_file
    
    
    print "executing command " + cmd
    
    os.system(cmd)
    
    return rada_lol_file,rada_log_file
示例#59
0
def convert_list_Louvain(Louvain_list_file,louvain_bin_path):
    import os
    
    from nipype.utils.filemanip import split_filename as split_f
    
    #path, fname, ext = '','',''
    path, fname, ext = split_f(Louvain_list_file)
    
    Louvain_bin_file = os.path.abspath(fname + '.bin')
    
    Louvain_node_file = os.path.abspath(fname  + '.node.txt')
    
    Louvain_conf_file = os.path.abspath(fname  + '.conf')
    
    cmd = os.path.join(louvain_bin_path,'slicer') + ' -i ' + Louvain_list_file + ' -o ' +  Louvain_bin_file + ' -n ' + Louvain_node_file + ' -c ' + Louvain_conf_file + ' -u' 
    
    print "executing command " + cmd
    
    os.system(cmd)
    
    return Louvain_bin_file,Louvain_node_file,Louvain_conf_file
示例#60
0
def create_ts(raw_fname):
    
    import os
    import numpy as np

    import mne
    from mne.io import Raw

    from nipype.utils.filemanip import split_filename as split_f

    raw = Raw(raw_fname, preload=True)
    
    subj_path, basename, ext = split_f(raw_fname)    
    
    select_sensors = mne.pick_types(raw.info, meg=True, ref_meg=False,
                                    exclude='bads')
    
    # save electrode locations
    sens_loc = [raw.info['chs'][i]['loc'][:3] for i in select_sensors]
    sens_loc = np.array(sens_loc)

    channel_coords_file = os.path.abspath("correct_channel_coords.txt")
    np.savetxt(channel_coords_file, sens_loc, fmt='%s')

    # save electrode names
    sens_names = np.array([raw.ch_names[pos] for pos in select_sensors],
                          dtype="str")

    channel_names_file = os.path.abspath("correct_channel_names.txt")
    np.savetxt(channel_names_file, sens_names, fmt='%s')
    
    data, times = raw[select_sensors, :]
    
    print data.shape

    ts_file = os.path.abspath(basename + '.npy')
    np.save(ts_file, data)
    print '\n *** TS FILE ' + ts_file + '*** \n'

    return ts_file, channel_coords_file, channel_names_file, raw.info['sfreq']