def apply_import_to_fif(opt):
    """
    apply jumeg import 4D/BTi data to FIF
    convert 4D-file to FIF format using mne
    save raw-obj to new file
    
    jumeg wrapper for <mne.io.read_raw_bti>
    https://martinos.org/mne/stable/generated/mne.io.read_raw_bti.html#mne.io.read_raw_bti
    
    Parameter
    ---------
     opt
     
    Outputfile
    ----------
    <wawa>, -raw.fif

    Returns
    -------
    return mne.io.Raw instance
    """
    # --- ck file fullpath
    fpdf = jb.isFile(opt.pdf_fname,
                     path=opt.pdf_stage,
                     head="apply_import_to_fif => file check: 4D/BTI <raw>",
                     exit_on_error=True)
    if not fpdf: return
    fcfg = jb.isFile(opt.config_fname,
                     path=opt.pdf_stage,
                     head="apply_import_to_fif:=> file check: 4D/BTI <config>",
                     exit_on_error=True)
    if not fcfg: return

    # ToDo ck if headshape file must exist
    #  pt.headshape_fake and touch hs
    #---
    #fhs  = jb.isFile(opt.head_shape_fname,path=opt.pdf_stage,head="apply_import_to_fif:=> file check: 4D/BTI <head shape>",exit_on_error=True)
    #if not fhs : return

    #--- mk fif ouput file name
    # fpdf="/mnt/meg_store2/megdaw_data21/211063/INTEXT01//18-11-15@11:20/1/c,rfDC"
    # 211063_INTEXT01_181115_1120_1_c,rfDC-raw.fif  size [Mb]:  703.534
    #---> FIF / MNE path        : /mnt/meg_store1/exp/INTEXT/mne/211063/INTEXT01/181115_1120/1/

    fif_out = os.path.expandvars(os.path.expanduser(opt.fif_stage)) + "/"
    #if opt.fif_path_prefix:
    #   fif_out += opt.fif_path_prefix+"/"
    fif_out += "/".join(fpdf.split("/")[-5:-1]) + "/"
    fif_out += "_".join(fpdf.split("/")[-5:])
    fif_out = re.sub('/+', '/',
                     fif_out).replace('@', "_").replace(":",
                                                        "").replace("-", "")
    fif_out += opt.fif_extention

    if not opt.overwrite:
        if os.path.isfile(fif_out):
            if opt.verbose:
                logger.info(
                    "---> 4D/BTI file   : {}\n".format(fpdf) +
                    " --> FIF / MNE file: {} size [Mb]: {}\n".format(
                        os.path.basename(fif_out),
                        os.path.getsize(fif_out) / 1024.0**2) +
                    " --> FIF / MNE path: {}\n".format(os.path.dirname(
                        fif_out)) +
                    "  -> !!! FIF File exist will not overwrite [overwrite={}\n"
                    .format(opt.overwrite) + "===> Done")
            return

# --- check and set opt parameter
    kwargs = dict()

    if jb.isNotEmpty(opt.rotation_x):
        kwargs["rotation_x"] = float(opt.rotation_x)
    if jb.isNotEmpty(opt.translation):
        kwargs["translation"] = float(opt.translation)
    if jb.isNotEmpty(opt.ecg_ch): kwargs["ecg_ch"] = opt.ecg_ch
    if jb.isNotEmpty(opt.eog_ch): kwargs["eog_ch"] = opt.eog_ch

    #--- run
    if opt.run:
        #print("RUN")
        # defaults mne017
        # pdf_fname, config_fname='config', head_shape_fname='hs_file', rotation_x=0.0, translation=(0.0, 0.02, 0.11), convert=True,
        # rename_channels=True, sort_by_ch_name=True, ecg_ch='E31', eog_ch=('E63', 'E64'), preload=False, verbose=None
        try:
            raw = mne.io.read_raw_bti(fpdf,
                                      config_fname=opt.config_fname,
                                      head_shape_fname=opt.head_shape_fname,
                                      preload=opt.preload,
                                      convert=opt.convert,
                                      rename_channels=opt.rename_channels,
                                      sort_by_ch_name=opt.sort_by_ch_name,
                                      verbose=opt.verbose,
                                      **kwargs)
        except:
            logger.exception(
                "---> error in mne.io.read_raw_bti:\n   -> file: {}".format(
                    fpdf))

    #--- make output filename and save
        if opt.save:
            fif_out = jb.apply_save_mne_data(raw,
                                             fname=fif_out,
                                             overwrite=opt.overwrite)

            if opt.verbose:
                logger.info("===> 4D/BTI file   : {}\n".format(fpdf) +
                            " --> FIF / MNE file: {} size [Mb]: {}\n".format(
                                os.path.basename(fif_out),
                                os.path.getsize(fif_out) / 1024.0**2) +
                            " --> FIF / MNE path: {}\n".format(
                                os.path.dirname(fif_out)))
        return raw
예제 #2
0
def apply_jumeg_merge_meeg(opt):
    """
   apply jumeg_merge_meeg
    
   Parameter
   ---------                 
    opt: argparser option obj
     
   Result
   -------
 
   """

    fn_raw_list = []
    opt_dict = {}
    jb.verbose = opt.verbose

    JuMEEG = JuMEG_MergeMEEG()
    #--- flags
    JuMEEG.verbose = opt.verbose
    JuMEEG.debug = opt.debug
    JuMEEG.filter_meg = opt.filter_meg
    JuMEEG.filter_eeg = opt.filter_eeg
    JuMEEG.do_check_ids = opt.check_ids
    JuMEEG.match_first_event = opt.first_event

    #--- check if defined not None
    if jb.isNotEmptyString(opt.meg_stim_channel):
        JuMEEG.meg.stim_channel = opt.meg_stim_channel
    if jb.isNotEmptyString(opt.eeg_stim_channel):
        JuMEEG.eeg.stim_channel = opt.eeg_stim_channel
    if jb.isNotEmptyString(opt.eeg_stim_type):
        JuMEEG.eeg.stim_type = opt.eeg_stim_type
    #---
    if jb.isNotEmpty(opt.eeg_response_shift):
        JuMEEG.eeg.response_shift = int(opt.eeg_response_shift)
    if jb.isNotEmpty(opt.eeg_and_mask):
        JuMEEG.eeg.and_mask = int(opt.eeg_and_mask)

    #--- check for single file pair or list
    if jb.isNotEmptyString(opt.list_filename):
        fn_raw_list, opt_dict = JuMEEG.get_filename_list_from_file(
            opt.list_path + "/" + opt.list_filename, start_path=opt.meg_stage)
#--- check for meg and eeg filename
    elif (jb.isNotEmptyString(opt.meg_filename)
          and jb.isNotEmptyString(opt.eeg_filename)):
        fn_raw_list.append(opt.meg_filename)
        opt_dict[opt.meg_filename] = {'bads': None, 'feeg': opt.eeg_filename}

    if not fn_raw_list:
        logger.error(
            "jumeg_merger_meeg: no meg and/or eeg file to process !!!")
        return

#--- loop preproc for each fif file
    for fif_file in (fn_raw_list):
        feeg = None
        fmeg = fif_file

        if opt_dict[fif_file]['feeg']:
            feeg = str(opt_dict[fif_file]['feeg'])
            if opt.eeg_stage:
                if os.path.isfile(opt.eeg_stage + '/' + feeg):
                    feeg = opt.eeg_stage + '/' + feeg
            if opt.meg_stage:
                if os.path.isfile(opt.meg_stage + '/' + fmeg):
                    fmeg = opt.meg_stage + '/' + fmeg

        JuMEEG.meg.filename = fmeg
        JuMEEG.eeg.filename = feeg

        #--- ck bags add global bds
        JuMEEG.bads_list = []
        if opt.set_bads:
            JuMEEG.bads_list = opt.bads_list.split(',')
    #--- ck add individual bads
        if opt_dict[fif_file].get("bads"):
            JuMEEG.bads_list.append(opt_dict[fif_file]['bads'].split(','))
    #--- individual startcode
        if opt_dict[fif_file].get("startcode"):
            JuMEEG.startcode = int(opt_dict[fif_file]["startcode"])
        elif jb.isNumber(opt.startcode):
            JuMEEG.startcode = int(opt.startcode)
        else:
            JuMEEG.startcode = JuMEEG.default_start_code
        JuMEEG.run()
예제 #3
0
def apply_filter(opt):
    """
    apply jumeg filter with argparser options
    
    load fif file (mne) get raw-obj
    calc  FIR FFT filter [bp,hp,lp,notches] for raw-obj data
    save raw-obj to new file
    filter_method : mne => fft mne-filter
                    bw  => fft butterwoth
                    ws  => fft - windowed sinc
    
    Parameter
    ---------                 
     opt: argparser option obj
     
    Result
    -------
    raw-obj
    """
    raw = None
    fout = None
    jb.verbose = opt.verbose

    #--- check if fullfile exists
    fin = jb.isfile(opt.fif_filename,
                    path=opt.fif_stage,
                    head="apply_suggest_bads: FIF File Check",
                    exit_on_error=False)
    if not fin: return

    #--- generate filter obj reset no defaults
    filter_obj = jumeg_filter(filter_method=opt.method,
                              filter_type=opt.type,
                              fcut1=None,
                              fcut2=None,
                              remove_dcoffset=False,
                              notch=np.array([]),
                              notch_width=1.0,
                              order=4)

    # !!! Py3 type(opt.fcut  ) return < cls str>

    #--- check and set opt parameter
    if jb.isNotEmpty(opt.fcut1): filter_obj.fcut1 = float(opt.fcut1)
    #---
    if jb.isNotEmpty(opt.fcut2): filter_obj.fcut2 = float(opt.fcut2)
    #---
    if jb.isNotEmpty(opt.order): filter_obj.order = float(opt.order)
    #--- calc notch array e.g. 50,100,150 .. max
    if opt.notch:
        filter_obj.calc_notches(opt.notch, opt.notch_max)
        if jb.isNotEmpty(opt.notch_width):
            filter_obj.notch_width = float(opt.notch_width)
#---
    filter_obj.filter_window = opt.window
    filter_obj.remove_dcoffset = opt.remove_dcoffset
    filter_obj.verbose = opt.verbose

    if opt.method.lower() == "mne":
        filter_obj.mne_filter_method = opt.mne_method
        if jb.isNotEmpty(opt.mne_length):
            filter_obj.mne_filter_length = float(opt.mne_length)
        if jb.isNotEmpty(opt.mne_trans_bandwith):
            filter_obj.trans_bandwith = float(opt.mne_trans_bandwith)


#--- load fif
    logger.info(" --> jumeg filter load MEG data: " + fin)
    raw, _ = jb.get_raw_obj(fin, raw=raw)
    #--- get MEG & Ref picks
    picks = jb.picks.exclude_trigger(raw)
    filter_obj.sampling_frequency = raw.info['sfreq']

    #--- apply filter
    logger.info(" --> jumeg filter apply filter")
    filter_obj.apply_filter(raw._data, picks=picks)
    logger.info(" --> jumeg filter info: " + filter_obj.filter_info)

    filter_obj.update_info_filter_settings(
        raw)  # raw.info lowpass and highpass

    #--- make output filename
    name_raw = fin.split('-')[0]
    fout = name_raw + "," + filter_obj.filter_name_postfix + opt.file_extention

    if opt.save:
        fout = jb.apply_save_mne_data(raw, fname=fout)

    return raw