How to use the mne.utils.logger.info 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 / minimum_norm / inverse.py View on Github external
#
    #   Transformation into current distributions by weighting the eigenleads
    #   with the weights computed above
    #
    if inv['eigen_leads_weighted']:
        #
        #     R^0.5 has been already factored in
        #
        logger.info('    Eigenleads already weighted ... ')
        K = np.dot(eigen_leads, trans)
    else:
        #
        #     R^0.5 has to be factored in
        #
        logger.info('    Eigenleads need to be weighted ...')
        K = np.sqrt(source_cov) * np.dot(eigen_leads, trans)

    return K, noise_norm, vertno, source_nn
github mne-tools / mne-python / mne / cuda.py View on Github external
def _set_cuda_device(device_id, verbose=None):
    """Set the CUDA device."""
    import cupy
    cupy.cuda.Device(device_id).use()
    logger.info('Now using CUDA device {}'.format(device_id))
github mne-tools / mne-python / mne / datasets / utils.py View on Github external
def _manifest_check_download(manifest_path, destination, url, hash_):
    with open(manifest_path, 'r') as fid:
        names = [name.strip() for name in fid.readlines()]
    need = list()
    for name in names:
        if not op.isfile(op.join(destination, name)):
            need.append(name)
    logger.info('%d file%s missing from %s in %s'
                % (len(need), _pl(need), manifest_path, destination))
    if len(need) > 0:
        with tempfile.TemporaryDirectory() as path:
            logger.info('Downloading missing files remotely')

            fname_path = op.join(path, 'temp.zip')
            _fetch_file(url, fname_path, hash_=hash_)
            logger.info('Extracting missing file%s' % (_pl(need),))
            with zipfile.ZipFile(fname_path, 'r') as ff:
                members = set(f for f in ff.namelist() if not f.endswith('/'))
                missing = sorted(members.symmetric_difference(set(names)))
                if len(missing):
                    raise RuntimeError('Zip file did not have correct names:'
                                       '\n%s' % ('\n'.join(missing)))
                for name in need:
                    ff.extract(name, path=destination)
        logger.info('Successfully extracted %d file%s'
                    % (len(need), _pl(need)))
github mne-tools / mne-python / mne / source_space.py View on Github external
def _get_vertex_map_nn(fro_src, subject_from, subject_to, hemi, subjects_dir,
                       to_neighbor_tri=None):
    """Get a nearest-neigbor vertex match for a given hemi src.

    The to_neighbor_tri can optionally be passed in to avoid recomputation
    if it's already available.
    """
    # adapted from mne_make_source_space.c, knowing accurate=False (i.e.
    # nearest-neighbor mode should be used)
    logger.info('Mapping %s %s -> %s (nearest neighbor)...'
                % (hemi, subject_from, subject_to))
    regs = [op.join(subjects_dir, s, 'surf', '%s.sphere.reg' % hemi)
            for s in (subject_from, subject_to)]
    reg_fro, reg_to = [read_surface(r, return_dict=True)[-1] for r in regs]
    if to_neighbor_tri is not None:
        reg_to['neighbor_tri'] = to_neighbor_tri
    if 'neighbor_tri' not in reg_to:
        reg_to['neighbor_tri'] = _triangle_neighbors(reg_to['tris'],
                                                     reg_to['np'])

    morph_inuse = np.zeros(len(reg_to['rr']), bool)
    best = np.zeros(fro_src['np'], int)
    ones = _compute_nearest(reg_to['rr'], reg_fro['rr'][fro_src['vertno']])
    for v, one in zip(fro_src['vertno'], ones):
        # if it were actually a proper morph map, we would do this, but since
        # we know it's nearest neighbor list, we don't need to:
github mne-tools / mne-python / mne / stats / cluster_level.py View on Github external
if check_disjoint is True and (connectivity is not None and
                                   connectivity is not False):
        partitions = _get_partitions_from_connectivity(connectivity, n_times)
    else:
        partitions = None
    logger.info('Running initial clustering')
    out = _find_clusters(t_obs, threshold, tail, connectivity,
                         max_step=max_step, include=include,
                         partitions=partitions, t_power=t_power,
                         show_info=True)
    clusters, cluster_stats = out
    # For TFCE, return the "adjusted" statistic instead of raw scores
    if isinstance(threshold, dict):
        t_obs = cluster_stats.copy()

    logger.info('Found %d clusters' % len(clusters))

    # convert clusters to old format
    if connectivity is not None and connectivity is not False:
        # our algorithms output lists of indices by default
        if out_type == 'mask':
            clusters = _cluster_indices_to_mask(clusters, n_tests)
    else:
        # ndimage outputs slices or boolean masks by default
        if out_type == 'indices':
            clusters = _cluster_mask_to_indices(clusters)

    # The stat should have the same shape as the samples
    t_obs.shape = sample_shape

    # convert our seed to orders
    # check to see if we can do an exact test
github mne-tools / mne-python / mne / forward / _compute_forward.py View on Github external
mri_rr = np.ascontiguousarray(
            apply_trans(fd['head_mri_t']['trans'], rr))
    mri_Q, bem_rr, fun = fd['mri_Q'], fd['bem_rr'], fd['fun']
    for ci in range(len(fd['coils_list'])):
        coils, ccoils = fd['coils_list'][ci], fd['ccoils_list'][ci]
        if len(coils) == 0:  # nothing to do
            Bs.append(np.zeros((3 * len(rr), 0)))
            continue

        coil_type, compensator = fd['coil_types'][ci], fd['compensators'][ci]
        solution, csolution = fd['solutions'][ci], fd['csolutions'][ci]
        info = fd['infos'][ci]

        # Do the actual forward calculation for a list MEG/EEG sensors
        if not silent:
            logger.info('Computing %s at %d source location%s '
                        '(free orientations)...'
                        % (coil_type.upper(), len(rr), _pl(rr)))
        # Calculate forward solution using spherical or BEM model
        B = fun(rr, mri_rr, mri_Q, coils, solution, bem_rr, n_jobs,
                coil_type)

        # Compensate if needed (only done for MEG systems w/compensation)
        if compensator is not None:
            # Compute the field in the compensation sensors
            work = fun(rr, mri_rr, mri_Q, ccoils, csolution, bem_rr,
                       n_jobs, coil_type)
            # Combine solutions so we can do the compensation
            both = np.zeros((work.shape[0], B.shape[1] + work.shape[1]))
            picks = pick_types(info, meg=True, ref_meg=False, exclude=[])
            both[:, picks] = B
            picks = pick_types(info, meg=False, ref_meg=True, exclude=[])
github mne-tools / mne-python / mne / dipole.py View on Github external
' got %s' % (pos,))
        logger.info('Fixed position    : %6.1f %6.1f %6.1f mm'
                    % tuple(1000 * pos))
        if ori is not None:
            ori = np.array(ori, float)
            if ori.shape != (3,):
                raise ValueError('oris must be None or a 3-element array-like,'
                                 ' got %s' % (ori,))
            norm = np.sqrt(np.sum(ori * ori))
            if not np.isclose(norm, 1):
                raise ValueError('ori must be a unit vector, got length %s'
                                 % (norm,))
            logger.info('Fixed orientation  : %6.4f %6.4f %6.4f mm'
                        % tuple(ori))
        else:
            logger.info('Free orientation   : ')
        fit_n_jobs = 1  # only use 1 job to do the guess fitting
    else:
        fixed_position = False
        # Eventually these could be parameters, but they are just used for
        # the initial grid anyway
        guess_grid = 0.02  # MNE-C uses 0.01, but this is faster w/similar perf
        guess_mindist = max(0.005, min_dist_to_inner_skull)
        guess_exclude = 0.02

        logger.info('Guess grid        : %6.1f mm' % (1000 * guess_grid,))
        if guess_mindist > 0.0:
            logger.info('Guess mindist     : %6.1f mm'
                        % (1000 * guess_mindist,))
        if guess_exclude > 0:
            logger.info('Guess exclude     : %6.1f mm'
                        % (1000 * guess_exclude,))
github mne-tools / mne-python / mne / realtime / stim_server_client.py View on Github external
def __init__(self, host, port=4218, timeout=5.0,
                 verbose=None):  # noqa: D102
        try:
            logger.info("Setting up client socket")
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._sock.settimeout(timeout)
            self._sock.connect((host, port))

            logger.info("Establishing connection with server")
            data = "add client".encode('utf-8')
            n_sent = self._sock.send(data)
            if n_sent != len(data):
                raise RuntimeError('Could not communicate with server')
            resp = self._sock.recv(1024).decode()  # turn bytes into str (Py3k)

            if resp == 'Client added':
                logger.info("Connection established")
            else:
                raise RuntimeError('Client not added')

        except Exception:
            raise RuntimeError('Setting up acquisition <-> stimulation '
                               'computer connection (host: %s '
                               'port: %d) failed. Make sure StimServer '
                               'is running.' % (host, port))
github mne-tools / mne-python / mne / proj.py View on Github external
'Maxfiltered data', verbose=False)
        if n_grad != n_mag:
            raise ValueError('n_grad (%d) must be equal to n_mag (%d) when '
                             'using meg="combined"')
        kinds = ['meg', '', 'eeg']
        n_mag = 0
        grad_ind = pick_types(info, meg=True, ref_meg=False, exclude='bads')
        if (n_grad > 0) and len(grad_ind) == 0:
            logger.info("No MEG channels found for joint estimation. "
                        "Forcing n_grad=n_mag=0")
            n_grad = 0
    else:
        kinds = ['planar', 'axial', 'eeg']

    if (n_grad > 0) and len(grad_ind) == 0:
        logger.info("No gradiometers found. Forcing n_grad to 0")
        n_grad = 0
    if (n_mag > 0) and len(mag_ind) == 0:
        logger.info("No magnetometers found. Forcing n_mag to 0")
        n_mag = 0
    if (n_eeg > 0) and len(eeg_ind) == 0:
        logger.info("No EEG channels found. Forcing n_eeg to 0")
        n_eeg = 0

    ch_names = info['ch_names']
    grad_names, mag_names, eeg_names = ([ch_names[k] for k in ind]
                                        for ind in [grad_ind, mag_ind,
                                                    eeg_ind])

    projs = []
    for n, ind, names, desc in zip([n_grad, n_mag, n_eeg],
                                   [grad_ind, mag_ind, eeg_ind],
github mne-tools / mne-python / mne / minimum_norm / inverse.py View on Github external
inv['noise_cov']['eig'] = scale * inv['noise_cov']['eig']
    inv['source_cov']['data'] = scale * inv['source_cov']['data']
    #
    if inv['eigen_leads_weighted']:
        inv['eigen_leads']['data'] = sqrt(scale) * inv['eigen_leads']['data']

    logger.info('    Scaled noise and source covariance from nave = %d to'
                ' nave = %d' % (inv['nave'], nave))
    inv['nave'] = nave
    #
    #   Create the diagonal matrix for computing the regularized inverse
    #
    sing = np.array(inv['sing'], dtype=np.float64)
    with np.errstate(invalid='ignore'):  # if lambda2==0
        inv['reginv'] = np.where(sing > 0, sing / (sing ** 2 + lambda2), 0)
    logger.info('    Created the regularized inverter')
    #
    #   Create the projection operator
    #
    inv['proj'], ncomp, _ = make_projector(inv['projs'],
                                           inv['noise_cov']['names'])
    if ncomp > 0:
        logger.info('    Created an SSP operator (subspace dimension = %d)'
                    % ncomp)
    else:
        logger.info('    The projection vectors do not apply to these '
                    'channels.')

    #
    #   Create the whitener
    #