Python matplotlib.pyplot.pause() Examples

The following are 30 code examples of matplotlib.pyplot.pause(). 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: viz.py    From LearnTrajDep with MIT License 6 votes vote down vote up
def plot_predictions(expmap_gt, expmap_pred, fig, ax, f_title):
    # Load all the data
    parent, offset, rotInd, expmapInd = fk._some_variables()

    nframes_pred = expmap_pred.shape[0]

    # Compute 3d points for each frame
    xyz_gt = np.zeros((nframes_pred, 96))
    for i in range(nframes_pred):
        xyz_gt[i, :] = fk.fkl(expmap_gt[i, :], parent, offset, rotInd, expmapInd).reshape([96])
    xyz_pred = np.zeros((nframes_pred, 96))
    for i in range(nframes_pred):
        xyz_pred[i, :] = fk.fkl(expmap_pred[i, :], parent, offset, rotInd, expmapInd).reshape([96])

    # === Plot and animate ===
    ob = Ax3DPose(ax)
    # Plot the prediction
    for i in range(nframes_pred):

        ob.update(xyz_gt[i, :], xyz_pred[i, :])
        ax.set_title(f_title + ' frame:{:d}'.format(i + 1), loc="left")
        plt.show(block=False)

        fig.canvas.draw()
        plt.pause(0.05) 
Example #2
Source File: motor_dashboard.py    From gym-electric-motor with MIT License 6 votes vote down vote up
def reset(self, reference_trajectories=None, *_, **__):
        """
        Function to call when a new episode has started

        Args:
            reference_trajectories: the references for the new episode
        """
        self._k = 0
        if not self.initialized:
            return
        if reference_trajectories is None:
            for var in self.dash_vars:
                var.reset()
        else:
            self._episode_length = reference_trajectories.shape[1]
            self._visu_period = min(self._visu_period, self._episode_length * self._tau)
            for index, var in enumerate(self.dash_vars):
                if self._referenced_states[index]:
                    var.reset(reference_trajectories[index, :])
                else:
                    var.reset()
        plt.pause(0.05) 
Example #3
Source File: matplotlib_trading_chart.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def render(self, current_step, net_worths, benchmarks, trades, window_size=50):
        net_worth = round(net_worths[-1], 2)
        initial_net_worth = round(net_worths[0], 2)
        profit_percent = round((net_worth - initial_net_worth) / initial_net_worth * 100, 2)

        self.fig.suptitle('Net worth: $' + str(net_worth) +
                          ' | Profit: ' + str(profit_percent) + '%')

        window_start = max(current_step - window_size, 0)
        step_range = slice(window_start, current_step)
        times = self.df.index.values[step_range]

        self._render_net_worth(step_range, times, current_step, net_worths, benchmarks)
        self._render_price(step_range, times, current_step)
        self._render_volume(step_range, times)
        self._render_trades(step_range, trades)

        self.price_ax.set_xticklabels(times, rotation=45, horizontalalignment='right')

        # Hide duplicate net worth date labels
        plt.setp(self.net_worth_ax.get_xticklabels(), visible=False)

        # Necessary to view frames before they are unrendered
        plt.pause(0.001) 
Example #4
Source File: stress_gui.py    From fenics-topopt with 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 #5
Source File: stress_gui.py    From fenics-topopt with 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 #6
Source File: Reinforcement Learning DQN.py    From ML_CIA with MIT License 6 votes vote down vote up
def plot_durations():
    plt.figure(2)
    plt.clf()
    durations_t = torch.tensor(episode_durations, dtype=torch.float)
    plt.title('Training...')
    plt.xlabel('Episode')
    plt.ylabel('Duration')
    plt.plot(durations_t.numpy())
    # Take 100 episode averages and plot them too
    if len(durations_t) >= 100:
        means = durations_t.unfold(0, 100, 1).mean(1).view(-1)
        means = torch.cat((torch.zeros(99), means))
        plt.plot(means.numpy())

    plt.pause(0.001)
    if is_ipython:
        display.clear_output(wait=True)
        display.display(plt.gcf())

#%% Training loop 
Example #7
Source File: BN.py    From ML_CIA with MIT License 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 #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: gibbs_ss_demo.py    From pyhawkes with MIT License 6 votes vote down vote up
def update_plots(itr, test_model, S, ln, im_clus, im_net):
    K = test_model.K
    C = test_model.network.C
    T = S.shape[0]

    plt.figure(2)
    ln.set_data(np.arange(T), test_model.compute_rate()[:,0])
    plt.title("\lambda_{%d}. Iteration %d" % (0, itr))
    plt.pause(0.001)

    plt.figure(3)
    KC = np.zeros((K,C))
    KC[np.arange(K), test_model.network.c] = 1.0
    im_clus.set_data(KC)
    plt.title("KxC: Iteration %d" % itr)
    plt.pause(0.001)

    plt.figure(4)
    plt.title("W: Iteration %d" % itr)
    im_net.set_data(test_model.weight_model.W_effective)
    plt.pause(0.001) 
Example #10
Source File: toy2d_intractable.py    From zhusuan with 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 #11
Source File: svi_demo.py    From pyhawkes with MIT License 6 votes vote down vote up
def update_plots(itr, test_model, S, ln, im_clus, im_net):
    K = test_model.K
    C = test_model.C
    T = S.shape[0]
    plt.figure(2)
    ln.set_data(np.arange(T), test_model.compute_rate()[:,0])
    plt.title("\lambda_{%d}. Iteration %d" % (0, itr))
    plt.pause(0.001)

    plt.figure(3)
    KC = np.zeros((K,C))
    KC[np.arange(K), test_model.network.c] = 1.0
    im_clus.set_data(KC)
    plt.title("KxC: Iteration %d" % itr)
    plt.pause(0.001)

    plt.figure(4)
    plt.title("W: Iteration %d" % itr)
    im_net.set_data(test_model.weight_model.W_effective)
    plt.pause(0.001) 
Example #12
Source File: cat_mouse.py    From Projects with MIT License 6 votes vote down vote up
def state(self):
        img = np.copy(self.world[self.sight_range:self.world.shape[0]-self.sight_range,self.sight_range:self.world.shape[0]-self.sight_range])
        img[img==0] = 256
        img[img==1] = 215
        img[img==2] = 123
        img[img==3] = 175
        img[img==9] = 1
        p = plt.imshow(img, interpolation='nearest', cmap='nipy_spectral')
        fig = plt.gcf()
        c1 = mpatches.Patch(color='red', label='cats')
        c2 = mpatches.Patch(color='green', label='mice')
        c3 = mpatches.Patch(color='yellow', label='cheese')
        plt.legend(handles=[c1,c2,c3],loc='center left',bbox_to_anchor=(1, 0.5))
        #plt.savefig("cat_mouse%i.png" % self.gif, bbox_inches='tight')
        #self.gif += 1
        plt.pause(0.1)
        
# Run algorithm 
Example #13
Source File: gif_demo.py    From pyhawkes with MIT License 6 votes vote down vote up
def initialize_plots(true_model, test_model, S):
    K = true_model.K
    C = true_model.C
    R = true_model.compute_rate(S=S)
    T = S.shape[0]

    # Plot the true network
    plt.ion()
    plot_network(true_model.weight_model.A,
                 true_model.weight_model.W)
    plt.pause(0.001)


    # Plot the true and inferred firing rate
    plt.figure(2)
    plt.plot(np.arange(T), R[:,0], '-k', lw=2)
    plt.ion()
    ln = plt.plot(np.arange(T), test_model.compute_rate()[:,0], '-r')[0]
    plt.show()
    plt.pause(0.001)

    return ln, im_net 
Example #14
Source File: cam_demo.py    From gluon-cv with 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_alpha_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_alpha_pose(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 #15
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 #16
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 #17
Source File: lstm_with_tensorflow.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #18
Source File: rnn_with_ms.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #19
Source File: rnn_with_tensorflow.py    From Neural-Network-Programming-with-TensorFlow with MIT License 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 batchSeriesIdx in range(5):
        oneHotOutputSeries = np.array(predictions_series)[:, batchSeriesIdx, :]
        singleOutputSeries = np.array([(1 if out[0] < 0.5 else 0) for out in oneHotOutputSeries])

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

    plt.draw()
    plt.pause(0.0001) 
Example #20
Source File: vis.py    From rl-rc-car with MIT License 6 votes vote down vote up
def visualize_polar(state):
    plt.clf()

    sonar = state[0][-1:]
    readings = state[0][:-1]

    r = []
    t = []
    for i, s in enumerate(readings):
        r.append(math.radians(i * 6))
        t.append(s)

    ax = plt.subplot(111, polar=True)

    ax.set_theta_zero_location('W')
    ax.set_theta_direction(-1)
    ax.set_ylim(bottom=0, top=105)

    plt.plot(r, t)
    plt.scatter(math.radians(90), sonar, s=50)
    plt.draw()
    plt.pause(0.1) 
Example #21
Source File: keras_utils.py    From enzynet with 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 #22
Source File: multigoal_env.py    From pytorchrl with 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 #23
Source File: FPS_matplotlib_image.py    From pyimagevideo with GNU General Public License v3.0 5 votes vote down vote up
def fpsmatplotlib_pcolor(dat: np.ndarray):
    fg = figure()
    ax = fg.gca()
    h = ax.pcolormesh(dat[0, ...])
    ax.set_title('pcolormesh')
    ax.autoscale(True, tight=True)
    tic = time()
    for i in range(Nfps):
        h.set_array(dat[i % 2, ...].ravel())
        draw(), pause(1e-3)
    close(fg)
    return Nfps / (time() - tic) 
Example #24
Source File: VNet.py    From VNet with GNU General Public License v3.0 5 votes vote down vote up
def trainThread(self,dataQueue,solver):

        nr_iter = self.params['ModelParams']['numIterations']
        batchsize = self.params['ModelParams']['batchsize']

        batchData = np.zeros((batchsize, 1, self.params['DataManagerParams']['VolSize'][0], self.params['DataManagerParams']['VolSize'][1], self.params['DataManagerParams']['VolSize'][2]), dtype=float)
        batchLabel = np.zeros((batchsize, 1, self.params['DataManagerParams']['VolSize'][0], self.params['DataManagerParams']['VolSize'][1], self.params['DataManagerParams']['VolSize'][2]), dtype=float)

        #only used if you do weighted multinomial logistic regression
        batchWeight = np.zeros((batchsize, 1, self.params['DataManagerParams']['VolSize'][0],
                               self.params['DataManagerParams']['VolSize'][1],
                               self.params['DataManagerParams']['VolSize'][2]), dtype=float)

        train_loss = np.zeros(nr_iter)
        for it in range(nr_iter):
            for i in range(batchsize):
                [defImg, defLab, defWeight] = dataQueue.get()

                batchData[i, 0, :, :, :] = defImg.astype(dtype=np.float32)
                batchLabel[i, 0, :, :, :] = (defLab > 0.5).astype(dtype=np.float32)
                batchWeight[i, 0, :, :, :] = defWeight.astype(dtype=np.float32)

            solver.net.blobs['data'].data[...] = batchData.astype(dtype=np.float32)
            solver.net.blobs['label'].data[...] = batchLabel.astype(dtype=np.float32)
            #solver.net.blobs['labelWeight'].data[...] = batchWeight.astype(dtype=np.float32)
            #use only if you do softmax with loss


            solver.step(1)  # this does the training
            train_loss[it] = solver.net.blobs['loss'].data

            if (np.mod(it, 10) == 0):
                plt.clf()
                plt.plot(range(0, it), train_loss[0:it])
                plt.pause(0.00000001)


            matplotlib.pyplot.show() 
Example #25
Source File: utilities.py    From VNet with GNU General Public License v3.0 5 votes vote down vote up
def sitk_show(nda, title=None, margin=0.0, dpi=40):
    figsize = (1 + margin) * nda.shape[0] / dpi, (1 + margin) * nda.shape[1] / dpi

    extent = (0, nda.shape[1], nda.shape[0], 0)
    fig = plt.figure(figsize=figsize, dpi=dpi)
    ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])

    plt.set_cmap("gray")
    for k in range(0,nda.shape[2]):
        print "printing slice "+str(k)
        ax.imshow(np.squeeze(nda[:,:,k]),extent=extent,interpolation=None)
        plt.draw()
        plt.pause(0.1)
        #plt.waitforbuttonpress() 
Example #26
Source File: imager_utils.py    From eht-imaging with GNU General Public License v3.0 5 votes vote down vote up
def plot_i(im, Prior, nit, chi2_dict, **kwargs):
    """Plot the total intensity image at each iteration
    """

    cmap = kwargs.get('cmap', 'afmhot')
    interpolation = kwargs.get('interpolation', 'gaussian')
    pol = kwargs.get('pol', '')
    scale = kwargs.get('scale', None)
    dynamic_range = kwargs.get('dynamic_range', 1.e5)
    gamma = kwargs.get('dynamic_range', .5)

    plt.ion()
    plt.pause(1.e-6)
    plt.clf()

    imarr = im.reshape(Prior.ydim, Prior.xdim)

    if scale == 'log':
        if (imarr < 0.0).any():
            print('clipping values less than 0')
            imarr[imarr < 0.0] = 0.0
        imarr = np.log(imarr + np.max(imarr)/dynamic_range)

    if scale == 'gamma':
        if (imarr < 0.0).any():
            print('clipping values less than 0')
            imarr[imarr < 0.0] = 0.0
        imarr = (imarr + np.max(imarr)/dynamic_range)**(gamma)

    plt.imshow(imarr, cmap=plt.get_cmap(cmap), interpolation=interpolation)
    xticks = obsh.ticks(Prior.xdim, Prior.psize/ehc.RADPERAS/1e-6)
    yticks = obsh.ticks(Prior.ydim, Prior.psize/ehc.RADPERAS/1e-6)
    plt.xticks(xticks[0], xticks[1])
    plt.yticks(yticks[0], yticks[1])
    plt.xlabel(r'Relative RA ($\mu$as)')
    plt.ylabel(r'Relative Dec ($\mu$as)')
    plotstr = str(pol) + " : step: %i  " % nit
    for key in chi2_dict.keys():
        plotstr += r"$\chi^2_{%s}$: %0.2f  " % (key, chi2_dict[key])
    plt.title(plotstr, fontsize=18) 
Example #27
Source File: visualization.py    From NTM-Keras with MIT License 5 votes vote down vote up
def update(self, matrix_list, name_list):
        # draw first line
        axes_input = plt.subplot2grid((3, 1), (0, 0), colspan=1)
        axes_input.set_aspect('equal')
        plt.imshow(matrix_list[0], interpolation='none')
        axes_input.set_xticks([])
        axes_input.set_yticks([])

        # draw second line
        axes_output = plt.subplot2grid((3, 1), (1, 0), colspan=1)
        plt.imshow(matrix_list[1], interpolation='none')
        axes_output.set_xticks([])
        axes_output.set_yticks([])

        # draw third line
        axes_predict = plt.subplot2grid((3, 1), (2, 0), colspan=1)
        plt.imshow(matrix_list[2], interpolation='none')
        axes_predict.set_xticks([])
        axes_predict.set_yticks([])

        # # add text
        # plt.text(-2, -19.5, name_list[0], ha='right')
        # plt.text(-2, -7.5, name_list[1], ha='right')
        # plt.text(-2, 4.5, name_list[2], ha='right')
        # plt.text(6, 10, 'Time $\longrightarrow$', ha='right')

        # set tick labels invisible
        make_tick_labels_invisible(plt.gcf())
        # adjust spaces
        plt.subplots_adjust(hspace=0.05, wspace=0.05, bottom=0.1, right=0.8, top=0.9)
        # add color bars
        # *rect* = [left, bottom, width, height]
        cax = plt.axes([0.85, 0.125, 0.015, 0.75])
        plt.colorbar(cax=cax)

        # show figure
        # plt.show()
        plt.draw()
        plt.pause(0.025)
        # plt.pause(15) 
Example #28
Source File: play.py    From DRL_DeliveryDuel with MIT License 5 votes vote down vote up
def callback(self, obs_t, obs_tp1, action, rew, done, info):
        points = self.data_callback(obs_t, obs_tp1, action, rew, done, info)
        for point, data_series in zip(points, self.data):
            data_series.append(point)
        self.t += 1

        xmin, xmax = max(0, self.t - self.horizon_timesteps), self.t

        for i, plot in enumerate(self.cur_plot):
            if plot is not None:
                plot.remove()
            self.cur_plot[i] = self.ax[i].scatter(range(xmin, xmax), list(self.data[i]))
            self.ax[i].set_xlim(xmin, xmax)
        plt.pause(0.000001) 
Example #29
Source File: 7_Transfer Learning Tutorial.py    From ML_CIA with MIT License 5 votes vote down vote up
def imshow(inp, title=None):
    """Imshow of Tensor."""
    inp = inp.numpy().transpose(1, 2, 0)
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    inp = std * inp + mean
    inp = np.clip(inp, 0, 1)
    plt.imshow(inp)
    if title is not None:
        plt.title(title)
    plt.pause(0.001)
    plt.show() 
Example #30
Source File: 5_Data Loading And Processing.py    From ML_CIA with MIT License 5 votes vote down vote up
def show_landmarks(image, landmarks):
    """Show image with landmarks
    :param image:
    :param landmarks:
    """
    plt.imshow(image)
    plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r')
    plt.pause(1)