Python matplotlib.pyplot.semilogy() Examples

The following are code examples for showing how to use matplotlib.pyplot.semilogy(). 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: vibe   Author: 3ll3d00d   File: graphs.py    MIT License 6 votes vote down vote up
def deconvolve(self):
        measurementPath = os.path.join(os.path.dirname(__file__), '../test/data', 'white15.out')
        fc = 2
        plt.figure(1)
        x = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=1, skipHeader=1)
        y = ms.loadSignalFromDelimitedFile(measurementPath, timeColumnIdx=0, dataColumnIdx=2, skipHeader=1)
        vibeX = Signal(self.butter_filter(x.samples, fc, x.fs, True), x.fs)
        vibeY = Signal(self.butter_filter(y.samples, fc, y.fs, True), y.fs)
        f, Px_spec = vibeX.spectrum()
        plt.semilogy(f, Px_spec, label='x')
        f, Py_spec = vibeY.spectrum()
        plt.semilogy(f, Py_spec, label='y')
        # show where x is > y
        spec = Px_spec - Py_spec
        plt.semilogy(f, spec, label='x / y')
        plt.legend(loc='lower right')
        plt.tight_layout()
        plt.grid(True)
        plt.show() 
Example 2
Project: YellowFin   Author: JianGoForIt   File: resnet_utils.py    Apache License 2.0 6 votes vote down vote up
def plot_loss(loss_list, log_dir, iter_id):
  def running_mean(x, N):
    cumsum = np.cumsum(np.insert(x, 0, 0))
    return (cumsum[N:] - cumsum[:-N]) / N
  plt.figure()
  plt.semilogy(loss_list, '.', alpha=0.2, label="Loss")
  plt.semilogy(running_mean(loss_list,100), label="Average Loss")
  plt.xlabel('Iterations')
  plt.ylabel('Loss')
  plt.legend()
  plt.grid()
  ax = plt.subplot(111)
  ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
        ncol=3, fancybox=True, shadow=True)
  plt.savefig(log_dir + "/fig_loss_iter_" + str(iter_id) + ".pdf")
  print("figure plotted")
  plt.close() 
Example 3
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 6 votes vote down vote up
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 4
Project: DiCoNet   Author: alexnowakvila   File: Logger.py    MIT License 6 votes vote down vote up
def plot_losses(self, losses, losses_reg, scales=[], fig=0):
        # discriminative losses
        plt.figure(fig)
        plt.clf()
        plt.semilogy(range(0, len(losses)), losses, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('discriminative loss')
        path = os.path.join(self.path, 'losses.png')
        plt.savefig(path)
        # reg loss
        plt.figure(fig + 1)
        plt.clf()
        plt.semilogy(range(0, len(losses_reg)), losses_reg, 'b')
        plt.xlabel('iterations')
        plt.ylabel('Loss')
        plt.title('split regularization loss')
        path = os.path.join(self.path, 'split_variances.png')
        plt.savefig(path) 
Example 5
Project: GWNRTools   Author: prayush   File: PlotOverlaps.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_cce_max_mismatch(self, savedir=None, savefig=None):
    #{{{
    if savedir is None: savedir = self.plotdir
    #
    overlaps = self.data.get_max_cce_mismatch()
    X = overlaps.X()
    Y = overlaps.Y()
    fig = plt.figure(int(1e7 * np.random.random()))
    for i in range( overlaps.nWindows ):
      plt.semilogy( X, 1. - Y, label=self.taperlabels[i] )
    plt.grid()
    plt.xlabel('Total mass (solar masses)')
    plt.ylabel('Max of CCER, Lev, Extraction mismatches')
    plt.title(self.simtag)
    plt.legend(ncol=2, loc='lower left')
    if savefig: plt.savefig(savedir + '/' + savefig, dpi=400)
    else: plt.savefig(savedir + '/' + self.simtag + '_MAXNR.png', dpi=400)
    return
    #}}} 
Example 6
Project: a2dr   Author: cvxgrp   File: base_test.py    Apache License 2.0 6 votes vote down vote up
def plot_residuals(self, r_primal, r_dual, normalize = False, show = True, title = None, semilogy = False, savefig = None, *args, **kwargs):
        if normalize:
            r_primal = r_primal / r_primal[0] if r_primal[0] != 0 else r_primal
            r_dual = r_dual / r_dual[0] if r_dual[0] != 0 else r_dual

        if semilogy:
            plt.semilogy(range(len(r_primal)), r_primal, label = "Primal", *args, **kwargs)
            plt.semilogy(range(len(r_dual)), r_dual, label = "Dual", *args, **kwargs)
        else:
            plt.plot(range(len(r_primal)), r_primal, label = "Primal", *args, **kwargs)
            plt.plot(range(len(r_dual)), r_dual, label = "Dual", *args, **kwargs)
        plt.legend()
        plt.xlabel("Iteration")
        plt.ylabel("Residual")
        if title:
            plt.title(title)
        if show:
            plt.show()
        if savefig:
            plt.savefig(savefig, bbox_inches="tight") 
Example 7
Project: a2dr   Author: cvxgrp   File: base_test.py    Apache License 2.0 6 votes vote down vote up
def compare_residuals(self, res_drs, res_a2dr, m_vals):
        if not isinstance(res_a2dr, list):
            res_a2dr = [res_a2dr]
        if not isinstance(m_vals, list):
            m_vals = [m_vals]
        if len(m_vals) != len(res_a2dr):
            raise ValueError("Must have same number of AA-II residuals as memory parameter values")

        plt.semilogy(range(res_drs.shape[0]), res_drs, label="DRS")
        for i in range(len(m_vals)):
            label = "A2DR (m = {})".format(m_vals[i])
            plt.semilogy(range(res_a2dr[i].shape[0]), res_a2dr[i], linestyle="--", label=label)
        plt.legend()
        plt.xlabel("Iteration")
        plt.ylabel("Residual")
        plt.show() 
Example 8
Project: mx-lsoftmax   Author: luoyetx   File: plot_beta.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_beta():
    '''plot beta over training
    '''
    beta = args.beta
    scale = args.scale
    beta_min = args.beta_min
    num_epoch = args.num_epoch
    epoch_size = int(float(args.num_examples) / args.batch_size)

    x = np.arange(num_epoch*epoch_size)
    y = beta * np.power(scale, x)
    y = np.maximum(y, beta_min)
    epoch_x = np.arange(num_epoch) * epoch_size
    epoch_y = beta * np.power(scale, epoch_x)
    epoch_y = np.maximum(epoch_y, beta_min)

    # plot beta descent curve
    plt.semilogy(x, y)
    plt.semilogy(epoch_x, epoch_y, 'ro')
    plt.title('beta descent')
    plt.ylabel('beta')
    plt.xlabel('epoch')
    plt.show() 
Example 9
Project: deeplearning-notes   Author: juxiangwu   File: utils.py    Apache License 2.0 6 votes vote down vote up
def optimize(batch_size, trainer, num_epochs, decay_epoch, log_interval, X, y,
             net):
    """优化目标函数。"""
    dataset = gluon.data.ArrayDataset(X, y)
    data_iter = gluon.data.DataLoader(dataset, batch_size, shuffle=True)
    square_loss = gluon.loss.L2Loss()
    y_vals = [square_loss(net(X), y).mean().asnumpy()]
    for epoch in range(1, num_epochs + 1): 
        # 学习率自我衰减。
        if decay_epoch and epoch > decay_epoch:
            trainer.set_learning_rate(trainer.learning_rate * 0.1)
        for batch_i, (features, label) in enumerate(data_iter):
            with autograd.record():
                output = net(features)
                loss = square_loss(output, label)
            loss.backward()
            trainer.step(batch_size)
            if batch_i * batch_size % log_interval == 0:
                y_vals.append(square_loss(net(X), y).mean().asnumpy())
    print('w:', net[0].weight.data(), '\nb:', net[0].bias.data(), '\n')
    x_vals = np.linspace(0, num_epochs, len(y_vals), endpoint=True)
    semilogy(x_vals, y_vals, 'epoch', 'loss') 
Example 10
Project: gamma_limits_sensitivity   Author: mahnen   File: __init__.py    MIT License 6 votes vote down vote up
def plot_sensitive_energy(a_eff_interpol):
    '''
    fill a sensitive energy plot figure
    '''
    gamma_range = [-5., -0.5]
    stepsize = 0.1
    gammas = np.arange(gamma_range[0], gamma_range[1]+stepsize, stepsize)
    e_sens = np.array([sensitive_energy(i, a_eff_interpol) for i in gammas])

    plt.plot(gammas, e_sens, 'k')

    plt.title('sensitive energy E$_{sens}$($\\Gamma$)')
    plt.semilogy()
    plt.ylabel('E$_{sens}$ / TeV')
    plt.xlabel('$\\Gamma$')

    return gammas, e_sens 
Example 11
Project: maxent   Author: TRIQS   File: plot_utils.py    GNU General Public License v3.0 6 votes vote down vote up
def _plotter(x, y, label=None, x_label=None, y_label=None,
             log_x=False, log_y=False, **kwargs):
    """ actually plotting a curve

    a small wrapper over matplotlib"""

    plot_command = plt.plot
    if log_x and log_y:
        plot_command = plt.loglog
    elif log_x:
        plot_command = plt.semilogx
    elif log_y:
        plot_command = plt.semilogy

    if np.any(np.iscomplex(y)):
        plot_command(x, y.real,
                     label='Re ' + label if label is not None else None)
        plot_command(x, y.imag,
                     label='Im ' + label if label is not None else None)
    else:
        plot_command(x, y, label=label)
    plt.xlabel(x_label)
    plt.ylabel(y_label) 
Example 12
Project: deep-learning-note   Author: wdxtub   File: utils.py    MIT License 5 votes vote down vote up
def semilogy(x_vals, y_vals, x_label, y_label, x2_vals=None, y2_vals=None, legend=None):
    plt.xlabel(x_label)
    plt.ylabel(y_label)
    plt.semilogy(x_vals, y_vals)
    if x2_vals and y2_vals:
        plt.semilogy(x2_vals, y2_vals, linestyle=':')
        plt.legend(legend)
    plt.show() 
Example 13
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_axes_scaling(self, iabscissa=1):
        if not hasattr(self, 'D'):
            self.load()
        dat = self
        self._enter_plotting()
        pyplot.semilogy(dat.D[:, iabscissa], dat.D[:, 5:], '-b')
        pyplot.hold(True)
        pyplot.grid(True)
        ax = array(pyplot.axis())
        # ax[1] = max(minxend, ax[1])
        pyplot.axis(ax)
        pyplot.title('Principle Axes Lengths')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 14
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 15
Project: Autoenv   Author: intelligent-control-lab   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x 
Example 16
Project: subsync   Author: tympanix   File: test.py    Apache License 2.0 5 votes vote down vote up
def spectral_centroid(file):
    y, sr = librosa.load(file)
    cent = librosa.feature.spectral_centroid(y=y, sr=sr)

    plt.figure()
    plt.semilogy(cent.T, label='Spectral centroid')
    plt.ylabel('Hz')
    plt.xticks([])
    plt.xlim([0, cent.shape[-1]])
    plt.legend()
    plt.title('log Power spectrogram')
    plt.tight_layout() 
Example 17
Project: babusca   Author: georglind   File: test_g2_quasilocal.py    MIT License 5 votes vote down vote up
def g2_test(d, phi):
    deltas = np.linspace(-10, 10, 255)
    taus = np.array([0])

    g2n = g2s_num_00(d, phi, 1e8, deltas)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(deltas, g2n['g2'], label='num')
    plt.semilogy(deltas, g2s, label='exc')

    plt.legend()

    plt.tight_layout()
    plt.show() 
Example 18
Project: babusca   Author: georglind   File: test_g2.py    MIT License 5 votes vote down vote up
def test_g2_fock_state():

    N, U, = 2, 0
    gs = (.2, .1)

    model = scattering.Model(
        omegas=[0]*N,
        links=[(0, 1, 1)],
        U=[2*U]*N)

    channels = []
    channels.append(scattering.Channel(site=0, strength=gs[0]))
    channels.append(scattering.Channel(site=N-1, strength=gs[1]))

    setup = scattering.Setup(model, channels)

    Es = np.linspace(-3, 12, 1024)
    dE = 0

    g2s = np.zeros(Es.shape, dtype=np.complex128)
    g2n = np.zeros(Es.shape, dtype=np.complex128)
    g2d = np.zeros(Es.shape, dtype=np.complex128)

    for i, E in enumerate(Es):
        g2s[i], g2n[i], g2d[i] = g2.fock_state(setup, (0, 0), (1, 1), E, dE)

    plt.semilogy(Es, g2s, label='g2')
    plt.semilogy(Es, g2n, label='g2n')
    plt.semilogy(Es, g2d, label='g1g1')
    plt.legend()
    plt.show() 
Example 19
Project: babusca   Author: georglind   File: test_g2_quasilocal_tau.py    MIT License 5 votes vote down vote up
def g2_test(d, phi):
    # deltas = np.linspace(-10, 10, 255)
    deltas = np.array([0])
    taus = np.linspace(0, 10, 255)

    g2n = g2s_num_00(d, phi, 1e8, deltas, taus)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(taus, g2n.T, label='num')
    plt.semilogy(taus, g2s.T, label='exc', ls=':')

    plt.legend()

    plt.tight_layout()
    plt.show() 
Example 20
Project: babusca   Author: georglind   File: test_g2_quasilocal_phi.py    MIT License 5 votes vote down vote up
def g2_test(d, phi):
    deltas = np.linspace(-10, 10, 255)
    taus = np.array([0])

    g2n = g2s_num_00(d, phi, 1e8, deltas)
    g2s = g2s_exact_00(d, phi, deltas, taus)

    plt.semilogy(deltas, g2n, label='num')
    plt.semilogy(deltas, g2s, label='exc', ls=':')

    plt.legend()

    plt.tight_layout()
    plt.show() 
Example 21
Project: image-compression-cnn   Author: iamaaditya   File: read_log.py    MIT License 5 votes vote down vote up
def plot(values, metric_name):

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import sys

    plt.style.use('ggplot')

    fig, ax = plt.subplots(1, 1, figsize=(25, 3))
    ax.margins(0)

    x = []
    y = []
    for index,v in enumerate( values ):
        # if not index: continue
        # plt.plot(x, new_recall, linewidth=2, label='Condensed Mem Network')
        x.append(index)
        y.append(v[1]['our']-v[1]['jpeg'])

    # plt.plot(x,y, 'o')
    # plt.semilogy(x,y)
    y_neg = [max(0,i) for i in y]
    y_pos = [min(0,i) for i in y]

    plt.bar(x,y_neg)
    plt.bar(x,y_pos, color='r')
    plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off')

    plt.title(metric_name.upper(), x=0.5, y=0.8, fontsize=14)
    plt.legend(loc='')
    ax.get_xaxis().set_visible(False)
    ax.xaxis.set_major_formatter(plt.NullFormatter())
    fig.tight_layout()
    # plt.savefig('plot_size_' + metric_name + '.png', bbox_inches='tight_layout', pad_inches=0)
    plt.savefig('plot_kodak_' + metric_name + '.png') 
Example 22
Project: gluon-spaceTime   Author: D-Roberts   File: utils.py    Apache License 2.0 5 votes vote down vote up
def plot_losses(losses, label):
    """Plot losses per epoch.

    Train or validation loss or
    another metric.
    """
    x_axis = np.linspace(0, len(losses), len(losses), endpoint=True)
    plt.semilogy(x_axis, losses, label=label)
    plt.xlabel('epoch')
    plt.ylabel('loss')
    return plt 
Example 23
Project: ves_ajoros   Author: ajoros   File: figures.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def initFigure(self):
        # Plot out the results
        plt.semilogy(self.voltageSpacingExtrapolated,
                     self.filteredResistivity,
                     marker=self.marker,
                     linestyle=self.linestyle,
                     color=self.colors[0],
                     label="Filtered")
        plt.semilogy(self.voltageSpacing, self.apparentResistivity,
                     marker=self.marker,
                     linestyle=self.linestyle,
                     color=self.colors[1],
                     label="Observed")
        plt.legend()

        # Create an mpl axis and set the labels, add the rectangle
        self.ax = plt.gca()
        self.ax.set_xlabel(self.xlabel)
        self.ax.set_ylabel(self.ylabel)
        self.ax.margins(0.5)

        # self.ax.add_patch(self.rect)
        self.ax.figure.canvas.draw()

        # Update the figure object/property
        self.fig = plt.gcf()

        self.fig.tight_layout() 
Example 24
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def plot_correlations(self, iabscissa=1):
        """spectrum of correlation matrix and largest correlation"""
        if not hasattr(self, 'corrspec'):
            self.load()
        if len(self.corrspec) < 2:
            return self
        x = self.corrspec[:, iabscissa]
        y = self.corrspec[:, 6:]  # principle axes
        ys = self.corrspec[:, :6]  # "special" values

        from matplotlib.pyplot import semilogy, hold, text, grid, axis, title
        self._enter_plotting()
        semilogy(x, y, '-c')
        hold(True)
        semilogy(x[:], np.max(y, 1) / np.min(y, 1), '-r')
        text(x[-1], np.max(y[-1, :]) / np.min(y[-1, :]), 'axis ratio')
        if ys is not None:
            semilogy(x, 1 + ys[:, 2], '-b')
            text(x[-1], 1 + ys[-1, 2], '1 + min(corr)')
            semilogy(x, 1 - ys[:, 5], '-b')
            text(x[-1], 1 - ys[-1, 5], '1 - max(corr)')
            semilogy(x[:], 1 + ys[:, 3], '-k')
            text(x[-1], 1 + ys[-1, 3], '1 + max(neg corr)')
            semilogy(x[:], 1 - ys[:, 4], '-k')
            text(x[-1], 1 - ys[-1, 4], '1 - min(pos corr)')
        grid(True)
        ax = array(axis())
        # ax[1] = max(minxend, ax[1])
        axis(ax)
        title('Spectrum (roots) of correlation matrix')
        # pyplot.xticks(xticklocs)
        self._xlabel(iabscissa)
        self._finalize_plotting()
        return self 
Example 25
Project: bmaml_rl   Author: jsikyoon   File: cma_es_lib.py    MIT License 5 votes vote down vote up
def __init__(self, func, x, args=(), basis=None, name=None,
                 plot_cmd=pyplot.plot if pyplot else None, load=True):
        """
        Parameters
        ----------
            `func`
                objective function
            `x`
                point in search space, middle point of the sections
            `args`
                arguments passed to `func`
            `basis`
                evaluated points are ``func(x + locations[j] * basis[i])
                for i in len(basis) for j in len(locations)``,
                see `do()`
            `name`
                filename where to save the result
            `plot_cmd`
                command used to plot the data, typically matplotlib pyplots `plot` or `semilogy`
            `load`
                load previous data from file ``str(func) + '.pkl'``

        """
        self.func = func
        self.args = args
        self.x = x
        self.name = name if name else str(func).replace(' ', '_').replace('>', '').replace('<', '')
        self.plot_cmd = plot_cmd  # or semilogy
        self.basis = np.eye(len(x)) if basis is None else basis

        try:
            self.load()
            if any(self.res['x'] != x):
                self.res = {}
                self.res['x'] = x  # TODO: res['x'] does not look perfect
            else:
                print(self.name + ' loaded')
        except:
            self.res = {}
            self.res['x'] = x 
Example 26
Project: NICERsoft   Author: paulray   File: plotutils.py    MIT License 5 votes vote down vote up
def plot_fft_of_power(etable,nyquist, pslog, writeps):
    'plots the power spectrum'

    dt = 0.5/nyquist
    METmin = etable['MET'].min()
    T = etable['MET'].max() - etable['MET'].min()

    # Choose good number of bins for efficient FFT
    n = choose_N(T/float(dt))
    bins = np.arange(n)*dt
    log.info('{0} {1}'.format(T/dt,n))
    log.info('Computing FFT with {0} bins of {1} s, covering {2} total time (Nyquist = {3})'.format(n,dt,T, nyquist))
    ts, edges = np.histogram(etable['MET']-METmin,bins)

    ft = np.fft.rfft(ts)
    power = (ft * ft.conj()).real
    power /= len(etable['MET'])
    power[0:50] = 0.0
    x = np.fft.rfftfreq(len(ts), dt)
    #idx = np.where(power>20)
    idx = np.argmax(power)
    print(x[idx], power[idx])
    if pslog:
        plot.semilogy(x,power)
    else:
        plot.plot(x,power)
    if writeps:
        data = np.array([x,power])
        data = data.T
        np.savetxt(file('powspec.txt','w'), data, fmt=['%f','%f'])

    plot.title('Power Spectrum')
    plot.xlabel('Frequency')
    plot.ylabel('Power')
    return
#-------------------------------THIS PLOTS THE DEADTIME HISTOGRAM------------------ 
Example 27
Project: DiCoNet   Author: alexnowakvila   File: kmeans.py    MIT License 5 votes vote down vote up
def plot_train_logs(cost_train):
    plt.figure(1, figsize=(8,6))
    plt.clf()
    iters = range(len(cost_train))
    plt.semilogy(iters, cost_train, 'b')
    plt.xlabel('iterations')
    plt.ylabel('Average Mean cost')
    plt.title('Average Mean cost Training')
    plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=2.0)
    path = os.path.join('plots/logs', 'training.png') 
    plt.savefig(path) 
Example 28
Project: Dstl-Satellite-Imagery-Feature-Detection   Author: DeepVoltaire   File: training.py    MIT License 5 votes vote down vote up
def visualize_training(loss_train, loss_eval, name, acc_train, acc_eval):
    """
    Visualizes training with log_loss, loss and accuracy plot over training and evaluation sets.
    """
    loss_train = np.abs(loss_train)
    loss_eval = np.abs(loss_eval)
    plt.semilogy(loss_train, basey=2)
    plt.semilogy(loss_eval, basey=2, c="red")
    plt.title('{} model loss'.format(name))
    plt.ylabel('loss')
    plt.xlabel('batch')
    plt.legend(['train', 'eval'], loc='upper left')
    os.makedirs("../plots", exist_ok=True)
    plt.savefig("../plots/log_loss_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close()

    plt.plot(loss_train)
    plt.plot(loss_eval, c="red")
    plt.title('{} model loss'.format(name))
    plt.ylabel('loss')
    plt.xlabel('batch')
    plt.legend(['train', 'eval'], loc='upper left')
    plt.savefig("../plots/loss_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close()

    plt.plot(acc_train)
    plt.plot(acc_eval, c="red")
    plt.title('{} model accuracy'.format(name))
    plt.ylabel('accuracy')
    plt.xlabel('batch')
    plt.ylim([0.9, 1])
    plt.legend(['train', 'eval'], loc='lower right')
    os.makedirs("../plots", exist_ok=True)
    plt.savefig("../plots/acc_{}.png".format(name), bbox_inches="tight", pad_inches=1)
    plt.clf()
    plt.cla()
    plt.close() 
Example 29
Project: GWNRTools   Author: prayush   File: PlotOverlaps.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_effectualness_vs_totalmass(self, inkey=None,\
                          logy=True, figtype='pdf'):
    #{{{
    try: import matplotlib.pyplot as plt
    except: return
    if self.data == None: self.read_data_from_all_files()
    all_sims = self.data.data.keys()
    for sim in all_sims:
      plt.figure(int(1e7 * np.random.random()))
      for idx, app in enumerate(self.ApproxList):
        mm, ff = self.data.effectualness_vs_totalmass(inkey=sim, approx=app)
        #print "Masses = ", mm
        #print "FF = ", ff
        if not logy:
          plt.plot(mm, ff, label=app, \
                  linestyle=self.lines[-1],\
                  lw=3,\
                  marker=self.markers[idx],\
                  markersize=3,\
                  color=self.colors[idx])
        else:
          plt.semilogy(mm, 1.-ff, label=app, \
                  linestyle=self.lines[-1],\
                  lw=3,\
                  marker=self.markers[idx],\
                  markersize=3,\
                  color=self.colors[idx])
        plt.hold(True)
      plt.ylim(1.e-4,1)
      plt.legend(loc='best')
      plt.grid()
      plt.xlabel('Total Mass')# ($M_\odot$)')
      plt.ylabel('Effectualness')
      plt.title(sim.replace('_','-'))
      plt.savefig(self.plotdir+'/FF_%s.%s' % (sim[:-4],figtype))
    return
    #}}} 
Example 30
Project: GPS   Author: golsun   File: def_ct_tools.py    MIT License 5 votes vote down vote up
def test_est_tau0():

	atm_list = [20]# [1,10,20]
	T0_list = [900]#[600, 800, 1000, 1200, 1400, 1600]
	marker = ['o','x','+']
	for i_atm in range(len(atm_list)):
		atm = atm_list[i_atm]
		tau = []
		for T0 in T0_list:
			tau.append(estimate_tau0(T0, atm))
		#plt.semilogy(1000.0/np.array(T0_list), tau, label=str(atm)+'atm', marker=marker[i_atm],fillstyle='none')
		print tau

	plt.legend(loc='lower right')
	plt.savefig('est_tau.jpg') 
Example 31
Project: Complex-gated-recurrent-neural-networks   Author: v0lta   File: helper_module.py    Apache License 2.0 5 votes vote down vote up
def plot_logs(ps, legend, title, window_size=25, vtag='mse', ylim=[0.00, 0.35],
              tikz=False, pdf=False, filename='tfplots.tex', log=False):
    # cs = ['b', 'r', 'g']
    for no, p in enumerate(ps):
        adding_umc = []
        try:
            for e in tf.train.summary_iterator(p):
                for v in e.summary.value:
                    if v.tag == vtag:
                        # print(v.simple_value)
                        adding_umc.append(v.simple_value)
        except:
            # ingnore that silly data loss error....
            pass
        # x = np.array(range(len(adding_umc)))

        y = np.array(adding_umc)
        yhat = tensoboard_average(y, window_size)
        xhat = np.linspace(0, y.shape[0], yhat.shape[0])
        # plt.plot(yhat, cs[no])
        if log:
            plt.semilogy(xhat, yhat, label=legend[no])
        else:
            plt.plot(xhat, yhat, label=legend[no])

    plt.ylim(ylim[0], ylim[1])
    plt.grid()
    plt.ylabel(vtag)
    plt.xlabel('updates')
    plt.legend()
    plt.title(title)

    if tikz:
        from matplotlib2tikz import save as tikz_save
        tikz_save(filename)
    elif pdf:
        plt.savefig(filename, bbox_inches='tight')
    else:
        plt.show() 
Example 32
Project: imips_open   Author: uzh-rpg   File: plot_r_t.py    GNU General Public License v3.0 5 votes vote down vote up
def plot():
    print(hyperparams.methodEvalString())

    _, true_inl, _, R_errs, t_errs = cache.getOrEval()
    assert R_errs[0] is not None

    plt.semilogy(
         true_inl, R_errs, 'o', label='R')
    plt.semilogy(
         true_inl, t_errs, 'v', label='t') 
Example 33
Project: ncp-sort   Author: yueqiw   File: plotting.py    MIT License 5 votes vote down vote up
def plot_avgs(losses, accs, rot_vars, w, save_name=None):
    """Plot training curve 
    """
    up = -1  # 3500

    avg_loss = []
    for i in range(w, len(losses)):
        avg_loss.append(np.mean(losses[i-w:i]))

    avg_acc = []
    for i in range(w, len(accs)):
        avg_acc.append(np.mean(accs[i-w:i]))

    avg_var = []
    for i in range(w, len(rot_vars)):
        avg_var.append(np.mean(rot_vars[i-w:i]))

    plt.figure(22, figsize=(13, 10))
    plt.clf()

    plt.subplot(312)
    plt.semilogy(avg_loss[:up])
    plt.ylabel('Mean NLL')
    plt.grid()

    plt.subplot(311)
    plt.plot(avg_acc[:up])
    plt.ylabel('Mean Accuracy')
    plt.grid()

    plt.subplot(313)
    plt.semilogy(avg_var[:up])
    plt.ylabel('NLL std/mean')
    plt.xlabel('Iteration')
    plt.grid()

    if save_name:
        plt.savefig(save_name)
        plt.close() 
Example 34
Project: a2dr   Author: cvxgrp   File: base_test.py    Apache License 2.0 5 votes vote down vote up
def compare_primal_dual(self, drs_result, a2dr_result, savefig = None):
        # Compare residuals
        plt.semilogy(range(drs_result["num_iters"]), drs_result["primal"], color="blue", linestyle="--",
                     label="Primal (DRS)")
        plt.semilogy(range(a2dr_result["num_iters"]), a2dr_result["primal"], color="blue", label="Primal (A2DR)")
        plt.semilogy(range(drs_result["num_iters"]), drs_result["dual"], color="darkorange", linestyle="--",
                     label="Dual (DRS)")
        plt.semilogy(range(a2dr_result["num_iters"]), a2dr_result["dual"], color="darkorange", label="Dual (A2DR) ")
        # plt.title("Residuals")
        plt.legend()
        if savefig:
            plt.savefig(savefig, bbox_inches="tight")
        plt.show() 
Example 35
Project: a2dr   Author: cvxgrp   File: base_test.py    Apache License 2.0 5 votes vote down vote up
def compare_total(self, drs_result, a2dr_result, savefig = None):
        # Compare residuals
        plt.semilogy(range(drs_result["num_iters"]), np.sqrt(drs_result["primal"]**2+drs_result["dual"]**2), color="blue", label="Residuals (DRS)")
        plt.semilogy(range(a2dr_result["num_iters"]), np.sqrt(a2dr_result["primal"]**2+a2dr_result["dual"]**2), color="darkorange", label="Residuals (A2DR)")
        # plt.title("Residuals")
        plt.legend()
        if savefig:
            plt.savefig(savefig, bbox_inches="tight")
        plt.show() 
Example 36
Project: a2dr   Author: cvxgrp   File: base_test.py    Apache License 2.0 5 votes vote down vote up
def compare_total_all(self, results, names, savefig = None):
        # Compare residuals in the results list
        # len(names) must be equal to len(results)
        for i in range(len(names)):
            result = results[i]
            name = names[i]
            plt.semilogy(range(result["num_iters"]), np.sqrt(result["primal"]**2+result["dual"]**2), 
                         label="Residuals (" + name + ")")
        # plt.title("Residuals")
        plt.legend()
        if savefig:
            plt.savefig(savefig, bbox_inches="tight")
        plt.show() 
Example 37
Project: quffka   Author: maremun   File: visualize.py    MIT License 5 votes vote down vote up
def plot_time(times):
    fig = plt.figure()

    aps = []
    ts = []
    for a, t in times.items():
        plt.semilogy(DIMS[1:], t[1:,:].mean(1), label=a,
                     color=set_color(a), marker=MARKERS[a])
        plt.legend(loc='best')
        plt.ylabel('Time, s', fontsize=basefontsize)
        plt.title('Explicit mapping time', fontsize=basefontsize)
        plt.xlabel(r'$d$, dataset input dimension', fontsize=basefontsize)
        aps.append(a)
        ts.append(t[-1,:].mean())

    patches = []
    for t, a in sorted(zip(ts, aps), reverse=True):
        patches.append(mlines.Line2D([], [], color=set_color(a),
                       marker=MARKERS[a], markersize=5,
                       label=a))
    plt.legend(handles=patches)
    fig.tight_layout()
    top = 0.92
    right = 0.99
    left = 0.11
    bottom = 0.11
    fig.subplots_adjust(left=left, top=top, right=right, bottom=bottom)
    plt.show()
    return fig 
Example 38
Project: keras-training   Author: hls-fpga-machine-learning   File: eval.py    GNU General Public License v3.0 5 votes vote down vote up
def makeRoc(features_val, labels, labels_val, model, outputDir):

    print('in makeRoc()')
    if 'j_index' in labels: labels.remove('j_index')
        
    predict_test = model.predict(features_val)

    df = pd.DataFrame()
    
    fpr = {}
    tpr = {}
    auc1 = {}
    
    plt.figure()       
    for i, label in enumerate(labels):
        df[label] = labels_val[:,i]
        df[label + '_pred'] = predict_test[:,i]
        
        fpr[label], tpr[label], threshold = roc_curve(df[label],df[label+'_pred'])

        auc1[label] = auc(fpr[label], tpr[label])
            
        plt.plot(tpr[label],fpr[label],label='%s tagger, AUC = %.1f%%'%(label.replace('j_',''),auc1[label]*100.))
    plt.semilogy()
    plt.xlabel("Signal Efficiency")
    plt.ylabel("Background Efficiency")
    plt.ylim(0.001,1)
    plt.grid(True)
    plt.legend(loc='upper left')
    plt.figtext(0.25, 0.90,'hls4ml',fontweight='bold', wrap=True, horizontalalignment='right', fontsize=14)
    #plt.figtext(0.35, 0.90,'preliminary', style='italic', wrap=True, horizontalalignment='center', fontsize=14) 
    plt.savefig('%s/ROC.pdf'%(options.outputDir))
    return predict_test 
Example 39
Project: img-search-cnn   Author: Kandy16   File: extract_optimal_components.py    Apache License 2.0 5 votes vote down vote up
def drawPlotOfComponents(ca):
	##f = plt.figure(figsize=(9,8))
	plt.semilogy(ca.explained_variance_ratio_.cumsum(), '--o', label = 'Cumulative explained variance ratio')
	plt.xlabel('Principle components')
	plt.ylabel('Normalized proportion of data')
	plt.title('Variance represented by the principle components')
	plt.legend(loc='right')
	plt.savefig('/var/www/img-search-cnn/webapp/tSNE_visualization/plots/pca_components.png', dpi=120) 
Example 40
Project: neural_clustering_process   Author: aripakman   File: plot_functions.py    MIT License 5 votes vote down vote up
def plot_avgs(losses, accs, rot_vars, w, save_name=None):
    
    
    up = -1 #3500
    
    avg_loss = []
    for i in range(w, len(losses)):
        avg_loss.append(np.mean(losses[i-w:i]))
    
    avg_acc = []
    for i in range(w, len(accs)):
        avg_acc.append(np.mean(accs[i-w:i]))
    
    avg_var = []
    for i in range(w, len(rot_vars)):
        avg_var.append(np.mean(rot_vars[i-w:i]))
    
    
    plt.figure(22, figsize=(13,10))
    plt.clf()
    
    plt.subplot(312)
    plt.semilogy(avg_loss[:up])
    plt.ylabel('Mean NLL')
    plt.grid()
    
    plt.subplot(311)
    plt.plot(avg_acc[:up])
    plt.ylabel('Mean Accuracy')
    plt.grid()
    
    plt.subplot(313)
    plt.semilogy(avg_var[:up])
    plt.ylabel('Permutation Variance' )
    plt.xlabel('Iteration')
    plt.grid()

    if save_name:
        plt.savefig(save_name) 
Example 41
Project: PyMimircache   Author: 1a1a11a   File: profilerUtils.py    GNU General Public License v3.0 5 votes vote down vote up
def draw2d(*args, **kwargs):


    figname = kwargs.get("figname", "2dPlot.png")

    if "plot_type" in kwargs:
        if kwargs['plot_type'] == "scatter":
            l = args[0]
            plt.scatter([i+1 for i in range(len(l))], l, label=kwargs.get("label", None))
    else:
        if 'logX' in kwargs and kwargs["logX"]:
            if 'logY' in kwargs and kwargs["logY"]:
                plt.loglog(*args, label=kwargs.get("label", None))
            else:
                plt.semilogx(*args, label=kwargs.get("label", None))
        else:
            if 'logY' in kwargs and kwargs["logY"]:
                plt.semilogy(*args, label=kwargs.get("label", None))
            else:
                plt.plot(*args, label=kwargs.get("label", None))

    set_fig(**kwargs)

    if not kwargs.get("no_save", False):
        # if folder does not exist, create the folder
        dname = os.path.dirname(figname)
        if dname and not os.path.exists(dname):
            os.makedirs(dname)
        plt.savefig(figname, dpi=600)
        if not kwargs.get("no_print_info", False):
            INFO("plot is saved as {}".format(figname))

    if not kwargs.get("no_show", False):
        try: plt.show()
        except: pass

    if not kwargs.get("no_clear", False):
        plt.clf() 
Example 42
Project: torchhalp   Author: HazyResearch   File: main.py    MIT License 5 votes vote down vote up
def add_plot(iters, dist, label, log_y=True, T=None):
    if log_y:
        plt.plot = plt.semilogy
    plt.figure(0)
    plt.plot(range(iters), dist, label=label)

# https://discuss.pytorch.org/t/adaptive-learning-rate/320/23 
Example 43
Project: memetic_thin_film_py   Author: YuJerryShi   File: MAoptim.py    MIT License 5 votes vote down vote up
def plot_convergence(self, i, fig_conv):
        """
        Plots the convergence curve
        
        This method plots the convergence of the best fitness and average 
        fitness of the population over each generation. 
        
        Parameters: 
            i: current iteration
            fig_conv: figure that refers to the convergence plot
            
        """
        
        if i == 1:
            plt.semilogy([i-1, i], [self.fitness_best[i-1], self.fitness_best[i]], 'b', label='Best merit function')
            plt.semilogy([i-1, i], [self.fitness_avg[i-1], self.fitness_avg[i]], 'r--', label='Average merit function')
            plt.legend(loc='upper right')
            fig_conv.show()
            plt.pause(0.05)
        
        elif i > 1:
            plt.semilogy([i-1, i], [self.fitness_best[i-1], self.fitness_best[i]], 'b')
            plt.semilogy([i-1, i], [self.fitness_avg[i-1], self.fitness_avg[i]], 'r--')
            fig_conv.show()
            plt.pause(0.05)
            
        return
    
    #%% function 
Example 44
Project: pyBoloSN   Author: rscalzo   File: test_A82.py    MIT License 5 votes vote down vote up
def test_A82_Lambda():
    """Test plots for Lambda"""
    y = np.arange(0.7, 1.41, 0.1)
    c = color_ramp(len(y))
    for yi, ci in zip(y, c):
        pypl.semilogy(t, Lambda(t, yi), color=ci)
    pypl.show() 
Example 45
Project: pyBoloSN   Author: rscalzo   File: test_A82.py    MIT License 5 votes vote down vote up
def test_A82LC_full_01():
    """Test plots for A82LC_full"""
    y, tg, MNi, Eth0 = 1.0, 40.0, 0.6, 0.0e+51
    R0 = np.array([0.0, 0.1, 0.3, 1.0, 3.0, 10.0]) * 1e+14
    c = color_ramp(len(R0))
    for R0i, ci in zip(R0, c):
        td = tau_0(R0i, 0.1, 2.8e+33)
        L0, w = Eth0/(td * 86400), y*17.6/td
        print "R0, tau0, L0, w =", R0i, td, L0, w
        pypl.subplot(2, 1, 1)
        pypl.plot(t, A82LC_full(t, y, w, tg, MNi, Eth0), color=ci)
        pypl.subplot(2, 1, 2)
        pypl.semilogy(t, A82LC_full(t, y, w, tg, MNi, Eth0), color=ci)
    pypl.show() 
Example 46
Project: pyBoloSN   Author: rscalzo   File: test_A82.py    MIT License 5 votes vote down vote up
def test_A82LC_full_02():
    """More test plots for A82LC_full"""
    y, tg, MNi, R0 = 1.0, 40.0, 0.6, 1e+13
    Eth0 = np.arange(0.0, 0.51, 0.1) * 1e+51
    c = color_ramp(len(Eth0))
    for Ethi, ci in zip(Eth0, c):
        td = tau_0(R0, 0.1, 2.8e+33)
        L0, w = Ethi/(td * 86400), y*17.6/td
        print "R0, tau0, L0, w =", R0, td, L0, w
        pypl.subplot(2, 1, 1)
        pypl.plot(t, A82LC_full(t, y, w, tg, MNi, Ethi), color=ci)
        pypl.subplot(2, 1, 2)
        pypl.semilogy(t, A82LC_full(t, y, w, tg, MNi, Ethi), color=ci)
    pypl.show() 
Example 47
Project: COMBINE   Author: OGGM   File: data_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_costs(self, basedir):
        fig = plt.figure()
        plt.semilogy(self.costs)
        plt.xlabel('Iteration #')
        plt.ylabel('Cost')
        plt.savefig(os.path.join(basedir, 'cost.pdf'))
        plt.close(fig) 
Example 48
Project: COMBINE   Author: OGGM   File: data_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_c_terms(self, basedir):
        fig = plt.figure()
        data = np.array(self.c_terms)
        for i in range(self.lambdas.size):
            plt.semilogy(data[:, i], label='Reg {:d}'.format(i))
        plt.semilogy(data[:, -1], label='Bare cost', color='k')
        plt.xlabel('Iteration #')
        plt.ylabel('Cost')
        plt.legend()
        plt.savefig(os.path.join(basedir, 'c_terms.pdf'))
        plt.close(fig) 
Example 49
Project: COMBINE   Author: OGGM   File: data_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def plot_rmses(self, basedir):
        fig = plt.figure()
        plt.semilogy(self.get_bed_rmses()[self.step_indices], label='Bed')
        plt.semilogy(self.get_surf_rmses()[self.step_indices], label='Surface')
        plt.xlabel('Iteration #')
        plt.ylabel('RMSE')
        plt.legend()
        plt.savefig(os.path.join(basedir, 'bed_surf_rmse.pdf'))
        plt.close(fig) 
Example 50
Project: DRNN-Keras   Author: jmsalash   File: plot_results.py    MIT License 5 votes vote down vote up
def plot_loss(name, experimentPath, num_iters,train_err, test_err):
    plt.xlabel('Epochs')
    plt.ylabel('Errors')
    plt.title('RNN\n~~~ train & test errors for %s ~~~\n' %(name))
    plt.semilogy(range(num_iters),train_err , 'r', label="Train Error")
    plt.semilogy(range(num_iters),test_err , 'b', label="Test Error")
    plt.legend()
    plt.grid(True)
    plt.savefig(experimentPath+name+'.png')
    plt.clf()