Esempio n. 1
0
def test_bdevolpar_accuracy(modelname='baraffe', parameter='temperature',metallicity=0.,clouds='nocloud'):
#    model = readModel('saumon',metallicity='solar',cloud='hybrid')
    model = readModel(modelname,metallicity=metallicity,clouds=clouds)
    masses = model['mass'][-2]
    vals = []
    for i,age in enumerate(model['age']):
        t = []
        for j,m in enumerate(masses):
            if m in model['mass'][i]:
                t.append(numpy.array(model[parameter][i])[numpy.where(model['mass'][i]==m)])
            else:
                t.append(numpy.nan)
        vals.append(t)
    vl = numpy.array(vals).T
    for j,m in enumerate(masses):
        if parameter=='temperature' or parameter=='radius':
            plt.loglog(model['age'],vl[j],color='grey')
        else:
            plt.semilogx(model['age'],vl[j],color='grey')

    age_samp = 10.**(numpy.arange(1,100)/100.*4-3.)
    mass_samp = [0.003,0.005,0.01,0.02,0.05,0.08,0.1,0.2]
    for m in mass_samp:
        p = modelParameters(model,age=age_samp,mass=[m for i in range(len(age_samp))])
        if parameter=='temperature' or parameter=='radius':
            plt.loglog(age_samp,p[parameter],color='r')
        else:
            plt.semilogx(age_samp,p[parameter],color='r')
        plt.ylabel(parameter)
        plt.xlabel('Age')

    plt.show()
    return True
Esempio n. 2
0
def plotPeriodogram(fvec, pvec,  axes=None, thinning=None):
    '''
    **plotPeriodogram(fvec, pvec,  axes=None, thinning=None)**
    Function that plot a periodogram
    
    Parameters
    ----------
    **fvec** : vector containing  the frequencies resulting from fftdem() \n
    **pvec** : vector containing  the power values resulting from fftdem() \n
    **axes** : string indicating what type of axes to use. Possible options are: \n\t
        - "loglog" \n\t
        - "semilogx"\n\t
        - "semilogy" \n\t
        - None (default option)\n
    **thinning** : parameter to thin the data o plot as vectors can be ver large. It will plot only the number of dots indicated by thinning '''
    # Wvec=1/fvec
    if thinning == None:
        thinning = thinningCheckup(fvec)
    plt.figure()
    if axes == "loglog":
        plt.loglog(fvec[range(0,fvec.size,thinning)],pvec[range(0,pvec.size,thinning)])
    elif axes == "semilogx":
        plt.semilogx(fvec[range(0,fvec.size,thinning)],pvec[range(0,pvec.size,thinning)])
    elif axes == "semilogy":
        plt.semilogy(fvec[range(0,fvec.size,thinning)],pvec[range(0,pvec.size,thinning)])
    else:
        plt.plot(fvec[range(0,fvec.size,thinning)],pvec[range(0,pvec.size,thinning)])
    plt.title("Periodogram")
    plt.ylabel("DFT mean square amplitude")
    plt.xlabel("Frequency (1/m)")
    plt.show()
Esempio n. 3
0
def plotBode2(zpk, n=200, f_range=None, f_logspace=True):
    """
    Bode plot of ZerosAndPoles object using matplotlib
    """
    (f, y) = zpk.frequencyResponse(n=n, f_range=f_range, f_logspace=f_logspace)

    y_A = numpy.abs(y)
    y_phi = Misc.to_deg(Misc.continuousAngle(y))

    plt.figure()
    plt.subplot(211)
    if f_logspace:
        plt.loglog(f, y_A)
    else:
        plt.plot(f, y_A)
    plt.grid(True, which="both")
    plt.ylabel("Amplitude")

    plt.subplot(212)
    if f_logspace:
        plt.semilogx(f, y_phi)
    else:
        plt.plot(f, y_A)
    plt.grid(True, which="both")
    plt.xlabel("Frequency [Hz]")
    plt.ylabel("Phase [deg]")

    plt.show()
Esempio n. 4
0
def comp_conv(f,a,b,exact_value):
    nmax = 100
    
    x = np.arange(1.0, nmax, 1.0)

    t = np.arange(1.0, nmax, 1.0)
    u = np.arange(1.0, nmax, 1.0)
    v = np.arange(1.0, nmax, 1.0)
    w = np.arange(1.0, nmax, 1.0)

    for i in np.arange(0.0,t.size):
        t[i] = rect_meth(a,b,x[i],f)

    for i in np.arange(0.0,u.size):
        u[i] = simpson_meth(a,b,x[i],f)

    for i in np.arange(0.0,v.size):
        v[i] = midpoint_meth(a,b,x[i],f)

    for i in np.arange(0.0,v.size):
        w[i] = exact_value

    mp.clf()
    mp.semilogx()
    mp.plot(x, t, linewidth=1.0, label='Rectangle')
    mp.plot(x, u, linewidth=1.0, label='Simpson')
    mp.plot(x, v, linewidth=1.0, label='Midpoint')
    mp.plot(x, w, linewidth=1.0, label='Value of the integral')
    
    
    mp.title("Illustration of the convergence of the three integration methods");
    mp.xlabel('Number of subdivision points')
    mp.ylabel('Integral of f between a and b')
    mp.legend(loc='upper right')
    mp.show()
Esempio n. 5
0
def demon(n, d, g, kgiven=0):
    ks = np.arange(n + 1)
    c1, c2 = [], []
    for k in ks:
        a = hyp2f1(1, n - k + 1, n + 2, 1 - d)
        b = 0 if g == 0 else hyp2f1(1, n - k + 1, n + 2, 1 - d * g)
        c1.append(a * d - b * d * g)
        c2.append(a)
    plt.plot(ks / n, c1, label='c1')
    plt.plot(ks / n, c2, label='c2')
    plt.xlabel('k / n')
    plt.ylabel('Effective n / n')
    plt.legend()

    plt.figure()
    S = [100 * generalised_entropy_gain(n, k, d, g) for k in ks]
    plt.plot(ks / n, S, label='S')
    plt.xlabel('k / n')
    plt.ylabel('information gain')

    plt.figure()
    dif = np.logspace(-1, 1, 100)
    S = [100 * generalised_entropy_gain(n, kgiven, d, g) for d in dif]
    plt.semilogx(dif, S, label='S')
    plt.xlabel('difficulty')
    plt.ylabel('information gain')
Esempio n. 6
0
    def plotPredictions(self):

        plt.semilogx(self.freqsISO, self.thresholdsISO, label = 'ISO')
        plt.semilogx(self.freqsISO, self.predictions, color = 'r', 
                linestyle = '--', label = 'Predicted')
        plt.legend()
        plt.show()
Esempio n. 7
0
def plot_validation_curve(model, X, y, scorer, param_name, param_range=np.linspace(0.1, 1, 5), cv=None, n_jobs=5,
    ylim=None, title="Xval. validation curve"):
    ''' Plot learning curve for model on data '''

    df = pd.DataFrame()
    df['param_range'] = param_range
    train_scores, test_scores = validation_curve(model, X, y, param_name=param_name, param_range=param_range,
        cv=cv, scoring=scorer, n_jobs=n_jobs)
    df['train_mean'] = 1 - np.mean(train_scores, axis=1)
    df['train_std'] = np.std(train_scores, axis=1)
    df['test_mean'] = 1 - np.mean(test_scores, axis=1)
    df['test_std'] = np.std(test_scores, axis=1)

    plt.figure()
    plt.title(title)
    if ylim is not None:
        plt.ylim(*ylim)
    plt.xlabel("Parameter value")
    plt.ylabel("Error (1-score)")
    plt.grid()
    plt.semilogx(param_range, df.train_mean, color="r", label="Training")
    plt.fill_between(param_range, df.train_mean - df.train_std, df.train_mean + df.train_std, alpha=0.1, color="r")
    plt.semilogx(param_range, df.test_mean, color="g", label="Test")
    plt.fill_between(param_range, df.test_mean - df.test_std, df.test_mean + df.test_std, alpha=0.1, color="g")
    plt.legend(loc="best")
    plt.show()
    return df, plt
Esempio n. 8
0
def plot_cum_vw_data(zrange=None):
    """Plot a cumulative velocity width distribution with error"""
    (_, _, data) = load_data(zrange)
    v_table = 10**np.arange(1, np.log10(np.max(data)+10), 0.1)
    (center, cvels) = pdf_with_error(data, v_table, cumulative=True)
    plt.semilogx(center, cvels, ls="-",color="black", label="N13")
    return (center, cvels)
Esempio n. 9
0
    def plotPredictions(self):

        plt.semilogx(self.freqs, self.sPLs, label = 'ISO target')
        plt.semilogx(self.freqs, self.predictions, color = 'r', 
                linestyle = '--', label = 'Predicted')
        plt.legend()
        plt.show()
Esempio n. 10
0
def plot_graph(input_size_list, run_time_list):

    input_size_list = np.array(input_size_list)
    run_time_list = np.array(run_time_list)

    plt.semilogx(input_size_list, [0]*len(input_size_list))
    return plt.plot(input_size_list, run_time_list)
Esempio n. 11
0
def main():
    edges = [30, 60, 120, 240]
    corners = zip(edges[:-1], edges[1:])
    centres = [(a + b) / 2 for a, b in corners]

#c = [get_linkwitz_riley_coeffs(1, b, a, edges[-1] * 2) for b, a in corners]
    sr = 2000
    c = [get_peak_coeffs(-24, i, sr, 1) for i in centres]
    c.append([[1, 0, 0], [1, 0, 0]])

    bm = [BiquadMemory(0, 0) for _ in c]
    bc = [BiquadCoefficients(b0, b1, b2, a1, a2)
          for [b0, b1, b2], [a0, a1, a2] in c]

    c.append(series_coeffs(c))

#    c.append(impedance_filter(c[-1]))

    wh = [signal.freqz(b, a) for b, a in c]

    plt.subplot(111)
    plt.title("Frequency response - reflection filter")
    for w, h in wh:
        plt.semilogx(w, 20 * np.log10(np.abs(h)))
    plt.ylabel('Amplitude Response (dB)')
    plt.xlabel('Frequency (rad/sample)')
    plt.grid()

    plt.show()
Esempio n. 12
0
def plotRI(RI, title='', filename=''):
    
    global subdirectory

    directory = pinspec.get_output_directory() + subdirectory

    # Make directory if it does not exist
    if not os.path.exists(directory):
            os.makedirs(directory)

    # Plot Resonance Integrals
    fig = plt.figure()
    bins = RI.bin_edges
    plt.semilogx(bins[0:-1], RI.RIs, drawstyle='steps-post')
    plt.xlabel('Energy [eV]')
    plt.ylabel('RI')
    plt.grid()

    if title is '':
        plt.title('Resonance Integrals')
    else:
        plt.title(title.title() + ' Resonance Integrals')

    if filename is '':
        filename = directory + 'RI.png'
    else:
        filename = directory + filename.replace(' ', '-').lower() +'-RI.png'

    plt.savefig(filename)
Esempio n. 13
0
def plotGroupXS(group_xs, title='', filename=''):
    
    global subdirectory

    directory = pinspec.get_output_directory() + subdirectory

    # Make directory if it does not exist
    if not os.path.exists(directory):
            os.makedirs(directory)

    # Plot Resonance Integrals
    fig = plt.figure()
    bins = group_xs.bin_edges
    plt.semilogx(bins[0:-1], group_xs.groupXS[:,:], drawstyle='steps-post')
    plt.xlabel('Energy [eV]')
    plt.ylabel('Group XS')
    plt.grid()

    if title is '':
        plt.title('Group XS')
    else:
        plt.title(title.title() + ' Group XS')

    if filename is '':
        filename = directory + '/group-xs.png'
    else:
        filename = directory + filename.replace(' ', '-').lower() + \
                                                        '-group-xs.png'

    plt.savefig(filename)
    plt.close(fig)
def plot_validation_curve(estimator, title, X, y, param_name, param_range,
							cv=10, scoring='accuracy', n_jobs=2):
	from sklearn.learning_curve import validation_curve
	train_scores, test_scores = validation_curve(
	    estimator, X, y, param_name, param_range,
	    cv=cv, scoring=scoring, n_jobs=n_jobs)
	train_scores_mean = np.mean(train_scores, axis=1)
	train_scores_std = np.std(train_scores, axis=1)
	test_scores_mean = np.mean(test_scores, axis=1)
	test_scores_std = np.std(test_scores, axis=1)

	plt.figure()
	plt.title(title)
	plt.xlabel(param_name)
	plt.ylabel("Score")
	plt.ylim(0.0, 1.1)
	plt.semilogx(param_range, train_scores_mean, label="Training score", color="r")
	plt.fill_between(param_range, train_scores_mean - train_scores_std,
	                 train_scores_mean + train_scores_std, alpha=0.2, color="r")
	plt.semilogx(param_range, test_scores_mean, label="Cross-validation score",
	             color="g")
	plt.fill_between(param_range, test_scores_mean - test_scores_std,
	                 test_scores_mean + test_scores_std, alpha=0.2, color="g")
	plt.legend(loc="best")
	plt.show()
Esempio n. 15
0
def plot_containment_radii(fraction):
    """Plotting script for 68% and 95% containment radii."""

    psf_gc = FermiGalacticCenter.psf()
    gtpsf_table_gc = get_psf_table(psf_gc,  10000, 300000, 15)

    psf_vela = FermiVelaRegion.psf()
    gtpsf_table_vela = get_psf_table(psf_vela, 10000, 300000, 15)
    
    if fraction == 68:
        true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_68')
        true_table = load_lat_psf_performance('P7SOURCEV6_68')
        rad = 'CONT_68'
    elif fraction == 95:
        true_table_rep = load_lat_psf_performance('P7REP_SOURCE_V15_95')
        true_table = load_lat_psf_performance('P7SOURCEV6_95')
        rad = 'CONT_95'
    
    plt.plot(gtpsf_table_gc['ENERGY'], gtpsf_table_gc[rad],
             color='red',label='Fermi Tools PSF @ Galactic Center')
    plt.plot(gtpsf_table_vela['ENERGY'], gtpsf_table_vela[rad],
             color='blue', label='Fermi Tools PSF @ Vela Region')
    plt.plot(true_table_rep['energy'], true_table_rep['containment_angle'],
             color='green', linestyle='--', label='P7REP_SOURCE_V15')
    plt.plot(true_table['energy'], true_table['containment_angle'],
             color='black', linestyle='--', label='P7SOURCEV6')

    plt.xlim([10000, 300000])

    plt.legend()
    plt.semilogx()
    plt.xlabel('Energy/MeV')
    plt.ylabel('PSF Containment Radius/deg')

    return plt
Esempio n. 16
0
def colormap(data, alphas, R0s,
             p = True, logx = True, ret = False):
    """
    Use pcolormesh from matplotlib to create a visualization of the 
    SIRS phase diagram in the form of a heat map.
    Input:  
        data  : Dictionary of the form {(alpha, R0}:value}, where
                the value represents <I*>, <S*>, etc.  This dictionary
                is produced by avg_idata(), fluct(), or frac_fluct()
        alphas: Phase diagram parameters on x-axis; rho/gamma
        R0s   : Phase diagram parameters on y-axis; beta<k>/gamma
                These can be obtained with data_params()
        p     : Create a plot of the data if p==True
        logx  : Plot with a logarithmic x-axis (alphas logarithmic)
        ret   : If ret==True, return the values used to create the
                heat map, so that they may be manipulated in the 
                interpreter or elsewhere; defaults to False
    Output:
        Creates a matplotlib heatmap if p==True
        (X, Y, C): These are three arrays that pcolormesh() takes as
                arguments.  These are returned only if ret==True
    """
    X, Y = np.meshgrid(alphas, R0s)
    C = np.array([[data[rho_, R0] for rho_ in alphas] for R0 in R0s])
    if p:
        plt.figure()
        plt.pcolormesh(X, Y, C)
        plt.xlabel('rho/gamma')
        if logx: 
            plt.semilogx()
        plt.ylabel('R_0')
        plt.colorbar()
        plt.show()
    if ret: return X, Y, C
Esempio n. 17
0
def cmc(cmc_scores, logx = True, **kwargs):
  """Plots the (cumulative) match characteristics curve and returns the maximum rank.

  This function plots a CMC curve using the given CMC scores, which can be read from the our score files using the :py:func:`bob.measure.load.cmc_four_column` or :py:func:`bob.measure.load.cmc_five_column` methods.
  The structure of the ``cmc_scores`` parameter is relatively complex.
  It contains a list of pairs of lists.
  For each probe object, a pair of list negative and positive scores is required.

  **Parameters:**

  ``cmc_scores`` : [(array_like(1D, float), array_like(1D, float))]
    See :py:func:`bob.measure.cmc`

  ``logx`` : bool
    Plot the rank axis in logarithmic scale using :py:func:`matplotlib.pyplot.semilogx` or in linear scale using :py:func:`matplotlib.pyplot.plot`? (Default: ``True``)

  ``kwargs`` : keyword arguments
    Extra plotting parameters, which are passed directly to :py:func:`matplotlib.pyplot.plot` or :py:func:`matplotlib.pyplot.semilogx`.

  **Returns:**

  The number of classes (clients) in the given scores.
  """
  from matplotlib import pyplot
  from . import cmc as calc

  out = calc(cmc_scores)

  if logx:
    pyplot.semilogx(range(1, len(out)+1), out * 100, **kwargs)
  else:
    pyplot.plot(range(1, len(out)+1), out * 100, **kwargs)

  return len(out)
Esempio n. 18
0
def binning(data, quantity, show_plot=False, save_plot=False):
    """
    Calculate autocorrelation time, mean and error for a quantity using the binning method.

    The bins become uncorrelated when the error approaches a constant.
    These uncorrelated bins can be used for jackknife resampling.
    """
    original_length = len(data)
    errors = []
    errors.append((original_length, calculate_error(data)))
    while len(data) > 128:
        data = np.asarray([(a + b) / 2 for a, b in zip(data[::2], data[1::2])])
        errors.append((len(data), calculate_error(data)))
    autocorrelation_time = 0.5 * ((errors[-1][1] / errors[0][1])**2 - 1)
    if np.isnan(autocorrelation_time) or autocorrelation_time <= 0:
        autocorrelation_time = 1

    if show_plot:
        # plt.title(r'${0}$'.format('\mathrm{' + quantity.replace(' ', '\ ') + '\ Error}'))
        plt.xlabel(r'$\mathrm{Number\ of\ Data\ Points}$')
        plt.ylabel(r'$\mathrm{Error}$')
        plt.xlim(original_length, 1)
        plt.ylim(ymin=0, ymax=max(errors, key=lambda x: x[1])[1] * 1.15)
        plt.semilogx([e[0] for e in errors], [e[1] for e in errors], basex=2)
        sns.despine()
        if save_plot:
            plt.savefig("{0}/{1}_{2}_binning_error.pdf".format(SAVE_LOCATION, time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())), quantity.replace(" ", "_"), bbox_inches='tight'))
        plt.show()

    return np.mean(data), errors[-1][1], autocorrelation_time, data
Esempio n. 19
0
    def plot_marginal(self, param, lower_bound=0, upper_bound=1, is_int=False, resolution=100):
        if isinstance(param, int):
            dim = param
            param_name = self._fanova.get_config_space().get_parameter_names()[dim]
        else:
            assert param in self._fanova.param_name2dmin, "param %s not known" % param
            dim = self._fanova.param_name2dmin[param]
            param_name = param

        grid = np.linspace(lower_bound, upper_bound, resolution)
        display_grid = [self._fanova.get_config_space().unormalize_value(param_name, value) for value in grid]

        mean = np.zeros(resolution)
        std = np.zeros(resolution)
        for i in xrange(0, resolution):
            (m, s) = self._fanova.get_marginal_for_value(dim, grid[i])
            mean[i] = m
            std[i] = s
        mean = np.asarray(mean)
        std = np.asarray(std)

        lower_curve = mean - std
        upper_curve = mean + std

        if np.diff(display_grid).std() > 0.000001 and param_name in self._fanova.get_config_space().get_continuous_parameters():
            #HACK for detecting whether it's a log parameter, because the config space doesn't expose this information
            plt.semilogx(display_grid, mean, 'b')
            print "printing %s semilogx" % param_name
        else:
            plt.plot(display_grid, mean, 'b')
        plt.fill_between(display_grid, upper_curve, lower_curve, facecolor='red', alpha=0.6)
        plt.xlabel(param_name)

        plt.ylabel("Performance")
        return plt
Esempio n. 20
0
def hypers_demo():
    steps, mc = 500, 20
    ssm = UNGM()  # initialize UNGM model
    x, z = ssm.simulate(steps, mc_sims=mc)  # generate some data
    lscale = [1e-3, 3e-3, 1e-2, 3e-2, 1e-1, 3e-1, 1, 3, 1e1, 3e1]  # , 1e2, 3e2]
    sigmas_ut = Unscented.unit_sigma_points(ssm.xD, kappa=0.0)
    mean_f, cov_f = np.zeros((ssm.xD, steps, mc, len(lscale))), np.zeros((ssm.xD, ssm.xD, steps, mc, len(lscale)))
    for iel, el in enumerate(lscale):
        # initialize BHKF with current lenghtscale
        f = GPQuadKalman(ssm, usp_dyn=sigmas_ut, usp_meas=sigmas_ut,
                         hyp_dyn={'sig_var': 1.0, 'lengthscale': el * np.ones(ssm.xD, ), 'noise_var': 1e-8},
                         hyp_meas={'sig_var': 1.0, 'lengthscale': el * np.ones(ssm.xD, ), 'noise_var': 1e-8})
        # filtering
        for s in range(mc):
            mean_f[..., s, iel], cov_f[..., s, iel] = f.forward_pass(z[..., s])

    # compute average (over MC sims) RMSE and NCI
    rmseVsEl = rmse(x, mean_f).mean(axis=1)
    nciVsEl = nci(x, mean_f, cov_f).mean(axis=1)
    # plot influence of changing lengthscale on the RMSE and NCI filter performance
    plt.figure()
    plt.semilogx(lscale, rmseVsEl.squeeze(), color='k', ls='-', lw=2, marker='o', label='RMSE')
    plt.semilogx(lscale, nciVsEl.squeeze(), color='k', ls='--', lw=2, marker='o', label='NCI')
    plt.grid(True)
    plt.legend()
    plt.show()
    return lscale, rmseVsEl, nciVsEl
Esempio n. 21
0
def MakeAndPlotReadCountHistogram(readCountArray, plotCumulative=False, plotHistogram=False, \
title='', xlabel='', ylabel='', cumTitle='', cumXlabel='', cumYlabel='', binWidth=1):
	
	import numpy
	import matplotlib.pyplot as plt
	
	bins = numpy.arange(0, max(readCountArray)+binWidth, binWidth)
	values, base = numpy.histogram(readCountArray, bins=bins)
	cumulative = numpy.cumsum(values)
	
	binCenters = ConvertBinEdgesToCenters(base)	
	
	if plotCumulative:
		plt.figure()
		plt.semilogx(base[:-1],cumulative/max(cumulative))
		plt.title(cumTitle)
		plt.xlabel(cumXlabel)
		plt.ylabel(cumYlabel) 
		plt.show()
	
	if plotHistogram:
		plt.figure()
		plt.plot(binCenters, values)
		plt.title(title)
		plt.xlabel(xlabel)
		plt.ylabel(ylabel) 
		plt.show()

	
	return [bins, values, base, cumulative]
Esempio n. 22
0
def bode(G, w1, w2, label='Figure', margin=False):
    """ 
    Shows the bode plot for a plant model
    
    Parameters
    ----------
    G : tf
        plant transfer function
    w1 : real
        start frequency
    w2 : real
        end frequency
    label : string
        title for the figure (optional)
    margin : boolean
        show the cross over frequencies on the plot (optional)        
          
    Returns
    -------
    GM : array containing a real number      
        gain margin
    PM : array containing a real number           
        phase margin         
    """

    GM, PM, wc, w_180 = margins(G)

    # plotting of Bode plot and with corresponding frequencies for PM and GM
#    if ((w2 < numpy.log(w_180)) and margin):
#        w2 = numpy.log(w_180)  
    w = numpy.logspace(w1, w2, 1000)
    s = 1j*w

    plt.figure(label)
    # Magnitude of G(jw)
    plt.subplot(211)
    gains = numpy.abs(G(s))
    plt.loglog(w, gains)
    if margin:
        plt.axvline(w_180, color='black')
        plt.text(w_180, numpy.average([numpy.max(gains), numpy.min(gains)]), r'$\angle$G(jw) = -180$\degree$')
    plt.axhline(1., color='red')
    plt.grid()
    plt.ylabel('Magnitude')

    # Phase of G(jw)
    plt.subplot(212)
    phaseangle = phase(G(s), deg=True)
    plt.semilogx(w, phaseangle)
    if margin:
        plt.axvline(wc, color='black')
        plt.text(wc, numpy.average([numpy.max(phaseangle), numpy.min(phaseangle)]), '|G(jw)| = 1')
    plt.axhline(-180., color='red')
    plt.grid()
    plt.ylabel('Phase')
    plt.xlabel('Frequency [rad/unit time]')
    
    plt.show()

    return GM, PM
Esempio n. 23
0
def plotValidationCurve(c, training_avgs, validation_avgs, model_name,
                        x_label = 'C'):
    """                                                                                                                                                       
    This function plots the training and validation averages                                                                                                  
    Against the parameter we are trying to optimize                                                                                                           
    """
    plt.clf()
    
    p1, = plt.plot(c, training_avgs, 'ro-', label = 'training')
    p2, = plt.plot(c, validation_avgs, 'go-', label = 'validation')

    plt.xlabel(x_label, fontsize = 16)
    plt.ylabel('Score', fontsize = 16)

    plt.title(model_name + ' Validation Curve',
              fontdict = {'fontsize': 16})
    plt.legend(loc = 0)
    plt.semilogx()

    # now save the figure                                                                                   
    model_name = re.sub(r'\W', '_', model_name)
    plt.savefig(model_name + '_validation.png',
                format = 'png')
    
    return None
Esempio n. 24
0
File: plot2.py Progetto: POFK/Tide
def Pl(Outfile,line='-.',label=''):
    dd=np.loadtxt(Outfile+'PS_DD')
    dk=np.loadtxt(Outfile+'PS_DK')
    kk=np.loadtxt(Outfile+'PS_KK')
    halo=np.loadtxt('/home/mtx/data/tide/outdata/test/PS_haloDD')
    #plt.figure('Power Spectrum')
    #n=np.ones_like(kk[:,1])
    #plt.loglog(dd[:,0],dd[:,1],'b.-',label='P_DD')
    #plt.loglog(halo[:,0],halo[:,1],'m.-',label='P_halo')
    #plt.loglog(dk[:,0],dk[:,1],'g.-',label='P_DK')
    #plt.loglog(kk[:,0],kk[:,1],'r.-',label='P_KK')
    #plt.loglog(kk[:,0],n*noise3,'k-.',alpha=0.8,label='noise')
    #plt.title('Power Spectrum')
    #plt.xlabel('k $(h/Mpc)$')
    #plt.ylabel('P(k) $(Mpc^{3}/h^{3})$')
    #plt.legend()
    #plt.ylim(10**1,6*10**4)
    #plt.xlim([9*10**-3,1])
    ##plt.savefig(name+'PS.eps')
    
    plt.figure('correlation coefficient')
    plt.title('correlation coefficient')
    plt.semilogx(kk[:,0],dk[:,1]/np.sqrt(dd[:,1]*kk[:,1]),line,label=label)
    plt.xlabel('k $(h/Mpc)$')
    plt.ylabel('r')
Esempio n. 25
0
 def plot_fft(self, plotname=None, window='hann', normalise=True, **kwargs):
     """Make a plot (in the frequency domain) of all channels"""
     
     ymin = kwargs.get('ymin', -160) #dB
     
     freq, mag = self.fft(window=window, normalise=normalise)
     
     fig_id = 1
     plt.figure(fig_id)
     
     #plt.semilogx(freq, mag, **kwargs)   # plots all channel directly
     plt.hold(True)
     for ch in range(self.ch):
         plt.semilogx(freq, mag[:,ch], label='ch%2i' %(ch+1))
     plt.hold(False)
     
     plt.xlim(xmin=1)    # we're not interested in freqs. below 1 Hz
     plt.ylim(ymin=ymin)
     
     plt.xlabel('Frequency [Hz]')
     plt.ylabel('Magnitude [dB]')
     
     plt.legend(loc='best')
     plt.grid(True)
     
     if plotname is None:
         plt.show()
     else:
         plt.savefig(plotname)
         plt.close(fig_id)
Esempio n. 26
0
 def plotActiveFilters(self, colour='r'):
     if self.initialized:
         plt.semilogx(self.freqs, 10 *
                      np.log10(self.wActive + 1e-10), colour)
         plt.xlabel('Frequency, Hz')
         plt.ylabel('Response, dB')
         plt.show()
Esempio n. 27
0
def make_plot():
    def u(t):
        return sym.exp(-a*t)

    a, t, dt, p = sym.symbols('a t dt p')
    dudt = sym.diff(u(t), t)

    from numpy import logspace, exp
    from matplotlib.pyplot import (
        semilogx, legend, show, loglog, savefig)

    # Map operator function name to logical names
    operator2name = dict(
        D_f='forward', D_b='backward', D_c='central')
    legends = []
    for operator in D_f, D_b, D_c:
        E = operator(u, dt, t)/dudt
        # Expand, set p=a*dt, simplify
        E = sym.expand(E)
        E = E.subs(a*dt, p)
        E = sym.simplify(E)
        print '%s E:' % operator2name[operator.__name__], E
        print 'Taylor series:', E.series(p, 0, 3)
        latex_expr = sym.latex(E)

        E = sym.lambdify([p], E, modules='numpy')
        p_values = logspace(-6, -0.5, 101)
        y = E(p_values)
        semilogx(p_values, y)
        legends.append(operator2name[operator.__name__] +
                       ': $' + latex_expr + '$')
    legend(legends, loc='lower left')
    savefig('tmp.png'); savefig('tmp.pdf')
    show()
 def plotDimensionsUpdateFrequencyEstimation(self, returnAxisValuesOnly=True):
     '''
     numberOfTimeUnits=10*24*12
     Experts stream 12
     Houston stream 2
     '''
     dataDistribution = defaultdict(list)
     for line in FileIO.iterateJsonFromFile(self.dimensionsUpdateFrequencyFile):
         for k, v in line[ParameterEstimation.dimensionsUpdateFrequencyId].iteritems():
             k = int(k) / self.timeUnitInSeconds.seconds
             if k not in dataDistribution: dataDistribution[k] = [0., 0.]
             dataDistribution[k][0] += v; dataDistribution[k][1] += 1
     x, y = [], []; [(x.append(k), y.append((dataDistribution[k][0] / dataDistribution[k][1]))) for k in sorted(dataDistribution)]
     x1, y1 = [], []; [(x1.append(k), y1.append((dataDistribution[k][0] / dataDistribution[k][1]) / k)) for k in sorted(dataDistribution)]
     x = x[:numberOfTimeUnits]; y = y[:numberOfTimeUnits]; x1 = x1[:numberOfTimeUnits]; y1 = y1[:numberOfTimeUnits]
     def subPlot(id):
         plt.subplot(id)
         inactivityCorordinates = max(zip(x1, y1), key=itemgetter(1))
         plt.semilogx(x1, y1, '-', color=self.stream_settings['plot_color'], label=getLatexForString(self.stream_settings['plot_label'] + ' (Update frequency=%d TU)' % inactivityCorordinates[0]), lw=2)
         plt.subplot(id).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 3)))
         plt.semilogx([inactivityCorordinates[0]], [inactivityCorordinates[1]], 'o', alpha=0.7, color='r')
         plt.subplot(id).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 3)))
         plt.yticks((min(y1), max(y1)))
         print self.stream_settings['plot_label'], inactivityCorordinates[0]
     plt.subplot(311)
     plt.title(getLatexForString('Dimensions update frequency estimation'))
     plt.semilogx(x, y, '-', color=self.stream_settings['plot_color'], label=getLatexForString(self.stream_settings['plot_label']), lw=2)
     plt.subplot(311).yaxis.set_major_formatter(FuncFormatter(lambda x, i: '%0.1f' % (x / 10. ** 5)))
     plt.text(0.0, 1.01, getLatexForString('10^5'), transform=plt.gca().transAxes)
     plt.ylabel(getLatexForString('\# of decayed dimensions'))
     if self.stream_settings['stream_id'] == 'experts_twitter_stream': subPlot(312)
     else: subPlot(313); plt.xlabel(getLatexForString(xlabelTimeUnits))
     plt.ylabel(getLatexForString('Rate of DD (10^3)'))
     plt.legend(loc=3)
     if returnAxisValuesOnly: plt.show()
Esempio n. 29
0
    def test_frequency(self):
        import scipy.signal as ss
        nsteps = 10000
        dt = 0.1

        t,w = self.regular_integrator.run(self.regular_w0, dt=dt, nsteps=nsteps)
        f,fft = fft_orbit(t, w)

        peak_ix = ss.find_peaks_cwt(fft[:,0], widths=np.linspace(dt*2, dt*100, 10))
        print(peak_ix)

        plt.clf()
        plt.axvline(self.regular_par[1]/(2*np.pi), linewidth=3., alpha=0.35, color='b')
        plt.axvline(1/(2*np.pi), linewidth=3., alpha=0.35, color='r')
        plt.semilogx(f[:,0], fft[:,0], marker=None)
        plt.savefig(os.path.join(plot_path,"pend_fft_regular.png"))

        # ----------------------------------------------------------------------
        t,w = self.chaotic_integrator.run(self.chaotic_w0, dt=dt, nsteps=nsteps)
        f,fft = fft_orbit(t, w)

        peak_ix = ss.find_peaks_cwt(fft[:,0], widths=np.linspace(dt*2, dt*100, 10))
        print(peak_ix)

        plt.clf()
        plt.axvline(self.chaotic_par[1]/(2*np.pi), linewidth=3., alpha=0.35, color='b')
        plt.axvline(1/(2*np.pi), linewidth=3., alpha=0.35, color='r')
        plt.semilogx(f[:,0], fft[:,0], marker=None)
        plt.savefig(os.path.join(plot_path,"pend_fft_chaotic.png"))
Esempio n. 30
0
def main():
	# define paths
	dir			= 'media/results'
	sizefile	= os.path.join(dir,'sizes.csv')
	timefile	= os.path.join(dir,'times.csv')

	# load data
	sizedata = np.loadtxt(open(sizefile,"rb"),delimiter=",")
	timedata = np.loadtxt(open(timefile,"rb"),delimiter=",")

	timedata = 1000*timedata
	
	# calculate mean and standard deviation
	mean_time = timedata.mean(axis=0);
	stdev_time = timedata.std(axis=0);
	
	size	= [elem[0]*elem[1] for elem in sizedata]
	
	t_max	= mean_time+stdev_time
	t_min	= mean_time-stdev_time
	# show data
	plt.figure(facecolor='white')
	#plt.fill_between(size, t_min, t_max, facecolor='blue', interpolate=True,alpha = 0.5)
	plt.fill_between(size, t_min, t_max, facecolor='#8080FF',color='blue',linewidth=0.5, interpolate=True)
	plt.semilogx(size,mean_time, color='blue',linewidth=1)
	plt.title('Computational time vs number of pixels')
	plt.ylim([0,1])
	plt.xlim([min(size),max(size)])
	plt.xlabel("Size [pixels]")
	plt.ylabel("Time [ms]")
	#plt.show()

	# save plot
	plt.savefig('media/plots/size-time.eps',format='eps', facecolor="white")
Esempio n. 31
0
def create_validation_curve(estimator, X_train, y_train, data_name, clf_name,
                            param_name, param_range, scorer):
    """Generates an validation/complexity curve for the ANN estimator, saves
    tabular results to CSV and saves a plot of the validation curve.

    Args:
        estimator (object): Target classifier.
        X_train (numpy.Array): Training features.
        y_train (numpy.Array): Training labels.
        data_name (str): Name of data set being tested.
        clf_name (str): Type of algorithm.
        param_name (dict): Name of parameter to be tested.
        param_range (dict): Range of parameter values to be tested.
        scorer (function): Scoring function.

    """
    # generate validation curve results
    train_scores, test_scores = validation_curve(estimator,
                                                 X_train,
                                                 y_train,
                                                 param_name=param_name,
                                                 param_range=param_range,
                                                 cv=5,
                                                 scoring=scorer,
                                                 n_jobs=1)

    # generate validation curve plot
    plt.figure(4)
    if param_name is 'SVMR__gamma' or param_name is 'MLP__alpha':
        plt.semilogx(param_range,
                     np.mean(train_scores, axis=1),
                     marker='.',
                     color='b',
                     label='Train Score')
        plt.semilogx(param_range,
                     np.mean(test_scores, axis=1),
                     marker='.',
                     color='g',
                     label='Cross-validation Score')
    else:
        plt.plot(param_range,
                 np.mean(train_scores, axis=1),
                 marker='.',
                 color='b',
                 label='Train Score')
        plt.plot(param_range,
                 np.mean(test_scores, axis=1),
                 marker='.',
                 color='g',
                 label='Cross-validation Score')

    plt.legend(loc='best')
    plt.title("Validation Curve with {} on {}".format(clf_name, data_name))
    plt.grid(linestyle='dotted')
    plt.xlabel(param_name)
    plt.ylabel('Balanced Accuracy')
    plt.ylim((0, 1.1))

    # save iteration curve plot as PNG
    plotdir = 'plots'
    plot_tgt = '{}/{}'.format(plotdir, clf_name)
    plotpath = get_abspath('{}_VC.png'.format(data_name), plot_tgt)
    plt.savefig(plotpath)
    plt.close()
k2, cl2, info2 = mixsyn(g, ws2, wu)

# S and T for design 2
s2 = feedback(1, g * k2)
t2 = feedback(g * k2, 1)

# frequency response
omega = np.logspace(-2, 2, 101)
ws1mag, _, _ = ws1.frequency_response(omega)
s1mag, _, _ = s1.frequency_response(omega)
ws2mag, _, _ = ws2.frequency_response(omega)
s2mag, _, _ = s2.frequency_response(omega)

plt.figure(1)
# text uses log-scaled absolute, but dB are probably more familiar to most control engineers
plt.semilogx(omega, 20 * np.log10(s1mag.flat), label='$S_1$')
plt.semilogx(omega, 20 * np.log10(s2mag.flat), label='$S_2$')
# -1 in logspace is inverse
plt.semilogx(omega, -20 * np.log10(ws1mag.flat), label='$1/w_{P1}$')
plt.semilogx(omega, -20 * np.log10(ws2mag.flat), label='$1/w_{P2}$')

plt.ylim([-80, 10])
plt.xlim([1e-2, 1e2])
plt.xlabel('freq [rad/s]')
plt.ylabel('mag [dB]')
plt.legend()
plt.title('Sensitivity and sensitivity weighting frequency responses')

# time response
time = np.linspace(0, 3, 201)
_, y1 = step_response(t1, time)
Esempio n. 33
0
    def visualize(self,
                  plot_psd=True,
                  save_psd=False,
                  filename='psd.png',
                  title='PSD',
                  xlabel='frequency',
                  xlabel_rot=0,
                  ylabel='spectral level',
                  fmin=0,
                  fmax=32000,
                  vmin=20,
                  vmax=80,
                  figsize=(16, 9),
                  dpi=96):
        """
        !!!!! This function will be moved into a different module in the
        future. The current documentation might not be accurate !!!!!

        Basic visualization of PSD estimate based on matplotlib. The function
        offers two options: Plot PSD in Python (plot_psd = True) and save PSD
        plot in directory (save_psd = True). PSDs are plotted in dB re 1µ
        Pa^2/Hz.

        plot_psd (bool): whether or not PSD is plotted using Python
        save_psd (bool): whether or not PSD plot is saved
        filename (str): directory where PSD plot is saved. Use ending ".png"
        or ".pdf" to save as PNG or PDF
            file. This value will be ignored if save_psd=False
        title (str): title of plot
        ylabel (str): label of vertical axis
        xlabel (str): label of horizontal axis
        xlabel_rot (float): rotation of xlabel. This is useful if xlabel are
        longer strings.
        fmin (float): minimum frequency (unit same as f) that is displayed
        fmax (float): maximum frequency (unit same as f) that is displayed
        vmin (float): minimum value (dB) of PSD.
        vmax (float): maximum value (dB) of PSD.
        figsize (tuple(int)): size of figure
        dpi (int): dots per inch
        """
        import warnings
        raise warnings.warn('will be depricated in future. Please see '
                            'ooipy.tools.ooiplotlib.plot_psd()')
        # set backend for plotting/saving:
        if not plot_psd:
            matplotlib.use('Agg')

        font = {'size': 22}
        matplotlib.rc('font', **font)

        if len(self.freq) != len(self.values):
            f = np.linspace(0, len(self.values) - 1, len(self.values))
        else:
            f = self.freq

        fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
        plt.semilogx(f, self.values)
        plt.ylabel(ylabel)
        plt.xlabel(xlabel)
        plt.xlim([fmin, fmax])
        plt.ylim([vmin, vmax])
        plt.xticks(rotation=xlabel_rot)
        plt.title(title)
        plt.grid(True)

        if save_psd:
            plt.savefig(filename, dpi=dpi, bbox_inches='tight')

        if plot_psd:
            plt.show()
        else:
            plt.close(fig)
Esempio n. 34
0
    axarr[2].set_title('$\\mathrm{LASSO},\ \\lambda=%.4f$' %(lmbda),fontsize=16)
    axarr[2].tick_params(labelsize=16)
    
    divider = make_axes_locatable(axarr[2])
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cbar=fig.colorbar(im, cax=cax)
    
    cbar.ax.set_yticklabels(np.arange(-1.0, 1.0+0.25, 0.25),fontsize=14)
    cbar.set_label('$J_{i,j}$',labelpad=-40, y=1.12,fontsize=16,rotation=0)
    
    fig.subplots_adjust(right=2.0)
    
    plt.show()

# Plot our performance on both the training and test data
plt.semilogx(lmbdas, train_errors_leastsq, 'b',label='Train (OLS)')
plt.semilogx(lmbdas, test_errors_leastsq,'--b',label='Test (OLS)')
plt.semilogx(lmbdas, train_errors_ridge,'r',label='Train (Ridge)')#,linewidth=1)
plt.semilogx(lmbdas, test_errors_ridge,'--r',label='Test (Ridge)')#,linewidth=1)
plt.semilogx(lmbdas, train_errors_lasso, 'g',label='Train (LASSO)')
plt.semilogx(lmbdas, test_errors_lasso, '--g',label='Test (LASSO)')

fig = plt.gcf()
fig.set_size_inches(10.0, 6.0)

#plt.vlines(alpha_optim, plt.ylim()[0], np.max(test_errors), color='k',
#           linewidth=3, label='Optimum on test')
plt.legend(loc='lower left',fontsize=16)
plt.ylim([-0.01, 1.01])
plt.xlim([min(lmbdas), max(lmbdas)])
plt.xlabel(r'$\lambda$',fontsize=16)
Esempio n. 35
0
    def plotRatio(self,
                  stageN,
                  stageD,
                  xr=0,
                  yr=0,
                  label=1,
                  title=1,
                  bw=0,
                  semilogx=1,
                  verbose=0):
        '''
        Plots the ratio of the ionization equilibria of two stages of a given element

        self.plotRatio(stageN, stageD)
        stages = sequence of ions to be plotted, neutral == 1, fully stripped == Z+1
        stageN = numerator
        stageD = denominator
        xr = temperature range, yr = ion fraction range

        '''
        ionN = util.zion2name(self.Z, stageN)
        ionD = util.zion2name(self.Z, stageD)
        ionNS = util.zion2spectroscopic(self.Z, stageN)
        ionDS = util.zion2spectroscopic(self.Z, stageD)

        atitle = 'ratio of %s to %s ' % (ionN, ionD)
        alabel = 'ratio of %s to %s ' % (ionNS, ionDS)
        print(atitle)
        if not hasattr(self, 'Ioneq'):
            print(' must first load or calculate an ionization equilibrium')
            return

        if bw:
            linestyle = ['k-', 'k--', 'k-.', 'k:']
            plt.rcParams['font.size'] = 16.
            lw = 2
        else:
            linestyle = ['b-', 'r--', 'g-.', 'm:']
            plt.rcParams['font.size'] = 14.
            lw = 2
        #
        goodTn = self.Ioneq[stageN - 1, :] > 0.
        goodTd = self.Ioneq[stageD - 1, :] > 0.
        realGoodT = np.logical_and(goodTn, goodTd)
        goodT = self.Temperature[realGoodT]
        goodR = self.Ioneq[stageN - 1, realGoodT] / self.Ioneq[stageD - 1,
                                                               realGoodT]
        if not xr:
            xr = [goodT.min(), goodT.max()]
        if not yr:
            yr = [0.01, 1.1]
        xyr = list(xr)
        xyr.extend(list(yr))
        #
        if semilogx:
            plt.semilogx(goodT, goodR, linestyle[0], lw=lw, label=alabel)
        else:
            plt.loglog(goodT, goodR, linestyle[0], lw=lw, label=alabel)
        plt.xlabel('Temperature (K)')
        plt.ylabel('Ratio')
        if title:
            atitle = 'CHIANTI Ionization Equilibrium'
            plt.title(atitle)
        plt.legend(loc='lower right')
        plt.tight_layout()
        self.Ratio = {'Temperature': goodT, 'Ratio': goodR, 'label': alabel}
Esempio n. 36
0
    def plot(self,
             stages=0,
             xr=0,
             yr=0,
             oplot=False,
             label=1,
             title=1,
             bw=0,
             semilogx=0,
             verbose=0):
        '''
        Plots the ionization equilibria.

        self.plot(xr=None, yr=None, oplot=False)
        stages = sequence of ions to be plotted, neutral == 1, fully stripped == Z+1
        xr = temperature range, yr = ion fraction range

        for overplotting:
        oplot="ioneqfilename" such as 'mazzotta'
        or if oplot=True or oplot=1 and a widget will come up so that a file can be selected.
        '''
        if hasattr(self, 'Ioneq'):
            ioneq = getattr(self, 'Ioneq')
        else:
            print(' must first load or calculate and ionization equilibrium')
            return

        if bw:
            linestyle = ['k-', 'k--', 'k-.', 'k:']
            plt.rcParams['font.size'] = 16.
            lw = 2
        else:
            linestyle = ['b-', 'r--', 'g-.', 'm:']
            plt.rcParams['font.size'] = 14.
            lw = 2
        #
        if not stages:
            stages = range(1, self.Z + 2)
        elif min(stages) < 1 or max(stages) > self.Z + 1:
            stages = range(1, self.Z + 2)  #  spectroscopic notation
        if not xr:
            xr = [self.Temperature.min(), self.Temperature.max()]
        if not yr:
            yr = [0.01, 1.1]
        xyr = list(xr)
        xyr.extend(list(yr))
        #
        iz = stages[0]
        if semilogx:
            plt.semilogx(self.Temperature, ioneq[iz - 1], linestyle[0], lw=lw)
        else:
            plt.loglog(self.Temperature, ioneq[iz - 1], linestyle[0], lw=lw)
        if label:
            idx = self.Ioneq[iz - 1] == self.Ioneq[iz - 1].max()
            if idx.sum() > 1:
                jdx = np.arange(len(idx))
                idx = int(jdx[idx].max())
            ann = const.Ionstage[iz - 1]
            plt.annotate(ann,
                         [self.Temperature[idx], 0.7 * ioneq[iz - 1, idx]],
                         ha='center')
        for iz in stages[1:]:
            if semilogx:
                plt.semilogx(self.Temperature,
                             ioneq[iz - 1],
                             linestyle[0],
                             lw=lw)
            else:
                plt.loglog(self.Temperature,
                           ioneq[iz - 1],
                           linestyle[0],
                           lw=lw)
            if label:
                idx = ioneq[iz - 1] == ioneq[iz - 1].max()
                if idx.sum() > 1:
                    jdx = np.arange(len(idx))
                    idx = int(jdx[idx].mean())
                ann = const.Ionstage[iz - 1]
                plt.annotate(ann,
                             [self.Temperature[idx], 0.7 * ioneq[iz - 1, idx]],
                             ha='center')
        plt.xlabel('Temperature (K)')
        plt.ylabel('Ion Fraction')
        atitle = 'Chianti Ionization Equilibrium for ' + const.El[
            self.Z - 1].capitalize()
        #
        if oplot:
            if isinstance(oplot, int):
                result = io.ioneqRead(ioneqName='')
                #                print('keys = ', result.keys()
                if result != False:
                    atitle += '  & ' + result['ioneqname'].replace(
                        '.ioneq', '')
                    atitle += ' ' + linestyle[0]
                    for iz in stages:
                        plt.plot(result['ioneqTemperature'],
                                 result['ioneqAll'][self.Z - 1, iz - 1],
                                 linestyle[1],
                                 lw=lw)
            elif type(oplot) == type('string'):
                atitle += '  & ' + oplot
                result = io.ioneqRead(ioneqname=oplot)
                if result != False:
                    for iz in stages:
                        plt.plot(result['ioneqTemperature'],
                                 result['ioneqAll'][self.Z - 1, iz - 1],
                                 linestyle[1],
                                 lw=lw)
            elif type(oplot) == type([]):
                for iplot in range(len(oplot)):
                    result = io.ioneqRead(ioneqname=oplot[iplot])
                    #                    print 'keys = ', result.keys()
                    if result != False:
                        atitle += '  & ' + oplot[iplot] + ' ' + linestyle[iplot
                                                                          % 3]
                        for iz in stages:
                            plt.plot(result['ioneqTemperature'],
                                     result['ioneqAll'][self.Z - 1, iz - 1],
                                     linestyle[1],
                                     lw=lw)
            else:
                print(' oplot file not understood %s' % (oplot))
        if title:
            plt.title(atitle)
        plt.tight_layout()
        plt.axis(xyr)
Esempio n. 37
0
if options.format == None:
    plt.show()  # Showing graph
else:
    plt.savefig(filename + "_power." + options.format)  # Saving graph
plt.clf()  # Cleaning current plot.

gain = 10 * np.log10(padc / pdac)  # Calculating Gain in dB

# -3 dB is an important number, isn't it?
y_ticks = np.array([
    -40, -36, -33, -30, -26, -23, -20, -16, -13, -10, -6, -3, -1, 0, 1, 3, 6,
    10, 13, 16, 20, 23, 26, 30, 33, 36, 40
])

plt.semilogx(f, gain)
plt.yticks(y_ticks[(y_ticks < (gain.max() + 1))
                   & (y_ticks > (gain.min() - 1))])
plt.grid(b=True)
plt.grid(b=True, which='minor')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain (dB)')

if options.format == None:
    plt.show()
else:
    plt.savefig(filename + "_gain." + options.format)
plt.clf()

# Samples
plt.plot(3.3 * dac[-1000:-1] / 4096, 'x')
Esempio n. 38
0
                            ],
                    name=model_name
                            )

optimizer = SGD(lr=1e-8, momentum=0.9)
model.compile(loss="mse", optimizer=optimizer, metrics=['mae'])

#%%
# Training
epochs = 100
lr_schedule = LearningRateScheduler(lambda epoch: 1e-8 * 10**(epoch / 20))
history_lrs = model.fit(dataset, epochs=epochs, callbacks=[lr_schedule, tensorboard_callback], verbose=1)

#%%
# Visualizing Learning Rates
plt.semilogx(history_lrs.history['lr'], history_lrs.history["loss"])
plt.axis([1e-8, 1e-3, 0, 300])

#%%
# Repeat with the minimum learning rate
#%%
# Learning Rate Scheduler
dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)

model_name = f'seq_rnn-1010'

model = Sequential(layers=[
                            Conv1D(filters=32, kernel_size=5, strides=1, padding="causal", activation="relu", input_shape=[None, 1]),
                            Bidirectional(LSTM(32, return_sequences=True)),
                            Bidirectional(LSTM(32)),
                            Dense(1),
Esempio n. 39
0
for x0 in xx0:
    t, x = sol.ode1(system, x0, t0, tf, h)
    if x0 >= 0:
        T_x0[i] = np.argmax(np.abs(x) < 1.5e-4) * h
        i += 1
    plt.figure(num=1)
    plt.plot(t, x[0], color=0 * np.ones(3))

# Trajectories
plt.figure(num=1)
plt.ylim(-3, 5)
plt.xlim(0, 1.2)
plt.xlabel('$t$', fontsize=18)
plt.ylabel('$x(t,x_0)$', fontsize=18)
plt.axvline(x=1, ymin=-1, ymax=2, linestyle='dashed', color=0.3 * np.ones(3))
plt.grid()
plt.savefig('figures/basic.eps', bbox_inches='tight', format='eps', dpi=1500)

# Settling-time function figure
plt.figure(num=2)
plt.semilogx(xx0, T_x0, 'k', lw=2)
plt.grid()
plt.xlabel('|$x_0$|', fontsize=18)
plt.ylabel('$T(x_0)$', fontsize=18)
plt.axhline(y=1, xmin=-1, xmax=2, linestyle='dashed', color=0.3 * np.ones(3))
plt.ylim(0, 1.2)
plt.savefig('figures/settling_basic.eps',
            bbox_inches='tight',
            format='eps',
            dpi=1500)
Esempio n. 40
0
    Dx.append(stokeslaw(l1, l0))
    Dy.append(stokeslaw(l0, l1))
    Dxy.append(stokeslaw(l1, l1))

import matplotlib.pyplot as plt

D = {"r": Dx, "z": Dy, "rz": Dxy}

for s in D:
    fname = "confinement_%s.eps" % s
    plt.plot(lrange, D[s], 's-')
    plt.xlabel("distance of confining wall compared to particle radius")
    plt.ylabel("dimensionless diffusion constant D/D_bulk")
    plt.savefig(fname, bbox_inches='tight')
    plt.show()

    fname = "confinement_%s_semilogx.eps" % s
    plt.semilogx(lrange, D[s], 's-')
    plt.xlabel("distance of confining wall compared to particle radius")
    plt.ylabel("dimensionless diffusion constant D/D_bulk")
    plt.savefig(fname, bbox_inches='tight')
    plt.show()

    fname = "confinement_%s_loglog.eps" % s
    plt.loglog(lrange, D[s], 's-')
    plt.xlabel("distance of confining wall compared to particle radius")
    plt.ylabel("dimensionless diffusion constant D/D_bulk")
    plt.savefig(fname, bbox_inches='tight')
    plt.show()
    #plt.legend(loc='lower right')
speedW = []

for i in range(len(N)):
    s = timeS[0] / timeS[i]
    speedS.append(s)
    w = timeW[0] / timeW[i]
    speedW.append(w)

# print(speedW)
# print(speedS)
# # # Plotting
fig = plt.figure()
plt.semilogx(N,
             speedS,
             'black',
             label='Strong scaling',
             marker='o',
             markerfacecolor='red',
             markersize=4)
plt.semilogx(N,
             speedW,
             'blue',
             label='Weak scaling',
             marker='o',
             markerfacecolor='black',
             markersize=4)
# # plt.semilogy(N, speedS, 'black', label='Strong scaling',
# #                         marker='o', markerfacecolor='red', markersize=4)
# # plt.semilogy(N, speedW, 'blue', label='Weak scaling',
# #                         marker='o', markerfacecolor='red', markersize=4)
# # ## Theoritical error of MC: err is proportional to Itr ^ (-1/2) ###
Esempio n. 42
0
                          secondtimes) * np.transpose(bigfai) * t_train_use

        bigfai_val = a1.func_x_times(x_val, 2)
        y_val = np.transpose(w) * np.transpose(bigfai_val)
        t_val_error = t_val - np.transpose(y_val)
        rms_val_error = np.sqrt(np.mean(np.square(t_val_error)))
        validation_err += rms_val_error
    validation_err_avg[lamda] = validation_err / 10


regression_reg(0,
               2)  # replace lambda=0 with lambda=10^-5 for plotting purpose.
regression_reg(0.01, 2)
regression_reg(0.1, 2)
regression_reg(1, 2)
regression_reg(10, 2)
regression_reg(100, 2)
regression_reg(1000, 2)
regression_reg(10000, 2)

label = sorted(validation_err_avg.keys())
error = []
for key in label:
    error.append(validation_err_avg[key])
print(error)
plt.semilogx(label, error)
plt.ylabel('Average RMS')
plt.legend(['Average Validation error'])

plt.show()
Esempio n. 43
0
for ws in weight_scales:
  best_train_accs.append(max(solvers_ws[ws].train_acc_history))
  bn_best_train_accs.append(max(bn_solvers_ws[ws].train_acc_history))
  
  best_val_accs.append(max(solvers_ws[ws].val_acc_history))
  bn_best_val_accs.append(max(bn_solvers_ws[ws].val_acc_history))
  
  final_train_loss.append(np.mean(solvers_ws[ws].loss_history[-100:]))
  bn_final_train_loss.append(np.mean(bn_solvers_ws[ws].loss_history[-100:]))
  
plt.subplot(3, 1, 1)
plt.title('Best val accuracy vs weight initialization scale')
plt.xlabel('Weight initialization scale')
plt.ylabel('Best val accuracy')
plt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')
plt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')
plt.legend(ncol=2, loc='lower right')

plt.subplot(3, 1, 2)
plt.title('Best train accuracy vs weight initialization scale')
plt.xlabel('Weight initialization scale')
plt.ylabel('Best training accuracy')
plt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')
plt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')
plt.legend()

plt.subplot(3, 1, 3)
plt.title('Final training loss vs weight initialization scale')
plt.xlabel('Weight initialization scale')
plt.ylabel('Final training loss')
Esempio n. 44
0
ax.set_ylabel('$y$')
ax.set_zlabel('$u$')
fig.colorbar(surf, shrink=0.75, orientation='horizontal', label='$u$')

ax = fig.add_subplot(gs[1], projection='3d')
surf = ax.plot_surface(x_test[:, :, 0],
                       y_test[:, :, 0],
                       np.abs(u_analytic[:, :, -1] - u_pred[:, :, -1]),
                       vmin=0.,
                       cmap='hot_r')
ax.set_xlabel('$x$')
ax.set_ylabel('$y$')
ax.set_zlabel('$|u-u^*|$', labelpad=10)
cbar = fig.colorbar(surf,
                    shrink=0.75,
                    orientation='horizontal',
                    label='$|u-u^*|$')
cbar.formatter.set_powerlimits((0, 0))
# cbar.ax.set_xticklabels(np.linspace(0, 0.0012, 5), rotation=90, )

plt.savefig('membrane_inv-results.pdf', dpi=300)

fig = plt.figure(figsize=(4, 3))
plt.semilogx(h.history['parameter_epochs'],
             np.concatenate(h.history['parameter_c']).flatten())
plt.xlabel('epochs')
plt.ylabel('$c$')
plt.title('$c^* = 1.0$')
plt.subplots_adjust(0.2, 0.15, 0.8, 0.85)
plt.savefig('membrane_inv-resylts2.pdf', dpi=300)
Esempio n. 45
0
def plot_exptime_vs_limiting_mag(exptimes,
                                 limiting_mags,
                                 filter_names=["J", "H", "Ks"],
                                 colors="bgrcymk",
                                 mmin=22,
                                 mmax=29,
                                 legend_loc=3,
                                 marker="+"):
    """
    Plots exposure time versus limiting magnitudes


    Parameters
    ----------
    exptimes : list, array
        [s] Exposure times corresponding to the signal-to-noise values

    limiting_mags : array, list of array
        [mag] Limiting magnitudes for one, or more, filters for the given exposure times
        Dimensions are (1, n) for a single filter, or (m, n) for m filters

    filter_names : list
        A list of m filters. See :func:`simcado.optics.get_filter_set`

    colors : list
        The colours to use for dots in the plot

    mmin, mmax : float
        The minimum and maximum magnitudes for the y axis

    marker : str
        The matplotlib scatter marker key

    legend_loc : int
        Location of the legend. If ``None`` is passed, no legend is plotted

    """

    import matplotlib.pyplot as plt

    if len(np.shape(limiting_mags)) == 1:
        limiting_mags = [limiting_mags]
    if filter_names is None:
        filter_names = [
            "Filter " + str(i) for i in range(np.shape(limiting_mags)[0])
        ]

    elif isinstance(filter_names, str):
        filter_names = [filter_names] * np.shape(limiting_mags)[0]

    exptimes = np.array(exptimes)

    fig = plt.gcf()

    #ax = fig.add_axes([a_left, a_bottom, ax_width, ax_height])
    ax1 = fig.add_axes([0, 0, 1, 1])

    for mag, clr, filt in zip(limiting_mags, colors, filter_names):
        plt.plot(exptimes / 3600, mag, clr + marker, label=filt)

    if legend_loc is not None:
        plt.legend(loc=legend_loc, scatterpoints=1)

    plt.xlabel("Exposure time [hours]")
    plt.ylabel("Limiting Magnitudes")
    plt.xlim(np.min(exptimes / 3600) - 0.1, np.max(exptimes / 3600) + 0.1)
    plt.ylim(22, 31)

    plt.grid("on")

    ax2 = fig.add_axes([0.5, 0.15, 0.45, 0.35])

    for mag, clr in zip(limiting_mags, colors):
        plt.plot(exptimes, mag, clr + marker)

    plt.plot((60 * 1, 60 * 1), (mmin, mmax), "k:")
    plt.text(60 * 1 - 5, mmin + 0.5, "1 min", horizontalalignment="right")
    plt.plot((60 * 4, 60 * 4), (mmin, mmax), "k:")
    plt.text(60 * 4 - 5, mmin + 0.5, "4 min", horizontalalignment="right")
    plt.plot((60 * 15, 60 * 15), (mmin, mmax), "k:")
    plt.text(60 * 15 - 5, mmin + 0.5, "15 min", horizontalalignment="right")

    plt.xlim(10, 1800)
    plt.ylim(mmin, mmax)
    plt.semilogx()
    plt.xlabel("Exposure time [sec]")
    history = model.fit(dataset, epochs=100, callbacks=[lr_schedule])
    
    return history


# In[89]:


# Run the training with dynamic LR
lr_history = adjust_learning_rate(train_set)


# In[91]:


plt.semilogx(lr_history.history["lr"], lr_history.history["loss"])
plt.axis([1e-4, 10, 0, 10])


# ## Compiling the model
# Now that you have trained the model while varying the learning rate, it is time to do the actual training that will be used to forecast the time series. For this complete the `create_model` function below.
# 
# Notice that you are reusing the architecture you defined in the `create_uncompiled_model` earlier. Now you only need to compile this model using the appropriate loss, optimizer (and learning rate).
# 
# Hints:
# 
# - The training should be really quick so if you notice that each epoch is taking more than a few seconds, consider trying a different architecture.
# 
# 
# - If after the first epoch you get an output like this: loss: nan - mae: nan it is very likely that your network is suffering from exploding gradients. This is a common problem if you used SGD as optimizer and set a learning rate that is too high. If you encounter this problem consider lowering the learning rate or using Adam with the default learning rate.
Esempio n. 47
0
            learning_rate=3,
            max_iter=100,
            cv=3,
            verbose=True)

print("gl_glm: ", gl_glm)
print("glm: ", glm)

##########################################################
# Fit models

gl_glm.fit(Xtrain, ytrain)
glm.fit(Xtrain, ytrain)

##########################################################
# Visualize model scores on test set

plt.figure()
plt.semilogx(gl_glm.reg_lambda, gl_glm.scores_, 'go-')
plt.semilogx(glm.reg_lambda, glm.scores_, 'ro--')
plt.legend(['Group Lasso', 'Lasso'], frameon=False, loc='best')
plt.xlabel('$\lambda$')
plt.ylabel('pseudo-$R^2$')

plt.tick_params(axis='y', right='off')
plt.tick_params(axis='x', top='off')
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.show()
Esempio n. 48
0
                     [2, 3])
    Ebeam = col.beam_atte[0].E_ref
    dens = col.beam_atte[0].densities
    T = col.beam_atte[0].temperature
    lifetime = np.zeros((T.shape[0], dens.shape[0]))
    for i, t in enumerate(T):
        lifetime[i, :] = col.get_lifetime(dens, t, t, Ebeam, 1.0, 0)
    plt.figure()
    plt.contourf(dens, T, lifetime)
    plt.colorbar()
    plt.show()

    'small check for the emission and the beam stopping coefficient'
    ne = np.linspace(np.min(dens), np.max(dens), 1000)
    t_ref = T[4]
    at = col.get_attenutation(Ebeam, ne, 1.0, t_ref, 0)
    em = col.get_emission(Ebeam, ne, 1.0, t_ref, 0)
    if ((at < 0) | (em < 0)).any():
        print np.sum(at < 0), at[at < 0]
        print np.sum(em < 0), em[em < 0]
        plt.figure()
        plt.semilogx(ne, em < 0, label='emission')
        plt.semilogx(ne, at < 0, label='attenuation')
        plt.semilogx(dens, dens > 0, 'x')
        plt.legend()

        plt.figure()
        plt.semilogx(ne, em)
        plt.show()
        raise NameError('Error in the interpolation or in the ADAS file')
Esempio n. 49
0
def plot_lr_schedule(history):
    plt.figure(figsize=(10, 6))
    plt.semilogx(history.history["lr"], history.history["loss"])
    plt.axis([1e-8, 1e-4, 0, 30])
    plt.show()
Esempio n. 50
0
#Defining the transfer function  T(s)
#Since the transfer function T(s) is  (s+2)/(s^4 + 12s^3 + 47s^2 + 60s)
s1 = signal.lti([1 * k, 2 * k], [1, 12, 47, 60, 0])
w, mag, phase = signal.bode(s1)

#Wpc -phase crossover freq. using builtin functions
s = ml.tf('s')
gm, pm, Wpc, Wgc = ml.margin(
    (k * s + 2 * k) / (s**4 + 12 * s**3 + 47 * s**2 + 60 * s))

#Verifying Gain Margin of G(s)
gm = 20 * log10(gm)
print('Gain Margin of G(s) =', gm, ', when K is substituted')

plt.subplot(2, 1, 1)
plt.semilogx(w, mag, 'b', label='_nolegend_')  # Bode Magnitude plot
plt.plot(Wpc, -38, 'o', label='_nolegend_')
plt.xlabel('Frequency(rad/s)')
plt.ylabel('Mag')
plt.axhline(y=-RN, xmin=0, xmax=Wpc, color='b', linestyle='dashed')
plt.axvline(x=Wpc, ymin=0, ymax=0.56, color='k', linestyle='dashed')
plt.text(1.0, -60, '({}, {})'.format(round(Wpc, 2), -38))
plt.legend(['-38 dB line'], loc='lower left')
plt.grid()

plt.subplot(2, 1, 2)
plt.semilogx(w, phase, label='_nolegend_')  #Bode Pahse plot
plt.plot(Wpc, -180, 'o', label='_nolegend_')
plt.subplot(2, 1, 2)
plt.xlabel('Frequency(rad/s)')
plt.ylabel('Phase(deg)')
        plt.plot(y_array,
                 dsdxdy,
                 label="CalculationValues",
                 color="blue",
                 lw=2)
        spllist = np.power(
            10.,
            glam.grideval(result, [
                np.array([np.log10(q2)]),
                np.array([np.log10(x)]),
                np.log10(y_array)
            ])[0])
        #print spllist[0]
        plt.plot(y_array,
                 spllist[0],
                 label="InterValues",
                 color="red",
                 lw=2,
                 ls="dashed")
        plt.semilogx()
        plt.title(r"$Q2 = " + str(q2) + "," + " x = " + str(x) + "$")
        plt.legend(loc="lower left")
        plt.xlabel("y")
        plt.ylabel("dsigma/dxdy")

        plt.savefig("./plots/dsdxdy_" + pdfname + "_" + neutype + "_" +
                    str(q2) + "_" + str(x) + "_" + variation + ".png")
        print "Saved: ./plots/dsdxdy_" + pdfname + "_" + neutype + "_" + str(
            q2) + "_" + str(x) + "_" + variation + ".png"
        plt.close(fig)
Esempio n. 52
0
f2 = np.convolve(f, np.ones((N, )) / N, mode='same')
pref = np.convolve(pref, np.ones((N, )) / N, mode='same')

minfre = .16
maxfre = .3

scale = np.mean(pref[(f2 >= minfre) & (f2 <= maxfre)]) - np.mean(
    ps[0][(f >= minfre) & (f <= maxfre)])
print(scale)

scaleHF = np.mean(pm[(f >= 10.) & (f <= 11.)]) - np.mean(
    pmHF[(fHF >= 10.) & (fHF <= 11.)])

numb = 20
fig = plt.figure(1, figsize=(12, 12))
plt.semilogx(f2[numb:-numb], pref[numb:-numb], c='.5', label='STS-2 Reference')
plt.semilogx(f[numb:-numb],
             pm[numb:-numb] + scale,
             color='b',
             label='Mean Nodal Noise')
plt.semilogx(f[numb:-numb],
             nm[numb:-numb] + scale,
             color='r',
             label='Mean Nodal Incoherent Noise')
plt.semilogx(fHF[numb:-numb], pmHF[numb:-numb] + scale + scaleHF, color='b')
plt.semilogx(fHF[numb:-numb], nmHF[numb:-numb] + scale + scaleHF, color='r')

plt.semilogx(1. / NLNMper, NLNMpower, linewidth=2., color='k')
plt.semilogx(1. / NHNMper,
             NHNMpower,
             linewidth=2.,
Esempio n. 53
0
    tf.keras.layers.Bidirectional(
        tf.keras.layers.LSTM(32, return_sequences=True)),
    tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
    tf.keras.layers.Dense(1),
    tf.keras.layers.Lambda(lambda x: x * 10.0)
])

lr_schedule = tf.keras.callbacks.LearningRateScheduler(
    lambda epoch: 1e-8 * 10**(epoch / 20))
optimizer = tf.keras.optimizers.SGD(lr=1e-8, momentum=0.9)
model.compile(loss=tf.keras.losses.Huber(),
              optimizer=optimizer,
              metrics=["mae"])
history = model.fit(dataset, epochs=100, callbacks=[lr_schedule])

plt.semilogx(history.history["lr"], history.history["loss"])
plt.axis([1e-8, 1e-4, 0, 30])

tf.keras.backend.clear_session()
tf.random.set_seed(51)
np.random.seed(51)

tf.keras.backend.clear_session()
dataset = windowed_dataset(x_train, window_size, batch_size,
                           shuffle_buffer_size)

model = tf.keras.models.Sequential([
    tf.keras.layers.Lambda(lambda x: tf.expand_dims(x, axis=-1),
                           input_shape=[None]),
    tf.keras.layers.Bidirectional(
        tf.keras.layers.LSTM(32, return_sequences=True)),
#if using termux
import subprocess
import shlex
#end if

gain = [50]
poles=[0,-2,-4,-6]
zeros=[-3,-5]
system = signal.lti(zeros,poles,gain)
w , mag, phase = signal.bode(system)

plt.subplot(2,1,1)
plt.xlabel('Frequency(rad/sec)')	# Bode Magnitude plot
plt.ylabel('Mag')
plt.title('Magnitude plot')
plt.semilogx(w, mag,'b')        
plt.axhline(y = 0,xmin=0,xmax= 0.68,color = 'r',linestyle='dashed')
plt.axvline(x = 6.43,ymax=0.4,color='k',linestyle='dashed')
plt.plot(6.43,0,'o')
plt.text(6.45,2, '({}, {})'.format(6.43,0))
plt.axhline(y = -7,xmin=0,xmax= 0.72,color = 'r',linestyle='dashed')
plt.axvline(x = 10.1,ymax=0.38,color='k',linestyle='dashed')
plt.plot(10.1,-7,'o')
plt.text(10.4,-7.4, '({}, {})'.format(10.1,-7))
plt.grid()

plt.subplots_adjust(hspace=0.5)

plt.subplot(2,1,2)
plt.xlabel('Frequency(rad/s)')		# Bode phase plot
plt.ylabel('Phase(deg)')
Esempio n. 55
0
    nonlinear = False
    with open(filename, 'r') as logfile:
        for line in logfile:
            words = line.split()
            if words[0] == 'Elements' and words[1] == 'QoI':
                use = True
                continue
            if words[0] == 'nonlinear':
                nonlinear = words[-1] == 'True'
            if use:
                elements.append(int(words[0]))
                qois.append(float(words[1]))
    qois = np.array(qois)
    # init_diff = np.zeros(len(qois)) if qois_old is None else qois[0] - qois_old[0]
    # qois_old = qois
    # plt.semilogx(elements, qois - init_diff, label='Nonlinear SWEs' if nonlinear else 'Linear SWEs')
    plt.semilogx(elements,
                 qois,
                 linestyle='--',
                 marker='o',
                 label='Nonlinear SWEs' if nonlinear else 'Linear SWEs')
plt.xlabel("Element count")
plt.ylabel(r"Quantity of interest, $J(\mathbf{u},\eta)$")
plt.legend()
date = datetime.date.today()
date = '{:d}-{:d}-{:d}'.format(date.year, date.month, date.day)
di = create_directory(
    os.path.join(di, '{:s}-runs-{:s}'.format(date,
                                             '-'.join([r for r in runs]))))
plt.savefig(os.path.join(di, 'qoi_convergence.png'))
Esempio n. 56
0

def satview(h):
    a = np.pi * 0.5 - np.arcsin(R / (R + h))
    o = 4 * np.pi * np.sin(a * 0.5)**2
    return o * R**2


mansee = satview(H)  # ca 72 km**2

Hiss = 370.0e3  # ISS, Hubble
Hsun = 800.0e3  # sun-syncro satellites, science obs, Iridium satellites (flares in the sky)
Hmeo = 20.2e6  # GNSS
Hgeo = 35.786e6  #

Hbm = 29.0e6  # distance for Blue marble
Hma = 405.4e6  # Moon apogee
Hl1 = 1.4811e11  # Lagrangian point L1 Earth-Sun system
H = np.logspace(np.log10(1000), np.log10(Hbm), 1000)

plt.figure()
plt.plot(H, satview(H) / Se)
plt.vlines([Hiss, Hsun, Hmeo, Hbm], ymin=0.0, ymax=0.5)
plt.grid()

H = np.logspace(np.log10(10000), np.log10(Hl1), 1000)

plt.figure()
plt.semilogx(H, satview(H) / Se)
plt.vlines([Hiss, Hsun, Hmeo, Hgeo, Hbm, Hma, Hl1], ymin=0.0, ymax=0.5)
plt.grid()
plt.figure()

train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

plt.title('Validation Curve with SVM')
plt.xlabel('$\gamma$ (gamma)')
plt.ylabel('Score')
plt.ylim(0.0, 1.1)
lw = 2

plt.semilogx(param_range,
             train_scores_mean,
             label='Training score',
             color='darkorange',
             lw=lw)

plt.fill_between(param_range,
                 train_scores_mean - train_scores_std,
                 train_scores_mean + train_scores_std,
                 alpha=0.2,
                 color='darkorange',
                 lw=lw)

plt.semilogx(param_range,
             test_scores_mean,
             label='Cross-validation score',
             color='navy',
             lw=lw)
Esempio n. 58
0
])

# In[21]:

plt.plot(fbz_count[:, :], 'k', lw=1)
plt.plot(fbz_n33_count[:, :], 'r', lw=1)

# In[22]:

fig, ax_arr = plt.subplots(1, 2, sharey=True)
ax_arr[1].semilogx(gammas[::], fbz_mean[:, :], 'k', lw=1)
ax_arr[0].semilogx(n33_gammas[::], fbz_n33_mean[:, :], 'k', lw=1)

# In[23]:

plt.semilogx(gammas[::], fbz_mean[:, :], 'b', lw=1)
plt.semilogx(n33_gammas[::], fbz_n33_mean[:, :], 'k', lw=1)

# In[24]:

fig, ax_arr = plt.subplots(1, 2, sharey=True)
ax_arr[1].semilogx(omegas[::], fbz_mean[:, :], 'k', lw=1)
ax_arr[0].semilogx(n33_omegas[::], fbz_n33_mean[:, :], 'k', lw=1)
plt.ylim(-20, 20)

# In[25]:

plt.semilogx(omegas[::], fbz_mean[:, :], 'b', lw=1)
plt.semilogx(n33_omegas[::], fbz_n33_mean[:, :], 'k', lw=1)

# In[26]:
Esempio n. 59
0
                                             cv=10,
                                             scoring="accuracy",
                                             n_jobs=1)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)

plt.title("Validation Curve with SVM")
plt.xlabel("$\gamma$")
plt.ylabel("Score")
plt.ylim(0.0, 1.1)
lw = 2
plt.semilogx(param_range,
             train_scores_mean,
             label="Training score",
             color="darkorange",
             lw=lw)
plt.fill_between(param_range,
                 train_scores_mean - train_scores_std,
                 train_scores_mean + train_scores_std,
                 alpha=0.2,
                 color="darkorange",
                 lw=lw)
plt.semilogx(param_range,
             test_scores_mean,
             label="Cross-validation score",
             color="navy",
             lw=lw)
plt.fill_between(param_range,
                 test_scores_mean - test_scores_std,
Esempio n. 60
0
plt.loglog(flops[GPU2_22], GPUdat[GPU2_22, 6], 'r+')
plt.loglog(flops[GPU4_22], GPUdat[GPU4_22, 6], 'b+')
plt.loglog(flops[GPU6_22], GPUdat[GPU6_22, 6], 'g+')
plt.xlabel('Problem FLOPs')
plt.ylabel('Computational time')

plt.legend(('2 GPUs nonblocking', '4 GPUs nonblocking',\
            '6 GPUs nonblocking', '2 GPUs', '4 GPUs', '6 GPUs'))
plt.savefig('../report/fig/flops_time.eps', format='eps')

msize = GPUdat[:, 2] * GPUdat[:, 3] * GPUdat[:,
                                             4] * 8 * 3 * 1e-6  #/GPUdat[:,1]
#msize=GPUdat[:,2]*GPUdat[:,3]/(GPUdat[:,4]/GPUdat[:,1])
plt.figure()
plt.grid()
plt.semilogx(msize[GPU2_23], fps[GPU2_23], 'rx-')
plt.semilogx(msize[GPU4_23], fps[GPU4_23], 'bx-')
plt.semilogx(msize[GPU6_23], fps[GPU6_23], 'gx-')
plt.xlabel('Memory footprint [MB]')
plt.ylabel('FLOPs/s')
plt.legend(('2 GPUs', '4 GPUs', '6 GPUs'), loc='upper left')
plt.ylim((0, 1e+12))
plt.savefig('../report/fig/m_fps_23.eps', format='eps')

plt.figure()
plt.grid()
plt.semilogx(msize[GPU2_22], fps[GPU2_22], 'rx-')
plt.semilogx(msize[GPU4_22], fps[GPU4_22], 'bx-')
plt.semilogx(msize[GPU6_22], fps[GPU6_22], 'gx-')
plt.xlabel('Memory footprint [MB]')
plt.ylabel('FLOPs/s')