Beispiel #1
0
def _setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    try:
        locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
    except locale.Error:
        try:
            locale.setlocale(locale.LC_ALL, str('English_United States.1252'))
        except locale.Error:
            warnings.warn(
                "Could not set locale to English/United States. "
                "Some date-related tests may fail")

    plt.switch_backend('Agg')  # use Agg backend for these test
    if mpl.get_backend().lower() != "agg":
        msg = ("Using a wrong matplotlib backend ({0}), "
               "which will not produce proper images")
        raise Exception(msg.format(mpl.get_backend()))

    # These settings *must* be hardcoded for running the comparison
    # tests
    mpl.rcdefaults()  # Start with all defaults
    mpl.rcParams['text.hinting'] = True
    mpl.rcParams['text.antialiased'] = True
    mpl.rcParams['text.hinting_factor'] = 8

    # make sure we don't carry over bad plots from former tests
    msg = ("no of open figs: {} -> find the last test with ' "
           "python tests.py -v' and add a '@cleanup' decorator.")
    assert len(plt.get_fignums()) == 0, msg.format(plt.get_fignums())
Beispiel #2
0
def test_plot_tfr_topo():
    """Test plotting of TFR data."""
    import matplotlib.pyplot as plt

    epochs = _get_epochs()
    n_freqs = 3
    nave = 1
    data = np.random.RandomState(0).randn(len(epochs.ch_names),
                                          n_freqs, len(epochs.times))
    tfr = AverageTFR(epochs.info, data, epochs.times, np.arange(n_freqs), nave)
    plt.close('all')
    fig = tfr.plot_topo(baseline=(None, 0), mode='ratio',
                        title='Average power', vmin=0., vmax=14.)

    # test opening tfr by clicking
    num_figures_before = len(plt.get_fignums())
    # could use np.reshape(fig.axes[-1].images[0].get_extent(), (2, 2)).mean(1)
    with pytest.warns(None):  # on old mpl there is a warning
        _fake_click(fig, fig.axes[0], (0.08, 0.65))
    assert num_figures_before + 1 == len(plt.get_fignums())
    plt.close('all')

    tfr.plot([4], baseline=(None, 0), mode='ratio', show=False, title='foo')
    pytest.raises(ValueError, tfr.plot, [4], yscale='lin', show=False)

    # nonuniform freqs
    freqs = np.logspace(*np.log10([3, 10]), num=3)
    tfr = AverageTFR(epochs.info, data, epochs.times, freqs, nave)
    fig = tfr.plot([4], baseline=(None, 0), mode='mean', vmax=14., show=False)
    assert fig.axes[0].get_yaxis().get_scale() == 'log'

    # one timesample
    tfr = AverageTFR(epochs.info, data[:, :, [0]], epochs.times[[1]],
                     freqs, nave)
    with pytest.warns(None):  # matplotlib equal left/right
        tfr.plot([4], baseline=None, vmax=14., show=False, yscale='linear')

    # one frequency bin, log scale required: as it doesn't make sense
    # to plot log scale for one value, we test whether yscale is set to linear
    vmin, vmax = 0., 2.
    fig, ax = plt.subplots()
    tmin, tmax = epochs.times[0], epochs.times[-1]
    with pytest.warns(RuntimeWarning, match='not masking'):
        _imshow_tfr(ax, 3, tmin, tmax, vmin, vmax, None, tfr=data[:, [0], :],
                    freq=freqs[[-1]], x_label=None, y_label=None,
                    colorbar=False, cmap=('RdBu_r', True), yscale='log')
    fig = plt.gcf()
    assert fig.axes[0].get_yaxis().get_scale() == 'linear'

    # ValueError when freq[0] == 0 and yscale == 'log'
    these_freqs = freqs[:3].copy()
    these_freqs[0] = 0
    with pytest.warns(RuntimeWarning, match='not masking'):
        pytest.raises(ValueError, _imshow_tfr, ax, 3, tmin, tmax, vmin, vmax,
                      None, tfr=data[:, :3, :], freq=these_freqs, x_label=None,
                      y_label=None, colorbar=False, cmap=('RdBu_r', True),
                      yscale='log')
Beispiel #3
0
 def decorated():
     # make sure we don't carry over bad images from former tests.
     assert len(plt.get_fignums()) == 0, "no of open figs: %s -> find the last test with ' " \
                                 "python tests.py -v' and add a '@cleanup' decorator." % \
                                 str(plt.get_fignums())
     func()
     assert len(plt.get_fignums()) == len(baseline_images), "different number of " \
                                                            "baseline_images and actuall " \
                                                            "plots."
     for fignum, baseline in zip(plt.get_fignums(), baseline_images):
         figure = plt.figure(fignum)
         _assert_same_figure_images(figure, baseline, _file, tol=tol)
Beispiel #4
0
 def load(self):
     inter = mp.isinteractive()
     if inter: mp.ioff()
     fig_list = mp.get_fignums()
     if self.file != None:
         with open(self.file, 'r') as f:
             ps = pkl.load(f)
         self.dict = ps.dict
     for p in mp.get_fignums():
         if p not in fig_list:
             mp.close(p)
     if inter: mp.ion()
Beispiel #5
0
def test_plot_topomap_interactive():
    """Test interactive topomap projection plotting."""
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
    from matplotlib.figure import Figure
    evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
    evoked.pick_types(meg='mag')
    evoked.info['projs'] = []
    assert not evoked.proj
    evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))

    plt.close('all')
    fig = Figure()
    canvas = FigureCanvas(fig)
    ax = fig.gca()

    kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax,
                  res=8, time_unit='s')
    evoked.copy().plot_topomap(proj=False, **kwargs)
    canvas.draw()
    image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj=True, **kwargs)
    canvas.draw()
    image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert not np.array_equal(image_noproj, image_proj)
    assert len(plt.get_fignums()) == 1

    ax.clear()
    evoked.copy().plot_topomap(proj='interactive', **kwargs)
    canvas.draw()
    image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive)
    assert not np.array_equal(image_proj, image_interactive)
    assert len(plt.get_fignums()) == 2

    proj_fig = plt.figure(plt.get_fignums()[-1])
    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_proj, image_interactive_click)
    assert not np.array_equal(image_noproj, image_interactive_click)

    _fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
    canvas.draw()
    image_interactive_click = np.frombuffer(
        canvas.tostring_rgb(), dtype='uint8')
    assert_array_equal(image_noproj, image_interactive_click)
    assert not np.array_equal(image_proj, image_interactive_click)
Beispiel #6
0
    def test_plotting(self):
        Options.multiprocessing=False
        self.fldr.figure(figsize=(9,6))
        self.fldr.each.plot()
        self.assertEqual(len(plt.get_fignums()),1,"Plotting to a single figure in PlotFolder failed.")
        plt.close("all")
        self.fldr.plot(extra=extra)
        self.assertEqual(len(plt.get_fignums()),2,"Plotting to a single figure in PlotFolder failed.")
        self.ax=self.fldr[0].subplots
        self.assertEqual(len(self.ax),12,"Subplots check failed.")

        plt.close("all")
        Options.multiprocessing=True
Beispiel #7
0
def _image_comparison(baseline_images, extensions=["pdf", "svg", "png"], tol=11, rtol=1e-3, **kwargs):

    for num, base in zip(plt.get_fignums(), baseline_images):
        for ext in extensions:
            fig = plt.figure(num)
            fig.canvas.draw()
            # fig.axes[0].set_axis_off()
            # fig.set_frameon(False)
            if ext in ["npz"]:
                figdict = flatten_axis(fig)
                np.savez_compressed(os.path.join(result_dir, "{}.{}".format(base, ext)), **figdict)
                fig.savefig(
                    os.path.join(result_dir, "{}.{}".format(base, "png")),
                    transparent=True,
                    edgecolor="none",
                    facecolor="none",
                    # bbox='tight'
                )
    for num, base in zip(plt.get_fignums(), baseline_images):
        for ext in extensions:
            # plt.close(num)
            actual = os.path.join(result_dir, "{}.{}".format(base, ext))
            expected = os.path.join(baseline_dir, "{}.{}".format(base, ext))
            if ext == "npz":

                def do_test():
                    if not os.path.exists(expected):
                        import shutil

                        shutil.copy2(actual, expected)
                        # shutil.copy2(os.path.join(result_dir, "{}.{}".format(base, 'png')), os.path.join(baseline_dir, "{}.{}".format(base, 'png')))
                        raise IOError("Baseline file {} not found, copying result {}".format(expected, actual))
                    else:
                        exp_dict = dict(np.load(expected).items())
                        act_dict = dict(np.load(actual).items())
                        for name in act_dict:
                            if name in exp_dict:
                                try:
                                    np.testing.assert_allclose(
                                        exp_dict[name],
                                        act_dict[name],
                                        err_msg="Mismatch in {}.{}".format(base, name),
                                        rtol=rtol,
                                        **kwargs
                                    )
                                except AssertionError as e:
                                    raise SkipTest(e)

            yield do_test
    plt.close("all")
Beispiel #8
0
def save_all(basename,pdf=True,png=True,single_pdf=False,close=True):
    """Save all figures"""
    if not pl.get_fignums(): return
    if pdf: pp = PdfPages(basename+".pdf")
    for i in pl.get_fignums():
        fig = pl.figure(i)
        if pdf: pp.savefig(fig)
        if png:
            fig.patch.set_alpha(0.0)
            fig.savefig(basename+"-%02d.png" % i)
        if single_pdf:
            fig.savefig(basename+"-%02d.pdf" % i)

    if pdf: pp.close()
    if close: pl.close("all")
Beispiel #9
0
 def setup(self):
     func = self.func
     plt.close('all')
     self.setup_class()
     try:
         matplotlib.style.use(self.style)
         matplotlib.testing.set_font_settings_for_testing()
         func()
         assert len(plt.get_fignums()) == len(self.baseline_images), (
             "Test generated {} images but there are {} baseline images"
             .format(len(plt.get_fignums()), len(self.baseline_images)))
     except:
         # Restore original settings before raising errors.
         self.teardown_class()
         raise
Beispiel #10
0
def test_plot_topo_image_epochs():
    """Test plotting of epochs image topography."""
    title = 'ERF images - MNE sample data'
    epochs = _get_epochs()
    epochs.load_data()
    cmap = mne_analyze_colormap(format='matplotlib')
    data_min = epochs._data.min()
    plt.close('all')
    fig = plot_topo_image_epochs(epochs, sigma=0.5, vmin=-200, vmax=200,
                                 colorbar=True, title=title, cmap=cmap)
    assert epochs._data.min() == data_min
    num_figures_before = len(plt.get_fignums())
    _fake_click(fig, fig.axes[0], (0.08, 0.64))
    assert num_figures_before + 1 == len(plt.get_fignums())
    plt.close('all')
  def run_sskk(self, anchor=0.58929, grid_size=100, iter=1):
    #This section determined the real index of refraction, n, from k, using a
    #singly subtractive Kramers Kronig calculation. For this lamdiff, you will
    #need MIR data of your sample and should obtain n and k for those data
    #using a dispersion analysis (see other material).

    #Select anchor wavelength (this is usually sodium D line of 0.58929um)
    #this is the wavelength at which n1 was determined
    #iteration through program
    plt.close('all')  # hack!

    n1 = self.hapke_scalar.n1
    kset = self.vnirv, self.vnirk, self.fullv, self.fullk

    wave = self.pp_spectra['file2'][:,0]
    _, lend, lstart = self.pp_bounds #low, high, UV

    pltData, vars = analysis.MasterSSKK(kset, anchor, iter, wave, n1, lstart, lend)

    figures = [plt.figure(i) for i in plt.get_fignums()]
    self.sskk = pltData

    ## Should this be overwritten in self.pp_bounds -- I guess not we need the low from preprocessing
    self.sskk_lstart, self.sskk_lend, self.sskk_lamdiff, self.vislam, self.visn = vars
    
    return 'Solved for n: ', 'sskk', figures
Beispiel #12
0
def cursor(artists_or_axes=None, **kwargs):
    """Create a :class:`Cursor` for a list of artists or axes.

    Parameters
    ----------

    artists_or_axes : Optional[List[Union[Artist, Axes]]]
        All artists in the list and all artists on any of the axes passed in
        the list are selectable by the constructed :class:`Cursor`.  Defaults
        to all artists on any of the figures that :mod:`pyplot` is tracking.

    **kwargs
        Keyword arguments are passed to the :class:`Cursor` constructor.
    """

    if artists_or_axes is None:
        artists_or_axes = [ax
                           for fig in map(plt.figure, plt.get_fignums())
                           for ax in fig.axes]
    elif not isinstance(artists_or_axes, Iterable):
        artists_or_axes = [artists_or_axes]
    artists = []
    for entry in artists_or_axes:
        if isinstance(entry, Axes):
            ax = entry
            artists.extend(ax.lines + ax.patches + ax.collections + ax.images)
            # No need to extend with each container (ax.containers): the
            # contained artists have already been added.
        else:
            artist = entry
            artists.append(artist)
    return Cursor(artists, **kwargs)
def show_pdf(filename,width=0.5,aspect=None):
    """
    Displays the specified pdf file in a ipython/jupiter notebook.
    The width is given as screen width, the height is given via the
    aspect ratio.
    
    Arguments:
    ----------
    
    filename : string
        The path of the pdf to be shown
       
    Keywords:
    ---------
    
    width : float
        The width where 1 = full width
        
    aspect : float
        The aspect ratio width/height. Defaults to last figure's
        aspect ratio or to 4./3. if no figure present.
        
    Returns:
    --------
    A HTML object
    """
    if aspect is None:
        if plt.get_fignums()==[]:
            aspect = aspect or 4./3.
        else:
            aspect = plt.gcf().get_size_inches()
            aspect = aspect[0]/aspect[1]
    return HTML('<div style="position:relative;width:{:g}%;height:0;padding-bottom:{:g}%">'.format(width*100,width*100/aspect+2)+\
         '<iframe src="'+filename+'" style="width:100%;height:100%"></iframe></div>')
    def savefigs(self, chunk):
        if chunk["name"] is None:
            prefix = self._basename() + "_figure" + str(chunk["number"])
        else:
            prefix = self._basename() + "_" + chunk["name"]

        fignames = []

        if Pweb.usematplotlib:
            import matplotlib.pyplot as plt

            # Iterate over figures
            figs = plt.get_fignums()
            # print figs
            for i in figs:
                plt.figure(i)
                plt.figure(i).set_size_inches(chunk["f_size"])
                # plt.figure(i).set_size_inches(4,4)

                name = Pweb.figdir + "/" + prefix + "_" + str(i) + self.formatdict["figfmt"]
                for format in self.formatdict["savedformats"]:
                    plt.savefig(Pweb.figdir + "/" + prefix + "_" + str(i) + format)
                    plt.draw()
                fignames.append(name)
                # plt.clf()
                plt.close()

        if Pweb.usesho:
            from sho import saveplot

            figname = Pweb.figdir + "/" + prefix + self.formatdict["figfmt"]
            saveplot(figname)
            fignames = [figname]

        return fignames
Beispiel #15
0
def figures2pdf(fname, fignums=None, figures=None, close=False):
    """Save list of figures into a multipage pdf.

    **Arguments:**
      - **fname**: Name of the file to save to.

    **Keywords:**
      - **fignums**: list of figure numbers to save
        if None given, all currently open figures get saved into a pdf.
    """
    from matplotlib.backends.backend_pdf import PdfPages
    if fname[-4:] != '.pdf':
        fname += '.pdf'
    print('Saving to:', path.abspath(fname))

    if isinstance(fignums, type(None)) and isinstance(figures, type(None)):
        fignums = plt.get_fignums()
    elif isinstance(fignums, type(None)):
        fignums = [fig.number for fig in figures]

    with PdfPages(fname) as pdf:
        for num in fignums:
            fig = plt.figure(num)
            pdf.savefig()
            if close:
                plt.close(fig)
    print('DONE')
Beispiel #16
0
 def do_ui_pause(self, prompt=None):
     """Make a UI pause without regard to the current pause state."""
     if prompt is None:
         prompt = "Paused. Press ENTER to continue..."
     if not plt.get_fignums():  # empty list: no figures are open
         input(prompt)
     else:  # a figure is open
         if matplotlib.get_backend().upper().startswith("GTK"):
             title_before = plt.gcf().canvas.get_toplevel().get_title()
         elif matplotlib.get_backend().upper().startswith("TK"):
             title_before = plt.gcf().canvas.get_tk_widget().winfo_toplevel().wm_title()
         elif matplotlib.get_backend().upper().startswith("WX"):
             title_before = plt.gcf().canvas.GetTopLevelParent().GetTitle()
         elif matplotlib.get_backend().upper().startswith("QT"):
             title_before = str(plt.gcf().canvas.topLevelWidget().windowTitle())
         else:
             title_before = "Figure %d" % plt.gcf().number
         while True:  # wait until a key is pressed. Blink the title meanwhile.
             plt.gcf().canvas.set_window_title(prompt)
             result = plt.gcf().waitforbuttonpress(1)
             if result:  # waitforbuttonpress returns True for keypress, False for mouse click and None for timeout
                 break
             plt.gcf().canvas.set_window_title(title_before)
             result = plt.gcf().waitforbuttonpress(1)
             if result:  # waitforbuttonpress returns True for keypress, False for mouse click and None for timeout
                 break
         plt.gcf().canvas.set_window_title(title_before)
def update_plots(data, figs):

    start = time.time()

    cur_figs = plt.get_fignums()
    if cur_figs:
        
        # plot verbose link states
        fignum = figs[0].number
        if fignum in cur_figs:
            plot_verbose_network_states(fignum, data)
        
        # plot all network states
        fignum = figs[1].number
        if fignum in cur_figs:
            plot_network_states(fignum, data)

        # plot lower level database vars
        fignum = figs[2].number
        if fignum in cur_figs:
            plot_db_vars(fignum, data)
            
        draw()
        plt.pause(.1)  
        
        end = time.time()

        print "Plotting time was: ", end-start, " seconds"
    else:
        time.sleep(1)
Beispiel #18
0
def main():
  if '-a' in sys.argv:
    pr = 'all'
  else:
    pr = 'some'
  ns = int(sys.argv[-1])
  
  phase, intesity, tparams = genmultilc(nspots=ns,noisefactor=0.0)
  print 'tparams:', tparams
  print
  
  paramsets = ratchetfit((phase,intesity),ns,plsprint=pr,plsplot='-p' in sys.argv)
  pdists = [multiparamdists(fps,tparams) for fps in paramsets]
  
  print
  print 'tparams:', tparams
  print 'final param sets:'
  for i in range(len(paramsets)):
    print 'params: ', paramsets[i]
    print 'pdists: ', pdists[i]
  
  if '-p' in sys.argv:
    for i in plt.get_fignums():
      plt.figure(i)
      plt.savefig('figure%d.png' % i)
Beispiel #19
0
def show_plots(plotengine, ax=None, output_dir=None):
    if plotengine == 'mpld3':
        import mpld3
        mpld3.show()

    elif plotengine == 'matplotlib':
        import matplotlib.pyplot as plt

        if not output_dir:  # None or ""
            plt.show()
        else:
            for fi in plt.get_fignums():
                plt.figure(fi)
                fig_name = getattr(plt.figure(fi), 'name', 'figure%d' % fi)
                fig_path = op.join(output_dir, '%s.png' % fig_name)
                if not op.exists(op.dirname(fig_path)):
                    os.makedirs(op.dirname(fig_path))
                plt.savefig(fig_path)
                plt.close()

    elif plotengine in ['bokeh', 'bokeh-silent']:
        import bokeh.plotting
        import tempfile
        output_dir = output_dir or tempfile.mkdtemp()
        output_name = getattr(ax, 'name', ax.title).replace(':', '-')
        output_file = op.join(output_dir, '%s.html' % output_name)

        if not op.exists(output_dir):
            os.makedirs(output_dir)
        if op.exists(output_file):
            os.remove(output_file)
        bokeh.plotting.output_file(output_file, title=ax.title, mode='inline')
        if plotengine == 'bokeh':
            bokeh.plotting.show(ax)
Beispiel #20
0
    def test(self):
        baseline_dir, result_dir = _image_directories(self._func)

        for fignum, baseline in zip(plt.get_fignums(), self._baseline_images):
            for extension in self._extensions:
                will_fail = not extension in comparable_formats()
                if will_fail:
                    fail_msg = 'Cannot compare %s files on this system' % extension
                else:
                    fail_msg = 'No failure expected'

                orig_expected_fname = os.path.join(baseline_dir, baseline) + '.' + extension
                if extension == 'eps' and not os.path.exists(orig_expected_fname):
                    orig_expected_fname = os.path.join(baseline_dir, baseline) + '.pdf'
                expected_fname = make_test_filename(os.path.join(
                    result_dir, os.path.basename(orig_expected_fname)), 'expected')
                actual_fname = os.path.join(result_dir, baseline) + '.' + extension
                if os.path.exists(orig_expected_fname):
                    shutil.copyfile(orig_expected_fname, expected_fname)
                else:
                    will_fail = True
                    fail_msg = (
                        "Do not have baseline image {0} because this "
                        "file does not exist: {1}".format(
                            expected_fname,
                            orig_expected_fname
                        )
                    )

                @knownfailureif(
                    will_fail, fail_msg,
                    known_exception_class=ImageComparisonFailure)
                def do_test():
                    figure = plt.figure(fignum)

                    if self._remove_text:
                        self.remove_text(figure)

                    figure.savefig(actual_fname, **self._savefig_kwarg)

                    err = compare_images(expected_fname, actual_fname,
                                         self._tol, in_decorator=True)

                    try:
                        if not os.path.exists(expected_fname):
                            raise ImageComparisonFailure(
                                'image does not exist: %s' % expected_fname)

                        if err:
                            raise ImageComparisonFailure(
                                'images not close: %(actual)s vs. %(expected)s '
                                '(RMS %(rms).3f)'%err)
                    except ImageComparisonFailure:
                        if not check_freetype_version(self._freetype_version):
                            raise KnownFailureTest(
                                "Mismatched version of freetype.  Test requires '%s', you have '%s'" %
                                (self._freetype_version, ft2font.__freetype_version__))
                        raise

                yield (do_test,)
Beispiel #21
0
    def _init_figure(self, **kwargs):
        from matplotlib import pyplot

        # add new attributes
        self.colorbars = []
        self._coloraxes = []

        # create Figure
        num = kwargs.pop('num', max(pyplot.get_fignums() or {0}) + 1)
        self._parse_subplotpars(kwargs)
        super(Plot, self).__init__(**kwargs)
        self.number = num

        # add interactivity (scraped from pyplot.figure())
        backend_mod = get_backend_mod()
        try:
            manager = backend_mod.new_figure_manager_given_figure(num, self)
        except AttributeError:
            upstream_mod = importlib.import_module(
                pyplot.new_figure_manager.__module__)
            canvas = upstream_mod.FigureCanvasBase(self)
            manager = upstream_mod.FigureManagerBase(canvas, 1)
        manager._cidgcf = manager.canvas.mpl_connect(
            'button_press_event',
            lambda ev: _pylab_helpers.Gcf.set_active(manager))
        _pylab_helpers.Gcf.set_active(manager)
        pyplot.draw_if_interactive()
Beispiel #22
0
def splay_figures():
    """Get all figures and spread them across my secondary monitor"""
    fig_list = plt.get_fignums()
    wx = 640
    h = 500
    x1, x2, x3 = 1367, 1367 + wx, 1367 + wx*2
    y0 = 30
    y1 = 570
    points = np.array([[x1,y0,wx,h],
                       [x2,y0,wx,h],
                       [x3,y0,wx,h],
                       [x1,y1,wx,h],
                       [x2,y1,wx,h],
                       [x3,y1,wx,h]])

    if len(fig_list) == 2:
        points = points[[2, 5]]
    if len(fig_list) == 3:
        points = points[[2, 4, 5]]
    if len(fig_list) == 4:
        points = points[[1, 2, 4, 5]]

    for i in range(len(fig_list)):
        plt.figure(fig_list[i])
        plt.get_current_fig_manager().window.setGeometry(
            points[i,0],points[i,1], points[i,2], points[i,3])
Beispiel #23
0
def ShowLastPos(plt):
    # Call plt.show but pickles the plot position on window close.  When called a second time
    # it loads the figure to the last position.  So matplotlib now remembers figure positions!
    # This version works for QT and WX backends.

    backend = matplotlib.get_backend()

    FigNums = plt.get_fignums()

    for FigNum in FigNums:
        plt.figure(FigNum)
        fig=plt.gcf()
        fig.canvas.mpl_connect('close_event', RecordLastPos)
        mgr = plt.get_current_fig_manager()
        # WX backend
        if 'WX' in backend:
            try:
                with open('CurrentWindowPos%d.pkl'%FigNum, 'r') as f:
                    CurPos = pickle.load(f)
                mgr.window.SetPosition((CurPos[0], CurPos[1]))
                mgr.window.SetSize((CurPos[2], CurPos[3]))
            except:
                pass
        # QT backend.
        elif 'QT' in backend:
            try:
                with open('CurrentWindowPos%d.pkl'%FigNum, 'r') as f:
                    CurPos = pickle.load(f)
                mgr.window.setGeometry(CurPos[0], CurPos[1], CurPos[2], CurPos[3])
            except:
                pass
        else:
            print 'Backend ' + backend + ' not supported.  Plot figure position will not be sticky.'

    plt.show()
Beispiel #24
0
def doubleprof(prof1,prof2,rangecor=True,deltaplot=True):
    plotprofs=[]
    
    for p in [prof1,prof2]:
        if rangecor:
            alts=p.index()
            plotprofs.append(p*alts**2)
        else:
            plotprofs.append(p)
    
    if deltaplot:
        normprofs=[]
        for p in plotprofs:
            tempmean=p.mean()
            normprofs.append(p/tempmean())
        deltaprof=(normprofs[1]-normprofs[2])*100.0/normprofs[1] 
    
    numfigs=len(plt.get_fignums())
    fig=plt.figure(numfigs+1)
    ax1=fig.add_subplot(211)
    ax1a=plotprofs[0].plot()
    ax1b=plotprofs[1].plot(secondary_y=True)
    align_yaxis(ax1a,0,ax1b,0)
    ax2=fig.add_subplot(212)
    deltaprof.plot()
def multipage(filename, figs=None, dpi=200):
    pp = PdfPages(filename)
    if figs is None:
        figs = [plt.figure(n) for n in plt.get_fignums()]
    for fig in figs:
        fig.savefig(pp, format='pdf')
    pp.close()
def main(args):
    # Load parameters from yaml
    param_path = 'params.yaml' # rospy.get_param("~param_path")
    f = open(param_path,'r')
    params_raw = f.read()
    f.close()
    params = yaml.load(params_raw)
    occupancy_map = np.array(params['occupancy_map'])
    world_map = np.array(params['world_map'])
    pos_init = np.array(params['pos_init'])
    pos_goal = np.array(params['pos_goal'])
    max_vel = params['max_vel']
    max_omega = params['max_omega']
    t_cam_to_body = np.array(params['t_cam_to_body'])
    x_spacing = params['x_spacing']
    y_spacing = params['y_spacing']

    # Intialize the RobotControl object
    robotControl = RobotControl(world_map, occupancy_map, pos_init, pos_goal,
                                max_vel, max_omega, x_spacing, y_spacing,
                                t_cam_to_body)

    # TODO for student: Comment this when running on the robot 
    # Run the simulation
    while not robotControl.robot_sim.done and plt.get_fignums():
        robotControl.process_measurements()
        robotControl.robot_sim.update_frame()

    plt.ioff()
    plt.show()

    # TODO for student: Use this to run the interface on the robot
    # Call process_measurements at 60Hz
    """r = rospy.Rate(60)
Beispiel #27
0
def process_statspecs(directive, part=None, designname=None):
    """
    Main processor for the staplestatter directive. Responsible for:
    1) Initialize figure and optionally axes as specified by the directive instructions.
    2) Loop over all statspecs and call process_statspec.
    3) Aggregate and return a list of stats/scores.
    """
    if part is None:
        part = cadnano_api.p()
    if designname is None:
        designname = os.path.splitext(os.path.basename(part.document().controller().filename()))[0]
    print("designname:", designname)

    statspecs = directive['statspecs']
    figspec = directive.get('figure', dict())
    if figspec.get('newfigure', False) or len(pyplot.get_fignums()) < 1:
        fig = pyplot.figure(**figspec.get('figure_kwargs', {}))
    else:
        fig = pyplot.gcf() # Will make a new figure if no figure has been created.
    # Here you can add more "figure/axes" specification logic:
    adjustfuncs = ('title', 'size_inches', 'dpi')
    for cand in adjustfuncs:
        if cand in figspec and figspec[cand]:
            getattr(fig, 'set_'+cand)(figspec[cand]) # equivalent to fig.title(figspec['title'])

    pyplot.ion()
    allscores = list()
    for _, statspec in enumerate(statspecs):
        scores = process_statspec(statspec, part=part, designname=designname, fig=fig)
        allscores.append(scores)
        if 'printspec' in statspec:
            print("Printing highest scores with: statspec['printspec']")
            get_highest_scores(scores, **statspec['printspec']) # This logic is subject to change.
    return dict(figure=fig, scores=allscores)
Beispiel #28
0
    def updatePlot(self, dataList):

        # plotLine.set_xdata(range(Nsamples))

        # if plot window is closed
        if 0 == len(plt.get_fignums()):
            return

        self.yDataLineOne.append(dataList[0]) # data 1 form queue
        del (self.yDataLineOne[0])
        self.pltLineOne.set_ydata(self.yDataLineOne)  # update the data

        ## for second line
        if len(dataList) == 2:
            self.yDataLineTwo.append(dataList[1]) # data 2 from queue
            del (self.yDataLineTwo[0])
            self.pltLineTwo.set_ydata(self.yDataLineTwo)

        ymin = float(min(self.yDataLineOne + self.yDataLineTwo))-1
        ymax = float(max(self.yDataLineOne + self.yDataLineTwo))+1
        plt.ylim([ymin,ymax])

        # update text on the plot
        self.TextValTemp1.set_text(round(self.yDataLineOne[-1], 2))
        self.TextValTemp2.set_text(round(self.yDataLineTwo[-1], 2))

        plt.draw()  # update the plot
        self.refreshPlot()
Beispiel #29
0
 def test_hist_by_no_extra_plots(self):
     import matplotlib.pyplot as plt
     n = 10
     df = DataFrame({'gender': tm.choice(['Male', 'Female'], size=n),
                     'height': random.normal(66, 4, size=n)})
     axes = df.height.hist(by=df.gender)
     self.assertEqual(len(plt.get_fignums()), 1)
Beispiel #30
0
    def save_plots(self):
        if not self.args.out and not self.args.out_only:
            return

        print("saving plots")

        # get output prefix:
        prefix = self.args.out if self.args.out else self.args.out_only

        # create dir if needed or check for dir type
        if not os.path.exists(prefix):
            os.mkdir(prefix)
        elif not os.path.isdir(prefix):
            print("not a directory: {}".format(prefix))
            sys.exit(1)

        # Prepare for a single file with all plots
        p = os.path.join(prefix, "all_plots.pdf")
        pdf_pages = PdfPages(p)

        for fig in list(map(plt.figure, plt.get_fignums())):
            # Add plot to the one and only pdf
            pdf_pages.savefig(fig, transparent=True)

            # fetch and remove title from plot (used in filename instead)
            title = fig.axes[0].get_title().replace(' ', '_')
            fig.axes[0].set_title("")

            # create filename and save plot
            filename = os.path.join(prefix, title + ".pdf")
            print(filename)
            fig.savefig(filename, transparent=True, bbox_inches='tight', pad_inches=0)

        # Save the teh single file
        pdf_pages.close()
Beispiel #31
0
def test_classifier_binary():
    mlflow.sklearn.autolog()
    # use RandomForestClassifier that has method [predict_proba], so that we can test
    # logging of (1) log_loss and (2) roc_auc_score.
    model = sklearn.ensemble.RandomForestClassifier(max_depth=2,
                                                    random_state=0,
                                                    n_estimators=10)

    # use binary datasets to cover the test for roc curve & precision recall curve
    X, y_true = sklearn.datasets.load_breast_cancer(return_X_y=True)

    with mlflow.start_run() as run:
        model = fit_model(model, X, y_true, "fit")

    y_pred = model.predict(X)
    y_pred_prob = model.predict_proba(X)
    # For binary classification, y_score only accepts the probability of greater label
    y_pred_prob_roc = y_pred_prob[:, 1]

    run_id = run.info.run_id
    params, metrics, tags, artifacts = get_run_data(run_id)
    assert params == truncate_dict(
        stringify_dict_values(model.get_params(deep=True)))

    expected_metrics = {
        TRAINING_SCORE:
        model.score(X, y_true),
        "training_accuracy_score":
        sklearn.metrics.accuracy_score(y_true, y_pred),
        "training_precision_score":
        sklearn.metrics.precision_score(y_true, y_pred, average="weighted"),
        "training_recall_score":
        sklearn.metrics.recall_score(y_true, y_pred, average="weighted"),
        "training_f1_score":
        sklearn.metrics.f1_score(y_true, y_pred, average="weighted"),
        "training_log_loss":
        sklearn.metrics.log_loss(y_true, y_pred_prob),
    }
    if _is_metric_supported("roc_auc_score"):
        expected_metrics[
            "training_roc_auc_score"] = sklearn.metrics.roc_auc_score(
                y_true,
                y_score=y_pred_prob_roc,
                average="weighted",
                multi_class="ovo",
            )

    assert metrics == expected_metrics

    assert tags == get_expected_class_tags(model)
    assert MODEL_DIR in artifacts

    client = mlflow.tracking.MlflowClient()
    artifacts = [x.path for x in client.list_artifacts(run_id)]

    plot_names = []
    if _is_plotting_supported():
        plot_names.extend([
            "{}.png".format("training_confusion_matrix"),
            "{}.png".format("training_roc_curve"),
            "{}.png".format("training_precision_recall_curve"),
        ])

    assert all(x in artifacts for x in plot_names)

    loaded_model = load_model_by_run_id(run_id)
    assert_predict_equal(loaded_model, model, X)
    # verify no figure is open
    assert len(plt.get_fignums()) == 0
Beispiel #32
0
plt.figure()
plt.plot(t, states_new[:, 1], label='new')
plt.plot(t, states_old[:, 1], label='old')
plt.xlabel('time [s]')
plt.ylabel('angular velocity [rad/s]')
plt.legend()
plt.show(block=False)

plt.figure()
plt.plot(t[:-1], actions_new, label='new')
plt.plot(t[:-1], actions_old, label='old')
plt.xlabel('time [s]')
plt.ylabel('actions')
plt.legend()
plt.show(block=False)

print(
    'reward old:',
    tf.reduce_sum(rl.reward_function(
        states_old[:-1], actions_old)).eval(feed_dict=rl.feed_dict))
print(
    'reward new:',
    tf.reduce_sum(rl.reward_function(
        states_new[:-1], actions_new)).eval(feed_dict=rl.feed_dict))

# Prevent pyplot windows from closing
plt.pause(3)
while plt.get_fignums():
    plt.pause(10000)
    pass
Beispiel #33
0
    tokenizer.fit_on_texts(samples)
    sequences = tokenizer.texts_to_sequences(samples)
    one_hot_results = tokenizer.texts_to_matrix(samples, mode = 'binary')
    word_index = tokenizer.word_index
    print("Found {} unique tokens.".format(len(word_index)))


# Listing 6.4 使用散列技巧的单词级别的 One-Hot 编码(简单示例)
# 单词向量的维度是1000,如果单词数量接近甚至超过1000,那么散列冲突的频率就会很高,严重影响编码的效率和质量
def one_hot_word_with_hash_set():
    dimensionality = 1000
    max_length = 10
    results = np.zeros((len(samples), max_length, dimensionality))
    for i, sample in enumerate(samples):
        for j, word in list(enumerate(sample.split()))[:max_length]:
            # 通过下面的散列函数给出单词的索引
            index = abs(hash(word)) % dimensionality
            results[i, j, index] = 1.


if __name__ == '__main__':
    # one_hot_word()
    # one_hot_character()
    # one_hot_word_with_keras()
    one_hot_word_with_hash_set()
    # 运行结束的提醒
    winsound.Beep(600, 500)
    if len(plt.get_fignums()) != 0:
        plt.show()
    pass
Beispiel #34
0
        caffe.set_mode_gpu()
        caffe.set_device(args.gpu_id)
        cfg.GPU_ID = args.gpu_id
    net = caffe.Net(prototxt, caffemodel, caffe.TEST)

    print '\n\nLoaded network {:s}'.format(caffemodel)

    # Warmup on a dummy image
    im = 128 * np.ones((300, 500, 3), dtype=np.uint8)
    for i in xrange(2):
        _, _= im_detect(net, im)

    im_names_real = ['real01.jpg','real02.jpg','real03.jpg','real04.jpg','real05.jpg','real06.jpg','real07.jpg','real08.jpg','real09.jpg','real10.jpg','real11.jpg','real12.jpg','real13.jpg','real14.jpg','real15.jpg','real16.jpg','real17.jpg','real18.jpg','real19.jpg','real20.jpg','real21.jpg','real22.jpg','real23.jpg','real24.jpg','real25.jpg','real26.jpg']
    im_names_gen = ['p277_1_0.jpg','p274_1_0.jpg','t69_1_0.jpg','t71_1_0.jpg','t92_1_0.jpg','t82_1_0.jpg','t83_1_0.jpg','t116_1_0.jpg','t114_1_0.jpg','t113_1_0.jpg','t94_1_0.jpg','t89_1_0.jpg','t76_1_0.jpg','t74_1_0.jpg','t48_1_0.jpg','t33_1_0.jpg']
    im_names_room = ['v1_1_0.jpg','v2_1_0.jpg','v3_1_0.jpg','v4_1_0.jpg','v5_1_0.jpg','v6_1_0.jpg','v7_1_0.jpg','v8_1_0.jpg','v9_1_0.jpg','v10_1_0.jpg','v11_1_0.jpg','v12_1_0.jpg','v14_1_0.jpg','v117_1_0.jpg']
    im_names = im_names_real
    for im_name in im_names:
        print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
        print 'Demo for data/demo/{}'.format(im_name)
        demo(net, im_name)

    ## plt.show()
    from matplotlib.backends.backend_pdf import PdfPages
    pp = PdfPages('/home/javier/rcnn/py-faster-rcnn/output/demo/multi.pdf')
    for i in plt.get_fignums():
	plt.figure(i)
	pp.savefig()
        #plt.savefig('/home/javier/rcnn/py-faster-rcnn/output/demo/figure%d.png' % i)
    pp.close()

Beispiel #35
0
            #print d.xydata[0][0][12], d.xydata[0][1][12] # print the x and y data, respectively, for the 13th sample on fast adc channel 0
            
            #if len(HaasoscopeLib.max10adcchans)>0: print "slow", d.xydataslow[0][0][99], d.xydataslow[0][1][99] # print the x and y data, respectively, for the 100th sample on slow max10 adc channel 0
            
            #if d.dolockin: print d.lockinamp, d.lockinphase # print the lockin info
            
            #if d.fftdrawn: # print some fft info (the freq with the biggest amplitude)
            #    fftxdata = d.fftfreqplot.get_xdata(); fftydata = d.fftfreqplot.get_ydata()
            #    maxfftydata=np.max(fftydata); maxfftfrq=fftxdata[fftydata.argmax()]
            #    print "max amp=",maxfftydata, "at freq=",maxfftfrq, d.fftax[1].get_xlabel().replace('Freq ','')
            
            if d.db: print time.time()-d.oldtime,"done with evt",nevents
            nevents+=1
            if nevents-oldnevents >= tinterval:
                elapsedtime=time.time()-oldtime
                lastrate = round(tinterval/elapsedtime,2)
                print nevents,"events,",lastrate,"Hz"
                oldtime=time.time()
                if lastrate>40: tinterval=500.
                else: tinterval=100.
                oldnevents=nevents
            if d.getone: d.paused=True
        d.redraw()
        if len(plt.get_fignums())==0:
            if d.domaindrawing: break # quit when all the plots have been closed
            elif nevents>50: break
except SerialException:
    print "serial com failed!"
finally:
    d.cleanup()
Beispiel #36
0
    # Loop over the examples
    for example in example_list:
        output.write('\n')
        output.write('+++++++++++++++++++++++++++++++++++++++\n')
        output.write('Example ' + example + '\n')

        # Start time of the example
        example_start = datetime.datetime.now()

        # Running the example
        subprocess.call(["python3", example])

        # write the runtime and the time since the start of the example to the log file
        example_runtime = datetime.datetime.now() - example_start
        output.write('Time for example: ' + str(example_runtime) + '\n')
        time_since_start = datetime.datetime.now() - batch_start
        output.write('Time since batch start: ' + str(time_since_start) + '\n')
        output.write('+++++++++++++++++++++++++++++++++++++++\n')

        # closes figures if still open
        if len(plt.get_fignums()) > 0:
            plt.close('all')

    # close the log file
    output.close()

# remove the dummy file (Very important! for normal runs we check if it exists or not!)
os.remove('batch_run.txt')

sys.exit(0)
Beispiel #37
0
def _annotation_helper(raw, events=False):
    """Test interactive annotations."""
    # Some of our checks here require modern mpl to work properly
    mpl_good_enough = LooseVersion(matplotlib.__version__) >= '2.0'
    n_anns = len(raw.annotations)
    plt.close('all')

    if events:
        events = np.array([[raw.first_samp + 100, 0, 1],
                           [raw.first_samp + 300, 0, 3]])
        n_events = len(events)
    else:
        events = None
        n_events = 0
    fig = raw.plot(events=events)
    assert len(plt.get_fignums()) == 1
    data_ax = fig.axes[0]
    fig.canvas.key_press_event('a')  # annotation mode
    assert len(plt.get_fignums()) == 2
    # +2 from the scale bars
    n_scale = 2
    assert len(fig.axes[0].texts) == n_anns + n_events + n_scale
    # modify description
    ann_fig = plt.gcf()
    for key in ' test':
        ann_fig.canvas.key_press_event(key)
    ann_fig.canvas.key_press_event('enter')

    ann_fig = plt.gcf()
    # XXX: _fake_click raises an error on Agg backend
    _annotation_radio_clicked('', ann_fig.radio, data_ax.selector)

    # draw annotation
    fig.canvas.key_press_event('p')  # use snap mode
    _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press')
    _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='motion')
    _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='release')
    assert len(raw.annotations.onset) == n_anns + 1
    assert len(raw.annotations.duration) == n_anns + 1
    assert len(raw.annotations.description) == n_anns + 1
    assert raw.annotations.description[n_anns] == 'BAD_ test'
    assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale
    onset = raw.annotations.onset[n_anns]
    want_onset = _sync_onset(raw, 1., inverse=True)
    assert_allclose(onset, want_onset)
    assert_allclose(raw.annotations.duration[n_anns], 4.)
    # hover event
    _fake_click(fig,
                data_ax, [4.5, 1.],
                xform='data',
                button=None,
                kind='motion')
    _fake_click(fig,
                data_ax, [4.7, 1.],
                xform='data',
                button=None,
                kind='motion')
    # modify annotation from end
    _fake_click(fig, data_ax, [5., 1.], xform='data', button=1, kind='press')
    _fake_click(fig, data_ax, [2.5, 1.], xform='data', button=1, kind='motion')
    _fake_click(fig,
                data_ax, [2.5, 1.],
                xform='data',
                button=1,
                kind='release')
    if mpl_good_enough:
        assert raw.annotations.onset[n_anns] == onset
        assert_allclose(raw.annotations.duration[n_anns], 1.5)  # 4->1.5
    # modify annotation from beginning
    _fake_click(fig, data_ax, [1., 1.], xform='data', button=1, kind='press')
    _fake_click(fig, data_ax, [0.5, 1.], xform='data', button=1, kind='motion')
    _fake_click(fig,
                data_ax, [0.5, 1.],
                xform='data',
                button=1,
                kind='release')
    if mpl_good_enough:
        assert_allclose(raw.annotations.onset[n_anns], onset - 0.5, atol=1e-10)
        assert_allclose(raw.annotations.duration[n_anns], 2.0)
    assert len(raw.annotations.onset) == n_anns + 1
    assert len(raw.annotations.duration) == n_anns + 1
    assert len(raw.annotations.description) == n_anns + 1
    assert raw.annotations.description[n_anns] == 'BAD_ test'
    assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale
    fig.canvas.key_press_event('shift+right')
    assert len(fig.axes[0].texts) == n_scale
    fig.canvas.key_press_event('shift+left')
    assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale

    # draw another annotation merging the two
    _fake_click(fig, data_ax, [5.5, 1.], xform='data', button=1, kind='press')
    _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='motion')
    _fake_click(fig, data_ax, [2., 1.], xform='data', button=1, kind='release')
    # delete the annotation
    assert len(raw.annotations.onset) == n_anns + 1
    assert len(raw.annotations.duration) == n_anns + 1
    assert len(raw.annotations.description) == n_anns + 1
    if mpl_good_enough:
        assert_allclose(raw.annotations.onset[n_anns], onset - 0.5, atol=1e-10)
        assert_allclose(raw.annotations.duration[n_anns], 5.0)
    assert len(fig.axes[0].texts) == n_anns + 1 + n_events + n_scale
    # Delete
    _fake_click(fig, data_ax, [1.5, 1.], xform='data', button=3, kind='press')
    fig.canvas.key_press_event('a')  # exit annotation mode
    assert len(raw.annotations.onset) == n_anns
    assert len(fig.axes[0].texts) == n_anns + n_events + n_scale
    fig.canvas.key_press_event('shift+right')
    assert len(fig.axes[0].texts) == n_scale
    fig.canvas.key_press_event('shift+left')
    assert len(fig.axes[0].texts) == n_anns + n_events + n_scale
    plt.close('all')
Beispiel #38
0
def test_plot_raw_traces():
    """Test plotting of raw data."""
    raw = _get_raw()
    raw.info['lowpass'] = 10.  # allow heavy decim during plotting
    events = _get_events()
    plt.close('all')  # ensure all are closed
    assert len(plt.get_fignums()) == 0
    fig = raw.plot(events=events,
                   order=[1, 7, 5, 2, 3],
                   n_channels=3,
                   group_by='original')
    assert len(plt.get_fignums()) == 1

    # make sure fig._mne_params is present
    assert isinstance(fig._mne_params, dict)

    # test mouse clicks
    x = fig.get_axes()[0].lines[1].get_xdata().mean()
    y = fig.get_axes()[0].lines[1].get_ydata().mean()
    data_ax = fig.axes[0]
    assert len(fig.axes) == 5

    _fake_click(fig, data_ax, [x, y], xform='data')  # mark a bad channel
    _fake_click(fig, data_ax, [x, y], xform='data')  # unmark a bad channel
    _fake_click(fig, data_ax, [0.5, 0.999])  # click elsewhere in 1st axes
    _fake_click(fig, data_ax, [-0.1, 0.9])  # click on y-label
    _fake_click(fig, fig.axes[1], [0.5, 0.5])  # change time
    labels = [label.get_text() for label in data_ax.get_yticklabels()]
    assert labels == [raw.ch_names[1], raw.ch_names[7], raw.ch_names[5]]
    _fake_click(fig, fig.axes[2], [0.5, 0.01])  # change channels to end
    labels = [label.get_text() for label in data_ax.get_yticklabels()]
    assert labels == [raw.ch_names[2], raw.ch_names[3]]
    _fake_click(fig, fig.axes[2], [0.5, 0.5])  # change channels to mid
    labels = [label.get_text() for label in data_ax.get_yticklabels()]
    assert labels == [raw.ch_names[7], raw.ch_names[5], raw.ch_names[2]]
    assert len(plt.get_fignums()) == 1
    # open SSP window
    _fake_click(fig, fig.get_axes()[-1], [0.5, 0.5])
    _fake_click(fig, fig.get_axes()[-1], [0.5, 0.5], kind='release')
    assert len(plt.get_fignums()) == 2
    ssp_fig = plt.figure(plt.get_fignums()[-1])
    fig.canvas.button_press_event(1, 1, 1)  # outside any axes
    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up

    ax = ssp_fig.get_axes()[0]  # only one axis is used
    assert _proj_status(ax) == [True] * 3
    t = [c for c in ax.get_children() if isinstance(c, matplotlib.text.Text)]
    pos = np.array(t[0].get_position()) + 0.01
    _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data')  # off
    assert _proj_status(ax) == [False, True, True]
    _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data')  # on
    assert _proj_status(ax) == [True] * 3
    _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5])  # all off
    _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5], kind='release')
    assert _proj_status(ax) == [False] * 3
    assert fig._mne_params['projector'] is None  # actually off
    _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5])  # all on
    _fake_click(ssp_fig, ssp_fig.get_axes()[1], [0.5, 0.5], kind='release')
    assert fig._mne_params['projector'] is not None  # on
    assert _proj_status(ax) == [True] * 3

    # test keypresses
    # test for group_by='original'
    for key in [
            'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'd', 'd',
            'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'z', 'escape'
    ]:
        fig.canvas.key_press_event(key)

    # test for group_by='selection'
    fig = plot_raw(raw, events=events, group_by='selection')
    for key in [
            'b', 'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'd', 'd',
            'pageup', 'pagedown', 'home', 'end', '?', 'f11', 'b', 'z', 'escape'
    ]:
        fig.canvas.key_press_event(key)

    # test zen mode
    fig = plot_raw(raw, show_scrollbars=False)

    # Color setting
    pytest.raises(KeyError, raw.plot, event_color={0: 'r'})
    pytest.raises(TypeError, raw.plot, event_color={'foo': 'r'})
    annot = Annotations([10, 10 + raw.first_samp / raw.info['sfreq']],
                        [10, 10], ['test', 'test'], raw.info['meas_date'])
    with pytest.warns(RuntimeWarning, match='outside data range'):
        raw.set_annotations(annot)
    fig = plot_raw(raw, events=events, event_color={-1: 'r', 998: 'b'})
    plt.close('all')
    for group_by, order in zip(
        ['position', 'selection'],
        [np.arange(len(raw.ch_names))[::-3], [1, 2, 4, 6]]):
        with pytest.warns(None):  # sometimes projection
            fig = raw.plot(group_by=group_by, order=order)
        x = fig.get_axes()[0].lines[1].get_xdata()[10]
        y = fig.get_axes()[0].lines[1].get_ydata()[10]
        with pytest.warns(None):  # old mpl (at least 2.0) can warn
            _fake_click(fig, data_ax, [x, y], xform='data')  # mark bad
        fig.canvas.key_press_event('down')  # change selection
        _fake_click(fig, fig.get_axes()[2], [0.5, 0.5])  # change channels
        sel_fig = plt.figure(1)
        topo_ax = sel_fig.axes[1]
        _fake_click(sel_fig, topo_ax, [-0.425, 0.20223853], xform='data')
        fig.canvas.key_press_event('down')
        fig.canvas.key_press_event('up')
        fig.canvas.scroll_event(0.5, 0.5, -1)  # scroll down
        fig.canvas.scroll_event(0.5, 0.5, 1)  # scroll up
        _fake_click(sel_fig, topo_ax, [-0.5, 0.], xform='data')
        _fake_click(sel_fig, topo_ax, [0.5, 0.], xform='data', kind='motion')
        _fake_click(sel_fig, topo_ax, [0.5, 0.5], xform='data', kind='motion')
        _fake_click(sel_fig,
                    topo_ax, [-0.5, 0.5],
                    xform='data',
                    kind='release')

        plt.close('all')
    # test if meas_date is off
    raw.set_meas_date(_dt_to_stamp(raw.info['meas_date'])[0])
    annot = Annotations([1 + raw.first_samp / raw.info['sfreq']], [5], ['bad'])
    with pytest.warns(RuntimeWarning, match='outside data range'):
        raw.set_annotations(annot)
    with pytest.warns(None):  # sometimes projection
        raw.plot(group_by='position', order=np.arange(8))
    for fig_num in plt.get_fignums():
        fig = plt.figure(fig_num)
        if hasattr(fig, 'radio'):  # Get access to selection fig.
            break
    for key in ['down', 'up', 'escape']:
        fig.canvas.key_press_event(key)

    raw._data[:] = np.nan
    # this should (at least) not die, the output should pretty clearly show
    # that there is a problem so probably okay to just plot something blank
    with pytest.warns(None):
        raw.plot(scalings='auto')

    plt.close('all')
def analog_output_function_symmetry_demo(device, num_periods):
    """Demonstrate the effect of different 'symmetry' settings on the analog output functions."""

    # pylint: disable=too-many-locals, too-many-statements, too-many-branches

    analogOut = device.analogOut
    analogIn  = device.analogIn

    if analogOut.count() == 0 or analogIn.channelCount() == 0:
        print("The device has no analog output channels that can be used for this demo.")
        return

    CH1 = 0

    # We don't do Noise, Custom, and Play.
    waveform_functions = [
        DwfAnalogOutFunction.DC,
        DwfAnalogOutFunction.Sine,
        DwfAnalogOutFunction.Square,
        DwfAnalogOutFunction.Triangle,
        DwfAnalogOutFunction.RampUp,
        DwfAnalogOutFunction.RampDown,
        DwfAnalogOutFunction.Pulse,
        DwfAnalogOutFunction.Trapezium,
        DwfAnalogOutFunction.SinePower
    ]

    input_frequency_setpoint = 1e6 # 1 MHz

    symmetry_setpoint = 0
    stepsize = 5

    while True:

        plt.clf()

        plt.gcf().set_size_inches(16, 9)
        plt.subplots_adjust(hspace=0.4)

        plt.suptitle("Effect of the symmetry setting on different wave-shape functions\nsymmetry parameter value = {}".
                     format(symmetry_setpoint))

        for (waveform_index, waveform_func) in enumerate(waveform_functions, 1):

            # Prepare analog-out device

            analogOut.reset(-1)

            set_analog_output_node_settings(analogOut, CH1, DwfAnalogOutNode.Carrier,
                                            enable    = True,
                                            func      = waveform_func,
                                            frequency = input_frequency_setpoint / 16384 * num_periods,
                                            amplitude = 1.0,
                                            offset    = 0.0,
                                            symmetry  = symmetry_setpoint,
                                            phase     = 0.0)

            carrier_settings = get_analog_output_node_settings(analogOut, CH1, DwfAnalogOutNode.Carrier)

            analogOut.idleSet(CH1, DwfAnalogOutIdle.Initial)

            analogOut.triggerSourceSet(CH1, DwfTriggerSource.PC)

            analogOut.configure(CH1, True)

            # Prepare analog-in device

            analogIn.reset()

            analogIn.frequencySet(input_frequency_setpoint)
            input_frequency = analogIn.frequencyGet()

            input_buffer_size      = analogIn.bufferSizeGet()
            input_capture_duration = input_buffer_size / input_frequency

            analogIn.channelEnableSet(CH1, True)
            analogIn.channelFilterSet(CH1, DwfAnalogInFilter.Average)
            analogIn.channelRangeSet(CH1, 5.0)

            analogIn.acquisitionModeSet(DwfAcquisitionMode.Single)

            analogIn.triggerSourceSet(DwfTriggerSource.PC)

            analogIn.triggerPositionSet(0.5 * input_capture_duration)

            analogIn.configure(False, True)

            # Start both

            while True:
                status = analogIn.status(True)
                if status == DwfState.Armed:
                    break

            device.triggerPC()

            # Monitor analogIn

            while True:
                status = analogIn.status(True)
                if status == DwfState.Done:
                    break

            input_samples = analogIn.statusData(CH1, input_buffer_size)

            t = np.arange(input_buffer_size) / input_frequency
            predicted_samples = analog_output_signal_simulator(carrier_settings, None, None, t)

            # The "x" value goes from 0 to just under num_periods.
            x = np.arange(input_buffer_size) / input_buffer_size * num_periods

            plt.subplot(3, 3, waveform_index)
            plt.title(waveform_func.name)
            plt.xlim(-0.1, num_periods + 0.1)
            plt.ylim(-1.1, 1.1)

            plt.plot(x, predicted_samples, lw=5.0, c='cyan', label="calculated")
            plt.plot(x, input_samples, c='blue', label="measured")
            for period_boundary in range(1, num_periods):
                plt.axvline(period_boundary, c='gray')

            if waveform_index == 1:
                plt.legend(loc="upper left")

            if waveform_index == 8:
                plt.xlabel("period")

            if waveform_index == 4:
                plt.ylabel("signal")

        analogIn.reset()
        analogOut.reset(-1)

        plt.pause(0.200)

        if len(plt.get_fignums()) == 0:
            # User has closed the window, finish.
            break

        # Proceed to next symmetry setting.
        symmetry_setpoint += stepsize
        if abs(symmetry_setpoint) > 100:
            stepsize *= -1
            symmetry_setpoint += 2 * stepsize
def process_samples(queue):
    global decoder
    global should_finish
    global sat_gps_dict
    global sat_plot_lines

    ##########################################
    # configure the matplotlib plots
    if realtime_plotting:
        # Create a figure with 4 subplots
        const_fig, ax_arr = plt.subplots(2, 2, num=10)

        # Plot of the complex IQ samples
        cost_line, = ax_arr[0, 0].plot([
            0,
        ], 'bx')
        ax_arr[0, 0].set_xlim((-2, 2))
        ax_arr[0, 0].set_ylim((-2, 2))
        ax_arr[0, 0].set_title("Complex I/Q samples")
        ax_arr[0, 0].set_xlabel("I")
        ax_arr[0, 0].set_ylabel("Q")

        # Plot of the channel spectrum
        fft_line, = ax_arr[1, 0].plot([
            0,
        ], 'b')
        ax_arr[1, 0].set_xlim((-6e3, 6e3))
        ax_arr[1, 0].set_ylim((-50, 20))
        ax_arr[1, 0].set_title("Channel Spectrum")
        ax_arr[1, 0].set_xlabel("Frequency (centered on channel) Hz")
        ax_arr[1, 0].set_ylabel("Power (dB)")

        # Plot of globe and ground station location
        img = plt.imread("./map.jpg")
        img_plot = ax_arr[1, 1].imshow(img, extent=[-180, 180, -90, 90])
        loc_plot, = ax_arr[1, 1].plot(lon, lat, 'ro')

        ax_arr[0, 1].axis('off')
        plt.pause(0.0001)
    ##########################################

    tic = time()

    while 1:
        try:
            samples, context = queue.get()
            if context == None:
                break

            doppler = context['doppler']
            sat_name = context['sat_name']
            az = context['azimuth']
            el = context['elevation']

            tic = time()
            packet_list = decoder.decode_samples_to_packets(samples, doppler)
            # if should_save_to_file:
            #     do saving stuff
            decoder.parse_packets()

            if realtime_plotting:
                if len(decoder.decimated_samples) == 0:
                    # This happens when the receiver resets
                    continue

                # Get the welch spectrum for just the channel we are decoding
                f, pxx = welch(decoder.decimated_samples, fs=decoder.sample_rate/decoder.decimation, \
                               return_onesided=False, nperseg= int(len(decoder.decimated_samples)/10), \
                               scaling='density')
                f = (np.roll(f, int(len(f) / 2)))
                pxx = np.roll(pxx, int(len(pxx) / 2))
                pxx = 20 * np.log10(pxx)
                pxx -= np.median(pxx)

                symbols = decoder.symbols
                symbols /= np.median(np.abs(symbols))

                # plot IQ samples
                cost_line.set_xdata(symbols.real)
                cost_line.set_ydata(symbols.imag)
                ax_arr[0, 0].draw_artist(ax_arr[0, 0].patch)
                ax_arr[0, 0].draw_artist(cost_line)

                # plot spectrum
                fft_line.set_xdata(f)
                fft_line.set_ydata(pxx)
                ax_arr[1, 0].draw_artist(ax_arr[1, 0].patch)
                ax_arr[1, 0].draw_artist(fft_line)

                # Check if we have new lat/long for satellite
                # If we do, plot the track of the satellite since we've been recording
                # This track is from received lat/long (not from TLE position)
                if decoder.sat_lon != 0.0 and decoder.sat_lat != 0.0:
                    if abs(decoder.sat_lon) < 180 and abs(
                            decoder.sat_lat) < 90:
                        sat_lat_lon = (decoder.sat_lon, decoder.sat_lat)
                        if sat_name not in sat_gps_dict:
                            sat_gps_dict[sat_name] = [sat_lat_lon]
                            sat_plot_lines.append(ax_arr[1, 1].plot(
                                [
                                    0,
                                ], 'D:', color='cyan', markevery=[-1])[0])
                        else:
                            if sat_lat_lon not in sat_gps_dict[sat_name]:
                                sat_gps_dict[sat_name].append(sat_lat_lon)

                        # Only update the plot when we get a new lat/long
                        ax_arr[1, 1].draw_artist(ax_arr[1, 1].patch)
                        ax_arr[1, 1].draw_artist(img_plot)
                        ax_arr[1, 1].draw_artist(loc_plot)
                        for idx, key in enumerate(sat_gps_dict):
                            lon_lat_arr = sat_gps_dict[key]
                            lons, lats = zip(*lon_lat_arr)
                            sat_plot_lines[idx].set_xdata(lons)
                            sat_plot_lines[idx].set_ydata(lats)
                            text = ax_arr[1, 1].text(lons[-1],
                                                     lats[-1],
                                                     "{}".format(key),
                                                     color='cyan',
                                                     wrap=True)
                            ax_arr[1, 1].draw_artist(sat_plot_lines[idx])
                            ax_arr[1, 1].draw_artist(text)

                toc = time()
                # The time ratio is the amount of time it takes to process a batch of samples
                # divided by the time that it takes to record the samples.
                # A time ratio over 1.0 means that you are falling behind.
                time_ratio = sdr.sample_rate / len(samples) * (toc - tic)

                bad_percent = decoder.bad_packets / (
                    decoder.bad_packets + decoder.good_packets + 0.1)
                good_percent = decoder.good_packets / (
                    decoder.bad_packets + decoder.good_packets + 0.1)

                text0 = ax_arr[0,
                               1].text(0.10, 0.90,
                                       "Satellite Name: {}".format(sat_name))
                text1 = ax_arr[0, 1].text(
                    0.10, 0.80,
                    "Lat/Lon: {:6.3f} {:6.3f}".format(decoder.sat_lon,
                                                      decoder.sat_lat))
                text2 = ax_arr[0, 1].text(
                    0.10, 0.70,
                    "Azimuth: {:6.0f}   Elevation: {:6.0f}".format(az, el))
                text3 = ax_arr[0, 1].text(
                    0.10, 0.60,
                    "Bad Packets %:  {:4.1f}".format(bad_percent * 100.0))
                text4 = ax_arr[0, 1].text(
                    0.10, 0.50,
                    "Good Packets %: {:4.1f}".format(good_percent * 100.0))
                text5 = ax_arr[0, 1].text(
                    0.10, 0.40, "Time ratio:     {:4.2f}".format(time_ratio))

                ax_arr[0, 1].draw_artist(ax_arr[0, 1].patch)
                ax_arr[0, 1].draw_artist(text0)
                ax_arr[0, 1].draw_artist(text1)
                ax_arr[0, 1].draw_artist(text2)
                ax_arr[0, 1].draw_artist(text3)
                ax_arr[0, 1].draw_artist(text4)
                ax_arr[0, 1].draw_artist(text5)

                const_fig.canvas.update()
                const_fig.canvas.flush_events()

                # If the user closes the figure, fignums goes to 0
                # Then we'll close this process and exit the program
                fignums = plt.get_fignums()
                if len(fignums) == 0:
                    should_finish = True
                    break

        # Catch ctrl+c and exit program
        except KeyboardInterrupt:
            break
    return 0
 def none_selected(self, state):
     FreeCAD.FEM_dialog["results_type"] = "None"
     self.set_result_stats("mm", 0.0, 0.0)
     self.reset_mesh_color()
     if len(plt.get_fignums()) > 0:
         plt.close()
Beispiel #42
0
 def open_figs(cls) -> Sequence[Figure]:
     """
     Returns all currently open figures.
     """
     warnings.warn("open_figs will be removed; use list_open_figs instead", DeprecationWarning)
     return [plt.figure(num=i) for i in plt.get_fignums()]
Beispiel #43
0
    resolutions = [10, 50, 100, 150, 190, 224]
    dfs = []
    for hardware in hardwares:
        for convolution_type in convolution_types:
            for scale in scales:
                for resolution in resolutions:
                    plt_figure()
                    dfs.append(load_and_plot(hardware, convolution_type, scale, resolution))

    df = pd.concat(
        dfs
    )

    grouped = df.groupby(["Hardware", "ConvolutionType", "Scale", "Resolution"])

    #plt_figure()

    means = grouped.aggregate(np.mean)

    ax = means.unstack(level=0).unstack(level=0).unstack(level=0).TotalTime.plot(marker='o', linestyle='--')
    ax.set_ylabel("Convolution Running Time (ms)")

    # plt.show()
    
    figs = [plt.figure(n) for n in plt.get_fignums()]
    figno = 0
    for fig in figs:
        fig.savefig("figure_{}.pdf".format(figno))
        fig.savefig("figure_{}.pgf".format(figno))
        figno = figno + 1
Beispiel #44
0
time_tick_count = 10
binned_tick_inds = np.arange(0, len(binned_t_vec),
                             len(binned_t_vec) // time_tick_count)
binned_tick_vals = np.arange(time_lims[0], time_lims[1],
                             np.abs(np.diff(time_lims)) // time_tick_count)
binned_tick_vals -= t_stim
max_trials = 15
num_plots = int(np.ceil(len(good_trial_list) / max_trials))
trial_inds_list = [good_trial_list[x*max_trials:(x+1)*max_trials] \
                        for x in np.arange(num_plots)]

create_changepoint_plots(plot_spikes, tau_samples, trial_inds_list, title_dict,
                         taste_label, sorted_region_units, binned_tick_inds,
                         binned_tick_vals)

for fig_num in tqdm(plt.get_fignums()):
    plt.figure(fig_num)
    plt.savefig(os.path.join(\
            this_plot_dir,'good_trials_sorted_nrns{}'.format(fig_num)))#,dpi=300)
    plt.close(fig_num)

########################################
cut_spikes = np.array(dat.spikes)[..., time_lims[0]:time_lims[1]]
spike_array_long = np.reshape(cut_spikes, (-1, *cut_spikes.shape[-2:]))
spike_array_long = spike_array_long[:, fin_sort_order]

raw_tick_inds = np.arange(0, cut_spikes.shape[-1],
                          cut_spikes.shape[-1] // time_tick_count)
scaled_tau_samples = (tau_samples /
                      binned_dat.shape[-1]) * cut_spikes.shape[-1]
Beispiel #45
0
def test_plot_ica_sources():
    """Test plotting of ICA panel."""
    raw = read_raw_fif(raw_fname).crop(0, 1).load_data()
    picks = _get_picks(raw)
    epochs = _get_epochs()
    raw.pick_channels([raw.ch_names[k] for k in picks])
    ica_picks = pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=False,
                           ecg=False,
                           eog=False,
                           exclude='bads')
    ica = ICA(n_components=2)
    ica.fit(raw, picks=ica_picks)
    ica.exclude = [1]
    fig = ica.plot_sources(raw)
    assert len(plt.get_fignums()) == 1
    # change which component is in ICA.exclude (click data trace to remove
    # current one; click name to add other one)
    fig.canvas.draw()
    x = fig.mne.traces[1].get_xdata()[5]
    y = fig.mne.traces[1].get_ydata()[5]
    _fake_click(fig, fig.mne.ax_main, (x, y), xform='data')  # exclude = []
    _click_ch_name(fig, ch_index=0, button=1)  # exclude = [0]
    fig.canvas.key_press_event(fig.mne.close_key)
    _close_event(fig)
    assert len(plt.get_fignums()) == 0
    assert_array_equal(ica.exclude, [0])
    plt.close('all')

    # dtype can change int->np.int64 after load, test it explicitly
    ica.n_components_ = np.int64(ica.n_components_)

    # test clicks on y-label (need >2 secs for plot_properties() to work)
    long_raw = read_raw_fif(raw_fname).crop(0, 5).load_data()
    fig = ica.plot_sources(long_raw)
    assert len(plt.get_fignums()) == 1
    fig.canvas.draw()
    _fake_click(fig, fig.mne.ax_main, (-0.1, 0), xform='data', button=3)
    assert len(fig.mne.child_figs) == 1
    assert len(plt.get_fignums()) == 2
    # close child fig directly (workaround for mpl issue #18609)
    fig.mne.child_figs[0].canvas.key_press_event('escape')
    assert len(plt.get_fignums()) == 1
    fig.canvas.key_press_event(fig.mne.close_key)
    assert len(plt.get_fignums()) == 0
    del long_raw

    # test with annotations
    orig_annot = raw.annotations
    raw.set_annotations(Annotations([0.2], [0.1], 'Test'))
    fig = ica.plot_sources(raw)
    assert len(fig.mne.ax_main.collections) == 1
    assert len(fig.mne.ax_hscroll.collections) == 1
    raw.set_annotations(orig_annot)

    # test error handling
    raw.info['bads'] = ['MEG 0113']
    with pytest.raises(RuntimeError, match="Raw doesn't match fitted data"):
        ica.plot_sources(inst=raw)
    epochs.info['bads'] = ['MEG 0113']
    with pytest.raises(RuntimeError, match="Epochs don't match fitted data"):
        ica.plot_sources(inst=epochs)
    epochs.info['bads'] = []

    # test w/ epochs and evokeds
    ica.plot_sources(epochs)
    ica.plot_sources(epochs.average())
    evoked = epochs.average()
    fig = ica.plot_sources(evoked)
    # Test a click
    ax = fig.get_axes()[0]
    line = ax.lines[0]
    _fake_click(fig, ax, [line.get_xdata()[0], line.get_ydata()[0]], 'data')
    _fake_click(fig, ax, [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
    # plot with bad channels excluded
    ica.exclude = [0]
    ica.plot_sources(evoked)
    ica.labels_ = dict(eog=[0])
    ica.labels_['eog/0/crazy-channel'] = [0]
    ica.plot_sources(evoked)  # now with labels
    with pytest.raises(ValueError, match='must be of Raw or Epochs type'):
        ica.plot_sources('meeow')
Beispiel #46
0
def run_code(result, run_req):
    # {{{ silence matplotlib font cache warnings

    import warnings
    warnings.filterwarnings("ignore",
                            message="Matplotlib is building the font cache.*")

    # }}}

    # {{{ compile code

    if getattr(run_req, "setup_code", None):
        try:
            setup_code = compile(run_req.setup_code, "[setup code]", 'exec')
        except Exception:
            package_exception(result, "setup_compile_error")
            return
    else:
        setup_code = None

    try:
        user_code = compile(run_req.user_code, "[user code]", 'exec')
    except Exception:
        package_exception(result, "user_compile_error")
        return

    if getattr(run_req, "test_code", None):
        try:
            test_code = compile(run_req.test_code, "[test code]", 'exec')
        except Exception:
            package_exception(result, "test_compile_error")
            return
    else:
        test_code = None

    # }}}

    if hasattr(run_req, "compile_only") and run_req.compile_only:
        result["result"] = "success"
        return

    # {{{ run code

    data_files = {}
    if hasattr(run_req, "data_files"):
        from base64 import b64decode
        for name, contents in run_req.data_files.items():
            data_files[name] = b64decode(contents.encode())

    generated_html = []
    result["html"] = generated_html

    def output_html(s):
        generated_html.append(s)

    feedback = Feedback()
    maint_ctx = {
        "feedback": feedback,
        "user_code": run_req.user_code,
        "data_files": data_files,
        "output_html": output_html,
        "GradingComplete": GradingComplete,
    }

    if setup_code is not None:
        try:
            maint_ctx["_MODULE_SOURCE_CODE"] = run_req.setup_code
            exec(setup_code, maint_ctx)
        except BaseException:
            package_exception(result, "setup_error")
            return

    user_ctx = {}
    if hasattr(run_req, "names_for_user"):
        for name in run_req.names_for_user:
            if name not in maint_ctx:
                result["result"] = "setup_error"
                result["message"] = "Setup code did not define '%s'." % name

            user_ctx[name] = maint_ctx[name]

    from copy import deepcopy
    user_ctx = deepcopy(user_ctx)

    try:
        user_ctx["_MODULE_SOURCE_CODE"] = run_req.user_code
        exec(user_code, user_ctx)
    except BaseException:
        package_exception(result, "user_error")
        return

    # {{{ export plots

    if "matplotlib" in sys.modules:
        import matplotlib.pyplot as pt
        from io import BytesIO
        from base64 import b64encode

        format = "png"
        mime = "image/png"
        figures = []

        for fignum in pt.get_fignums():
            pt.figure(fignum)
            bio = BytesIO()
            try:
                pt.savefig(bio, format=format)
            except Exception:
                pass
            else:
                figures.append(
                    (fignum, mime, b64encode(bio.getvalue()).decode()))

        result["figures"] = figures

    # }}}

    if hasattr(run_req, "names_from_user"):
        for name in run_req.names_from_user:
            if name not in user_ctx:
                feedback.add_feedback(
                    "Required answer variable '%s' is not defined." % name)
                maint_ctx[name] = None
            else:
                maint_ctx[name] = user_ctx[name]

    if test_code is not None:
        try:
            maint_ctx["_MODULE_SOURCE_CODE"] = run_req.test_code
            exec(test_code, maint_ctx)
        except GradingComplete:
            pass
        except BaseException:
            package_exception(result, "test_error")
            return

    result["points"] = feedback.points
    result["feedback"] = feedback.feedback_items

    # }}}

    result["result"] = "success"
Beispiel #47
0
def test_InstallationGanttChartPlot(core, project, tree):

    project = deepcopy(project)
    module_menu = ModuleMenu()
    project_menu = ProjectMenu()

    mod_name = "Mock Module"
    module_menu.activate(core, project, mod_name)
    project_menu.initiate_dataflow(core, project)

    mod_branch = tree.get_branch(core, project, mod_name)

    plan = [
        'Installation of support structure',
        'Installation of driven piles anchors/foundations',
        'Installation of mooring systems with direct-embedment anchors',
        'Installation of gravity based foundations',
        'Installation of mooring systems with pile anchors',
        'Installation of mooring systems with drag-embedment anchors',
        'Installation of mooring systems with suction-embedment anchors',
        'Installation of collection point (surface piercing)',
        'Installation of collection point (seabed)',
        'Installation of dynamic cables',
        'Installation of static export cables',
        'Installation of static array cables',
        'Installation of external cable protection', 'Installation of devices'
    ]
    install_support_structure_dates = {
        'Start': dt.datetime(
            2000,
            6,
            25,
            4,
            55,
            31,
        ),
        'End': dt.datetime(2000, 7, 29, 3, 24, 19),
        'Depart': dt.datetime(2000, 7, 25, 7, 55, 31)
    }
    install_devices_dates = {
        'Start': dt.datetime(
            2000,
            6,
            25,
            4,
            55,
            31,
        ),
        'End': dt.datetime(2000, 7, 29, 3, 24, 19),
        'Depart': dt.datetime(2000, 7, 25, 7, 55, 31)
    }
    install_dynamic_cable_dates = {
        'Start': dt.datetime(2000, 5, 2, 19, 11, 47),
        'End': dt.datetime(2000, 6, 18, 19, 12, 9),
        'Depart': dt.datetime(2000, 6, 14, 15, 11, 47)
    }
    install_export_cable_dates = {
        'Start': dt.datetime(2000, 5, 2, 19, 11, 47),
        'End': dt.datetime(2000, 6, 18, 19, 12, 9),
        'Depart': dt.datetime(2000, 6, 14, 15, 11, 47)
    }
    install_array_cable_dates = {
        'Start': dt.datetime(2000, 5, 2, 21, 48, 59),
        'End': dt.datetime(2000, 6, 19, 0, 55, 31),
        'Depart': dt.datetime(2000, 6, 14, 15, 48, 59)
    }
    install_surface_piercing_substation_dates = {
        'Start': dt.datetime(2000, 1, 5, 1, 0),
        'End': dt.datetime(2000, 4, 30, 17, 42, 6),
        'Depart': dt.datetime(2000, 4, 26, 7, 0)
    }
    install_subsea_collection_point_dates = {
        'Start': dt.datetime(2000, 1, 5, 1, 0),
        'End': dt.datetime(2000, 4, 30, 17, 42, 6),
        'Depart': dt.datetime(2000, 4, 26, 7, 0)
    }
    install_cable_protection_dates = {
        'Start': dt.datetime(2000, 1, 5, 1, 0),
        'End': dt.datetime(2000, 4, 30, 17, 42, 6),
        'Depart': dt.datetime(2000, 4, 26, 7, 0)
    }
    install_driven_piles_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_direct_embedment_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_gravity_based_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_pile_anchor_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_drag_embedment_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_suction_embedment_dates = {
        'Start': dt.datetime(2000, 1, 3, 5, 0),
        'End': dt.datetime(2000, 2, 11, 5, 4, 21),
        'Depart': dt.datetime(2000, 2, 4, 15, 0)
    }
    install_device_times = pd.DataFrame({
        'Preparation': {
            0: 148.0,
            1: 100
        },
        'Operations': {
            0: 32.0,
            1: 30
        },
        'Transit': {
            0: 59.480022782839399,
            1: 60
        },
        'Component': {
            0: 'Device',
            1: 'Support Structure'
        },
        'Waiting': {
            0: 0,
            1: 0
        }
    })
    install_electrical_times = pd.DataFrame({
        'Preparation': {
            0: 49.49,
            1: 52.11,
            2: 97.0,
            3: 90,
            4: 10
        },
        'Operations': {
            0: 7.48,
            1: 12.72,
            2: 21.0,
            3: 20,
            4: 50
        },
        'Transit': {
            0: 92.51,
            1: 92.38,
            2: 85.70,
            3: 80,
            4: 90
        },
        'Component': {
            0: 'Export Cables',
            1: 'Inter-Array Cables',
            2: 'Collection Points',
            3: 'Dynamic Cables',
            4: 'External Cable Protection'
        },
        'Waiting': {
            0: 0,
            1: 0,
            2: 0,
            3: 0,
            4: 0
        }
    })
    install_mooring_times = pd.DataFrame({
        'Preparation': {
            0: 53.0,
            1: 53.0,
            2: 53.0,
            3: 53.0,
            4: 53.0,
            5: 53.0
        },
        'Operations': {
            0: 83.00,
            1: 83.00,
            2: 83.00,
            3: 83.00,
            4: 83.00,
            5: 83.00
        },
        'Transit': {
            0: 75.06,
            1: 75.06,
            2: 75.06,
            3: 75.06,
            4: 75.06,
            5: 75.06
        },
        'Component': {
            0: 'Driven Piles',
            1: "Direct-Embedment Anchors",
            2: "Gravity Based Foundations",
            3: "Pile Anchors",
            4: "Drag-Embedment Anchors",
            5: "Suction-Caisson Anchors"
        },
        'Waiting': {
            0: 0,
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
        }
    })

    identifiers = [
        "project.installation_plan", "project.install_support_structure_dates",
        "project.install_devices_dates", "project.install_dynamic_cable_dates",
        "project.install_export_cable_dates",
        "project.install_array_cable_dates",
        "project.install_surface_piercing_substation_dates",
        "project.install_subsea_collection_point_dates",
        "project.install_cable_protection_dates",
        "project.install_driven_piles_dates",
        "project.install_direct_embedment_dates",
        "project.install_gravity_based_dates",
        "project.install_pile_anchor_dates",
        "project.install_drag_embedment_dates",
        "project.install_suction_embedment_dates",
        "project.device_phase_installation_times",
        "project.electrical_phase_installation_times",
        "project.mooring_phase_installation_times"
    ]

    # Force addition of variables
    core.add_datastate(
        project,
        identifiers=identifiers,
        values=[
            plan, install_support_structure_dates, install_devices_dates,
            install_dynamic_cable_dates, install_export_cable_dates,
            install_array_cable_dates,
            install_surface_piercing_substation_dates,
            install_subsea_collection_point_dates,
            install_cable_protection_dates, install_driven_piles_dates,
            install_direct_embedment_dates, install_gravity_based_dates,
            install_pile_anchor_dates, install_drag_embedment_dates,
            install_suction_embedment_dates, install_device_times,
            install_electrical_times, install_mooring_times
        ])

    gantt = mod_branch.get_output_variable(core, project,
                                           "project.installation_plan")
    gantt.plot(core, project, "Installation Gantt Chart")

    assert len(plt.get_fignums()) == 1

    plt.close("all")
Beispiel #48
0
def test_plot_ica_sources():
    """Test plotting of ICA panel."""
    raw = read_raw_fif(raw_fname).crop(0, 1).load_data()
    picks = _get_picks(raw)
    epochs = _get_epochs()
    raw.pick_channels([raw.ch_names[k] for k in picks])
    ica_picks = pick_types(raw.info,
                           meg=True,
                           eeg=False,
                           stim=False,
                           ecg=False,
                           eog=False,
                           exclude='bads')
    ica = ICA(n_components=2, max_pca_components=3, n_pca_components=3)
    ica.fit(raw, picks=ica_picks)
    ica.exclude = [1]
    fig = ica.plot_sources(raw)
    fig.canvas.key_press_event('escape')
    # Sadly close_event isn't called on Agg backend and the test always passes.
    assert_array_equal(ica.exclude, [1])
    plt.close('all')

    # dtype can change int->np.int64 after load, test it explicitly
    ica.n_components_ = np.int64(ica.n_components_)
    fig = ica.plot_sources(raw)
    # also test mouse clicks
    data_ax = fig.axes[0]
    assert len(plt.get_fignums()) == 1
    _fake_click(fig, data_ax, [-0.1, 0.9])  # click on y-label
    assert len(plt.get_fignums()) == 2
    ica.exclude = [1]
    ica.plot_sources(raw)

    # test with annotations
    orig_annot = raw.annotations
    raw.set_annotations(Annotations([0.2], [0.1], 'Test'))
    fig = ica.plot_sources(raw)
    assert len(fig.axes[0].collections) == 1
    assert len(fig.axes[1].collections) == 1
    raw.set_annotations(orig_annot)

    raw.info['bads'] = ['MEG 0113']
    with pytest.raises(RuntimeError, match="Raw doesn't match fitted data"):
        ica.plot_sources(inst=raw)
    ica.plot_sources(epochs)
    epochs.info['bads'] = ['MEG 0113']
    with pytest.raises(RuntimeError, match="Epochs don't match fitted data"):
        ica.plot_sources(inst=epochs)
    epochs.info['bads'] = []
    ica.plot_sources(epochs.average())
    evoked = epochs.average()
    fig = ica.plot_sources(evoked)
    # Test a click
    ax = fig.get_axes()[0]
    line = ax.lines[0]
    _fake_click(fig, ax, [line.get_xdata()[0], line.get_ydata()[0]], 'data')
    _fake_click(fig, ax, [ax.get_xlim()[0], ax.get_ylim()[1]], 'data')
    # plot with bad channels excluded
    ica.exclude = [0]
    ica.plot_sources(evoked)
    ica.labels_ = dict(eog=[0])
    ica.labels_['eog/0/crazy-channel'] = [0]
    ica.plot_sources(evoked)  # now with labels
    with pytest.raises(ValueError, match='must be of Raw or Epochs type'):
        ica.plot_sources('meeow')
    plt.close('all')
Beispiel #49
0
 def do_close_all(self, arg):
     """ Close all plots except the main one. """
     for fig in plt.get_fignums()[1:]:
         plt.close(fig)
Beispiel #50
0
 def __enter__(self):
     self._enter_fignums = pl.get_fignums()
     return self
Beispiel #51
0
    def show_figure_box(figurebox, hold=False):
        """
        Display the figure in the figurebox.
        The figure has to be added to the current pyplot backend.            
        
        :param bool hold: Replace the figure in the current selected panel by the new figure
        """
        #unpickling a figure will call show when interactive is on
        #But this will be on the backend of the pickling process
        #All callbacks related to gui calls where removed by the pickling
        #

        from ...matplotbe import new_figure_manager_given_figure

        import matplotlib.pyplot as plt
        import matplotlib._pylab_helpers as pylab_helpers

        fig = figurebox.figure

        def make_active(event):
            pylab_helpers.Gcf.set_active(mgr)

        if False:
            #Creating a new figure manager
            allnums = plt.get_fignums()
            num = max(allnums) + 1 if allnums else 1

            mgr = new_figure_manager_given_figure(num, fig)
            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            pylab_helpers.Gcf.set_active(mgr)
            fig = mgr.canvas.figure
            fig.number = num

            mgr.show()

        else:
            #Use the current figure mamaner and plot panel
            # Try to replace the figure on the current plot panel with this new figure
            from ...matplotbe import FigureCanvasGh2
            panids = gui.get_panel_ids('plot')

            if not hold or len(panids) == 0:
                ignore, num = PlotGuiProxy.new()
            else:
                num = panids[-1]

            plotpanel = gui.qapp.panels['plot'][num]
            fig.number = num
            plotpanel.showNewFigure(fig)

            #Hack to call the correct set_active
            #Note that Gcf.set_active() is mapped to panel.select() in plotpanel.py
            mgr = fig.canvas.manager
            mgr._cidgcf = mgr.canvas.mpl_connect('button_press_event',
                                                 make_active)

            plotpanel.show()

        # I don't get the interactive update working
        # After a function lik grid(), xlabel(), ..
        # the stale property is set to  True
        # This should trigger the call of stale_callback on the figure (=Artist)
        # or stall_callback on the axis object

        #Configure stale call backs
        #The hierarchy of the figure can be type of figure dependend
        try:
            from matplotlib.pyplot import _auto_draw_if_interactive
            from matplotlib.figure import _stale_figure_callback
            from matplotlib.artist import _stale_axes_callback

            fig.stale_callback = _auto_draw_if_interactive

            for ax in fig.axes:
                ax.stale_callback = _stale_figure_callback
                ax.xaxis.stale_callback = _stale_axes_callback
                ax.yaxis.stale_callback = _stale_axes_callback
        except:
            logger.error('Could not configure all interactive callbacks')

        return num
Beispiel #52
0
def get_kick(orbit, phase, tune, plot=False, error_curves=False):
    """ Find the kick in the orbit.

        Parameters
        ----------
        orbit : np.array
            Orbit.
        phase : np.array
            Phase.
        tune : float
            The orbit tune.
        plot : bool, optional.
            If True, plot the orbit with the kick position, else don't.
            Default to False.

        Returns
        -------
        kick_phase : float
            The phase where the kick was found.
        cos_coefficients : [a, b]
            a and b so that the sine is a*cos(b+phase)

    """
    bpm_nb = orbit.size
    rms_tab = []
    best_rms = 0
    cos_coefficients = []

    # duplicate the signal to find the sine between the kick and its duplicate
    signal_exp = np.concatenate((orbit, orbit))
    phase_exp = np.concatenate((phase, phase + tune * 2 * pi))

    # shift the sine between each BPM and its duplicate and find the best
    # match
    for i in range(bpm_nb):
        signal_t = signal_exp[i:i + bpm_nb]
        phase_t = phase_exp[i:i + bpm_nb]
        _, b, c = fit_sine(signal_t, phase_t, False)
        cos_coefficients.append([b, c])

        y = b * cos(c + phase_t)

        # calculate the RMS. the best fit means that the kick is around
        # the ith BPMs
        rms = sum(pow(y - signal_t, 2))
        rms_tab.append(rms)
        if rms < best_rms or i == 0:
            best_rms = rms
            i_best = i

    b, c = cos_coefficients[i_best]
    apriori_phase = phase[i_best]
    k = int((apriori_phase + c) / np.pi + tune)
    solutions = -c - np.pi * tune + np.array([k, k + 1]) * np.pi
    idx = np.argmin(abs(solutions - apriori_phase))
    kick_phase = solutions[idx]

    if error_curves:
        transl = bpm_nb // 2 - i_best
        rms_tab = np.roll(rms_tab, transl)
        cos_coef_tmp = np.array(np.roll(cos_coefficients, transl))

        offset = 2 * pi
        n_lspace = 10000

        interval_rel = np.linspace(-offset, +offset, n_lspace)
        interval = interval_rel + phase_exp[i_best]

        plt.figure('skcore::get_kick -- Error curves [{}]'.format(
            len(plt.get_fignums())))
        plt.subplot(211)
        plt.title('1- Sine Fit')
        idx_range = range(-len(rms_tab) // 2, len(rms_tab) // 2)
        plt.plot(idx_range, rms_tab, label='RMS')
        plt.plot(idx_range,
                 cos_coef_tmp[:, 0] * 100,
                 label=r'Amplitude $\times 100$')
        plt.plot(idx_range,
                 -cos_coef_tmp[:, 1] * 1000 / (2 * pi),
                 label=r'Phase $\times (-1000 / 2\pi)$')
        plt.legend(loc='best', fancybox=True, frameon=True)
        plt.ylabel('RMS')
        plt.xlabel(
            'Distance from chosen one (in indexes), chosen one is {}'.format(
                i_best))
        plt.grid()

        plt.subplot(212)
        plt.title('2- Find kick')
        plt.plot(
            interval_rel,
            abs(b * cos(interval + c) - b * cos(interval + c + 2 * pi * tune)))
        tick_vals = []
        tick_labels = []
        amp_max = int(offset // pi)
        for x in range(-amp_max, amp_max + 1):
            if x == 0:
                tick_labels.append('0')
                tick_vals.append(0)
            elif x == 1:
                tick_labels.append(r'$\pi$')
                tick_vals.append(pi)
            elif x == -1:
                tick_labels.append(r'$-\pi$')
                tick_vals.append(-pi)
            else:
                tick_labels.append(r'$' + str(x) + '\pi$')
                tick_vals.append(x * pi)

        plt.xticks(tick_vals, tick_labels)
        plt.ylabel('Size of curve jump')
        plt.xlabel('Position of kick (relative to initial one) ')
        plt.tight_layout()

    if plot:
        plt.figure('skcore::get_kick -- Orbit plot [{}]'.format(
            len(plt.get_fignums())))
        plt.plot(phase / (2 * pi), orbit, '.', ms=10, label='Real orbit')
        sine_signal, phase_th = build_sine(kick_phase, tune,
                                           cos_coefficients[i_best % bpm_nb])
        plt.plot(phase_th / (2 * pi), sine_signal, label='Reconstructed sine')
        plt.axvline(kick_phase / (2 * pi),
                    -2,
                    2,
                    color='red',
                    label='Kick position')
        plt.xlabel(r'phase / $2 \pi$')
        plt.legend(fancybox=True, frameon=True)
    return kick_phase, cos_coefficients[i_best % bpm_nb]
Beispiel #53
0
def hist_series(
    self,
    by=None,
    ax=None,
    grid=True,
    xlabelsize=None,
    xrot=None,
    ylabelsize=None,
    yrot=None,
    figsize=None,
    bins=10,
    legend: bool = False,
    **kwds,
):
    import matplotlib.pyplot as plt

    if legend and "label" in kwds:
        raise ValueError("Cannot use both legend and label")

    if by is None:
        if kwds.get("layout", None) is not None:
            raise ValueError(
                "The 'layout' keyword is not supported when 'by' is None")
        # hack until the plotting interface is a bit more unified
        fig = kwds.pop(
            "figure",
            plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize))
        if figsize is not None and tuple(figsize) != tuple(
                fig.get_size_inches()):
            fig.set_size_inches(*figsize, forward=True)
        if ax is None:
            ax = fig.gca()
        elif ax.get_figure() != fig:
            raise AssertionError("passed axis not bound to passed figure")
        values = self.dropna().values
        if legend:
            kwds["label"] = self.name
        ax.hist(values, bins=bins, **kwds)
        if legend:
            ax.legend()
        ax.grid(grid)
        axes = np.array([ax])

        set_ticks_props(axes,
                        xlabelsize=xlabelsize,
                        xrot=xrot,
                        ylabelsize=ylabelsize,
                        yrot=yrot)

    else:
        if "figure" in kwds:
            raise ValueError(
                "Cannot pass 'figure' when using the "
                "'by' argument, since a new 'Figure' instance will be created")
        axes = _grouped_hist(
            self,
            by=by,
            ax=ax,
            grid=grid,
            figsize=figsize,
            bins=bins,
            xlabelsize=xlabelsize,
            xrot=xrot,
            ylabelsize=ylabelsize,
            yrot=yrot,
            legend=legend,
            **kwds,
        )

    if hasattr(axes, "ndim"):
        if axes.ndim == 1 and len(axes) == 1:
            return axes[0]
    return axes
    accuracy_no_sampling = accuracy_score(Y_test, prediction_no_sampling)
    accuracy_over_sample = accuracy_score(Y_test, prediction_over_sampling)
    accuracy_under_sample = accuracy_score(Y_test, prediction_under_sampling)
    subs_metrics[row][2].bar(['no sampling'], [accuracy_no_sampling], color='b')
    subs_metrics[row][2].bar(['over sampling'], [accuracy_over_sample], color='orange')
    subs_metrics[row][2].bar(['under sampling'], [accuracy_under_sample], color='g')
    subs_metrics[row][2].legend([
        "no sampling - {:.0%}".format(accuracy_no_sampling),
        "over sampling - {:.0%}".format(accuracy_over_sample),
        "under sampling - {:.0%}".format(accuracy_under_sample)
    ])

    # Add model name to plots row
    subs_metrics[row][0].set_ylabel(model_name)
    subs_confusion[row][0].set_ylabel(model_name)

    # Clear un-needed figures to coserve memory
    for fig_num in plt.get_fignums():
        if fig_confusion.number != fig_num and fig_metrics.number != fig_num:
            plt.close(fig_num)

    # Save model result to file
    pickle.dump(model_no_sampling, open('./models/' + model_name.lower().replace(' ', '_') + '_no_sampling', 'wb'))
    pickle.dump(model_over_sampling, open('./models/' + model_name.lower().replace(' ', '_') + '_over_sampling', 'wb'));
    pickle.dump(model_under_sampling, open('./models/' + model_name.lower().replace(' ', '_') + '_under_sampling', 'wb'));
    row += 1
    print("====================\n\n")

plt.show()

def findaxes(axisid=None, sca=False, fignum=None):
    '''Convert axisid to a list of matplotlib Axes instances.

    axisid   -- integer zero based index or a matplotlib Axes instance.
                Can be also a list of indices or Axes objects.
                Use the current axis if None or ''.
                When 'all', use all axes in the current figure.
                When axisid >= 111 or 'h,k,l' use suplot(hkl).
    sca      -- flag for setting the last found axis as the current one
                The return value is also changed from a list to the
                last found Axes object or None.
    fignum   -- integer figure number for selecting axis in other
                figure than the current one

    Return a list of Axes instances.
    Return an empty list if no axes exist in the current figure.
    '''
    import numpy
    from matplotlib import pyplot
    from matplotlib import _pylab_helpers
    def _dosca(foundaxes):
        if foundaxes and sca:
            pyplot.sca(foundaxes[-1])
        return foundaxes
    fnums = pyplot.get_fignums()
    if not fnums or (fignum is not None and not fignum in fnums):
        return []
    if fignum is None:
        thefigure = pyplot.gcf()
    else:
        figman = _pylab_helpers.Gcf.figs[fignum]
        thefigure = figman.canvas.figure
    if isinstance(axisid, pyplot.Axes):
        return _dosca([axisid])
    # resolve subplot ids
    issubplotid = (isinstance(axisid, tuple) and len(axisid) == 3 and
            all([numpy.issubdtype(type(i), int) for i in axisid]))
    if issubplotid:
        return _dosca([thefigure.add_subplot(*axisid)])
    issubplotid = numpy.issubdtype(type(axisid), int) and 111 <= axisid
    if issubplotid:
        return _dosca([thefigure.add_subplot(axisid)])
    # find current or all axes
    figaxes = thefigure.get_axes()[:]
    if axisid in (None, ''):
        rv = figaxes and [thefigure.gca()]
        return _dosca(rv)
    if axisid == 'all':
        return _dosca(figaxes)
    elif isinstance(axisid, slice):
        return _dosca(figaxes[axisid])
    # resolve other string IDs
    if isinstance(axisid, basestring):
        words = [w.split() or [''] for w in axisid.split(',')]
        words = sum(words, [])
        return findaxes(words, sca=sca)
    # take care of iterables
    if _isiterablenotstring(axisid):
        rv = []
        fn = thefigure.number
        for aid in axisid:
            if isinstance(aid, basestring):
                if aid.isdigit():
                    rv += findaxes(int(aid), fignum=fn)
                    continue
                if aid.startswith('f') and aid[1:].isdigit():
                    fn = int(aid[1:])
                    continue
            rv += findaxes(aid, fignum=fn)
    # or assume it is an integer index
    else:
        rv = [figaxes[axisid]]
    return _dosca(rv)
Beispiel #56
0
    def test(self):
        baseline_dir, result_dir = _image_directories(self._func)
        if self._style != 'classic':
            raise KnownFailureTest('temporarily disabled until 2.0 tag')
        for fignum, baseline in zip(plt.get_fignums(), self._baseline_images):
            for extension in self._extensions:
                will_fail = not extension in comparable_formats()
                if will_fail:
                    fail_msg = 'Cannot compare %s files on this system' % extension
                else:
                    fail_msg = 'No failure expected'

                orig_expected_fname = os.path.join(baseline_dir,
                                                   baseline) + '.' + extension
                if extension == 'eps' and not os.path.exists(
                        orig_expected_fname):
                    orig_expected_fname = os.path.join(baseline_dir,
                                                       baseline) + '.pdf'
                expected_fname = make_test_filename(
                    os.path.join(result_dir,
                                 os.path.basename(orig_expected_fname)),
                    'expected')
                actual_fname = os.path.join(result_dir,
                                            baseline) + '.' + extension
                if os.path.exists(orig_expected_fname):
                    shutil.copyfile(orig_expected_fname, expected_fname)
                else:
                    will_fail = True
                    fail_msg = ("Do not have baseline image {0} because this "
                                "file does not exist: {1}".format(
                                    expected_fname, orig_expected_fname))

                @knownfailureif(will_fail,
                                fail_msg,
                                known_exception_class=ImageComparisonFailure)
                def do_test():
                    figure = plt.figure(fignum)

                    if self._remove_text:
                        self.remove_text(figure)

                    figure.savefig(actual_fname, **self._savefig_kwarg)

                    err = compare_images(expected_fname,
                                         actual_fname,
                                         self._tol,
                                         in_decorator=True)

                    try:
                        if not os.path.exists(expected_fname):
                            raise ImageComparisonFailure(
                                'image does not exist: %s' % expected_fname)

                        if err:
                            raise ImageComparisonFailure(
                                'images not close: %(actual)s vs. %(expected)s '
                                '(RMS %(rms).3f)' % err)
                    except ImageComparisonFailure:
                        if not check_freetype_version(self._freetype_version):
                            raise KnownFailureTest(
                                "Mismatched version of freetype.  Test requires '%s', you have '%s'"
                                % (self._freetype_version,
                                   ft2font.__freetype_version__))
                        raise

                yield (do_test, )
Beispiel #57
0
def test_plot_epochs_image(epochs):
    """Test plotting of epochs image.

    Note that some of these tests that should pass are triggering MPL
    UserWarnings about tight_layout not being applied ("tight_layout cannot
    make axes width small enough to accommodate all axes decorations"). Calling
    `plt.close('all')` just before the offending test seems to prevent this
    warning, though it's unclear why.
    """
    figs = epochs.plot_image()
    assert len(figs) == 2  # one fig per ch_type (test data has mag, grad)
    assert len(plt.get_fignums()) == 2
    figs = epochs.plot_image()
    assert len(figs) == 2
    assert len(plt.get_fignums()) == 4  # should create new figures
    epochs.plot_image(picks='mag', sigma=0.1)
    epochs.plot_image(picks=[0, 1],
                      combine='mean',
                      ts_args=dict(show_sensors=False))
    epochs.plot_image(picks=[1],
                      order=[0],
                      overlay_times=[0.1],
                      vmin=0.01,
                      title='test')
    plt.close('all')
    epochs.plot_image(picks=[1], overlay_times=[0.1], vmin=-0.001, vmax=0.001)
    plt.close('all')
    epochs.plot_image(picks=[1], vmin=lambda x: x.min())
    # test providing figure
    fig, axs = plt.subplots(3, 1)
    epochs.plot_image(picks=[1], fig=fig)
    # test providing axes instance
    epochs.plot_image(picks=[1], axes=axs[0], evoked=False, colorbar=False)
    plt.close('all')
    # test order=callable
    epochs.plot_image(picks=[0, 1],
                      order=lambda times, data: np.arange(len(data))[::-1])
    # test warning
    with pytest.warns(RuntimeWarning, match='Only one channel in group'):
        epochs.plot_image(picks=[1], combine='mean')
    # group_by should be a dict
    with pytest.raises(TypeError, match="dict or None"):
        epochs.plot_image(group_by='foo')
    # units and scalings keys must match
    with pytest.raises(ValueError, match='Scalings and units must have the'):
        epochs.plot_image(units=dict(hi=1), scalings=dict(ho=1))
    plt.close('all')
    # test invert_y
    epochs.plot_image(ts_args=dict(invert_y=True))
    # can't combine different sensor types
    with pytest.raises(ValueError, match='Cannot combine sensors of differ'):
        epochs.plot_image(group_by=dict(foo=[0, 1, 2]))
    # can't pass both fig and axes
    with pytest.raises(ValueError, match='one of "fig" or "axes" must be'):
        epochs.plot_image(fig='foo', axes='bar')
    # wrong number of axes in fig
    with pytest.raises(ValueError, match='"fig" must contain . axes, got .'):
        epochs.plot_image(fig=plt.figure())
    # only 1 group allowed when fig is passed
    with pytest.raises(ValueError, match='"group_by" can only have one group'):
        fig, axs = plt.subplots(3, 1)
        epochs.plot_image(fig=fig, group_by=dict(foo=[0, 1], bar=[5, 6]))
        del fig, axs
    plt.close('all')
    # must pass correct number of axes (1, 2, or 3)
    with pytest.raises(ValueError, match='is a list, can only plot one group'):
        fig, axs = plt.subplots(1, 3)
        epochs.plot_image(axes=axs)
    for length, kwargs in ([3, dict()], [2, dict(evoked=False)
                                         ], [2, dict(colorbar=False)],
                           [1, dict(evoked=False, colorbar=False)]):
        fig, axs = plt.subplots(1, length + 1)
        epochs.plot_image(picks='mag', axes=axs[:length], **kwargs)
        with pytest.raises(ValueError, match='"axes" must be length ., got .'):
            epochs.plot_image(picks='mag', axes=axs, **kwargs)
    plt.close('all')
    # mismatch between axes dict keys and group_by dict keys
    with pytest.raises(ValueError, match='must match the keys in "group_by"'):
        epochs.plot_image(axes=dict())
    # wrong number of axes in dict
    match = 'each value in "axes" must be a list of . axes, got .'
    with pytest.raises(ValueError, match=match):
        epochs.plot_image(axes=dict(foo=axs[:2], bar=axs[:3]),
                          group_by=dict(foo=[0, 1], bar=[5, 6]))
    # bad value of "combine"
    with pytest.raises(ValueError, match='"combine" must be None, a callable'):
        epochs.plot_image(combine='foo')
    # mismatched picks and overlay_times
    with pytest.raises(ValueError, match='size of overlay_times parameter'):
        epochs.plot_image(picks=[1], overlay_times=[0.1, 0.2])
    # bad overlay times
    with pytest.warns(RuntimeWarning, match='fall outside'):
        epochs.plot_image(overlay_times=[999.])
    # mismatched picks and order
    with pytest.raises(ValueError, match='must match the length of the data'):
        epochs.plot_image(picks=[1], order=[0, 1])
    plt.close('all')
Beispiel #58
0
def show_3D_array\
    (array, index=None, tile_shape=None, scale=None, power=None, \
     suptitle=None, titles=None, title_size=None, \
     zyx=None, xlabel=None, ylabel=None, label=None, \
     cmap=None, show=True):
    '''
    Displays a 3D array as a set of z-slice tiles.
    On successful completion returns 0.
    array     : 3D array
    index     : z-slices index, either Python list or string of the form
              : 'a, b-c, ...', where 'b-c' is decoded as 'b, b+1, ..., c';
              : out-of-range index value causes error (non-zero) return
    tile_shape: tuple (tile_rows, tile_columns);
                if not present, the number of tile rows and columns is
                computed based on the array dimensions
    scale     : tuple (vmin, vmax) for imshow; defaults to the range of
                array values
    power     : if present, numpy.power(abs(array), power) is displayed
                (power < 1 improves visibility of relatively small array values)
    suptitle  : figure title; defaults to None
    titles    : array of tile titles; if not present, each tile title is
                label + tile_number
    zyx       : tuple (z, y, x), where x, y, anad z are the dimensions of array
                corresponding to the spatial dimensions x, y and z; zyx=None is
                interpreted as (0, 1, 2)
    xlabel    : label for x axis
    ylabel    : label for y axis
    label     : tile title prefix
    cmap      : colormap
    show      : flag specifying whether the array must be displayed immediately
    '''
    import math
    import numpy

    current_title_size = mpl.rcParams['axes.titlesize']
    current_label_size = mpl.rcParams['axes.labelsize']
    current_xlabel_size = mpl.rcParams['xtick.labelsize']
    current_ylabel_size = mpl.rcParams['ytick.labelsize']
    mpl.rcParams['axes.titlesize'] = 'small'
    mpl.rcParams['axes.labelsize'] = 'small'
    mpl.rcParams['xtick.labelsize'] = 'small'
    mpl.rcParams['ytick.labelsize'] = 'small'

    if zyx is not None:
        array = numpy.transpose(array, zyx)

    nz = array.shape[0]
    if index is None:
        n = nz
        index = range(n)
    else:
        if type(index) == type(' '):
            try:
                index = str_to_int_list(index)
            except:
                return 1
        n = len(index)
        for k in range(n):
            z = index[k]
            if z < 0 or z >= nz:
                return k + 1
    ny = array.shape[1]
    nx = array.shape[2]
    if tile_shape is None:
        rows = int(round(math.sqrt(n*nx/ny)))
        if rows < 1:
            rows = 1
        if rows > n:
            rows = n
        cols = (n - 1)//rows + 1
        last_row = rows - 1
    else:
        rows, cols = tile_shape
        assert rows*cols >= n, \
            "tile rows x columns must be not less than the number of images"
        last_row = (n - 1)//cols
    if scale is None:
        if power is None:
            vmin = numpy.amin(array)
            vmax = numpy.amax(array)
        else:
            vmin = numpy.power(numpy.amin(abs(array)), power)
            vmax = numpy.power(numpy.amax(abs(array)), power)
    else:
        vmin, vmax = scale
    fig = plt.figure()
    if suptitle is not None:
        if title_size is None:
            fig.suptitle(suptitle)
        else:
            fig.suptitle(suptitle, fontsize=title_size)
    for k in range(n):
        z = index[k] #- 1
        ax = fig.add_subplot(rows, cols, k + 1)
        if titles is None:
            if label is not None and nz > 1:
                ax.set_title(label + (' %d' % z))
        else:
            ax.set_title(titles[k])
        row = k//cols
        col = k - row*cols
        if xlabel is None and ylabel is None or row < last_row or col > 0:
            ax.set_axis_off()
        else:
            ax.set_axis_on()
            if xlabel is not None:
                plt.xlabel(xlabel)
                plt.xticks([0, nx - 1], [0, nx - 1])
            if ylabel is not None:
                plt.ylabel(ylabel)
                plt.yticks([0, ny - 1], [0, ny - 1])
        if power is None:
            imgplot = ax.imshow(array[z,:,:], cmap, vmin=vmin, vmax=vmax)
        else:
            imgplot = ax.imshow(numpy.power(abs(array[z,:,:]), power), cmap, \
                                vmin=vmin, vmax=vmax)
    if show:
        fignums = plt.get_fignums()
        last = fignums[-1]
        if last > 1:
            print("You may need to close Figures' 1 - %d windows to continue..." \
                  % last)
        else:
            print('You may need to close Figure 1 window to continue...')
        plt.show()

    mpl.rcParams['axes.titlesize'] = current_title_size
    mpl.rcParams['axes.labelsize'] = current_label_size
    mpl.rcParams['xtick.labelsize'] = current_xlabel_size
    mpl.rcParams['ytick.labelsize'] = current_ylabel_size

    return 0
Beispiel #59
0
def test_plot_raw():
    """Test plotting of raw data."""
    import matplotlib.pyplot as plt
    raw = _get_raw()
    raw.info['lowpass'] = 10.  # allow heavy decim during plotting
    events = _get_events()
    plt.close('all')  # ensure all are closed
    fig = raw.plot(events=events,
                   show_options=True,
                   order=[1, 7, 3],
                   group_by='original')
    # test mouse clicks
    x = fig.get_axes()[0].lines[1].get_xdata().mean()
    y = fig.get_axes()[0].lines[1].get_ydata().mean()
    data_ax = fig.axes[0]

    _fake_click(fig, data_ax, [x, y], xform='data')  # mark a bad channel
    _fake_click(fig, data_ax, [x, y], xform='data')  # unmark a bad channel
    _fake_click(fig, data_ax, [0.5, 0.999])  # click elsewhere in 1st axes
    _fake_click(fig, data_ax, [-0.1, 0.9])  # click on y-label
    _fake_click(fig, fig.get_axes()[1], [0.5, 0.5])  # change time
    _fake_click(fig, fig.get_axes()[2], [0.5, 0.5])  # change channels
    _fake_click(fig, fig.get_axes()[3], [0.5, 0.5])  # open SSP window
    fig.canvas.button_press_event(1, 1, 1)  # outside any axes
    fig.canvas.scroll_event(0.5, 0.5, -0.5)  # scroll down
    fig.canvas.scroll_event(0.5, 0.5, 0.5)  # scroll up
    # sadly these fail when no renderer is used (i.e., when using Agg):
    # ssp_fig = set(plt.get_fignums()) - set([fig.number])
    # assert_equal(len(ssp_fig), 1)
    # ssp_fig = plt.figure(list(ssp_fig)[0])
    # ax = ssp_fig.get_axes()[0]  # only one axis is used
    # t = [c for c in ax.get_children() if isinstance(c,
    #      matplotlib.text.Text)]
    # pos = np.array(t[0].get_position()) + 0.01
    # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data')  # off
    # _fake_click(ssp_fig, ssp_fig.get_axes()[0], pos, xform='data')  # on
    #  test keypresses
    for key in [
            'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup',
            'pagedown', 'home', 'end', '?', 'f11', 'escape'
    ]:
        fig.canvas.key_press_event(key)
    fig = plot_raw(raw, events=events, group_by='selection')
    for key in [
            'b', 'down', 'up', 'right', 'left', 'o', '-', '+', '=', 'pageup',
            'pagedown', 'home', 'end', '?', 'f11', 'b', 'escape'
    ]:
        fig.canvas.key_press_event(key)
    # Color setting
    pytest.raises(KeyError, raw.plot, event_color={0: 'r'})
    pytest.raises(TypeError, raw.plot, event_color={'foo': 'r'})
    annot = Annotations([10, 10 + raw.first_samp / raw.info['sfreq']],
                        [10, 10], ['test', 'test'], raw.info['meas_date'])
    with pytest.warns(RuntimeWarning, match='outside data range'):
        raw.set_annotations(annot)
    fig = plot_raw(raw, events=events, event_color={-1: 'r', 998: 'b'})
    plt.close('all')
    for group_by, order in zip(
        ['position', 'selection'],
        [np.arange(len(raw.ch_names))[::-3], [1, 2, 4, 6]]):
        with pytest.warns(None):  # sometimes projection
            fig = raw.plot(group_by=group_by, order=order)
        x = fig.get_axes()[0].lines[1].get_xdata()[10]
        y = fig.get_axes()[0].lines[1].get_ydata()[10]
        _fake_click(fig, data_ax, [x, y], xform='data')  # mark bad
        fig.canvas.key_press_event('down')  # change selection
        _fake_click(fig, fig.get_axes()[2], [0.5, 0.5])  # change channels
        sel_fig = plt.figure(1)
        topo_ax = sel_fig.axes[1]
        _fake_click(sel_fig, topo_ax, [-0.425, 0.20223853], xform='data')
        fig.canvas.key_press_event('down')
        fig.canvas.key_press_event('up')
        fig.canvas.scroll_event(0.5, 0.5, -1)  # scroll down
        fig.canvas.scroll_event(0.5, 0.5, 1)  # scroll up
        _fake_click(sel_fig, topo_ax, [-0.5, 0.], xform='data')
        _fake_click(sel_fig, topo_ax, [0.5, 0.], xform='data', kind='motion')
        _fake_click(sel_fig, topo_ax, [0.5, 0.5], xform='data', kind='motion')
        _fake_click(sel_fig,
                    topo_ax, [-0.5, 0.5],
                    xform='data',
                    kind='release')

        plt.close('all')
    # test if meas_date has only one element
    raw.info['meas_date'] = np.array([raw.info['meas_date'][0]],
                                     dtype=np.int32)
    annot = Annotations([1 + raw.first_samp / raw.info['sfreq']], [5], ['bad'])
    with pytest.warns(RuntimeWarning, match='outside data range'):
        raw.set_annotations(annot)
    with pytest.warns(None):  # sometimes projection
        raw.plot(group_by='position', order=np.arange(8))
    for fig_num in plt.get_fignums():
        fig = plt.figure(fig_num)
        if hasattr(fig, 'radio'):  # Get access to selection fig.
            break
    for key in ['down', 'up', 'escape']:
        fig.canvas.key_press_event(key)
    plt.close('all')
Beispiel #60
0
def plot_set2(tsteps, tvec, path):
    reader = mir.MirandaReader(path,
                               periodic_dimensions=(False, True, True),
                               verbose=True)

    print("Domain Size: {} ".format(reader._domain_size))
    print("Variables available: {}".format(reader.varNames))
    Nx, Ny, Nz = reader._domain_size

    W = np.zeros(len(tsteps))

    t_legend = []

    for tind, step in enumerate(tsteps):

        ##################################
        #Reading in full fields to figure out where subdomain and interface are
        reader.setStep(step)
        reader.setSubDomain(((0, 0, 0), (Nx - 1, Ny - 1, Nz - 1)))
        print("Figuring out subdomain at step {}".format(step))
        YN2 = np.squeeze(np.array(reader.readData('Ideal1_01')))
        YO2 = np.squeeze(np.array(reader.readData('Ideal1_02')))
        YSF6 = np.squeeze(np.array(reader.readData('Ideal1_03')))
        YAc = np.squeeze(np.array(reader.readData('Ideal1_04')))
        YHeavy = YSF6 + YAc

        M = (YN2 / M_N2 + YO2 / M_O2 + YSF6 / M_SF6 + YAc / M_Ac)**(-1)

        #Find inner mixing zone (IMZ)
        IMZ_thresh = 0.9
        XHeavy = M / M_Heavy * YHeavy
        XHeavy_bar = np.mean(np.mean(XHeavy, axis=2), axis=1)
        IMZ_crit = 4 * XHeavy_bar * (1 - XHeavy_bar) - IMZ_thresh

        for ind in range(len(IMZ_crit)):
            if IMZ_crit[ind] >= 0:
                IMZ_lo = ind
                break

        for ind in range(len(IMZ_crit)):
            ind2 = Nx - ind - 1
            if IMZ_crit[ind2] >= 0:
                IMZ_hi = ind2
                break

        IMZ_mid = np.argmax(IMZ_crit)

        middle_selection = 0.40  #select middle 20% of domain in x
        x1 = IMZ_mid - int(middle_selection / 2 * Nx)
        x2 = min(IMZ_mid + int(middle_selection / 2 * Nx), Nx - 1)
        reader.setSubDomain(((x1, 0, 0), (x2, Ny - 1, Nz - 1)))

        # Get coordinates based on subdomain
        x, y, z = reader.readCoordinates()
        x = x / 100.0  #convert from cm-> m
        y = y / 100.0
        z = z / 100.0
        nx = reader.chunk[0][1] - reader.chunk[0][0]
        ny = reader.chunk[1][1] - reader.chunk[1][0]
        nz = reader.chunk[2][1] - reader.chunk[2][0]

        ##################################

        # Reading in on subdomain
        reader.setStep(step)
        print("reading in Mass Fraction at step {}.".format(step))
        YN2 = np.squeeze(np.array(reader.readData('Ideal1_01')))
        YO2 = np.squeeze(np.array(reader.readData('Ideal1_02')))
        YSF6 = np.squeeze(np.array(reader.readData('Ideal1_03')))
        YAc = np.squeeze(np.array(reader.readData('Ideal1_04')))
        YHeavy = YSF6 + YAc

        print("reading in density at step {}.".format(step))
        density = 1e3 * np.squeeze(np.array(reader.readData('density')))
        print("reading in pressure at step {}.".format(step))
        pressure = 1e-1 * np.squeeze(np.array(reader.readData('pressure')))

        #Calculating Stats
        print("Computing Diffusion Properties")
        rho_bar = np.mean(np.mean(density, axis=2), axis=1)

        Cp = YN2 * Cp_N2 + YO2 * Cp_O2 + YSF6 * Cp_SF6 + YAc * Cp_Ac
        Cv = YN2 * Cv_N2 + YO2 * Cv_O2 + YSF6 * Cv_SF6 + YAc * Cv_Ac

        gamma = Cp / Cv
        M = (YN2 / M_N2 + YO2 / M_O2 + YSF6 / M_SF6 + YAc / M_Ac)**(-1)
        T = M * pressure / (density * Ru)
        c = (gamma * pressure / density)**0.5

        del YAc, gamma

        #Find inner mixing zone (IMZ)
        IMZ_thresh = 0.9
        XHeavy = M / M_Heavy * YHeavy
        XHeavy_bar = np.mean(np.mean(XHeavy, axis=2), axis=1)
        IMZ_crit = 4 * XHeavy_bar * (1 - XHeavy_bar) - IMZ_thresh

        for ind in range(len(IMZ_crit)):
            if IMZ_crit[ind] >= 0:
                IMZ_lo = ind
                break

        for ind in range(len(IMZ_crit)):
            ind2 = nx - ind - 1
            if IMZ_crit[ind2] >= 0:
                IMZ_hi = ind2
                break

        IMZ_mid = np.argmax(IMZ_crit)

        #Mole Fraction Variance
        XHeavy_prime = XHeavy - XHeavy_bar.reshape((nx, 1, 1))
        XHeavy_variance = np.mean(np.mean(XHeavy_prime**2, axis=2), axis=1)

        #Compute Turbulent Mach Number
        print("reading in velocity at step {}.".format(step))
        velocity = np.zeros((3, nx, ny, nz))
        velocity[0, :, :, :] = 1e-2 * np.squeeze(
            np.array(reader.readData('velocity-0')))
        velocity[1, :, :, :] = 1e-2 * np.squeeze(
            np.array(reader.readData('velocity-1')))
        velocity[2, :, :, :] = 1e-2 * np.squeeze(
            np.array(reader.readData('velocity-2')))
        u_tilde = np.mean(np.mean(velocity[0, :, :, :] * density, axis=2),
                          axis=1) / np.mean(np.mean(density, axis=2), axis=1)

        u_doubleprime = velocity[0, :, :, :] - u_tilde.reshape((nx, 1, 1))

        #Density Spectra
        t_legend.append("t = {} ms".format(step * 1e-1))

        k_rad, rho_spec_rad = fh.radial_spectra(
            x[:, 0, 0], y[0, :, 0], z[0, 0, :],
            density[IMZ_lo:IMZ_hi + 1, :, :])

        plt.figure(2)
        plt.loglog(k_rad, rho_spec_rad)
        plt.xlabel('Radial Wavenumber [m-1]')
        plt.ylabel("Density spectra")

        #Energy Spectra
        energy_for_spectra = density * u_doubleprime / (np.reshape(
            rho_bar, (nx, 1, 1)))**0.5
        k_rad, rhoU_spec_rad = fh.radial_spectra(
            x[:, 0, 0], y[0, :, 0], z[0, 0, :],
            energy_for_spectra[IMZ_lo:IMZ_hi + 1, :, :])

        plt.figure(3)
        plt.loglog(k_rad, rhoU_spec_rad)
        plt.xlabel('Radial Wavenumber [m-1]')
        plt.ylabel("Energy Spectra")

    #Format plots
    print("Formatting Plots")
    t_legend.append("-3/2 slope")
    for ind in plt.get_fignums():
        plt.figure(ind)
        plt.loglog(k_rad, 1e2 * k_rad**(-1.5), 'k--')
        plt.legend(t_legend)
        plt.tight_layout()

    return None