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类subplot()的实例源码
def plot(self, ylim=None):
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from pylab import subplot
number_of_subplots=len(self.scores.keys())
colors = ['blue', 'green', 'orange']
patches = []
for plot_idx, metric in enumerate(self.scores):
for i, set_name in enumerate(self.scores[metric].keys()):
data = self.scores[metric][set_name][0]
time = self.scores[metric][set_name][1]
patches.append(mpatches.Patch(color=colors[i], label='{0} {1}'.format(set_name, metric)))
ax1 = subplot(number_of_subplots,1,plot_idx+1)
ax1.plot(time,data, label='{0}'.format(metric), color=colors[i])
if ylim != None:
plt.ylim(ymin=ylim[0])
plt.ylim(ymax=ylim[1])
plt.xlabel('iter')
plt.ylabel('{0} {1}'.format(set_name, metric))
ax1.legend(handles=patches)
plt.show()
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % epoch))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words, 1, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\' Decoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 12)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % epoch))
pylab.close()
# Input Parameters
def plot(self, overlay_alpha=0.5):
import pylab as pl
rows = int(sqrt(self.layers()))
cols = int(ceil(self.layers()/rows))
for i in range(rows*cols):
pl.subplot(rows, cols, i+1)
pl.axis('off')
if i >= self.layers():
continue
pl.title('{}({})'.format(self.labels[i], i))
pl.imshow(self.image)
pl.imshow(colorize(self.features[i].argmax(0),
colors=np.array([[0, 0, 255],
[0, 255, 255],
[255, 255, 0],
[255, 0, 0]])),
alpha=overlay_alpha)
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()
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def plot_okada(self, axes=None, dim=1, displacement='vertical', kwargs={}):
if (self.dtopo is None):
raise ValueError("Need to call create_dtopography before plot_okada")
if (displacement is 'vertical'):
if axes is None:
from pylab import figure, subplot
figure()
axes = subplot(111)
if (dim is 1):
axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dZ[0,0,:],**kwargs)
elif (dim is 2):
X,Y = numpy.meshgrid(self.dtopo.x,self.dtopo.y)
axes.pcolormesh(X*LAT2METER,Y*LAT2METER,self.dtopo.dZ[0,:,:],**kwargs)
elif (displacement is 'horizontal'):
if axes is None:
from pylab import figure, subplot
figure()
axes = subplot(111)
if (dim is 1):
axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dY[0,0,:],**kwargs)
dtopotools_horiz_okada_and_1d.py 文件源码
项目:finite_volume_seismic_model
作者: cjvogl
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def plot_okada(self, axes=None, dim=1, displacement='vertical', kwargs={}):
if (self.dtopo is None):
raise ValueError("Need to call create_dtopography before plot_okada")
if (displacement is 'vertical'):
if axes is None:
from pylab import figure, subplot
figure()
axes = subplot(111)
if (dim is 1):
axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dZ[0,0,:],**kwargs)
elif (dim is 2):
X,Y = numpy.meshgrid(self.dtopo.x,self.dtopo.y)
axes.pcolormesh(X*LAT2METER,Y*LAT2METER,self.dtopo.dZ[0,:,:],**kwargs)
elif (displacement is 'horizontal'):
if axes is None:
from pylab import figure, subplot
figure()
axes = subplot(111)
if (dim is 1):
axes.plot(self.dtopo.x*LAT2METER,self.dtopo.dY[0,0,:],**kwargs)
def plot_glcf_labelmap(labels, ax=None):
import pylab as pl
if ax is None:
ax = pl.subplot(111)
vimg = glcf_to_rgb(labels)
vimg[labels.mask] = (0, 0, 0)
ax.imshow(vimg, interpolation='nearest')
lgd_patches = []
for glcf_type in sorted(np.unique(labels)):
if glcf_type is ma.masked:
continue
lgd_patches.append(
mpatches.Patch(
color=np.array(CMAP[glcf_type]) / 255.,
label=CLASSES_NAMES[glcf_type]
)
)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
handles=lgd_patches)
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 on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
image_ocr_gpu.py 文件源码
项目:keras-mxnet-benchmarks
作者: sandeep-krishnamurthy
项目源码
文件源码
阅读 37
收藏 0
点赞 0
评论 0
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
def tile_images(image_batch, image_width=28, image_height=28, image_channel=1, dir=None, filename="images"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
pylab.imshow(image_batch[m].reshape((image_width, image_height)), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
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
项目源码
文件源码
阅读 29
收藏 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.py 文件源码
项目:computational_physics_N2014301020117
作者: yukangnineteen
项目源码
文件源码
阅读 22
收藏 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()
def DrawDvs(pl, closes, curve, sign, dvs, pandl, sh, title, leag=None, lad=None ):
pl.figure
pl.subplot(311)
pl.title("id:%s Sharpe ratio: %.2f"%(str(title),sh))
pl.plot(closes)
DrawLine(pl, sign, closes)
pl.subplot(312)
pl.grid()
if dvs != None:
pl.plot(dvs)
if isinstance(curve, np.ndarray):
DrawZZ(pl, curve, 'r')
if leag != None:
pl.plot(leag, 'r')
if lad != None:
pl.plot(lad, 'b')
#pl.plot(stock.GuiYiHua(closes[:i])[60:])
pl.subplot(313)
pl.plot(sign)
pl.plot(pandl)
pl.show()
pl.close()
def DrawDvsAndZZ(pl, dvs, zz, closes=None):
"""dvs?zz??????; dvs : ????closes, """
dvs = np.array(dvs)
pl.figure
if closes == None:
pl.plot(dvs)
pl.plot(zz[:,0], zz[:,1], 'r')
else:
pl.subplot(211)
pl.plot(closes)
pl.grid()
pl.subplot(212)
pl.grid()
pl.plot(dvs)
pl.plot(zz[:,0], zz[:,1], 'r')
pl.show()
pl.close()
def Unittest_Kline():
""""""
kline = Guider("600100", "")
print(kline.getData(0).date, kline.getLastData().date)
#kline.myprint()
obv = kline.OBV()
pl.figure
pl.subplot(2,1,1)
pl.plot(kline.getCloses())
pl.subplot(2,1,2)
ma,m2,m3 = kline.MACD()
pl.plot(ma)
pl.plot(m2,'r')
left = np.arange(0, len(m3))
pl.bar(left,m3)
#pl.plot(obv, 'y')
pl.show()
#Unittest_Kstp()
#
#???????????
#----------------------------------------------------------------------
def setMargins(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None):
"""
Tune the subplot layout via the meanings (and suggested defaults) are::
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots
hspace = 0.2 # the amount of height reserved for white space between subplots
The actual defaults are controlled by the rc file
"""
plt.subplots_adjust(left, bottom, right, top, wspace, hspace)
plt.draw_if_interactive()
def visualize_reconstruction(xp, model, x, visualization_dir, epoch, gpu=False):
x_variable = chainer.Variable(xp.asarray(x))
_x = model.decode(model.encode(x_variable), test=True)
_x.to_cpu()
_x = _x.data
fig = pylab.gcf()
fig.set_size_inches(8.0, 8.0)
pylab.clf()
pylab.gray()
for m in range(50):
i = m / 10
j = m % 10
pylab.subplot(10, 10, 20 * i + j + 1, xticks=[], yticks=[])
pylab.imshow(x[m].reshape((28, 28)), interpolation="none")
pylab.subplot(10, 10, 20 * i + j + 10 + 1, xticks=[], yticks=[])
pylab.imshow(_x[m].reshape((28, 28)), interpolation="none")
# pylab.imshow(np.clip((_x_batch.data[m] + 1.0) / 2.0, 0.0, 1.0).reshape(
# (config.img_channel, config.img_width, config.img_width)), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/reconstruction_{}.png".format(visualization_dir, epoch))
# pylab.show()
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
def plot_eigenspectrum(G, s, nvis, nhid):
with misc.gnumpy_conversion_check('allow'):
dim = G.shape[0]
d, Q = scipy.linalg.eigh(G)
d = d[::-1]
Q = Q[:, ::-1]
pts = np.unique(np.floor(np.logspace(0., np.log10(dim-1), 500)).astype(int)) - 1
cf = [fisher.correlation_fraction(Q[:, i], s, nvis, nhid) for i in pts]
pylab.figure()
pylab.subplot(2, 1, 1)
pylab.loglog(range(1, dim+1), d, 'b-', lw=2.)
pylab.xticks([])
pylab.yticks(fontsize='large')
pylab.subplot(2, 1, 2)
pylab.semilogx(pts+1, cf, 'r-', lw=2.)
pylab.xticks(fontsize='x-large')
pylab.yticks(fontsize='large')
def two_plot_time_freq_mag(self, minlen=10):
part = [pp for pp in self.partial if len(pp.f) > minlen]
pl.figure()
ax1 = pl.subplot(211)
pl.hold(True)
ax2 = pl.subplot(212, sharex=ax1)
pl.hold(True)
for pp in part:
ax1.plot(pp.start_idx + np.arange(len(pp.f)), np.array(pp.f))
ax2.plot(pp.start_idx + np.arange(len(pp.f)),
20*np.log10(np.array(pp.mag)))
ax1.hold(False)
# ax1.xlabel('Time (s)')
ax1.set_ylabel('Frequency (Hz)')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Frequency (Hz)')
# pl.show()
return pl.gca()
def tile_binary_images(x, dir=None, filename="x", row=10, col=10):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(col * 2, row * 2)
pylab.clf()
pylab.gray()
for m in range(row * col):
pylab.subplot(row, col, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def plotstuff():
X__ = np.load("tm_X.npy")
S_pred = np.load("tm_S_pred.npy")
E_pred = np.load("tm_E_pred.npy")
M = np.load("tm_M.npy")
pl.ioff()
pl.suptitle("mode: %s (X: FM input, state pred: FM output)" % ("bluib"))
pl.subplot(511)
pl.title("X[goals]")
pl.plot(X__[10:,0:4], "-x")
pl.subplot(512)
pl.title("X[prediction error]")
pl.plot(X__[10:,4:], "-x")
pl.subplot(513)
pl.title("state pred")
pl.plot(S_pred)
pl.subplot(514)
pl.title("error state - goal")
pl.plot(E_pred)
pl.subplot(515)
pl.title("state")
pl.plot(M)
pl.show()
def tile_binary_images(x, dir=None, filename="x", row=10, col=10):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(col * 2, row * 2)
pylab.clf()
pylab.gray()
for m in range(row * col):
pylab.subplot(row, col, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def tile_binary_images(x, dir=None, filename="x"):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
pylab.imshow(np.clip(x[m], 0, 1), interpolation="none")
pylab.axis("off")
pylab.savefig("{}/{}.png".format(dir, filename))
def plot_multiple_rocs_separate(rocList,title='', labels = None, equal_aspect = True):
""" Plot multiples ROC curves as separate at the same painting area. """
pylab.clf()
pylab.title(title)
for ix, r in enumerate(rocList):
ax = pylab.subplot(4,4,ix+1)
pylab.ylim((0,1))
pylab.xlim((0,1))
ax.set_yticklabels([])
ax.set_xticklabels([])
if equal_aspect:
cax = pylab.gca()
cax.set_aspect('equal')
if not labels:
labels = ['' for x in rocList]
pylab.text(0.2,0.1,labels[ix],fontsize=8)
pylab.plot([x[0] for x in r.derived_points],[y[1] for y in r.derived_points], 'r-',linewidth=2)
pylab.show()
def plot_signals(input_data, filename=None,downsamplefactor=1,n_columns=1):
import pylab as pl
n_rows = input_data.signal.n_channels()
n_rows = int(n_rows/n_columns)
print str(n_rows) + ' ' + str(n_columns)
for row in range(n_rows):
for col in range(n_columns):
print (row)*n_columns+col+1
pl.subplot(n_rows, n_columns, row*n_columns+col+1)
if downsamplefactor==1:
pl.plot(input_data.timebase, input_data.signal.get_channel(row*n_columns+col))
pl.axis([-0.01,0.1,-5, 5])
else:
plotdata=input_data.signal.get_channel(row*n_columns+col)
timedata=input_data.timebase
pl.plot(timedata[0:len(timedata):downsamplefactor], plotdata[0:len(timedata):downsamplefactor])
pl.axis([-0.01,0.1,-5,5])
if filename != None:
pl.savefig(filename)
else:
pl.show()
def visualize_x(reconstructed_x_batch, image_width=28, image_height=28, image_channel=1, dir=None):
if dir is None:
raise Exception()
try:
os.mkdir(dir)
except:
pass
fig = pylab.gcf()
fig.set_size_inches(16.0, 16.0)
pylab.clf()
if image_channel == 1:
pylab.gray()
for m in range(100):
pylab.subplot(10, 10, m + 1)
if image_channel == 1:
pylab.imshow(reconstructed_x_batch[m].reshape((image_width, image_height)), interpolation="none")
elif image_channel == 3:
pylab.imshow(reconstructed_x_batch[m].reshape((image_channel, image_width, image_height)), interpolation="none")
pylab.axis("off")
pylab.savefig("%s/reconstructed_x.png" % dir)