Esempio n. 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())
Esempio n. 2
0
def _setup_matplotlib ():
    import matplotlib, os

    if matplotlib.get_backend () == 'MacOSX':
        matplotlib.use ('TkAgg')
    if 'DISPLAY' not in os.environ and matplotlib.get_backend () == 'TkAgg':
        matplotlib.use ('Agg')
Esempio n. 3
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)
Esempio n. 4
0
    def __init__(self, work_dir=None, backend='TkAgg'):
        if work_dir != None and os.path.exists(work_dir):
            self.__WORK_DIR__ = work_dir
        else:
            self.__WORK_DIR__ = os.getcwd()
        try:
            import matplotlib
            if backend in self.__INTERACTIVE_BACKENDS__:
                matplotlib.use(backend, warn=False)
                self.__BACKEND__ = backend
                if not __SILENT_START__:
                    print(('Matplotlib backend set to: \"{}\"'.format(backend)))
            else:
                if backend in [None, 'None', 'none']:
                    print(('Matplotlib backend not set, using: \"{}\"'.format(matplotlib.get_backend())))
                    self.__BACKEND__ = matplotlib.get_backend()
                else:
                    matplotlib.use('TkAgg', warn=False)
                    self.__BACKEND__ = 'TkAgg'
                    print(('Matplotlib \"{}\" backend not set, defaulting to: \"{}\"'.format(backend, 'TkAgg')))

            #if self.__ENABLE_HTML5__:
                #matplotlib.use('module://mplh5canvas.backend_h5canvas') # HTML5
            #else:
                #matplotlib.use('TKagg', warn=False)
        except Exception as ex:
            print(ex)
            print("\nPySCeS defaults to matplotlib's TKagg backend if not specified in the user conficuration file, set \"matplotlib_backend = <backend>\" ")

        from matplotlib import pyplot
        from matplotlib import pylab
        ##  self.pyplot = pyplot
        self.pyplot = pylab
        if self.__MODE_INTERACTIVE__: self.pyplot.ion()
        self._setNewFigureGenerator(self.MAX_OPEN_WINDOWS)
Esempio n. 5
0
def _setup():
    # The baseline images are created in this locale, so we should use
    # it during all of the tests.
    import locale
    import warnings
    from matplotlib.backends import backend_agg, backend_pdf, backend_svg

    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")

    mpl.use('Agg', warn=False)  # use Agg backend for these tests
    if mpl.get_backend().lower() != "agg":
        raise Exception(("Using a wrong matplotlib backend ({0}), which will not produce proper "
                        "images").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

    # Clear the font caches.  Otherwise, the hinting mode can travel
    # from one test to another.
    backend_agg.RendererAgg._fontd.clear()
    backend_pdf.RendererPdf.truetype_font_cache.clear()
    backend_svg.RendererSVG.fontd.clear()
Esempio n. 6
0
def _init_matplotlib():
    import matplotlib as mpl
    import utool
    backend = mpl.get_backend()
    if not sys.platform.startswith('win32') and not sys.platform.startswith('darwin') and os.environ.get('DISPLAY', None) is None:
        # Write to files if we cannot display
        TARGET_BACKEND = 'PDF'
    else:
        TARGET_BACKEND = 'Qt4Agg'
    if utool.in_main_process():
        if not utool.QUIET and utool.VERBOSE:
            print('--- INIT MPL---')
            print('[main] current backend is: %r' % backend)
            print('[main] mpl.use(%r)' % TARGET_BACKEND)
        if backend != TARGET_BACKEND:
            mpl.use(TARGET_BACKEND, warn=True, force=True)
            backend = mpl.get_backend()
            if not utool.QUIET and utool.VERBOSE:
                print('[main] current backend is: %r' % backend)
        if utool.get_flag('--notoolbar'):
            toolbar = 'None'
        else:
            toolbar = 'toolbar2'
        mpl.rcParams['toolbar'] = toolbar
        mpl.rc('text', usetex=False)
        mpl_keypress_shortcuts = [key for key in mpl.rcParams.keys() if key.find('keymap') == 0]
        for key in mpl_keypress_shortcuts:
            mpl.rcParams[key] = ''
Esempio n. 7
0
def Show():
    """
    Show all figures and start the event loop if necessary
    """
    managers = GlobalFigureManager.get_all_fig_managers()
    if not managers:
        return

    for manager in managers:
        manager.show()

    # Hack: determine at runtime whether we are
    # inside ipython in pylab mode.
    from matplotlib import pyplot

    try:
        ipython_pylab = not pyplot.show._needmain
        # IPython versions >= 0.10 tack the _needmain
        # attribute onto pyplot.show, and always set
        # it to False, when in %pylab mode.
        ipython_pylab = ipython_pylab and mpl.get_backend() != 'WebAgg'
        # TODO: The above is a hack to get the WebAgg backend
        # working with ipython's `%pylab` mode until proper
        # integration is implemented.
    except AttributeError:
        ipython_pylab = False

    # Leave the following as a separate step in case we
    # want to control this behavior with an rcParam.
    if ipython_pylab:
        return

    if not mpl.is_interactive() or mpl.get_backend() == 'WebAgg':
        QAppThreadCall(mainloop)()
Esempio n. 8
0
def ensure_mpl_backend(backend=None):
    """
    Tries to select the matplotlib backend.

    Raises EnvironmentError, if the desired backend is valid
    but could not be selected.
    If `backend` is None, either 'agg' or 'wxagg' is chosen,
    depending on whether a display is present (on Linux and Darwin).
    For other platforms, 'wxagg' is always the default.
    Returns the selected backend as given by matplotlib.get_backend().
    """
    if backend is None:
        import platform
        import os
        if (
            platform.system() in ('Linux', 'Darwin') and not
            'DISPLAY' in os.environ
            ):
            backend = 'agg'
        else:
            backend = 'wxagg'
    import matplotlib
    active_backend = matplotlib.get_backend()
    if active_backend.lower() != backend.lower():
        matplotlib.use(backend)
        active_backend = matplotlib.get_backend()
        if active_backend.lower() != backend.lower():
            raise EnvironmentError(
                "Could not select matplotlib backend '%s' ('%s' is active)!" \
                % (backend, active_backend)
                )
    return active_backend
Esempio n. 9
0
def save_figure_helper(fpath):
    if matplotlib.get_backend() == 'pdf':
        final_path = fpath + '.pdf'
        pylab.savefig(final_path)
        pylab.close()
        print('Written: %s'%final_path)
        print('Converting to eps...')
        os.system('pdftops -eps ' + final_path)
        os.rename(fpath+'.eps', fpath+'_.eps') #missing bounding box
        os.system('eps2eps ' + fpath+'_.eps' + '  ' + fpath+'.eps')
        os.remove(fpath+'_.eps')
    elif matplotlib.get_backend() == 'ps':
        final_path = fpath + '.eps'
        pylab.savefig(final_path)
        pylab.close()
        print('Written: %s'%final_path)
        print('Converting to pdf...')
        os.system('epstopdf ' + final_path)
    else:
        print('Trying to save to PDF.  Backend: %s'%matplotlib.get_backend())
        final_path = fpath + '.pdf'
        pylab.savefig(final_path)
        pylab.close()
        print('Written: %s'%final_path)
    subprocess.call(['xdg-open', final_path])
Esempio n. 10
0
def test_create_figure():
    if matplotlib.get_backend() == "agg":
        pytest.xfail("{} backend does not support on_close event.".format(
            matplotlib.get_backend()))

    dummy_function = Mock()
    fig = utils.create_figure(window_title="test title",
                              _on_figure_window_close=dummy_function)
    assert isinstance(fig, matplotlib.figure.Figure) == True
    matplotlib.pyplot.close(fig)
    dummy_function.assert_called_once_with()
def plot_exemplary_roc(fname=None):
    if (fname is not None and mpl.get_backend() == u'pgf'):
        fileName, fileExtension = os.path.splitext(fname)
        if (fileExtension == "pdf"):
            pf.latexify()
        if(fileExtension == "pgf"):
            pf.latexifypgf()
    frange = [0.0, 1.0]
    magrange = [0.0, 1.0]
    fig, ax1 = pyplot.subplots()
    pf.format_axes(ax1)
    colors = pf.getColorList(7)
    pyplot.subplots_adjust(
        left=0.125, bottom=0.125, right=0.92, top=0.9, wspace=0.2, hspace=0.3)

    # add title, if given
    # pyplot.title("BI measurement with denoising ");
    npzfile = np.load(pf.data_dir() + 'exampleROC.npz')
    fpr = npzfile['fpr']
    tpr = npzfile['tpr']
    mean_fpr = npzfile['mean_fpr']
    pyplot.plot(fpr, tpr, color=colors[
                1], linestyle='-', linewidth=1.5, label="trained classifier")

    pyplot.plot(mean_fpr, mean_fpr, color=colors[5], linestyle='--', linewidth=1.5, label="random classifier")

    pf.modifyLegend(pyplot.legend(loc=4))
    # plot it as a log-scaled graph
    # update axis ranges
    ax_lim = []
    ax_lim[0:4] = pyplot.axis()
    # check if we were given a frequency range for the plot
    if (frange != None):
        ax_lim[0:2] = frange
    # check if we were given a dB range for the magnitude part of the plot
    # magrange = [0.2, 1.01]
    if (magrange != None):
        ax_lim[2:4] = magrange

    pyplot.axis(ax_lim)

    pyplot.grid(True)
    # turn on the minor gridlines to give that awesome log-scaled look
    pyplot.grid(True, which='minor')
    pyplot.xlabel("False positive rate")
    # pyplot.title("(b)");
    pyplot.ylabel("True positive rate")
    if (fname != None and mpl.get_backend() == u'pgf'):
        pyplot.savefig(fname, dpi=pf.getDpi())
    else:
        pyplot.show()
Esempio n. 12
0
    def __init__(self, dendrogram, hub, catalog, xaxis, yaxis):

        self.hub = hub
        self.dendrogram = dendrogram
        self.structures = list(self.dendrogram.all_structures)

        self.fig = plt.figure()
        self.axes = plt.subplot(1,1,1)

        self.catalog = catalog
        self.xdata = catalog[xaxis]
        self.ydata = catalog[yaxis]

        self.xys = np.column_stack((self.xdata, self.ydata))

        self.x_column_name = xaxis
        self.y_column_name = yaxis

        self.lines2d = {} # selection_id -> matplotlib.lines.Line2D

        # This is a workaround for a (likely) bug in matplotlib.widgets. Lasso crashes without this fix.
        if matplotlib.get_backend() == 'MacOSX':
            self.fig.canvas.supports_blit = False

        self._draw_plot()
        self.hub.add_callback(self.update_selection)

        self.cid = self.fig.canvas.mpl_connect('button_press_event', self.onpress)

        # If things are already selected in the hub, go select them!
        for selection_id in self.hub.selections:
            self.update_selection(selection_id)
    def __init__(self, draw_timestep=0.033333, facecolor=[1, 1, 1],
                 figsize=None, ax=None):
        LeafSystem.__init__(self)

        self.set_name('pyplot_visualization')
        self.timestep = draw_timestep
        self.DeclarePeriodicPublish(draw_timestep, 0.0)

        if ax is None:
            (self.fig, self.ax) = plt.subplots(facecolor=facecolor,
                                               figsize=figsize)
        else:
            self.ax = ax
            self.fig = ax.get_figure()

        self.ax.axis('equal')
        self.ax.axis('off')
        self.record = False
        self.recorded_contexts = []
        self.show = (matplotlib.get_backend().lower() != 'template')

        def on_initialize(context, event):
            if self.show:
                self.fig.show()

        self.DeclareInitializationEvent(
            event=PublishEvent(
                trigger_type=TriggerType.kInitialization,
                callback=on_initialize))
Esempio n. 14
0
def set_mpl_backend():

    try:
        from qtpy import PYQT5
    except:
        # If Qt isn't available, we don't have to worry about
        # setting the backend
        return

    from matplotlib import rcParams, rcdefaults

    # standardize mpl setup
    rcdefaults()

    if PYQT5:
        rcParams['backend'] = 'Qt5Agg'
    else:
        rcParams['backend'] = 'Qt4Agg'

    # The following is a workaround for the fact that Matplotlib checks the
    # rcParams at import time, not at run-time. I have opened an issue with
    # Matplotlib here: https://github.com/matplotlib/matplotlib/issues/5513
    from matplotlib import get_backend
    from matplotlib import backends
    backends.backend = get_backend()
Esempio n. 15
0
    def test_viz_scatter_scatter_xyid(self):
        fLOG(__file__, self._testMethodName,
             OutputPrint=__name__ == "__main__")
        if sys.version_info[:2] <= (3, 4):
            return
        fix_tkinter_issues_virtualenv()
        if __name__ == "__main__":
            rcParams["backend"] = "TkAgg"
        fold = os.path.abspath(os.path.split(__file__)[0])
        fold = os.path.join(fold, "temp_graph_xyz")
        im = os.path.join(fold, self._testMethodName + ".png")
        if not os.path.exists(fold):
            os.mkdir(fold)
        for img in [im]:
            if os.path.exists(img):
                os.remove(img)

        nuage1 = self.generate_gauss(0, 0, 3)
        nuage2 = self.generate_gauss(3, 4, 2)
        nuage = [(a, b, 0) for a, b in nuage1] + [(a, b, 1) for a, b in nuage2]

        matplotlib.use(matplotlib.get_backend(), warn=False, force=True)

        fig, ax = scatter_xy_id(
            nuage, title=self._testMethodName, legend={0: "c0", 1: "c1"})
        fig.savefig(im)
        assert os.path.exists(im)
        if __name__ == "__main__":
            rcParams["backend"] = TestMatplotlibHelperVizScatterPlots.backend
        plt.close('all')
        fLOG(plt.style.available)
Esempio n. 16
0
def has_matplotlib(version=None, op=">="):
    """
    True if matplotlib_ is installed.
    If version is None, the result of matplotlib.__version__ `op` version is returned.
    """
    try:
        import matplotlib
        # have_display = "DISPLAY" in os.environ
    except ImportError:
        print("Skipping matplotlib test")
        return False

    matplotlib.use("Agg")
    #matplotlib.use("Agg", force=True)  # Use non-graphical display backend during test.
    import matplotlib.pyplot as plt
    # http://stackoverflow.com/questions/21884271/warning-about-too-many-open-figures
    plt.close("all")

    backend = matplotlib.get_backend()
    if backend.lower() != "agg":
        #raise RuntimeError("matplotlib backend now is %s" % backend)
        #matplotlib.use("Agg", warn=True, force=False)
        # Switch the default backend.
        # This feature is experimental, and is only expected to work switching to an image backend.
        plt.switch_backend("Agg")

    if version is None: return True
    return cmp_version(matplotlib.__version__, version, op=op)
Esempio n. 17
0
def software_stack():
    """
    Import all the hard dependencies. Returns ordered dict: package --> string with version info.
    """
    # Mandatory
    import numpy, scipy, netCDF4, pymatgen, apscheduler, pydispatch, yaml

    d = collections.OrderedDict([
        ("numpy", numpy.version.version),
        ("scipy", scipy.version.version),
        ("netCDF4", netCDF4.__version__),
        ("apscheduler", apscheduler.version),
        ("pydispatch", pydispatch.__version__),
        ("yaml", yaml.__version__),
        ("pymatgen", pymatgen.__version__),
    ])

    # Optional but strongly suggested.
    try:
        import matplotlib
        d["matplotlib"] = "%s (backend: %s)" % (matplotlib.__version__, matplotlib.get_backend())
    except ImportError:
        pass

    return d
Esempio n. 18
0
    def __enter__(self):
        """
        Set matplotlib defaults.
        """
        from matplotlib import get_backend, rcParams, rcdefaults
        import locale

        try:
            locale.setlocale(locale.LC_ALL, str('en_US.UTF-8'))
        except:
            try:
                locale.setlocale(locale.LC_ALL,
                                 str('English_United States.1252'))
            except:
                msg = "Could not set locale to English/United States. " + \
                      "Some date-related tests may fail"
                warnings.warn(msg)

        if get_backend().upper() != 'AGG':
            import matplotlib
            try:
                matplotlib.use('AGG', warn=False)
            except TypeError:
                msg = "Image comparison requires matplotlib backend 'AGG'"
                warnings.warn(msg)

        # set matplotlib builtin default settings for testing
        rcdefaults()
        rcParams['font.family'] = 'Bitstream Vera Sans'
        rcParams['text.hinting'] = False
        try:
            rcParams['text.hinting_factor'] = 8
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting_factor']")
        return self
Esempio n. 19
0
    def _acquire_externals(self, out):
        # Test and list all dependencies:
        sdeps = {True: [], False: [], 'Error': []}
        for dep in sorted(externals._KNOWN):
            try:
                sdeps[externals.exists(dep, force=False)] += [dep]
            except:
                sdeps['Error'] += [dep]
        out.write('EXTERNALS:\n')
        out.write(' Present:       %s\n' % ', '.join(sdeps[True]))
        out.write(' Absent:        %s\n' % ', '.join(sdeps[False]))
        if len(sdeps['Error']):
            out.write(' Errors in determining: %s\n' % ', '.join(sdeps['Error']))

        SV = ('.__version__', )              # standard versioning
        out.write(' Versions of critical externals:\n')
        # First the ones known to externals,
        for k, v in sorted(externals.versions.iteritems()):
            out.write('  %-12s: %s\n' % (k, str(v)))
        try:
            if externals.exists('matplotlib'):
                import matplotlib
                out.write(' Matplotlib backend: %s\n'
                          % matplotlib.get_backend())
        except Exception, exc:
            out.write(' Failed to determine backend of matplotlib due to "%s"'
                      % str(exc))
Esempio n. 20
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()
Esempio n. 21
0
def mpl_test_settings(request):
    from matplotlib.testing.decorators import _do_cleanup

    original_units_registry = matplotlib.units.registry.copy()
    original_settings = matplotlib.rcParams.copy()

    backend = None
    backend_marker = request.keywords.get('backend')
    if backend_marker is not None:
        assert len(backend_marker.args) == 1, \
            "Marker 'backend' must specify 1 backend."
        backend = backend_marker.args[0]
        prev_backend = matplotlib.get_backend()

    style = '_classic_test'  # Default of cleanup and image_comparison too.
    style_marker = request.keywords.get('style')
    if style_marker is not None:
        assert len(style_marker.args) == 1, \
            "Marker 'style' must specify 1 style."
        style = style_marker.args[0]

    matplotlib.testing.setup()
    if backend is not None:
        # This import must come after setup() so it doesn't load the default
        # backend prematurely.
        import matplotlib.pyplot as plt
        plt.switch_backend(backend)
    matplotlib.style.use(style)
    try:
        yield
    finally:
        if backend is not None:
            plt.switch_backend(prev_backend)
        _do_cleanup(original_units_registry,
                    original_settings)
Esempio n. 22
0
def _set_mpl_backend():
    try:
        # We are doing local imports here to avoid poluting our namespace
        import matplotlib
        import os
        import sys

        # Set the backend to a non-interactive one for unices without X
        if (
            os.name == "posix"
            and "DISPLAY" not in os.environ
            and not (sys.platform == "darwin" and matplotlib.get_backend() == "MacOSX")
        ):
            matplotlib.use("Agg")
    except ImportError:
        from .._utils.testing import skip_if_running_nose

        # No need to fail when running tests
        skip_if_running_nose("matplotlib not installed")
        raise
    else:
        from ..version import _import_module_with_version_check, OPTIONAL_MATPLOTLIB_MIN_VERSION

        # When matplotlib was successfully imported we need to check
        # that the version is greater that the minimum required one
        _import_module_with_version_check("matplotlib", OPTIONAL_MATPLOTLIB_MIN_VERSION)
Esempio n. 23
0
def redraw(figure):
    if 'inline' in matplotlib.get_backend():
        from IPython import display
        display.clear_output(wait=True)
        display.display(figure)
    else:
        plt.draw()
Esempio n. 24
0
def mpl_test_settings(request):
    from matplotlib.testing.decorators import _cleanup_cm

    with _cleanup_cm():

        backend = None
        backend_marker = request.keywords.get('backend')
        if backend_marker is not None:
            assert len(backend_marker.args) == 1, \
                "Marker 'backend' must specify 1 backend."
            backend = backend_marker.args[0]
            prev_backend = matplotlib.get_backend()

        style = '_classic_test'  # Default of cleanup and image_comparison too.
        style_marker = request.keywords.get('style')
        if style_marker is not None:
            assert len(style_marker.args) == 1, \
                "Marker 'style' must specify 1 style."
            style = style_marker.args[0]

        matplotlib.testing.setup()
        if backend is not None:
            # This import must come after setup() so it doesn't load the
            # default backend prematurely.
            import matplotlib.pyplot as plt
            plt.switch_backend(backend)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
            matplotlib.style.use(style)
        try:
            yield
        finally:
            if backend is not None:
                plt.switch_backend(prev_backend)
Esempio n. 25
0
def software_stack():
    """
    Import all the hard dependencies.
    Returns a dict with the version.
    """
    # Mandatory
    import numpy, scipy

    d = dict(
        numpy=numpy.version.version,
        scipy=scipy.version.version,
    )

    # Optional but strongly suggested.
    try:
        import netCDF4, matplotlib
        d.update(dict(
            netCDF4=netCDF4.getlibversion(),
            matplotlib="Version: %s, backend: %s" % (matplotlib.__version__, matplotlib.get_backend()),
            ))
    except ImportError:
        pass

    # Optional (GUIs).
    try:
        import wx
        d["wx"] = wx.version()
    except ImportError:
        pass

    return d
Esempio n. 26
0
def _init_mpl_mainprocess(verbose=VERBOSE_MPLINIT):
    global __IS_INITIALIZED__
    global __WHO_INITIALIZED__
    import matplotlib as mpl
    #mpl.interactive(True)
    current_backend = mpl.get_backend()
    target_backend = get_target_backend()
    if __IS_INITIALIZED__ is True:
        if verbose:
            print('[!plottool] matplotlib has already been initialized.  backend=%r' % current_backend)
            print('[!plottool] Initially initialized by %r' % __WHO_INITIALIZED__)
            print('[!plottool] Trying to be init by %r' % (ut.get_caller_name(N=range(0, 5))))
        return False
    __IS_INITIALIZED__ = True

    if verbose:
        print('[plottool] matplotlib initialized by %r' % __WHO_INITIALIZED__)
        __WHO_INITIALIZED__ = ut.get_caller_name(N=range(0, 5))
    if verbose:
        print('--- INIT MPL---')
        print('[pt] current backend is: %r' % current_backend)
        print('[pt] mpl.use(%r)' % target_backend)
    if current_backend != target_backend:
        _mpl_set_backend(target_backend)
    _init_mpl_rcparams()
Esempio n. 27
0
def setWindowRectangle(x, y=None, w=None, h=None, mngr=None, be=None):
    """ Position the current Matplotlib figure at the specified position

    """
    if y is None:
        y = x[1]
        w = x[2]
        h = x[3]
        x = x[0]
    if mngr is None:
        mngr = plt.get_current_fig_manager()
    be = matplotlib.get_backend()
    if be == 'WXAgg':
        mngr.canvas.manager.window.SetPosition((x, y))
        mngr.canvas.manager.window.SetSize((w, h))
    elif be == 'agg':
            # mngr.canvas.manager.window.setGeometry(x,y,w,h)
        mngr.canvas.manager.window.SetPosition((x, y))
        mngr.canvas.manager.window.resize(w, h)
    elif be == 'module://IPython.kernel.zmq.pylab.backend_inline':
        pass
    else:
        # assume Qt canvas
        mngr.canvas.manager.window.move(x, y)
        mngr.canvas.manager.window.resize(w, h)
        mngr.canvas.manager.window.setGeometry(x, y, w, h)
Esempio n. 28
0
def check_for_modules(module_list):
    # make sure module_list only contains recognized modules
    unnamed_modules = set(module_list) - set(CMD_DICT.keys())
    unnamed_modules = unnamed_modules - {'datetime', 're'}
    if unnamed_modules:
        msg = '\n\nThese modules unrecognized by check_for_modules(): '
        msg += '{}\n'.format(unnamed_modules)
        raise ValueError(msg)

    # try using configured backend ignoring errors so they'll be caught later
    if set(module_list).intersection({'matplotlib', 'pylab', 'seaborn'}):
        CONFIG = config_lib.get_config()
        try:
            import matplotlib
            if matplotlib.get_backend() != CONFIG['plot_backend']:
                matplotlib.use(CONFIG['plot_backend'])
        except ImportError:
            pass

    # initialize an error message
    msg = ''

    # try importing all the required mojkdules
    for module in sorted(module_list):
        try:
            importlib.import_module(module)
        except ImportError:
            # add to error message for each bad module
            msg = msg if msg else HEADER
            msg += '-' * 60 + '\n'
            msg += "Missing module '{}'. To install use: \n".format(module)
            msg += "    {}\n\n".format(CMD_DICT[module])
            sys.stdout.write(msg + '\n')
            raise
Esempio n. 29
0
    def switch_backend(backend, sloppy=True):
        """
        Switch matplotlib backend.

        :type backend: str
        :param backend: Name of matplotlib backend to switch to.
        :type sloppy: bool
        :param sloppy: If ``True``, only uses
            :func:`matplotlib.pyplot.switch_backend` and no warning will be
            shown if the backend was not switched successfully. If ``False``,
            additionally tries to use :func:`matplotlib.use` first and also
            shows a warning if the backend was not switched successfully.
        """
        import matplotlib
        # sloppy. only do a `plt.switch_backend(..)`
        if sloppy:
            import matplotlib.pyplot as plt
            plt.switch_backend(backend)
        else:
            # check if `matplotlib.use(..)` is emitting a warning
            try:
                with warnings.catch_warnings(record=True):
                    warnings.simplefilter("error", UserWarning)
                    matplotlib.use(backend)
            # if that's the case, follow up with `plt.switch_backend(..)`
            except UserWarning:
                import matplotlib.pyplot as plt
                plt.switch_backend(backend)
            # finally check if the switch was successful,
            # show a warning if not
            if matplotlib.get_backend().upper() != backend.upper():
                msg = "Unable to change matplotlib backend to '%s'" % backend
                warnings.warn(msg)
Esempio n. 30
0
    def _get_cursor_endpoints(self):
        import matplotlib as mpl
        # to get cursor position:
        #   1) change text to chars left of the cursor
        #   2) if macos, redraw
        #   3) get extent of temporary text box
        #   4) place cursor at appropriate place

        text = self.text.get_text()
        self.text.set_text(text[:self._cursorpos])
        if mpl.get_backend() == 'MacOSX':
            # self.text can't get_window_extent() until drawn
            # this introduces some lag, so only do it on macos
            # apparently the GCContext gets invalidated when you set_text, so
            # you always have to do this
            self.canvas.draw()
        bbox = self.text.get_window_extent()
        l, b, w, h = bbox.bounds  # in pixels
        r = l + w
        # now restore correct text
        self.text.set_text(text)

        # cursor line in data coordinates
        bx, by = self.ax.transAxes.inverted().transform((r, b))
        tx, ty = self.ax.transAxes.inverted().transform((r, b + h))
        dy = 0.5 * (ty - by)
        return [bx, tx], [by - dy, ty + dy]
Esempio n. 31
0
def pulse_drawer(
    data: Union[Waveform, Union[Schedule, Instruction]],
    dt: int = 1,
    style: Union[PulseStyle, SchedStyle] = None,
    filename: str = None,
    interp_method: Callable = None,
    scale: float = None,
    channel_scales: Dict[Channel, float] = None,
    plot_all: bool = False,
    plot_range: Tuple[Union[int, float], Union[int, float]] = None,
    interactive: bool = False,
    table: bool = False,
    label: bool = False,
    framechange: bool = True,
    channels: List[Channel] = None,
    show_framechange_channels: bool = True,
    draw_title: bool = False,
):
    """Deprecated.

    Plot the interpolated envelope of pulse and schedule.

    Args:
        data: Pulse or schedule object to plot.
        dt: Time interval of samples. Pulses are visualized in the unit of
            cycle time if not provided.
        style: A style sheet to configure plot appearance.
            See :mod:`~qiskit.visualization.pulse.qcstyle` for more information.
        filename: Name required to save pulse image. The drawer just returns
            `matplot.Figure` object if not provided.
        interp_method: Interpolation function. Interpolation is disabled in default.
            See :mod:`~qiskit.visualization.pulse.interpolation` for more information.
        scale: Scaling of waveform amplitude. Pulses are automatically
            scaled channel by channel if not provided.
        channel_scales: Dictionary of scale factor for specific channels.
            Scale of channels not specified here is overwritten by `scale`.
        plot_all: When set `True` plot empty channels.
        plot_range: A tuple of time range to plot.
        interactive: When set `True` show the circuit in a new window.
            This depends on the matplotlib backend being used supporting this.
        table: When set `True` draw event table for supported commands.
        label: When set `True` draw label for individual instructions.
        framechange: When set `True` draw framechange indicators.
        channels: A list of channel names to plot.
            All non-empty channels are shown if not provided.
        show_framechange_channels: When set `True` plot channels
            with only framechange instructions.
        draw_title: Add a title to the plot when set to ``True``.

    Returns:
        matplotlib.figure.Figure: A matplotlib figure object for the pulse envelope.

    Example:
        This example shows how to visualize your pulse schedule.
        Pulse names are added to the plot, unimportant channels are removed
        and the time window is truncated to draw out U3 pulse sequence of interest.

        .. jupyter-execute::

            import numpy as np
            import qiskit
            from qiskit import pulse
            from qiskit.test.mock.backends.almaden import FakeAlmaden

            inst_map = FakeAlmaden().defaults().instruction_schedule_map

            sched = pulse.Schedule()
            sched += inst_map.get('u3', 0, np.pi, 0, np.pi)
            sched += inst_map.get('measure', list(range(20))) << sched.duration

            channels = [pulse.DriveChannel(0), pulse.MeasureChannel(0)]
            scales = {pulse.DriveChannel(0): 10}

            qiskit.visualization.pulse_drawer(sched,
                                              channels=channels,
                                              plot_range=(0, 1000),
                                              label=True,
                                              channel_scales=scales)

        You are also able to call visualization module from the instance method::

            sched.draw(channels=channels, plot_range=(0, 1000), label=True, channel_scales=scales)

        To customize the format of the schedule plot, you can setup your style sheet.

        .. jupyter-execute::

            import numpy as np
            import qiskit
            from qiskit import pulse
            from qiskit.test.mock.backends.almaden import FakeAlmaden

            inst_map = FakeAlmaden().defaults().instruction_schedule_map

            sched = pulse.Schedule()
            sched += inst_map.get('u3', 0, np.pi, 0, np.pi)
            sched += inst_map.get('measure', list(range(20))) << sched.duration

            # setup style sheet
            my_style = qiskit.visualization.SchedStyle(
                figsize = (10, 5),
                bg_color='w',
                d_ch_color = ['#32cd32', '#556b2f'])

            channels = [pulse.DriveChannel(0), pulse.MeasureChannel(0)]
            scales = {pulse.DriveChannel(0): 10}

            qiskit.visualization.pulse_drawer(sched, style=my_style,
                                              channels=channels,
                                              plot_range=(0, 1000),
                                              label=True,
                                              channel_scales=scales)

    Raises:
        VisualizationError: when invalid data is given
        MissingOptionalLibraryError: when matplotlib is not installed
    """
    warnings.warn(
        "This legacy pulse drawer is deprecated and will be removed no earlier than "
        "3 months after the release date. Use `qiskit.visualization.pulse_drawer_v2` "
        "instead. After the legacy drawer is removed, the import path of this module "
        "will be dedicated to the v2 drawer. "
        "New drawer will provide much more flexibility with richer stylesheets "
        "and cleaner visualization.",
        DeprecationWarning,
    )

    if not HAS_MATPLOTLIB:
        raise MissingOptionalLibraryError(
            libname="Matplotlib",
            name="pulse_drawer",
            pip_install="pip install matplotlib",
        )
    from matplotlib import get_backend
    from matplotlib import pyplot as plt

    if isinstance(data, Waveform):
        drawer = _matplotlib.WaveformDrawer(style=style)
        image = drawer.draw(data,
                            dt=dt,
                            interp_method=interp_method,
                            scale=scale)
    elif isinstance(data, (Schedule, Instruction)):
        drawer = _matplotlib.ScheduleDrawer(style=style)
        image = drawer.draw(
            data,
            dt=dt,
            interp_method=interp_method,
            scale=scale,
            channel_scales=channel_scales,
            plot_range=plot_range,
            plot_all=plot_all,
            table=table,
            label=label,
            framechange=framechange,
            channels=channels,
            show_framechange_channels=show_framechange_channels,
            draw_title=draw_title,
        )
    else:
        raise VisualizationError("This data cannot be visualized.")

    if filename:
        image.savefig(filename, dpi=drawer.style.dpi, bbox_inches="tight")

    if get_backend() in ["module://ipykernel.pylab.backend_inline", "nbAgg"]:
        plt.close(image)
    if image and interactive:
        image.show()
    return image
Esempio n. 32
0
#------------------------------
#  Module's version from CVS --
#------------------------------
__version__ = "$Revision: 4 $"
# $Source$

#--------------------------------
#  Imports of standard modules --
#--------------------------------
import sys
import os

import matplotlib
#matplotlib.use('Qt4Agg') # forse Agg rendering to a Qt4 canvas (backend)
if matplotlib.get_backend() != 'Qt4Agg': matplotlib.use('Qt4Agg')

from PyQt4 import QtGui, QtCore
#import time   # for sleep(sec)

#-----------------------------
# Imports for other modules --
#-----------------------------

from ConfigParametersForApp import cp

from Logger import logger
from FileNameManager import fnm

from CorAna.MaskEditor import MaskEditor
import GlobalUtils as gu
Esempio n. 33
0
import matplotlib
import math
import random
import matplotlib.pyplot as plt

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transform as T

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

env = gym.make("").unwrapped

is_ipytohn = "inline" in matplotlib.get_backend()
if is_ipython:
    from IPython import display

plt.ion()


class replay_memories(object):
    def __init__(self, capacity):
        self.capacity = capacity
        self.memory = []
        self.position = 0

    def push(self, *args):
        if len(self.memory) < self.capacity:
            self.memory.append(None)
# coding: utf-8

# In[ ]:

#!/usr/bin/env python


from pywps.Process import WPSProcess 
import logging

import matplotlib 
logging.info('get backend before set')
print('get backend before set')
logging.info(matplotlib.matplotlib_fname())
print(matplotlib.matplotlib_fname())
logging.info(matplotlib.get_backend())
print(matplotlib.get_backend())
matplotlib.rcParams['backend'] = 'AGG'
matplotlib.use('AGG')

logging.info('get backend after set')
logging.info(matplotlib.get_backend())

import sys
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.mpl.gridliner import LATITUDE_FORMATTER, LONGITUDE_FORMATTER
import matplotlib.ticker as mticker
import matplotlib.colors as mcolors
import matplotlib.colorbar as mcb
import cartopy.feature as cfeature
Esempio n. 35
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import io
from multiprocessing import Process, Manager

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.basemap import Basemap

from . import BaseDomsHandler
from . import ResultsStorage

if not matplotlib.get_backend():
    matplotlib.use('Agg')

PARAMETER_TO_FIELD = {
    "sst": "sea_water_temperature",
    "sss": "sea_water_salinity"
}

PARAMETER_TO_UNITS = {"sst": "($^\circ$ C)", "sss": "(g/L)"}


def __square(minLon, maxLon, minLat, maxLat):
    if maxLat - minLat > maxLon - minLon:
        a = ((maxLat - minLat) - (maxLon - minLon)) / 2.0
        minLon -= a
        maxLon += a
Esempio n. 36
0
#!/usr/bin/env python
import sys
import matplotlib
if matplotlib.get_backend() != "TKAgg":
    matplotlib.use("TKAgg")

import pmagpy.pmag as pmag
import pmagpy.pmagplotlib as pmagplotlib


def main():
    """
    NAME
        lowrie_magic.py

    DESCRIPTION
       plots intensity decay curves for Lowrie experiments

    SYNTAX
        lowrie_magic.py -h [command line options]

    INPUT
       takes measurements formatted input files

    OPTIONS
        -h prints help message and quits
        -f FILE: specify input file, default is magic_measurements.txt
        -N do not normalize by maximum magnetization
        -fmt [svg, pdf, eps, png] specify fmt, default is svg
        -sav saves plots and quits
        -DM [2, 3] MagIC data model number
Esempio n. 37
0
import os
import subprocess
from multiprocessing import Process
from packaging import version
import matplotlib
from matplotlib import animation
BACKEND = 'Agg'
if matplotlib.get_backend().lower() != BACKEND.lower():
    matplotlib.use(BACKEND)
import matplotlib.pyplot as plt


def save_animation(filepath, shp, ds, color):
    print("Starting to generate %s" % filepath)
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    ims = []
    print("Generating images.")
    for i in range(0, shp[2]):
        ttl = plt.text(0.5,
                       1.01,
                       "Depth: %s" % i,
                       horizontalalignment='center',
                       verticalalignment='bottom',
                       transform=ax.transAxes)
        im = plt.imshow(ds['v'][:, :, i], animated=True, cmap=color)
        plt.xlabel("x")
        plt.ylabel("y")
        ims.append([im, ttl])
    print("Generating animation.")
    ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True)
Esempio n. 38
0
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from PIL import Image

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torchvision.transforms as T

env = gym.make('CartPole-v0').unwrapped

#set up matplotlib
is_ipython = 'inline' in matplotlib.get_backend()
if is_ipython:
    from IPython import display
plt.ion()
#if gup is to be used
device = torch.device('cuda' if torch.cuda.is_available() else "cpu")

#回放记忆
Transition = namedtuple('Transition',
                        ('state', 'action', 'next_state', 'reward'))


class ReplayMemory(object):
    def __init__(self, capacity):
        self.capacity = capacity
        self.memory = []
Esempio n. 39
0
def _is_notebook_inline_backend():
    return _is_jupyter_notebook() and 'backend_inline' in mpl.get_backend()
Esempio n. 40
0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import re
import numpy as np
from collections import OrderedDict

import matplotlib
if matplotlib.get_backend() != 'module://backend_interagg':
    matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

import tkinter as tk
from tkinter import ttk
from tkinter import Frame

from tframe import console
from tframe.utils.tensor_viewer.plugin import Plugin, VariableWithView


class VariableViewer(Frame):
    # Configurations of VariableViewer widget
    WIDTH = 500
    HEIGHT = 500

    def __init__(self, master):
        # Call parent's constructor
        Frame.__init__(self, master)
Esempio n. 41
0
    def transform_epochs(self, X, warm_start=False, scaling=1, save=False, verbose=True):
        orig_mpl_backend = matplotlib.get_backend()
        matplotlib.use("agg")

        X = X.get_data() * scaling
        # X = X / X.transpose(1, 0, 2).reshape(X.shape[1], -1).std(axis=1)[np.newaxis, :, np.newaxis]
        n_epochs, n_channels, n_times = X.shape
        X_filtered = X.copy()
        if not warm_start:
            self.m = self.m_0
            self.w = self.w_0
        self.lambdas = [self.lw_0]
        self.sigmas = list()
        im_cnt = 0
        epoch_iter = range(n_epochs)
        if verbose:
            epoch_iter = tqdm(epoch_iter)
        for e in epoch_iter:
            window_iter = range(self.size_block, n_times + self.stride, self.stride)
            if verbose:
                window_iter = tqdm(window_iter, leave=False)
            for i in window_iter:
                X_i = X[e, :, i - self.size_block:i]
                n_p = X_i.shape[1]
                for n_pass in range(self.n_passes):

                    lm, lw, sigma = self.get_lambdas(X_i, e * n_times + i, self.m, self.w)
#                    print(e, n_times, e * n_times + i, max(lm), min(lm))
                    m = update_m(X_i, self.m, lambdas=lm)
                    w = update_w_block(self.m @ X_i, self.w, lambdas=lw, n_sub=self.n_sub)

                    self.m, self.w = m, w

                    y = self.w @ self.m @ X_i
                    X_filtered[e, :, i - self.size_block:i] = y

                    self.lambdas.append(lw.mean())
                    self.sigmas.append(sigma)
                
                if ((i % 100) < self.stride) and save:
                    fig = plt.figure(figsize=(9, 9))
                    plt.imshow(self.m)
                    plt.colorbar()
                    fig.savefig("./m/img_{}.png".format(str(im_cnt).rjust(5, "0")))
                    plt.close(fig)
                    del fig
                    
                    fig = plt.figure(figsize=(9, 9))
                    plt.imshow(self.w)
                    plt.colorbar()
                    fig.savefig("./w/img_{}.png".format(str(im_cnt).rjust(5, "0")))
                    plt.close(fig)
                    del fig

                    fig = plt.figure(figsize=(9, 9))
                    plt.imshow(np.corrcoef(self.m @ X_i))
                    plt.colorbar()
                    fig.savefig("./c/img_{}.png".format(str(im_cnt).rjust(5, "0")))
                    plt.close(fig)
                    del fig
                    
                    plt.close("all")
                    im_cnt += 1

        matplotlib.use(orig_mpl_backend)
        return X_filtered
Esempio n. 42
0
def plot_state_qsphere(state, figsize=None, ax=None, show_state_labels=True,
                       show_state_phases=False, use_degrees=False, *, rho=None):
    """Plot the qsphere representation of a quantum state.
    Here, the size of the points is proportional to the probability
    of the corresponding term in the state and the color represents
    the phase.

    Args:
        state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
        figsize (tuple): Figure size in inches.
        ax (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. Additionally, if specified there
            will be no returned Figure since it is redundant.
        show_state_labels (bool): An optional boolean indicating whether to
            show labels for each basis state.
        show_state_phases (bool): An optional boolean indicating whether to
            show the phase for each basis state.
        use_degrees (bool): An optional boolean indicating whether to use
            radians or degrees for the phase values in the plot.

    Returns:
        Figure: A matplotlib figure instance if the ``ax`` kwag is not set

    Raises:
        ImportError: Requires matplotlib.
        VisualizationError: if input is not a valid N-qubit state.

        QiskitError: Input statevector does not have valid dimensions.

    Example:
        .. jupyter-execute::

           from qiskit import QuantumCircuit
           from qiskit.quantum_info import Statevector
           from qiskit.visualization import plot_state_qsphere
           %matplotlib inline

           qc = QuantumCircuit(2)
           qc.h(0)
           qc.cx(0, 1)

           state = Statevector.from_instruction(qc)
           plot_state_qsphere(state)
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed. To install, run "pip install '
                          'matplotlib".')
    try:
        import seaborn as sns
    except ImportError:
        raise ImportError('Must have seaborn installed to use '
                          'plot_state_qsphere. To install, run "pip install seaborn".')
    rho = DensityMatrix(state)
    num = rho.num_qubits
    if num is None:
        raise VisualizationError("Input is not a multi-qubit quantum state.")
    # get the eigenvectors and eigenvalues
    eigvals, eigvecs = linalg.eigh(rho.data)

    if figsize is None:
        figsize = (7, 7)

    if ax is None:
        return_fig = True
        fig = plt.figure(figsize=figsize)
    else:
        return_fig = False
        fig = ax.get_figure()

    gs = gridspec.GridSpec(nrows=3, ncols=3)

    ax = fig.add_subplot(gs[0:3, 0:3], projection='3d')
    ax.axes.set_xlim3d(-1.0, 1.0)
    ax.axes.set_ylim3d(-1.0, 1.0)
    ax.axes.set_zlim3d(-1.0, 1.0)
    ax.axes.grid(False)
    ax.view_init(elev=5, azim=275)

    # start the plotting
    # Plot semi-transparent sphere
    u = np.linspace(0, 2 * np.pi, 25)
    v = np.linspace(0, np.pi, 25)
    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))
    ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',
                    alpha=0.05, linewidth=0)

    # Get rid of the panes
    ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
    ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))

    # Get rid of the spines
    ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
    ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))
    ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))

    # Get rid of the ticks
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_zticks([])

    # traversing the eigvals/vecs backward as sorted low->high
    for idx in range(eigvals.shape[0]-1, -1, -1):
        if eigvals[idx] > 0.001:
            # get the max eigenvalue
            state = eigvecs[:, idx]
            loc = np.absolute(state).argmax()
            # remove the global phase from max element
            angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)
            angleset = np.exp(-1j * angles)
            state = angleset * state

            d = num
            for i in range(2 ** num):
                # get x,y,z points
                element = bin(i)[2:].zfill(num)
                weight = element.count("1")
                zvalue = -2 * weight / d + 1
                number_of_divisions = n_choose_k(d, weight)
                weight_order = bit_string_index(element)
                angle = (float(weight) / d) * (np.pi * 2) + \
                        (weight_order * 2 * (np.pi / number_of_divisions))

                if (weight > d / 2) or ((weight == d / 2) and
                                        (weight_order >= number_of_divisions / 2)):
                    angle = np.pi - angle - (2 * np.pi / number_of_divisions)

                xvalue = np.sqrt(1 - zvalue ** 2) * np.cos(angle)
                yvalue = np.sqrt(1 - zvalue ** 2) * np.sin(angle)

                # get prob and angle - prob will be shade and angle color
                prob = np.real(np.dot(state[i], state[i].conj()))
                if prob > 1:  # See https://github.com/Qiskit/qiskit-terra/issues/4666
                    prob = 1
                colorstate = phase_to_rgb(state[i])

                alfa = 1
                if yvalue >= 0.1:
                    alfa = 1.0 - yvalue

                if not np.isclose(prob, 0) and show_state_labels:
                    rprime = 1.3
                    angle_theta = np.arctan2(np.sqrt(1 - zvalue ** 2), zvalue)
                    xvalue_text = rprime * np.sin(angle_theta) * np.cos(angle)
                    yvalue_text = rprime * np.sin(angle_theta) * np.sin(angle)
                    zvalue_text = rprime * np.cos(angle_theta)
                    element_text = '$\\vert' + element + '\\rangle$'
                    if show_state_phases:
                        element_angle = (np.angle(state[i]) + (np.pi * 4)) % (np.pi * 2)
                        if use_degrees:
                            element_text += '\n$%.1f^\\circ$' % (element_angle * 180/np.pi)
                        else:
                            element_angle = pi_check(element_angle, ndigits=3).replace('pi', '\\pi')
                            element_text += '\n$%s$' % (element_angle)
                    ax.text(xvalue_text, yvalue_text, zvalue_text, element_text,
                            ha='center', va='center', size=12)

                ax.plot([xvalue], [yvalue], [zvalue],
                        markerfacecolor=colorstate,
                        markeredgecolor=colorstate,
                        marker='o', markersize=np.sqrt(prob) * 30, alpha=alfa)

                a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],
                            mutation_scale=20, alpha=prob, arrowstyle="-",
                            color=colorstate, lw=2)
                ax.add_artist(a)

            # add weight lines
            for weight in range(d + 1):
                theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)
                z = -2 * weight / d + 1
                r = np.sqrt(1 - z ** 2)
                x = r * np.cos(theta)
                y = r * np.sin(theta)
                ax.plot(x, y, z, color=(.5, .5, .5), lw=1, ls=':', alpha=.5)

            # add center point
            ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),
                    markeredgecolor=(.5, .5, .5), marker='o', markersize=3,
                    alpha=1)
        else:
            break

    n = 64
    theta = np.ones(n)

    ax2 = fig.add_subplot(gs[2:, 2:])
    ax2.pie(theta, colors=sns.color_palette("hls", n), radius=0.75)
    ax2.add_artist(Circle((0, 0), 0.5, color='white', zorder=1))
    offset = 0.95  # since radius of sphere is one.

    if use_degrees:
        labels = ['Phase\n(Deg)', '0', '90', '180   ', '270']
    else:
        labels = ['Phase', '$0$', '$\\pi/2$', '$\\pi$', '$3\\pi/2$']

    ax2.text(0, 0, labels[0], horizontalalignment='center',
             verticalalignment='center', fontsize=14)
    ax2.text(offset, 0, labels[1], horizontalalignment='center',
             verticalalignment='center', fontsize=14)
    ax2.text(0, offset, labels[2], horizontalalignment='center',
             verticalalignment='center', fontsize=14)
    ax2.text(-offset, 0, labels[3], horizontalalignment='center',
             verticalalignment='center', fontsize=14)
    ax2.text(0, -offset, labels[4], horizontalalignment='center',
             verticalalignment='center', fontsize=14)

    if return_fig:
        if get_backend() in ['module://ipykernel.pylab.backend_inline',
                             'nbAgg']:
            plt.close(fig)
        return fig
Esempio n. 43
0
# Import Python modules
import os
import sys
import math
import atexit
import shutil
import tempfile
import numpy as np
import subprocess
from scipy import interpolate
from scipy.signal import sosfiltfilt, filtfilt, ellip, butter, kaiser, zpk2sos, decimate
from scipy.signal.windows import tukey
from scipy.integrate import cumtrapz
import matplotlib as mpl
if mpl.get_backend() != 'agg':
    mpl.use('Agg')  # Disables use of Tk/X11
import matplotlib.pyplot as plt
import pylab

# This is used to convert from accel in g to accel in cm/s/s
G2CMSS = 980.665  # Convert g to cm/s/s


def cleanup(dir_name):
    """
    This function removes the temporary directory
    """
    shutil.rmtree(dir_name)

Esempio n. 44
0
def mpl_test_settings(request):
    from matplotlib.testing.decorators import _cleanup_cm

    with _cleanup_cm():

        backend = None
        backend_marker = request.node.get_closest_marker('backend')
        if backend_marker is not None:
            assert len(backend_marker.args) == 1, \
                "Marker 'backend' must specify 1 backend."
            backend, = backend_marker.args
            skip_on_importerror = backend_marker.kwargs.get(
                'skip_on_importerror', False)
            prev_backend = matplotlib.get_backend()

            # special case Qt backend importing to avoid conflicts
            if backend.lower().startswith('qt4'):
                if any(k in sys.modules for k in ('PyQt5', 'PySide2')):
                    pytest.skip('Qt5 binding already imported')
                try:
                    import PyQt4
                # RuntimeError if PyQt5 already imported.
                except (ImportError, RuntimeError):
                    try:
                        import PySide
                    except ImportError:
                        pytest.skip("Failed to import a Qt4 binding.")
            elif backend.lower().startswith('qt5'):
                if any(k in sys.modules for k in ('PyQt4', 'PySide')):
                    pytest.skip('Qt4 binding already imported')
                try:
                    import PyQt5
                # RuntimeError if PyQt4 already imported.
                except (ImportError, RuntimeError):
                    try:
                        import PySide2
                    except ImportError:
                        pytest.skip("Failed to import a Qt5 binding.")

        # Default of cleanup and image_comparison too.
        style = ["classic", "_classic_test_patch"]
        style_marker = request.node.get_closest_marker('style')
        if style_marker is not None:
            assert len(style_marker.args) == 1, \
                "Marker 'style' must specify 1 style."
            style, = style_marker.args

        matplotlib.testing.setup()
        if backend is not None:
            # This import must come after setup() so it doesn't load the
            # default backend prematurely.
            import matplotlib.pyplot as plt
            try:
                plt.switch_backend(backend)
            except ImportError as exc:
                # Should only occur for the cairo backend tests, if neither
                # pycairo nor cairocffi are installed.
                if 'cairo' in backend.lower() or skip_on_importerror:
                    pytest.skip("Failed to switch to backend {} ({}).".format(
                        backend, exc))
                else:
                    raise
        with cbook._suppress_matplotlib_deprecation_warning():
            matplotlib.style.use(style)
        try:
            yield
        finally:
            if backend is not None:
                plt.switch_backend(prev_backend)
Esempio n. 45
0
import ekf
import imm
import pda
import estimationstatistics as estats

# %% plot config check and style setup


# to see your plot config
print(f"matplotlib backend: {matplotlib.get_backend()}")
print(f"matplotlib config file: {matplotlib.matplotlib_fname()}")
print(f"matplotlib config dir: {matplotlib.get_configdir()}")
plt.close("all")

# try to set separate window ploting
if "inline" in matplotlib.get_backend():
    print("Plotting is set to inline at the moment:", end=" ")

    if "ipykernel" in matplotlib.get_backend():
        print("backend is ipykernel (IPython?)")
        print("Trying to set backend to separate window:", end=" ")
        import IPython

        IPython.get_ipython().run_line_magic("matplotlib", "")
    else:
        print("unknown inline backend")

print("continuing with this plotting backend", end="\n\n\n")


# set styles
Esempio n. 46
0
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.patches import Rectangle
matplotlib.get_backend()
matplotlib.use('TkAgg')
import dateutil.parser as parser

file_path = 'G:/Semester 8/FYP2/dataset/users/users_part.tsv'
users = pd.read_csv(file_path, sep='\t')

# display more width and columns
desired_width = 320
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns', None)

# Unique values
unique_managed_others = users.ManagedOthers.unique()
print('Managed Others Unique Values', unique_managed_others)

# Bar Graph
counts = users.ManagedOthers.value_counts()
output = plt.bar(counts.index, counts.values, ec='black', width=0.5)

cmap = plt.get_cmap('jet')
color1 = cmap(0.25)
color2 = cmap(0.75)

output[0].set_facecolor(color1)
output[1].set_facecolor(color2)
Esempio n. 47
0
def PlottingBackend_Switch(whichBackEnd):
    import matplotlib
    matplotlib.use(whichBackEnd, warn=False, force=True)
    from matplotlib import pyplot as plt
    print "Switched to:", matplotlib.get_backend()
Esempio n. 48
0
def main(filename, outfile="stdout", verbose=3):
    """Method to call ahkab from a Python script with a netlist file.

    **Parameters:**

    filename : string
        The netlist filename.

    outfile : string, optional
        The outfiles base name, the suffixes shown below will be added.
        With the exception of the magic value ``stdout`` which causes
        ahkab to print out instead of to disk.

    verbose : int, optional
        the verbosity level, from 0 (silent) to 6 (debug).
        It defaults to 3, the same as running ahkab through its command
        line interface.

    Filename suffixes, for each analysis:

    - Alternate Current (AC): ``.ac``
    - Direct Current (DC): ``.dc``
    - Operating Point (OP): ``.opinfo``
    - Periodic Steady State (PSS): ``.pss``
    - Pole-zero Analysis (PZ): ``.pz``
    - TRANsient (TRAN): ``.tran``
    - Symbolic: ``.symbolic``

    **Returns:**

    res : dict
        A dictionary containing the computed results.
    """
    printing.print_info_line(
        ("This is ahkab %s running with:" % (__version__), 6), verbose)
    printing.print_info_line(
        ("  Python %s" % (sys.version.split('\n')[0],), 6), verbose)
    printing.print_info_line(("  Numpy %s" % (np.__version__), 6), verbose)
    printing.print_info_line(("  Scipy %s" % (sp.__version__), 6), verbose)
    printing.print_info_line(("  Sympy %s" % (sympy.__version__), 6), verbose)
    printing.print_info_line(("  Tabulate %s" % (tabulate.__version__), 6), verbose)
    if plotting_available:
        printing.print_info_line(("  Matplotlib %s" % (matplotlib.__version__),
                                  6), verbose)
        printing.print_info_line(("  -> backend: %s" %
                                 (matplotlib.get_backend()), 6), verbose)
        printing.print_info_line(("  -> matplotlibrc: %s" %
                                 (matplotlib.matplotlib_fname()), 6), verbose)
    else:
        printing.print_info_line(
            ("  Matplotlib not found.", 6), verbose)


    read_netlist_from_stdin = (filename is None or filename == "-")
    (circ, directives, postproc_direct) = netlist_parser.parse_circuit(
        filename, read_netlist_from_stdin)

    printing.print_info_line(("Checking circuit for common mistakes...", 6),
                             verbose, print_nl=False)
    check, reason = utilities.check_circuit(circ)
    if not check:
        printing.print_general_error(reason)
        sys.exit(3)
    printing.print_info_line(("done.", 6), verbose)

    if verbose > 3 or _print:
        print("Parsed circuit:")
        print(circ)
        print("Models:")
        for m in circ.models:
            circ.models[m].print_model()
        print("")

    ic_list = netlist_parser.parse_ics(directives)
    _handle_netlist_ics(circ, an_list=[], ic_list=ic_list)
    results = {}
    for an in netlist_parser.parse_analysis(circ, directives):
        if 'outfile' not in list(an.keys()) or not an['outfile']:
            an.update(
                {'outfile': outfile + ("." + an['type']) * (outfile != 'stdout')})
        if 'verbose' in list(an.keys()) and (an['verbose'] is None or an['verbose'] < verbose) \
           or not 'verbose' in list(an.keys()):
            an.update({'verbose': verbose})
        _handle_netlist_ics(circ, [an], ic_list=[])
        if verbose >= 4:
            printing.print_info_line(("Requested an.:", 4), verbose)
            printing.print_analysis(an)
        results.update(run(circ, [an]))

    postproc_list = netlist_parser.parse_postproc(circ, postproc_direct)
    if len(postproc_list) > 0 and len(results):
        process_postproc(postproc_list, circ.title, results, outfile)

    return results
Esempio n. 49
0
def plot_state_hinton(state, title='', figsize=None, ax_real=None, ax_imag=None, *, rho=None):
    """Plot a hinton diagram for the density matrix of a quantum state.

    Args:
        state (Statevector or DensityMatrix or ndarray): An N-qubit quantum state.
        title (str): a string that represents the plot title
        figsize (tuple): Figure size in inches.
        ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. If this is specified without an
            ax_imag only the real component plot will be generated.
            Additionally, if specified there will be no returned Figure since
            it is redundant.
        ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. If this is specified without an
            ax_imag only the real component plot will be generated.
            Additionally, if specified there will be no returned Figure since
            it is redundant.

    Returns:
         matplotlib.Figure:
            The matplotlib.Figure of the visualization if
            neither ax_real or ax_imag is set.

    Raises:
        ImportError: Requires matplotlib.
        VisualizationError: if input is not a valid N-qubit state.

    Example:
        .. jupyter-execute::

            from qiskit import QuantumCircuit
            from qiskit.quantum_info import DensityMatrix
            from qiskit.visualization import plot_state_hinton
            %matplotlib inline

            qc = QuantumCircuit(2)
            qc.h(0)
            qc.cx(0, 1)

            state = DensityMatrix.from_instruction(qc)
            plot_state_hinton(state, title="New Hinton Plot")
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed. To install, run '
                          '"pip install matplotlib".')
    # Figure data
    rho = DensityMatrix(state)
    num = rho.num_qubits
    if num is None:
        raise VisualizationError("Input is not a multi-qubit quantum state.")
    max_weight = 2 ** np.ceil(np.log(np.abs(rho.data).max()) / np.log(2))
    datareal = np.real(rho.data)
    dataimag = np.imag(rho.data)

    if figsize is None:
        figsize = (8, 5)
    if not ax_real and not ax_imag:
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)
    else:
        if ax_real:
            fig = ax_real.get_figure()
        else:
            fig = ax_imag.get_figure()
        ax1 = ax_real
        ax2 = ax_imag
    column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
    row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
    ly, lx = datareal.shape
    # Real
    if ax1:
        ax1.patch.set_facecolor('gray')
        ax1.set_aspect('equal', 'box')
        ax1.xaxis.set_major_locator(plt.NullLocator())
        ax1.yaxis.set_major_locator(plt.NullLocator())

        for (x, y), w in np.ndenumerate(datareal):
            color = 'white' if w > 0 else 'black'
            size = np.sqrt(np.abs(w) / max_weight)
            rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                                 facecolor=color, edgecolor=color)
            ax1.add_patch(rect)

        ax1.set_xticks(np.arange(0, lx+0.5, 1))
        ax1.set_yticks(np.arange(0, ly+0.5, 1))
        row_names.append('')
        ax1.set_yticklabels(row_names, fontsize=14)
        column_names.append('')
        ax1.set_xticklabels(column_names, fontsize=14, rotation=90)
        ax1.autoscale_view()
        ax1.invert_yaxis()
        ax1.set_title('Re[$\\rho$]', fontsize=14)
    # Imaginary
    if ax2:
        ax2.patch.set_facecolor('gray')
        ax2.set_aspect('equal', 'box')
        ax2.xaxis.set_major_locator(plt.NullLocator())
        ax2.yaxis.set_major_locator(plt.NullLocator())

        for (x, y), w in np.ndenumerate(dataimag):
            color = 'white' if w > 0 else 'black'
            size = np.sqrt(np.abs(w) / max_weight)
            rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                                 facecolor=color, edgecolor=color)
            ax2.add_patch(rect)

        ax2.set_xticks(np.arange(0, lx+0.5, 1))
        ax2.set_yticks(np.arange(0, ly+0.5, 1))
        ax2.set_yticklabels(row_names, fontsize=14)
        ax2.set_xticklabels(column_names, fontsize=14, rotation=90)

        ax2.autoscale_view()
        ax2.invert_yaxis()
        ax2.set_title('Im[$\\rho$]', fontsize=14)
    if title:
        fig.suptitle(title, fontsize=16)
    if ax_real is None and ax_imag is None:
        if get_backend() in ['module://ipykernel.pylab.backend_inline',
                             'nbAgg']:
            plt.close(fig)
        return fig
Esempio n. 50
0
def plot_state_city(state,
                    title="",
                    figsize=None,
                    color=None,
                    alpha=1,
                    ax_real=None,
                    ax_imag=None,
                    *,
                    rho=None):
    """Plot the cityscape of quantum state.

    Plot two 3d bar graphs (two dimensional) of the real and imaginary
    part of the density matrix rho.

    Args:
        state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
        title (str): a string that represents the plot title
        figsize (tuple): Figure size in inches.
        color (list): A list of len=2 giving colors for real and
            imaginary components of matrix elements.
        alpha (float): Transparency value for bars
        ax_real (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. If this is specified without an
            ax_imag only the real component plot will be generated.
            Additionally, if specified there will be no returned Figure since
            it is redundant.
        ax_imag (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. If this is specified without an
            ax_imag only the real component plot will be generated.
            Additionally, if specified there will be no returned Figure since
            it is redundant.

    Returns:
         matplotlib.Figure:
            The matplotlib.Figure of the visualization if the
            ``ax_real`` and ``ax_imag`` kwargs are not set

    Raises:
        ImportError: Requires matplotlib.
        ValueError: When 'color' is not a list of len=2.
        VisualizationError: if input is not a valid N-qubit state.

    Example:
        .. jupyter-execute::

           from qiskit import QuantumCircuit
           from qiskit.quantum_info import DensityMatrix
           from qiskit.visualization import plot_state_city
           %matplotlib inline

           qc = QuantumCircuit(2)
           qc.h(0)
           qc.cx(0, 1)

           state = DensityMatrix.from_instruction(qc)
           plot_state_city(state, color=['midnightblue', 'midnightblue'],
                title="New State City")
    """
    if not HAS_MATPLOTLIB:
        raise ImportError(
            'Must have Matplotlib installed. To install, run "pip install '
            'matplotlib".')
    rho = DensityMatrix(state)
    num = rho.num_qubits
    if num is None:
        raise VisualizationError("Input is not a multi-qubit quantum state.")

    # get the real and imag parts of rho
    datareal = np.real(rho.data)
    dataimag = np.imag(rho.data)

    # get the labels
    column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]
    row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]

    lx = len(datareal[0])  # Work out matrix dimensions
    ly = len(datareal[:, 0])
    xpos = np.arange(0, lx, 1)  # Set up a mesh of positions
    ypos = np.arange(0, ly, 1)
    xpos, ypos = np.meshgrid(xpos + 0.25, ypos + 0.25)

    xpos = xpos.flatten()
    ypos = ypos.flatten()
    zpos = np.zeros(lx * ly)

    dx = 0.5 * np.ones_like(zpos)  # width of bars
    dy = dx.copy()
    dzr = datareal.flatten()
    dzi = dataimag.flatten()

    if color is None:
        color = ["#648fff", "#648fff"]
    else:
        if len(color) != 2:
            raise ValueError("'color' must be a list of len=2.")
        if color[0] is None:
            color[0] = "#648fff"
        if color[1] is None:
            color[1] = "#648fff"
    if ax_real is None and ax_imag is None:
        # set default figure size
        if figsize is None:
            figsize = (15, 5)

        fig = plt.figure(figsize=figsize)
        ax1 = fig.add_subplot(1, 2, 1, projection='3d')
        ax2 = fig.add_subplot(1, 2, 2, projection='3d')
    elif ax_real is not None:
        fig = ax_real.get_figure()
        ax1 = ax_real
        if ax_imag is not None:
            ax2 = ax_imag
    else:
        fig = ax_imag.get_figure()
        ax1 = None
        ax2 = ax_imag

    max_dzr = max(dzr)
    min_dzr = min(dzr)
    min_dzi = np.min(dzi)
    max_dzi = np.max(dzi)

    if ax1 is not None:
        fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])
        for idx, cur_zpos in enumerate(zpos):
            if dzr[idx] > 0:
                zorder = 2
            else:
                zorder = 0
            b1 = ax1.bar3d(xpos[idx],
                           ypos[idx],
                           cur_zpos,
                           dx[idx],
                           dy[idx],
                           dzr[idx],
                           alpha=alpha,
                           zorder=zorder)
            b1.set_facecolors(fc1[6 * idx:6 * idx + 6])

        xlim, ylim = ax1.get_xlim(), ax1.get_ylim()
        x = [xlim[0], xlim[1], xlim[1], xlim[0]]
        y = [ylim[0], ylim[0], ylim[1], ylim[1]]
        z = [0, 0, 0, 0]
        verts = [list(zip(x, y, z))]

        pc1 = Poly3DCollection(verts,
                               alpha=0.15,
                               facecolor='k',
                               linewidths=1,
                               zorder=1)

        if min(dzr) < 0 < max(dzr):
            ax1.add_collection3d(pc1)
        ax1.set_xticks(np.arange(0.5, lx + 0.5, 1))
        ax1.set_yticks(np.arange(0.5, ly + 0.5, 1))
        if max_dzr != min_dzr:
            ax1.axes.set_zlim3d(np.min(dzr), max(np.max(dzr) + 1e-9, max_dzi))
        else:
            if min_dzr == 0:
                ax1.axes.set_zlim3d(np.min(dzr),
                                    max(np.max(dzr) + 1e-9, np.max(dzi)))
            else:
                ax1.axes.set_zlim3d(auto=True)
        ax1.get_autoscalez_on()
        ax1.w_xaxis.set_ticklabels(row_names,
                                   fontsize=14,
                                   rotation=45,
                                   ha='right',
                                   va='top')
        ax1.w_yaxis.set_ticklabels(column_names,
                                   fontsize=14,
                                   rotation=-22.5,
                                   ha='left',
                                   va='center')
        ax1.set_zlabel('Re[$\\rho$]', fontsize=14)
        for tick in ax1.zaxis.get_major_ticks():
            tick.label.set_fontsize(14)

    if ax2 is not None:
        fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])
        for idx, cur_zpos in enumerate(zpos):
            if dzi[idx] > 0:
                zorder = 2
            else:
                zorder = 0
            b2 = ax2.bar3d(xpos[idx],
                           ypos[idx],
                           cur_zpos,
                           dx[idx],
                           dy[idx],
                           dzi[idx],
                           alpha=alpha,
                           zorder=zorder)
            b2.set_facecolors(fc2[6 * idx:6 * idx + 6])

        xlim, ylim = ax2.get_xlim(), ax2.get_ylim()
        x = [xlim[0], xlim[1], xlim[1], xlim[0]]
        y = [ylim[0], ylim[0], ylim[1], ylim[1]]
        z = [0, 0, 0, 0]
        verts = [list(zip(x, y, z))]

        pc2 = Poly3DCollection(verts,
                               alpha=0.2,
                               facecolor='k',
                               linewidths=1,
                               zorder=1)

        if min(dzi) < 0 < max(dzi):
            ax2.add_collection3d(pc2)
        ax2.set_xticks(np.arange(0.5, lx + 0.5, 1))
        ax2.set_yticks(np.arange(0.5, ly + 0.5, 1))
        if min_dzi != max_dzi:
            eps = 0
            ax2.axes.set_zlim3d(np.min(dzi),
                                max(np.max(dzr) + 1e-9,
                                    np.max(dzi) + eps))
        else:
            if min_dzi == 0:
                ax2.set_zticks([0])
                eps = 1e-9
                ax2.axes.set_zlim3d(np.min(dzi),
                                    max(np.max(dzr) + 1e-9,
                                        np.max(dzi) + eps))
            else:
                ax2.axes.set_zlim3d(auto=True)

        ax2.w_xaxis.set_ticklabels(row_names,
                                   fontsize=14,
                                   rotation=45,
                                   ha='right',
                                   va='top')
        ax2.w_yaxis.set_ticklabels(column_names,
                                   fontsize=14,
                                   rotation=-22.5,
                                   ha='left',
                                   va='center')
        ax2.set_zlabel('Im[$\\rho$]', fontsize=14)
        for tick in ax2.zaxis.get_major_ticks():
            tick.label.set_fontsize(14)
        ax2.get_autoscalez_on()

    fig.suptitle(title, fontsize=16)
    if ax_real is None and ax_imag is None:
        if get_backend() in [
                'module://ipykernel.pylab.backend_inline', 'nbAgg'
        ]:
            plt.close(fig)
        return fig
Esempio n. 51
0
def plot_state_paulivec(state, title="", figsize=None, color=None, ax=None, *, rho=None):
    """Plot the paulivec representation of a quantum state.

    Plot a bargraph of the mixed state rho over the pauli matrices

    Args:
        state (Statevector or DensityMatrix or ndarray): an N-qubit quantum state.
        title (str): a string that represents the plot title
        figsize (tuple): Figure size in inches.
        color (list or str): Color of the expectation value bars.
        ax (matplotlib.axes.Axes): An optional Axes object to be used for
            the visualization output. If none is specified a new matplotlib
            Figure will be created and used. Additionally, if specified there
            will be no returned Figure since it is redundant.

    Returns:
         matplotlib.Figure:
            The matplotlib.Figure of the visualization if the
            ``ax`` kwarg is not set

    Raises:
        ImportError: Requires matplotlib.
        VisualizationError: if input is not a valid N-qubit state.

    Example:
        .. jupyter-execute::

           from qiskit import QuantumCircuit
           from qiskit.quantum_info import Statevector
           from qiskit.visualization import plot_state_paulivec
           %matplotlib inline

           qc = QuantumCircuit(2)
           qc.h(0)
           qc.cx(0, 1)

           state = Statevector.from_instruction(qc)
           plot_state_paulivec(state, color='midnightblue',
                title="New PauliVec plot")
    """
    if not HAS_MATPLOTLIB:
        raise ImportError('Must have Matplotlib installed. To install, run "pip install '
                          'matplotlib".')
    labels, values = _paulivec_data(state)
    numelem = len(values)

    if figsize is None:
        figsize = (7, 5)
    if color is None:
        color = "#648fff"

    ind = np.arange(numelem)  # the x locations for the groups
    width = 0.5  # the width of the bars
    if ax is None:
        return_fig = True
        fig, ax = plt.subplots(figsize=figsize)
    else:
        return_fig = False
        fig = ax.get_figure()
    ax.grid(zorder=0, linewidth=1, linestyle='--')
    ax.bar(ind, values, width, color=color, zorder=2)
    ax.axhline(linewidth=1, color='k')
    # add some text for labels, title, and axes ticks
    ax.set_ylabel('Expectation value', fontsize=14)
    ax.set_xticks(ind)
    ax.set_yticks([-1, -0.5, 0, 0.5, 1])
    ax.set_xticklabels(labels, fontsize=14, rotation=70)
    ax.set_xlabel('Pauli', fontsize=14)
    ax.set_ylim([-1, 1])
    ax.set_facecolor('#eeeeee')
    for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():
        tick.label.set_fontsize(14)
    ax.set_title(title, fontsize=16)
    if return_fig:
        if get_backend() in ['module://ipykernel.pylab.backend_inline',
                             'nbAgg']:
            plt.close(fig)
        return fig
Esempio n. 52
0
# -*- coding: utf-8 -*-
'''
**********************************************************
*
* SpectraLearnPredict2 - Preprocess data
* Perform Machine Learning on Spectroscopy Data.
*
* Uses: Deep Neural Networks, TensorFlow, SVM, PCA, K-Means
*
* By: Nicola Ferralis <*****@*****.**>
*
***********************************************************
'''

import matplotlib
if matplotlib.get_backend() == 'TkAgg':
    matplotlib.use('Agg')

import numpy as np
import sys, os.path, getopt, glob, csv
import random, time, configparser, os
from os.path import exists, splitext
from os import rename
from datetime import datetime, date

from .slp_config import *

#************************************
''' Read Learning file '''

Esempio n. 53
0
        def refresh_ptcl(change=None, force=False):
            """
            Refresh the current particle figure

            Parameters :
            ------------
            change: dictionary
                Dictionary passed by the widget to a callback functions
                whenever a change of a widget happens
                (see docstring of ipywidgets.Widget.observe)
                This is mainline a place holder ; not used in this function

            force: bool
                Whether to force the update
            """
            # Determine whether to do the refresh
            do_refresh = False
            if self.avail_species is not None:
                if force or ptcl_refresh_toggle.value:
                    do_refresh = True
            # Do the refresh
            if do_refresh:
                plt.figure(ptcl_figure_button.value, figsize=figsize)
                plt.clf()

                # When working in inline mode, in an ipython notebook,
                # clear the output (prevents the images from stacking
                # in the notebook)
                if 'inline' in matplotlib.get_backend():
                    clear_output()

                if ptcl_use_button.value:
                    i_power = ptcl_magnitude_button.value
                    vmin = ptcl_range_button.value[0] * 10**i_power
                    vmax = ptcl_range_button.value[1] * 10**i_power
                else:
                    vmin = None
                    vmax = None

                if ptcl_yaxis_button.value == 'None':
                    # 1D histogram
                    self.get_particle(t=self.current_t,
                                      output=False,
                                      var_list=[ptcl_xaxis_button.value],
                                      select=ptcl_select_widget.to_dict(),
                                      species=ptcl_species_button.value,
                                      plot=True,
                                      vmin=vmin,
                                      vmax=vmax,
                                      cmap=ptcl_color_button.value,
                                      nbins=ptcl_bins_button.value)
                else:
                    # 2D histogram
                    self.get_particle(t=self.current_t,
                                      output=False,
                                      var_list=[
                                          ptcl_xaxis_button.value,
                                          ptcl_yaxis_button.value
                                      ],
                                      select=ptcl_select_widget.to_dict(),
                                      species=ptcl_species_button.value,
                                      plot=True,
                                      vmin=vmin,
                                      vmax=vmax,
                                      cmap=ptcl_color_button.value,
                                      nbins=ptcl_bins_button.value)
Esempio n. 54
0
 def __enter__(self):
     if mpl.get_backend() in mpl.rcsetup.interactive_bk:
         mpl.rcParams['text.latex.preview'] = True
Esempio n. 55
0
def _save_raw_dialog_box(*, bads, bad_descriptions, annotations, bids_path,
                         verbose):
    """Display a dialog box asking whether to save the changes."""
    # Delay the imports
    import matplotlib
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    from mne.viz.utils import figure_nobar

    title = 'Save changes?'
    message = 'You have modified '
    if bads is not None and annotations is None:
        message += 'the bad channel selection '
        figsize = (7.5, 2.5)
    elif bads is None and annotations is not None:
        message += 'the bad segments selection '
        figsize = (7.5, 2.5)
    else:
        message += 'the bad channel and\nannotations selection '
        figsize = (8.5, 3)

    message += (f'of\n'
                f'{bids_path.basename}.\n\n'
                f'Would you like to save these changes to the\n'
                f'BIDS dataset?')
    icon_fname = str(Path(__file__).parent / 'assets' / 'help-128px.png')
    icon = plt.imread(icon_fname)

    fig = figure_nobar(figsize=figsize)
    fig.canvas.manager.set_window_title('MNE-BIDS Inspector')
    fig.suptitle(title, y=0.95, fontsize='xx-large', fontweight='bold')

    gs = fig.add_gridspec(1, 2, width_ratios=(1.5, 5))

    # The dialog box tet.
    ax_msg = fig.add_subplot(gs[0, 1])
    ax_msg.text(x=0,
                y=0.8,
                s=message,
                fontsize='large',
                verticalalignment='top',
                horizontalalignment='left',
                multialignment='left')
    ax_msg.axis('off')

    # The help icon.
    ax_icon = fig.add_subplot(gs[0, 0])
    ax_icon.imshow(icon)
    ax_icon.axis('off')

    # Buttons.
    ax_save = fig.add_axes([0.6, 0.05, 0.3, 0.1])
    ax_dont_save = fig.add_axes([0.1, 0.05, 0.3, 0.1])

    save_button = Button(ax=ax_save, label='Save')
    save_button.label.set_fontsize('medium')
    save_button.label.set_fontweight('bold')

    dont_save_button = Button(ax=ax_dont_save, label="Don't save")
    dont_save_button.label.set_fontsize('medium')
    dont_save_button.label.set_fontweight('bold')

    # Store references to keep buttons alive.
    fig.save_button = save_button
    fig.dont_save_button = dont_save_button

    # Define callback functions.
    def _save_callback(event):
        plt.close(event.canvas.figure)  # Close dialog
        _global_vars['dialog_fig'] = None

        if bads is not None:
            _save_bads(bads=bads,
                       descriptions=bad_descriptions,
                       bids_path=bids_path,
                       verbose=verbose)
        if annotations is not None:
            _save_annotations(annotations=annotations,
                              bids_path=bids_path,
                              verbose=verbose)

    def _dont_save_callback(event):
        plt.close(event.canvas.figure)  # Close dialog
        _global_vars['dialog_fig'] = None

    def _keypress_callback(event):
        if event.key in ['enter', 'return']:
            _save_callback(event)
        elif event.key == _global_vars['mne_close_key']:
            _dont_save_callback(event)

    # Connect events to callback functions.
    save_button.on_clicked(_save_callback)
    dont_save_button.on_clicked(_dont_save_callback)
    fig.canvas.mpl_connect('close_event', _dont_save_callback)
    fig.canvas.mpl_connect('key_press_event', _keypress_callback)

    if matplotlib.get_backend() != 'agg':
        fig.show()

    _global_vars['dialog_fig'] = fig
Esempio n. 56
0
def visualize_solution_scatter(jobs: List['TaskJobs'],
                               title,
                               path: Optional[str] = None,
                               solution_type: Optional[str] = None,
                               logscale=False,
                               ylabel=None,
                               vis_type=VisTypes.Absolute,
                               loc=1,
                               bbox_pos=None,
                               top_margin=0.65,
                               show_legend=True):
    if solution_type is None:
        solution_type = _get_dominant_solution_type(jobs)
    if not ylabel:
        y_label = _sol_type_to_label[solution_type]
    for s in tqdm.tqdm(jobs, desc="Calculate lower bounds"):
        if s.solution is not None:
            _get_LB(s.solution, solution_type)
    df = pd.DataFrame([{
        "Solver":
        _get_solver_name(job),
        "VertAmount":
        job.solution.graph.vert_amount,
        "EdgeAmount":
        job.solution.graph.edge_amount,
        "Graph_id":
        job.solution.graph.id,
        "Runtime":
        float(job.solution.runtime) if job.prev_job is None else
        float(job.prev_job.solution.runtime + job.solution.runtime),
        "MinSum":
        job.solution.min_sum,
        "LocalMinSum":
        job.solution.local_min_sum,
        "Makespan":
        job.solution.makespan,
        "LB":
        _get_LB(job.solution, solution_type)
    } for job in tqdm.tqdm(jobs, desc="Collect solution information")
                       if job.solution is not None])
    # Then plot the data
    if vis_type == VisTypes.All:
        fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True)
        #fig.suptitle(title)
        if isinstance(logscale, bool):
            logscale = [logscale for i in range(4)]
        if len(logscale) < 4:
            logscale = logscale + [False for i in range(4 - len(logscale))]
        label_cols = 3
        top_margin = top_margin + 0.2
        columns = _plot_data(
            df,
            solution_type,
            "Edge amount",
            y_label,
            logscale=logscale[0],
            vis_type=VisTypes.Absolute,
            ax=axes[0, 0],
        )  # show_legend=True)
        columns = _plot_data(
            df,
            solution_type,
            "Edge amount",
            y_label,
            logscale=logscale[1],
            vis_type=VisTypes.VsBest,
            ax=axes[0, 1],
        )  # show_legend=True)
        columns = _plot_data(
            df,
            solution_type,
            "Edge amount",
            y_label,
            logscale=logscale[2],
            vis_type=VisTypes.VsLB,
            ax=axes[1, 0],
        )  # show_legend=True)
        columns = _plot_data(
            df,
            "runtime",
            "Edge amount",
            "Runtime",
            logscale=logscale[3],
            vis_type=VisTypes.Absolute,
            ax=axes[1, 1],
        )  # show_legend=True)
        fig.set_size_inches(fig.get_size_inches() * 1.5)
        fig.tight_layout()
        handles, labels = axes[1, 1].get_legend_handles_labels()
        fig.legend(handles, labels, loc=loc, bbox_to_anchor=bbox_pos,\
            ncol=label_cols)

        _make_space_above(axes, top_margin)
        #fig.legend([m_i[1] for m_i in columns], loc=loc, bbox_to_anchor=bbox_pos)
    elif vis_type == VisTypes.LB_Runtime:
        fig, axes = plt.subplots(nrows=1, ncols=2, sharex=True)
        #fig.suptitle(title)
        if isinstance(logscale, bool):
            logscale = [logscale for i in range(2)]
        if len(logscale) < 4:
            logscale = logscale + [False for i in range(2 - len(logscale))]
        label_cols = 3
        top_margin = top_margin + 0.25
        columns = _plot_data(
            df,
            solution_type,
            "Edge amount",
            y_label,
            logscale=logscale[0],
            vis_type=VisTypes.VsLB,
            ax=axes[0],
        )  # show_legend=True)
        columns = _plot_data(
            df,
            "runtime",
            "Edge amount",
            "Runtime",
            logscale=logscale[1],
            vis_type=VisTypes.Absolute,
            ax=axes[1],
        )  # show_legend=True)
        fig.set_size_inches(fig.get_size_inches() * (1.3, 0.9))
        fig.tight_layout()
        handles, labels = axes[1].get_legend_handles_labels()
        fig.legend(handles, labels, loc=loc, bbox_to_anchor=bbox_pos,\
            ncol=label_cols)
        _make_space_above(axes, top_margin)

    else:
        columns = _plot_data(df,
                             solution_type,
                             "Edge amount",
                             y_label,
                             logscale=logscale,
                             vis_type=vis_type,
                             show_legend=True)
        plt.title(title)

    if path is None:
        plt.show()
    else:
        if path[-3:] == "ipe":
            old_backend = matplotlib.get_backend()
            matplotlib.use('module://backend_ipe')
            save_format = "ipe"
            plt.savefig(path, format=save_format)
            matplotlib.use(old_backend)
        else:
            plt.savefig(path)
Esempio n. 57
0
import wx
import matplotlib
if matplotlib.get_backend() != 'WXAgg':
    # this is actually just to check if it's loaded. if it already was loaded
    # and set to a different backend, then we couldn't change it anyway.
    matplotlib.use('WXAgg')

from matplotlib.figure import Figure as MatplotlibFigure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as MatplotlibFigureCanvas
from matplotlib.backends.backend_wxagg import NavigationToolbar2WxAgg as MatplotlibToolbar


class Figure():
    """ WxAgg version of the Matplotlib figure.
        Pass it a wx.Panel as a parent, and then you can
        access axes, etc.
        I tried directly inheriting from MatplotlibFigure but
        I kept getting an error about the axes not being iterable...
    """
    def __init__(self, parent, **kwargs):
        self.fig = MatplotlibFigure(facecolor=(0.94117, 0.92156, 0.88627),
                                    figsize=(4, 4))
        self.fig.clf()
        self.axes = self.fig.add_subplot(111)

        if 'xlabel' in kwargs.keys():
            self.axes.set_xlabel(kwargs['xlabel'])

        if 'ylabel' in kwargs.keys():
            self.axes.set_ylabel(kwargs['ylabel'])
Esempio n. 58
0
ipythonpath = casa['dirs']['rc'] + '/ipython'
try:
    os.makedirs(ipythonpath, 0755)
except:
    pass

if (not os.environ.has_key('IPYTHONDIR')):
    os.environ['IPYTHONDIR'] = ipythonpath
if (not os.path.exists(os.environ['IPYTHONDIR'])):
    os.makedirs(os.environ['IPYTHONDIR'], 0755)

os.environ['__CASARCDIR__'] = casa['dirs']['rc']

# Special case if the back-end is set to MacOSX reset it
# to TkAgg as our TablePlot stuff is specific for TkAgg
if matplotlib.get_backend() == "MacOSX":
    matplotlib.use('TkAgg')

# Check if the display environment is set if not
# switch the backend to Agg only if it's TkAgg
if not os.environ.has_key('DISPLAY') and matplotlib.get_backend() == "TkAgg":
    matplotlib.use('Agg')

showconsole = False
deploylogger = False
thelogfile = 'null'

# Task Interface
from parameter_check import *

# CAS-951: matplotlib unresponsive on some 64bit systems
Esempio n. 59
0
from pyrates.utility.visualization import plot_timeseries, create_cmap
from pyrates.utility.grid_search import grid_search
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter1d
from scipy.signal import correlate
import matplotlib as mpl

print(mpl.get_backend())
plt.style.reload_library()
plt.style.use('ggplot')
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['axes.titlesize'] = 12
mpl.rcParams['axes.titleweight'] = 'bold'
mpl.rcParams['axes.labelsize'] = 12
mpl.rcParams['axes.labelcolor'] = 'black'
mpl.rcParams['axes.labelweight'] = 'bold'
mpl.rcParams['xtick.labelsize'] = 12
mpl.rcParams['ytick.labelsize'] = 12
mpl.rcParams['xtick.color'] = 'black'
mpl.rcParams['ytick.color'] = 'black'
mpl.rcParams['legend.fontsize'] = 12

# simulation parameters
dt = 1e-3
dts = 1e-1
T = 200.0

# model parameters
etas = np.linspace(-200.0, 200.0, num=40)
ks = np.asarray([0.2, 0.6, 1.0, 1.4, 1.8])
Esempio n. 60
0
def _inspect_raw(*,
                 bids_path,
                 l_freq,
                 h_freq,
                 find_flat,
                 show_annotations,
                 verbose=None):
    """Raw data inspection."""
    # Delay the import
    import matplotlib
    import matplotlib.pyplot as plt

    extra_params = dict()
    if bids_path.extension == '.fif':
        extra_params['allow_maxshield'] = True
    raw = read_raw_bids(bids_path, extra_params=extra_params, verbose='error')
    old_bads = raw.info['bads'].copy()
    old_annotations = raw.annotations.copy()

    if find_flat:
        raw.load_data()  # Speeds up processing dramatically
        flat_annot, flat_chans = annotate_flat(raw=raw,
                                               min_duration=0.05,
                                               verbose=verbose)
        new_annot = raw.annotations + flat_annot
        raw.set_annotations(new_annot)
        raw.info['bads'] = list(set(raw.info['bads'] + flat_chans))
        del new_annot, flat_annot
    else:
        flat_chans = []

    show_options = bids_path.datatype == 'meg'
    fig = raw.plot(title=f'{bids_path.root.name}: {bids_path.basename}',
                   highpass=l_freq,
                   lowpass=h_freq,
                   show_options=show_options,
                   block=False,
                   show=False,
                   verbose='warning')

    # Add our own event handlers so that when the MNE Raw Browser is being
    # closed, our dialog box will pop up, asking whether to save changes.
    def _handle_close(event):
        mne_raw_fig = event.canvas.figure
        # Bads alterations are only transferred to `inst` once the figure is
        # closed; Annotation changes are immediately reflected in `inst`
        new_bads = mne_raw_fig.mne.info['bads'].copy()
        new_annotations = mne_raw_fig.mne.inst.annotations.copy()

        if not new_annotations:
            # Ensure it's not an empty list, but an empty set of Annotations.
            new_annotations = mne.Annotations(
                onset=[],
                duration=[],
                description=[],
                orig_time=mne_raw_fig.mne.info['meas_date'])
        _save_raw_if_changed(old_bads=old_bads,
                             new_bads=new_bads,
                             flat_chans=flat_chans,
                             old_annotations=old_annotations,
                             new_annotations=new_annotations,
                             bids_path=bids_path,
                             verbose=verbose)
        _global_vars['raw_fig'] = None

    def _keypress_callback(event):
        if event.key == _global_vars['mne_close_key']:
            _handle_close(event)

    fig.canvas.mpl_connect('close_event', _handle_close)
    fig.canvas.mpl_connect('key_press_event', _keypress_callback)

    if not show_annotations:
        # Remove annotations and kill `_toggle_annotation_fig` method, since
        # we cannot directly and easily remove the associated `a` keyboard
        # event callback.
        fig._clear_annotations()
        fig._toggle_annotation_fig = lambda: None
        # Ensure it's not an empty list, but an empty set of Annotations.
        old_annotations = mne.Annotations(onset=[],
                                          duration=[],
                                          description=[],
                                          orig_time=raw.info['meas_date'])

    if matplotlib.get_backend() != 'agg':
        plt.show(block=True)

    _global_vars['raw_fig'] = fig
    _global_vars['mne_close_key'] = fig.mne.close_key