def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-s', '--subject', dest='subject', help='Freesurfer subject id', type='str') parser.add_option('-l', '--layers', dest='layers', default=1, type=int, help='Number BEM layers.') parser.add_option('-i', '--ico', dest='ico', default=4, type=int, help='Triangle decimation number for single layer bem') parser.add_option('-d', '--subjects-dir', dest='subjects_dir', help='FS Subjects directory', default=subjects_dir) parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', help='Overwrite existing neuromag MRI and MNE BEM files.') options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir if subject is None or subjects_dir is None: parser.print_help() sys.exit(1) _run(subjects_dir, subject, options.layers, options.ico, options.overwrite)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-s', '--subject', dest='subject', help='Freesurfer subject id', type='str') parser.add_option('-r', '--raw-dir', dest='raw_dir', help='Path to parent directory containing raw mri data', default='PARREC', metavar='FILE') parser.add_option('-d', '--subjects-dir', dest='subjects_dir', help='FS Subjects directory', default=subjects_dir) parser.add_option('-f', '--force', dest='force', action='store_true', help='Force FreeSurfer reconstruction.') parser.add_option('-o', '--openmp', dest='openmp', default=2, type=str, help='Number of CPUs to use for reconstruction routines.') parser.add_option('-v', '--volume', dest='volume', default='MPRAGE', type=str, help='Input raw volume file for nii conversion. Default is MPRAGE ' 'it can also be MEMP_VBM.') options, args = parser.parse_args() subject = vars(options).get('subject', os.getenv('SUBJECT')) subjects_dir = options.subjects_dir raw_dir = options.raw_dir if subject is None or subjects_dir is None: parser.print_help() sys.exit(1) _run(subjects_dir, subject, raw_dir, options.force, options.openmp, options.volume)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("-o", "--out", dest="raw_out", help="Output raw FIF file", metavar="FILE", default=None) parser.add_option("-e", "--no-eog", dest="eog", action="store_false", help="Remove EOG", default=True) parser.add_option("-c", "--no-ecg", dest="ecg", action="store_false", help="Remove ECG", default=True) parser.add_option("-q", "--quiet", dest="quiet", action="store_true", help="Suppress mne_process_raw output", default=False) options, args = parser.parse_args() if options.raw_in is None: parser.print_help() sys.exit(1) raw_in = options.raw_in raw_out = options.raw_out eog = options.eog ecg = options.ecg quiet = options.quiet clean_ecg_eog(raw_in, raw_out, eog=eog, ecg=ecg, quiet=quiet)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") parser.add_option("--no-guess-mri", dest="guess_mri_subject", action='store_false', default=True, help="Prevent the GUI from automatically guessing and " "changing the MRI subject when a new head shape source " "file is selected.") options, args = parser.parse_args() with ETSContext(): mne.gui.coregistration(options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=options.subjects_dir, guess_mri_subject=options.guess_mri_subject) if is_main: sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) subject = os.environ.get('SUBJECT') subjects_dir = os.environ.get('SUBJECTS_DIR') parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=subject) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-5", "--flash05", dest="flash05", help=("Path to FLASH sequence with a spin angle of 5 " "degrees in Nifti format"), metavar="FILE") parser.add_option("-3", "--flash30", dest="flash30", help=("Path to FLASH sequence with a spin angle of 30 " "degrees in Nifti format"), metavar="FILE") parser.add_option("-v", "--view", dest="show", action="store_true", help="Show BEM model in 3D for visual inspection", default=False) options, args = parser.parse_args() if options.flash05 is None or options.flash30 is None: parser.print_help() sys.exit(1) subject = options.subject subjects_dir = options.subjects_dir flash05 = os.path.abspath(options.flash05) flash30 = os.path.abspath(options.flash30) show = options.show make_flash_bem(subject, subjects_dir, flash05, flash30, show=show)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', help='Overwrite previously computed surface') parser.add_option('-s', '--subject', dest='subject', help='The name of the subject', type='str') parser.add_option('-f', '--force', dest='force', action='store_true', help='Force transformation of surface into bem.') parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Print the debug messages.') parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-n", "--no-decimate", dest="no_decimate", help="Disable medium and sparse decimations " "(dense only)", action='store_true') options, args = parser.parse_args() subject = vars(options).get('subject', os.getenv('SUBJECT')) subjects_dir = options.subjects_dir if subject is None or subjects_dir is None: parser.print_help() sys.exit(1) _run(subjects_dir, subject, options.force, options.overwrite, options.no_decimate, options.verbose)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") parser.add_option("--no-guess-mri", dest="guess_mri_subject", action='store_false', default=None, help="Prevent the GUI from automatically guessing and " "changing the MRI subject when a new head shape source " "file is selected.") parser.add_option("--head-opacity", type=float, default=None, dest="head_opacity", help="The opacity of the head surface, in the range " "[0, 1].") parser.add_option("--high-res-head", action='store_true', default=False, dest="high_res_head", help="Use a high-resolution head surface.") parser.add_option("--low-res-head", action='store_true', default=False, dest="low_res_head", help="Use a low-resolution head surface.") parser.add_option('--trans', dest='trans', default=None, help='Head<->MRI transform FIF file ("-trans.fif")') parser.add_option('--verbose', action='store_true', dest='verbose', help='Turn on verbose mode.') options, args = parser.parse_args() if options.low_res_head: if options.high_res_head: raise ValueError("Can't specify --high-res-head and " "--low-res-head at the same time.") head_high_res = False elif options.high_res_head: head_high_res = True else: head_high_res = None with ETSContext(): mne.gui.coregistration(options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=options.subjects_dir, guess_mri_subject=options.guess_mri_subject, head_opacity=options.head_opacity, head_high_res=head_high_res, trans=options.trans, verbose=options.verbose) if is_main: sys.exit(0)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option('--input', dest='input_fname', help='Input data file name', metavar='filename') parser.add_option('--mrk', dest='mrk_fname', help='MEG Marker file name', metavar='filename') parser.add_option('--elp', dest='elp_fname', help='Headshape points file name', metavar='filename') parser.add_option('--hsp', dest='hsp_fname', help='Headshape file name', metavar='filename') parser.add_option('--stim', dest='stim', help='Colon Separated Stimulus Trigger Channels', metavar='chs') parser.add_option('--slope', dest='slope', help='Slope direction', metavar='slope') parser.add_option('--stimthresh', dest='stimthresh', default=1, help='Threshold value for trigger channels', metavar='value') parser.add_option('--output', dest='out_fname', help='Name of the resulting fiff file', metavar='filename') parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Set logging level for terminal output to debug') options, args = parser.parse_args() if options.debug: mne.set_log_level('debug') input_fname = options.input_fname if input_fname is None: with ETSContext(): mne.gui.kit2fiff() sys.exit(0) hsp_fname = options.hsp_fname elp_fname = options.elp_fname mrk_fname = options.mrk_fname stim = options.stim slope = options.slope stimthresh = options.stimthresh out_fname = options.out_fname if isinstance(stim, str): stim = map(int, stim.split(':')) raw = read_raw_kit(input_fname=input_fname, mrk=mrk_fname, elp=elp_fname, hsp=hsp_fname, stim=stim, slope=slope, stimthresh=stimthresh) raw.save(out_fname) raw.close() sys.exit(0)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=None) parser.add_option("-3", "--noflash30", dest="noflash30", action="store_true", default=False, help=("Skip the 30-degree flip angle data"),) parser.add_option("-n", "--noconvert", dest="noconvert", action="store_true", default=False, help=("Assume that the Flash MRI images have already " "been converted to mgz files")) parser.add_option("-u", "--unwarp", dest="unwarp", action="store_true", default=False, help=("Run grad_unwarp with -unwarp <type> option on " "each of the converted data sets")) parser.add_option("-o", "--overwrite", dest="overwrite", action="store_true", default=False, help="Write over existing .surf files in bem folder") parser.add_option("-v", "--view", dest="show", action="store_true", help="Show BEM model in 3D for visual inspection", default=False) parser.add_option("--copy", dest="copy", help="Use copies instead of symlinks for surfaces", action="store_true") parser.add_option("-p", "--flash-path", dest="flash_path", default=None, help="The directory containing flash05.mgz and " "flash30.mgz files (defaults to " "$SUBJECTS_DIR/$SUBJECT/mri/flash/parameter_maps") options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir flash30 = not options.noflash30 convert = not options.noconvert unwarp = options.unwarp overwrite = options.overwrite show = options.show flash_path = options.flash_path copy = options.copy if options.subject is None: parser.print_help() raise RuntimeError('The subject argument must be set') convert_flash_mris(subject=subject, subjects_dir=subjects_dir, flash30=flash30, convert=convert, unwarp=unwarp, verbose=True) make_flash_bem(subject=subject, subjects_dir=subjects_dir, overwrite=overwrite, show=show, flash_path=flash_path, copy=copy, verbose=True)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option('-p', '--pdf', dest='pdf_fname', help='Input data file name', metavar='FILE') parser.add_option('-c', '--config', dest='config_fname', help='Input config file name', metavar='FILE', default='config') parser.add_option('--head_shape', dest='head_shape_fname', help='Headshape file name', metavar='FILE', default='hs_file') parser.add_option('-o', '--out_fname', dest='out_fname', help='Name of the resulting fiff file', default='as_data_fname') parser.add_option('-r', '--rotation_x', dest='rotation_x', type='float', help='Compensatory rotation about Neuromag x axis, deg', default=2.0) parser.add_option('-T', '--translation', dest='translation', type='str', help='Default translation, meter', default=(0.00, 0.02, 0.11)) parser.add_option('--ecg_ch', dest='ecg_ch', type='str', help='4D ECG channel name', default='E31') parser.add_option('--eog_ch', dest='eog_ch', type='str', help='4D EOG channel names', default='E63,E64') options, args = parser.parse_args() pdf_fname = options.pdf_fname if pdf_fname is None: parser.print_help() sys.exit(1) config_fname = options.config_fname head_shape_fname = options.head_shape_fname out_fname = options.out_fname rotation_x = options.rotation_x translation = options.translation ecg_ch = options.ecg_ch eog_ch = options.ecg_ch.split(',') if out_fname == 'as_data_fname': out_fname = pdf_fname + '_raw.fif' raw = read_raw_bti(pdf_fname=pdf_fname, config_fname=config_fname, head_shape_fname=head_shape_fname, rotation_x=rotation_x, translation=translation, ecg_ch=ecg_ch, eog_ch=eog_ch) raw.save(out_fname) raw.close() if is_main: sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) options, args = parser.parse_args() os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.coregistration() if is_main: sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option('--input', dest='input_fname', help='Input data file name', metavar='filename') parser.add_option('--mrk', dest='mrk_fname', help='MEG Marker file name', metavar='filename') parser.add_option('--elp', dest='elp_fname', help='Headshape points file name', metavar='filename') parser.add_option('--hsp', dest='hsp_fname', help='Headshape file name', metavar='filename') parser.add_option('--stim', dest='stim', help='Colon Separated Stimulus Trigger Channels', metavar='chs') parser.add_option('--slope', dest='slope', help='Slope direction', metavar='slope') parser.add_option('--stimthresh', dest='stimthresh', default=1, help='Threshold value for trigger channels', metavar='value') parser.add_option('--output', dest='out_fname', help='Name of the resulting fiff file', metavar='filename') options, args = parser.parse_args() input_fname = options.input_fname if input_fname is None: os.environ['ETS_TOOLKIT'] = 'qt4' mne.gui.kit2fiff() sys.exit(0) hsp_fname = options.hsp_fname elp_fname = options.elp_fname mrk_fname = options.mrk_fname stim = options.stim slope = options.slope stimthresh = options.stimthresh out_fname = options.out_fname if isinstance(stim, str): stim = stim.split(':') raw = read_raw_kit(input_fname=input_fname, mrk=mrk_fname, elp=elp_fname, hsp=hsp_fname, stim=stim, slope=slope, stimthresh=stimthresh) raw.save(out_fname) raw.close() sys.exit(0)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--subject", dest="subject", help="Subject name (required)", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=None) parser.add_option("-o", "--overwrite", dest="overwrite", help="Write over existing files", action="store_true") parser.add_option("-v", "--volume", dest="volume", help="Defaults to T1", default='T1') parser.add_option("-a", "--atlas", dest="atlas", help="Specify the --atlas option for mri_watershed", default=False, action="store_true") parser.add_option("-g", "--gcaatlas", dest="gcaatlas", help="Use the subcortical atlas", default=False, action="store_true") parser.add_option("-p", "--preflood", dest="preflood", help="Change the preflood height", default=None) parser.add_option("--copy", dest="copy", help="Use copies instead of symlinks for surfaces", action="store_true") parser.add_option("--verbose", dest="verbose", help="If not None, override default verbose level", default=None) options, args = parser.parse_args() if options.subject is None: parser.print_help() sys.exit(1) subject = options.subject subjects_dir = options.subjects_dir overwrite = options.overwrite volume = options.volume atlas = options.atlas gcaatlas = options.gcaatlas preflood = options.preflood copy = options.copy verbose = options.verbose make_watershed_bem(subject=subject, subjects_dir=subjects_dir, overwrite=overwrite, volume=volume, atlas=atlas, gcaatlas=gcaatlas, preflood=preflood, copy=copy, verbose=verbose)
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', help='Overwrite previously computed surface') parser.add_option('-s', '--subject', dest='subject', help='The name of the subject', type='str') parser.add_option('-f', '--force', dest='force', action='store_true', help='Force creation of the surface even if it has ' 'some topological defects.') parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-n", "--no-decimate", dest="no_decimate", help="Disable medium and sparse decimations " "(dense only)", action='store_true') _add_verbose_flag(parser) options, args = parser.parse_args() subject = vars(options).get('subject', os.getenv('SUBJECT')) subjects_dir = options.subjects_dir if subject is None or subjects_dir is None: parser.print_help() sys.exit(1) make_scalp_surfaces(subject=subject, subjects_dir=subjects_dir, force=options.force, overwrite=options.overwrite, no_decimate=options.no_decimate, verbose=options.verbose)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', help='Overwrite previously computed surface') parser.add_option('-s', '--subject', dest='subject', help='The name of the subject', type='str') parser.add_option('-f', '--force', dest='force', action='store_true', help='Force transformation of surface into bem.') parser.add_option('-v', '--verbose', dest='verbose', action='store_true', help='Print the debug messages.') parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-n", "--no-decimate", dest="no_decimate", help="Disable medium and sparse decimations " "(dense only)", action='store_true') options, args = parser.parse_args() subject = vars(options).get('subject', os.getenv('SUBJECT')) subjects_dir = options.subjects_dir if subject is None or subjects_dir is None: parser.print_help() sys.exit(1) print(options.no_decimate) _run(subjects_dir, subject, options.force, options.overwrite, options.no_decimate, options.verbose)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("--input", dest="input_fname", help="Input data file name", metavar="filename") parser.add_option("--mrk", dest="mrk_fname", help="MEG Marker file name", metavar="filename") parser.add_option("--elp", dest="elp_fname", help="Headshape points file name", metavar="filename") parser.add_option("--hsp", dest="hsp_fname", help="Headshape file name", metavar="filename") parser.add_option("--stim", dest="stim", help="Colon Separated Stimulus Trigger Channels", metavar="chs") parser.add_option("--slope", dest="slope", help="Slope direction", metavar="slope") parser.add_option( "--stimthresh", dest="stimthresh", default=1, help="Threshold value for trigger channels", metavar="value" ) parser.add_option("--output", dest="out_fname", help="Name of the resulting fiff file", metavar="filename") options, args = parser.parse_args() input_fname = options.input_fname if input_fname is None: os.environ["ETS_TOOLKIT"] = "qt4" mne.gui.kit2fiff() sys.exit(0) hsp_fname = options.hsp_fname elp_fname = options.elp_fname mrk_fname = options.mrk_fname stim = options.stim slope = options.slope stimthresh = options.stimthresh out_fname = options.out_fname if isinstance(stim, str): stim = map(int, stim.split(":")) raw = read_raw_kit( input_fname=input_fname, mrk=mrk_fname, elp=elp_fname, hsp=hsp_fname, stim=stim, slope=slope, stimthresh=stimthresh, ) raw.save(out_fname) raw.close() sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-p", "--path", dest="path", help="Path to folder who MNE-Report must be created") parser.add_option("-i", "--info", dest="info_fname", help="File from which info dictionary is to be read", metavar="FILE") parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="The subjects directory") parser.add_option("-s", "--subject", dest="subject", help="The subject name") parser.add_option("-v", "--verbose", dest="verbose", action='store_true', help="run in verbose mode") parser.add_option("--no-browser", dest="no_browser", action='store_false', help="Do not open MNE-Report in browser") parser.add_option("--overwrite", dest="overwrite", action='store_false', help="Overwrite html report if it already exists") parser.add_option("-j", "--jobs", dest="n_jobs", help="Number of jobs to" " run in parallel") parser.add_option("-m", "--mri-decim", type="int", dest="mri_decim", default=2, help="Integer factor used to decimate " "BEM plots") options, args = parser.parse_args() path = options.path if path is None: parser.print_help() sys.exit(1) info_fname = options.info_fname subjects_dir = options.subjects_dir subject = options.subject mri_decim = int(options.mri_decim) verbose = True if options.verbose is not None else False open_browser = False if options.no_browser is not None else True overwrite = True if options.overwrite is not None else False n_jobs = int(options.n_jobs) if options.n_jobs is not None else 1 t0 = time.time() report = Report(info_fname, subjects_dir=subjects_dir, subject=subject, verbose=verbose) report.parse_folder(path, verbose=verbose, n_jobs=n_jobs, mri_decim=mri_decim) log_elapsed(time.time() - t0, verbose=verbose) report.save(open_browser=open_browser, overwrite=overwrite)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=None) parser.add_option("-3", "--noflash30", dest="noflash30", action="store_true", default=False, help=("Skip the 30-degree flip angle data"),) parser.add_option("-n", "--noconvert", dest="noconvert", action="store_true", default=False, help=("Assume that the Flash MRI images have already " "been converted to mgz files")) parser.add_option("-u", "--unwarp", dest="unwarp", action="store_true", default=False, help=("Run grad_unwarp with -unwarp <type> option on " "each of the converted data sets")) parser.add_option("-o", "--overwrite", dest="overwrite", action="store_true", default=False, help="Write over existing .surf files in bem folder") parser.add_option("-v", "--view", dest="show", action="store_true", help="Show BEM model in 3D for visual inspection", default=False) options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir flash30 = not options.noflash30 convert = not options.noconvert unwarp = options.unwarp overwrite = options.overwrite show = options.show if options.subject is None: parser.print_help() raise RuntimeError('The subject argument must be set') convert_flash_mris(subject=subject, subjects_dir=subjects_dir, flash30=flash30, convert=convert, unwarp=unwarp) make_flash_bem(subject=subject, subjects_dir=subjects_dir, overwrite=overwrite, show=show, flash_path='.')
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=None) parser.add_option("-3", "--noflash30", dest="noflash30", action="store_true", default=False, help=("Skip the 30-degree flip angle data"),) parser.add_option("-n", "--noconvert", dest="noconvert", action="store_true", default=False, help=("Assume that the Flash MRI images have already " "been converted to mgz files")) parser.add_option("-u", "--unwarp", dest="unwarp", action="store_true", default=False, help=("Run grad_unwarp with -unwarp <type> option on " "each of the converted data sets")) parser.add_option("-o", "--overwrite", dest="overwrite", action="store_true", default=False, help="Write over existing .surf files in bem folder") parser.add_option("-v", "--view", dest="show", action="store_true", help="Show BEM model in 3D for visual inspection", default=False) options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir flash30 = not options.noflash30 convert = not options.noconvert unwarp = options.unwarp overwrite = options.overwrite show = options.show if options.subject is None: parser.print_help() raise RuntimeError('The subject argument must be set') convert_flash_mris(subject=subject, subjects_dir=subjects_dir, flash30=flash30, convert=convert, unwarp=unwarp) make_flash_bem(subject=subject, subjects_dir=subjects_dir, overwrite=overwrite, show=show)
def run(): """Run the calibration_to_bids command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage="usage: %prog options args", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--bids_root', dest='bids_root', help='The path of the folder containing the BIDS ' 'dataset') parser.add_option('--subject_id', dest='subject', help=('Subject name')) parser.add_option('--session_id', dest='session', help='Session name') parser.add_option('--file', dest='fname', help='The path of the crosstalk file') parser.add_option('--verbose', dest='verbose', action='store_true', help='Whether do generate additional diagnostic output') opt, args = parser.parse_args() if args: parser.print_help() parser.error(f'Please do not specify arguments without flags. ' f'Got: {args}.\n') if opt.bids_root is None: parser.print_help() parser.error('You must specify bids_root') if opt.subject is None: parser.print_help() parser.error('You must specify a subject') bids_path = BIDSPath(subject=opt.subject, session=opt.session, root=opt.bids_root) logger.info(f'Writing fine-calibration file {bids_path.basename} …') write_meg_calibration(calibration=opt.fname, bids_path=bids_path, verbose=opt.verbose)
def run(): """Run the raw_to_bids command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage="usage: %prog options args", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS compatible folder.') parser.add_option('--datatype', dest='datatype', default='auto', help='The datatype to consider.') parser.add_option('--describe', dest='describe', action="store_true", help=('If set print the descriptive statistics ' '(min, max, etc.).')) opt, args = parser.parse_args() if len(args) > 0: parser.print_help() parser.error( 'Do not specify arguments without flags. Found: "{}".\n'.format( args)) if not all([opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to specify the ' '--bids_root parameter.') counts = count_events(opt.bids_root, datatype=opt.datatype) if opt.describe: counts = counts.describe() print(counts)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") parser.add_option("--no-guess-mri", dest="guess_mri_subject", action='store_false', default=True, help="Prevent the GUI from automatically guessing and " "changing the MRI subject when a new head shape source " "file is selected.") parser.add_option("--head-opacity", type=float, default=1., dest="head_opacity", help="The opacity of the head surface, in the range " "[0, 1].") parser.add_option("--low-res-head", action='store_true', default=False, dest="low_res_head", help="Default to using a low-resolution head surface.") parser.add_option('--verbose', action='store_true', dest='verbose', help='Turn on verbose mode.') options, args = parser.parse_args() with ETSContext(): mne.gui.coregistration(options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=options.subjects_dir, guess_mri_subject=options.guess_mri_subject, head_opacity=options.head_opacity, head_high_res=not options.low_res_head, verbose=options.verbose) if is_main: sys.exit(0)
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) parser.add_option('--bem', dest='bem_fname', help='The name of the file containing the ' 'triangulations of the BEM surfaces and the ' 'conductivities of the compartments. The standard ' 'ending for this file is -bem.fif.', metavar="FILE") parser.add_option('--sol', dest='bem_sol_fname', help='The name of the resulting file containing BEM ' 'solution (geometry matrix). It uses the linear ' 'collocation approach. The file should end with ' '-bem-sof.fif.', metavar='FILE', default=None) _add_verbose_flag(parser) options, args = parser.parse_args() bem_fname = options.bem_fname bem_sol_fname = options.bem_sol_fname verbose = True if options.verbose is not None else False if bem_fname is None: parser.print_help() sys.exit(1) if bem_sol_fname is None: base, _ = os.path.splitext(bem_fname) bem_sol_fname = base + '-sol.fif' bem_model = mne.read_bem_surfaces(bem_fname, patch_stats=False, verbose=verbose) bem_solution = mne.make_bem_solution(bem_model, verbose=verbose) mne.write_bem_solution(bem_sol_fname, bem_solution)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") options, args = parser.parse_args() with ETSContext(): mne.gui.coregistration(options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=options.subjects_dir) if is_main: sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--surf", dest="surf", help="Surface in Freesurfer format", metavar="FILE") parser.add_option("-f", "--fif", dest="fif", help="FIF file produced", metavar="FILE") parser.add_option("-i", "--id", dest="id", default=4, help=("Surface Id (e.g. 4 sur head surface)")) options, args = parser.parse_args() if options.surf is None: parser.print_help() sys.exit(1) print("Converting %s to BEM FIF file." % options.surf) points, tris = mne.read_surface(options.surf) points *= 1e-3 surf = dict(coord_frame=5, id=int(options.id), nn=None, np=len(points), ntri=len(tris), rr=points, sigma=1, tris=tris) mne.write_bem_surface(options.fif, surf)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) subject = os.environ.get('SUBJECT') subjects_dir = get_subjects_dir() parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=subject) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-m", "--method", dest="method", help=("Method used to generate the BEM model. " "Can be flash or watershed."), metavar="FILE") options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir method = options.method freeview_bem_surfaces(subject, subjects_dir, method)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-s", "--surf", dest="surf", help="Surface in Freesurfer format", metavar="FILE") parser.add_option("-f", "--fif", dest="fif", help="FIF file produced", metavar="FILE") parser.add_option("-i", "--id", dest="id", default=4, help=("Surface Id (e.g. 4 sur head surface)")) options, args = parser.parse_args() if options.surf is None: parser.print_help() sys.exit(1) print("Converting %s to BEM FIF file." % options.surf) surf = mne.bem._surfaces_to_bem([options.surf], [int(options.id)], sigmas=[1]) mne.write_bem_surfaces(options.fif, surf)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) subject = os.environ.get('SUBJECT') subjects_dir = get_subjects_dir() parser.add_option("-s", "--subject", dest="subject", help="Subject name", default=subject) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=subjects_dir) parser.add_option("-m", "--method", dest="method", help=("Method used to generate the BEM model. " "Can be flash or watershed.")) options, args = parser.parse_args() subject = options.subject subjects_dir = options.subjects_dir method = options.method freeview_bem_surfaces(subject, subjects_dir, method)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") options, args = parser.parse_args() with ETSContext(): mne.gui.coregistration(options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=options.subjects_dir) if is_main: sys.exit(0)
def run(): """Run the raw_to_bids command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage="usage: %prog options args", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('subject name in BIDS compatible format ' '(01, 02, etc.)')) parser.add_option('--task', dest='task', help='name of the task the data is based on') parser.add_option('--raw', dest='raw_fname', help='path to the raw MEG file') parser.add_option('--bids_root', dest='bids_root', help='The path of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='session name in BIDS compatible format') parser.add_option('--run', dest='run', help='run number for this dataset') parser.add_option('--acq', dest='acq', help='acquisition parameter for this dataset') parser.add_option('--events_data', dest='events_data', help='events file (events.tsv)') parser.add_option('--event_id', dest='event_id', help='event id dict', metavar='eid') parser.add_option('--hpi', dest='hpi', help='path to the MEG marker points') parser.add_option('--electrode', dest='electrode', help='path to head-native digitizer points') parser.add_option('--hsp', dest='hsp', help='path to headshape points') parser.add_option('--config', dest='config', help='path to the configuration file') parser.add_option('--overwrite', dest='overwrite', help="whether to overwrite existing data (BOOLEAN)") parser.add_option('--line_freq', dest='line_freq', help="The frequency of the line noise in Hz " "(e.g. 50 or 60). If unknown, pass None") opt, args = parser.parse_args() if len(args) > 0: parser.print_help() parser.error( 'Do not specify arguments without flags. Found: "{}".\n'.format( args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.bids_root]): parser.print_help() parser.error('Arguments missing. You need to specify at least the' 'following: --subject_id, --task, --raw, --bids_root.') bids_path = BIDSPath(subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task, root=opt.bids_root) allow_maxshield = False if opt.raw_fname.endswith('.fif'): allow_maxshield = True raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=allow_maxshield) if opt.line_freq is not None: line_freq = None if opt.line_freq == "None" else opt.line_freq raw.info['line_freq'] = line_freq write_raw_bids(raw, bids_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True)
def run(): import matplotlib.pyplot as plt from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default='') parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default='') parser.add_option("-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0) parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0) parser.add_option("-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20) parser.add_option("-o", "--order", dest="order", help="Order for plotting ('type' or 'original')", default='type') parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False) parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False) parser.add_option("--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true") parser.add_option("--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", default=-1) parser.add_option("--lowpass", dest="lowpass", type="float", help="Display low-pass filter corner frequency", default=-1) parser.add_option("--filtorder", dest="filtorder", type="int", help="Display filtering IIR order", default=4) parser.add_option("--clipping", dest="clipping", help="Enable trace clipping mode, either 'clip' or " "'transparent'", default=None) options, args = parser.parse_args() raw_in = options.raw_in duration = options.duration start = options.start n_channels = options.n_channels order = options.order preload = options.preload show_options = options.show_options proj_in = options.proj_in eve_in = options.eve_in maxshield = options.maxshield highpass = options.highpass lowpass = options.lowpass filtorder = options.filtorder clipping = options.clipping if raw_in is None: parser.print_help() sys.exit(1) raw = mne.io.Raw(raw_in, preload=preload, allow_maxshield=maxshield) if len(proj_in) > 0: projs = mne.read_proj(proj_in) raw.info['projs'] = projs if len(eve_in) > 0: events = mne.read_events(eve_in) else: events = None highpass = None if highpass < 0 or filtorder <= 0 else highpass lowpass = None if lowpass < 0 or filtorder <= 0 else lowpass filtorder = 4 if filtorder <= 0 else filtorder raw.plot(duration=duration, start=start, n_channels=n_channels, order=order, show_options=show_options, events=events, highpass=highpass, lowpass=lowpass, filtorder=filtorder, clipping=clipping) plt.show(block=True)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option('--input', dest='input_fname', help='Input data file name', metavar='filename') parser.add_option('--mrk', dest='mrk_fname', help='MEG Marker file name', metavar='filename') parser.add_option('--elp', dest='elp_fname', help='Headshape points file name', metavar='filename') parser.add_option('--hsp', dest='hsp_fname', help='Headshape file name', metavar='filename') parser.add_option('--stim', dest='stim', help='Colon Separated Stimulus Trigger Channels', metavar='chs') parser.add_option('--slope', dest='slope', help='Slope direction', metavar='slope') parser.add_option('--stimthresh', dest='stimthresh', default=1, help='Threshold value for trigger channels', metavar='value') parser.add_option('--output', dest='out_fname', help='Name of the resulting fiff file', metavar='filename') options, args = parser.parse_args() input_fname = options.input_fname if input_fname is None: with ETSContext(): mne.gui.kit2fiff() sys.exit(0) hsp_fname = options.hsp_fname elp_fname = options.elp_fname mrk_fname = options.mrk_fname stim = options.stim slope = options.slope stimthresh = options.stimthresh out_fname = options.out_fname if isinstance(stim, str): stim = map(int, stim.split(':')) raw = read_raw_kit(input_fname=input_fname, mrk=mrk_fname, elp=elp_fname, hsp=hsp_fname, stim=stim, slope=slope, stimthresh=stimthresh) raw.save(out_fname) raw.close() sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-p", "--path", dest="path", help="Path to folder who MNE-Report must be created") parser.add_option("-i", "--info", dest="info_fname", help="File from which info dictionary is to be read", metavar="FILE") parser.add_option("-c", "--cov", dest="cov_fname", help="File from which noise covariance is to be read", metavar="FILE") parser.add_option("--bmin", dest="bmin", help="Time at which baseline correction starts for " "evokeds", default=None) parser.add_option("--bmax", dest="bmax", help="Time at which baseline correction stops for " "evokeds", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="The subjects directory") parser.add_option("-s", "--subject", dest="subject", help="The subject name") parser.add_option("-v", "--verbose", dest="verbose", action='store_true', help="run in verbose mode") parser.add_option("--no-browser", dest="no_browser", action='store_false', help="Do not open MNE-Report in browser") parser.add_option("--overwrite", dest="overwrite", action='store_false', help="Overwrite html report if it already exists") parser.add_option("-j", "--jobs", dest="n_jobs", help="Number of jobs to" " run in parallel") parser.add_option("-m", "--mri-decim", type="int", dest="mri_decim", default=2, help="Integer factor used to decimate " "BEM plots") options, args = parser.parse_args() path = options.path if path is None: parser.print_help() sys.exit(1) info_fname = options.info_fname cov_fname = options.cov_fname subjects_dir = options.subjects_dir subject = options.subject mri_decim = int(options.mri_decim) verbose = True if options.verbose is not None else False open_browser = False if options.no_browser is not None else True overwrite = True if options.overwrite is not None else False n_jobs = int(options.n_jobs) if options.n_jobs is not None else 1 bmin = float(options.bmin) if options.bmin is not None else None bmax = float(options.bmax) if options.bmax is not None else None # XXX: this means (None, None) cannot be specified through command line if bmin is None and bmax is None: baseline = None else: baseline = (bmin, bmax) t0 = time.time() report = Report(info_fname, subjects_dir=subjects_dir, subject=subject, baseline=baseline, cov_fname=cov_fname, verbose=verbose) report.parse_folder(path, verbose=verbose, n_jobs=n_jobs, mri_decim=mri_decim) log_elapsed(time.time() - t0, verbose=verbose) report.save(open_browser=open_browser, overwrite=overwrite)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--tmin", dest="tmin", type="float", help="Time before event in seconds", default=-0.2) parser.add_option("--tmax", dest="tmax", type="float", help="Time after event in seconds", default=0.2) parser.add_option("-g", "--n-grad", dest="n_grad", type="int", help="Number of SSP vectors for gradiometers", default=2) parser.add_option("-m", "--n-mag", dest="n_mag", type="int", help="Number of SSP vectors for magnetometers", default=2) parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int", help="Number of SSP vectors for EEG", default=2) parser.add_option("--l-freq", dest="l_freq", type="float", help="Filter low cut-off frequency in Hz", default=1) parser.add_option("--h-freq", dest="h_freq", type="float", help="Filter high cut-off frequency in Hz", default=35) parser.add_option("--eog-l-freq", dest="eog_l_freq", type="float", help="Filter low cut-off frequency in Hz used for " "EOG event detection", default=1) parser.add_option("--eog-h-freq", dest="eog_h_freq", type="float", help="Filter high cut-off frequency in Hz used for " "EOG event detection", default=10) parser.add_option("-p", "--preload", dest="preload", help="Temporary file used during computation (to " "save memory)", default=True) parser.add_option("-a", "--average", dest="average", action="store_true", help="Compute SSP after averaging", default=False) # XXX: change to default=True in 0.17 parser.add_option("--proj", dest="proj", help="Use SSP projections from a fif file.", default=None) parser.add_option("--filtersize", dest="filter_length", type="int", help="Number of taps to use for filtering", default=2048) parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int", help="Number of jobs to run in parallel", default=1) parser.add_option("--rej-grad", dest="rej_grad", type="float", help="Gradiometers rejection parameter in fT/cm (peak " "to peak amplitude)", default=2000) parser.add_option("--rej-mag", dest="rej_mag", type="float", help="Magnetometers rejection parameter in fT (peak to " "peak amplitude)", default=3000) parser.add_option("--rej-eeg", dest="rej_eeg", type="float", help="EEG rejection parameter in uV (peak to peak " "amplitude)", default=50) parser.add_option("--rej-eog", dest="rej_eog", type="float", help="EOG rejection parameter in uV (peak to peak " "amplitude)", default=1e9) parser.add_option("--avg-ref", dest="avg_ref", action="store_true", help="Add EEG average reference proj", default=False) parser.add_option("--no-proj", dest="no_proj", action="store_true", help="Exclude the SSP projectors currently in the " "fiff file", default=False) parser.add_option("--bad", dest="bad_fname", help="Text file containing bad channels list " "(one per line)", default=None) parser.add_option("--event-id", dest="event_id", type="int", help="ID to use for events", default=998) parser.add_option("--event-raw", dest="raw_event_fname", help="raw file to use for event detection", default=None) parser.add_option("--tstart", dest="tstart", type="float", help="Start artifact detection after tstart seconds", default=0.) parser.add_option("-c", "--channel", dest="ch_name", type="string", help="Custom EOG channel(s), comma separated", default=None) options, args = parser.parse_args() raw_in = options.raw_in if raw_in is None: parser.print_help() sys.exit(1) tmin = options.tmin tmax = options.tmax n_grad = options.n_grad n_mag = options.n_mag n_eeg = options.n_eeg l_freq = options.l_freq h_freq = options.h_freq eog_l_freq = options.eog_l_freq eog_h_freq = options.eog_h_freq average = options.average preload = options.preload filter_length = options.filter_length n_jobs = options.n_jobs reject = dict(grad=1e-13 * float(options.rej_grad), mag=1e-15 * float(options.rej_mag), eeg=1e-6 * float(options.rej_eeg), eog=1e-6 * float(options.rej_eog)) avg_ref = options.avg_ref no_proj = options.no_proj bad_fname = options.bad_fname event_id = options.event_id proj_fname = options.proj raw_event_fname = options.raw_event_fname tstart = options.tstart ch_name = options.ch_name if bad_fname is not None: with open(bad_fname, 'r') as fid: bads = [w.rstrip() for w in fid.readlines()] print('Bad channels read : %s' % bads) else: bads = [] if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'): prefix = raw_in[:-8] else: prefix = raw_in[:-4] eog_event_fname = prefix + '_eog-eve.fif' if average: eog_proj_fname = prefix + '_eog_avg-proj.fif' else: eog_proj_fname = prefix + '_eog-proj.fif' raw = mne.io.read_raw_fif(raw_in, preload=preload) if raw_event_fname is not None: raw_event = mne.io.read_raw_fif(raw_event_fname) else: raw_event = raw flat = None # XXX : not exposed to the user projs, events = mne.preprocessing.compute_proj_eog( raw=raw, raw_event=raw_event, tmin=tmin, tmax=tmax, n_grad=n_grad, n_mag=n_mag, n_eeg=n_eeg, l_freq=l_freq, h_freq=h_freq, average=average, filter_length=filter_length, n_jobs=n_jobs, reject=reject, flat=flat, bads=bads, avg_ref=avg_ref, no_proj=no_proj, event_id=event_id, eog_l_freq=eog_l_freq, eog_h_freq=eog_h_freq, tstart=tstart, ch_name=ch_name, copy=False) raw.close() if raw_event_fname is not None: raw_event.close() if proj_fname is not None: print('Including SSP projections from : %s' % proj_fname) # append the eog projs, so they are last in the list projs = mne.read_proj(proj_fname) + projs if isinstance(preload, string_types) and os.path.exists(preload): os.remove(preload) print("Writing EOG projections in %s" % eog_proj_fname) mne.write_proj(eog_proj_fname, projs) print("Writing EOG events in %s" % eog_event_fname) mne.write_events(eog_event_fname, events)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--tmin", dest="tmin", type="float", help="Time before event in seconds", default=-0.2) parser.add_option("--tmax", dest="tmax", type="float", help="Time after event in seconds", default=0.4) parser.add_option("-g", "--n-grad", dest="n_grad", type="int", help="Number of SSP vectors for gradiometers", default=2) parser.add_option("-m", "--n-mag", dest="n_mag", type="int", help="Number of SSP vectors for magnetometers", default=2) parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int", help="Number of SSP vectors for EEG", default=2) parser.add_option("--l-freq", dest="l_freq", type="float", help="Filter low cut-off frequency in Hz", default=1) parser.add_option("--h-freq", dest="h_freq", type="float", help="Filter high cut-off frequency in Hz", default=100) parser.add_option("--ecg-l-freq", dest="ecg_l_freq", type="float", help="Filter low cut-off frequency in Hz used " "for ECG event detection", default=5) parser.add_option("--ecg-h-freq", dest="ecg_h_freq", type="float", help="Filter high cut-off frequency in Hz used " "for ECG event detection", default=35) parser.add_option("-p", "--preload", dest="preload", help="Temporary file used during computation " "(to save memory)", default=True) parser.add_option("-a", "--average", dest="average", action="store_true", help="Compute SSP after averaging", default=False) parser.add_option("--proj", dest="proj", help="Use SSP projections from a fif file.", default=None) parser.add_option("--filtersize", dest="filter_length", type="int", help="Number of taps to use for filtering", default=2048) parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int", help="Number of jobs to run in parallel", default=1) parser.add_option("-c", "--channel", dest="ch_name", help="Channel to use for ECG detection " "(Required if no ECG found)", default=None) parser.add_option("--rej-grad", dest="rej_grad", type="float", help="Gradiometers rejection parameter " "in fT/cm (peak to peak amplitude)", default=2000) parser.add_option("--rej-mag", dest="rej_mag", type="float", help="Magnetometers rejection parameter " "in fT (peak to peak amplitude)", default=3000) parser.add_option("--rej-eeg", dest="rej_eeg", type="float", help="EEG rejection parameter in uV " "(peak to peak amplitude)", default=50) parser.add_option("--rej-eog", dest="rej_eog", type="float", help="EOG rejection parameter in uV " "(peak to peak amplitude)", default=250) parser.add_option("--avg-ref", dest="avg_ref", action="store_true", help="Add EEG average reference proj", default=False) parser.add_option("--no-proj", dest="no_proj", action="store_true", help="Exclude the SSP projectors currently " "in the fiff file", default=False) parser.add_option("--bad", dest="bad_fname", help="Text file containing bad channels list " "(one per line)", default=None) parser.add_option("--event-id", dest="event_id", type="int", help="ID to use for events", default=999) parser.add_option("--event-raw", dest="raw_event_fname", help="raw file to use for event detection", default=None) parser.add_option("--tstart", dest="tstart", type="float", help="Start artifact detection after tstart seconds", default=0.) parser.add_option("--qrsthr", dest="qrs_threshold", type="string", help="QRS detection threshold. Between 0 and 1. Can " "also be 'auto' for automatic selection", default='auto') options, args = parser.parse_args() raw_in = options.raw_in if raw_in is None: parser.print_help() sys.exit(1) tmin = options.tmin tmax = options.tmax n_grad = options.n_grad n_mag = options.n_mag n_eeg = options.n_eeg l_freq = options.l_freq h_freq = options.h_freq ecg_l_freq = options.ecg_l_freq ecg_h_freq = options.ecg_h_freq average = options.average preload = options.preload filter_length = options.filter_length n_jobs = options.n_jobs ch_name = options.ch_name reject = dict(grad=1e-13 * float(options.rej_grad), mag=1e-15 * float(options.rej_mag), eeg=1e-6 * float(options.rej_eeg), eog=1e-6 * float(options.rej_eog)) avg_ref = options.avg_ref no_proj = options.no_proj bad_fname = options.bad_fname event_id = options.event_id proj_fname = options.proj raw_event_fname = options.raw_event_fname tstart = options.tstart qrs_threshold = options.qrs_threshold if qrs_threshold != 'auto': try: qrs_threshold = float(qrs_threshold) except ValueError: raise ValueError('qrsthr must be "auto" or a float') if bad_fname is not None: with open(bad_fname, 'r') as fid: bads = [w.rstrip() for w in fid.readlines()] print('Bad channels read : %s' % bads) else: bads = [] if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'): prefix = raw_in[:-8] else: prefix = raw_in[:-4] ecg_event_fname = prefix + '_ecg-eve.fif' if average: ecg_proj_fname = prefix + '_ecg_avg-proj.fif' else: ecg_proj_fname = prefix + '_ecg-proj.fif' raw = mne.io.read_raw_fif(raw_in, preload=preload) if raw_event_fname is not None: raw_event = mne.io.read_raw_fif(raw_event_fname) else: raw_event = raw flat = None # XXX : not exposed to the user cpe = mne.preprocessing.compute_proj_ecg projs, events = cpe(raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg, l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, flat, bads, avg_ref, no_proj, event_id, ecg_l_freq, ecg_h_freq, tstart, qrs_threshold, copy=False) raw.close() if raw_event_fname is not None: raw_event.close() if proj_fname is not None: print('Including SSP projections from : %s' % proj_fname) # append the ecg projs, so they are last in the list projs = mne.read_proj(proj_fname) + projs if isinstance(preload, string_types) and os.path.exists(preload): os.remove(preload) print("Writing ECG projections in %s" % ecg_proj_fname) mne.write_proj(ecg_proj_fname, projs) print("Writing ECG events in %s" % ecg_event_fname) mne.write_events(ecg_event_fname, events)
dspath = op.join(data_dir, dsname) # install the dataset print('datalad installing "{}"'.format(dsname)) dataset = dl.install(path=dspath, source=url) # XXX: git-annex bug: https://github.com/datalad/datalad/issues/3583 # if datalad fails, use "get" twice, or set `n_jobs=1` if dsname == 'ds003104': n_jobs = 16 else: n_jobs = 1 # get the first subject for to_get in get_dict[dsname]: print('datalad get data "{}" for "{}"'.format(to_get, dsname)) dataset.get(to_get, jobs=n_jobs) if __name__ == '__main__': parser = get_optparser(__file__, usage="usage: %prog -dataset DATASET") parser.add_option('-d', '--dataset', dest='dataset', help='Name of the dataset', metavar='INPUT', default=None) opt, args = parser.parse_args() dataset = opt.dataset if opt.dataset != '' else None main(dataset)
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") parser.add_option("--no-guess-mri", dest="guess_mri_subject", action='store_false', default=None, help="Prevent the GUI from automatically guessing and " "changing the MRI subject when a new head shape source " "file is selected.") parser.add_option("--head-opacity", type=float, default=None, dest="head_opacity", help="The opacity of the head surface, in the range " "[0, 1].") parser.add_option("--high-res-head", action='store_true', default=False, dest="high_res_head", help="Use a high-resolution head surface.") parser.add_option("--low-res-head", action='store_true', default=False, dest="low_res_head", help="Use a low-resolution head surface.") parser.add_option('--trans', dest='trans', default=None, help='Head<->MRI transform FIF file ("-trans.fif")') parser.add_option('--project-eeg', dest='project_eeg', action='store_true', default=None, help="Project EEG electrodes to the head surface (" "for visualization purposes only)") parser.add_option('--orient-to-surface', action='store_true', default=None, dest='orient_to_surface', help='Orient points to the surface.') parser.add_option('--scale-by-distance', action='store_true', default=None, dest='scale_by_distance', help='Scale points by distance from the surface.') parser.add_option('--mark-inside', action='store_true', default=None, dest='mark_inside', help='Mark points inside the head using a different ' 'color.') parser.add_option('--interaction', type=str, default=None, dest='interaction', help='Interaction style to use, can be "trackball" or ' '"terrain".') parser.add_option('--scale', type=float, default=None, dest='scale', help='Scale factor for the scene.') parser.add_option('--simple-rendering', action='store_false', dest='advanced_rendering', help='Use simplified OpenGL rendering') _add_verbose_flag(parser) options, args = parser.parse_args() if options.low_res_head: if options.high_res_head: raise ValueError("Can't specify --high-res-head and " "--low-res-head at the same time.") head_high_res = False elif options.high_res_head: head_high_res = True else: head_high_res = None # expanduser allows ~ for --subjects-dir subjects_dir = options.subjects_dir if subjects_dir is not None: subjects_dir = op.expanduser(subjects_dir) trans = options.trans if trans is not None: trans = op.expanduser(trans) import faulthandler faulthandler.enable() mne.gui.coregistration( options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=subjects_dir, guess_mri_subject=options.guess_mri_subject, head_opacity=options.head_opacity, head_high_res=head_high_res, trans=trans, scrollable=True, project_eeg=options.project_eeg, orient_to_surface=options.orient_to_surface, scale_by_distance=options.scale_by_distance, mark_inside=options.mark_inside, interaction=options.interaction, scale=options.scale, advanced_rendering=options.advanced_rendering, verbose=options.verbose)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-p", "--path", dest="path", help="Path to folder who MNE-Report must be created") parser.add_option("-i", "--info", dest="info_fname", help="File from which info dictionary is to be read", metavar="FILE") parser.add_option("-c", "--cov", dest="cov_fname", help="File from which noise covariance is to be read", metavar="FILE") parser.add_option("--bmin", dest="bmin", help="Time at which baseline correction starts for " "evokeds", default=None) parser.add_option("--bmax", dest="bmax", help="Time at which baseline correction stops for " "evokeds", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="The subjects directory") parser.add_option("-s", "--subject", dest="subject", help="The subject name") parser.add_option("-v", "--verbose", dest="verbose", action='store_true', help="run in verbose mode") parser.add_option("--no-browser", dest="no_browser", action='store_false', help="Do not open MNE-Report in browser") parser.add_option("--overwrite", dest="overwrite", action='store_false', help="Overwrite html report if it already exists") parser.add_option("-j", "--jobs", dest="n_jobs", help="Number of jobs to" " run in parallel") parser.add_option("-m", "--mri-decim", type="int", dest="mri_decim", default=2, help="Integer factor used to decimate " "BEM plots") options, args = parser.parse_args() path = options.path if path is None: parser.print_help() sys.exit(1) info_fname = options.info_fname cov_fname = options.cov_fname subjects_dir = options.subjects_dir subject = options.subject mri_decim = int(options.mri_decim) verbose = True if options.verbose is not None else False open_browser = False if options.no_browser is not None else True overwrite = True if options.overwrite is not None else False n_jobs = int(options.n_jobs) if options.n_jobs is not None else 1 bmin = float(options.bmin) if options.bmin is not None else None bmax = float(options.bmax) if options.bmax is not None else None # XXX: this means (None, None) cannot be specified through command line if bmin is None and bmax is None: baseline = None else: baseline = (bmin, bmax) t0 = time.time() report = Report(info_fname, subjects_dir=subjects_dir, subject=subject, baseline=baseline, cov_fname=cov_fname, verbose=verbose) report.parse_folder(path, verbose=verbose, n_jobs=n_jobs, mri_decim=mri_decim) log_elapsed(time.time() - t0, verbose=verbose) report.save(open_browser=open_browser, overwrite=overwrite)
def run(): """Run the raw_to_bids command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__, usage="usage: %prog options args", prog_prefix='mne_bids', version=mne_bids.__version__) parser.add_option('--subject_id', dest='subject_id', help=('The subject name in BIDS compatible format' '(01,02, etc.)')) parser.add_option('--task', dest='task', help='Name of the task the data is based on.') parser.add_option('--raw', dest='raw_fname', help='The path to the raw MEG file.') parser.add_option('--output_path', dest='output_path', help='The path of the BIDS compatible folder.') parser.add_option('--session_id', dest='session_id', help='The session name in BIDS compatible format.') parser.add_option('--run', dest='run', help='The run number for this dataset.') parser.add_option('--acq', dest='acq', help='The acquisition parameter.') parser.add_option('--events_data', dest='events_data', help='The events file.') parser.add_option('--event_id', dest='event_id', help='The event id dict.', metavar='eid') parser.add_option('--hpi', dest='hpi', help='The path to the MEG Marker points') parser.add_option('--electrode', dest='electrode', help='The path to head-native Digitizer points') parser.add_option('--hsp', dest='hsp', help='The path to headshape points.') parser.add_option('--config', dest='config', help='The path to the configuration file') parser.add_option('--overwrite', dest='overwrite', help="Boolean. Whether to overwrite existing data") parser.add_option('--allow_maxshield', dest='allow_maxshield', help="Boolean. Whether to allow non Maxfiltered data.", action='store_true') opt, args = parser.parse_args() if len(args) > 0: parser.print_help() parser.error( 'Do not specify arguments without flags. Found: "{}".\n'.format( args)) if not all([opt.subject_id, opt.task, opt.raw_fname, opt.output_path]): parser.print_help() parser.error('Arguments missing. You need to specify at least the' 'following: --subject_id, --task, --raw, --output_path.') bids_basename = make_bids_basename(subject=opt.subject_id, session=opt.session_id, run=opt.run, acquisition=opt.acq, task=opt.task) raw = _read_raw(opt.raw_fname, hpi=opt.hpi, electrode=opt.electrode, hsp=opt.hsp, config=opt.config, allow_maxshield=opt.allow_maxshield) write_raw_bids(raw, bids_basename, opt.output_path, event_id=opt.event_id, events_data=opt.events_data, overwrite=opt.overwrite, verbose=True)
def run(): t0 = time.time() parser = get_optparser(__file__) parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--pos", dest="pos", default=None, help="Position definition text file. Can be 'constant' " "to hold the head position fixed", metavar="FILE") parser.add_option("--dipoles", dest="dipoles", default=None, help="Dipole definition file", metavar="FILE") parser.add_option("--cov", dest="cov", help="Covariance to use for noise generation. Can be " "'simple' to use a diagonal covariance, or 'off' to " "omit noise", metavar="FILE", default='simple') parser.add_option("--duration", dest="duration", default=None, help="Duration of each epoch (sec). If omitted, the last" " time point in the dipole definition file plus 200 ms " "will be used", type="float") parser.add_option("-j", "--jobs", dest="n_jobs", help="Number of jobs to" " run in parallel", type="int", default=1) parser.add_option("--out", dest="raw_out", help="Output raw filename", metavar="FILE") parser.add_option("--plot-dipoles", dest="plot_dipoles", help="Plot " "input dipole positions", action="store_true") parser.add_option("--plot-raw", dest="plot_raw", help="Plot the resulting " "raw traces", action="store_true") parser.add_option("--plot-evoked", dest="plot_evoked", help="Plot evoked " "data", action="store_true") parser.add_option("-p", "--plot", dest="plot", help="Plot dipoles, raw, " "and evoked", action="store_true") parser.add_option("--overwrite", dest="overwrite", help="Overwrite the" "output file if it exists", action="store_true") options, args = parser.parse_args() raw_in = options.raw_in pos = options.pos raw_out = options.raw_out dipoles = options.dipoles n_jobs = options.n_jobs plot = options.plot plot_dipoles = options.plot_dipoles or plot plot_raw = options.plot_raw or plot plot_evoked = options.plot_evoked or plot overwrite = options.overwrite duration = options.duration cov = options.cov # check parameters if not (raw_out or plot_raw or plot_evoked): raise ValueError('data must either be saved (--out) or ' 'plotted (--plot-raw or --plot_evoked)') if raw_out and op.isfile(raw_out) and not overwrite: raise ValueError('output file exists, use --overwrite (%s)' % raw_out) if raw_in is None or pos is None or dipoles is None: parser.print_help() sys.exit(1) s = 'Simulate raw data with head movements' print('\n%s\n%s\n%s\n' % ('-' * len(s), s, '-' * len(s))) # setup the simulation with printer('Reading dipole definitions'): if not op.isfile(dipoles): raise IOError('dipole file not found:\n%s' % dipoles) dipoles = np.loadtxt(dipoles, skiprows=1, dtype=float) n_dipoles = dipoles.shape[0] if dipoles.shape[1] != 8: raise ValueError('dipoles must have 8 columns') rr = dipoles[:, :3] * 1e-3 nn = dipoles[:, 3:6] t = dipoles[:, 6:8] duration = t.max() + 0.2 if duration is None else duration if (t[:, 0] > t[:, 1]).any(): raise ValueError('found tmin > tmax in dipole file') if (t < 0).any(): raise ValueError('found t < 0 in dipole file') if (t > duration).any(): raise ValueError('found t > duration in dipole file') amp = np.sqrt(np.sum(nn * nn, axis=1)) * 1e-9 mne.surface._normalize_vectors(nn) nn[(nn == 0).all(axis=1)] = (1, 0, 0) src = mne.SourceSpaces([ dict(rr=rr, nn=nn, inuse=np.ones(n_dipoles, int), coord_frame=FIFF.FIFFV_COORD_HEAD) ]) for key in ['pinfo', 'nuse_tri', 'use_tris', 'patch_inds']: src[0][key] = None trans = { 'from': FIFF.FIFFV_COORD_HEAD, 'to': FIFF.FIFFV_COORD_MRI, 'trans': np.eye(4) } if (amp > 100e-9).any(): print('') warnings.warn('Largest dipole amplitude %0.1f > 100 nA' % (amp.max() * 1e9)) if pos == 'constant': print('Holding head position constant') pos = None else: with printer('Loading head positions'): pos = mne.get_chpi_positions(pos) with printer('Loading raw data file'): with warnings.catch_warnings(record=True): raw = mne.io.Raw(raw_in, preload=False, allow_maxshield=True, verbose=False) if cov == 'simple': print('Using diagonal covariance for brain noise') elif cov == 'off': print('Omitting brain noise in the simulation') cov = None else: with printer('Loading covariance file for brain noise'): cov = mne.read_cov(cov) with printer('Setting up spherical model'): bem = mne.bem.make_sphere_model('auto', 'auto', raw.info, verbose=False) # check that our sources are reasonable rad = bem['layers'][0]['rad'] r0 = bem['r0'] outside = np.sqrt(np.sum((rr - r0)**2, axis=1)) >= rad n_outside = outside.sum() if n_outside > 0: print('') raise ValueError( '%s dipole%s outside the spherical model, are your positions ' 'in mm?' % (n_outside, 's were' if n_outside != 1 else ' was')) with printer('Constructing source estimate'): tmids = t.mean(axis=1) t = np.round(t * raw.info['sfreq']).astype(int) t[:, 1] += 1 # make it inclusive n_samp = int(np.ceil(duration * raw.info['sfreq'])) data = np.zeros((n_dipoles, n_samp)) for di, (t_, amp_) in enumerate(zip(t, amp)): data[di, t_[0]:t_[1]] = amp_ * np.hanning(t_[1] - t_[0]) stc = mne.VolSourceEstimate(data, np.arange(n_dipoles), 0, 1. / raw.info['sfreq']) # do the simulation print('') raw_mv = simulate_raw(raw, stc, trans, src, bem, cov=cov, head_pos=pos, chpi=True, n_jobs=n_jobs, verbose=True) print('') if raw_out: with printer('Saving data'): raw_mv.save(raw_out, overwrite=overwrite) # plot results -- must be *after* save because we low-pass filter if plot_dipoles: with printer('Plotting dipoles'): fig, axs = plt.subplots(1, 3, figsize=(10, 3), facecolor='w') fig.canvas.set_window_title('Dipoles') meg_info = mne.pick_info( raw.info, mne.pick_types(raw.info, meg=True, eeg=False)) helmet_rr = [ ch['coil_trans'][:3, 3].copy() for ch in meg_info['chs'] ] helmet_nn = np.zeros_like(helmet_rr) helmet_nn[:, 2] = 1. surf = dict(rr=helmet_rr, nn=helmet_nn, coord_frame=FIFF.FIFFV_COORD_DEVICE) helmet_rr = mne.surface.transform_surface_to( surf, 'head', meg_info['dev_head_t'])['rr'] p = np.linspace(0, 2 * np.pi, 40) x_sphere, y_sphere = rad * np.sin(p), rad * np.cos(p) for ai, ax in enumerate(axs): others = np.setdiff1d(np.arange(3), [ai]) ax.plot(helmet_rr[:, others[0]], helmet_rr[:, others[1]], marker='o', linestyle='none', alpha=0.1, markeredgecolor='none', markerfacecolor='b', zorder=-2) ax.plot(x_sphere + r0[others[0]], y_sphere + r0[others[1]], color='y', alpha=0.25, zorder=-1) ax.quiver(rr[:, others[0]], rr[:, others[1]], amp * nn[:, others[0]], amp * nn[:, others[1]], angles='xy', units='x', color='k', alpha=0.5) ax.set_aspect('equal') ax.set_xlabel(' - ' + 'xyz'[others[0]] + ' + ') ax.set_ylabel(' - ' + 'xyz'[others[1]] + ' + ') ax.set_xticks([]) ax.set_yticks([]) plt.setp(list(ax.spines.values()), color='none') plt.tight_layout() if plot_raw or plot_evoked: with printer('Low-pass filtering simulated data'): events = mne.find_events(raw_mv, 'STI101', verbose=False) b, a = signal.butter(4, 40. / (raw.info['sfreq'] / 2.), 'low', analog=False) raw_mv.filter(None, 40., method='iir', iir_params=dict(b=b, a=a), verbose=False, n_jobs=n_jobs) if plot_raw: with printer('Plotting raw data'): raw_mv.plot(clipping='transparent', events=events, show=False) if plot_evoked: with printer('Plotting evoked data'): picks = mne.pick_types(raw_mv.info, meg=True, eeg=True) events[:, 2] = 1 evoked = mne.Epochs(raw_mv, events, { 'Simulated': 1 }, 0, duration, None, picks).average() evoked.plot_topomap(np.unique(tmids), show=False) print('\nTotal time: %0.1f sec' % (time.time() - t0)) sys.stdout.flush() if any([plot_dipoles, plot_raw, plot_evoked]): plt.show(block=True)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--tmin", dest="tmin", type="float", help="Time before event in seconds", default=-0.2) parser.add_option("--tmax", dest="tmax", type="float", help="Time after event in seconds", default=0.4) parser.add_option("-g", "--n-grad", dest="n_grad", type="int", help="Number of SSP vectors for gradiometers", default=2) parser.add_option("-m", "--n-mag", dest="n_mag", type="int", help="Number of SSP vectors for magnetometers", default=2) parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int", help="Number of SSP vectors for EEG", default=2) parser.add_option("--l-freq", dest="l_freq", type="float", help="Filter low cut-off frequency in Hz", default=1) parser.add_option("--h-freq", dest="h_freq", type="float", help="Filter high cut-off frequency in Hz", default=100) parser.add_option("--ecg-l-freq", dest="ecg_l_freq", type="float", help="Filter low cut-off frequency in Hz used " "for ECG event detection", default=5) parser.add_option("--ecg-h-freq", dest="ecg_h_freq", type="float", help="Filter high cut-off frequency in Hz used " "for ECG event detection", default=35) parser.add_option("-p", "--preload", dest="preload", help="Temporary file used during computation " "(to save memory)", default=True) parser.add_option("-a", "--average", dest="average", action="store_true", help="Compute SSP after averaging", default=False) # XXX: change to default=True in 0.17 parser.add_option("--proj", dest="proj", help="Use SSP projections from a fif file.", default=None) parser.add_option("--filtersize", dest="filter_length", type="int", help="Number of taps to use for filtering", default=2048) parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int", help="Number of jobs to run in parallel", default=1) parser.add_option("-c", "--channel", dest="ch_name", help="Channel to use for ECG detection " "(Required if no ECG found)", default=None) parser.add_option("--rej-grad", dest="rej_grad", type="float", help="Gradiometers rejection parameter " "in fT/cm (peak to peak amplitude)", default=2000) parser.add_option("--rej-mag", dest="rej_mag", type="float", help="Magnetometers rejection parameter " "in fT (peak to peak amplitude)", default=3000) parser.add_option("--rej-eeg", dest="rej_eeg", type="float", help="EEG rejection parameter in uV " "(peak to peak amplitude)", default=50) parser.add_option("--rej-eog", dest="rej_eog", type="float", help="EOG rejection parameter in uV " "(peak to peak amplitude)", default=250) parser.add_option("--avg-ref", dest="avg_ref", action="store_true", help="Add EEG average reference proj", default=False) parser.add_option("--no-proj", dest="no_proj", action="store_true", help="Exclude the SSP projectors currently " "in the fiff file", default=False) parser.add_option("--bad", dest="bad_fname", help="Text file containing bad channels list " "(one per line)", default=None) parser.add_option("--event-id", dest="event_id", type="int", help="ID to use for events", default=999) parser.add_option("--event-raw", dest="raw_event_fname", help="raw file to use for event detection", default=None) parser.add_option("--tstart", dest="tstart", type="float", help="Start artifact detection after tstart seconds", default=0.) parser.add_option("--qrsthr", dest="qrs_threshold", type="string", help="QRS detection threshold. Between 0 and 1. Can " "also be 'auto' for automatic selection", default='auto') options, args = parser.parse_args() raw_in = options.raw_in if raw_in is None: parser.print_help() sys.exit(1) tmin = options.tmin tmax = options.tmax n_grad = options.n_grad n_mag = options.n_mag n_eeg = options.n_eeg l_freq = options.l_freq h_freq = options.h_freq ecg_l_freq = options.ecg_l_freq ecg_h_freq = options.ecg_h_freq average = options.average preload = options.preload filter_length = options.filter_length n_jobs = options.n_jobs ch_name = options.ch_name reject = dict(grad=1e-13 * float(options.rej_grad), mag=1e-15 * float(options.rej_mag), eeg=1e-6 * float(options.rej_eeg), eog=1e-6 * float(options.rej_eog)) avg_ref = options.avg_ref no_proj = options.no_proj bad_fname = options.bad_fname event_id = options.event_id proj_fname = options.proj raw_event_fname = options.raw_event_fname tstart = options.tstart qrs_threshold = options.qrs_threshold if qrs_threshold != 'auto': try: qrs_threshold = float(qrs_threshold) except ValueError: raise ValueError('qrsthr must be "auto" or a float') if bad_fname is not None: with open(bad_fname, 'r') as fid: bads = [w.rstrip() for w in fid.readlines()] print('Bad channels read : %s' % bads) else: bads = [] if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'): prefix = raw_in[:-8] else: prefix = raw_in[:-4] ecg_event_fname = prefix + '_ecg-eve.fif' if average: ecg_proj_fname = prefix + '_ecg_avg-proj.fif' else: ecg_proj_fname = prefix + '_ecg-proj.fif' raw = mne.io.read_raw_fif(raw_in, preload=preload) if raw_event_fname is not None: raw_event = mne.io.read_raw_fif(raw_event_fname) else: raw_event = raw flat = None # XXX : not exposed to the user projs, events = mne.preprocessing.compute_proj_ecg( raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg, l_freq, h_freq, average, filter_length, n_jobs, ch_name, reject, flat, bads, avg_ref, no_proj, event_id, ecg_l_freq, ecg_h_freq, tstart, qrs_threshold, copy=False) raw.close() if raw_event_fname is not None: raw_event.close() if proj_fname is not None: print('Including SSP projections from : %s' % proj_fname) # append the ecg projs, so they are last in the list projs = mne.read_proj(proj_fname) + projs if isinstance(preload, str) and os.path.exists(preload): os.remove(preload) print("Writing ECG projections in %s" % ecg_proj_fname) mne.write_proj(ecg_proj_fname, projs) print("Writing ECG events in %s" % ecg_event_fname) mne.write_events(ecg_event_fname, events)
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) parser.add_option("-s", "--subject", dest="subject", help="Subject name (required)", default=None) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", help="Subjects directory", default=None) parser.add_option("-o", "--overwrite", dest="overwrite", help="Write over existing files", action="store_true") parser.add_option("-v", "--volume", dest="volume", help="Defaults to T1", default='T1') parser.add_option("-a", "--atlas", dest="atlas", help="Specify the --atlas option for mri_watershed", default=False, action="store_true") parser.add_option("-g", "--gcaatlas", dest="gcaatlas", help="Specify the --brain_atlas option for " "mri_watershed", default=False, action="store_true") parser.add_option("-p", "--preflood", dest="preflood", help="Change the preflood height", default=None) parser.add_option("--copy", dest="copy", help="Use copies instead of symlinks for surfaces", action="store_true") parser.add_option("-t", "--T1", dest="T1", help="Whether or not to pass the -T1 flag " "(can be true, false, 0, or 1). " "By default it takes the same value as gcaatlas.", default=None) parser.add_option("-b", "--brainmask", dest="brainmask", help="The filename for the brainmask output file " "relative to the " "$SUBJECTS_DIR/$SUBJECT/bem/watershed/ directory.", default="ws") _add_verbose_flag(parser) options, args = parser.parse_args() if options.subject is None: parser.print_help() sys.exit(1) subject = options.subject subjects_dir = options.subjects_dir overwrite = options.overwrite volume = options.volume atlas = options.atlas gcaatlas = options.gcaatlas preflood = options.preflood copy = options.copy brainmask = options.brainmask T1 = options.T1 if T1 is not None: T1 = T1.lower() _check_option("--T1", T1, ('true', 'false', '0', '1')) T1 = T1 in ('true', '1') verbose = options.verbose make_watershed_bem(subject=subject, subjects_dir=subjects_dir, overwrite=overwrite, volume=volume, atlas=atlas, gcaatlas=gcaatlas, preflood=preflood, copy=copy, T1=T1, brainmask=brainmask, verbose=verbose)
def run(): """Run command.""" from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-d", "--subjects-dir", dest="subjects_dir", default=None, help="Subjects directory") parser.add_option("-s", "--subject", dest="subject", default=None, help="Subject name") parser.add_option("-f", "--fiff", dest="inst", default=None, help="FIFF file with digitizer data for coregistration") parser.add_option("-t", "--tabbed", dest="tabbed", action="store_true", default=False, help="Option for small screens: Combine " "the data source panel and the coregistration panel " "into a single panel with tabs.") parser.add_option("--no-guess-mri", dest="guess_mri_subject", action='store_false', default=None, help="Prevent the GUI from automatically guessing and " "changing the MRI subject when a new head shape source " "file is selected.") parser.add_option("--head-opacity", type=float, default=None, dest="head_opacity", help="The opacity of the head surface, in the range " "[0, 1].") parser.add_option("--high-res-head", action='store_true', default=False, dest="high_res_head", help="Use a high-resolution head surface.") parser.add_option("--low-res-head", action='store_true', default=False, dest="low_res_head", help="Use a low-resolution head surface.") parser.add_option('--trans', dest='trans', default=None, help='Head<->MRI transform FIF file ("-trans.fif")') parser.add_option('--project-eeg', dest='project_eeg', action='store_true', default=None, help="Project EEG electrodes to the head surface (" "for visualization purposes only)") parser.add_option('--orient-to-surface', action='store_true', default=None, dest='orient_to_surface', help='Orient points to the surface.') parser.add_option('--scale-by-distance', action='store_true', default=None, dest='scale_by_distance', help='Scale points by distance from the surface.') parser.add_option('--mark-inside', action='store_true', default=None, dest='mark_inside', help='Mark points inside the head using a different ' 'color.') parser.add_option('--interaction', type=str, default=None, dest='interaction', help='Interaction style to use, can be "trackball" or ' '"terrain".') parser.add_option('--scale', type=float, default=None, dest='scale', help='Scale factor for the scene.') parser.add_option('--verbose', action='store_true', dest='verbose', help='Turn on verbose mode.') parser.add_option('--simple-rendering', action='store_false', dest='advanced_rendering', help='Use simplified OpenGL rendering') options, args = parser.parse_args() if options.low_res_head: if options.high_res_head: raise ValueError("Can't specify --high-res-head and " "--low-res-head at the same time.") head_high_res = False elif options.high_res_head: head_high_res = True else: head_high_res = None # expanduser allows ~ for --subjects-dir subjects_dir = options.subjects_dir if subjects_dir is not None: subjects_dir = op.expanduser(subjects_dir) trans = options.trans if trans is not None: trans = op.expanduser(trans) try: import faulthandler faulthandler.enable() except ImportError: pass # old Python2 with ETSContext(): mne.gui.coregistration( options.tabbed, inst=options.inst, subject=options.subject, subjects_dir=subjects_dir, guess_mri_subject=options.guess_mri_subject, head_opacity=options.head_opacity, head_high_res=head_high_res, trans=trans, scrollable=True, project_eeg=options.project_eeg, orient_to_surface=options.orient_to_surface, scale_by_distance=options.scale_by_distance, mark_inside=options.mark_inside, interaction=options.interaction, scale=options.scale, advanced_rendering=options.advanced_rendering, verbose=options.verbose) if is_main: sys.exit(0)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="in_fname", help="Input raw FIF file", metavar="FILE") parser.add_option("-o", dest="out_fname", help="Output FIF file (if not set, suffix '_sss' will " "be used)", metavar="FILE", default=None) parser.add_option("--origin", dest="origin", help="Head origin in mm, or a filename to read the " "origin from. If not set it will be estimated from " "headshape points", default=None) parser.add_option("--origin-out", dest="origin_out", help="Filename to use for computed origin", default=None) parser.add_option("--frame", dest="frame", type="string", help="Coordinate frame for head center ('device' or " "'head')", default="device") parser.add_option("--bad", dest="bad", type="string", help="List of static bad channels", default=None) parser.add_option("--autobad", dest="autobad", type="string", help="Set automated bad channel detection ('on', 'off', " "'n')", default="off") parser.add_option("--skip", dest="skip", help="Skips raw data sequences, time intervals pairs in " "sec, e.g.: 0 30 120 150", default=None) parser.add_option("--force", dest="force", action="store_true", help="Ignore program warnings", default=False) parser.add_option("--st", dest="st", action="store_true", help="Apply the time-domain MaxST extension", default=False) parser.add_option("--buflen", dest="st_buflen", type="float", help="MaxSt buffer length in sec", default=16.0) parser.add_option("--corr", dest="st_corr", type="float", help="MaxSt subspace correlation", default=0.96) parser.add_option("--trans", dest="mv_trans", help="Transforms the data into the coil definitions of " "in_fname, or into the default frame", default=None) parser.add_option("--movecomp", dest="mv_comp", action="store_true", help="Estimates and compensates head movements in " "continuous raw data", default=False) parser.add_option("--headpos", dest="mv_headpos", action="store_true", help="Estimates and stores head position parameters, " "but does not compensate movements", default=False) parser.add_option("--hp", dest="mv_hp", type="string", help="Stores head position data in an ascii file", default=None) parser.add_option("--hpistep", dest="mv_hpistep", type="float", help="Sets head position update interval in ms", default=None) parser.add_option("--hpisubt", dest="mv_hpisubt", type="string", help="Subtracts hpi signals: sine amplitudes, amp + " "baseline, or switch off", default=None) parser.add_option("--nohpicons", dest="mv_hpicons", action="store_false", help="Do not check initial consistency isotrak vs " "hpifit", default=True) parser.add_option("--linefreq", dest="linefreq", type="float", help="Sets the basic line interference frequency (50 or " "60 Hz)", default=None) parser.add_option("--nooverwrite", dest="overwrite", action="store_false", help="Do not overwrite output file if it already exists", default=True) parser.add_option("--args", dest="mx_args", type="string", help="Additional command line arguments to pass to " "MaxFilter", default="") options, args = parser.parse_args() in_fname = options.in_fname if in_fname is None: parser.print_help() sys.exit(1) out_fname = options.out_fname origin = options.origin origin_out = options.origin_out frame = options.frame bad = options.bad autobad = options.autobad skip = options.skip force = options.force st = options.st st_buflen = options.st_buflen st_corr = options.st_corr mv_trans = options.mv_trans mv_comp = options.mv_comp mv_headpos = options.mv_headpos mv_hp = options.mv_hp mv_hpistep = options.mv_hpistep mv_hpisubt = options.mv_hpisubt mv_hpicons = options.mv_hpicons linefreq = options.linefreq overwrite = options.overwrite mx_args = options.mx_args if in_fname.endswith('_raw.fif') or in_fname.endswith('-raw.fif'): prefix = in_fname[:-8] else: prefix = in_fname[:-4] if out_fname is None: if st: out_fname = prefix + '_tsss.fif' else: out_fname = prefix + '_sss.fif' if origin is not None and os.path.exists(origin): with open(origin, 'r') as fid: origin = fid.readlines()[0].strip() origin = mne.preprocessing.apply_maxfilter( in_fname, out_fname, origin, frame, bad, autobad, skip, force, st, st_buflen, st_corr, mv_trans, mv_comp, mv_headpos, mv_hp, mv_hpistep, mv_hpisubt, mv_hpicons, linefreq, mx_args, overwrite) if origin_out is not None: with open(origin_out, 'w') as fid: fid.write(origin + '\n')
def run(): t0 = time.time() parser = get_optparser(__file__) parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--pos", dest="pos", default=None, help="Position definition text file. Can be 'constant' " "to hold the head position fixed", metavar="FILE") parser.add_option("--dipoles", dest="dipoles", default=None, help="Dipole definition file", metavar="FILE") parser.add_option("--cov", dest="cov", help="Covariance to use for noise generation. Can be " "'simple' to use a diagonal covariance, or 'off' to " "omit noise", metavar="FILE", default='simple') parser.add_option("--duration", dest="duration", default=None, help="Duration of each epoch (sec). If omitted, the last" " time point in the dipole definition file plus 200 ms " "will be used", type="float") parser.add_option("-j", "--jobs", dest="n_jobs", help="Number of jobs to" " run in parallel", type="int", default=1) parser.add_option("--out", dest="raw_out", help="Output raw filename", metavar="FILE") parser.add_option("--plot-dipoles", dest="plot_dipoles", help="Plot " "input dipole positions", action="store_true") parser.add_option("--plot-raw", dest="plot_raw", help="Plot the resulting " "raw traces", action="store_true") parser.add_option("--plot-evoked", dest="plot_evoked", help="Plot evoked " "data", action="store_true") parser.add_option("-p", "--plot", dest="plot", help="Plot dipoles, raw, " "and evoked", action="store_true") parser.add_option("--overwrite", dest="overwrite", help="Overwrite the" "output file if it exists", action="store_true") options, args = parser.parse_args() raw_in = options.raw_in pos = options.pos raw_out = options.raw_out dipoles = options.dipoles n_jobs = options.n_jobs plot = options.plot plot_dipoles = options.plot_dipoles or plot plot_raw = options.plot_raw or plot plot_evoked = options.plot_evoked or plot overwrite = options.overwrite duration = options.duration cov = options.cov # check parameters if not (raw_out or plot_raw or plot_evoked): raise ValueError('data must either be saved (--out) or ' 'plotted (--plot-raw or --plot_evoked)') if raw_out and op.isfile(raw_out) and not overwrite: raise ValueError('output file exists, use --overwrite (%s)' % raw_out) if raw_in is None or pos is None or dipoles is None: parser.print_help() sys.exit(1) s = 'Simulate raw data with head movements' print('\n%s\n%s\n%s\n' % ('-' * len(s), s, '-' * len(s))) # setup the simulation with printer('Reading dipole definitions'): if not op.isfile(dipoles): raise IOError('dipole file not found:\n%s' % dipoles) dipoles = np.loadtxt(dipoles, skiprows=1, dtype=float) n_dipoles = dipoles.shape[0] if dipoles.shape[1] != 8: raise ValueError('dipoles must have 8 columns') rr = dipoles[:, :3] * 1e-3 nn = dipoles[:, 3:6] t = dipoles[:, 6:8] duration = t.max() + 0.2 if duration is None else duration if (t[:, 0] > t[:, 1]).any(): raise ValueError('found tmin > tmax in dipole file') if (t < 0).any(): raise ValueError('found t < 0 in dipole file') if (t > duration).any(): raise ValueError('found t > duration in dipole file') amp = np.sqrt(np.sum(nn * nn, axis=1)) * 1e-9 mne.surface._normalize_vectors(nn) nn[(nn == 0).all(axis=1)] = (1, 0, 0) src = mne.SourceSpaces([ dict(rr=rr, nn=nn, inuse=np.ones(n_dipoles, int), coord_frame=FIFF.FIFFV_COORD_HEAD)]) for key in ['pinfo', 'nuse_tri', 'use_tris', 'patch_inds']: src[0][key] = None trans = {'from': FIFF.FIFFV_COORD_HEAD, 'to': FIFF.FIFFV_COORD_MRI, 'trans': np.eye(4)} if (amp > 100e-9).any(): print('') warnings.warn('Largest dipole amplitude %0.1f > 100 nA' % (amp.max() * 1e9)) if pos == 'constant': print('Holding head position constant') pos = None else: with printer('Loading head positions'): pos = mne.get_chpi_positions(pos) with printer('Loading raw data file'): with warnings.catch_warnings(record=True): raw = mne.io.Raw(raw_in, preload=False, allow_maxshield=True, verbose=False) if cov == 'simple': print('Using diagonal covariance for brain noise') elif cov == 'off': print('Omitting brain noise in the simulation') cov = None else: with printer('Loading covariance file for brain noise'): cov = mne.read_cov(cov) with printer('Setting up spherical model'): bem = mne.bem.make_sphere_model('auto', 'auto', raw.info, verbose=False) # check that our sources are reasonable rad = bem['layers'][0]['rad'] r0 = bem['r0'] outside = np.sqrt(np.sum((rr - r0) ** 2, axis=1)) >= rad n_outside = outside.sum() if n_outside > 0: print('') raise ValueError( '%s dipole%s outside the spherical model, are your positions ' 'in mm?' % (n_outside, 's were' if n_outside != 1 else ' was')) with printer('Constructing source estimate'): tmids = t.mean(axis=1) t = np.round(t * raw.info['sfreq']).astype(int) t[:, 1] += 1 # make it inclusive n_samp = int(np.ceil(duration * raw.info['sfreq'])) data = np.zeros((n_dipoles, n_samp)) for di, (t_, amp_) in enumerate(zip(t, amp)): data[di, t_[0]:t_[1]] = amp_ * np.hanning(t_[1] - t_[0]) stc = mne.VolSourceEstimate(data, np.arange(n_dipoles), 0, 1. / raw.info['sfreq']) # do the simulation print('') raw_mv = simulate_raw(raw, stc, trans, src, bem, cov=cov, head_pos=pos, chpi=True, n_jobs=n_jobs, verbose=True) print('') if raw_out: with printer('Saving data'): raw_mv.save(raw_out, overwrite=overwrite) # plot results -- must be *after* save because we low-pass filter if plot_dipoles: with printer('Plotting dipoles'): fig, axs = plt.subplots(1, 3, figsize=(10, 3), facecolor='w') fig.canvas.set_window_title('Dipoles') meg_info = mne.pick_info(raw.info, mne.pick_types(raw.info, meg=True, eeg=False)) helmet_rr = [ch['coil_trans'][:3, 3].copy() for ch in meg_info['chs']] helmet_nn = np.zeros_like(helmet_rr) helmet_nn[:, 2] = 1. surf = dict(rr=helmet_rr, nn=helmet_nn, coord_frame=FIFF.FIFFV_COORD_DEVICE) helmet_rr = mne.surface.transform_surface_to( surf, 'head', meg_info['dev_head_t'])['rr'] p = np.linspace(0, 2 * np.pi, 40) x_sphere, y_sphere = rad * np.sin(p), rad * np.cos(p) for ai, ax in enumerate(axs): others = np.setdiff1d(np.arange(3), [ai]) ax.plot(helmet_rr[:, others[0]], helmet_rr[:, others[1]], marker='o', linestyle='none', alpha=0.1, markeredgecolor='none', markerfacecolor='b', zorder=-2) ax.plot(x_sphere + r0[others[0]], y_sphere + r0[others[1]], color='y', alpha=0.25, zorder=-1) ax.quiver(rr[:, others[0]], rr[:, others[1]], amp * nn[:, others[0]], amp * nn[:, others[1]], angles='xy', units='x', color='k', alpha=0.5) ax.set_aspect('equal') ax.set_xlabel(' - ' + 'xyz'[others[0]] + ' + ') ax.set_ylabel(' - ' + 'xyz'[others[1]] + ' + ') ax.set_xticks([]) ax.set_yticks([]) plt.setp(list(ax.spines.values()), color='none') plt.tight_layout() if plot_raw or plot_evoked: with printer('Low-pass filtering simulated data'): events = mne.find_events(raw_mv, 'STI101', verbose=False) b, a = signal.butter(4, 40. / (raw.info['sfreq'] / 2.), 'low', analog=False) raw_mv.filter(None, 40., method='iir', iir_params=dict(b=b, a=a), verbose=False, n_jobs=n_jobs) if plot_raw: with printer('Plotting raw data'): raw_mv.plot(clipping='transparent', events=events, show=False) if plot_evoked: with printer('Plotting evoked data'): picks = mne.pick_types(raw_mv.info, meg=True, eeg=True) events[:, 2] = 1 evoked = mne.Epochs(raw_mv, events, {'Simulated': 1}, 0, duration, None, picks).average() evoked.plot_topomap(np.unique(tmids), show=False) print('\nTotal time: %0.1f sec' % (time.time() - t0)) sys.stdout.flush() if any([plot_dipoles, plot_raw, plot_evoked]): plt.show(block=True)
def run(): from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--tmin", dest="tmin", type="float", help="Time before event in seconds", default=-0.2) parser.add_option("--tmax", dest="tmax", type="float", help="Time after event in seconds", default=0.2) parser.add_option("-g", "--n-grad", dest="n_grad", type="int", help="Number of SSP vectors for gradiometers", default=2) parser.add_option("-m", "--n-mag", dest="n_mag", type="int", help="Number of SSP vectors for magnetometers", default=2) parser.add_option("-e", "--n-eeg", dest="n_eeg", type="int", help="Number of SSP vectors for EEG", default=2) parser.add_option("--l-freq", dest="l_freq", type="float", help="Filter low cut-off frequency in Hz", default=1) parser.add_option("--h-freq", dest="h_freq", type="float", help="Filter high cut-off frequency in Hz", default=35) parser.add_option("--eog-l-freq", dest="eog_l_freq", type="float", help="Filter low cut-off frequency in Hz used for " "EOG event detection", default=1) parser.add_option("--eog-h-freq", dest="eog_h_freq", type="float", help="Filter high cut-off frequency in Hz used for " "EOG event detection", default=10) parser.add_option("-p", "--preload", dest="preload", help="Temporary file used during computation (to " "save memory)", default=True) parser.add_option("-a", "--average", dest="average", action="store_true", help="Compute SSP after averaging", default=False) parser.add_option("--proj", dest="proj", help="Use SSP projections from a fif file.", default=None) parser.add_option("--filtersize", dest="filter_length", type="int", help="Number of taps to use for filtering", default=2048) parser.add_option("-j", "--n-jobs", dest="n_jobs", type="int", help="Number of jobs to run in parallel", default=1) parser.add_option("--rej-grad", dest="rej_grad", type="float", help="Gradiometers rejection parameter in fT/cm (peak " "to peak amplitude)", default=2000) parser.add_option("--rej-mag", dest="rej_mag", type="float", help="Magnetometers rejection parameter in fT (peak to " "peak amplitude)", default=3000) parser.add_option("--rej-eeg", dest="rej_eeg", type="float", help="EEG rejection parameter in uV (peak to peak " "amplitude)", default=50) parser.add_option("--rej-eog", dest="rej_eog", type="float", help="EOG rejection parameter in uV (peak to peak " "amplitude)", default=1e9) parser.add_option("--avg-ref", dest="avg_ref", action="store_true", help="Add EEG average reference proj", default=False) parser.add_option("--no-proj", dest="no_proj", action="store_true", help="Exclude the SSP projectors currently in the " "fiff file", default=False) parser.add_option("--bad", dest="bad_fname", help="Text file containing bad channels list " "(one per line)", default=None) parser.add_option("--event-id", dest="event_id", type="int", help="ID to use for events", default=998) parser.add_option("--event-raw", dest="raw_event_fname", help="raw file to use for event detection", default=None) parser.add_option("--tstart", dest="tstart", type="float", help="Start artifact detection after tstart seconds", default=0.) parser.add_option("-c", "--channel", dest="ch_name", type="string", help="Custom EOG channel(s), comma separated", default=None) options, args = parser.parse_args() raw_in = options.raw_in if raw_in is None: parser.print_help() sys.exit(1) tmin = options.tmin tmax = options.tmax n_grad = options.n_grad n_mag = options.n_mag n_eeg = options.n_eeg l_freq = options.l_freq h_freq = options.h_freq eog_l_freq = options.eog_l_freq eog_h_freq = options.eog_h_freq average = options.average preload = options.preload filter_length = options.filter_length n_jobs = options.n_jobs reject = dict(grad=1e-13 * float(options.rej_grad), mag=1e-15 * float(options.rej_mag), eeg=1e-6 * float(options.rej_eeg), eog=1e-6 * float(options.rej_eog)) avg_ref = options.avg_ref no_proj = options.no_proj bad_fname = options.bad_fname event_id = options.event_id proj_fname = options.proj raw_event_fname = options.raw_event_fname tstart = options.tstart ch_name = options.ch_name if bad_fname is not None: with open(bad_fname, 'r') as fid: bads = [w.rstrip() for w in fid.readlines()] print('Bad channels read : %s' % bads) else: bads = [] if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'): prefix = raw_in[:-8] else: prefix = raw_in[:-4] eog_event_fname = prefix + '_eog-eve.fif' if average: eog_proj_fname = prefix + '_eog_avg-proj.fif' else: eog_proj_fname = prefix + '_eog-proj.fif' raw = mne.io.Raw(raw_in, preload=preload) if raw_event_fname is not None: raw_event = mne.io.Raw(raw_event_fname) else: raw_event = raw flat = None # XXX : not exposed to the user projs, events = mne.preprocessing.compute_proj_eog( raw=raw, raw_event=raw_event, tmin=tmin, tmax=tmax, n_grad=n_grad, n_mag=n_mag, n_eeg=n_eeg, l_freq=l_freq, h_freq=h_freq, average=average, filter_length=filter_length, n_jobs=n_jobs, reject=reject, flat=flat, bads=bads, avg_ref=avg_ref, no_proj=no_proj, event_id=event_id, eog_l_freq=eog_l_freq, eog_h_freq=eog_h_freq, tstart=tstart, ch_name=ch_name, copy=False) raw.close() if raw_event_fname is not None: raw_event.close() if proj_fname is not None: print('Including SSP projections from : %s' % proj_fname) # append the eog projs, so they are last in the list projs = mne.read_proj(proj_fname) + projs if isinstance(preload, string_types) and os.path.exists(preload): os.remove(preload) print("Writing EOG projections in %s" % eog_proj_fname) mne.write_proj(eog_proj_fname, projs) print("Writing EOG events in %s" % eog_event_fname) mne.write_events(eog_event_fname, events)
def run(): """Run command.""" import matplotlib.pyplot as plt from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__, usage='usage: %prog raw [options]') parser.add_option("--raw", dest="raw_in", help="Input raw FIF file (can also be specified " "directly as an argument without the --raw prefix)", metavar="FILE") parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default='') parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default='') parser.add_option("-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0) parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0) parser.add_option("-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20) parser.add_option("-o", "--order", dest="group_by", help="Order to use for grouping during plotting " "('type' or 'original')", default='type') parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False, action="store_true") parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False) parser.add_option("--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true") parser.add_option("--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", default=-1) parser.add_option("--lowpass", dest="lowpass", type="float", help="Display low-pass filter corner frequency", default=-1) parser.add_option("--filtorder", dest="filtorder", type="int", help="Display filtering IIR order (or 0 to use FIR)", default=4) parser.add_option("--clipping", dest="clipping", help="Enable trace clipping mode, either 'clamp' or " "'transparent'", default=None) parser.add_option("--filterchpi", dest="filterchpi", help="Enable filtering cHPI signals.", default=None, action="store_true") _add_verbose_flag(parser) options, args = parser.parse_args() if len(args): raw_in = args[0] else: raw_in = options.raw_in duration = options.duration start = options.start n_channels = options.n_channels group_by = options.group_by preload = options.preload show_options = options.show_options proj_in = options.proj_in eve_in = options.eve_in maxshield = options.maxshield highpass = options.highpass lowpass = options.lowpass filtorder = options.filtorder clipping = options.clipping filterchpi = options.filterchpi verbose = options.verbose if raw_in is None: parser.print_help() sys.exit(1) raw = mne.io.read_raw_fif(raw_in, preload=preload, allow_maxshield=maxshield) if len(proj_in) > 0: projs = mne.read_proj(proj_in) raw.info['projs'] = projs if len(eve_in) > 0: events = mne.read_events(eve_in) else: events = None if filterchpi: if not preload: raise RuntimeError( 'Raw data must be preloaded for chpi, use --preload') raw = mne.chpi.filter_chpi(raw) highpass = None if highpass < 0 or filtorder < 0 else highpass lowpass = None if lowpass < 0 or filtorder < 0 else lowpass raw.plot(duration=duration, start=start, n_channels=n_channels, group_by=group_by, show_options=show_options, events=events, highpass=highpass, lowpass=lowpass, filtorder=filtorder, clipping=clipping, verbose=verbose) plt.show(block=True)
# Martin Luessi <*****@*****.**> # Alexandre Gramfort <*****@*****.**> # Matti Hamalainen <*****@*****.**> # Yuval Harpaz <*****@*****.**> # # simplified bsd-3 license import sys from mne.fiff.bti import read_raw_bti if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option('-p', '--pdf', dest='pdf_fname', help='Input data file name', metavar='FILE') parser.add_option('-c', '--config', dest='config_fname', help='Input config file name', metavar='FILE', default='config') parser.add_option('--head_shape', dest='head_shape_fname', help='Headshape file name',
def run(): import matplotlib.pyplot as plt from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default='') parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default='') parser.add_option("-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0) parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0) parser.add_option("-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20) parser.add_option("-o", "--order", dest="order", help="Order for plotting ('type' or 'original')", default='type') parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False) parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False) options, args = parser.parse_args() raw_in = options.raw_in duration = options.duration start = options.start n_channels = options.n_channels order = options.order preload = options.preload show_options = options.show_options proj_in = options.proj_in eve_in = options.eve_in if raw_in is None: parser.print_help() sys.exit(1) raw = mne.io.Raw(raw_in, preload=preload) if len(proj_in) > 0: projs = mne.read_proj(proj_in) raw.info['projs'] = projs if len(eve_in) > 0: events = mne.read_events(eve_in) else: events = None raw.plot(duration=duration, start=start, n_channels=n_channels, order=order, show_options=show_options, events=events) plt.show(block=True)
from __future__ import print_function # Authors : Alexandre Gramfort, Ph.D. # Martin Luessi, Ph.D. from mne.externals.six import string_types import os import sys import mne if __name__ == '__main__': from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("-i", "--in", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--tmin", dest="tmin", type="float", help="Time before event in seconds", default=-0.2) parser.add_option("--tmax", dest="tmax", type="float", help="Time after event in seconds", default=0.2) parser.add_option("-g", "--n-grad", dest="n_grad", type="int", help="Number of SSP vectors for gradiometers", default=2) parser.add_option("-m", "--n-mag", dest="n_mag", type="int", help="Number of SSP vectors for magnetometers", default=2)
def run(): """Run command.""" import matplotlib.pyplot as plt from mne.commands.utils import get_optparser parser = get_optparser(__file__) parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE") parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default="") parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default="") parser.add_option( "-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0 ) parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0) parser.add_option( "-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20 ) parser.add_option("-o", "--order", dest="order", help="Order for plotting ('type' or 'original')", default="type") parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False) parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False) parser.add_option( "--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true" ) parser.add_option( "--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", default=-1 ) parser.add_option( "--lowpass", dest="lowpass", type="float", help="Display low-pass filter corner frequency", default=-1 ) parser.add_option("--filtorder", dest="filtorder", type="int", help="Display filtering IIR order", default=4) parser.add_option( "--clipping", dest="clipping", help="Enable trace clipping mode, either 'clip' or " "'transparent'", default=None, ) parser.add_option("--filterchpi", dest="filterchpi", help="Enable filtering cHPI signals.", default=None) options, args = parser.parse_args() raw_in = options.raw_in duration = options.duration start = options.start n_channels = options.n_channels order = options.order preload = options.preload show_options = options.show_options proj_in = options.proj_in eve_in = options.eve_in maxshield = options.maxshield highpass = options.highpass lowpass = options.lowpass filtorder = options.filtorder clipping = options.clipping filterchpi = options.filterchpi if raw_in is None: parser.print_help() sys.exit(1) raw = mne.io.read_raw_fif(raw_in, preload=preload, allow_maxshield=maxshield) if len(proj_in) > 0: projs = mne.read_proj(proj_in) raw.info["projs"] = projs if len(eve_in) > 0: events = mne.read_events(eve_in) else: events = None if filterchpi: if not preload: raise RuntimeError("Raw data must be preloaded for chpi, use --preload") raw = mne.chpi.filter_chpi(raw) highpass = None if highpass < 0 or filtorder <= 0 else highpass lowpass = None if lowpass < 0 or filtorder <= 0 else lowpass filtorder = 4 if filtorder <= 0 else filtorder raw.plot( duration=duration, start=start, n_channels=n_channels, order=order, show_options=show_options, events=events, highpass=highpass, lowpass=lowpass, filtorder=filtorder, clipping=clipping, ) plt.show(block=True)