Python matplotlib.pyplot.pause() Examples

The following are code examples for showing how to use matplotlib.pyplot.pause(). 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: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 7 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example 2
Project: fenics-topopt   Author: zfergus   File: stress_gui.py    MIT License 6 votes vote down vote up
def update(self, xPhys, u, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        stress = self.stress_calculator.calculate_stress(xPhys, u, self.nu)
        # self.stress_calculator.calculate_fdiff_stress(xPhys, u, self.nu)
        self.myColorMap.set_norm(colors.Normalize(vmin=0, vmax=max(stress)))
        stress_rgba = self.myColorMap.to_rgba(stress)
        stress_rgba[:, :, 3] = xPhys.reshape(-1, 1)
        self.stress_im.set_array(np.swapaxes(
            stress_rgba.reshape((self.nelx, self.nely, 4)), 0, 1))
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        else:
            plt.xlabel("Max stress = {:.2f}".format(max(stress)[0]))
        plt.pause(0.01) 
Example 3
Project: FCOS_GluonCV   Author: DetectionTeamUCAS   File: cam_demo.py    Apache License 2.0 6 votes vote down vote up
def keypoint_detection(img, detector, pose_net, ctx=mx.cpu(), axes=None):
    x, img = gcv.data.transforms.presets.yolo.transform_test(img, short=512, max_size=350)
    x = x.as_in_context(ctx)
    class_IDs, scores, bounding_boxs = detector(x)

    plt.cla()
    pose_input, upscale_bbox = detector_to_simple_pose(img, class_IDs, scores, bounding_boxs,
                                                       output_shape=(128, 96), ctx=ctx)
    if len(upscale_bbox) > 0:
        predicted_heatmap = pose_net(pose_input)
        pred_coords, confidence = heatmap_to_coord(predicted_heatmap, upscale_bbox)

        axes = plot_keypoints(img, pred_coords, confidence, class_IDs, bounding_boxs, scores,
                              box_thresh=0.5, keypoint_thresh=0.2, ax=axes)
        plt.draw()
        plt.pause(0.001)
    else:
        axes = plot_image(frame, ax=axes)
        plt.draw()
        plt.pause(0.001)

    return axes 
Example 4
Project: StyleGAN   Author: mgmk2   File: image_utils.py    Apache License 2.0 6 votes vote down vote up
def show_images(images, epoch=None, mode='show'):
    if mode not in ['show', 'pause']:
        raise ValueError('Unknown mode to show images: ' + mode)

    if images.shape[-1] == 1:
        x = images[:, :, :, 0]
        cmap = 'gray'
    else:
        x = images
        cmap = None
    fig = plt.figure(figsize=(4, 4))
    for i in range(16):
        plt.subplot(4, 4, i + 1)
        plt.imshow(x[i].clip(0, 1), cmap=cmap)
        plt.axis('off')
    if epoch is not None:
        fig.suptitle('epoch: {:}'.format(epoch))

    if mode == 'pause':
        plt.pause(.05)
    else:
        plt.show() 
Example 5
Project: shenfun   Author: spectralDNS   File: RayleighBenardRK3.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def plot(self, t, tstep):
        if tstep % self.modplot == 0:
            ub = self.u_.backward(self.ub)
            e0 = dx(ub[0]*ub[0])
            e1 = dx(ub[1]*ub[1])
            T_b = self.T_.backward(self.T_b)
            e2 = inner(1, T_b*T_b)
            div_u = project(div(self.u_), self.TD).backward()
            e3 = dx(div_u*div_u)
            if comm.Get_rank() == 0:
                print("Time %2.5f Energy %2.6e %2.6e %2.6e div %2.6e" %(t, e0, e1, e2, e3))

                plt.figure(1)
                self.im1.set_UVC(ub[1], ub[0])
                self.im1.scale = np.linalg.norm(ub[1])
                plt.pause(1e-6)
                plt.figure(2)
                self.im2.ax.clear()
                self.im2.ax.contourf(self.X[1], self.X[0], T_b, 100)
                self.im2.autoscale()
                plt.pause(1e-6) 
Example 6
Project: pymoku   Author: liquidinstruments   File: automation_demo.py    MIT License 6 votes vote down vote up
def phase1_plot_update(f, ax1, ax2, data, passed, results, fails,
                       failure_criteria, progress):
    ax1.cla()
    ax2.cla()
    sns.tsplot(data.ch1, time=data.time, color="g" if passed else "r",
               ax=ax1, interpolate=True)
    if len(results) > 1:
        try:
            sns.distplot(results, norm_hist=False, rug=True, ax=ax2)
        except Exception:
            pass
    ax1.set(title='Transition Waveform', xlabel='Time (sec)',
            ylabel='Amplitude (V)')
    ax2.set(title="Risetime Histogram", ylabel="Density",
            xlabel="Risetime (sec)")
    ax2.annotate('Outside Spec: %d / %d\n'
                 'Completed %d%%' % (len(fails), len(results), progress),
                 xy=(0.75, 0.90), xycoords='axes fraction', fontsize=14)
    xlims = ax2.get_xlim()
    ax2.axvspan(failure_criteria, xlims[1] - 0.001 * (xlims[1] - xlims[0]),
                alpha=0.1, color='red')
    plt.pause(0.01) 
Example 7
Project: pymoku   Author: liquidinstruments   File: automation_demo.py    MIT License 6 votes vote down vote up
def phase2_plot_update(f, ax1, data, passed, peak, hf1, hf2, progress):
    # Update the plot with latest measurement
    ax1.cla()
    freq_mhz = map(lambda x: x / 1e6, data.frequency)
    sns.tsplot(data.ch1, time=freq_mhz, ax=ax1, interpolate=True)
    ax1.plot(peak[0] / 1e6, peak[1], 'v')
    ax1.set(title='Beatnote Spectrum', xlabel='Frequency (MHz)',
            ylabel='Power (dBm)')
    ax1.annotate('Peak (%.2f MHz)\n'
                 'Linewidth (%.2f kHz)\n'
                 'Completed %d%%'
                 '' % (peak[0] / 1e6, (hf2[0] - hf1[0]) / 1e3, progress),
                 xy=(0.80, 0.90), xycoords='axes fraction', fontsize=14)
    ax1.axvspan(hf1[0] / 1e6, hf2[0] / 1e6,
                alpha=0.1, color='green' if passed else 'red')
    plt.pause(0.01) 
Example 8
Project: smp_graphs   Author: x75   File: graph.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nxgraph_plot2(G):
    import matplotlib.pyplot as plt
    G_ = G
    # nxgraph_plot(G_)
    fig = plt.figure()
    ax = fig.add_subplot(111)
    layout_type = 'linear_hierarchical' # shell, pygraphviz, random
    pos = nxgraph_get_layout(G_, layout_type)

    nxgraph_plot(G = G_, pos = pos, ax = ax, node_size = 300)
    # print "pos", pos
    # labels = {node[0]: '%s\n%s' % (node[1]['block_'].id, node[1]['block_'].cname[:-6]) for node in G_.nodes(data = True)}
    # nx.draw_networkx_nodes(G_, pos = pos, ax = ax)
    # nx.draw_networkx_labels(G_, ax = ax, pos = pos, labels = labels, font_color = 'k', font_size = 8, fontsize = 6)
    # plt.draw()
    # plt.pause(0) 
Example 9
Project: smp_graphs   Author: x75   File: block_cls.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def step(self, x = None):
        for i in range(self.blocksize):
            self.u = self.inputs['u']['val'][:,[i]]
            self.x = self.system.step(self.u)
            # print "self.u", self.u
            # real output variables defined by config
            # for k in ['s_proprio', 's_extero', 's_all']:
            for k in list(self.outputs.keys()):
                k_ = getattr(self, k)
                # print "bhasysblock k_", k_, k_[:,[i]].shape, self.x[k].shape
                # print "bhasysblock k_", k_, k_[:,[i]], self.x[k]
                k_[:,[i]] = self.x[k].T
                # setattr(self, k, self.x[k])
                # print "%s.step[%d]: x = %s/%s" % (self.cname, self.cnt, self.x, self.system.x)
            if self.doplot and self.cnt % 100 == 0:
                print("%s.step plotting arm with u = %s" % (self.cname, self.u.T))
                self.system.visualize(self.ax, self.u.T)
                plt.draw()
                plt.pause(1e-6) 
Example 10
Project: Aegis   Author: jlillywh   File: live_plotter.py    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=(8, 4))
        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.xlabel('Time')
        plt.ylabel('Depth [m]')
        plt.title('Reservoir Level'.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 
Example 11
Project: Aegis   Author: jlillywh   File: sliding_ts_chart.py    GNU General Public License v3.0 6 votes vote down vote up
def update(self, new_value):
        """Adds a value to the end of the array and removes the first.
        
            Parameters
            ----------
            new_value : Quantity
                The value that is added to the front of the list.
        """
        self.queue.append(new_value)
        self.queue.popleft()
        self.last_date += pd.Timedelta('1 days')

        plt.axis([0, 10, 0, 1])

        for i in range(10):
            y = np.random.random()
            plt.scatter(i, y)
            plt.pause(0.05)

        plt.show() 
Example 12
Project: esys-pbi   Author: fsxfreak   File: matplotlib_standalone.py    MIT License 6 votes vote down vote up
def begin(queue, event=None):
  signal.signal(signal.SIGINT, sigint_handler)
  signal.signal(signal.SIGTERM, sigterm_handler)

  load(queue)
  start()

  try:
    while True:
      signal.pause()
  except AttributeError:
    # signal.pause() not implemented on windows
   # while not event.is_set():
    while not event:
      time.sleep(1)

    print('event was set, stopping')
    stop() 
Example 13
Project: infusion   Author: jiamings   File: infusion.py    MIT License 6 votes vote down vote up
def visualize(self, alpha=0.05, batch_size=10, repeat=1):
        assert(repeat > 0)
        bx, by = mnist.train.next_batch(batch_size)
        if alpha > 0:
            print(np.where(by > 0)[1])

        bz = self.sess.run(self.rand_init, feed_dict={self.x: bx, self.alpha: alpha})

        z = self.sess.run(self.z, feed_dict={self.x: bx, self.alpha: alpha, self.init: bz})

        # z = [bz]
        # for _ in range(0, repeat):
        #     zz = self.sess.run(self.z, feed_dict={self.x: bx, self.alpha: alpha, self.init: bz})
        #     bz = zz[-1]
        #     z += zz[1:]

        z = [np.reshape(zm, [zm.shape[0], 28, 28]) for zm in z]
        v = np.zeros([z[0].shape[0] * 28, len(z) * 28])
        for b in range(0, z[0].shape[0]):
            for t in range(0, len(z)):
                v[b * 28:(b + 1) * 28, t * 28:(t + 1) * 28] = z[t][b, :]
        plt.imshow(v, cmap='gray')
        plt.show()
        plt.pause(0.01) 
Example 14
Project: basler-pypylon-examples   Author: scivision   File: SingleImage.py    MIT License 6 votes vote down vote up
def simpleloop(cams):

    cam = connect(cams) 

    print('exposure time [millisec]:',cam.properties['ExposureTime']/1e3)
    # cam.properties['ExposureTime'] = 1000

    # cam.properties['DeviceLinkThroughputLimitMode'] = 'On'

    # %% movie
    ax = figure().gca()
    h = ax.imshow(list(cam.grab_images(1))[0])  # TODO workaround for grab_image() broken
    ht = ax.set_title('')
    cam.close()

    for i in range(Nblocks):

        cam = connect(cams,0)

        for j,I in enumerate(cam.grab_images(Nblock)):  # grab_images argument is how many images to yield
            h.set_data(I)
            ht.set_text(f'Image # {i*Nblock+j} / {Nblocks*Nblock}')
            draw(); pause(0.01)

        cam.close() 
Example 15
Project: stackednet   Author: zsdonghao   File: stacked_autoencoder.py    MIT License 6 votes vote down vote up
def visualize_assquare_W(D1, n_units_l1, second=10, saveable=False, idx=None, fig_idx=0):
        plt.ion()
        fig = plt.figure(fig_idx)      # show all feature images
        size = D1.shape[0]

        num_r = int(np.round(np.sqrt(n_units_l1)))  # 每行显示的个数   若25个hidden unit -> 每行显示5个
        count = 1
        for row in range(1,num_r+1):
            for col in range(1, int(n_units_l1/num_r)+1):
                #print(col, row, count)
                a = fig.add_subplot(int(n_units_l1/num_r), num_r, count)
                # plt.imshow(np.reshape(D1.get_value()[:,count-1],(28,28)), cmap='gray')
                plt.imshow(np.reshape(D1[:,count-1] / np.sqrt( (D1[:,count-1]**2).sum()) ,(np.sqrt(size),np.sqrt(size))), cmap='gray', interpolation="nearest")
                plt.gca().xaxis.set_major_locator(plt.NullLocator())    # 不显示刻度(tick)
                plt.gca().yaxis.set_major_locator(plt.NullLocator())
                count = count + 1
        # plt.title('All feature groups from GVM')
        # plt.show()
        if saveable:
            plt.savefig(str(idx)+'.pdf',format='pdf')
        else:
            plt.draw()
            plt.pause(second) 
Example 16
Project: Deep-reinforcement-learning-with-pytorch   Author: sweetice   File: naive-policy-gradient.py    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 17
Project: TF_RL   Author: Rowing0914   File: visualise.py    MIT License 6 votes vote down vote up
def plot_Q_values(data, xmin=-1, xmax=4, ymin=0, ymax=2):
    """
    Real time Bar plot of Q_values

    :param data:
    :param xmin:
    :param xmax:
    :param ymin:
    :param ymax:
    :return:
    """
    plt.axis([xmin, xmax, ymin, ymax])
    # print(data)
    length = np.arange(data.shape[0])
    plt.bar(length, data, align='center')
    plt.xticks(length)
    plt.xlabel("Actions")
    plt.ylabel("Q_values")
    plt.pause(0.02)
    plt.clf() 
Example 18
Project: MachineLearning-memo   Author: del680202   File: BN.py    Apache License 2.0 6 votes vote down vote up
def plot_his(inputs, inputs_norm):
    # plot histogram for the inputs of every layer
    for j, all_inputs in enumerate([inputs, inputs_norm]):
        for i, input in enumerate(all_inputs):
            plt.subplot(2, len(all_inputs), j*len(all_inputs)+(i+1))
            plt.cla()
            if i == 0:
                the_range = (-7, 10)
            else:
                the_range = (-1, 1)
            plt.hist(input.ravel(), bins=15, range=the_range, color='#FF5733')
            plt.yticks(())
            if j == 1:
                plt.xticks(the_range)
            else:
                plt.xticks(())
            ax = plt.gca()
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
        plt.title("%s normalizing" % ("Without" if j == 0 else "With"))
    plt.draw()
    plt.pause(0.01) 
Example 19
Project: zhusuan   Author: thu-ml   File: toy2d_intractable.py    MIT License 6 votes vote down vote up
def draw(vmean, vlogstd):
        from scipy import stats
        plt.cla()
        xlimits = [-2, 2]
        ylimits = [-4, 2]

        def log_prob(z):
            z1, z2 = z[:, 0], z[:, 1]
            return stats.norm.logpdf(z2, 0, 1.35) + \
                stats.norm.logpdf(z1, 0, np.exp(z2))

        plot_isocontours(ax, lambda z: np.exp(log_prob(z)), xlimits, ylimits)

        def variational_contour(z):
            return stats.multivariate_normal.pdf(
                z, vmean, np.diag(np.exp(vlogstd)))

        plot_isocontours(ax, variational_contour, xlimits, ylimits)
        plt.draw()
        plt.pause(1.0 / 30.0) 
Example 20
Project: fcos-gluon-cv   Author: Angzz   File: cam_demo.py    Apache License 2.0 6 votes vote down vote up
def keypoint_detection(img, detector, pose_net, ctx=mx.cpu(), axes=None):
    x, img = gcv.data.transforms.presets.yolo.transform_test(img, short=512, max_size=350)
    x = x.as_in_context(ctx)
    class_IDs, scores, bounding_boxs = detector(x)

    plt.cla()
    pose_input, upscale_bbox = detector_to_simple_pose(img, class_IDs, scores, bounding_boxs,
                                                       output_shape=(128, 96), ctx=ctx)
    if len(upscale_bbox) > 0:
        predicted_heatmap = pose_net(pose_input)
        pred_coords, confidence = heatmap_to_coord(predicted_heatmap, upscale_bbox)

        axes = plot_keypoints(img, pred_coords, confidence, class_IDs, bounding_boxs, scores,
                              box_thresh=0.5, keypoint_thresh=0.2, ax=axes)
        plt.draw()
        plt.pause(0.001)
    else:
        axes = plot_image(frame, ax=axes)
        plt.draw()
        plt.pause(0.001)

    return axes 
Example 21
Project: press-alt   Author: mrwojtek   File: case-repeat.py    Apache License 2.0 6 votes vote down vote up
def plot_plot(file, fig, ax, tight, xlabel, ylabel, loc, title=None):
    if tight:
        ax.set_xlabel(xlabel, fontsize=9)
        ax.set_ylabel(ylabel, fontsize=9)
        ax.tick_params(axis='both', which='major', labelsize=9)
        if title is not None:
            ax.set_title(title, fontsize=9)
            fig.subplots_adjust(0.1, 0.13, 0.985, 0.93)
        else:
            fig.subplots_adjust(0.1, 0.13, 0.985, 0.97)
    else:
        ax.set_xlabel(xlabel, fontsize=10)
        ax.set_ylabel(ylabel, fontsize=10)
        ax.tick_params(axis='both', which='major', labelsize=9)
        if title is not None:
            ax.set_title(title, fontsize=12)
            fig.subplots_adjust(0.13, 0.15, 0.95, 0.9)
        else:
            fig.subplots_adjust(0.13, 0.15, 0.95, 0.95)

    if file is not None:
        fig.savefig(file)
    else:
        plt.pause(0) 
Example 22
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def graphplot(self):
        plt.clf()
        # wave
        plt.subplot(311)
        plt.plot(self.wave_x, self.wave_y)
        plt.axis([self.START, self.START + self.N, -0.5, 0.5])
        plt.xlabel("time [sample]")
        plt.ylabel("amplitude")
        #Spectrum
        plt.subplot(312)
        plt.plot(self.spec_x, self.spec_y, marker= 'o', linestyle='-')
        plt.axis([0, self.RATE / 2, 0, 50])
        plt.xlabel("frequency [Hz]")
        plt.ylabel("amplitude spectrum")
        #Pause
        plt.pause(.01) 
Example 23
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def plot(loss_list, predictions_series, batchX, batchY):
    plt.subplot(2, 3, 1)
    plt.cla()
    plt.plot(loss_list)

    for batch_series_idx in range(5):
        one_hot_output_series = np.array(predictions_series)[:, batch_series_idx, :]
        single_output_series = np.array([(1 if out[0] < 0.5 else 0) for out in one_hot_output_series])

        plt.subplot(2, 3, batch_series_idx + 2)
        plt.cla()
        plt.axis([0, truncated_backprop_length, 0, 2])
        left_offset = range(truncated_backprop_length)
        plt.bar(left_offset, batchX[batch_series_idx, :], width=1, color="blue")
        plt.bar(left_offset, batchY[batch_series_idx, :] * 0.5, width=1, color="red")
        plt.bar(left_offset, single_output_series * 0.3, width=1, color="green")

    plt.draw()
    plt.pause(0.0001) 
Example 24
Project: pytorchrl   Author: nosyndicate   File: multigoal_env.py    MIT License 6 votes vote down vote up
def render(self, close=False):
        if self.fig is None:
            self.fig = plt.figure()
            self.ax = self.fig.add_subplot(111)
            plt.axis('equal')

        if self.fixed_plots is None:
            self.fixed_plots = self.plot_position_cost(self.ax)

        [o.remove() for o in self.dynamic_plots]

        x, y = self.observation
        point = self.ax.plot(x, y, 'b*')
        self.dynamic_plots = point

        if close:
            self.fixed_plots = None

        plt.pause(0.001)
        plt.draw() 
Example 25
Project: enzynet   Author: shervinea   File: keras_utils.py    MIT License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        # Store
        self.epochs += [epoch]
        self.losses += [logs.get('loss')]
        self.val_losses += [logs.get('val_loss')]
        self.accs += [logs.get('acc')]
        self.val_accs += [logs.get('val_acc')]

        # Add point to plot
        self.display.add(x=epoch,
                         y_tr=logs.get('acc'),
                         y_val=logs.get('val_acc'))
        plt.pause(0.001)


        # Save to file
        dictionary = {'epochs': self.epochs,
                      'losses': self.losses,
                      'val_losses': self.val_losses,
                      'accs': self.accs,
                      'val_accs': self.val_accs}
        dict_to_csv(dictionary, self.saving_path) 
Example 26
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def update(self, xPhys, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        plt.pause(0.01) 
Example 27
Project: fenics-topopt   Author: zfergus   File: gui.py    MIT License 5 votes vote down vote up
def update(self, xPhys, title=None):
        """Plot to screen"""
        self.im.set_array(-xPhys.reshape((self.nelx, self.nely)).T)
        self.fig.canvas.draw()
        self.fig.canvas.flush_events()
        if title is not None:
            plt.title(title)
        plt.pause(0.01) 
Example 28
Project: neural-fingerprinting   Author: StephanZheng   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pair_visual(original, adversarial, figure=None):
    """
    This function displays two images: the original and the adversarial sample
    :param original: the original input
    :param adversarial: the input after perterbations have been applied
    :param figure: if we've already displayed images, use the same plot
    :return: the matplot figure to reuse for future samples
    """
    import matplotlib.pyplot as plt

    # Squeeze the image to remove single-dimensional entries from array shape
    original = np.squeeze(original)
    adversarial = np.squeeze(adversarial)

    # Ensure our inputs are of proper shape
    assert(len(original.shape) == 2 or len(original.shape) == 3)

    # To avoid creating figures per input sample, reuse the sample plot
    if figure is None:
        plt.ion()
        figure = plt.figure()
        figure.canvas.set_window_title('Cleverhans: Pair Visualization')

    # Add the images to the plot
    perterbations = adversarial - original
    for index, image in enumerate((original, perterbations, adversarial)):
        figure.add_subplot(1, 3, index + 1)
        plt.axis('off')

        # If the image is 2D, then we have 1 color channel
        if len(image.shape) == 2:
            plt.imshow(image, cmap='gray')
        else:
            plt.imshow(image)

        # Give the plot some time to update
        plt.pause(0.01)

    # Draw the plot and return
    plt.show()
    return figure 
Example 29
Project: neural-pipeline   Author: toodef   File: mpl.py    MIT License 5 votes vote down vote up
def update_losses(self, losses: {}):
        def on_loss(name: str, values: np.ndarray):
            plot = self._cur_plot(['loss', name])
            plot.add_value(name, np.mean(values), self.epoch_num)

        self._iterate_by_losses(losses, on_loss)

        if not self._plots_placed:
            self._place_plots()
            self._plots_placed = True

        if self._realtime:
            plt.pause(0.01) 
Example 30
Project: cs294-112_hws   Author: xuwd11   File: pointmass.py    MIT License 5 votes vote down vote up
def render(self):
        # create a grid
        states = [self.state/self.scale]
        indices = np.array([int(self.preprocess(s)) for s in states])
        a = np.zeros(self.grid_size)
        for i in indices:
            a[i] += 1
        max_freq = np.max(a)
        a/=float(max_freq)  # normalize
        a = np.reshape(a, (self.scale, self.scale))
        ax = sns.heatmap(a)
        plt.draw()
        plt.pause(0.001)
        plt.clf() 
Example 31
Project: iqoption-bot   Author: rrfaria   File: pyrenko.py    MIT License 5 votes vote down vote up
def plot_renko(self, col_up = 'g', col_down = 'r'):
        #fig, ax = plt.subplots(1, figsize=(20, 10))
        self.ax.clear()
        self.ax.set_title('Renko chart: ' + self.chart_title)
        self.ax.set_xlabel('Renko bars')
        self.ax.set_ylabel('Price')

        # Calculate the limits of axes
        self.ax.set_xlim(0.0,
                    len(self.renko_prices) + 1.0)
        self.ax.set_ylim(np.min(self.renko_prices) - 3.0 * self.brick_size,
                    np.max(self.renko_prices) + 3.0 * self.brick_size)

        # exponential
        ema = talib.EMA(np.array(self.renko_prices,dtype='f8'),timeperiod=self.ema_period)
        self.ax.plot(ema, color='#5957ce', lw=1, label='EMA ('+ str(self.ema_period) + ')')

        # Plot each renko bar
        for i in range(1, len(self.renko_prices)):
            # Set basic params for patch rectangle
            col = col_up if self.renko_directions[i] == 1 else col_down
            x = i
            y = self.renko_prices[i] - self.brick_size if self.renko_directions[i] == 1 else self.renko_prices[i]
            height = self.brick_size

            # Draw bar with params
            self.ax.add_patch(
                patches.Rectangle(
                    (x, y),   # (x,y)
                    1.0,     # width
                    self.brick_size, # height
                    facecolor = col
                )
            )

        #plt.show()
        plt.pause(self.chart_iterval) 
Example 32
Project: SNN   Author: arnogranier   File: core.py    MIT License 5 votes vote down vote up
def cascade(self, event, line, point, start_point, T, dt, xvarname,
                yvarname):
        """When left mouse button pressed on interactive phase_plan,
           start plotting the dynamic (ie the evolution through time
           of the variables) """

        # Check that the click was really on the phase_plan
        if event.inaxes != line.axes:
            return

        # Get click coordinates
        x, y = event.xdata, event.ydata

        # Plot the starting point
        start_point.set_data(x, y)

        # Simulate the model starting with the right values for x and
        # y variables ie the coordinates of the click
        data, _ = self.simulation(T, dt, start={xvarname: x, yvarname: y})

        # Loop through the values of the variables during the simulation
        xs, ys = [x, ],  [y, ]
        fig = line.figure
        for (x, y) in [(x,y) for (x,y) in zip(data[xvarname], data[yvarname])]:

            # Update line
            xs.append(x)
            ys.append(y)
            line.set_data(xs, ys)

            # Update current point
            point.set_data(x, y)

            plt.pause(0.01)
            fig.canvas.draw() 
Example 33
Project: Deformable-ConvNets   Author: guanfuchen   File: show_offset.py    MIT License 5 votes vote down vote up
def show_dconv_offset(im, all_offset, step=[2, 2], filter_size=3,
                      dilation=2, pad=2, plot_area=2, plot_level=3):
    vis_attr = {'filter_size': filter_size, 'dilation': dilation, 'pad': pad,
                'plot_area': plot_area, 'plot_level': plot_level}

    map_h = all_offset[0].shape[2]
    map_w = all_offset[0].shape[3]

    step_h = step[0]
    step_w = step[1]
    start_h = np.round(step_h / 2)
    start_w = np.round(step_w / 2)

    plt.figure()
    for im_h in range(start_h, map_h, step_h):
        for im_w in range(start_w, map_w, step_w):
            target_point = np.array([im_h, im_w])
            source_y = np.round(target_point[0] * im.shape[0] / map_h)
            source_x = np.round(target_point[1] * im.shape[1] / map_w)
            if source_y < plot_area or source_x < plot_area \
                    or source_y >= im.shape[0] - plot_area or source_x >= im.shape[1] - plot_area:
                continue

            cur_im = np.copy(im)
            source_points = get_bottom_position(vis_attr, [target_point], all_offset)
            cur_im = plot_according_to_point(vis_attr, cur_im, source_points, map_h, map_w)
            cur_im[source_y-plot_area:source_y+plot_area+1, source_x-plot_area:source_x+plot_area+1, :] = \
                np.tile(np.reshape([0, 255, 0], (1, 1, 3)), (2*plot_area+1, 2*plot_area+1, 1))


            plt.axis("off")
            plt.imshow(cur_im)
            plt.show(block=False)
            plt.pause(0.01)
            plt.clf() 
Example 34
Project: shenfun   Author: spectralDNS   File: Ginzburg_Landau.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, u, u_hat, t, tstep, plot_tstep, write_tstep, file, **params):
    global count
    if tstep % plot_tstep == 0 and plot_tstep > 0:
        u = u_hat.backward(u)
        image.ax.clear()
        image.ax.contourf(X[0], X[1], u.real, 100)
        plt.pause(1e-6)
        count += 1
        #plt.savefig('Ginzburg_Landau_{}_{}.png'.format(N[0], count))
    if tstep % write_tstep[0] == 0:
        u = u_hat.backward(u)
        file.write(tstep, write_tstep[1]) 
Example 35
Project: shenfun   Author: spectralDNS   File: Gray_Scott_fractal.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, uv, uv_hat, t, tstep, **params):
    if tstep % params['plot_step'] == 0 and params['plot_step'] > 0:
        uv = uv_hat.backward(uv)
        image.ax.clear()
        image.ax.contourf(X[0], X[1], uv[0].real, 100)
        plt.pause(1e-6)
        print(np.linalg.norm(uv[0]-uv0[0]),
              np.linalg.norm(uv[1]-uv0[1]),
              np.linalg.norm(uv[0]),
              np.linalg.norm(uv[1]))
        uv0[:] = uv

    if tstep % params['write_tstep'][0] == 0:
        uv = uv_hat.backward(uv)
        params['file'].write(tstep, params['write_tstep'][1], as_scalar=True) 
Example 36
Project: shenfun   Author: spectralDNS   File: KleinGordon.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, fu, fu_hat, t, tstep, **params):
    global gradu

    timer()
    transformed = False

    if rank == 0 and tstep % params['plot_tstep'] == 0 and params['plot_tstep'] > 0:
        fu = fu_hat.backward(fu)
        f, u = fu[:]
        image.ax.clear()
        image.ax.contourf(X[1][..., 0], X[0][..., 0], u[..., N[2]//2], 100)
        plt.pause(1e-6)
        transformed = True

    if tstep % params['write_slice_tstep'][0] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
            transformed = True
        params['file'].write(tstep, params['write_slice_tstep'][1], as_scalar=True)

    if tstep % params['write_tstep'][0] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
            transformed = True
        params['file'].write(tstep, params['write_tstep'][1], as_scalar=True)

    if tstep % params['Compute_energy'] == 0:
        if transformed is False:
            fu = fu_hat.backward(fu)
        f, u = fu
        f_hat, u_hat = fu_hat
        ekin = 0.5*energy_fourier(f_hat, T)
        es = 0.5*energy_fourier(1j*(K[0]*u_hat[0]+K[1]*u_hat[1]+K[2]*u_hat[2]), T)
        eg = gamma*np.sum(0.5*u**2 - 0.25*u**4)/np.prod(np.array(N))
        eg = comm.allreduce(eg)
        gradu = TV.backward(1j*(K[0]*u_hat[0]+K[1]*u_hat[1]+K[2]*u_hat[2]), gradu)
        ep = comm.allreduce(np.sum(f*gradu)/np.prod(np.array(N)))
        ea = comm.allreduce(np.sum(np.array(X)*(0.5*f**2 + 0.5*gradu**2 - (0.5*u**2 - 0.25*u**4)*f))/np.prod(np.array(N)))
        if rank == 0:
            print("Time = %2.2f Total energy = %2.8e Linear momentum %2.8e Angular momentum %2.8e" %(t, ekin+es+eg, ep, ea))
        comm.barrier() 
Example 37
Project: shenfun   Author: spectralDNS   File: RayleighBenardRK3.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init_plots(self):
        ub = self.u_.backward(self.ub)
        T_b = self.T_.backward(self.T_b)
        if comm.Get_rank() == 0:
            plt.figure(1, figsize=(6, 3))
            self.im1 = plt.quiver(self.X[1], self.X[0], ub[1], ub[0], pivot='mid', scale=0.01)
            plt.draw()
            plt.figure(2, figsize=(6, 3))
            self.im2 = plt.contourf(self.X[1], self.X[0], T_b, 100)
            plt.draw()
            plt.pause(1e-6) 
Example 38
Project: shenfun   Author: spectralDNS   File: kdv.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def update(self, u, u_hat, t, tstep, plot_step, **params):
    if tstep % plot_step == 0 and plot_step > 0:
        u = T.backward(u_hat, u)
        plt.plot(x, u)
        plt.draw()
        plt.pause(1e-6)
        data.append(u.copy()) 
Example 39
Project: poeai   Author: nicholastoddsmith   File: BotDebugger.py    MIT License 5 votes vote down vote up
def PlotMap(self):
        mm = self.B.mm
        cp = mm.GetPosition()
        if self.B.p is not None:
            ppx = [self.B.p[0], cp[0]]
            ppy = [self.B.p[1], cp[1]]
        else:
            ppx, ppy = [cp[0]], [cp[1]]
        pc = ['r', 'g']
        C, CC = [], []
        for qp in mm.GetCells():
            C.append(qp[0:2])
            CC.append(mm.GetCellType(qp))
        C = np.stack(C)
        if self.sct is None:
            mpl.ion()
            fig, self.ax  = mpl.subplots()
            fig.canvas.manager.window.setGeometry(840, 5, 640, 545)
            self.sct = 1
        else:
            self.ax.clear()
        self.ax.scatter(C[:, 0], C[:, 1], color = [CF(j) for j in CC])
        self.ax.scatter(ppx, ppy, c = pc, s = 64)
        self.ax.scatter([mm.hp[0]], [mm.hp[1]], color = 'm', s = 64)
        self.ax.set_title("At: " + str(cp))
        mpl.pause(0.1) 
Example 40
Project: optimization   Author: computeVision   File: graph.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def visualize_solution(I, x, filename=None):
    """
    Visualize a path in the image I given by the solution vector x
    """
    plt.figure(); plt.imshow(I, interpolation='none', cmap='gray')

    free_y,free_x = np.where(I)
    edges = np.reshape(x,(-1,4))    # every row in the matrix corresponds to a graph node
    
    th = 0.5
    e_row, e_col = np.where(edges > th)   # find all rows with active edges
    
    for ne, (idx, e) in enumerate(zip(e_row, e_col)):
        x = free_x[idx]; y = free_y[idx]   # x/y coordinates of node
        if e==0:
            plt.plot([x,x],[y,y-1],'b', lw=2.5)
        elif e==1:
            plt.plot([x,x+1],[y,y],'b', lw=2.5)
        elif e==2:
            plt.plot([x,x],[y,y+1],'b', lw=2.5)
        elif e==3:
            plt.plot([x,x-1],[y,y],'b', lw=2.5)
        
        if ne % 250 == 0:
            plt.pause(0.001)
        
    plt.pause(0.001)
    if filename is not None:
        plt.savefig(filename) 
Example 41
Project: optimization   Author: computeVision   File: solver.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_energy(energy):
    plt.clf()
    plt.plot(energy)
    plt.xlabel('Epochs')
    plt.ylabel('Energy')
    plt.grid(True)
    plt.title("Energy Plot")
    plt.pause(0.001) 
Example 42
Project: VRPTW-ga   Author: shayan-ys   File: report.py    MIT License 5 votes vote down vote up
def plot_draw(self, x_axis: list, y_axis: list, latest_result):
        y_axis_parsed = []
        for y in y_axis:
            try:
                y_axis_parsed.append(y['best'])
            except:
                break
        if y_axis_parsed:
            y_axis = y_axis_parsed

        plt.figure(1)
        # self.subplot.set_xlim([self.plot_x_axis[0], self.plot_x_axis[-1]])
        self.subplot.set_ylim([min(y_axis) - 5, max(y_axis) + 5])
        plt.suptitle('Best solution so far: ' + re.sub("(.{64})", "\\1\n", str(latest_result), 0, re.DOTALL),
                     fontsize=10)
        print(latest_result)
        self.subplot.plot(x_axis, y_axis)

        plt.figure(2)
        for route_x, route_y in latest_result.plot_get_route_cords():
            plt.plot(route_x, route_y)

        plt.draw()
        self.fig.savefig("plot-output.png")
        self.fig_node_connector.savefig("plot2-output.png")
        plt.pause(0.000001) 
Example 43
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP(self):
        '''Plot the GP at its current stage in the minimization.
        '''
        maxloc = self.maxloc; umax = self.umax
        xt = self.xt; mean = np.squeeze( self.mean )
        cov = self.cov; u = self.u;
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        pl.figure(5)
        pl.clf()
        pl.plot(xt,mean)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),
                        mean+np.squeeze(2*np.sqrt(var)),
                        facecolor = "grey", alpha=0.5)
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 44
Project: aftershoq   Author: mfranckie   File: gaussopt.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plotGP_testfunc(self, model, hutil):
        '''Plot the GP at its current stage in the minimization
        with the test function "model".

        Parameters

        model: A tets function giving a fast merit function evaluation'''

        xt = self.xt; mean = np.squeeze( self.mean ); cov = self.cov; u = self.u;
        maxloc = self.maxloc; umax = self.umax
        x = self.x; y = self.y;

        var = np.reshape( np.abs( np.diag( self.cov ) ), (self.Nx,1) )

        yt = []
        [yt.append(-model.getMerit((hutil.interp_coords_from_dist(xx)/float(2**hutil.p)))) for xx in xt]

        pl.figure(5)
        pl.hold(False)
        pl.plot(xt,mean)
        pl.hold(True)
        pl.plot(x,y,'*')
        pl.fill_between(np.squeeze(xt), mean-np.squeeze(2*np.sqrt(var)),mean+np.squeeze(2*np.sqrt(var)), facecolor = "grey", alpha=0.5)
        pl.plot(xt,yt,'-')
        pl.plot(xt,u/5,'-g')
        pl.plot(maxloc,umax,'*')
        pl.ylim(-5, 5)

        lim_diff = (np.max(y) - np.min(y))/2.

        pl.gca().set_xlim( 0, np.max(x) )
        pl.gca().set_ylim( np.min(y) - lim_diff, np.max(y) + lim_diff )

        #writer.grab_frame()
        pl.pause(0.01) 
Example 45
Project: esys-pbi   Author: fsxfreak   File: matplotlib_standalone.py    MIT License 5 votes vote down vote up
def _graph_lsl(self):
    print('checking if stream has be initialized')
    self.streams = resolve_byprop('name', 'bci', timeout=2.5)
    try:
      self.inlet = StreamInlet(self.streams[0])
    except IndexError:
      raise ValueError('Make sure stream name=bci is opened first.')
    while self.running:
      # initial run
      self.sample, self.timestamp = self.inlet.pull_sample(timeout=5)
    # time correction to sync to local_clock()
      try:
        if self.timestamp is not None and self.sample is not None:
          self.timestamp = self.timestamp + self.inlet.time_correction(timeout=5) 

      except TimeoutError:
        pass
      self.SecondTimes.append(self.sample[1])                         #add time stamps to array 'timeValSeconds'
      self.ProcessedSig.append(self.sample[0])                           #add processed signal values to 'processedSig'
    
      self.count = self.count + 1

      if((self.count % 20 == 0) and (self.count != 0)):   #every 20 samples (ie ~ 0.10 s) is when plot updates
	self.lineHandle[0].set_ydata(self.ProcessedSig)
	self.lineHandle[0].set_xdata(self.SecondTimes)
	#plt.xlim(0, 5)
	plt.xlim(self.SecondTimes[0], self.SecondTimes[-1])
	plt.ylim(0, 10)
	plt.pause(0.01)
      
      if(self.count >= 399): 
        self.ProcessedSig.pop(0)    
        self.SecondTimes.pop(0)

    plt.pause(0.01)
    print('closing graphing utility')
    self.inlet.close_stream() 
Example 46
Project: esys-pbi   Author: fsxfreak   File: matplotlib_standalone.py    MIT License 5 votes vote down vote up
def main():
  signal.signal(signal.SIGINT, sigint_handler)
  signal.signal(signal.SIGTERM, sigterm_handler)
  load(queue=None)
  start()

  try:
    signal.pause()
  except AttributeError:
    while True:
      time.sleep(1)

  stop() 
Example 47
Project: esys-pbi   Author: fsxfreak   File: graph_matplotlib.py    MIT License 5 votes vote down vote up
def main():
  signal.signal(signal.SIGINT, sigint_handler)
  signal.signal(signal.SIGTERM, sigterm_handler)
  load(queue=None)
  start()

  try:
    signal.pause()
  except AttributeError:
    while True:
      time.sleep(1)

  stop() 
Example 48
Project: autoencoders_using_numpy   Author: Hadisalman   File: autoencoder.py    MIT License 5 votes vote down vote up
def visualize_weights(self, title):
		weights = self.model['W1']
		reshaped_weights = np.reshape(weights,(28,28,self.layers[1]))
		plt.figure(1)
		for i in range(self.layers[1]):
			ax = plt.subplot(np.sqrt(self.layers[1]),np.sqrt(self.layers[1]),i+1)	
			ax.imshow(reshaped_weights[:,:,i],cmap = 'gray')
			plt.axis('off')
		plt.pause(1) 
Example 49
Project: Deep-Feature-Flow-Segmentation   Author: tonysy   File: show_offset.py    MIT License 5 votes vote down vote up
def show_dconv_offset(im, all_offset, step=[2, 2], filter_size=3,
                      dilation=2, pad=2, plot_area=2, plot_level=3):
    vis_attr = {'filter_size': filter_size, 'dilation': dilation, 'pad': pad,
                'plot_area': plot_area, 'plot_level': plot_level}

    map_h = all_offset[0].shape[2]
    map_w = all_offset[0].shape[3]

    step_h = step[0]
    step_w = step[1]
    start_h = np.round(step_h / 2)
    start_w = np.round(step_w / 2)

    plt.figure()
    for im_h in range(start_h, map_h, step_h):
        for im_w in range(start_w, map_w, step_w):
            target_point = np.array([im_h, im_w])
            source_y = np.round(target_point[0] * im.shape[0] / map_h)
            source_x = np.round(target_point[1] * im.shape[1] / map_w)
            if source_y < plot_area or source_x < plot_area \
                    or source_y >= im.shape[0] - plot_area or source_x >= im.shape[1] - plot_area:
                continue

            cur_im = np.copy(im)
            source_points = get_bottom_position(vis_attr, [target_point], all_offset)
            cur_im = plot_according_to_point(vis_attr, cur_im, source_points, map_h, map_w)
            cur_im[source_y-plot_area:source_y+plot_area+1, source_x-plot_area:source_x+plot_area+1, :] = \
                np.tile(np.reshape([0, 255, 0], (1, 1, 3)), (2*plot_area+1, 2*plot_area+1, 1))


            plt.axis("off")
            plt.imshow(cur_im)
            plt.show(block=False)
            plt.pause(0.01)
            plt.clf() 
Example 50
Project: social_mind   Author: byeongkyu   File: motion_arbiter.py    Apache License 2.0 5 votes vote down vote up
def handle_update_figure(self, signum, frame):
        self.plot_to_matplotlib(self.plot_item.get_plot_data())
        self.fig.canvas.draw()
        plt.pause(0.001)