当前位置: 首页>>代码示例>>Python>>正文


Python Report.add_figs_to_section方法代码示例

本文整理汇总了Python中mne.report.Report.add_figs_to_section方法的典型用法代码示例。如果您正苦于以下问题:Python Report.add_figs_to_section方法的具体用法?Python Report.add_figs_to_section怎么用?Python Report.add_figs_to_section使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mne.report.Report的用法示例。


在下文中一共展示了Report.add_figs_to_section方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_render_add_sections

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt

    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'], scale=1.2,
                               image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    # Check deprecation of add_section
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.add_section(figs=fig,
                           captions=['evoked response'])
        assert_true(w[0].category == DeprecationWarning)
开发者ID:LizetteH,项目名称:mne-python,代码行数:31,代码来源:test_report.py

示例2: test_render_add_sections

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    tempdir = _TempDir()
    import matplotlib.pyplot as plt
    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'], scale=1.2,
                               image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=0, image_format='svg')
    assert_raises(ValueError, report.add_figs_to_section, figs=fig,
                  captions=['foo'], scale=1e-10, image_format='svg')
    # need to recreate because calls above change size
    fig = plt.plot([1, 2], [1, 2])[0].figure

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    evoked = read_evokeds(evoked_fname, condition='Left Auditory',
                          baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject='sample',
                     subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions='random image', scale=1.2)
开发者ID:Lem97,项目名称:mne-python,代码行数:37,代码来源:test_report.py

示例3: test_remove

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_remove():
    """Test removing figures from a report."""
    r = Report()
    fig1, fig2 = _get_example_figures()
    r.add_figs_to_section(fig1, 'figure1', 'mysection')
    r.add_slider_to_section([fig1, fig2], title='figure1',
                            section='othersection')
    r.add_figs_to_section(fig2, 'figure1', 'mysection')
    r.add_figs_to_section(fig2, 'figure2', 'mysection')

    # Test removal by caption
    r2 = copy.deepcopy(r)
    removed_index = r2.remove(caption='figure1')
    assert removed_index == 2
    assert len(r2.html) == 3
    assert r2.html[0] == r.html[0]
    assert r2.html[1] == r.html[1]
    assert r2.html[2] == r.html[3]

    # Test restricting to section
    r2 = copy.deepcopy(r)
    removed_index = r2.remove(caption='figure1', section='othersection')
    assert removed_index == 1
    assert len(r2.html) == 3
    assert r2.html[0] == r.html[0]
    assert r2.html[1] == r.html[2]
    assert r2.html[2] == r.html[3]

    # Test removal of empty sections
    r2 = copy.deepcopy(r)
    r2.remove(caption='figure1', section='othersection')
    assert r2.sections == ['mysection']
    assert r2._sectionvars == {'mysection': 'report_mysection'}
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:35,代码来源:test_report.py

示例4: test_render_add_sections

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_render_add_sections():
    """Test adding figures/images to section.
    """
    from PIL import Image

    tempdir = _TempDir()
    import matplotlib.pyplot as plt

    report = Report(subjects_dir=subjects_dir)
    # Check add_figs_to_section functionality
    fig = plt.plot([1, 2], [1, 2])[0].figure
    report.add_figs_to_section(
        figs=fig, captions=["evoked response"], scale=1.2, image_format="svg"  # test non-list input
    )
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig], captions="H")
    assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=["foo"], scale=0, image_format="svg")
    assert_raises(ValueError, report.add_figs_to_section, figs=fig, captions=["foo"], scale=1e-10, image_format="svg")
    # need to recreate because calls above change size
    fig = plt.plot([1, 2], [1, 2])[0].figure

    # Check add_images_to_section with png and then gif
    img_fname = op.join(tempdir, "testimage.png")
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname], captions=["evoked response"])

    im = Image.open(img_fname)
    op.join(tempdir, "testimage.gif")
    im.save(img_fname)  # matplotlib does not support gif
    report.add_images_to_section(fnames=[img_fname], captions=["evoked response"])

    assert_raises(ValueError, report.add_images_to_section, fnames=[img_fname, img_fname], captions="H")

    assert_raises(ValueError, report.add_images_to_section, fnames=["foobar.xxx"], captions="H")

    evoked = read_evokeds(evoked_fname, condition="Left Auditory", baseline=(-0.2, 0.0))
    fig = plot_trans(evoked.info, trans_fname, subject="sample", subjects_dir=subjects_dir)

    report.add_figs_to_section(figs=fig, captions="random image", scale=1.2)  # test non-list input
开发者ID:rajegannathan,项目名称:grasp-lift-eeg-cat-dog-solution-updated,代码行数:40,代码来源:test_report.py

示例5: test_add_or_replace

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_add_or_replace():
    """Test replacing existing figures in a report."""
    r = Report()
    fig1, fig2 = _get_example_figures()
    r.add_figs_to_section(fig1, 'duplicate', 'mysection')
    r.add_figs_to_section(fig1, 'duplicate', 'mysection')
    r.add_figs_to_section(fig1, 'duplicate', 'othersection')
    r.add_figs_to_section(fig2, 'nonduplicate', 'mysection')
    # By default, replace=False, so all figures should be there
    assert len(r.html) == 4

    old_r = copy.deepcopy(r)

    # Re-add fig1 with replace=True, it should overwrite the last occurrence of
    # fig1 in section 'mysection'.
    r.add_figs_to_section(fig2, 'duplicate', 'mysection', replace=True)
    assert len(r.html) == 4
    assert r.html[1] != old_r.html[1]  # This figure should have changed
    # All other figures should be the same
    assert r.html[0] == old_r.html[0]
    assert r.html[2] == old_r.html[2]
    assert r.html[3] == old_r.html[3]
开发者ID:kambysese,项目名称:mne-python,代码行数:24,代码来源:test_report.py

示例6: test_render_report

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_render_report():
    """Test rendering -*.fif files for mne report."""
    tempdir = _TempDir()
    raw_fname_new = op.join(tempdir, 'temp_raw.fif')
    ms_fname_new = op.join(tempdir, 'temp_ms_raw.fif')
    event_fname_new = op.join(tempdir, 'temp_raw-eve.fif')
    cov_fname_new = op.join(tempdir, 'temp_raw-cov.fif')
    fwd_fname_new = op.join(tempdir, 'temp_raw-fwd.fif')
    inv_fname_new = op.join(tempdir, 'temp_raw-inv.fif')
    for a, b in [[raw_fname, raw_fname_new],
                 [ms_fname, ms_fname_new],
                 [event_fname, event_fname_new],
                 [cov_fname, cov_fname_new],
                 [fwd_fname, fwd_fname_new],
                 [inv_fname, inv_fname_new]]:
        shutil.copyfile(a, b)

    # create and add -epo.fif and -ave.fif files
    epochs_fname = op.join(tempdir, 'temp-epo.fif')
    evoked_fname = op.join(tempdir, 'temp-ave.fif')
    # Speed it up by picking channels
    raw = read_raw_fif(raw_fname_new, preload=True)
    raw.pick_channels(['MEG 0111', 'MEG 0121'])
    raw.del_proj()
    epochs = Epochs(raw, read_events(event_fname), 1, -0.2, 0.2)
    epochs.save(epochs_fname)
    # This can take forever (stall Travis), so let's make it fast
    # Also, make sure crop range is wide enough to avoid rendering bug
    epochs.average().crop(0.1, 0.2).save(evoked_fname)

    report = Report(info_fname=raw_fname_new, subjects_dir=subjects_dir)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.parse_folder(data_path=tempdir, on_error='raise')
    assert_true(len(w) >= 1)
    assert_true(repr(report))

    # Check correct paths and filenames
    fnames = glob.glob(op.join(tempdir, '*.fif'))
    for fname in fnames:
        assert_true(op.basename(fname) in
                    [op.basename(x) for x in report.fnames])
        assert_true(''.join(report.html).find(op.basename(fname)) != -1)

    assert_equal(len(report.fnames), len(fnames))
    assert_equal(len(report.html), len(report.fnames))
    assert_equal(len(report.fnames), len(report))

    # Check saving functionality
    report.data_path = tempdir
    fname = op.join(tempdir, 'report.html')
    report.save(fname=fname, open_browser=False)
    assert_true(op.isfile(fname))
    with open(fname, 'rb') as fid:
        html = fid.read().decode('utf-8')
    assert '(MaxShield on)' in html

    assert_equal(len(report.html), len(fnames))
    assert_equal(len(report.html), len(report.fnames))

    # Check saving same report to new filename
    report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False)
    assert_true(op.isfile(op.join(tempdir, 'report2.html')))

    # Check overwriting file
    report.save(fname=op.join(tempdir, 'report.html'), open_browser=False,
                overwrite=True)
    assert_true(op.isfile(op.join(tempdir, 'report.html')))

    # Check pattern matching with multiple patterns
    pattern = ['*raw.fif', '*eve.fif']
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.parse_folder(data_path=tempdir, pattern=pattern)
    assert_true(len(w) >= 1)
    assert_true(repr(report))

    fnames = glob.glob(op.join(tempdir, '*.raw')) + \
        glob.glob(op.join(tempdir, '*.raw'))
    for fname in fnames:
        assert_true(op.basename(fname) in
                    [op.basename(x) for x in report.fnames])
        assert_true(''.join(report.html).find(op.basename(fname)) != -1)

    assert_raises(ValueError, Report, image_format='foo')
    assert_raises(ValueError, Report, image_format=None)

    # SVG rendering
    report = Report(info_fname=raw_fname_new, subjects_dir=subjects_dir,
                    image_format='svg')
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.parse_folder(data_path=tempdir, on_error='raise')

    # ndarray support smoke test
    report.add_figs_to_section(np.zeros((2, 3, 3)), 'caption', 'section')
开发者ID:HSMin,项目名称:mne-python,代码行数:98,代码来源:test_report.py

示例7: preprocess_ICA_fif_to_ts

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]

#.........这里部分代码省略.........
        ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5,
                                       picks=select_sensors)

    # ICA for ECG artifact
    # threshold=0.25 come default
    ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')
    print scores
    print '\n len ecg_inds *** ' + str(len(ecg_inds)) + '***\n'
    if len(ecg_inds) > 0:
        ecg_evoked = ecg_epochs.average()

        fig1 = ica.plot_scores(scores, exclude=ecg_inds,
                               title=ICA_title % 'ecg', show=is_show)

        show_picks = np.abs(scores).argsort()[::-1][:5] # Pick the five largest scores and plot them

        # Plot estimated latent sources given the unmixing matrix.
        #ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=ICA_title % 'ecg', show=is_show)
        t_start = 0
        t_stop = 30 # take the fist 30s
        fig2 = ica.plot_sources(raw, show_picks, exclude=ecg_inds, title=ICA_title % 'ecg' + ' in 30s' 
                                            ,start = t_start, stop  = t_stop, show=is_show)

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

        ecg_inds = ecg_inds[:n_max_ecg]
        ica.exclude += ecg_inds
    
        fig4 = ica.plot_sources(ecg_evoked, exclude=ecg_inds, show=is_show)  # plot ECG sources + selection
        fig5 = ica.plot_overlay(ecg_evoked, exclude=ecg_inds, show=is_show)  # plot ECG cleaning
    
        fig = [fig1, fig2, fig3, fig4, fig5]
        report.add_figs_to_section(fig, captions=['Scores of ICs related to ECG',
                                                  'Time Series plots of ICs (ECG)',
                                                  'TopoMap of ICs (ECG)', 
                                                  'Time-locked ECG sources', 
                                                  'ECG overlay'], section = 'ICA - ECG')    
    
    # check if EoG_ch_name is in the raw channels
    # if EoG_ch_name is empty if data_type is fif, ICA routine automatically looks for EEG61, EEG62
    # otherwise if data_type is ds we jump this step
    if not EoG_ch_name and data_type=='ds':
        eog_inds = []
    else:
        if EoG_ch_name in raw.info['ch_names']:        
            ### ICA for eye blink artifact - detect EOG by correlation
            eog_inds, scores = ica.find_bads_eog(raw, ch_name = EoG_ch_name)
        else:
            eog_inds, scores = ica.find_bads_eog(raw)

    if len(eog_inds) > 0:  
        
        fig6 = ica.plot_scores(scores, exclude=eog_inds, title=ICA_title % 'eog', show=is_show)
        report.add_figs_to_section(fig6, captions=['Scores of ICs related to EOG'], 
                           section = 'ICA - EOG')
                           
        # check how many EoG ch we have
        rs = np.shape(scores)
        if len(rs)>1:
            rr = rs[0]
            show_picks = [np.abs(scores[i][:]).argsort()[::-1][:5] for i in range(rr)]
            for i in range(rr):
                fig7 = ica.plot_sources(raw, show_picks[i][:], exclude=eog_inds, 
                                    start = raw.times[0], stop  = raw.times[-1], 
                                    title=ICA_title % 'eog',show=is_show)       
开发者ID:davidmeunier79,项目名称:neuropype_ephy,代码行数:70,代码来源:preproc.py

示例8: preprocess_set_ICA_comp_fif_to_ts

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def preprocess_set_ICA_comp_fif_to_ts(fif_file, n_comp_exclude, l_freq, h_freq,
                                      down_sfreq, is_sensor_space):
    import os
    import numpy as np
    import sys

    import mne
    from mne.io import Raw
    from mne.preprocessing import read_ica
    from mne.report import Report

    from nipype.utils.filemanip import split_filename as split_f

    report = Report()

    subj_path, basename, ext = split_f(fif_file)
    (data_path,  sbj_name) = os.path.split(subj_path)

    print '*** SBJ %s' % sbj_name + '***'

#    n_session = int(filter(str.isdigit, basename))
#    print '*** n session = %d' % n_session + '***'

    # Read raw
    raw = Raw(fif_file, preload=True)

    # select sensors
    select_sensors = mne.pick_types(raw.info, meg=True, ref_meg=False,
                                    exclude='bads')
    picks_meeg = mne.pick_types(raw.info, meg=True, eeg=True,
                                exclude='bads')

    # save electrode locations
    sens_loc = [raw.info['chs'][i]['loc'][:3] for i in select_sensors]
    sens_loc = np.array(sens_loc)

    channel_coords_file = os.path.abspath("correct_channel_coords.txt")
    np.savetxt(channel_coords_file, sens_loc, fmt='%s')

    # save electrode names
    sens_names = np.array([raw.ch_names[pos] for pos in select_sensors],
                          dtype="str")

    channel_names_file = os.path.abspath("correct_channel_names.txt")
    np.savetxt(channel_names_file, sens_names, fmt='%s')

    # filtering + downsampling
    # TODO n_jobs=8
    raw.filter(l_freq=l_freq, h_freq=h_freq, picks=picks_meeg,
               method='iir',n_jobs=8)
#    raw.resample(sfreq=down_sfreq, npad=0)

    # load ICA
    is_show = False  # visualization
    ica_filename = os.path.join(subj_path, basename + '-ica.fif')
    if os.path.exists(ica_filename) is False:
        print "$$$ Warning, no %s found" % ica_filename
        sys.exit()
    else:
        ica = read_ica(ica_filename)

    # AP 210316
    '''
    print '*** ica.exclude before set components= ', ica.exclude
    if n_comp_exclude.has_key(sbj_name):
        print '*** ICA to be excluded for sbj %s ' % sbj_name + ' ' + str(n_comp_exclude[sbj_name]) + '***'
        matrix_c_ICA = n_comp_exclude[sbj_name]

        if not matrix_c_ICA[n_session-1]:
            print 'no ICA'
        else:
            print '*** ICA to be excluded for session %d ' %n_session + ' ' + str(matrix_c_ICA[n_session-1]) + '***'        
    ica.exclude = matrix_c_ICA[n_session-1]
    '''
    # AP new dict
    print '*** ica.exclude before set components= ', ica.exclude
    if n_comp_exclude.has_key(sbj_name):
        print '*** ICA to be excluded for sbj %s ' % sbj_name + ' ' + str(n_comp_exclude[sbj_name]) + '***'
        session_dict = n_comp_exclude[sbj_name]
        session_names = session_dict.keys()

        componentes = []
        for s in session_names:
            if basename.find(s) > -1:
                componentes = session_dict[s]
                break

        if len(componentes) == 0:
            print '\n no ICA to be excluded \n'
        else:
            print '\n *** ICA to be excluded for session %s ' % s + \
                    ' ' + str(componentes) + ' *** \n'

    ica.exclude = componentes

    print '\n *** ica.exclude after set components = ', ica.exclude

    fig1 = ica.plot_overlay(raw, show=is_show)
    report.add_figs_to_section(fig1, captions=['Signal'],
                               section='Signal quality')
#.........这里部分代码省略.........
开发者ID:davidmeunier79,项目名称:neuropype_ephy,代码行数:103,代码来源:preproc.py

示例9: check_apply_filter

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def check_apply_filter(raw, subject, filter_params=None,
                       notch_filter_params=None, plot_fmin=None,
                       plot_fmax=None, n_jobs=1, figsize=None, show=True,
                       report=None, img_scale=1.0):
    """Apply filtering and save diagnostic plots

    Parameters
    ----------
    raw : instance of Raw
        Raw measurements to be decomposed.
    subject : str
        The name of the subject.
    filter_params : dict | list of dict | None
        The parametrs passed to raw.filter. If list, raw.filter will be
        invoked len(filter_params) times. Defaults to None. If None, expands
        to:

        dict(l_freq=0.5, h_freq=200, n_jobs=n_jobs,
             method='fft', l_trans_bandwidth=0.1, h_trans_bandwidth=0.5)
    notch_filter_params : dict | list of dict | None
        The parametrs passed to raw.notch_filter. Defaults to None.
        If None, expands to:
    n_jobs : int
        The number of CPUs to use in parallel.
    figsize : tuple of int
        The figsize in inches. See matplotlib documentation.
    show : bool
        Show figure if True
    scale_img : float
        The scaling factor for the report. Defaults to 1.0.
    report : instance of Report | None
        The report object. If None, a new report will be generated.
    """
    _default_filter_params = dict(l_freq=0.5, h_freq=200, n_jobs=n_jobs,
                                  method='fft',
                                  l_trans_bandwidth=0.1, h_trans_bandwidth=0.5)
    if filter_params is None:
        filter_params = _default_filter_params
    if not isinstance(filter_params, (list, tuple)):
        filter_params = [filter_params]
    if notch_filter_params is None:
        notch_filter_params = dict(freqs=(50, 100, 150, 200, 250,),
                                   method='fft')
    if report is None:
        report = Report(subject)

    notch_filter_params.update(n_jobs=n_jobs)
    picks_list, n_rows, fig, axes = _prepare_filter_plot(raw, figsize)

    iter_plot = zip(axes, picks_list)
    fmin, fmax = plot_fmin or 0, plot_fmax or raw.info['lowpass'] + 20

    ###########################################################################
    # plot before filter
    for ax, (picks, ch_type) in iter_plot:

        raw.plot_psd(fmin=fmin, fmax=fmax, ax=ax,
                     picks=picks, color='black', show=show)
        first_line = ax.get_lines()[0]
        first_line.set_label('{} - raw'.format(ch_type))
        ax.set_ylabel('Power (dB)')
        ax.grid(True)
        ax.set_title(ch_type)

    ###########################################################################
    # filter

    # Note. It turns out to be safer to first run the notch filter.
    # Ohterwise crazy notch resonance with some filter settings.
    raw.notch_filter(**notch_filter_params)

    for filter_params_ in filter_params:
        final_filter_params_ = deepcopy(_default_filter_params)
        final_filter_params_.update(filter_params_)
        final_filter_params_.update({'n_jobs': n_jobs})
        raw.filter(**final_filter_params_)

    ###########################################################################
    # plot after filter
    for ax, (picks, ch_type) in iter_plot:

        raw.plot_psd(fmin=fmin, fmax=fmax, ax=ax,
                     picks=picks, color='red', show=show)
        second_line = ax.get_lines()[1]
        second_line.set_label('{} - filtered'.format(ch_type))
        ax.legend(loc='best')

    fig.suptitle('Multitaper PSD')
    report.add_figs_to_section(fig, 'filter PSD spectra {}'.format(subject),
                               'FILTER', scale=img_scale)
    return fig, report
开发者ID:christianbrodbeck,项目名称:meeg-preprocessing,代码行数:93,代码来源:preprocessing.py

示例10: compute_ica

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]

#.........这里部分代码省略.........
    # 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
开发者ID:christianbrodbeck,项目名称:meeg-preprocessing,代码行数:70,代码来源:preprocessing.py

示例11: gen_html_report

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def gen_html_report(p, subjects, structurals, run_indices=None):
    """Generates HTML reports"""
    import matplotlib.pyplot as plt
    from ._mnefun import (_load_trans_to, plot_good_coils, _head_pos_annot,
                          _get_bem_src_trans, safe_inserter, _prebad,
                          _load_meg_bads, mlab_offscreen, _fix_raw_eog_cals,
                          _handle_dict, _get_t_window, plot_chpi_snr_raw)
    if run_indices is None:
        run_indices = [None] * len(subjects)
    style = {'axes.spines.right': 'off', 'axes.spines.top': 'off',
             'axes.grid': True}
    time_kwargs = dict()
    if 'time_unit' in mne.fixes._get_args(mne.viz.plot_evoked):
        time_kwargs['time_unit'] = 's'
    for si, subj in enumerate(subjects):
        struc = structurals[si]
        report = Report(verbose=False)
        print('  Processing subject %s/%s (%s)'
              % (si + 1, len(subjects), subj))

        # raw
        fnames = get_raw_fnames(p, subj, 'raw', erm=False, add_splits=False,
                                run_indices=run_indices[si])
        for fname in fnames:
            if not op.isfile(fname):
                raise RuntimeError('Cannot create reports until raw data '
                                   'exist, missing:\n%s' % fname)
        raw = [read_raw_fif(fname, allow_maxshield='yes')
               for fname in fnames]
        _fix_raw_eog_cals(raw)
        prebad_file = _prebad(p, subj)
        for r in raw:
            _load_meg_bads(r, prebad_file, disp=False)
        raw = mne.concatenate_raws(raw)

        # sss
        sss_fnames = get_raw_fnames(p, subj, 'sss', False, False,
                                    run_indices[si])
        has_sss = all(op.isfile(fname) for fname in sss_fnames)
        sss_info = mne.io.read_raw_fif(sss_fnames[0]) if has_sss else None
        bad_file = get_bad_fname(p, subj)
        if bad_file is not None:
            sss_info.load_bad_channels(bad_file)
        sss_info = sss_info.info

        # pca
        pca_fnames = get_raw_fnames(p, subj, 'pca', False, False,
                                    run_indices[si])
        has_pca = all(op.isfile(fname) for fname in pca_fnames)

        # whitening and source localization
        inv_dir = op.join(p.work_dir, subj, p.inverse_dir)

        has_fwd = op.isfile(op.join(p.work_dir, subj, p.forward_dir,
                                    subj + p.inv_tag + '-fwd.fif'))

        with plt.style.context(style):
            ljust = 25
            #
            # Head coils
            #
            section = 'Good HPI count'
            if p.report_params.get('good_hpi_count', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    _, _, fit_data = _head_pos_annot(p, fname, prefix='      ')
                    assert fit_data is not None
                    fig = plot_good_coils(fit_data, show=False)
                    fig.set_size_inches(10, 2)
                    fig.tight_layout()
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
                report.add_figs_to_section(figs, captions, section,
                                           image_format='svg')
                print('%5.1f sec' % ((time.time() - t0),))
            else:
                print('    %s skipped' % section)

            #
            # cHPI SNR
            #
            section = 'cHPI SNR'
            if p.report_params.get('chpi_snr', True) and p.movecomp:
                t0 = time.time()
                print(('    %s ... ' % section).ljust(ljust), end='')
                figs = list()
                captions = list()
                for fname in fnames:
                    raw = mne.io.read_raw_fif(fname, allow_maxshield='yes')
                    t_window = _get_t_window(p, raw)
                    fig = plot_chpi_snr_raw(raw, t_window, show=False,
                                            verbose=False)
                    fig.set_size_inches(10, 5)
                    fig.subplots_adjust(0.1, 0.1, 0.8, 0.95,
                                        wspace=0, hspace=0.5)
                    figs.append(fig)
                    captions.append('%s: %s' % (section, op.split(fname)[-1]))
#.........这里部分代码省略.........
开发者ID:LABSN,项目名称:mnefun,代码行数:103,代码来源:_report.py

示例12: generateReport

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
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)
开发者ID:dmalt,项目名称:ICA_clean_pipeline,代码行数:96,代码来源:reportGen.py

示例13: test_render_report

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
def test_render_report():
    """Test rendering -*.fif files for mne report.
    """

    report = Report(info_fname=raw_fname)
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.parse_folder(data_path=base_dir)
    assert_true(len(w) == 1)

    # Check correct paths and filenames
    assert_true(raw_fname in report.fnames)
    assert_true(event_name in report.fnames)
    assert_true(report.data_path == base_dir)

    # Check if all files were rendered in the report
    fnames = glob.glob(op.join(base_dir, '*.fif'))
    bad_name = 'test_ctf_comp_raw-eve.fif'
    decrement = any(fname.endswith(bad_name) for fname in fnames)
    fnames = [fname for fname in fnames if
              fname.endswith(('-eve.fif', '-ave.fif', '-cov.fif',
                              '-sol.fif', '-fwd.fif', '-inv.fif',
                              '-src.fif', '-trans.fif', 'raw.fif',
                              'sss.fif', '-epo.fif')) and
              not fname.endswith(bad_name)]
    # last file above gets created by another test, and it shouldn't be there

    for fname in fnames:
        assert_true(''.join(report.html).find(op.basename(fname)) != -1)

    assert_equal(len(report.fnames), len(fnames))
    assert_equal(len(report.html), len(report.fnames))

    evoked1 = read_evokeds(evoked1_fname)
    evoked2 = read_evokeds(evoked2_fname)
    assert_equal(len(report.fnames) + len(evoked1) + len(evoked2) - 2,
                 report.initial_id - decrement)

    # Check saving functionality
    report.data_path = tempdir
    report.save(fname=op.join(tempdir, 'report.html'), open_browser=False)
    assert_true(op.isfile(op.join(tempdir, 'report.html')))

    # Check add_figs_to_section functionality
    fig = evoked1[0].plot(show=False)
    report.add_figs_to_section(figs=fig,  # test non-list input
                               captions=['evoked response'])
    assert_equal(len(report.html), len(fnames) + 1)
    assert_equal(len(report.html), len(report.fnames))
    assert_raises(ValueError, report.add_figs_to_section, figs=[fig, fig],
                  captions='H')

    # Check add_images_to_section
    img_fname = op.join(tempdir, 'testimage.png')
    fig.savefig(img_fname)
    report.add_images_to_section(fnames=[img_fname],
                                 captions=['evoked response'])
    assert_raises(ValueError, report.add_images_to_section,
                  fnames=[img_fname, img_fname], captions='H')

    # Check deprecation of add_section
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        report.add_section(figs=fig,
                           captions=['evoked response'])
        assert_true(w[0].category == DeprecationWarning)

    # Check saving same report to new filename
    report.save(fname=op.join(tempdir, 'report2.html'), open_browser=False)
    assert_true(op.isfile(op.join(tempdir, 'report2.html')))

    # Check overwriting file
    report.save(fname=op.join(tempdir, 'report.html'), open_browser=False,
                overwrite=True)
    assert_true(op.isfile(op.join(tempdir, 'report.html')))
开发者ID:dengemann,项目名称:mne-python,代码行数:77,代码来源:test_report.py

示例14: print

# 需要导入模块: from mne.report import Report [as 别名]
# 或者: from mne.report.Report import add_figs_to_section [as 别名]
                picks = mne.pick_types(raw.info, meg=True, eog=True)

                for trial_type in trial_types:
                    epochs = mne.Epochs(raw, eve_dict[trial_type],
                                    id_dict[trial_type],
                                    tmin, tmax, picks=picks, verbose=False,
                                    baseline=baseline, reject=reject,
                                    preload=True, reject_tmin=rej_tmin,
                                    reject_tmax=rej_tmax) # Check rejection settings
                    ica_check_evoked = \
                                epochs[ica_check_eves[trial_type]].average()

                    fig = ica.plot_overlay(ica_check_evoked, exclude=ica_excludes)  # plot EOG cleaning
                    #fig.savefig(ica_check_img_folder + '/' +trial_type + session_no + '-savgol.png')
                    report.add_figs_to_section(fig, trial_type + session_no,
                            section=filter_string, scale=None, image_format='png')
                    plt.close(fig)

                    ica.exclude = ica_excludes

                    ica.apply(epochs, copy=False)

                    print('Resampling epochs...')
                    epochs.resample(epoch_params['rsl'],
                                    n_jobs=1, verbose=False)
                                    # Trust the defaults here

                    epochs.save(opj(epochs_folder,
                                    trial_type + session_no + '-epo.fif'))

                # Try if deleting the raw object helps here!
开发者ID:cjayb,项目名称:VSC-MEG-analysis,代码行数:33,代码来源:scr_run_ica_exclude_and_epoch.py


注:本文中的mne.report.Report.add_figs_to_section方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。