@verbose
def _prepare_forward(forward, info, noise_cov, pca=False, rank=None,
                     verbose=None):
    """Util function to prepare forward solution for inverse solvers
    """
    # fwd['sol']['row_names'] may be different order from fwd['info']['chs']
    fwd_sol_ch_names = forward['sol']['row_names']
    ch_names = [c['ch_name'] for c in info['chs']
                if ((c['ch_name'] not in info['bads'] and
                     c['ch_name'] not in noise_cov['bads']) and
                    (c['ch_name'] in fwd_sol_ch_names and
                     c['ch_name'] in noise_cov.ch_names))]

    if not len(info['bads']) == len(noise_cov['bads']) or \
            not all(b in noise_cov['bads'] for b in info['bads']):
        logger.info('info["bads"] and noise_cov["bads"] do not match, '
                    'excluding bad channels from both')

    n_chan = len(ch_names)
    logger.info("Computing inverse operator with %d channels." % n_chan)

    #
    #   Handle noise cov
    #
    noise_cov = prepare_noise_cov(noise_cov, info, ch_names, rank)

    #   Omit the zeroes due to projection
    eig = noise_cov['eig']
    nzero = (eig > 0)
    n_nzero = sum(nzero)

    if pca:
        #   Rows of eigvec are the eigenvectors
        whitener = noise_cov['eigvec'][nzero] / np.sqrt(eig[nzero])[:, None]
        logger.info('Reducing data rank to %d' % n_nzero)
    else:
        whitener = np.zeros((n_chan, n_chan), dtype=np.float)
        whitener[nzero, nzero] = 1.0 / np.sqrt(eig[nzero])
        #   Rows of eigvec are the eigenvectors
        whitener = np.dot(whitener, noise_cov['eigvec'])

    gain = forward['sol']['data']

    # This actually reorders the gain matrix to conform to the info ch order
    fwd_idx = [fwd_sol_ch_names.index(name) for name in ch_names]
    gain = gain[fwd_idx]
    # Any function calling this helper will be using the returned fwd_info
    # dict, so fwd['sol']['row_names'] becomes obsolete and is NOT re-ordered

    info_idx = [info['ch_names'].index(name) for name in ch_names]
    fwd_info = pick_info(info, info_idx)

    logger.info('Total rank is %d' % n_nzero)

    return fwd_info, gain, noise_cov, whitener, n_nzero
dataset/ETHPy150Open mne-tools/mne-python/mne/minimum_norm/inverse.py/_prepare_forward/original