How to use the mne.utils.logger function in mne

To help you get started, we’ve selected a few mne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mne-tools / mne-python / mne / io / artemis123 / utils.py View on Github external
def _load_mne_locs(fname=None):
    """Load MNE locs structure from file (if exists) or recreate it."""
    if (not fname):
        # find input file
        resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources')
        fname = op.join(resource_dir, 'Artemis123_mneLoc.csv')

    if not op.exists(fname):
        raise IOError('MNE locs file "%s" does not exist' % (fname))

    logger.info('Loading mne loc file {}'.format(fname))
    locs = dict()
    with open(fname, 'r') as fid:
        for line in fid:
            vals = line.strip().split(',')
            locs[vals[0]] = np.array(vals[1::], np.float)

    return locs
github mne-tools / mne-python / mne / forward / _lead_dots.py View on Github external
extra_str = ' derivative'
        lut_shape = (n_interp + 1, n_coeff, 3)
    else:  # 'eeg'
        fname = op.join(fname, 'legval_%s_%s.bin' % (n_coeff, n_interp))
        leg_fun = _get_legen
        extra_str = ''
        lut_shape = (n_interp + 1, n_coeff)
    if not op.isfile(fname) or force_calc:
        logger.info('Generating Legendre%s table...' % extra_str)
        x_interp = np.linspace(-1, 1, n_interp + 1)
        lut = leg_fun(x_interp, n_coeff).astype(np.float32)
        if not force_calc:
            with open(fname, 'wb') as fid:
                fid.write(lut.tostring())
    else:
        logger.info('Reading Legendre%s table...' % extra_str)
        with open(fname, 'rb', buffering=0) as fid:
            lut = np.fromfile(fid, np.float32)
    lut.shape = lut_shape

    # we need this for the integration step
    n_fact = np.arange(1, n_coeff, dtype=float)
    if ch_type == 'meg':
        n_facts = list()  # multn, then mult, then multn * (n + 1)
        if volume_integral:
            n_facts.append(n_fact / ((2.0 * n_fact + 1.0) *
                                     (2.0 * n_fact + 3.0)))
        else:
            n_facts.append(n_fact / (2.0 * n_fact + 1.0))
        n_facts.append(n_facts[0] / (n_fact + 1.0))
        n_facts.append(n_facts[0] * (n_fact + 1.0))
        # skip the first set of coefficients because they are not used
github mne-tools / mne-python / mne / io / ctf / eeg.py View on Github external
raise RuntimeError('Illegal data in EEG position file: %s'
                                       % line)
                r = np.array([float(p) for p in parts[2:]]) / 100.
                if (r * r).sum() > 1e-4:
                    label = parts[1]
                    eeg['labels'].append(label)
                    eeg['rr'].append(r)
                    id_ = _cardinal_dict.get(label.lower(), int(parts[0]))
                    if label.lower() in _cardinal_dict:
                        kind = FIFF.FIFFV_POINT_CARDINAL
                    else:
                        kind = FIFF.FIFFV_POINT_EXTRA
                    eeg['ids'].append(id_)
                    eeg['kinds'].append(kind)
                    eeg['np'] += 1
    logger.info('    Separate EEG position data file read.')
    return eeg
github mne-tools / mne-python / mne / io / reference.py View on Github external
break
        # if auto comes up empty, or the user specifies a bad ch_type.
        else:
            raise ValueError('No EEG, ECoG or sEEG channels found '
                             'to rereference.')

    ch_dict = {ch_type: True, 'meg': False, 'ref_meg': False}
    eeg_idx = pick_types(inst.info, **ch_dict)
    ch_sel = [inst.ch_names[i] for i in eeg_idx]

    if ref_channels == 'average' and not projection:  # apply average reference
        logger.info('Applying average reference.')
        ref_channels = ch_sel

    if ref_channels == []:
        logger.info('EEG data marked as already having the desired reference. '
                    'Preventing automatic future re-referencing to an average '
                    'reference.')
    else:
        logger.info('Applying a custom %s '
                    'reference.' % DEFAULTS['titles'][type_])

    return _apply_reference(inst, ref_channels, ch_sel)
github mne-tools / mne-python / mne / io / pick.py View on Github external
sel_info = pick_channels(orig['info']['ch_names'], include=include,
                             exclude=exclude, ordered=ordered)

    fwd = deepcopy(orig) if copy else orig

    # Check that forward solution and original data file agree on #channels
    if len(sel_sol) != len(sel_info):
        raise ValueError('Forward solution and functional data appear to '
                         'have different channel names, please check.')

    #   Do we have something?
    nuse = len(sel_sol)
    if nuse == 0:
        raise ValueError('Nothing remains after picking')

    logger.info('    %d out of %d channels remain after picking'
                % (nuse, fwd['nchan']))

    #   Pick the correct rows of the forward operator using sel_sol
    fwd['sol']['data'] = fwd['sol']['data'][sel_sol, :]
    fwd['_orig_sol'] = fwd['_orig_sol'][sel_sol, :]
    fwd['sol']['nrow'] = nuse

    ch_names = [fwd['sol']['row_names'][k] for k in sel_sol]
    fwd['nchan'] = nuse
    fwd['sol']['row_names'] = ch_names

    # Pick the appropriate channel names from the info-dict using sel_info
    fwd['info']['chs'] = [fwd['info']['chs'][k] for k in sel_info]
    fwd['info']._update_redundant()
    fwd['info']['bads'] = [b for b in fwd['info']['bads'] if b in ch_names]
github mne-tools / mne-python / mne / preprocessing / maxfilter.py View on Github external
"""
    # check for possible maxfilter bugs
    if mv_trans is not None and mv_comp:
        _mxwarn("Don't use '-trans' with head-movement compensation "
                "'-movecomp'")

    if autobad != 'off' and (mv_headpos or mv_comp):
        _mxwarn("Don't use '-autobad' with head-position estimation "
                "'-headpos' or movement compensation '-movecomp'")

    if st and autobad != 'off':
        _mxwarn("Don't use '-autobad' with '-st' option")

    # determine the head origin if necessary
    if origin is None:
        logger.info('Estimating head origin from headshape points..')
        raw = read_raw_fif(in_fname)
        r, o_head, o_dev = fit_sphere_to_headshape(raw.info, units='mm')
        raw.close()
        logger.info('[done]')
        if frame == 'head':
            origin = o_head
        elif frame == 'device':
            origin = o_dev
        else:
            raise RuntimeError('invalid frame for origin')

    if not isinstance(origin, str):
        origin = '%0.1f %0.1f %0.1f' % (origin[0], origin[1], origin[2])

    # format command
    cmd = ('maxfilter -f %s -o %s -frame %s -origin %s '
github mne-tools / mne-python / mne / coreg.py View on Github external
# make sure destination does not already exist
    dest = os.path.join(subjects_dir, 'fsaverage')
    if dest == fs_src:
        raise IOError(
            "Your subjects_dir points to the freesurfer subjects_dir (%r). "
            "The default subject can not be created in the freesurfer "
            "installation directory; please specify a different "
            "subjects_dir." % subjects_dir)
    elif (not update) and os.path.exists(dest):
        raise IOError(
            "Can not create fsaverage because %r already exists in "
            "subjects_dir %r. Delete or rename the existing fsaverage "
            "subject folder." % ('fsaverage', subjects_dir))

    # copy fsaverage from freesurfer
    logger.info("Copying fsaverage subject from freesurfer directory...")
    if (not update) or not os.path.exists(dest):
        shutil.copytree(fs_src, dest)
        _make_writable_recursive(dest)

    # copy files from mne
    source_fname = os.path.join(os.path.dirname(__file__), 'data', 'fsaverage',
                                'fsaverage-%s.fif')
    dest_bem = os.path.join(dest, 'bem')
    if not os.path.exists(dest_bem):
        os.mkdir(dest_bem)
    logger.info("Copying auxiliary fsaverage files from mne...")
    dest_fname = os.path.join(dest_bem, 'fsaverage-%s.fif')
    _make_writable_recursive(dest_bem)
    for name in ('fiducials', 'head', 'inner_skull-bem', 'trans'):
        if not os.path.exists(dest_fname % name):
            shutil.copy(source_fname % name, dest_bem)
github mne-tools / mne-python / mne / dipole.py View on Github external
def _make_guesses(surf, grid, exclude, mindist, n_jobs):
    """Make a guess space inside a sphere or BEM surface."""
    if 'rr' in surf:
        logger.info('Guess surface (%s) is in %s coordinates'
                    % (_surf_name[surf['id']],
                       _coord_frame_name(surf['coord_frame'])))
    else:
        logger.info('Making a spherical guess space with radius %7.1f mm...'
                    % (1000 * surf['R']))
    logger.info('Filtering (grid = %6.f mm)...' % (1000 * grid))
    src = _make_volume_source_space(surf, grid, exclude, 1000 * mindist,
                                    do_neighbors=False, n_jobs=n_jobs)
    assert 'vertno' in src
    # simplify the result to make things easier later
    src = dict(rr=src['rr'][src['vertno']], nn=src['nn'][src['vertno']],
               nuse=src['nuse'], coord_frame=src['coord_frame'],
               vertno=np.arange(src['nuse']))
    return SourceSpaces([src])
github mne-tools / mne-python / mne / chpi.py View on Github external
def _get_hpi_info(info, verbose=None):
    """Get HPI information from raw."""
    if len(info['hpi_meas']) == 0 or \
            ('coil_freq' not in info['hpi_meas'][0]['hpi_coils'][0]):
        raise RuntimeError('Appropriate cHPI information not found in'
                           'info["hpi_meas"] and info["hpi_subsystem"], '
                           'cannot process cHPI')
    hpi_coils = sorted(info['hpi_meas'][-1]['hpi_coils'],
                       key=lambda x: x['number'])  # ascending (info) order

    # get frequencies
    hpi_freqs = np.array([float(x['coil_freq']) for x in hpi_coils])
    logger.info('Using %s HPI coils: %s Hz'
                % (len(hpi_freqs), ' '.join(str(int(s)) for s in hpi_freqs)))

    # how cHPI active is indicated in the FIF file
    hpi_sub = info['hpi_subsystem']
    hpi_pick = None  # there is no pick!
    if hpi_sub is not None:
        if 'event_channel' in hpi_sub:
            hpi_pick = pick_channels(info['ch_names'],
                                     [hpi_sub['event_channel']])
            hpi_pick = hpi_pick[0] if len(hpi_pick) > 0 else None
        # grab codes indicating a coil is active
        hpi_on = [coil['event_bits'][0] for coil in hpi_sub['hpi_coils']]
        # not all HPI coils will actually be used
        hpi_on = np.array([hpi_on[hc['number'] - 1] for hc in hpi_coils])
        # mask for coils that may be active
        hpi_mask = np.array([event_bit != 0 for event_bit in hpi_on])
github mne-tools / mne-python / mne / beamformer / _dics.py View on Github external
combine_xyz = False

    _check_one_ch_type('dics', info, forward)

    # pick info, get gain matrix, etc.
    _, info, proj, vertices, G, _, nn, orient_std = _prepare_beamformer_input(
        info, forward, label, pick_ori,
        combine_xyz=combine_xyz, exp=exp)
    subject = _subject_from_forward(forward)
    src_type = _get_src_type(forward['src'], vertices)
    del forward
    ch_names = list(info['ch_names'])

    csd_picks = [csd.ch_names.index(ch) for ch in ch_names]

    logger.info('Computing DICS spatial filters...')
    Ws = []
    for i, freq in enumerate(frequencies):
        if n_freqs > 1:
            logger.info('    computing DICS spatial filter at %sHz (%d/%d)' %
                        (freq, i + 1, n_freqs))

        Cm = csd.get_data(index=i)

        if real_filter:
            Cm = Cm.real

        # Ensure the CSD is in the same order as the leadfield
        Cm = Cm[csd_picks, :][:, csd_picks]

        # compute spatial filter
        W = _compute_beamformer(G, Cm, reg, n_orient, weight_norm, pick_ori,