def test_add_htmls_to_section():
    """Test adding html str to mne report.
    """
    report = Report(info_fname=raw_fname, subject="sample", subjects_dir=subjects_dir)
    html = "<b>MNE-Python is AWESOME</b>"
    caption, section = "html", "html_section"
    report.add_htmls_to_section(html, caption, section)
    idx = report._sectionlabels.index("report_" + section)
    html_compare = report.html[idx]
    assert_true(html in html_compare)
Exemple #2
0
def test_add_htmls_to_section():
    """Test adding html str to mne report."""
    report = Report(info_fname=raw_fname,
                    subject='sample', subjects_dir=subjects_dir)
    html = '<b>MNE-Python is AWESOME</b>'
    caption, section = 'html', 'html_section'
    report.add_htmls_to_section(html, caption, section)
    idx = report._sectionlabels.index('report_' + section)
    html_compare = report.html[idx]
    assert_true(html in html_compare)
    assert_true(repr(report))
Exemple #3
0
epochs_ar, reject_log = ar.fit_transform(this_epoch, return_log=True)

reject_log.plot_epochs(this_epoch, scalings='auto')
epochs_ar.plot(scalings='auto')

epochs_ar.plot_drop_log()  #dropp epochs

#---------------------Report-------------------------------#
###################################################################
name = 'Subject1_report'
report = Report(image_format='png', raw_psd=False, title=name, subject=name)

#generate ICA
fig = ica.plot_components(inst=raw)
report.add_htmls_to_section(
    "Filter parameters: 0.1-50 Hz, fir_design='firwin'; ICA parameters: n_components=40, random_state=97, max_iter=800, method = 'fastica'",
    captions="Description")

report.add_slider_to_section(fig,
                             title="ICA",
                             section="ICA_components",
                             image_format='png')

# generate images with properties
n = list(range(0, 40))
fig_2 = ica.plot_properties(raw, picks=n, psd_args={'fmax': 50})
report.add_slider_to_section(fig_2,
                             title="ICA",
                             section="ICA_components_properties",
                             image_format='png')
report.save('/Users/n/PycharmProjects/application/' + name + '.html',
def compute_ica(raw, subject, n_components=0.99, picks=None, decim=None,
                reject=None, ecg_tmin=-0.5, ecg_tmax=0.5, eog_tmin=-0.5,
                eog_tmax=0.5, n_max_ecg=3, n_max_eog=1,
                n_max_ecg_epochs=200, show=True, img_scale=1.0,
                random_state=None, report=None, artifact_stats=None):
    """Run ICA in raw data

    Parameters
    ----------,
    raw : instance of Raw
        Raw measurements to be decomposed.
    subject : str
        The name of the subject.
    picks : array-like of int, shape(n_channels, ) | None
        Channels to be included. This selection remains throughout the
        initialized ICA solution. If None only good data channels are used.
        Defaults to None.
    n_components : int | float | None | 'rank'
        The number of components used for ICA decomposition. If int, it must be
        smaller then max_pca_components. If None, all PCA components will be
        used. If float between 0 and 1 components can will be selected by the
        cumulative percentage of explained variance.
        If 'rank', the number of components equals the rank estimate.
        Defaults to 0.99.
    decim : int | None
        Increment for selecting each nth time slice. If None, all samples
        within ``start`` and ``stop`` are used. Defalts to None.
    reject : dict | None
        Rejection parameters based on peak to peak amplitude.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
        If reject is None then no rejection is done. You should
        use such parameters to reject big measurement artifacts
        and not EOG for example. It only applies if `inst` is of type Raw.
        Defaults to {'mag': 5e-12}
    ecg_tmin : float
        Start time before ECG event. Defaults to -0.5.
    ecg_tmax : float
        End time after ECG event. Defaults to 0.5.
    eog_tmin : float
        Start time before rog event. Defaults to -0.5.
    eog_tmax : float
        End time after rog event. Defaults to 0.5.
    n_max_ecg : int | None
        The maximum number of ECG components to exclude. Defaults to 3.
    n_max_eog : int | None
        The maximum number of EOG components to exclude. Defaults to 1.
    n_max_ecg_epochs : int
        The maximum number of ECG epochs to use for phase-consistency
        estimation. Defaults to 200.
    show : bool
        Show figure if True
    scale_img : float
        The scaling factor for the report. Defaults to 1.0.
    random_state : None | int | instance of np.random.RandomState
        np.random.RandomState to initialize the FastICA estimation.
        As the estimation is non-deterministic it can be useful to
        fix the seed to have reproducible results. Defaults to None.
    report : instance of Report | None
        The report object. If None, a new report will be generated.
    artifact_stats : None | dict
        A dict that contains info on amplitude ranges of artifacts and
        numbers of events, etc. by channel type.

    Returns
    -------
    ica : instance of ICA
        The ICA solution.
    report : dict
        A dict with an html report ('html') and artifact statistics ('stats').
    """
    if report is None:
        report = Report(subject=subject, title='ICA preprocessing')
    if n_components == 'rank':
        n_components = raw.estimate_rank(picks=picks)
    ica = ICA(n_components=n_components, max_pca_components=None,
              random_state=random_state, max_iter=256)
    ica.fit(raw, picks=picks, decim=decim, reject=reject)

    comment = []
    for ch in ('mag', 'grad', 'eeg'):
        if ch in ica:
            comment += [ch.upper()]
    if len(comment) > 0:
        comment = '+'.join(comment) + ' '
    else:
        comment = ''

    topo_ch_type = 'mag'
    if 'GRAD' in comment and 'MAG' not in comment:
        topo_ch_type = 'grad'
    elif 'EEG' in comment:
        topo_ch_type = 'eeg'

    ###########################################################################
    # 2) identify bad components by analyzing latent sources.

    title = '%s related to %s artifacts (red) ({})'.format(subject)

    # generate ECG epochs use detection via phase statistics
    reject_ = {'mag': 5e-12, 'grad': 5000e-13, 'eeg': 300e-6}
    if reject is not None:
        reject_.update(reject)
    for ch_type in ['mag', 'grad', 'eeg']:
        if ch_type not in ica:
            reject_.pop(ch_type)

    picks_ = np.array([raw.ch_names.index(k) for k in ica.ch_names])
    if 'eeg' in ica:
        if 'ecg' in raw:
            picks_ = np.append(picks_,
                               pick_types(raw.info, meg=False, ecg=True)[0])
        else:
            logger.info('There is no ECG channel, trying to guess ECG from '
                        'magnetormeters')

    if artifact_stats is None:
        artifact_stats = dict()

    ecg_epochs = create_ecg_epochs(raw, tmin=ecg_tmin, tmax=ecg_tmax,
                                   keep_ecg=True, picks=picks_, reject=reject_)

    n_ecg_epochs_found = len(ecg_epochs.events)
    artifact_stats['ecg_n_events'] = n_ecg_epochs_found
    n_max_ecg_epochs = min(n_max_ecg_epochs, n_ecg_epochs_found)
    artifact_stats['ecg_n_used'] = n_max_ecg_epochs

    sel_ecg_epochs = np.arange(n_ecg_epochs_found)
    rng = np.random.RandomState(42)
    rng.shuffle(sel_ecg_epochs)
    ecg_ave = ecg_epochs.average()

    report.add_figs_to_section(ecg_ave.plot(), 'ECG-full', 'artifacts')
    ecg_epochs = ecg_epochs[sel_ecg_epochs[:n_max_ecg_epochs]]
    ecg_ave = ecg_epochs.average()
    report.add_figs_to_section(ecg_ave.plot(), 'ECG-used', 'artifacts')

    _put_artifact_range(artifact_stats, ecg_ave, kind='ecg')

    ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
    if len(ecg_inds) > 0:
        ecg_evoked = ecg_epochs.average()
        del ecg_epochs

        fig = ica.plot_scores(scores, exclude=ecg_inds, labels='ecg',
                              title='', show=show)

        report.add_figs_to_section(fig, 'scores ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

        current_exclude = [e for e in ica.exclude]  # issue #2608 MNE
        fig = ica.plot_sources(raw, ecg_inds, exclude=ecg_inds,
                               title=title % ('components', 'ecg'), show=show)

        report.add_figs_to_section(fig, 'sources ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        fig = ica.plot_components(ecg_inds, ch_type=topo_ch_type,
                                  title='', colorbar=True, show=show)
        report.add_figs_to_section(fig, title % ('sources', 'ecg'),
                                   section=comment + 'ECG', scale=img_scale)
        ica.exclude = current_exclude

        ecg_inds = ecg_inds[:n_max_ecg]
        ica.exclude += ecg_inds
        fig = ica.plot_sources(ecg_evoked, exclude=ecg_inds, show=show)
        report.add_figs_to_section(fig, 'evoked sources ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

        fig = ica.plot_overlay(ecg_evoked, exclude=ecg_inds, show=show)
        report.add_figs_to_section(fig,
                                   'rejection overlay ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

    # detect EOG by correlation
    picks_eog = np.concatenate(
        [picks_, pick_types(raw.info, meg=False, eeg=False, ecg=False,
                            eog=True)])

    eog_epochs = create_eog_epochs(raw, tmin=eog_tmin, tmax=eog_tmax,
                                   picks=picks_eog, reject=reject_)
    artifact_stats['eog_n_events'] = len(eog_epochs.events)
    artifact_stats['eog_n_used'] = artifact_stats['eog_n_events']
    eog_ave = eog_epochs.average()
    report.add_figs_to_section(eog_ave.plot(), 'EOG-used', 'artifacts')
    _put_artifact_range(artifact_stats, eog_ave, kind='eog')

    eog_inds = None
    if len(eog_epochs.events) > 0:
        eog_inds, scores = ica.find_bads_eog(eog_epochs)

    if eog_inds is not None and len(eog_epochs.events) > 0:
        fig = ica.plot_scores(scores, exclude=eog_inds, labels='eog',
                              show=show, title='')
        report.add_figs_to_section(fig, 'scores ({})'.format(subject),
                                   section=comment + 'EOG',
                                   scale=img_scale)

        current_exclude = [e for e in ica.exclude]  # issue #2608 MNE
        fig = ica.plot_sources(raw, eog_inds, exclude=ecg_inds,
                               title=title % ('sources', 'eog'), show=show)
        report.add_figs_to_section(fig, 'sources', section=comment + 'EOG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        fig = ica.plot_components(eog_inds, ch_type=topo_ch_type,
                                  title='', colorbar=True, show=show)
        report.add_figs_to_section(fig, title % ('components', 'eog'),
                                   section=comment + 'EOG', scale=img_scale)
        ica.exclude = current_exclude

        eog_inds = eog_inds[:n_max_eog]
        ica.exclude += eog_inds

        eog_evoked = eog_epochs.average()
        fig = ica.plot_sources(eog_evoked, exclude=eog_inds, show=show)
        report.add_figs_to_section(
            fig, 'evoked sources ({})'.format(subject),
            section=comment + 'EOG', scale=img_scale)

        fig = ica.plot_overlay(eog_evoked, exclude=eog_inds, show=show)
        report.add_figs_to_section(
            fig, 'rejection overlay({})'.format(subject),
            section=comment + 'EOG', scale=img_scale)
    else:
        del eog_epochs

    # check the amplitudes do not change
    if len(ica.exclude) > 0:
        fig = ica.plot_overlay(raw, show=show)  # EOG artifacts remain
        html = _render_components_table(ica)
        report.add_htmls_to_section(
            html, captions='excluded components',
            section='ICA rejection summary (%s)' % ch_type)
        report.add_figs_to_section(
            fig, 'rejection overlay({})'.format(subject),
            section=comment + 'RAW', scale=img_scale)
    return ica, dict(html=report, stats=artifact_stats)
def generateReport(raw, ica, subj_name, subj_path, basename,
                   ecg_evoked, ecg_scores, ecg_inds, ECG_ch_name,
                   eog_evoked, eog_scores, eog_inds, EoG_ch_name):
    from mne.report import Report
    import numpy as np
    import os
    import HTML
    report = Report()

    ICA_title = 'Sources related to %s artifacts (red)'
    is_show = False # visualization

    File_length = str(round(raw.times[-1], 0))
    # report.add_htmls_to_section(htmls=name_html, captions='File path', section='General')
    name_html =  '<h4 style="text-align:left;"> Path:  ' + subj_path + '/' + basename + '.fif' + '</h4>'
    ex_comps_table = [['', 'ICs to exclude'],['ECG', ecg_inds], ['EOG', eog_inds]]
    ex_comps_html = '<h4>' + HTML.table(ex_comps_table) + '</h4>'
    File_length_html = '<h4 style="text-align:left;">' + 'File length: ' + File_length + ' seconds' + '</h4>'
    report.add_htmls_to_section(htmls=name_html + File_length_html + ex_comps_html, captions='General info', section='General info')
    # --------------------- Generate report for ECG ---------------------------------------- #
    fig1 = ica.plot_scores(
        ecg_scores, exclude=ecg_inds, title=ICA_title % 'ecg', show=is_show)
    # Pick the five largest ecg_scores and plot them
    show_picks = np.abs(ecg_scores).argsort()[::-1][:5]

    # Plot estimated latent sources given the unmixing matrix.

    # topoplot of unmixing matrix columns
    fig2 = ica.plot_components(
        show_picks, title=ICA_title % 'ecg', colorbar=True, show=is_show)

    

    # plot ECG sources + selection
    fig3 = ica.plot_sources(ecg_evoked, exclude=ecg_inds, show=is_show)
    fig = [fig1, fig2, fig3]
    report.add_figs_to_section(fig, captions=['Scores of ICs related to ECG',
                                              'TopoMap of ICs (ECG)',
                                              'Time-locked ECG sources'], section='ICA - ECG')
    # ----------------------------------- end generate report for ECG ------------------------------- #


    # --------------------------------- Generate report for EoG --------------------------------------------- #

    # check how many EoG ch we have
    if set(EoG_ch_name.split(',')).issubset(set(raw.info['ch_names'])):
        fig4 = ica.plot_scores(
            eog_scores, exclude=eog_inds, title=ICA_title % 'eog', show=is_show)
        report.add_figs_to_section(fig4, captions=['Scores of ICs related to EOG'],
                                   section='ICA - EOG')
        rs = np.shape(eog_scores)
        if len(rs) > 1:
            rr = rs[0]
            show_picks = [np.abs(eog_scores[i][:]).argsort()[::-1][:5]
                          for i in range(rr)]
            for i in range(rr):
                fig5 = ica.plot_components(show_picks[i][:], title=ICA_title % 'eog',
                                           colorbar=True, show=is_show)  # ICA nel tempo
                fig = [fig5]
                report.add_figs_to_section(fig, captions=['Scores of ICs related to EOG'],
                                           section='ICA - EOG')
        else:
            show_picks = np.abs(eog_scores).argsort()[::-1][:5]
            fig5 = ica.plot_components(
                show_picks, title=ICA_title % 'eog', colorbar=True, show=is_show)
            fig = [fig5]
            report.add_figs_to_section(fig, captions=['TopoMap of ICs (EOG)', ],
                                       section='ICA - EOG')
        fig9 = ica.plot_sources(eog_evoked, exclude=eog_inds, show=is_show)  # plot EOG sources + selection
        # fig10 = ica.plot_overlay(eog_evoked, exclude=eog_inds, show=is_show)  # plot EOG cleaning

        # fig = [fig9, fig10]
        fig = [fig9]
        report.add_figs_to_section(fig, captions=['Time-locked EOG sources'], section = 'ICA - EOG')
   # -------------------- end generate report for EoG -------------------------------------------------------- #
    # import ipdb; ipdb.set_trace()
    IC_nums = range(ica.n_components_)
    fig = ica.plot_components(picks=IC_nums, show=False)
    report.add_figs_to_section(fig, captions=['All IC topographies'], section='ICA - muscles')

    psds = []
    captions_psd = []
    ica_src = ica.get_sources(raw)
    for iIC in IC_nums:
        fig = ica_src.plot_psd(tmax=None, picks=[iIC], fmax=140, show=False)
        fig.set_figheight(3)
        fig.set_figwidth(5)
        psds.append(fig)
        captions_psd.append('IC #' + str(iIC))
    # report.add_slider_to_section(figs=psds, captions=captions_psd, title='', section='ICA - muscles')
    report.add_figs_to_section(figs=psds, captions=captions_psd, section='ICA - muscles')
    report_filename = os.path.join(subj_path, basename + "-report.html")
    print '******* ' + report_filename
    report.save(report_filename, open_browser=False, overwrite=True)
Exemple #6
0
percleft_cue = []
percleft_shock = []

for p in part:
    # ______________________________________________________
    # Make out dir
    outdir = opj('/data/derivatives', p, 'eeg')
    if not os.path.exists(outdir):
        os.mkdir(outdir)

    # _______________________________________________________
    # Initialise MNE report
    report = Report(verbose=False, subject=p, title='TFR report for part ' + p)

    report.add_htmls_to_section(htmls=pprint.pformat(param),
                                captions='Parameters',
                                section='Parameters')

    # ______________________________________________________
    # Load cleaned raw file
    raw = mne.io.read_raw_fif(opj(outdir,
                                  p + '_task-fearcond_cleanedeeg_raw.fif'),
                              preload=True)

    # ______________________________________________________
    # Additional filter
    raw = raw.filter(l_freq=None, h_freq=200)

    # Load trial info in scr data
    events = pd.read_csv(layout.get(subject=p[-2:],
                                    extension='tsv',
def compute_ica(raw,
                subject,
                n_components=0.99,
                picks=None,
                decim=None,
                reject=None,
                ecg_tmin=-0.5,
                ecg_tmax=0.5,
                eog_tmin=-0.5,
                eog_tmax=0.5,
                n_max_ecg=3,
                n_max_eog=1,
                n_max_ecg_epochs=200,
                show=True,
                img_scale=1.0,
                random_state=None,
                report=None,
                artifact_stats=None):
    """Run ICA in raw data

    Parameters
    ----------,
    raw : instance of Raw
        Raw measurements to be decomposed.
    subject : str
        The name of the subject.
    picks : array-like of int, shape(n_channels, ) | None
        Channels to be included. This selection remains throughout the
        initialized ICA solution. If None only good data channels are used.
        Defaults to None.
    n_components : int | float | None | 'rank'
        The number of components used for ICA decomposition. If int, it must be
        smaller then max_pca_components. If None, all PCA components will be
        used. If float between 0 and 1 components can will be selected by the
        cumulative percentage of explained variance.
        If 'rank', the number of components equals the rank estimate.
        Defaults to 0.99.
    decim : int | None
        Increment for selecting each nth time slice. If None, all samples
        within ``start`` and ``stop`` are used. Defalts to None.
    reject : dict | None
        Rejection parameters based on peak to peak amplitude.
        Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
        If reject is None then no rejection is done. You should
        use such parameters to reject big measurement artifacts
        and not EOG for example. It only applies if `inst` is of type Raw.
        Defaults to {'mag': 5e-12}
    ecg_tmin : float
        Start time before ECG event. Defaults to -0.5.
    ecg_tmax : float
        End time after ECG event. Defaults to 0.5.
    eog_tmin : float
        Start time before rog event. Defaults to -0.5.
    eog_tmax : float
        End time after rog event. Defaults to 0.5.
    n_max_ecg : int | None
        The maximum number of ECG components to exclude. Defaults to 3.
    n_max_eog : int | None
        The maximum number of EOG components to exclude. Defaults to 1.
    n_max_ecg_epochs : int
        The maximum number of ECG epochs to use for phase-consistency
        estimation. Defaults to 200.
    show : bool
        Show figure if True
    scale_img : float
        The scaling factor for the report. Defaults to 1.0.
    random_state : None | int | instance of np.random.RandomState
        np.random.RandomState to initialize the FastICA estimation.
        As the estimation is non-deterministic it can be useful to
        fix the seed to have reproducible results. Defaults to None.
    report : instance of Report | None
        The report object. If None, a new report will be generated.
    artifact_stats : None | dict
        A dict that contains info on amplitude ranges of artifacts and
        numbers of events, etc. by channel type.

    Returns
    -------
    ica : instance of ICA
        The ICA solution.
    report : dict
        A dict with an html report ('html') and artifact statistics ('stats').
    """
    if report is None:
        report = Report(subject=subject, title='ICA preprocessing')
    if n_components == 'rank':
        n_components = raw.estimate_rank(picks=picks)
    ica = ICA(n_components=n_components,
              max_pca_components=None,
              random_state=random_state,
              max_iter=256)
    ica.fit(raw, picks=picks, decim=decim, reject=reject)

    comment = []
    for ch in ('mag', 'grad', 'eeg'):
        if ch in ica:
            comment += [ch.upper()]
    if len(comment) > 0:
        comment = '+'.join(comment) + ' '
    else:
        comment = ''

    topo_ch_type = 'mag'
    if 'GRAD' in comment and 'MAG' not in comment:
        topo_ch_type = 'grad'
    elif 'EEG' in comment:
        topo_ch_type = 'eeg'

    ###########################################################################
    # 2) identify bad components by analyzing latent sources.

    title = '%s related to %s artifacts (red) ({})'.format(subject)

    # generate ECG epochs use detection via phase statistics
    reject_ = {'mag': 5e-12, 'grad': 5000e-13, 'eeg': 300e-6}
    if reject is not None:
        reject_.update(reject)
    for ch_type in ['mag', 'grad', 'eeg']:
        if ch_type not in ica:
            reject_.pop(ch_type)

    picks_ = np.array([raw.ch_names.index(k) for k in ica.ch_names])
    if 'eeg' in ica:
        if 'ecg' in raw:
            picks_ = np.append(picks_,
                               pick_types(raw.info, meg=False, ecg=True)[0])
        else:
            logger.info('There is no ECG channel, trying to guess ECG from '
                        'magnetormeters')

    if artifact_stats is None:
        artifact_stats = dict()

    ecg_epochs = create_ecg_epochs(raw,
                                   tmin=ecg_tmin,
                                   tmax=ecg_tmax,
                                   keep_ecg=True,
                                   picks=picks_,
                                   reject=reject_)

    n_ecg_epochs_found = len(ecg_epochs.events)
    artifact_stats['ecg_n_events'] = n_ecg_epochs_found
    n_max_ecg_epochs = min(n_max_ecg_epochs, n_ecg_epochs_found)
    artifact_stats['ecg_n_used'] = n_max_ecg_epochs

    sel_ecg_epochs = np.arange(n_ecg_epochs_found)
    rng = np.random.RandomState(42)
    rng.shuffle(sel_ecg_epochs)
    ecg_ave = ecg_epochs.average()

    report.add_figs_to_section(ecg_ave.plot(), 'ECG-full', 'artifacts')
    ecg_epochs = ecg_epochs[sel_ecg_epochs[:n_max_ecg_epochs]]
    ecg_ave = ecg_epochs.average()
    report.add_figs_to_section(ecg_ave.plot(), 'ECG-used', 'artifacts')

    _put_artifact_range(artifact_stats, ecg_ave, kind='ecg')

    ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
    if len(ecg_inds) > 0:
        ecg_evoked = ecg_epochs.average()
        del ecg_epochs

        fig = ica.plot_scores(scores,
                              exclude=ecg_inds,
                              labels='ecg',
                              title='',
                              show=show)

        report.add_figs_to_section(fig,
                                   'scores ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

        current_exclude = [e for e in ica.exclude]  # issue #2608 MNE
        fig = ica.plot_sources(raw,
                               ecg_inds,
                               exclude=ecg_inds,
                               title=title % ('components', 'ecg'),
                               show=show)

        report.add_figs_to_section(fig,
                                   'sources ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        fig = ica.plot_components(ecg_inds,
                                  ch_type=topo_ch_type,
                                  title='',
                                  colorbar=True,
                                  show=show)
        report.add_figs_to_section(fig,
                                   title % ('sources', 'ecg'),
                                   section=comment + 'ECG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        ecg_inds = ecg_inds[:n_max_ecg]
        ica.exclude += ecg_inds
        fig = ica.plot_sources(ecg_evoked, exclude=ecg_inds, show=show)
        report.add_figs_to_section(fig,
                                   'evoked sources ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

        fig = ica.plot_overlay(ecg_evoked, exclude=ecg_inds, show=show)
        report.add_figs_to_section(fig,
                                   'rejection overlay ({})'.format(subject),
                                   section=comment + 'ECG',
                                   scale=img_scale)

    # detect EOG by correlation
    picks_eog = np.concatenate([
        picks_,
        pick_types(raw.info, meg=False, eeg=False, ecg=False, eog=True)
    ])

    eog_epochs = create_eog_epochs(raw,
                                   tmin=eog_tmin,
                                   tmax=eog_tmax,
                                   picks=picks_eog,
                                   reject=reject_)
    artifact_stats['eog_n_events'] = len(eog_epochs.events)
    artifact_stats['eog_n_used'] = artifact_stats['eog_n_events']
    eog_ave = eog_epochs.average()
    report.add_figs_to_section(eog_ave.plot(), 'EOG-used', 'artifacts')
    _put_artifact_range(artifact_stats, eog_ave, kind='eog')

    eog_inds = None
    if len(eog_epochs.events) > 0:
        eog_inds, scores = ica.find_bads_eog(eog_epochs)

    if eog_inds is not None and len(eog_epochs.events) > 0:
        fig = ica.plot_scores(scores,
                              exclude=eog_inds,
                              labels='eog',
                              show=show,
                              title='')
        report.add_figs_to_section(fig,
                                   'scores ({})'.format(subject),
                                   section=comment + 'EOG',
                                   scale=img_scale)

        current_exclude = [e for e in ica.exclude]  # issue #2608 MNE
        fig = ica.plot_sources(raw,
                               eog_inds,
                               exclude=ecg_inds,
                               title=title % ('sources', 'eog'),
                               show=show)
        report.add_figs_to_section(fig,
                                   'sources',
                                   section=comment + 'EOG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        fig = ica.plot_components(eog_inds,
                                  ch_type=topo_ch_type,
                                  title='',
                                  colorbar=True,
                                  show=show)
        report.add_figs_to_section(fig,
                                   title % ('components', 'eog'),
                                   section=comment + 'EOG',
                                   scale=img_scale)
        ica.exclude = current_exclude

        eog_inds = eog_inds[:n_max_eog]
        ica.exclude += eog_inds

        eog_evoked = eog_epochs.average()
        fig = ica.plot_sources(eog_evoked, exclude=eog_inds, show=show)
        report.add_figs_to_section(fig,
                                   'evoked sources ({})'.format(subject),
                                   section=comment + 'EOG',
                                   scale=img_scale)

        fig = ica.plot_overlay(eog_evoked, exclude=eog_inds, show=show)
        report.add_figs_to_section(fig,
                                   'rejection overlay({})'.format(subject),
                                   section=comment + 'EOG',
                                   scale=img_scale)
    else:
        del eog_epochs

    # check the amplitudes do not change
    if len(ica.exclude) > 0:
        fig = ica.plot_overlay(raw, show=show)  # EOG artifacts remain
        html = _render_components_table(ica)
        report.add_htmls_to_section(html,
                                    captions='excluded components',
                                    section='ICA rejection summary (%s)' %
                                    ch_type)
        report.add_figs_to_section(fig,
                                   'rejection overlay({})'.format(subject),
                                   section=comment + 'RAW',
                                   scale=img_scale)
    return ica, dict(html=report, stats=artifact_stats)
Exemple #8
0
    # _______________________________________________________
    # Make fslevel part dir
    pdir = opj(outdir, p, 'eeg')
    if not os.path.exists(pdir):
        os.mkdir(pdir)

    # _______________________________________________________
    # Initialise MNE report
    report = Report(verbose=False, subject=p,
                    title='EEG report for part ' + p)

    # report.add_htmls_to_section(
    #     htmls=part.comments[p], captions='Comments', section='Comments')
    report.add_htmls_to_section(
        htmls=pprint.pformat(param),
        captions='Parameters',
        section='Parameters')

    # ______________________________________________________
    # Load EEG file
    f = layout.get(subject=p[-2:], extension='bdf', return_type='filename')[0]
    raw = mne.io.read_raw_bdf(f, verbose=False,
                              eog=param['eogchan'],
                              exclude=param['dropchan'],
                              preload=True)


    # Rename external channels
    raw.rename_channels(param['renamechan'])

    events = pd.read_csv(layout.get(subject=p[-2:], extension='tsv',