Python matplotlib.pyplot.switch_backend() Examples

The following are code examples for showing how to use matplotlib.pyplot.switch_backend(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Chinese-Character-and-Calligraphic-Image-Processing   Author: MingtaoGuo   File: plot_confusion_matrix.py    MIT License 6 votes vote down vote up
def plotCM(classes, matrix, savname):
    """classes: a list of class names"""
    # Normalize by row
    matrix = matrix.astype(np.float)
    linesum = matrix.sum(1)
    linesum = np.dot(linesum.reshape(-1, 1), np.ones((1, matrix.shape[1])))
    matrix /= linesum
    # plot
    plt.switch_backend('agg')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    cax = ax.matshow(matrix)
    fig.colorbar(cax)
    ax.xaxis.set_major_locator(MultipleLocator(1))
    ax.yaxis.set_major_locator(MultipleLocator(1))
    for i in range(matrix.shape[0]):
        ax.text(i, i, str('%.2f' % (matrix[i, i] * 100)), va='center', ha='center')
    ax.set_xticklabels([''] + classes, rotation=90)
    ax.set_yticklabels([''] + classes)
    plt.savefig(savname) 
Example 2
Project: LaserTOF   Author: kyleuckert   File: decorators.py    MIT License 6 votes vote down vote up
def switch_backend(backend):
    # Local import to avoid a hard nose dependency and only incur the
    # import time overhead at actual test-time.
    import nose
    def switch_backend_decorator(func):
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                result = func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)
            return result

        return nose.tools.make_decorator(func)(backend_switcher)
    return switch_backend_decorator 
Example 3
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", name=key, obj_type="rcparam", addendum="In the future, "
                "examples will be found relative to the 'datapath' directory.")

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: decorators.py    MIT License 6 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):

        @functools.wraps(func)
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                return func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)

        return backend_switcher

    return switch_backend_decorator 
Example 5
Project: ble5-nrf52-mac   Author: tomasero   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", "{} is deprecated; in the future, examples will be "
                "found relative to the 'datapath' directory.".format(key))

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example 6
Project: ble5-nrf52-mac   Author: tomasero   File: decorators.py    MIT License 6 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):

        @functools.wraps(func)
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                return func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)

        return backend_switcher

    return switch_backend_decorator 
Example 7
Project: neural-network-animation   Author: miloharper   File: test_backend_qt4.py    MIT License 6 votes vote down vote up
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt4Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
Example 8
Project: neural-network-animation   Author: miloharper   File: test_backend_qt4.py    MIT License 6 votes vote down vote up
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt4Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
Example 9
Project: neural-network-animation   Author: miloharper   File: test_backend_qt5.py    MIT License 6 votes vote down vote up
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt5Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
Example 10
Project: neural-network-animation   Author: miloharper   File: test_backend_qt5.py    MIT License 6 votes vote down vote up
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt5Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
Example 11
Project: seam-retrieval   Author: jwehrmann   File: train.py    Apache License 2.0 6 votes vote down vote up
def save_histograms(model, logger_name, curr_iter):
    print 'saving histograms'    
    from matplotlib import pyplot as plt
    plt.switch_backend('agg')

    hist_folder = '/'.join([logger_name, 'histograms'])
    if not os.path.exists(hist_folder):
        os.makedirs(hist_folder)

    filename = '{}/{:07d}.pdf'.format(hist_folder, curr_iter)

    encoder = model.txt_enc
    n_layers = len(encoder.outputs)
    fig, ax = plt.subplots(n_layers, figsize=(10, 4*n_layers))
    for z, (l_name, l_cont) in enumerate(sorted(encoder.outputs.iteritems())):
    #     curr_axis = ax[z%3, z%4]
        curr_axis = ax[z]
        curr_axis.set_title('{}/{}'.format(l_name, l_cont.size()))
        _ = curr_axis.hist(l_cont.data.cpu().numpy().flatten(), bins=100)

    plt.savefig(filename) 
Example 12
Project: GraphicDesignPatternByPython   Author: Relph1119   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", "{} is deprecated; in the future, examples will be "
                "found relative to the 'datapath' directory.".format(key))

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example 13
Project: GraphicDesignPatternByPython   Author: Relph1119   File: decorators.py    MIT License 6 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):

        @functools.wraps(func)
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                return func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)

        return backend_switcher

    return switch_backend_decorator 
Example 14
Project: python3_ios   Author: holzschu   File: __init__.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", "{} is deprecated; in the future, examples will be "
                "found relative to the 'datapath' directory.".format(key))

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example 15
Project: gnn-model-explainer   Author: RexYing   File: io_utils.py    Apache License 2.0 6 votes vote down vote up
def log_matrix(writer, mat, name, epoch, fig_size=(8, 6), dpi=200):
    """Save an image of a matrix to disk.

    Args:
        - writer    :  A file writer.
        - mat       :  The matrix to write.
        - name      :  Name of the file to save.
        - epoch     :  Epoch number.
        - fig_size  :  Size to of the figure to save.
        - dpi       :  Resolution.
    """
    plt.switch_backend("agg")
    fig = plt.figure(figsize=fig_size, dpi=dpi)
    mat = mat.cpu().detach().numpy()
    if mat.ndim == 1:
        mat = mat[:, np.newaxis]
    plt.imshow(mat, cmap=plt.get_cmap("BuPu"))
    cbar = plt.colorbar()
    cbar.solids.set_edgecolor("face")

    plt.tight_layout()
    fig.canvas.draw()
    writer.add_image(name, tensorboardX.utils.figure_to_image(fig), epoch) 
Example 16
Project: gnn-model-explainer   Author: RexYing   File: io_utils.py    Apache License 2.0 6 votes vote down vote up
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend("agg")
    fig = plt.figure(figsize=(8, 6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i + 1)
        plt.imshow(
            assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap("BuPu")
        )
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep="")
    data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    writer.add_image("assignment", data, epoch)

# TODO: unify log_graph and log_graph2 
Example 17
Project: frbpoppy   Author: davidgardenier   File: convenience.py    MIT License 6 votes vote down vote up
def plot_aa_style(cols=1):
    """Use a plotting style specifically for Astronomy & Astrophyiscs."""
    # Use a style file
    dir = os.path.abspath(os.path.dirname(__file__))
    style_file = os.path.join(dir, './aa.mplstyle')
    plt.style.use(style_file)

    # Check whether interactive backend is present
    if os.name == 'posix' and "DISPLAY" not in os.environ:
        # On a cluster
        plt.switch_backend('Agg')
        # Use just the basic latex package allowing \text to be used
        plt.rcParams['text.latex.preamble'] = r'\usepackage{amsmath}'

    if cols == 2:
        plt.rcParams["figure.figsize"] = (5.75373, 3.556) 
Example 18
Project: linear_neuron   Author: uglyboxer   File: test_backend_qt4.py    MIT License 6 votes vote down vote up
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt4Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
Example 19
Project: linear_neuron   Author: uglyboxer   File: test_backend_qt4.py    MIT License 6 votes vote down vote up
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt4Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
Example 20
Project: linear_neuron   Author: uglyboxer   File: test_backend_qt5.py    MIT License 6 votes vote down vote up
def test_fig_close():
    # force switch to the Qt4 backend
    plt.switch_backend('Qt5Agg')

    #save the state of Gcf.figs
    init_figs = copy.copy(Gcf.figs)

    # make a figure using pyplot interface
    fig = plt.figure()

    # simulate user clicking the close button by reaching in
    # and calling close on the underlying Qt object
    fig.canvas.manager.window.close()

    # assert that we have removed the reference to the FigureManager
    # that got added by plt.figure()
    assert(init_figs == Gcf.figs) 
Example 21
Project: linear_neuron   Author: uglyboxer   File: test_backend_qt5.py    MIT License 6 votes vote down vote up
def assert_correct_key(qt_key, qt_mods, answer):
    """
    Make a figure
    Send a key_press_event event (using non-public, qt4 backend specific api)
    Catch the event
    Assert sent and caught keys are the same
    """
    plt.switch_backend('Qt5Agg')
    qt_canvas = plt.figure().canvas

    event = mock.Mock()
    event.isAutoRepeat.return_value = False
    event.key.return_value = qt_key
    event.modifiers.return_value = qt_mods

    def receive(event):
        assert event.key == answer

    qt_canvas.mpl_connect('key_press_event', receive)
    qt_canvas.keyPressEvent(event) 
Example 22
Project: psychrometric-chart-makeover   Author: buds-lab   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, key):
        if key in _deprecated_map:
            version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return inverse_alt(dict.__getitem__(self, alt_key))

        elif key in _deprecated_ignore_map:
            version, alt_key = _deprecated_ignore_map[key]
            cbook.warn_deprecated(
                version, name=key, obj_type="rcparam", alternative=alt_key)
            return dict.__getitem__(self, alt_key) if alt_key else None

        elif key == 'examples.directory':
            cbook.warn_deprecated(
                "3.0", name=key, obj_type="rcparam", addendum="In the future, "
                "examples will be found relative to the 'datapath' directory.")

        elif key == "backend":
            val = dict.__getitem__(self, key)
            if val is rcsetup._auto_backend_sentinel:
                from matplotlib import pyplot as plt
                plt.switch_backend(rcsetup._auto_backend_sentinel)

        return dict.__getitem__(self, key) 
Example 23
Project: psychrometric-chart-makeover   Author: buds-lab   File: decorators.py    MIT License 6 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):

        @functools.wraps(func)
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                matplotlib.testing.setup()
                plt.switch_backend(backend)
                return func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)

        return backend_switcher

    return switch_backend_decorator 
Example 24
Project: Cirq   Author: quantumlib   File: visualize_test.py    Apache License 2.0 6 votes vote down vote up
def test_plot_state_histogram():
    pl.switch_backend('PDF')
    simulator = cirq.Simulator()

    q0 = GridQubit(0, 0)
    q1 = GridQubit(1, 0)
    circuit = cirq.Circuit()
    circuit.append([cirq.X(q0), cirq.X(q1)])
    circuit.append([cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')])
    result = simulator.run(program=circuit,
                           repetitions=5)

    values_plotted = visualize.plot_state_histogram(result)
    expected_values = [0., 0., 0., 5.]

    np.testing.assert_equal(values_plotted, expected_values) 
Example 25
Project: diffpool   Author: RexYing   File: train.py    MIT License 6 votes vote down vote up
def log_assignment(assign_tensor, writer, epoch, batch_idx):
    plt.switch_backend('agg')
    fig = plt.figure(figsize=(8,6), dpi=300)

    # has to be smaller than args.batch_size
    for i in range(len(batch_idx)):
        plt.subplot(2, 2, i+1)
        plt.imshow(assign_tensor.cpu().data.numpy()[batch_idx[i]], cmap=plt.get_cmap('BuPu'))
        cbar = plt.colorbar()
        cbar.solids.set_edgecolor("face")
    plt.tight_layout()
    fig.canvas.draw()

    #data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    #data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
    data = tensorboardX.utils.figure_to_image(fig)
    writer.add_image('assignment', data, epoch) 
Example 26
Project: crappy   Author: LaboratoireMecaniqueLille   File: drawing.py    GNU General Public License v2.0 5 votes vote down vote up
def prepare(self):
    plt.switch_backend(self.backend)
    self.fig, self.ax = plt.subplots(figsize=self.window_size)
    image = self.ax.imshow(plt.imread(self.image), cmap=cm.coolwarm)
    image.set_clim(-0.5, 1)
    cbar = self.fig.colorbar(image, ticks=[-0.5, 1], fraction=0.061,
        orientation='horizontal', pad=0.04)
    cbar.set_label('Temperatures(C)')
    cbar.ax.set_xticklabels(self.crange)
    self.ax.set_title(self.title)
    self.ax.set_axis_off()

    self.elements = []
    for d in self.draw:
      self.elements.append(elements[d['type']](self,**d)) 
Example 27
Project: crappy   Author: LaboratoireMecaniqueLille   File: grapher.py    GNU General Public License v2.0 5 votes vote down vote up
def prepare(self):
    if self.backend:
      plt.switch_backend(self.backend)
    self.f = plt.figure(figsize=self.window_size)
    self.ax = self.f.add_subplot(111)
    self.lines = []
    for _ in self.labels:
      self.lines.append(self.ax.plot([], [])[0])
    # Keep only 1/factor points on each line
    self.factor = [1 for i in self.labels]
    # Count to drop exactly 1/factor points, no more and no less
    self.counter = [0 for i in self.labels]
    legend = [y for x, y in self.labels]
    plt.legend(legend, bbox_to_anchor=(-0.03, 1.02, 1.06, .102), loc=3,
               ncol=len(legend), mode="expand", borderaxespad=1)
    plt.xlabel(self.labels[0][0])
    plt.ylabel(self.labels[0][1])
    plt.grid()
    self.axclear = plt.axes([.8,.02,.15,.05])
    self.bclear = Button(self.axclear,'Clear')
    self.bclear.on_clicked(self.clear)

    if self.window_pos:
      mng = plt.get_current_fig_manager()
      mng.window.wm_geometry("+%s+%s" % self.window_pos)
    plt.draw()
    plt.pause(.001) 
Example 28
Project: partycrasher   Author: naturalness   File: fake_data_generator.py    GNU General Public License v3.0 5 votes vote down vote up
def test(self):
        nr_observations = sum(self.histogram)
        observed_frequencies = []
        expected_frequencies = []
        frequencies_of = []
        thresh = 10
        for i in range(0, len(self.histogram)):
            observed = self.histogram[i]
            expected = stats.poisson.pmf(i, self.lambda_) * nr_observations
            if (
                (observed >= thresh)
                and (expected >= thresh)):
                observed_frequencies.append(observed)
                expected_frequencies.append(expected)
                frequencies_of.append(i)
        results = stats.chisquare(observed_frequencies,
                                  expected_frequencies)
        print("expected: mean %f variance %f" % (
                      self.expected_mean(),
                      self.expected_variance()))
        print("actual: mean %f variance %f" % (
                      self.mean(),
                      self.variance()))
        print(len(expected_frequencies))
        print(results)
        from matplotlib import pyplot
        import matplotlib
        pyplot.switch_backend('Qt5Agg')
        actual_plot, = pyplot.plot(frequencies_of, observed_frequencies, label='actual')
        expected_plot, = pyplot.plot(frequencies_of, expected_frequencies, 'r', linewidth=1, label='expected')
        matplotlib.interactive(True)
        #pyplot.ylabel("People at Table")
        #pyplot.xlabel("Table Number")
        #pyplot.title("Chinese Restaurant Process Unit Test")
        pyplot.legend()
        pyplot.show(block=True)
        return results 
Example 29
Project: partycrasher   Author: naturalness   File: fake_data_generator.py    GNU General Public License v3.0 5 votes vote down vote up
def test_chinese_restaurant_process(self):
        print(sys.path)
        import os
        os.environ["MPLBACKEND"] = "Qt5Agg"
        from matplotlib import pyplot
        import matplotlib
        from scipy import stats
        alpha = 10
        test_size = 10000
        tests = 100
        data = [0]
        for j in range(0, tests):
            cr = ChineseRestaurant(alpha, Numbers())
            for i in range(0, test_size):
                new_sample = cr.draw()
                if new_sample >= len(data):
                    data.append(0)
                data[new_sample] += 1
            assert cr.heap[1] == test_size
        pyplot.switch_backend('Qt5Agg')
        #data=sorted(data, reverse=True)
        print(len(data))
        actual_plot, = pyplot.plot(range(1,len(data)), data[1:], label='actual avg')
        expected = [0]
        remain = test_size * tests
        # stick breaking process
        for i in range(1, len(data)):
            break_ = stats.beta.mean(1.0, float(alpha)) * remain
            expected.append(break_)
            remain -= break_
        #print est
        expected_plot, = pyplot.plot(range(1,len(data)), expected[1:], 'r', linewidth=1, label='expected')
        matplotlib.interactive(True)
        pyplot.ylabel("People at Table")
        pyplot.xlabel("Table Number")
        pyplot.title("Chinese Restaurant Process Unit Test")
        pyplot.legend()
        pyplot.show(block=True) 
Example 30
Project: visual_foresight   Author: SudeepDasari   File: render_utils.py    MIT License 5 votes vote down vote up
def make_direct_vid(dict, numex, gif_savepath, suf):
    """
    :param dict:  dictionary with video tensors of shape bsize, tlen, r, c, 3
    :param numex:
    :param gif_savepath:
    :param suf:
    :param resize:
    :return:
    """
    new_videolist = []
    shapes = []
    for key in dict:
        images = dict[key]
        print('key', key)
        print('shape', images.shape)

        if len(shapes) > 0:   # check that all the same size
            assert images.shape == shapes[-1], 'shape is different!'
        shapes.append(images.shape)
        assert not isinstance(images, list)

        # if 'gen_distrib' in vid[1]:
        #     plt.switch_backend('TkAgg')
        #     plt.imshow(vid[0][0][0])
        #     plt.show()

        if images[0].shape[-1] == 1 or len(images[0].shape) == 3:
            images = color_code_distrib(images, numex, renormalize=True)
        new_videolist.append((images, key))

    framelist = assemble_gif(new_videolist, convert_from_float=True, num_exp=numex)
    framelist.append(np.zeros_like(framelist[0]))
    # save_video_mp4(gif_savepath +'/prediction_at_t{}')
    npy_to_gif(framelist, gif_savepath +'/direct_{}'.format(suf)) 
Example 31
Project: visual_foresight   Author: SudeepDasari   File: user_interface.py    MIT License 5 votes vote down vote up
def __init__(self, img, basedir, img_namesuffix = '', n_desig=1, only_desig = False,
                 im_shape = None, clicks_per_desig=2):
        plt.switch_backend('qt5agg')
        self.im_shape = im_shape

        self.only_desig = only_desig
        self.n_desig = n_desig
        self.suf = img_namesuffix
        self.basedir = basedir
        self.img = img
        fig = plt.figure()
        self.ax = fig.add_subplot(111)
        self.ax.set_xlim(0, self.im_shape[1])
        self.ax.set_ylim(self.im_shape[0], 0)
        plt.imshow(img)

        self.goal = None
        cid = fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.i_click = 0

        self.desig = np.zeros((n_desig,2))  #idesig, (r,c)
        if clicks_per_desig == 2:
            self.goal = np.zeros((n_desig, 2))  # idesig, (r,c)
        else: self.goal = None

        self.i_click_max = n_desig * clicks_per_desig
        self.clicks_per_desig = clicks_per_desig

        self.i_desig = 0
        self.i_goal = 0
        self.marker_list = ['o',"D","v","^"]

        plt.show() 
Example 32
Project: ble5-nrf52-mac   Author: tomasero   File: conftest.py    MIT License 5 votes vote down vote up
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) 
Example 33
Project: latexipy   Author: masasin   File: _latexipy.py    MIT License 5 votes vote down vote up
def latexify(params=PARAMS, new_backend='pgf'):
    '''
    Set up Matplotlib's RC params for LaTeX plotting.

    Call this function before plotting the first figure.

    Parameters
    ----------
    params : Optional[dict]
        A dictionary containing the RC params that need to be updated. Default
        is ``PARAMS``. The defaults should be okay for most cases, but
        ``PARAMS`` can be updated via ``.update()`` as well.

    new_backend : Optional[str|None]
        The backend to switch too. Default is PGF, which allows a nicer PDF
        output too.

    Raises
    ------
    ValueError
        If the new backend is not supported.

    Example
    -------
    >>> params = PARAMS.copy()
    >>> params.update({'font.family': 'sans-serif'})
    >>> latexify(params)

    '''
    plt.rcParams.update(params)
    if new_backend is not None:
        try:
            plt.switch_backend(new_backend)
        except ValueError:
            logger.error(f'Backend not supported: {new_backend!r}')
            raise 
Example 34
Project: latexipy   Author: masasin   File: _latexipy.py    MIT License 5 votes vote down vote up
def revert():
    '''
    Return to the settings before running ``latexify()`` and updating params.

    '''
    plt.rcParams.update(_ORIGINAL_PARAMS)
    plt.switch_backend(_ORIGINAL_BACKEND) 
Example 35
Project: graph-generation   Author: JiaxuanYou   File: data.py    MIT License 5 votes vote down vote up
def test_graph_load_DD():
    graphs, max_num_nodes = Graph_load_batch(min_num_nodes=10,name='DD',node_attributes=False,graph_labels=True)
    shuffle(graphs)
    plt.switch_backend('agg')
    plt.hist([len(graphs[i]) for i in range(len(graphs))], bins=100)
    plt.savefig('figures/test.png')
    plt.close()
    row = 4
    col = 4
    draw_graph_list(graphs[0:row*col], row=row,col=col, fname='figures/test')
    print('max num nodes',max_num_nodes) 
Example 36
Project: QARC   Author: thu-media   File: gray.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(
        y.shape[1], 1, sharex=True, figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
    # ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:, i])
        ax[i].plot(x, y_pred[:, i])

    savefig('save/' + str(KERNEL) + '_' + str(KERNEL) +
            '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 37
Project: QARC   Author: thu-media   File: vqn-new.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(y.shape[1], 1, sharex=True,figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
        #ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:,i])
        ax[i].plot(x, y_pred[:,i])

    savefig('save/' + str(KERNEL) + '_' + str(DENSE_SIZE) + '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 38
Project: QARC   Author: thu-media   File: vqn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(y.shape[1], 1, sharex=True,figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
        #ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:,i])
        ax[i].plot(x, y_pred[:,i])

    savefig('save/' + str(KERNEL) + '_' + str(DENSE_SIZE) + '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 39
Project: QARC   Author: thu-media   File: cnn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    #y_pred = np.reshape(y_pred, (y_pred.shape[0]))
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(
        y.shape[1], 1, sharex=True, figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
    # ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:, i])
        ax[i].plot(x, y_pred[:, i])

    savefig('save/' + str(KERNEL) + '_' + str(DENSE_SIZE) +
            '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 40
Project: QARC   Author: thu-media   File: vqn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    #y_pred = np.reshape(y_pred, (y_pred.shape[0]))
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(y.shape[1], 1, sharex=True,figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
        #ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:,i])
        ax[i].plot(x, y_pred[:,i])

    savefig('save/' + str(KERNEL) + '_' + str(DENSE_SIZE) + '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 41
Project: QARC   Author: thu-media   File: cnn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    #y_pred = np.reshape(y_pred, (y_pred.shape[0]))
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(
        y.shape[1], 1, sharex=True, figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
    # ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:, i])
        ax[i].plot(x, y_pred[:, i])

    savefig('save/' + str(KERNEL) + '_' + str(DENSE_SIZE) +
            '_' + str(LR_RATE) + '/' + str(j) + '.png') 
Example 42
Project: QARC   Author: thu-media   File: vqn-cnn.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save_plot(y_pred, y, j):
    #y_pred = np.reshape(y_pred, (y_pred.shape[0]))
    plt.switch_backend('agg')
    plt.figure()
    fig, ax = plt.subplots(
        y.shape[1], 1, sharex=True, figsize=(10, 16), dpi=100)
    x = np.linspace(0, y.shape[0] - 1, y.shape[0])
    # ax.set_ylim(0,1)
    for i in range(y.shape[1]):
        ax[i].grid(True)
        ax[i].plot(x, y[:, i])
        ax[i].plot(x, y_pred[:, i])

    savefig('save/' + str(j) + '.png') 
Example 43
Project: neural-network-animation   Author: miloharper   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                mpl.rcdefaults()
                plt.switch_backend(backend)
                result = func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)
            return result

        return nose.tools.make_decorator(func)(backend_switcher)
    return switch_backend_decorator 
Example 44
Project: SSM   Author: yanxp   File: help.py    MIT License 5 votes vote down vote up
def vis_detections(image_name, im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    plt.switch_backend('Agg')
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    im = im[:, :, (2, 1, 0)]
    fig,ax = plt.subplots()
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1], fill=False,
                          edgecolor='red', linewidth=3.5)
            )
        ax.text(bbox[0], bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14, color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                  fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
    # save the image
    fig = plt.gcf()
    import time
    t0 = time.time()
    fig.savefig(str(t0)+'.jpg') 
Example 45
Project: GraphicDesignPatternByPython   Author: Relph1119   File: conftest.py    MIT License 5 votes vote down vote up
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) 
Example 46
Project: GraphRNN   Author: snap-stanford   File: data.py    MIT License 5 votes vote down vote up
def test_graph_load_DD():
    graphs, max_num_nodes = Graph_load_batch(min_num_nodes=10,name='DD',node_attributes=False,graph_labels=True)
    shuffle(graphs)
    plt.switch_backend('agg')
    plt.hist([len(graphs[i]) for i in range(len(graphs))], bins=100)
    plt.savefig('figures/test.png')
    plt.close()
    row = 4
    col = 4
    draw_graph_list(graphs[0:row*col], row=row,col=col, fname='figures/test')
    print('max num nodes',max_num_nodes) 
Example 47
Project: linear_neuron   Author: uglyboxer   File: test_backend_pgf.py    MIT License 5 votes vote down vote up
def switch_backend(backend):

    def switch_backend_decorator(func):
        def backend_switcher(*args, **kwargs):
            try:
                prev_backend = mpl.get_backend()
                mpl.rcdefaults()
                plt.switch_backend(backend)
                result = func(*args, **kwargs)
            finally:
                plt.switch_backend(prev_backend)
            return result

        return nose.tools.make_decorator(func)(backend_switcher)
    return switch_backend_decorator 
Example 48
Project: Cirq   Author: quantumlib   File: run_doctest.py    Apache License 2.0 5 votes vote down vote up
def run_tests(file_paths: Iterable[str],
              include_modules: bool = True,
              include_local: bool = True,
              quiet: bool = True) -> doctest.TestResults:
    """Runs code snippets from docstrings found in each file.

    Args:
        file_paths: The list of files to test.
        include_modules: If True, the snippets can use `cirq` without explicitly
            importing it.  E.g. `>>> cirq.LineQubit(0)`
        include_local: If True, the file under test is imported as a python
            module (only if the file extension is .py) and all globals defined
            in the file may be used by the snippets.
        quiet: Determines if progress output is shown.

    Returns: A tuple with the results: (# tests failed, # tests attempted)
    """

    # Ignore calls to `plt.show()`.
    import matplotlib.pyplot as plt
    plt.switch_backend('pdf')

    tests = load_tests(file_paths,
                       include_modules=include_modules,
                       include_local=include_local,
                       quiet=quiet)
    if not quiet:
        print()
    results, error_messages = exec_tests(tests, quiet=quiet)
    if not quiet:
        print()
    for error in error_messages:
        print(error)
    return results 
Example 49
Project: Cirq   Author: quantumlib   File: examples_test.py    Apache License 2.0 5 votes vote down vote up
def test_example_runs_bristlecone_heatmap():
    plt.switch_backend('agg')
    examples.bristlecone_heatmap_example.main() 
Example 50
Project: Cirq   Author: quantumlib   File: conftest.py    Apache License 2.0 5 votes vote down vote up
def pytest_configure(config):
    # Use matplotlib agg backend which does not require a display.
    plt.switch_backend('agg')