Python matplotlib.pyplot.ion() Examples

The following are 30 code examples of matplotlib.pyplot.ion(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: visualise_att_maps_epoch.py    From Attention-Gated-Networks with MIT License 7 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Epochs 
Example #2
Source File: tiny_gp_plus.py    From tiny_gp with GNU General Public License v3.0 6 votes vote down vote up
def prepare_plots():
    fig, axarr = plt.subplots(2, sharex=True)
    fig.canvas.set_window_title('EVOLUTIONARY PROGRESS')
    fig.subplots_adjust(hspace = 0.5)
    axarr[0].set_title('error', fontsize=14)
    axarr[1].set_title('mean size', fontsize=14)
    plt.xlabel('generation', fontsize=18)
    plt.ion() # interactive mode for plot
    axarr[0].set_xlim(0, GENERATIONS)
    axarr[0].set_ylim(0, 1) # fitness range
    xdata = []
    ydata = [ [], [] ]
    line = [None, None]
    line[0], = axarr[0].plot(xdata, ydata[0], 'b-') # 'b-' = blue line    
    line[1], = axarr[1].plot(xdata, ydata[1], 'r-') # 'r-' = red line
    return axarr, line, xdata, ydata 
Example #3
Source File: interactive_plot.py    From srl-zoo with MIT License 6 votes vote down vote up
def plot3dRepresentation(states, rewards, images_path, name="Learned State Representation",
                         add_colorbar=True, multi_view=False):
    plt.ion()
    fig = plt.figure(name)
    plt.clf()
    ax = fig.add_subplot(111, projection='3d')
    im = ax.scatter(states[:, 0], states[:, 1], states[:, 2],
                    s=7, c=np.clip(rewards, -1, 1), cmap='coolwarm', linewidths=0.1)
    ax.set_xlabel('State dimension 1')
    ax.set_ylabel('State dimension 2')
    ax.set_zlabel('State dimension 3')
    ax.set_title(fill(name, TITLE_MAX_LENGTH))
    fig.tight_layout()
    if add_colorbar:
        fig.colorbar(im, label='Reward')

    if multi_view:
        createInteractivePlot(fig, ax, states, rewards, images_path, view=1)
        createInteractivePlot(plt.figure(name), ax, states, rewards, images_path, view=2)
    else:
        createInteractivePlot(fig, ax, states, rewards, images_path)

    plt.show() 
Example #4
Source File: toy_dataset.py    From firefly-monte-carlo with MIT License 6 votes vote down vote up
def main():
    # Generate synthetic data
    x = 2 * npr.rand(N,D) - 1  # data features, an (N,D) array
    x[:, 0] = 1
    th_true = 10.0 * np.array([0, 1, 1])
    y = np.dot(x, th_true[:, None])[:, 0]
    t = npr.rand(N) > (1 / ( 1 + np.exp(y)))  # data targets, an (N) array of 0s and 1s

    # Obtain joint distributions over z and th
    model = ff.LogisticModel(x, t, th0=th0, y0=y0)

    # Set up step functions
    th = np.random.randn(D) * th0
    z = ff.BrightnessVars(N)
    th_stepper = ff.ThetaStepMH(model.log_p_joint, stepsize)
    z__stepper = ff.zStepMH(model.log_pseudo_lik, q)

    plt.ion()
    ax = plt.figure(figsize=(8, 6)).add_subplot(111)
    while True:
        th = th_stepper.step(th, z)  # Markov transition step for theta
        z  = z__stepper.step(th ,z)  # Markov transition step for z
        update_fig(ax, x, y, z, th, t)
        plt.draw()
        plt.pause(0.05) 
Example #5
Source File: callbacks.py    From keras-utilities with MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        sns.set_style("whitegrid")
        sns.set_style("whitegrid", {"grid.linewidth": 0.5,
                                    "lines.linewidth": 0.5,
                                    "axes.linewidth": 0.5})
        flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e",
                  "#2ecc71"]
        sns.set_palette(sns.color_palette(flatui))
        # flatui = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"]
        # sns.set_palette(sns.color_palette("Set2", 10))

        plt.ion()  # set plot to animated
        width = self.width * (1 + len(self.get_metrics(logs)))
        height = self.height
        self.fig = plt.figure(figsize=(width, height))

        # move it to the upper left corner
        move_figure(self.fig, 25, 25) 
Example #6
Source File: callbacks.py    From keras-utilities with MIT License 6 votes vote down vote up
def on_train_begin(self, logs={}):
        for layer in self.get_trainable_layers():
            for param in self.parameters:
                if any(w for w in layer.weights if param in w.name.split("_")):
                    name = layer.name + "_" + param
                    self.layers_stats[name]["values"] = numpy.asarray(
                        []).ravel()
                    for s in self.stats:
                        self.layers_stats[name][s] = []

        # plt.style.use('ggplot')
        plt.ion()  # set plot to animated
        width = 3 * (1 + len(self.stats))
        height = 2 * len(self.layers_stats)
        self.fig = plt.figure(figsize=(width, height))
        # sns.set_style("whitegrid")
        self.draw_plot() 
Example #7
Source File: interactive_plot.py    From srl-zoo with MIT License 6 votes vote down vote up
def plot2dRepresentation(states, rewards, images_path, name="Learned State Representation",
                         add_colorbar=True):
    plt.ion()
    fig = plt.figure(name)
    plt.clf()
    ax = fig.add_subplot(111)
    im = ax.scatter(states[:, 0], states[:, 1], s=7, c=np.clip(rewards, -1, 1), cmap='coolwarm', linewidths=0.1)
    ax.set_xlabel('State dimension 1')
    ax.set_ylabel('State dimension 2')
    ax.set_title(fill(name, TITLE_MAX_LENGTH))
    fig.tight_layout()
    if add_colorbar:
        fig.colorbar(im, label='Reward')

    createInteractivePlot(fig, ax, states, rewards, images_path)
    plt.show() 
Example #8
Source File: naive-policy-gradient.py    From Deep-reinforcement-learning-with-pytorch with MIT License 6 votes vote down vote up
def plot_durations(episode_durations):
    plt.ion()
    plt.figure(2)
    plt.clf()
    duration_t = torch.FloatTensor(episode_durations)
    plt.title('Training')
    plt.xlabel('Episodes')
    plt.ylabel('Duration')
    plt.plot(duration_t.numpy())

    if len(duration_t) >= 100:
        means = duration_t.unfold(0,100,1).mean(1).view(-1)
        means = torch.cat((torch.zeros(99), means))
        plt.plot(means.numpy())

    plt.pause(0.00001) 
Example #9
Source File: pylive.py    From pylive with GNU General Public License v3.0 6 votes vote down vote up
def live_plotter(x_vec,y1_data,line1,identifier='',pause_time=0.1):
    if line1==[]:
        # this is the call to matplotlib that allows dynamic plotting
        plt.ion()
        fig = plt.figure(figsize=(13,6))
        ax = fig.add_subplot(111)
        # create a variable for the line so we can later update it
        line1, = ax.plot(x_vec,y1_data,'-o',alpha=0.8)        
        #update plot label/title
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()
    
    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)
    
    # return line so we can update it again in the next iteration
    return line1

# the function below is for updating both x and y values (great for updating dates on the x-axis) 
Example #10
Source File: pylive.py    From pylive with GNU General Public License v3.0 6 votes vote down vote up
def live_plotter_xy(x_vec,y1_data,line1,identifier='',pause_time=0.01):
    if line1==[]:
        plt.ion()
        fig = plt.figure(figsize=(13,6))
        ax = fig.add_subplot(111)
        line1, = ax.plot(x_vec,y1_data,'r-o',alpha=0.8)
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()
        
    line1.set_data(x_vec,y1_data)
    plt.xlim(np.min(x_vec),np.max(x_vec))
    if np.min(y1_data)<=line1.axes.get_ylim()[0] or np.max(y1_data)>=line1.axes.get_ylim()[1]:
        plt.ylim([np.min(y1_data)-np.std(y1_data),np.max(y1_data)+np.std(y1_data)])

    plt.pause(pause_time)
    
    return line1 
Example #11
Source File: clean.py    From eht-imaging with GNU General Public License v3.0 6 votes vote down vote up
def plot_i(Image, nit, chi2, fig=1, cmap='afmhot'):
    """Plot the total intensity image at each iteration
    """

    plt.ion()
    plt.figure(fig)
    plt.pause(0.00001)
    plt.clf()

    plt.imshow(Image.imvec.reshape(Image.ydim,Image.xdim), cmap=plt.get_cmap(cmap), interpolation='gaussian')
    xticks = ticks(Image.xdim, Image.psize/RADPERAS/1e-6)
    yticks = ticks(Image.ydim, Image.psize/RADPERAS/1e-6)
    plt.xticks(xticks[0], xticks[1])
    plt.yticks(yticks[0], yticks[1])
    plt.xlabel('Relative RA ($\mu$as)')
    plt.ylabel('Relative Dec ($\mu$as)')
    plt.title("step: %i  $\chi^2$: %f " % (nit, chi2), fontsize=20) 
Example #12
Source File: standard_sgd_demo.py    From pyhawkes with MIT License 6 votes vote down vote up
def sample_from_network_hawkes(C, K, T, dt, B):
    # Create a true model
    p = 0.8 * np.eye(C)
    v = 10.0 * np.eye(C) + 20.0 * (1-np.eye(C))
    c = (0.0 * (np.arange(K) < 10) + 1.0 * (np.arange(K)  >= 10)).astype(np.int)
    true_model = DiscreteTimeNetworkHawkesModelSpikeAndSlab(C=C, K=K, dt=dt, B=B, c=c, p=p, v=v)

    # Plot the true network
    plt.ion()
    plot_network(true_model.weight_model.A,
                 true_model.weight_model.W,
                 vmax=0.5)

    # Sample from the true model
    S,R = true_model.generate(T=T)

    # Return the spike count matrix
    return S, R, true_model 
Example #13
Source File: visualise_attention.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def plotNNFilterOverlay(input_im, units, figure_id, interp='bilinear',
                        colormap=cm.jet, colormap_lim=None, title='', alpha=0.8):
    plt.ion()
    filters = units.shape[2]
    fig = plt.figure(figure_id, figsize=(5,5))
    fig.clf()

    for i in range(filters):
        plt.imshow(input_im[:,:,0], interpolation=interp, cmap='gray')
        plt.imshow(units[:,:,i], interpolation=interp, cmap=colormap, alpha=alpha)
        plt.axis('off')
        plt.colorbar()
        plt.title(title, fontsize='small')
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

    # plt.savefig('{}/{}.png'.format(dir_name,time.time()))




## Load options 
Example #14
Source File: visualise_attention.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None, title=''):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()
    plt.suptitle(title) 
Example #15
Source File: visualise_fmaps.py    From Attention-Gated-Networks with MIT License 6 votes vote down vote up
def plotNNFilter(units, figure_id, interp='bilinear', colormap=cm.jet, colormap_lim=None):
    plt.ion()
    filters = units.shape[2]
    n_columns = round(math.sqrt(filters))
    n_rows = math.ceil(filters / n_columns) + 1
    fig = plt.figure(figure_id, figsize=(n_rows*3,n_columns*3))
    fig.clf()

    for i in range(filters):
        ax1 = plt.subplot(n_rows, n_columns, i+1)
        plt.imshow(units[:,:,i].T, interpolation=interp, cmap=colormap)
        plt.axis('on')
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        plt.colorbar()
        if colormap_lim:
            plt.clim(colormap_lim[0],colormap_lim[1])

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.tight_layout()

# Load options 
Example #16
Source File: test_utils.py    From viznet with MIT License 6 votes vote down vote up
def test_shapes():
    kwargs = {'ls':'--', 'lw':0.5, 'zorder':1, 'facecolor':'r', 'edgecolor': 'g'}
    plt.ion()
    ax = plt.subplot(111)
    shape_list = ['circle', 'golden', 'triangle', 'diamond', 'empty', 'dot', 'cross', 'measure', 'plus']
    for i, shape in enumerate(shape_list):
        func = eval('shapes.%s'%shape)
        for j in range(5):
            size_, angle_, roundness_, kwargs_ = 0.3, 0, 0, dict(kwargs)
            if j==1:
                size_ = 0.15
            if j==2:
                angle_ = np.pi/4.
            if j==3:
                angle_ = np.pi/4.
                roundness_ = 0.05
            if j==4:
                kwargs_['facecolor']='k'
            patches = func((i,-j), size_, angle_, roundness_, **kwargs_)
            for patch in patches:
                ax.add_patch(patch)
    plt.axis('equal')
    plt.axis('off')
    pdb.set_trace() 
Example #17
Source File: pyplot.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def draw():
    """Redraw the current figure.

    This is used to update a figure that has been altered, but not
    automatically re-drawn.  If interactive mode is on (:func:`.ion()`), this
    should be only rarely needed, but there may be ways to modify the state of
    a figure without marking it as `stale`.  Please report these cases as
    bugs.

    A more object-oriented alternative, given any
    :class:`~matplotlib.figure.Figure` instance, :attr:`fig`, that
    was created using a :mod:`~matplotlib.pyplot` function, is::

        fig.canvas.draw_idle()
    """
    get_current_fig_manager().canvas.draw_idle() 
Example #18
Source File: utils.py    From VNect with Apache License 2.0 6 votes vote down vote up
def draw_limbs_3d(joints_3d, joint_parents):
    fig = plt.figure()
    ax_3d = plt.axes(projection='3d')
    ax_3d.clear()
    ax_3d.view_init(-90, -90)
    ax_3d.set_xlim(-500, 500)
    ax_3d.set_ylim(-500, 500)
    ax_3d.set_zlim(-500, 500)
    ax_3d.set_xticks([])
    ax_3d.set_yticks([])
    ax_3d.set_zticks([])
    white = (1.0, 1.0, 1.0, 0.0)
    ax_3d.w_xaxis.set_pane_color(white)
    ax_3d.w_yaxis.set_pane_color(white)
    ax_3d.w_xaxis.line.set_color(white)
    ax_3d.w_yaxis.line.set_color(white)
    ax_3d.w_zaxis.line.set_color(white)
    for i in range(joints_3d.shape[0]):
        x_pair = [joints_3d[i, 0], joints_3d[joint_parents[i], 0]]
        y_pair = [joints_3d[i, 1], joints_3d[joint_parents[i], 1]]
        z_pair = [joints_3d[i, 2], joints_3d[joint_parents[i], 2]]
        ax_3d.plot(x_pair, y_pair, zs=z_pair, linewidth=3)
    plt.ion()
    plt.show() 
Example #19
Source File: celery_tasks.py    From Firmware_Slap with GNU General Public License v3.0 5 votes vote down vote up
def display_scores_list(done_list, per_row=2, plot_it=True):

    import subprocess
    subprocess.call(["clear"])

    print(
        colored("[+] Current cluster scores (Cluster Count, Cluster Score)",
                'white',
                attrs=['bold']))

    temp_list = sorted(done_list, key=lambda k: k['score'])

    iter_count = len(temp_list) / per_row

    format_item = " {:<3} : {:<6} |"

    item_iter = 0
    for item in temp_list:
        temp_string = format_item.format(item['count'], str(item['score'])[:6])
        print(temp_string, end=" ")
        if item_iter % per_row == 0:
            print()
        item_iter += 1
    print()

    if plot_it:
        plot_list = sorted(done_list, key=lambda k: k['count'])

        plt.ion()
        plt.show()
        plt.title("Function similarity by cluster count and Silhoette score")
        plt.xlabel("Cluster Centroid Count")
        plt.ylabel("Silhoette Score")
        plt.grid = True

        plt.plot([x['count'] for x in plot_list],
                 [x['score'] for x in plot_list])
        plt.draw()
        plt.pause(0.05)
        plt.clf() 
Example #20
Source File: motor_dashboard.py    From gym-electric-motor with MIT License 5 votes vote down vote up
def __init__(self, update_period=5e-2, visu_period=5, plotted_variables='all', **_):
        """
              Constructor of the dashboard.

              Args:
                  plotted_variables: Names of the variables that shall be shown on the dashboard
                        | Shortcut: ['all']/['none'] for all/no visualized variables
                  update_period: Number of seconds after that dashboard will be updated
                                | Updating with tiny periods lead to very low speed.
                  visu_period: Time period shown on the dashboard
        """

        self._update_period = update_period
        self._visu_period = visu_period
        self._plotted_variables = plotted_variables
        self._physical_system = None
        self._figure = None
        plt.ion()
        self._tau = None
        self._update_cycle = None
        self._episode_length = np.Inf

        self.dash_vars = None
        self._referenced_states = None
        self._limits = None
        self._nominal_state = None
        self._observation_space = None
        self._labels = None
        self._plotted_state_index = []
        self._k = 0
        self.initialized = False

        # If available use the Qt5 Backend and the update function to update the plot (faster)
        try:
            matplotlib.use('Qt5Agg')
        # Otherwise stick to the default backend and use the draw function (slower)
        except ImportError:
            warnings.warn('Cannot use Qt5Agg matplotlib backend. Plotting will be slower.') 
Example #21
Source File: visualization.py    From NTM-Keras with MIT License 5 votes vote down vote up
def __init__(self, matrix_list, name_list):
        """
        Initialize the value of matrix.
        :param matrix_list: a goup of matrix.
        :return: non.
        """
        self.matrix_list = matrix_list
        # set figure size
        self.fig = plt.figure(figsize=(7, 5))

        plt.ion()
        self.update(matrix_list, name_list) 
Example #22
Source File: utilities.py    From HARK with Apache License 2.0 5 votes vote down vote up
def make_figs(figure_name, saveFigs, drawFigs, target_dir="Figures"):
    """ Utility function to save figure in multiple formats and display the image.

    Parameters
    ----------
    figure_name: str
                name of the figure
    saveFigs: bool
              True if the figure needs to be written to disk else False
    drawFigs: bool
              True if the figure should be displayed using plt.draw()
    target_dir: str, default = 'Figures/'
              Name of folder to save figures to in the current directory
            
    """
    import matplotlib.pyplot as plt
    if saveFigs:
        import os
        # Where to put any figures that the user wants to save
        my_file_path = os.getcwd() # Find pathname to this file:
        Figures_dir = os.path.join(my_file_path, "{}".format(figure_name)) # LaTeX document assumes figures will be here
        if not os.path.exists(Figures_dir): 
            os.makedirs(Figures_dir)         # If dir does not exist, create it
        # Save the figures in several formats
        print("Saving figure {} in {}".format(figure_name, target_dir))
        plt.savefig(os.path.join(target_dir, '{}.jpg'.format(figure_name))) # For web/html
        plt.savefig(os.path.join(target_dir, '{}.png'.format(figure_name))) # For web/html
        plt.savefig(os.path.join(target_dir, '{}.pdf'.format(figure_name))) # For LaTeX
        plt.savefig(os.path.join(target_dir, '{}.svg'.format(figure_name))) # For html5
    # Make sure it's possible to plot it by checking for GUI
    if drawFigs and find_gui():
        plt.ion()  # Counterintuitively, you want interactive mode on if you don't want to interact
        plt.draw() # Change to false if you want to pause after the figure
        plt.pause(2) 
Example #23
Source File: main.py    From u_net_liver with MIT License 5 votes vote down vote up
def test(args):
    model = Unet(3, 1)
    model.load_state_dict(torch.load(args.ckpt,map_location='cpu'))
    liver_dataset = LiverDataset("data/val", transform=x_transforms,target_transform=y_transforms)
    dataloaders = DataLoader(liver_dataset, batch_size=1)
    model.eval()
    import matplotlib.pyplot as plt
    plt.ion()
    with torch.no_grad():
        for x, _ in dataloaders:
            y=model(x).sigmoid()
            img_y=torch.squeeze(y).numpy()
            plt.imshow(img_y)
            plt.pause(0.01)
        plt.show() 
Example #24
Source File: connection_strategy_simulator.py    From pydevp2p with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def draw(G, metrics=dict()):
    import matplotlib.pyplot as plt
    """
    dot - "hierarchical" or layered drawings of directed graphs. This is the default tool to use if edges have directionality.

    neato - "spring model'' layouts. This is the default tool to use if the graph is not too large (about 100 nodes) and you don't know anything else about it. Neato attempts to minimize a global energy function, which is equivalent to statistical multi-dimensional scaling.

    fdp - "spring model'' layouts similar to those of neato, but does this by reducing forces rather than working with energy.

    sfdp - multiscale version of fdp for the layout of large graphs.

    twopi - radial layouts, after Graham Wills 97. Nodes are placed on concentric circles depending their distance from a given root node.

    circo - circular layout, after Six and Tollis 99, Kauffman and Wiese 02. This is suitable for certain diagrams of multiple cyclic structures, such as certain telecommunications networks.

    """
    print 'layouting'

    text = ''
    for k, v in metrics.items():
        text += '%s: %.4f\n' % (k.ljust(max(len(x) for x in metrics.keys())), v)

    print text
    #pos = nx.graphviz_layout(G, prog='dot', args='')
    pos = nx.spring_layout(G)
    plt.figure(figsize=(8, 8))
    nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
    plt.text(0.02, 0.02, text, transform=plt.gca().transAxes)  # , font_family='monospace')
    plt.axis('equal')
    outfile = 'network_graph.png'
    plt.savefig(outfile)
    print 'saved visualization to', outfile
    plt.ion()
    plt.show()
    while True:
        time.sleep(0.1) 
Example #25
Source File: conf.py    From gym-electric-motor with MIT License 5 votes vote down vote up
def turn_off_windows(monkeypatch):
    """
    This preparation function is run before each test. Due to this, no rendering is performed.
    :param monkeypatch:
    :return:
    """
    monkeypatch.setattr(plt, "ion", monkey_ion_function)
    monkeypatch.setattr(plt, "pause", monkey_pause_function)
    monkeypatch.setattr(QWidget, "showMaximized", monkey_show_maximized_function)
    monkeypatch.setattr(matplotlib.figure.Figure, "show", monkey_show_function)


# endregion

# region system equations for testing 
Example #26
Source File: conf.py    From gym-electric-motor with MIT License 5 votes vote down vote up
def monkey_ion_function():
    """
    function used for plt.ion()
    :return:
    """
    pass 
Example #27
Source File: standard_bfgs_demo.py    From pyhawkes with MIT License 5 votes vote down vote up
def sample_from_network_hawkes(K, T, dt, dt_max, B):
    # Create a true model
    true_model = DiscreteTimeNetworkHawkesModelSpikeAndSlab(K=K, dt=dt, dt_max=dt_max, B=B,
                                                            network_hypers=dict(p=0.1))

    # Plot the true network
    plt.ion()
    true_model.plot_network()

    # Sample from the true model
    S,R = true_model.generate(T=T)

    # Return the spike count matrix
    return S, true_model 
Example #28
Source File: predictor_theano.py    From visual_dynamics with MIT License 5 votes vote down vote up
def draw(self):
        net_graph_fname = os.path.join(self.get_model_dir(), 'net_graph.png')
        with open(net_graph_fname, 'rb') as net_graph_file:
            image = plt.imread(net_graph_file)
        plt.ion()
        fig = plt.figure(num=self._draw_fig_num, figsize=(10.*image.shape[1]/image.shape[0], 10.), tight_layout=True)
        self._draw_fig_num = fig.number
        plt.axis('off')
        fig.canvas.set_window_title('Net graph for %s' % self.name)
        plt.imshow(image)
        plt.draw() 
Example #29
Source File: distribution_check.py    From hydrology with GNU General Public License v3.0 5 votes vote down vote up
def plotDensities(best):
    import matplotlib.pyplot as plt
    import numpy as np

    plt.ion()
    plt.clf()
    # plot fitted probability
    for i in range(len(best)-1, -1, -1):
        fct, values = best[i]
        plt.hist(values["p"], normed=True, bins=max(10, len(values["p"])/10), label=str(i+1)+". "+fct, alpha=0.5)
    plt.legend(loc='best', frameon=False)
    plt.title("Top Results")
    plt.show()
    plt.draw() 
Example #30
Source File: gui.py    From fenics-topopt with MIT License 5 votes vote down vote up
def __init__(self, nelx, nely, title=""):
        """Initialize plot and plot the initial design"""
        plt.ion()  # Ensure that redrawing is possible
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(-np.zeros((nelx, nely)).T, cmap='gray',
            interpolation='none', norm=colors.Normalize(vmin=-1, vmax=0))
        plt.xlabel(title)
        # self.fig.tight_layout()
        self.fig.show()
        self.nelx, self.nely = nelx, nely