Python matplotlib.pyplot.ion() Examples

The following are code examples for showing how to use matplotlib.pyplot.ion(). 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: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    MIT License 7 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 2
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 3
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_att_maps_epoch.py    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()

# Epochs 
Example 4
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_fmaps.py    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 5
Project: Attention-Gated-Networks   Author: ozan-oktay   File: visualise_attention.py    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 6
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    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 7
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 6 votes vote down vote up
def spy(Z, precision=0, marker=None, markersize=None, aspect='equal', **kwargs):
    ax = gca()
    hold = kwargs.pop('hold', None)
    # allow callers to override the hold state by passing hold=True|False
    washold = ax._hold

    if hold is not None:
        ax._hold = hold
        from matplotlib.cbook import mplDeprecation
        warnings.warn("The 'hold' keyword argument is deprecated since 2.0.",
                      mplDeprecation)
    try:
        ret = ax.spy(Z, precision, marker, markersize, aspect, **kwargs)
    finally:
        ax._hold = washold
    if isinstance(ret, cm.ScalarMappable):
        sci(ret)
    return ret

# just to be safe.  Interactive mode can be turned on without
# calling `plt.ion()` so register it again here.
# This is safe because multiple calls to `install_repl_displayhook`
# are no-ops and the registered function respect `mpl.is_interactive()`
# to determine if they should trigger a draw. 
Example 8
Project: infusion   Author: jiamings   File: infusion.py    MIT License 6 votes vote down vote up
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 64
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 1093
            self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20) 
Example 9
Project: infusion   Author: jiamings   File: infusion.py    MIT License 6 votes vote down vote up
def train(self, alpha=0.05, num_epochs=30):
        self.sess.run(tf.global_variables_initializer())
        batch_size = 128
        plt.ion()
        start_time = time.time()
        for epoch in range(0, num_epochs):
            batch_idxs = 545
            #self.visualize(alpha)
            for idx in range(0, batch_idxs):
                bx, _ = mnist.train.next_batch(batch_size)
                bz = self.sess.run(self.rand_init, feed_dict={self.x: bx, self.alpha: alpha})
                loss, _ = self.sess.run([self.loss, self.trainer], feed_dict={self.x: bx, self.alpha: alpha, self.init: bz})
                if idx % 100 == 0:
                    print("Epoch: [%2d] [%4d/%4d] time: %4.4f, " %
                          (epoch, idx, batch_idxs, time.time() - start_time), end='')
                    print("loss: %4.4f" % loss)
            self.visualize(alpha=0.0, batch_size=10, repeat=2)
        plt.ioff()
        self.visualize(alpha=0.0, batch_size=20, repeat=2) 
Example 10
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyplot.py    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 11
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 12
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 13
Project: pymaid   Author: schlegelp   File: core.py    GNU General Public License v3.0 6 votes vote down vote up
def _gen_svg_thumbnail(self):
        import matplotlib.pyplot as plt
        # Store some previous states
        prev_level = logger.getEffectiveLevel()
        prev_pbar = config.pbar_hide
        prev_int = plt.isinteractive()

        plt.ioff()  # turn off interactive mode
        logger.setLevel('WARNING')
        config.pbar_hide = True
        fig = plt.figure(figsize=(2, 2))
        ax = fig.add_subplot(111)
        fig, ax = self.plot2d(connectors=False, ax=ax)
        output = io.StringIO()
        fig.savefig(output, format='svg')

        if prev_int:
            plt.ion()  # turn on interactive mode
        logger.setLevel(prev_level)
        config.pbar_hide = prev_pbar
        _ = plt.clf()
        return output.getvalue() 
Example 14
Project: firefly-monte-carlo   Author: HIPS   File: toy_dataset.py    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 15
Project: fenics-topopt   Author: zfergus   File: gui.py    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 
Example 16
Project: fenics-topopt   Author: zfergus   File: gui.py    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 
Example 17
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 18
Project: black-widow   Author: BLQ-Software   File: run_interactive.py    MIT License 5 votes vote down vote up
def create_bw(settings=None, f=None):
    """Creates a command module and runs it.

    Parameters
    ----------
    settings : dict, optional
        A dictionary of settings (the default is None).
    f : string, optional
        The filename containing the network (the default is None).
    """

    # Turn interactive mode on for showing graph
    plt.ion()

    # Create new instance of command module
    b = BlackWidowInteractive()

    # Set command prompt
    b.prompt = "(blackwidow) "

    # Initialize command variables
    b.create_network(settings, f)

    # Install signal handler to stop network for Ctrl-C
    def signal_handler(signal, frame):
        b.do_stop("")

    signal.signal(signal.SIGINT, signal_handler)

    # Run the command module
    b.cmdloop(intro=spider.spider + "\nWelcome to BlackWidow") 
Example 19
Project: snn_global_pattern_induction   Author: chrhenning   File: mnist_data.py    Apache License 2.0 5 votes vote down vote up
def plot_sample(sample, interactive=False, file_name=None):
        """Plot a single MNIST sample.

        This method is thought to be helpful for evaluation and debugging
        purposes.

        Args:
            sample: An instance of the class Sample, that has been generated by
                the MNISTData class (it must contain the raw image data).
            interactive: Turn on interactive mode. Thus program will run in
                background while figure is displayed. The figure will be
                displayed until another one is displayed, the user closes it or
                the program has terminated. If this option is deactivated, the
                program will freeze until the user closes the figure.
            file_name: (optional) If a file name is provided, then the image
                will be written into a file instead of plotted to the screen.

        Returns:
        """
        plt.title('Label of shown sample: %d' % sample.label)
        plt.axis('off')
        if interactive:
            plt.ion()
        plt.imshow(sample.raw)
        if file_name is not None:
            plt.savefig(file_name, bbox_inches='tight')
        else:
            plt.show() 
Example 20
Project: GeoPy   Author: aerler   File: old_plots.py    GNU General Public License v3.0 5 votes vote down vote up
def hovmoellerPlot(varlist, clevs=None,cbls=None,title='',subplot=(),slices={},figargs={'figsize':(8,8)},**plotargs):
  import matplotlib.pylab as pyl    
  from pygeode.axis import XAxis, YAxis, TAxis
  from plotting.misc import multiPlot, sharedColorbar
  if not isinstance(varlist,list): varlist = [varlist]
  if not isinstance(clevs,list): clevs = [clevs]
  if not isinstance(cbls,list): cbls = [cbls]
  pyl.ioff() # non-interactive mode
  # construct figure and axes    
  f = pyl.figure(**figargs)    
  f.clf()
  # create zonal-mean variables
  titles = [var.name for var in varlist]
  plotlist = [var(**slices).mean(XAxis).transpose(YAxis,TAxis) for var in varlist] # latitude sliced
  # organize colorbar (cleanup arguments) 
  colorbar = plotargs.pop('colorbar',{})
  manualCbar = colorbar.pop('manual',False)
  if manualCbar: cbar = False
  else: cbar = colorbar 
  # set default margins  
  defaultMargins = {'left':0.065,'right':0.975,'bottom':0.05,'top':0.95,'wspace':0.05,'hspace':0.1}
  defaultMargins.update(plotargs.pop('margins',{}))
  ## make subplots
  (f,cf,subplot) = multiPlot(f=f,varlist=plotlist,titles=titles,clevs=clevs,cbls=cbls,subplot=subplot, #
                     colorbar=cbar,margins=defaultMargins,**plotargs)
  if title: f.suptitle(title,fontsize=14) 
  ## add common colorbar
  if manualCbar:
    f = sharedColorbar(f, cf, clevs, colorbar, cbls, subplot, defaultMargins)        
  # finalize
  pyl.draw(); # pyl.ion();
  return f 
Example 21
Project: ibmseti   Author: ibm-watson-data-lab   File: dsp.py    Apache License 2.0 5 votes vote down vote up
def compamp_to_spectrogram(compamp):
  '''
  Returns spectrogram, with each row containing the measured power spectrum for a XX second time sample.

  Using this function is shorthand for:
      aca = ibmseti.compamp.Compamp(raw_data)
      power = ibmseti.dsp.complex_to_power(aca.complex_data(), aca.header()['over_sampling'])
      spectrogram = ibmseti.dsp.reshape_to_2d(power)

  Example Usage: 
      import ibmseti
      import matplotlib.pyplot as plt
      plt.ion()
  
      aca = ibmseti.compamp.Compamp(raw_data)

      spectrogram = ibmseti.dsp.compamp_to_spectrogram(aca)
      time_bins = ibmseti.dsp.time_bins( aca.header() )
      freq_bins = ibmseti.dsp.frequency_bins( aca.header() )

      fig, ax = plt.subplots()
      ax.pcolormesh(freq_bins, time_bins, spectrogram)

      #Time is on the horizontal axis and frequency is along the vertical.

  '''

  power = complex_to_power(compamp.complex_data(), compamp.header()['over_sampling'])
  
  return reshape_to_2d(power) 
Example 22
Project: python-wavelet-transform   Author: bearicc   File: mycwt.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def cwt(x, scales, wname, bplot=False):
    coefs = sp.zeros((len(scales), len(x)))
    for i in range(0, len(scales)):
        if wname == 'bior2.6':
            length = min(13*scales[i], len(x))
            wavelet = bior2_6
        coefs[i-1, :] = convolve(x, wavelet(length, i), mode='same')
    
    if bplot:
        import matplotlib.pyplot as plt
        import matplotlib.gridspec as gridspec
        plt.ion()
        fig = plt.figure(num=None, figsize=(14,5), dpi=100, facecolor='w', edgecolor='k')
        plt.clf()
        gs = gridspec.GridSpec(3, 1)
        ax1 = fig.add_subplot(gs[0,0])
        ax1.plot(x,'b-')
    
        ax2 = fig.add_subplot(gs[1:,0])
        im = ax2.imshow(coefs[::-1,:], extent=[0, len(x), scales[0], scales[-1]], aspect='auto', cmap='jet')
        ax2.invert_yaxis()
        ax2.set_xlabel('t')
        ax2.set_ylabel('scale')
        l, b, w, h = ax2.get_position().bounds
        cax = fig.add_axes([l+w+0.01, b, 0.02, h])
        plt.colorbar(im, cax=cax)
        plt.suptitle('cwt by python')
        plt.draw()
        plt.show(block=True)
            
    return coefs 
Example 23
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 24
Project: VRPTW-ga   Author: shayan-ys   File: report.py    MIT License 5 votes vote down vote up
def __init__(self, run_name: str):
        if ga_params.draw_plot:
            plt.ion()
            self.fig, self.subplot = plt.subplots()
            self.fig_node_connector, self.subplot2 = plt.subplots()
        if ga_params.export_spreadsheet:
            self.init_spreadsheet(run_name=run_name) 
Example 25
Project: pysat   Author: pysat   File: test_ssnl_plot.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_scatterplot_w_ion(self):
        """Check if scatterplot generates and resets to interactive mode"""

        plt.ion()
        figs = plot.scatterplot(self.testInst, 'longitude', 'latitude',
                                'slt', [0.0, 24.0])

        axes = figs[0].get_axes()
        assert len(figs) == 1
        assert len(axes) == 3
        assert mpl.is_interactive() 
Example 26
Project: esys-pbi   Author: fsxfreak   File: matplotlib_standalone.py    MIT License 5 votes vote down vote up
def __init__(self, size=(600,350)):
    self.running = True
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Streaming Live EMG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('Volts')
    plt.show() 
Example 27
Project: esys-pbi   Author: fsxfreak   File: graph_matplotlib.py    MIT License 5 votes vote down vote up
def __init__(self, size=(600,350)):
    streams = resolve_byprop('name', 'bci', timeout=2.5)
    try:
      self.inlet = StreamInlet(streams[0])
    except IndexError:
      raise ValueError('Make sure stream name=bci is opened first.')
   
    self.running = True
    
    self.ProcessedSig = []
    self.SecondTimes = []
    self.count = -1
    self.sampleCount = self.count 
    self.maximum = 0
    self.minimum = 0

    plt.ion()
    plt.hold(False)     
    self.lineHandle = plt.plot(self.SecondTimes, self.ProcessedSig)
    plt.title("Live Stream EEG Data")
    plt.xlabel('Time (s)')
    plt.ylabel('mV')
    #plt.autoscale(True, 'y', tight = True)
    plt.show()
    #while(1):
    #secondTimes.append(serialData[0])                         #add time stamps to array 'timeValSeconds'
    #floatSecondTimes.append(float(serialData[0])/1000000)     # makes all second times into float from string
    
    #processedSig.append(serialData[6])                           #add processed signal values to 'processedSig'
    #floatProcessedSig.append(float(serialData[6])) 
Example 28
Project: LaserTOF   Author: kyleuckert   File: pyplot.py    MIT License 5 votes vote down vote up
def ion():
    'Turn interactive mode on.'
    matplotlib.interactive(True)
    install_repl_displayhook() 
Example 29
Project: chemtype2   Author: bradleyemi   File: ocr_classifier.py    MIT License 5 votes vote down vote up
def get_training_examples(path, n_per_size=5):
  for i, image in enumerate(os.listdir(path)):
    if image[len(image)-6:len(image)] not in TRAIN_IMAGES:
      continue
    print image
    im = cv2.imread(path+image,0)
    ret,im = cv2.threshold(im,100,255,cv2.THRESH_BINARY_INV)
    height,width = im.shape
    j = 0
    for size in PYRAMID_SIZES:
      print size
      n_subs = 0
      while n_subs < n_per_size:
        x = random.choice(range(0,width-size))
        y = random.choice(range(0,height-size))
        sub = im[y:y+size, x:x+size]
        if np.count_nonzero(sub) == 0:
            continue
        plt.imshow(sub, cmap='Greys_r')
        plt.ion()
        plt.show()
        letter = raw_input("Letter (x for none)--> ")
        plt.close()
        if letter == 'x':
          cv2.imwrite('train/none/' + image + '_' + str(j) + '.png', sub)
          n_subs += 1
          j += 1
        elif letter in ['h','o','r', 'n']:
          print letter
          cv2.imwrite('train/' + letter + '/' + image + '_' + str(j) + '.png', sub)
          n_subs += 1
          j += 1
        else:
          print "letter not recognized"

#for path in PATHS:
#  get_training_examples(path)

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_svm/py_svm_opencv/py_svm_opencv.html 
Example 30
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def show():
        # is_interactive = matplotlib.is_interactive()
        pyplot.ion()
        pyplot.show()
        # if we call now matplotlib.interactive(True), the console is
        # blocked 
Example 31
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def _finalize_plotting(self):
        pyplot.ion()
        pyplot.draw()  # update "screen"
        pyplot.show()  # show figure
        # matplotlib.interactive(interactive_status)
        pyplot.rcParams['font.size'] = self.original_fontsize 
Example 32
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot(self, plot_cmd=None, tf=lambda y: y):
        """plot the data we have, return ``self``"""
        if not plot_cmd:
            plot_cmd = self.plot_cmd
        colors = 'bgrcmyk'
        pyplot.hold(False)
        res = self.res

        flatx, flatf = self.flattened()
        minf = np.inf
        for i in flatf:
            minf = min((minf, min(flatf[i])))
        addf = 1e-9 - minf if minf <= 1e-9 else 0
        for i in sorted(res.keys()):  # we plot not all values here
            if isinstance(i, int):
                color = colors[i % len(colors)]
                arx = sorted(res[i].keys())
                plot_cmd(arx, [tf(np.median(res[i][x]) + addf) for x in arx], color + '-')
                pyplot.text(arx[-1], tf(np.median(res[i][arx[-1]])), i)
                pyplot.hold(True)
                plot_cmd(flatx[i], tf(np.array(flatf[i]) + addf), color + 'o')
        pyplot.ylabel('f + ' + str(addf))
        pyplot.draw()
        pyplot.ion()
        pyplot.show()
        # raw_input('press return')
        return self 
Example 33
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 34
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 35
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools (Deokwoo Jung's conflicted copy 2014-07-01).py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-'):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(diff(data_x.__dict__[key].val))
            title(key+'- Differential',fontsize='small')
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            title(key,fontsize='small')
        
        plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
    
    plt.xticks(fontsize='small')
    plt.yticks(fontsize='small')
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 36
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 37
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 38
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 39
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 40
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 41
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 42
Project: DDEA-DEV   Author: TinyOS-Camp   File: data_tools.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_data_x(data_x,stype='raw',smark='-',fontsize='small',xpos=0.5):
    plt.ioff()
    fig=plt.figure(figsize=(20.0,10.0))    
    sensor_names_x=data_x.__dict__.keys()
    num_plots=len(sensor_names_x)
    for k ,key in enumerate(sensor_names_x):
        plt.subplot(num_plots,1,k+1)
        if stype=='diff':
            t_=data_x.__dict__[key].time[1:]
            val_=abs(np.diff(data_x.__dict__[key].val))
            plt.title(key+'- Differential',fontsize=fontsize,x=xpos)
        else:
            t_=data_x.__dict__[key].time 
            val_=data_x.__dict__[key].val
            plt.title(key,fontsize=fontsize,x=xpos)
        
        plt.plot(t_,val_,smark)
        mn_=min(val_);mx_=max(val_)
        plt.ylim([mn_-0.1*abs(mn_),mx_+0.1*abs(mx_)])
        plt.xticks(fontsize=fontsize)
        plt.yticks(fontsize=fontsize)
        plt.tick_params(labelsize=fontsize)
    png_name=str(uuid.uuid4().get_hex().upper()[0:6])
    fig.savefig(fig_dir+png_name+'.png', bbox_inches='tight')
    plt.close()
    plt.ion()
    return png_name 
Example 43
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyplot.py    MIT License 5 votes vote down vote up
def ion():
    """Turn the interactive mode on."""
    matplotlib.interactive(True)
    install_repl_displayhook() 
Example 44
Project: Deep-reinforcement-learning-with-pytorch   Author: sweetice   File: DQN.py    MIT License 5 votes vote down vote up
def main():
    dqn = DQN()
    episodes = 400
    print("Collecting Experience....")
    reward_list = []
    plt.ion()
    fig, ax = plt.subplots()
    for i in range(episodes):
        state = env.reset()
        ep_reward = 0
        while True:
            env.render()
            action = dqn.choose_action(state)
            next_state, _ , done, info = env.step(action)
            x, x_dot, theta, theta_dot = next_state
            reward = reward_func(env, x, x_dot, theta, theta_dot)

            dqn.store_transition(state, action, reward, next_state)
            ep_reward += reward

            if dqn.memory_counter >= MEMORY_CAPACITY:
                dqn.learn()
                if done:
                    print("episode: {} , the episode reward is {}".format(i, round(ep_reward, 3)))
            if done:
                break
            state = next_state
        r = copy.copy(reward)
        reward_list.append(r)
        ax.set_xlim(0,300)
        #ax.cla()
        ax.plot(reward_list, 'g-', label='total_loss')
        plt.pause(0.001) 
Example 45
Project: Deep-reinforcement-learning-with-pytorch   Author: sweetice   File: REINFORCE_with_Baseline.py    MIT License 5 votes vote down vote up
def plot(live_time):
    plt.ion()
    plt.grid()
    plt.plot(live_time, 'g-')
    plt.xlabel('running step')
    plt.ylabel('live time')
    plt.pause(0.000001) 
Example 46
Project: ibllib   Author: int-brain-lab   File: smooth.py    MIT License 5 votes vote down vote up
def smooth_demo():

    t = np.linspace(-4, 4, 100)
    x = np.sin(t)
    xn = x + np.random.randn(len(t)) * 0.1

    ws = 31

    plt.subplot(211)
    plt.plot(np.ones(ws))

    windows = ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']

    for w in windows[1:]:
        eval('plt.plot(np.' + w + '(ws) )')

    plt.axis([0, 30, 0, 1.1])

    plt.legend(windows)
    plt.title("The smoothing windows")
    plt.subplot(212)
    plt.plot(x)
    plt.plot(xn)
    for w in windows:
        plt.plot(rolling_window(xn, 10, w))
    lst = ['original signal', 'signal with noise']
    lst.extend(windows)

    plt.legend(lst)
    plt.title("Smoothing a noisy signal")
    plt.ion() 
Example 47
Project: ehtplot   Author: liamedeiros   File: figure.py    GNU General Public License v3.0 5 votes vote down vote up
def __call__(self, **kwargs):
        """Figure realizer

        The Figure class only keeps track of a root panel.  It does
        not contain an actual matplotlib Figure instance.  Whenever a
        figure needs to be created, Figure creates a new matplotlib
        Figure in order to drew/rendered/realized the figure.

        Args:

            **kwargs (dict): Arbitrary Figure-specific keyworded
                arguments that are used to construct the matplotlib
                Figure.

        """
        kwprops = merge_dict(self.kwprops, kwargs)
        style   = kwprops.pop('style')

        with mpl.rc_context():
            mpl.rcdefaults()
            plt.style.use(style)

            imode = mpl.is_interactive()
            if imode:
                plt.ioff()

            fig = plt.figure(**kwprops)
            ax  = newaxes(fig)
            yield fig, ax

            if imode:
                plt.ion() 
Example 48
Project: grass_pytorch   Author: kevin-kaixu   File: dynamicplot.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, title, xdata, ydata):
        if len(xdata) == 0:
            return
        plt.ion()
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title(title, color='C0')
        self.ax.set_xlim(xdata[0], xdata[-1])
        self.yline = {}
        for label, data, idx in zip(ydata.keys(), ydata.values(), range(len(ydata))):
            if len(xdata) != len(data):
                print('DynamicPlot::Error: Dimensions of x- and y-data not the same (skipping).')
                continue
            self.yline[label], = self.ax.plot(xdata, data, 'C{}'.format((idx+1)%9), label=" ".join(label.split('_')))
        self.ax.legend() 
Example 49
Project: grass_pytorch   Author: kevin-kaixu   File: dynamicplot.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, title, xdata, ydata):
        if len(xdata) == 0:
            return
        plt.ion()
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)
        self.ax.set_title(title, color=u'C0')
        self.ax.set_xlim(xdata[0], xdata[-1])
        self.yline = {}
        for label, data, idx in izip(ydata.keys(), ydata.values(), xrange(len(ydata))):
            if len(xdata) != len(data):
                print u'DynamicPlot::Error: Dimensions of x- and y-data not the same (skipping).'
                continue
            self.yline[label], = self.ax.plot(xdata, data, u'C{}'.format((idx+1)%9), label=u" ".join(label.split(u'_')))
        self.ax.legend() 
Example 50
Project: hierarchical-sparse-coding   Author: sbrodeur   File: modeling.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, k, windowSize, algorithm='kmean', verbose=False):
        self.k = k
        self.windowSize = windowSize
        self.algorithm = algorithm
 
        if verbose:
            plt.ion()
            self.fig = plt.figure(figsize=(8,8), facecolor='white', frameon=True)
        else:
            self.fig = None
        self.verbose = verbose 
Example 51
Project: hierarchical-sparse-coding   Author: sbrodeur   File: modeling.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, verbose=False):

        if verbose:
            plt.ion()
            self.fig = plt.figure(figsize=(12,8), facecolor='white', frameon=True)
        else:
            self.fig = None
        self.verbose = verbose 
Example 52
Project: Visualization-of-sort-algorithms   Author: ForeverPs   File: SORT.py    MIT License 5 votes vote down vote up
def __init__(self):
		self.img = []
		self.fig = plt.figure()
		plt.ion()
		self.count = 0
		self.path = 'sp/'
		if not os.path.lexists(self.path):
			os.mkdir(self.path) 
Example 53
Project: classification-of-encrypted-traffic   Author: SalikLP   File: pca.py    MIT License 5 votes vote down vote up
def plotvarianceexp(pca, num_comp):
    # plt.ion()
    rho = pca.explained_variance_ratio_
    rhosum = np.empty(len(rho))
    for i in range(1, len(rho) + 1):
        rhosum[i - 1] = np.sum(rho[0:i])
    ind = np.arange(num_comp)
    width = 0.35
    opacity = 0.8
    fig, ax = plt.subplots()
    ax.set_ylim(0, 1.1)
    # Variance explained by single component
    bars1 = ax.bar(ind, rho[0:num_comp], width, alpha=opacity, color="xkcd:blue", label='Single')
    # Variance explained by cummulative component
    bars2 = ax.bar(ind + width, rhosum[0:num_comp], width, alpha=opacity, color="g", label='Cummulative')
    # add some text for labels, title and axes ticks
    ax.set_ylabel('Variance Explained', fontsize=16)
    # ax.set_title('Variance Explained by principal components')
    ax.set_xticks(ind + width / 2)

    labels = ["" for x in range(num_comp)]
    for k in range(0, num_comp):
        labels[k] = ('$v{0}$'.format(k + 1))
    ax.set_xticklabels(labels, fontsize=16)
    ax.legend(fontsize=16)
    autolabel(bars2, ax)
    plt.yticks(fontsize=16)
    plt.draw() 
Example 54
Project: Roy-Coinbase-Trader   Author: gincarbone   File: botindicators.py    GNU General Public License v3.0 5 votes vote down vote up
def plot(self, prices, emaSlow, emaFast):
		
		#z = [1.1, 1.2, 1.3]

		#times = pd.date_range('2015-10-06', periods=500, freq='5sec')
		try:
			os.remove("operate.png")
		except OSError:
			pass

		plt.xlabel("Data Time")
		plt.ylabel("Values")
		plt.title("A test graph")

		#plt.ion()
		#plt.clear()

		plt.figure(1)
		plt.subplot(211)
		plt.plot(prices)

		plt.subplot(212)
		plt.plot(emaSlow, 'b--')

		#plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),)

		plt.subplot(212)
		plt.plot(emaFast, 'r--')

		plt.xlabel("Data Time")
		plt.ylabel("Values")
		plt.title("A test graph")
		#plt.savefig("operate.png")
		plt.draw()
		plt.show() 
Example 55
Project: PyFluxPro   Author: OzFlux   File: pfp_cpd.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_hist(S,mu,sig,crit_t,year,d):
    if len(S)<=1:
        logger.info(" plot_hist: 1 or less values in S for year "+str(year)+", skipping histogram ...")
        return
    S=S.reset_index(drop=True)
    x_low=S.min()-0.1*S.min()
    x_high=S.max()+0.1*S.max()
    x=np.linspace(x_low,x_high,100)
    if d["show_plots"]:
        plt.ion()
    else:
        plt.ioff()
    fig=plt.figure(figsize=(12,8))
    #fig.patch.set_facecolor('white')
    #plt.hist(S,normed=True)
    plt.hist(S, density=True)
    plt.xlim(x_low,x_high)
    plt.xlabel(r'u* ($m\/s^{-1}$)',fontsize=16)
    if np.isfinite(mu) and np.isfinite(sig):
        plt.plot(x,stats.norm.pdf(x,mu,sig),color='red',linewidth=2.5,label='Gaussian PDF')
        plt.axvline(x=mu-sig*crit_t,color='black',linestyle='--')
        plt.axvline(x=mu+sig*crit_t,color='black',linestyle='--')
        plt.axvline(x=mu,color='black',linestyle='dotted')
    txt='mean u*='+str(mu)
    ax=plt.gca()
    props = dict(boxstyle='round,pad=1', facecolor='white', alpha=0.5)
    plt.text(0.4,0.1,txt,bbox=props,fontsize=12,verticalalignment='top',transform=ax.transAxes)
    plt.legend(loc='upper left')
    plt.title(str(year)+'\n')
    plot_out_name=os.path.join(d["plot_path"],d["site_name"]+'_CPD_'+str(year)+'.png')
    fig.savefig(plot_out_name)
    if d["show_plots"]:
        plt.draw()
        plt.ioff()
    else:
        plt.ion()
    #if d["call_mode"].lower()!="interactive": plt.close(fig)

# Plot normalised slope parameters to identify outlying years and output to
# results folder - user can discard output for that year 
Example 56
Project: PyFluxPro   Author: OzFlux   File: pfp_cpd.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def plot_slopes(df,d):
    df=df.reset_index(drop=True)
    if d["show_plots"]:
        plt.ion()
    else:
        plt.ioff()
    fig=plt.figure(figsize=(12,8))
    #fig.patch.set_facecolor('white')
    plt.scatter(df['norm_a1_median'],df['norm_a2_median'],s=80,edgecolors='blue',facecolors='none')
    plt.xlim(-4,4)
    plt.ylim(-4,4)
    plt.xlabel('$Median\/normalised\/ a^{1}$',fontsize=16)
    plt.ylabel('$Median\/normalised\/ a^{2}$',fontsize=16)
    plt.title('Normalised slope parameters \n')
    plt.axvline(x=1,color='black',linestyle='dotted')
    plt.axhline(y=0,color='black',linestyle='dotted')
    plot_out_name=os.path.join(d["plot_path"],d['site_name']+"_CPD_slopes.png")
    fig.savefig(plot_out_name)
    if d["show_plots"]:
        plt.draw()
        plt.ioff()
    else:
        plt.ion()
    #if d["call_mode"].lower()!="interactive": plt.close(fig)

#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
# Quality control within bootstrap 
Example 57
Project: KinMSpy   Author: TimothyADavis   File: KinMS_testsuite.py    MIT License 5 votes vote down vote up
def KinMStest_expdisk_gasgrav(scalerad=5.,inc=45.,gasmass=5e10):
# ;;;;;;;;;;;
# ;
# ; A test procedure to demonstrate the KinMS code, and check if it
# ; works on your system. This procedure demonstrates how to create a simulation of an
# ; exponential disk of molecular gas, including the effect of the potential of the gas on its own rotation.
# ; The user can input values for the scalerad and inc variables, and the procedure will 
# ; the create the simulation and display it to screen. 
# ;
# ;  INPUTS:
# ;       Scalerad -    Scale radius for the exponential disk (arcseconds)
# ;       Inc      -    Inclination to project the disk (degrees)
# ;       Gasmass  -    Total mass of the gas (solar masses)
# ;
# ;;;;;;;;;;;

# ;;;; Setup cube parameters ;;;;
    xsize=64
    ysize=64
    vsize=1400
    cellsize=1
    dv=10
    beamsize=[4.,4.,0.]
    nsamps=5e5
    dist=16.5 # Mpc

# ;;;; Set up exponential disk SB profile/velocity ;;;;
    x=np.arange(0,100,0.1)
    fx = np.exp(-x/scalerad)
    velfunc = interpolate.interp1d([0.0,0.5,1,3,500],[0,50,100,210,210], kind='linear')
    vel=velfunc(x)
# ;;;;

# ;;;; Simulate and plot ;;;;
    plt.ion()
    f=KinMS(xsize,ysize,vsize,cellsize,dv,beamsize,inc,sbProf=fx,sbRad=x,velRad=x,velProf=vel,nSamps=nsamps,intFlux=30.,posAng=270,gasSigma=10.)
    plot=makeplots(f,xsize,ysize,vsize,cellsize,dv,beamsize,posang=270.,title="Without Potential of Gas")
        

    f=KinMS(xsize,ysize,vsize,cellsize,dv,beamsize,inc,sbProf=fx,sbRad=x,velRad=x,velProf=vel,nSamps=nsamps,intFlux=30.,posAng=270,gasSigma=10.,gasGrav=np.array([gasmass,dist]))
    plot=makeplots(f,xsize,ysize,vsize,cellsize,dv,beamsize,posang=270.,title="With Potential of Gas Included") 
Example 58
Project: crappy   Author: LaboratoireMecaniqueLille   File: displayer.py    GNU General Public License v2.0 5 votes vote down vote up
def begin_mpl(self):
    plt.ion()
    fig = plt.figure()
    fig.add_subplot(111) 
Example 59
Project: SEVN   Author: mweiss17   File: SEVN_base.py    MIT License 5 votes vote down vote up
def graph_plotting(self, figname):
        plt.ion()
        self.fig, self.ax = plt.subplots(nrows=1, ncols=1)
        self.pos = {k: v.get('coords')[0:2] for k, v in self.G.nodes(data=True)}
        # nx.draw(self.G, pos, node_color='r', node_size=1)
        nodelist = list(self.G)
        self.xy = np.asarray([self.pos[v] for v in nodelist])
        self.corners = np.asarray([
            self.pos[node]
            for node in list(self.G)
            if node in self.coord_df[self.coord_df.type == 'intersection'].index
        ])
        self.streets = np.asarray([
            self.pos[node] for node in list(self.G) if node in self.coord_df[
                self.coord_df.type == 'street_segment'].index
        ])
        edgelist = list(self.G.edges())
        edge_pos = np.asarray([
            (self.pos[e[0]], self.pos[e[1]]) for e in edgelist
        ])
        self.edge_collection = LineCollection(edge_pos)
        self.edge_collection.set_zorder(1)  # edges go behind nodes
        self.ax.scatter(self.corners[:, 0], self.corners[:, 1], c='#fde724')
        self.ax.scatter(self.streets[:, 0], self.streets[:, 1], c='#79d151')
        self.ax.add_collection(self.edge_collection)
        plt.savefig(figname) 
Example 60
Project: squeezenet-keras   Author: chasingbob   File: visual_callbacks.py    MIT License 5 votes vote down vote up
def on_train_begin(self, logs={}):
        self.acc = []
        self.val_acc = []
        self.loss = []
        self.val_loss = []
        self.epoch_count = 0
        plt.ion()
        plt.show() 
Example 61
Project: squeezenet-keras   Author: chasingbob   File: visual_callbacks.py    MIT License 5 votes vote down vote up
def __init__(self, X_val, Y_val, classes, normalize=False, cmap=plt.cm.Blues, title='Confusion Matrix'):
        self.X_val = X_val
        self.Y_val = Y_val
        self.title = title
        self.classes = classes
        self.normalize = normalize
        self.cmap = cmap
        plt.ion()
        plt.show() 
Example 62
Project: squeezenet-keras   Author: chasingbob   File: visual_callbacks.py    MIT License 5 votes vote down vote up
def __init__(self, cmap=plt.cm.Blues, title='Confusion Matrix'):
        plt.ion()
        plt.show()
        self.title = title
        self.cmap = cmap 
Example 63
Project: industry-classifier   Author: xiedidan   File: plot.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_leakage(image_path, result):
    image = Image.open(image_path)
    image = transforms.functional.vflip(image)
    image = transforms.functional.to_tensor(image).numpy()
    image = np.transpose(image, (2, 1, 0))

    color = 'red'
    if result == 0:
        result = u'OK'
        color = 'lime'
    else:
        result = u'Leak'

    plt.ion()
    
    fig = plt.gcf()
    fig.set_size_inches(18.5, 10.5)

    plt.imshow(image)

    # plt.text(100, 500, result, color=color, fontsize=96)
    plt.xlabel(result, color=color, fontsize=96)

    plt.tight_layout()
    plt.ioff()

    plt.show() 
Example 64
Project: snn_global_pattern_induction   Author: chrhenning   File: seven_segment_data.py    Apache License 2.0 4 votes vote down vote up
def plot_sample(sample, interactive=False, file_name=None):
        """Plot a single 7segment sample.

        This method is thought to be helpful for evaluation and debugging
        purposes.

        Args:
            sample: An instance of the class Sample, that has been generated by
                the SevenSegmentData class (it must contain the raw states
                data).
            interactive: Turn on interactive mode. Thus program will run in
                background while figure is displayed. The figure will be
                displayed until another one is displayed, the user closes it or
                the program has terminated. If this option is deactivated, the
                program will freeze until the user closes the figure.
            file_name: (optional) If a file name is provided, then the image
                will be written into a file instead of plotted to the screen.

        Returns:
        """
        # Define the coordinates of a line for each LED.
        led_coords = {
            0: [(.25,1.),(.75,1.)],
            1: [(.25,.5),(.25,1.)],
            2: [(.75,.5),(.75,1.)],
            3: [(.25,.5),(.75,.5)],
            4: [(.25,0.),(.25,.5)],
            5: [(.75,0.),(.75,.5)],
            6: [(.25,0.),(.75,0.)]
        }

        # Add LED lines that are active in current sample.
        leds = []
        for i, s in enumerate(sample.raw):
            if s:
               leds.append(led_coords[i])

        if interactive:
            plt.ion()
        lc = col.LineCollection(leds, linewidths=2)

        fig, ax = plt.subplots()
        ax.add_collection(lc)
        ax.set_xlim(-0.1, 1.1)
        ax.set_ylim(-0.1, 1.1)
        ax.set_axis_off()

        plt.title('Label of shown sample: %d' % sample.label)

        if file_name is not None:
            plt.savefig(file_name, bbox_inches='tight')
        else:
            plt.show() 
Example 65
Project: GeoPy   Author: aerler   File: old_plots.py    GNU General Public License v3.0 4 votes vote down vote up
def surfacePlot(varlist, times=None, clevs=None,cbls=None,title='',axTitles=True,subplot=(),slices={},figargs={'figsize':(10,8)},**plotargs):
  import matplotlib.pylab as pyl
  from plotting.misc import multiPlot, sharedColorbar
  if not isinstance(varlist,list): varlist = [varlist]
  if not isinstance(times,list): times = [times]
  if not isinstance(clevs,list): clevs = [clevs]
  if not isinstance(cbls,list): cbls = [cbls]  
  pyl.ioff() # non-interactive mode
  # construct figure and axes    
  f = pyl.figure(**figargs)    
  f.clf()
  ## handle multiplot meta data
  if len(varlist)==1: 
    # plot single variable, possibly multiple times
    titles = []; plotlist = [];
    for time in times: 
      if time and axTitles: titles.append('time '+str(time))
      else: titles.append('')
      if varlist[0].hasaxis('time'): slices['time'] = time
      plotlist.append(varlist[0](**slices))
  else: 
    # plot multiple variables side-by-side, each time-step 
    if not subplot: subplot = (len(times),len(varlist))
    titles = []; plotlist = []; 
    for time in times:
      for var in varlist:
        if axTitles: titles.append(var.name+', time '+str(time))
        else: titles.append('')
        if var.hasaxis('time'): slices['time'] = time
        plotlist.append(var(**slices)) # sliced for time and latitude
  # expansion of other lists
  clevlist = clevs*len(times) # create contour level list for each plot
  cbllist = cbls*len(times) # create contour level list for each plot
  # organize colorbar (cleanup arguments) 
  colorbar = plotargs.pop('colorbar',{})
  manualCbar = colorbar.pop('manual',False)
  if manualCbar: cbar = False
  else: cbar = colorbar 
  # set default margins  
  defaultMargins = {'left':0.065,'right':0.975,'bottom':0.05,'top':0.95,'wspace':0.025,'hspace':0.1}
  defaultMargins.update(plotargs.pop('margins',{}))
  ## draw (sub-)plots  
  (f,cf,subplot) = multiPlot(f=f,varlist=plotlist,titles=titles,clevs=clevlist,cbls=cbllist, #
                     subplot=subplot,colorbar=cbar,margins=defaultMargins,**plotargs)  
  if title: f.suptitle(title,y=defaultMargins['top'],fontsize=plotargs.get('fontsize',12)+2) 
  ## add common colorbar
  if manualCbar:
    if len(varlist)==1: subplot = (1,1) # need only one colorbar, reference to first axes
    sharedColorbar(f, cf, clevs, colorbar, cbls, subplot, defaultMargins)   
  # finalize
  pyl.draw(); # pyl.ion(); 
  return f

## generates a hovmoeller plot of the given variables (with multiplot support) 
Example 66
Project: DeepQMC   Author: NLESC-JCER   File: plot_potential.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, wf, domain, res=51, sol=None,
                 plot_weight=False, plot_grad=False, save=None):
        '''Dynamic plot of a 1D-wave function during the optimization

        Args:
            wf : wave function object
            domain : dict containing the boundary
            res : number of points in each direction
            sol : callabale solution of the problem
            plot_weight : plot the weight of the fc
            plot_grad : plot the grad of the weight
        '''
        plt.ion()
        self.wf = wf
        self.res = res
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

        self.plot_weight = plot_weight
        self.plot_grad = plot_grad
        self.save = save
        self.iter = 0

        self.POS = Variable(torch.linspace(
            domain['min'], domain['max'], res).view(res, 1))
        pos = self.POS.detach().numpy().flatten()

        if callable(sol):
            v = sol(self.POS).detach().numpy()
            self.ax.plot(pos, v, color='#b70000', linewidth=4, linestyle='--',
                         label='solution')

        vpot = wf.nuclear_potential(self.POS).detach().numpy()
        self.ax.plot(pos, vpot, color='black', linestyle='--')

        vp = self.wf(self.POS).detach().numpy()
        vp /= np.max(vp)
        self.lwf, = self.ax.plot(pos, vp, linewidth=2, color='black')

        if self.plot_weight:
            self.pweight, = self.ax.plot(self.wf.rbf.centers.detach().numpy(),
                                         self.wf.fc.weight.detach().numpy().T,
                                         'o')
        if self.plot_grad:
            if self.wf.fc.weight.requires_grad:
                self.pgrad, = self.ax.plot(self.wf.rbf.centers.detach().numpy(),
                                           np.zeros(self.wf.ncenter), 'X')

        self.ax.set_ylim((np.min(vpot), 1))
        plt.grid()
        plt.draw()
        self.fig.canvas.flush_events()

        if self.save is not None:
            self._save_pic() 
Example 67
Project: DeepQMC   Author: NLESC-JCER   File: plot_potential.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, wf, domain, res, pot=False, kinetic=False, sol=None,
                 save=None):
        '''Dynamic plot of a 2D-wave function during the optimization

        Args:
            wf : wave function object
            domain : dict containing the boundary
            res : number of points in each direction
            sol : callabale solution of the problem
        '''
        plt.ion()

        self.wf = wf
        self.res = res
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, projection='3d')
        self.save = save
        self.iter = 0

        points = regular_mesh_2d(xmin=domain['min'], xmax=domain['max'],
                                 ymin=domain['min'], ymax=domain['max'],
                                 nx=res[0], ny=res[1])

        self.POS = Variable(torch.tensor(points))
        self.POS.requires_grad = True

        pos = self.POS.detach().numpy()
        self.xx = pos[:, 0].reshape(res[0], res[1])
        self.yy = pos[:, 1].reshape(res[0], res[1])

        if callable(sol):
            vs = sol(self.POS).view(self.res[0], self.res[1]).detach().numpy()
            vs /= np.linalg.norm(vs)
            self.ax.plot_wireframe(self.xx, self.yy, vs,
                                   color='black', linewidth=1)

        if pot:
            vs = wf.nuclear_potential(self.POS).view(
                self.res[0], self.res[1]).detach().numpy()
            self.ax.plot_wireframe(self.xx, self.yy, vs,
                                   color='red', linewidth=1)

        if kinetic:
            vs = wf.kinetic_energy(self.POS).view(
                self.res[0], self.res[1]).detach().numpy()
            self.ax.plot_wireframe(
                self.xx, self.yy, 10*vs, color='red', linewidth=1)

        self.vals = self.wf(self.POS).view(
            self.res[0], self.res[1]).detach().numpy()

        self.surf = self.ax.plot_surface(
            self.xx, self.yy, self.vals, rstride=1, cstride=1,
            cmap=cm.coolwarm, alpha=0.75, color='black', linewidth=2,
            antialiased=False)
        plt.draw()
        self.fig.canvas.flush_events() 
Example 68
Project: chemtype2   Author: bradleyemi   File: chemtype.py    MIT License 4 votes vote down vote up
def all_template_match(templates, template_names, img, tol=0.6, display=False):
  template_dict = {}
  all_boxes = []
  corresponding_templates = []
  for i,template in enumerate(templates):
    boxes = template_match(template, img, threshold=tol)
    all_boxes += boxes
    for j in range(len(boxes)):
      corresponding_templates.append(i)
    #template_dict[template_names[i]] = all_boxes
  keep = [1 for box in all_boxes]
  for i,box1 in enumerate(all_boxes):
    for j in range(i+1,len(all_boxes)):
      box2 = all_boxes[j]
      center1x = (box1[0]+box1[1])/2
      center1y = (box1[2]+box1[3])/2
      center2x = (box2[0]+box2[1])/2
      center2y = (box2[2]+box2[3])/2
      if inside_box(center1x,center1y,box2) or inside_box(center2x,center2y,box1):
        score1 = box1[4]
        score2 = box2[4]
        if score1 >= score2:
          keep[j] = 0
        else:
          keep[i] = 0
  for i, template in enumerate(templates):
    template_dict[template_names[i]] = [all_boxes[k] for k in range(len(all_boxes)) \
      if corresponding_templates[k] == i and keep[k] == 1]
  acc = 0
  if display:
    im = cv2.imread(img,0)
    ret, im = cv2.threshold(im, THRESH_VAL, 255, cv2.THRESH_BINARY_INV)
    im = cv2.copyMakeBorder(im,BORDER,BORDER,BORDER,BORDER,cv2.BORDER_CONSTANT,0)
    im = cv2.GaussianBlur(im, (LINE_WIDTH/2, LINE_WIDTH/2), LINE_WIDTH/2)
    im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB)
    for key in template_dict.keys():
      if len(template_dict[key]) != 0:
        color = COLOR_DICT_OCR[key]
        for box in template_dict[key]:
          cv2.rectangle(im,(box[0],box[2]),(box[1],box[3]),color=color, thickness=5)
    plt.imshow(im)
    plt.ion()
    plt.show()
    correct = raw_input("Is this correct? (y/n)--> ")
    plt.close()
    if correct == 'y':
      acc = 1
  return template_dict, acc 
Example 69
Project: chemtype2   Author: bradleyemi   File: chemtype.py    MIT License 4 votes vote down vote up
def corner_detector(img, template_dict, max_corners = 20, display=True, rect_w=6):
  max_rgb_val = 255
  im = cv2.imread(img,0)
  # threshold the image to make binary
  ret,im = cv2.threshold(im,THRESH_VAL,255,cv2.THRESH_BINARY_INV)
  im = cv2.copyMakeBorder(im,BORDER,BORDER,BORDER,BORDER,cv2.BORDER_CONSTANT,0)
  with open(template_dict) as handle:
    bbox_dict = pickle.load(handle)
  for k in bbox_dict.keys():
    for bbox in bbox_dict[k]:
      x0 = bbox[0]
      x1 = bbox[1]
      y0 = bbox[2]
      y1 = bbox[3]
      im[y0:y1, x0:x1] = np.zeros((y1-y0,x1-x0))
  im = cv2.GaussianBlur(im,(LINE_WIDTH+1,LINE_WIDTH+1),LINE_WIDTH+1)
  #im = auto_canny(im)
  corners = cv2.goodFeaturesToTrack(im, 20, 0.0001, 35, blockSize=40, useHarrisDetector=1, k=0.04)
  im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB)
  if corners is None:
    return 0
  for corner in corners:
    corner_points = corner[0]
    corner_y = int(corner_points[0])
    corner_x = int(corner_points[1])
    cv2.rectangle(im,(corner_y-rect_w/2,corner_x-rect_w/2),(corner_y+rect_w/2,corner_x+rect_w/2),color=[255,0,0],thickness=-1)
  final_corners = [((corner[0])[0], (corner[0])[1]) for corner in corners]
  if display:
    plt.imshow(im)
    plt.ion()
    plt.show()
    c = raw_input("Correct? (y/n) --> ")
    n = raw_input("Number of nodes --> ")
    if c == 'y':
      corr = 1.0
      fp_float = 0.0
      fn_float = 0.0
      with open(template_dict[0:11] + '_corners.pickle', 'wb') as handle:
        pickle.dump(final_corners, handle)
    else:
      corr = 0.0
      fp = raw_input("False positives --> ")
      fn = raw_input("False negatives --> ")
      fp_float = float(fp)
      fn_float = float(fn)
    plt.close()
    return corr, fp_float, fn_float, float(n) 
Example 70
Project: chemtype2   Author: bradleyemi   File: chemtype.py    MIT License 4 votes vote down vote up
def classify_bonds(edge_file,img,classifier,label_dict,template_dict_file,rect_w=6,empty_thresh=0.3):
  im = cv2.imread(img,0)
  ret,im = cv2.threshold(im,THRESH_VAL,255,cv2.THRESH_BINARY_INV)
  im = cv2.copyMakeBorder(im,BORDER,BORDER,BORDER,BORDER,cv2.BORDER_CONSTANT,0)
  shape = im.shape
  with open(edge_file) as handle:
    edges = pickle.load(handle)
  with open(template_dict_file) as handle:
    template_dict = pickle.load(handle)
  print edges
  subimgs = get_bonds(edges, im)
  assignments = []
  for i,subimg in enumerate(subimgs):
    subimg = cv2.GaussianBlur(subimg, (5,5), 5)
    n_blocks = max(int(np.floor((subimg.shape[0]-10) / 10)), 0)
    blocks = []
    if n_blocks == 0:
      assignments.append('none')
      continue
    else:
      for block_start in [i*10 for i in range(n_blocks)]:
        block_end = block_start + 10
        blocks.append(hog(subimg[block_start:block_end, :]))
    guesses = classifier.predict(blocks)
    guess_count = Counter(guesses)
    label = (guess_count.most_common(1)[0])[0]
    print label
    assignments.append(label_dict[label])
  color_im = cv2.cvtColor(im, cv2.COLOR_GRAY2RGB)
  for i,line_segment in enumerate(edges):
    color = COLOR_DICT[assignments[i]]
    if color == 'none':
      continue
    cv2.line(color_im,line_segment[0],line_segment[1],color,thickness=5)
  for key in template_dict.keys():
    if len(template_dict[key]) != 0:
      color = COLOR_DICT_OCR[key]
      for box in template_dict[key]:
        cv2.rectangle(color_im,(box[0],box[2]),(box[1],box[3]),color=color, thickness=5)
  plt.imshow(color_im)
  plt.ion()
  plt.show()
  c = raw_input("Correct? (y/n) --> ")
  n = raw_input("Number of edges correct --> ")
  if c == 'y':
    corr = 1.0
  else:
    corr = 0.0
  return corr, float(n) 

### Classifier testing ### 
Example 71
Project: pytentiostat   Author: juami   File: plotter.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_initializer(config_data):
    """
    Initializes plot based on experiment type and parameters in the config file.

    Parameters
    ----------
    config_data : dict
        The parameters from the config file.
    """
    exp_type = pytentiostat.config_reader.get_exp_type(config_data)
    exp_time = pytentiostat.config_reader.get_exp_time(config_data)

    times = []
    voltages = []
    currents = []

    # Let's start and setup initial plot parameters
    plt.show()
    axes = plt.gca()
    axes.set_xlim(-2.5, 2.5)
    axes.set_ylim(-2.5, 2.5)
    plt.ion()

    # This is just for testing
    if exp_type == "CA":
        axes.set_xlim(0, 2 * exp_time)

    # Let's switch commands based on experiment run
    if exp_type == "LSV":
        line, = axes.plot(voltages, currents, "r-")
        plt.xlabel("Voltage (V)")
        plt.ylabel("Current (mA)")
        return line

    elif exp_type == "CA":
        line, = axes.plot(times, currents, "r-")
        plt.xlabel("Time (s)")
        plt.ylabel("Current (mA)")
        return line

    elif exp_type == "CV":
        line, = axes.plot(voltages, currents, "r-")
        plt.xlabel("Voltage (V)")
        plt.ylabel("Current (mA)")
        return line 
Example 72
Project: MCTS-T   Author: tmoer   File: grid.py    MIT License 4 votes vote down vote up
def __init__(self,to_plot=False,grid=False):
        world = np.zeros([7,7],dtype='int32')
        world[1:6,1] = 1
        world[1:3,4] = 1
        world[4:6,4] = 1
        self.world = world
        self.grid = grid
        self.reset()
        self.observation_shape = np.shape(self.get_state())[0]
        
        if to_plot:
            plt.ion()
            fig = plt.figure()
            ax1 = fig.add_subplot(111,aspect='equal')
            ax1.axis('off')
            plt.xlim([-1,8])
            plt.ylim([-1,8])
            
            #colors = matplotlib.colors.ListerColormap()
            for i in range(7):
                for j in range(7):
                    if world[i,j]==1:
                        col = "black"
                    else:
                        col = "white"
                    ax1.add_patch(
                        patches.Rectangle(
                            (i,j),1,1,
                            #fill=False,
                            edgecolor='black',
                            linewidth = 2,
                            facecolor = col,),
                        )
                    if np.all([i,j] == self.ghost1):
                        self.g1 = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='red'))
                    if np.all([i,j] == self.ghost2):
                        self.g2 = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='blue'))                    
                    if np.all([i,j] == self.pacman):
                        self.p = ax1.add_artist(plt.Circle((i+0.5,j+0.5),0.3,color='yellow'))
            self.fig = fig
            self.ax1 = ax1
            self.fig.canvas.draw() 
Example 73
Project: MCTS-T   Author: tmoer   File: chicken.py    MIT License 4 votes vote down vote up
def __init__(self,to_plot = False):
        self.state = np.array([0,0])        
        self.observation_shape = np.shape(self.get_state())[0]
        
        if to_plot:
            plt.ion()
            fig = plt.figure()
            ax1 = fig.add_subplot(111,aspect='equal')
            #ax1.axis('off')
            plt.xlim([-0.5,5.5])
            plt.ylim([-0.5,5.5])

            self.g1 = ax1.add_artist(plt.Circle((self.state[0],self.state[1]),0.1,color='red'))
            self.fig = fig
            self.ax1 = ax1
            self.fig.canvas.draw()
            self.fig.canvas.flush_events() 
Example 74
Project: SkinLesionNeuralNetwork   Author: Neurality   File: callbacks.py    GNU General Public License v3.0 4 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):

        self.state['current_epoch']['end_time'] = datetime.now()
        self.state['current_epoch']['logs'] = logs

        # In seconds
        duration = (self.state['current_epoch']['end_time'] - \
                    self.state['current_epoch']['start_time']).total_seconds()
        self.state['current_epoch']['duration'] = duration

        self.state['epochs'].append(self.state['current_epoch'])

        self.state['current_epoch']['average_minute_per_epoch'] = self.average_minute_per_epoch()

        # Write and send message
        message = "Epoch {}/{} is done at {}. Average minutes/epoch is {:.2f}."
        self.notify(message.format(epoch + 1, self.params['nb_epoch'],
                                   self.state['current_epoch']['end_time'].strftime(self.date_format),
                                   self.state['current_epoch']['average_minute_per_epoch']))\

        nice_logs = ' | '.join(["{} = {:.6f}".format(k, v) for k, v in logs.items()])
        self.notify("Logs are : {}".format(nice_logs))

        # Plot if the current monitor can do it
        if self.can_plot and self.plot_history and ((epoch + 1) % self.plot_history) == 0:
            import matplotlib.pyplot as plt
            plt.style.use('seaborn-ticks')

            plt.ioff()

            index = [epoch['epoch'] for epoch in self.state['epochs']]
            logs = pd.DataFrame.from_dict([epoch['logs'] for epoch in self.state['epochs']])
            logs.index = [epoch['epoch'] for epoch in self.state['epochs']]
            logs.index.name = 'epoch'

            ax = logs.plot(marker='o', markeredgewidth=0)
            fig = ax.get_figure()

            ax.set_title("History at epoch #{}".format(epoch))

            self.notify_image(fig)

            plt.ion()

        # Reset current epoch
        self.state['current_epoch'] = {} 
Example 75
Project: PyFluxPro   Author: OzFlux   File: pfp_clim.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def compare_eddypro():
    epname = pfp_io.get_filename_dialog(title='Choose an EddyPro full output file')
    ofname = pfp_io.get_filename_dialog(title='Choose an L3 output file')

    ds_ep = pfp_io.read_eddypro_full(epname)
    ds_of = pfp_io.nc_read_series(ofname)

    dt_ep = ds_ep.series['DateTime']['Data']
    dt_of = ds_of.series['DateTime']['Data']

    start_datetime = max([dt_ep[0],dt_of[0]])
    end_datetime = min([dt_ep[-1],dt_of[-1]])

    si_of = pfp_utils.GetDateIndex(dt_of, str(start_datetime), ts=30, default=0, match='exact')
    ei_of = pfp_utils.GetDateIndex(dt_of, str(end_datetime), ts=30, default=len(dt_of), match='exact')
    si_ep = pfp_utils.GetDateIndex(dt_ep, str(start_datetime), ts=30, default=0, match='exact')
    ei_ep = pfp_utils.GetDateIndex(dt_ep, str(end_datetime), ts=30, default=len(dt_ep), match='exact')

    us_of = pfp_utils.GetVariable(ds_of,'ustar',start=si_of,end=ei_of)
    us_ep = pfp_utils.GetVariable(ds_ep,'ustar',start=si_ep,end=ei_ep)
    Fh_of = pfp_utils.GetVariable(ds_of,'Fh',start=si_of,end=ei_of)
    Fh_ep = pfp_utils.GetVariable(ds_ep,'Fh',start=si_ep,end=ei_ep)
    Fe_of = pfp_utils.GetVariable(ds_of,'Fe',start=si_of,end=ei_of)
    Fe_ep = pfp_utils.GetVariable(ds_ep,'Fe',start=si_ep,end=ei_ep)
    Fc_of = pfp_utils.GetVariable(ds_of,'Fc',start=si_of,end=ei_of)
    Fc_ep = pfp_utils.GetVariable(ds_ep,'Fc',start=si_ep,end=ei_ep)
    # copy the range check values from the OFQC attributes to the EP attributes
    for of, ep in zip([us_of, Fh_of, Fe_of, Fc_of], [us_ep, Fh_ep, Fe_ep, Fc_ep]):
        for item in ["rangecheck_upper", "rangecheck_lower"]:
            if item in of["Attr"]:
                ep["Attr"][item] = of["Attr"][item]
    # apply QC to the EddyPro data
    pfp_ck.ApplyRangeCheckToVariable(us_ep)
    pfp_ck.ApplyRangeCheckToVariable(Fc_ep)
    pfp_ck.ApplyRangeCheckToVariable(Fe_ep)
    pfp_ck.ApplyRangeCheckToVariable(Fh_ep)
    # plot the comparison
    plt.ion()
    fig = plt.figure(1,figsize=(8,8))
    pfp_plot.xyplot(us_ep["Data"],us_of["Data"],sub=[2,2,1],regr=2,xlabel='u*_EP (m/s)',ylabel='u*_OF (m/s)')
    pfp_plot.xyplot(Fh_ep["Data"],Fh_of["Data"],sub=[2,2,2],regr=2,xlabel='Fh_EP (W/m2)',ylabel='Fh_OF (W/m2)')
    pfp_plot.xyplot(Fe_ep["Data"],Fe_of["Data"],sub=[2,2,3],regr=2,xlabel='Fe_EP (W/m2)',ylabel='Fe_OF (W/m2)')
    pfp_plot.xyplot(Fc_ep["Data"],Fc_of["Data"],sub=[2,2,4],regr=2,xlabel='Fc_EP (umol/m2/s)',ylabel='Fc_OF (umol/m2/s)')
    plt.tight_layout()
    plt.draw()
    plt.ioff() 
Example 76
Project: PyFluxPro   Author: OzFlux   File: pfp_plot.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_fluxnet(cf):
    """ Plot the FluxNet style plots. """

    series_list = cf["Variables"].keys()
    infilename = pfp_io.get_infilenamefromcf(cf)

    ds = pfp_io.nc_read_series(infilename)
    nRecs = int(ds.globalattributes["nc_nrecs"])
    zeros = numpy.zeros(nRecs,dtype=numpy.int32)
    ones = numpy.ones(nRecs,dtype=numpy.int32)
    site_name = ds.globalattributes["site_name"]

    ldt=ds.series["DateTime"]["Data"]
    sdt = ldt[0]
    edt = ldt[-1]
    # Tumbarumba doesn't have RH in the netCDF files
    if "RH" not in ds.series.keys():
        Ah,f,a = pfp_utils.GetSeriesasMA(ds,'Ah')
        Ta,f,a = pfp_utils.GetSeriesasMA(ds,'Ta')
        RH = pfp_mf.RHfromabsolutehumidity(Ah, Ta)
        attr = pfp_utils.MakeAttributeDictionary(long_name='Relative humidity',units='%',standard_name='relative_humidity')
        flag = numpy.where(numpy.ma.getmaskarray(RH)==True,ones,zeros)
        pfp_utils.CreateSeries(ds,"RH",RH,flag,attr)

    nFig = 0
    plt.ion()
    for series in series_list:
        if series not in ds.series.keys():
            logger.error("Series "+series+" not found in input file, skipping ...")
            continue
        logger.info(" Doing plot for "+series)
        data,flag,attr = pfp_utils.GetSeriesasMA(ds,pfp_utils.GetAltName(cf,ds,series))
        nFig = nFig + 1
        fig = plt.figure(nFig,figsize=(10.9,7.5))
        fig.canvas.set_window_title(series)
        plt.plot(ldt,data,"b.")
        plt.xlim(sdt,edt)
        plt.xlabel("Date")
        plt.ylabel(series+" ("+attr["units"]+")")
        title_str = site_name+": "+sdt.strftime("%Y-%m-%d")+" to "+edt.strftime("%Y-%m-%d")+"; "+series
        plt.title(title_str)
        figname='plots/'+ds.globalattributes['site_name'].replace(' ','')+'_'+ds.globalattributes['nc_level']+'_FC_'+series+'.png'
        fig.savefig(figname,format='png')
        plt.draw()
    plt.ioff() 
Example 77
Project: PyFluxPro   Author: OzFlux   File: pfp_plot.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_quickcheck_seb(nFig, plot_title, figure_name, data, daily):
    logger.info(" Doing surface energy balance plots")
    Fa_30min = data["Fa"]["Data"]
    Fh_30min = data["Fh"]["Data"]
    Fe_30min = data["Fe"]["Data"]
    mask = numpy.ma.mask_or(Fa_30min.mask, Fe_30min.mask)
    mask = numpy.ma.mask_or(mask, Fh_30min.mask)
    Fa_SEB = numpy.ma.array(Fa_30min, mask=mask)     # apply the mask
    FhpFe_SEB = numpy.ma.array(Fh_30min, mask=mask) + numpy.ma.array(Fe_30min, mask=mask)
    plt.ion()
    fig = plt.figure(nFig, figsize=(8, 8))
    fig.canvas.set_window_title("Surface Energy Balance")
    plt.figtext(0.5, 0.95, plot_title, horizontalalignment='center', size=16)
    xyplot(Fa_SEB, FhpFe_SEB, sub=[2,2,1], regr=1, title="All hours", xlabel='Fa (W/m2)', ylabel='Fh+Fe (W/m2)')
    # scatter plot of (Fh+Fe) versus Fa, 24 hour averages
    mask = numpy.ma.mask_or(daily["Fa"]["Data"].mask, daily["Fe"]["Data"].mask)
    mask = numpy.ma.mask_or(mask, daily["Fh"]["Data"].mask)
    Fa_daily = numpy.ma.array(daily["Fa"]["Data"], mask=mask)         # apply the mask
    Fe_daily = numpy.ma.array(daily["Fe"]["Data"], mask=mask)
    Fh_daily = numpy.ma.array(daily["Fh"]["Data"], mask=mask)
    Fa_daily_avg = numpy.ma.average(Fa_daily, axis=1)      # get the daily average
    Fe_daily_avg = numpy.ma.average(Fe_daily, axis=1)
    Fh_daily_avg = numpy.ma.average(Fh_daily, axis=1)
    FhpFe_daily_avg = Fh_daily_avg + Fe_daily_avg
    xyplot(Fa_daily_avg, FhpFe_daily_avg, sub=[2,2,2], regr=1, thru0=1,
           title="Daily Average", xlabel="Fa (W/m2)", ylabel="Fh+Fe (W/m2)")
    # scatter plot of (Fh+Fe) versus Fa, day time
    day_mask = (data["Fsd"]["Data"] >= 10)
    Fa_day = numpy.ma.masked_where(day_mask == False, Fa_30min)
    Fe_day = numpy.ma.masked_where(day_mask == False, Fe_30min)
    Fh_day = numpy.ma.masked_where(day_mask == False, Fh_30min)
    mask = numpy.ma.mask_or(Fa_day.mask, Fe_day.mask)
    mask = numpy.ma.mask_or(mask, Fh_day.mask)
    Fa_day = numpy.ma.array(Fa_day, mask=mask)         # apply the mask
    Fe_day = numpy.ma.array(Fe_day, mask=mask)
    Fh_day = numpy.ma.array(Fh_day, mask=mask)
    FhpFe_day = Fh_day + Fe_day
    xyplot(Fa_day, FhpFe_day, sub=[2,2,3], regr=1, title="Day", xlabel="Fa (W/m2)", ylabel="Fh+Fe (W/m2)")
    # scatter plot of (Fh+Fe) versus Fa, night time
    night_mask = (data["Fsd"]["Data"] < 10)
    Fa_night = numpy.ma.masked_where(night_mask==False, Fa_30min)
    Fe_night = numpy.ma.masked_where(night_mask==False, Fe_30min)
    Fh_night = numpy.ma.masked_where(night_mask==False, Fh_30min)
    mask = numpy.ma.mask_or(Fa_night.mask, Fe_night.mask)
    mask = numpy.ma.mask_or(mask, Fh_night.mask)
    Fa_night = numpy.ma.array(Fa_night, mask=mask)         # apply the mask
    Fe_night = numpy.ma.array(Fe_night, mask=mask)
    Fh_night = numpy.ma.array(Fh_night, mask=mask)
    FhpFe_night = Fh_night + Fe_night
    xyplot(Fa_night, FhpFe_night, sub=[2,2,4], regr=1, title="Night", xlabel="Fa (W/m2)", ylabel="Fh+Fe (W/m2)")
    # hard copy of plot
    fig.savefig(figure_name, format='png')
    # draw the plot on the screen
    plt.draw()
    plt.ioff() 
Example 78
Project: open-recipe   Author: dspray95   File: _tqdm_gui.py    The Unlicense 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        warn('GUI is experimental/alpha', TqdmExperimentalWarning)
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax 
Example 79
Project: ssd-mxnet2caffe   Author: OSS-ArgoAI   File: test_converter.py    Apache License 2.0 4 votes vote down vote up
def test_final_result(self):
        """Plot final detections on test image
        """

        # swap channels from Caffe BGR to RGB
        self.caffe_mean = self.caffe_mean[::-1]
        image = read_img(self.image_url, mean=self.caffe_mean)

        # Run inference through mxnet and caffe
        mxnet_exe = run_inference_mxnet(self.sym, self.arg_params,
                                        self.aux_params, image, gpu=-1)
        caffe_network = run_inference_caffe(self.convertor.caffe_net, image)
        mx_output = mxnet_exe.output_dict['det_out_output'].asnumpy()
        mx_label = mx_output[0, np.argmax(mx_output[0, :, 1]), 0]
        mx_conf = mx_output[0, np.argmax(mx_output[0, :, 1]), 1]
        pyplot.ion()
        pyplot.figure()
        pyplot.subplot(2, 1, 1)
        pyplot.title('MXNET RESULTS')
        im = pyplot.imshow(np.transpose(image[0].astype(np.uint8), (1, 2, 0)))
        pyplot.tight_layout()
        pyplot.xticks([])
        pyplot.yticks([])
        xmin, ymin, xmax, ymax = mx_output[0,
                                           np.argmax(mx_output[0, :, 1]), 2:]
        img_width, img_height = image.shape[2:]
        xmin *= img_width
        xmax *= img_width
        ymin *= img_height
        ymax *= img_height
        coords = (xmin, ymin), xmax - xmin + 1, ymax - ymin + 1
        im.axes.add_patch(pyplot.Rectangle(
            *coords, fill=False, edgecolor='r', linewidth=2))
        pyplot.subplot(2, 1, 2)
        pyplot.title('CAFFE RESULTS')
        im = pyplot.imshow(np.transpose(image[0].astype(np.uint8), (1, 2, 0)))
        caffe_output = caffe_network.blobs['detection'].data

        det_conf = caffe_output[0, 0, :, 2]
        xmin, ymin, xmax, ymax = caffe_output[0, 0, np.argmax(det_conf), -4:]
        caffe_label = caffe_output[0, 0, np.argmax(
            det_conf), 1] - 1  # Subtract background label id
        caffe_conf = caffe_output[0, 0, np.argmax(
            det_conf), 2]

        assert caffe_label == mx_label
        assert abs(caffe_conf - mx_conf) < 1e-6

        xmin *= img_width
        xmax *= img_width
        ymin *= img_height
        ymax *= img_height
        coords = (xmin, ymin), xmax - xmin + 1, ymax - ymin + 1

        im.axes.add_patch(pyplot.Rectangle(
            *coords, fill=False, edgecolor='g', linewidth=2))
        pyplot.tight_layout()
        pyplot.xticks([])
        pyplot.yticks([])
        pyplot.savefig('result.png')
        logger.info('Saving predictions in result.png.') 
Example 80
Project: analyzePF   Author: analyzeDFIR   File: _tqdm_gui.py    MIT License 4 votes vote down vote up
def __init__(self, *args, **kwargs):
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        from collections import deque
        kwargs['gui'] = True

        super(tqdm_gui, self).__init__(*args, **kwargs)

        # Initialize the GUI display
        if self.disable or not kwargs['gui']:
            return

        self.fp.write('Warning: GUI is experimental/alpha\n')
        self.mpl = mpl
        self.plt = plt
        self.sp = None

        # Remember if external environment uses toolbars
        self.toolbar = self.mpl.rcParams['toolbar']
        self.mpl.rcParams['toolbar'] = 'None'

        self.mininterval = max(self.mininterval, 0.5)
        self.fig, ax = plt.subplots(figsize=(9, 2.2))
        # self.fig.subplots_adjust(bottom=0.2)
        if self.total:
            self.xdata = []
            self.ydata = []
            self.zdata = []
        else:
            self.xdata = deque([])
            self.ydata = deque([])
            self.zdata = deque([])
        self.line1, = ax.plot(self.xdata, self.ydata, color='b')
        self.line2, = ax.plot(self.xdata, self.zdata, color='k')
        ax.set_ylim(0, 0.001)
        if self.total:
            ax.set_xlim(0, 100)
            ax.set_xlabel('percent')
            self.fig.legend((self.line1, self.line2), ('cur', 'est'),
                            loc='center right')
            # progressbar
            self.hspan = plt.axhspan(0, 0.001,
                                     xmin=0, xmax=0, color='g')
        else:
            # ax.set_xlim(-60, 0)
            ax.set_xlim(0, 60)
            ax.invert_xaxis()
            ax.set_xlabel('seconds')
            ax.legend(('cur', 'est'), loc='lower left')
        ax.grid()
        # ax.set_xlabel('seconds')
        ax.set_ylabel((self.unit if self.unit else 'it') + '/s')
        if self.unit_scale:
            plt.ticklabel_format(style='sci', axis='y',
                                 scilimits=(0, 0))
            ax.yaxis.get_offset_text().set_x(-0.15)

        # Remember if external environment is interactive
        self.wasion = plt.isinteractive()
        plt.ion()
        self.ax = ax