def freq_from_HPS(sig, fs):
"""
Estimate frequency using harmonic product spectrum (HPS)
"""
windowed = sig * blackmanharris(len(sig))
from pylab import subplot, plot, log, copy, show
# harmonic product spectrum:
c = abs(rfft(windowed))
maxharms = 3
#subplot(maxharms, 1, 1)
#plot(log(c))
for x in range(2, maxharms):
a = copy(c[::x]) # Should average or maximum instead of decimating
# max(c[::x],c[1::x],c[2::x],...)
c = c[:len(a)]
i = argmax(abs(c))
true_i = parabolic(abs(c), i)[0]
print 'Pass %d: %f Hz' % (x, fs * true_i / len(windowed))
c *= a
#subplot(maxharms, 1, x)
#plot(log(c))
#show()
python类show()的实例源码
def view_trigger_snippets_bis(trigger_snippets, elec_index, save=None):
fig = pylab.figure()
ax = fig.add_subplot(1, 1, 1)
for n in xrange(0, trigger_snippets.shape[2]):
y = trigger_snippets[:, elec_index, n]
x = numpy.arange(- (y.size - 1) / 2, (y.size - 1) / 2 + 1)
b = 0.5 + 0.5 * numpy.random.rand()
ax.plot(x, y, color=(0.0, 0.0, b), linestyle='solid')
ax.grid(True)
ax.set_xlim([numpy.amin(x), numpy.amax(x)])
ax.set_xlabel("time")
ax.set_ylabel("amplitude")
if save is None:
pylab.show()
else:
pylab.savefig(save)
pylab.close(fig)
return
def view_dataset(X, color='blue', title=None, save=None):
n_components = 2
pca = PCA(n_components)
pca.fit(X)
x = pca.transform(X)
fig = pylab.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x[:, 0], x[:, 1], c=color, s=5, lw=0.1)
ax.grid(True)
if title is None:
ax.set_title("Dataset ({} samples)".format(X.shape[0]))
else:
ax.set_title(title + " ({} samples)".format(X.shape[0]))
ax.set_xlabel("1st component")
ax.set_ylabel("2nd component")
if save is None:
pylab.show()
else:
pylab.savefig(save)
pylab.close(fig)
return
def view_loss_curve(losss, title=None, save=None):
'''Plot loss curve'''
x_min = 1
x_max = len(losss) - 1
fig = pylab.figure()
ax = fig.gca()
ax.semilogy(range(x_min, x_max + 1), losss[1:], color='blue', linestyle='solid')
ax.grid(True, which='both')
if title is None:
ax.set_title("Loss curve")
else:
ax.set_title(title)
ax.set_xlabel("iteration")
ax.set_ylabel("loss")
ax.set_xlim([x_min - 1, x_max + 1])
if save is None:
pylab.show()
else:
pylab.savefig(save)
pylab.close(fig)
return
def display_wav(filename):
input_data = read(filename)
audio_in = input_data[1]
samples = len(audio_in)
fig = pylab.figure();
print samples/44100.0," seconds"
k = 0
plot_data_out = []
for i in xrange(samples):
plot_data_out.append(audio_in[k]/32768.0)
k = k+1
pdata = numpy.array(plot_data_out, dtype=numpy.float)
pylab.plot(pdata)
pylab.grid(True)
pylab.ion()
pylab.show()
def display_pr_curve(precision, recall):
# following examples from sklearn
# TODO: f1 operating point
import pylab as plt
# Plot Precision-Recall curve
plt.clf()
plt.plot(recall, precision, label='Precision-Recall curve')
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.ylim([0.0, 1.05])
plt.xlim([0.0, 1.0])
plt.title('Precision-Recall example: Max f1={0:0.2f}'.format(max_f1))
plt.legend(loc="lower left")
plt.show()
def disp(iimg, label = "", gray=False):
""" Display an image using pylab
"""
try:
import pylab
dimage = iimg.copy()
if iimg.ndim==3:
dimage[...,0] = iimg[...,2]
dimage[...,2] = iimg[...,0]
pylab.imshow(dimage, interpolation='none')
if gray: pylab.gray()
#pylab.gca().format_coord = format_coord
pylab.text(1500, -30, label)
pylab.axis('off')
pylab.show()
except ImportError:
print "Module pylab not available"
def PlotMultipleRuns(Alg, nruns=20, fname=None):
'''Plot "nruns" runs of a given algorithm to show performance
and variability across runs.'''
if fname:
runs = scipy.genfromtxt(fname)
else:
runs = []
for i in range(nruns):
bestSol, fitHistory = tsp.TSP(200, Alg, 3000, 30, seed=None,
coordfile='tmp.txt')
runs.append(fitHistory)
fname = 'MultRuns-' + str(Alg) + '.txt'
runs = scipy.array(runs)
scipy.savetxt(fname, runs)
# plotting
Xs = scipy.linspace(0, runs.shape[1] * 1000, runs.shape[1])
for i in range(runs.shape[0]):
pl.plot(Xs, runs[i, :])
pl.show()
def LongMC3(fname=None):
'''Plot a single long MC3 run to demonstrate high performance
but slow convergence.'''
if fname:
run = scipy.genfromtxt(fname)
else:
bestSol, run = tsp.TSP(200, 'MC3', 20000, 10, seed=None,
coordfile='tmp.txt')
fname = 'ExampleOutput/MC3-Long.txt'
run = scipy.array(run)
scipy.savetxt(fname, run)
# plotting
Xs = range(0, run.shape[0] * 1000, 1000)
pl.plot(Xs, run)
pl.show()
def LongSA(fname=None):
'''Plot a single long SA run to demonstrate performance under slower
cooling schedule.'''
if fname:
run = scipy.genfromtxt(fname)
else:
bestSol, run = tsp.TSP(200, 'SA', 20000, 'placeholder', seed=None,
coordfile='tmp.txt')
fname = 'ExampleOutput/SA-Long.txt'
run = scipy.array(run)
scipy.savetxt(fname, run)
# plotting
Xs = range(0, run.shape[0] * 1000, 1000)
pl.plot(Xs, run)
pl.show()
def PlotProps(pars):
import numpy as np
import pylab as pl
import vanGenuchten as vg
psi = np.linspace(-10, 2, 200)
pl.figure
pl.subplot(3, 1, 1)
pl.plot(psi, vg.thetaFun(psi, pars))
pl.ylabel(r'$\theta(\psi) [-]$')
pl.subplot(3, 1, 2)
pl.plot(psi, vg.CFun(psi, pars))
pl.ylabel(r'$C(\psi) [1/m]$')
pl.subplot(3, 1, 3)
pl.plot(psi, vg.KFun(psi, pars))
pl.xlabel(r'$\psi [m]$')
pl.ylabel(r'$K(\psi) [m/d]$')
# pl.show()
def buildArgsParser():
DESCRIPTION = "Generate samples from a Conv Deep NADE model."
p = argparse.ArgumentParser(description=DESCRIPTION, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
p.add_argument('experiment', type=str, help='folder where to find a trained ConvDeepNADE model')
p.add_argument('count', type=int, help='number of samples to generate.')
p.add_argument('--out', type=str, help='name of the samples file')
# General parameters (optional)
p.add_argument('--seed', type=int, help='seed used to generate random numbers. Default: 1234', default=1234)
p.add_argument('--view', action='store_true', help="show samples.")
p.add_argument('-v', '--verbose', action='store_true', help='produce verbose output')
p.add_argument('-f', '--force', action='store_true', help='permit overwriting')
return p
def plotPopScore(population, fitness=False):
""" Plot the population score distribution
Example:
>>> Interaction.plotPopScore(population)
:param population: population object (:class:`GPopulation.GPopulation`)
:param fitness: if True, the fitness score will be used, otherwise, the raw.
:rtype: None
"""
score_list = getPopScores(population, fitness)
pylab.plot(score_list, 'o')
pylab.title("Plot of population score distribution")
pylab.xlabel('Individual')
pylab.ylabel('Score')
pylab.grid(True)
pylab.show()
# -----------------------------------------------------------------
def plotHistPopScore(population, fitness=False):
""" Population score distribution histogram
Example:
>>> Interaction.plotHistPopScore(population)
:param population: population object (:class:`GPopulation.GPopulation`)
:param fitness: if True, the fitness score will be used, otherwise, the raw.
:rtype: None
"""
score_list = getPopScores(population, fitness)
n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1)
pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--')
pylab.xlabel('Score')
pylab.ylabel('Frequency')
pylab.grid(True)
pylab.title("Plot of population score distribution")
pylab.show()
# -----------------------------------------------------------------
def plotPopScore(population, fitness=False):
""" Plot the population score distribution
Example:
>>> Interaction.plotPopScore(population)
:param population: population object (:class:`GPopulation.GPopulation`)
:param fitness: if True, the fitness score will be used, otherwise, the raw.
:rtype: None
"""
score_list = getPopScores(population, fitness)
pylab.plot(score_list, 'o')
pylab.title("Plot of population score distribution")
pylab.xlabel('Individual')
pylab.ylabel('Score')
pylab.grid(True)
pylab.show()
# -----------------------------------------------------------------
def plotHistPopScore(population, fitness=False):
""" Population score distribution histogram
Example:
>>> Interaction.plotHistPopScore(population)
:param population: population object (:class:`GPopulation.GPopulation`)
:param fitness: if True, the fitness score will be used, otherwise, the raw.
:rtype: None
"""
score_list = getPopScores(population, fitness)
n, bins, patches = pylab.hist(score_list, 50, facecolor='green', alpha=0.75, normed=1)
pylab.plot(bins, pylab.normpdf(bins, numpy.mean(score_list), numpy.std(score_list)), 'r--')
pylab.xlabel('Score')
pylab.ylabel('Frequency')
pylab.grid(True)
pylab.title("Plot of population score distribution")
pylab.show()
# -----------------------------------------------------------------
def fastLapModel(xList, labels, names, multiple=0, full_set=0):
X = numpy.array(xList)
y = numpy.array(labels)
featureNames = []
featureNames = numpy.array(names)
# take fixed holdout set 30% of data rows
xTrain, xTest, yTrain, yTest = train_test_split(
X, y, test_size=0.30, random_state=531)
# for final model (no CV)
if full_set:
xTrain = X
yTrain = y
check_set(xTrain, xTest, yTrain, yTest)
print "Fitting the model to the data set..."
# train random forest at a range of ensemble sizes in order to see how the
# mse changes
mseOos = []
m = 10 ** multiple
nTreeList = range(500 * m, 1000 * m, 100 * m)
# iTrees = 10000
for iTrees in nTreeList:
depth = None
maxFeat = int(np.sqrt(np.shape(xTrain)[1])) + 1 # try tweaking
RFmd = ensemble.RandomForestRegressor(n_estimators=iTrees, max_depth=depth, max_features=maxFeat,
oob_score=False, random_state=531, n_jobs=-1)
# RFmd.n_features = 5
RFmd.fit(xTrain, yTrain)
# Accumulate mse on test set
prediction = RFmd.predict(xTest)
mseOos.append(mean_squared_error(yTest, prediction))
# plot training and test errors vs number of trees in ensemble
plot.plot(nTreeList, mseOos)
plot.xlabel('Number of Trees in Ensemble')
plot.ylabel('Mean Squared Error')
#plot.ylim([0.0, 1.1*max(mseOob)])
plot.show()
print("MSE")
print(mseOos[-1])
return xTrain, xTest, yTrain, yTest, RFmd
def plot_importance(names, model, savefig=True):
featureNames = numpy.array(names)
featureImportance = model.feature_importances_
featureImportance = featureImportance / featureImportance.max()
sorted_idx = numpy.argsort(featureImportance)
barPos = numpy.arange(sorted_idx.shape[0]) + .5
plot.barh(barPos, featureImportance[sorted_idx], align='center')
plot.yticks(barPos, featureNames[sorted_idx])
plot.xlabel('Variable Importance')
plot.subplots_adjust(left=0.2, right=0.9, top=0.9, bottom=0.1)
if savefig:
dt_ = datetime.datetime.now().strftime('%d%b%y_%H%M')
plt.savefig("../graphs/featureImportance_" + dt_ + ".png")
plot.show()
# Plot prediction save the graph with a timestamp
def plot_pred(y_predicted, y, savefig=True):
# y_predicted.reset_index(drop=1, inplace=1)
index = np.argsort(y)
y = y[index]
# y.shape
yhat = y_predicted[index]
yy = pd.DataFrame([y, yhat])
if yy.shape[1] > yy.shape[0]:
yy = yy.T
yy.reset_index(drop=0, inplace=1)
plt.scatter(yy.index, yy[1], s=.4)
plt.plot(yy.index, yy[0], ls='-', color='red', linewidth=.5)
if savefig:
dt_ = datetime.datetime.now().strftime('%d%b%y_%H%M')
plt.savefig("../graphs/" + dt_ + ".png")
plt.show()
# Check the data before regression (no Na, size, etc)
def backgroundPeakValue(img, bins=500):
f = FitHistogramPeaks(img, bins=bins, bins2=300)
bgp = getBackgroundPeak(f.fitParams)
ind = int(bgp[1])
if ind < 0:
ind = 0
# y = f.yvals[ind:]
# i = np.argmax(np.diff(y) > 0)
# bgmaxpos = ind # + i
# print(f.xvals[bgmaxpos], bgmaxpos)
# import pylab as plt
# plt.plot(f.xvals, f.yvals)
# plt.show()
return f.xvals[ind]
def interpolate2dDiffusion(arr1, arr2, steps=10, diffusivity=0.2):
psf = np.zeros((5, 5))
numbaGaussian2d(psf, 1, 1)
# plt.imshow(psf)
# plt.show()
last = arr1
out = []
for s in range(steps):
next = np.zeros_like(arr1)
diff = diffusivity * (last - arr2)
# plt.imshow(diff)
# plt.show()
weightedConvolution(last, next, diff, psf)
out.append(next)
last = next
return out
def _visualize(grid, device, img, gen):
# for debugging:
# show intermediate steps of iteration
# in [vignettingDiscreteSteps]
import pylab as plt
fig, ax = plt.subplots(1, 3)
ax[0].set_title('device')
ax[0].imshow(device, interpolation='none')
ax[1].set_title('average')
ax[1].imshow(grid, interpolation='none')
ax[2].set_title('grid')
im = ax[2].imshow(img, interpolation='none')
for x, y in gen:
ax[2].plot(x, y)
fig.colorbar(im)
plt.show()
def generate_inverted_sinewave_dataset(N = 1000, f = 1.0, p = 0.0, a1 = 1.0, a2 = 0.3):
"""models_actinf.generate_inverted_sinewave_dataset
Generate the inverted sine dataset used in Bishop's (Bishop96)
mixture density paper
Returns:
- matrices X, Y
"""
X = np.linspace(0,1,N)
# FIXME: include phase p
Y = a1 * X + a2 * np.sin(f * (2 * 3.1415926) * X) + np.random.uniform(-0.1, 0.1, N)
X,Y = Y[:,np.newaxis],X[:,np.newaxis]
# pl.subplot(211)
# pl.plot(Y, X, "ko", alpha=0.25)
# pl.subplot(212)
# pl.plot(X, Y, "ko", alpha=0.25)
# pl.show()
return X,Y
def plot_success_functions():
data_dir = "/Users/Chen/data/ngas_logs"
lru_yd = np.load("{0}/{1}".format(data_dir, 'yd_lru_ingest_correct.npy'))
lfu_yd = np.load("{0}/{1}".format(data_dir, 'yd_lfu_ingest_correct.npy'))
liat_yd = np.load("{0}/{1}".format(data_dir, 'yd_liat_ingest_correct.npy'))
lrud_yd = np.load("{0}/{1}".format(data_dir, 'yd_lrud_ingest_correct.npy'))
lnr_yd = np.load("{0}/{1}".format(data_dir, 'yd_lnr_ingest_correct.npy'))
law_yd = np.load("{0}/{1}".format(data_dir, 'yd_law_ingest_correct.npy'))
#liat_yd_imiat = np.load("{0}/{1}".format(data_dir, 'yd_liat_ingest_max_iat.npy'))
ax1 = plot_success_function(lru_yd, label='Least Recently Used', show=False)
#plot_success_function(lru_yd, label='LRU - default on disk', line='--', show=False, init_on_tape=False, ax=ax1)
plot_success_function(lfu_yd, label='Least Frequently Used', line='--', lcolor='skyblue', show=False, ax=ax1)
#plot_success_function(lfu_yd, label='LFU - default on disk', lcolor='r', line='--', init_on_tape=False, show=False, ax=ax1)
plot_success_function(liat_yd, label='Longest Inter-Arrival Time', line=':', lcolor='darkorchid', show=False, ax=ax1)
plot_success_function(law_yd, label='Largest Age Weight (DMF)', line='-', lcolor='k', show=False, ax=ax1)
#plot_success_function(liat_yd, label='LIAT - default on disk', lcolor='g', line='--', init_on_tape=False, ax=ax1)
#plot_success_function(liat_yd_imiat, label='LIAT - ingest max iat', lcolor='g', line='-.', ax=ax1)
plot_success_function(lnr_yd, label='Longest Next Access (Optimal)', line='--', lcolor='deeppink', show=False, ax=ax1, lw=3.0)
plot_ws_success_function(lru_yd, ax=ax1, lw=3.0)
plot_success_function(lrud_yd, label='Longest Reuse Distance', line='-.', lcolor='lime', show=True, ax=ax1, lw=4.0)
def ex2():
x = np.linspace(-10, 10)
# "--" = dashed line
plt.plot(x, np.sin(x), "--", label="sinus")
plt.plot(x, np.cos(x), label="cosinus")
# Show the legend using the labels above
plt.legend()
# The trick here is we have to make another plot on top of the two others.
pi2 = np.pi/2
# Find B such that (-B * pi/2) >= -10 > ((-B-1) * pi/2), i.e. the
# first multiple of pi/2 higher than -10.
b = pi2*int(-10.0/pi2)
# x2 is all multiples of pi/2 between -10 and 10.
x2 = np.arange(b, 10, pi2)
# "b." = blue dots
plt.plot(x2, np.sin(x2), "b.")
plt.show()
def plot(self):
"""
Plot startup data.
"""
import pylab
print("Plotting result...", end="")
avg_data = self.average_data()
avg_data = self.__sort_data(avg_data, False)
if len(self.raw_data) > 1:
err = self.stdev_data()
sorted_err = [err[k] for k in list(zip(*avg_data))[0]]
else:
sorted_err = None
pylab.barh(range(len(avg_data)), list(zip(*avg_data))[1],
xerr=sorted_err, align='center', alpha=0.4)
pylab.yticks(range(len(avg_data)), list(zip(*avg_data))[0])
pylab.xlabel("Average startup time (ms)")
pylab.ylabel("Plugins")
pylab.show()
print(" done.")
def view_(_pred,_lable):
fname = ['Captcha/lv3/%i.jpg' %i for i in range(20)]
img = []
for fn in fname:
img.append(Image.open(open(fn)))
#img.append(misc.imread(fn).astype(np.float))
for i in range(len(img)):
pylab.subplot(4,5,i+1); pylab.axis('off')
pylab.imshow(img[i])
#pylab.imshow( np.dot(np.array(img[i])[...,:3],[0.299,0.587,0.114]) , cmap=plt.get_cmap("gray"))
#pylab.text(40,60,_pred[i],color = 'b')
if ( _pred[i] == _lable[i] ):
pylab.text(40,65,_pred[i],color = 'b',size = 15)
else:
pylab.text(40,65,_pred[i],color = 'r',size = 15)
pylab.text(40,92,_lable[i],color = 'g',size = 15)
pylab.show()
7 code plus.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def show(self):
# pl.semilogy(self.theta, self.omega)
# , label = '$L =%.1f m, $'%self.l + '$dt = %.2f s, $'%self.dt + '$\\theta_0 = %.2f radians, $'%self.theta[0] + '$q = %i, $'%self.q + '$F_D = %.2f, $'%self.F_D + '$\\Omega_D = %.1f$'%self.Omega_D)
pl.plot(self.theta_phase ,self.omega_phase, '.', label = '$t \\approx 2\\pi n / \\Omega_D$')
pl.xlabel('$\\theta$ (radians)')
pl.ylabel('$\\omega$ (radians/s)')
pl.legend()
# pl.text(-1.4, 0.3, '$\\omega$ versus $\\theta$ $F_D = 1.2$', fontsize = 'x-large')
pl.title('Chaotic Regime')
# pl.show()
# pl.semilogy(self.time_array, self.delta)
# pl.legend(loc = 'upper center', fontsize = 'small')
# pl.xlabel('$time (s)$')
# pl.ylabel('$\\Delta\\theta (radians)$')
# pl.xlim(0, self.T)
# pl.ylim(float(input('ylim-: ')),float(input('ylim+: ')))
# pl.ylim(1E-11, 0.01)
# pl.text(4, -0.15, 'nonlinear pendulum - Euler-Cromer method')
# pl.text(10, 1E-3, '$\\Delta\\theta versus time F_D = 0.5$')
# pl.title('Simple Harmonic Motion')
pl.title('Chaotic Regime')
7 code plus.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def show_log(self):
# pl.subplot(121)
pl.semilogy(self.time_array, self.delta, 'c')
pl.xlabel('$time (s)$')
pl.ylabel('$\\Delta\\theta$ (radians)')
pl.xlim(0, self.T)
# pl.ylim(1E-11, 0.01)
pl.text(42, 1E-7, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
pl.title('Chaotic Regime')
pl.show()
# def show_log_sub122(self):
# pl.subplot(122)
# pl.semilogy(self.time_array, self.delta, 'g')
# pl.xlabel('$time (s)$')
# pl.ylabel('$\\Delta\\theta$ (radians)')
# pl.xlim(0, self.T)
# pl.ylim(1E-6, 100)
# pl.text(20, 1E-5, '$\\Delta\\theta$ versus time $F_D = 1.2$', fontsize = 'x-large')
# pl.title('Chaotic Regime')
# pl.show()
7 code plus.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def multi_show(self):
for i in range(2):
a = simple_harmonic_motion(time_step = float(input('time step: ')), time_duration = float(input('time duration: ')), initial_theta = float(input('initial theta: ')), length = float(input('length: ')), strength_of_damping = float(input('stength of damping: ')), amplitude = float(input('amplitude of driving force: ')), anguluar_frequency = float(input('angular frequency of driving force: ')))
a.calculate()
a.show()
pl.show()
#class please_input():
# string_input = input('xlocation ,ylocation: ')
# numbers = [float(n) for n in string_input.split()]
# x = numbers[0]
# y = numbers[1]
#b = simple_harmonic_motion()
#b.calculate_delta()
#b.show()