Python matplotlib.pylab 模块,show() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pylab.show()。
def plot_trajectory(name):
STEPS = 600
DELTA = 1 if name != 'linear' else 0.1
trajectory = create_trajectory(name, STEPS)
x = [trajectory.get_position_at(i * DELTA).x for i in range(STEPS)]
y = [trajectory.get_position_at(i * DELTA).y for i in range(STEPS)]
trajectory_fig, trajectory_plot = plt.subplots(1, 1)
trajectory_plot.plot(x, y, label='trajectory', lw=3)
trajectory_plot.set_title(name.title() + ' Trajectory', fontsize=20)
trajectory_plot.set_xlabel(r'$x{\rm[m]}$', fontsize=18)
trajectory_plot.set_ylabel(r'$y{\rm[m]}$', fontsize=18)
trajectory_plot.legend(loc=0)
trajectory_plot.grid()
plt.show()
def compare_images(path = '.'):
S_limit = 10.
file_list = glob.glob(os.path.join(path, 'Abu*'))
file_list_master = glob.glob(os.path.join(path, 'MasterAbu*'))
file_list.sort()
file_list_master.sort()
S=[]
print("Identifying images with rmq > "+'%3.1f'%S_limit)
ierr_count = 0
for i in range(len(file_list)):
this_S,fimg1,fimg2 = compare_entropy(file_list[i],file_list_master[i])
if this_S > S_limit:
warnings.warn(file_list[i]+" and "+file_list_master[i]+" differ by "+'%6.3f'%this_S)
ierr_count += 1
S.append(this_S)
if ierr_count > 0:
print("Error: at least one image differs by more than S_limit")
sys.exit(1)
#print ("S: ",S)
#plb.plot(S,'o')
#plb.xlabel("image number")
#plb.ylabel("modified log KL-divergence to previous image")
#plb.show()
def postaud(x, fmax, fbtype=None):
if fbtype is None:
fbtype = 'bark'
nbands = x.shape[0]
nframes = x.shape[1]
nfpts = nbands
if fbtype == 'bark':
bancfhz = bark2freq(np.linspace(0, freq2bark(fmax), nfpts))
fsq = bancfhz * bancfhz
ftmp = fsq + 1.6e5
eql = ((fsq/ftmp)**2) * ((fsq + 1.44e6)/(fsq + 9.61e6))
'''
plt.figure()
plt.plot(eql)
plt.show()
'''
eql = eql.reshape(np.size(eql), 1)
z = np.repeat(eql, nframes, axis=1) * x
z = z ** (1./3.)
y = np.vstack((z[1, :], z[1:nbands-1, :], z[nbands-2, :]))
return y
def plot_volcano(logFC,p_val,sample_name,saveName,logFC_thresh):
fig=pl.figure()
## To plot and save
pl.scatter(logFC[(p_val>0.05)|(abs(logFC)<logFC_thresh)],-np.log10(p_val[(p_val>0.05)|(abs(logFC)<logFC_thresh)]),color='blue',alpha=0.5);
pl.scatter(logFC[(p_val<0.05)&(abs(logFC)>logFC_thresh)],-np.log10(p_val[(p_val<0.05)&(abs(logFC)>logFC_thresh)]),color='red');
pl.hlines(-np.log10(0.05),min(logFC),max(logFC))
pl.vlines(-logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.vlines(logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.xlim(-3,3)
pl.xlabel('Log Fold Change')
pl.ylabel('-log10(p-value)')
pl.savefig(saveName)
pl.close(fig)
# def plot_histograms(df_peaks,pntr_list):
#
# for pntr in pntr_list:
# colName =pntr[2]+'_Intragenic_position'
# pl.hist(df_peaks[colName])
# pl.xlabel(colName)
# pl.ylabel()
# pl.show()
def plot(l, x1, x2, y, e):
# Plot
time_range = numpy.arange(0, l)
pl.figure(1)
pl.subplot(221)
pl.plot(time_range, x1)
pl.title("Input signal")
pl.subplot(222)
pl.plot(time_range, x2, c="r")
pl.plot(time_range, y, c="b")
pl.title("Reference signal")
pl.subplot(223)
pl.plot(time_range, e, c="r")
pl.title("Noise")
pl.xlabel("time")
pl.show()
def make_fft_graph(fft, corre):
fft_np = numpy.array(fft).swapaxes(0, 1).swapaxes(1, 2)
channel_N, freq_N, sample_N = fft_np.shape
if (channel_N > 6): # We don't have space for more than 6 channels
return
fig, axes = plt.subplots(2, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.05)
for ax, mat, i in zip(axes.flat, fft_np, range(1, channel_N + 1)):
fft_abs = numpy.abs(mat)
fft_less_row = fft_abs[0::20]
n = freq_N / 20
fft_sqr = numpy.repeat(fft_less_row, int(n / sample_N)).reshape([n, n])
ax.matshow(fft_sqr, cmap='viridis')
plt.xlabel('time')
plt.ylabel('freq')
ax.set_title('Channel {0}'.format(i))
plt.show()
print("Plotted.")
def run_regression_1D_aep_two_layers():
np.random.seed(42)
print "create dataset ..."
Xtrain, ytrain, Xtest, ytest = create_dataset()
alpha = 1 # other alpha is not valid here
M = 20
model = aep.SDGPR(Xtrain, ytrain, M, hidden_sizes=[2])
model.optimise(method='L-BFGS-B', alpha=1, maxiter=5000, disp=False)
my, vy = model.predict_y(Xtest)
my = np.reshape(my, ytest.shape)
vy = np.reshape(vy, ytest.shape)
rmse = np.sqrt(np.mean((my - ytest)**2))
ll = np.mean(-0.5 * np.log(2 * np.pi * vy) - 0.5 * (ytest - my)**2 / vy)
nlml, _ = model.objective_function(model.get_hypers(), Xtrain.shape[0], alpha)
print 'alpha=%.3f, train ml=%3f, test rmse=%.3f, ll=%.3f' % (alpha, nlml, rmse, ll)
# plot(model, Xtrain, ytrain)
# plt.show()
# should produce something like this
# alpha=1.000, train ml=-51.385404, test rmse=0.168, ll=0.311
def run_regression_1D_aep_two_layers_stoc():
np.random.seed(42)
print "create dataset ..."
Xtrain, ytrain, Xtest, ytest = create_dataset()
alpha = 1 # other alpha is not valid here
M = 20
model = aep.SDGPR(Xtrain, ytrain, M, hidden_sizes=[2])
model.optimise(method='adam', alpha=1, maxiter=5000, disp=False)
my, vy = model.predict_y(Xtest)
my = np.reshape(my, ytest.shape)
vy = np.reshape(vy, ytest.shape)
rmse = np.sqrt(np.mean((my - ytest)**2))
ll = np.mean(-0.5 * np.log(2 * np.pi * vy) - 0.5 * (ytest - my)**2 / vy)
nlml, _ = model.objective_function(model.get_hypers(), Xtrain.shape[0], alpha)
print 'alpha=%.3f, train ml=%3f, test rmse=%.3f, ll=%.3f' % (alpha, nlml, rmse, ll)
# plot(model, Xtrain, ytrain)
# plt.show()
# should produce something like this
# alpha=1.000, train ml=-69.444086, test rmse=0.170, ll=0.318
def plot(param, show = 1):
"""Returns the plot of spectrum as a pyplot object or plot it on the screen
Keyword arguments:
param -- Output spectrum file
show -- Optional, plot the spectrum on the screen. Enabled by default.
"""
s = sed.SED()
s.grmonty(param)
plt = pylab.plot(s.lognu, s.ll)
if show == 1:
pylab.show()
else:
return plt
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
from matplotlib import pylab
cm = np.asarray(cm, dtype=np.float32)
for i, row in enumerate(cm):
cm[i] = cm[i] / np.sum(cm[i])
#import matplotlib.pyplot as plt
#plt.ion()
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(label_list)))
ax.set_xticklabels(label_list, rotation='vertical')
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks(range(len(label_list)))
ax.set_yticklabels(label_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig('test.jpg')
pylab.show()
def plotRes(pre, real, test_x,l):
s = set(pre)
col = ['r','b','g','y','m']
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(0, len(s)):
index1 = pre == i
index2 = real == i
x1 = test_x[index1, :]
x2 = test_x[index2, :]
ax.scatter(x1[:,0],x1[:,1],color=col[i],marker='v',linewidths=0.5)
ax.scatter(x2[:,0],x2[:,1],color=col[i],marker='.',linewidths=12)
plt.title('learning rating='+str(l))
plt.legend(('c1:predict','c1:true',\
'c2:predict','c2:true',
'c3:predict','c3:true',
'c4:predict','c4:true',
'c5:predict','c5:true'), shadow = True, loc = (0.01, 0.4))
plt.show()
def __init__(self, data, **kwargs):
# Settings
self.show_ticks = kwargs.get("show_ticks", False)
self.show_values = kwargs.get("show_values", False)
self.show = kwargs.get("show", False)
self.labels = kwargs.get("labels", None)
# Setup plot
self.rows, self.cols = data.shape
self.fig = plt.figure()
self.plt_ax = self.fig.add_subplot(111)
self.cov_ax = self.plt_ax.matshow(np.array(data))
# Covariance matrix labels
self.label_values = self._add_data_labels(data)
self._add_axis_labels(data)
# Color bar
self.color_bar = self.fig.colorbar(self.cov_ax)
# Show plot
if self.show:
plt.show(block=False)
def test_plot_error_ellipse(self):
# Generate random data
x = np.random.normal(0, 1, 300)
s = np.array([2.0, 2.0])
y1 = np.random.normal(s[0] * x)
y2 = np.random.normal(s[1] * x)
data = np.array([y1, y2])
# Calculate covariance and plot error ellipse
cov = np.cov(data)
plot_error_ellipse([0.0, 0.0], cov)
debug = False
if debug:
plt.scatter(data[0, :], data[1, :])
plt.xlim([-8, 8])
plt.ylim([-8, 8])
plt.show()
plt.clf()
def test_augment_state(self):
self.msckf.augment_state()
N = self.msckf.N()
self.assertTrue(self.msckf.P_cam is not None)
self.assertTrue(self.msckf.P_imu_cam is not None)
self.assertEqual(self.msckf.P_cam.shape, (N * 6, N * 6))
self.assertEqual(self.msckf.P_imu_cam.shape, (15, N * 6))
self.assertEqual(self.msckf.N(), 2)
self.assertTrue(np.array_equal(self.msckf.cam_states[0].q_CG,
self.msckf.ext_q_CI))
self.assertEqual(self.msckf.counter_frame_id, 2)
# Plot matrix
# debug = True
debug = False
if debug:
ax = plt.subplot(111)
ax.matshow(self.msckf.P())
plt.show()
def test_F(self):
w_hat = np.array([1.0, 2.0, 3.0])
q_hat = np.array([0.0, 0.0, 0.0, 1.0])
a_hat = np.array([1.0, 2.0, 3.0])
w_G = np.array([0.1, 0.1, 0.1])
F = self.imu_state.F(w_hat, q_hat, a_hat, w_G)
# -- First row --
self.assertTrue(np_equal(F[0:3, 0:3], -skew(w_hat)))
self.assertTrue(np_equal(F[0:3, 3:6], -np.ones((3, 3))))
# -- Third Row --
self.assertTrue(np_equal(F[6:9, 0:3], dot(-C(q_hat).T, skew(a_hat))))
self.assertTrue(np_equal(F[6:9, 6:9], -2.0 * skew(w_G)))
self.assertTrue(np_equal(F[6:9, 9:12], -C(q_hat).T))
self.assertTrue(np_equal(F[6:9, 12:15], -skewsq(w_G)))
# -- Fifth Row --
self.assertTrue(np_equal(F[12:15, 6:9], np.ones((3, 3))))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(F)
plt.show()
def test_G(self):
q_hat = np.array([0.0, 0.0, 0.0, 1.0]).reshape((4, 1))
G = self.imu_state.G(q_hat)
# -- First row --
self.assertTrue(np_equal(G[0:3, 0:3], -np.ones((3, 3))))
# -- Second row --
self.assertTrue(np_equal(G[3:6, 3:6], np.ones((3, 3))))
# -- Third row --
self.assertTrue(np_equal(G[6:9, 6:9], -C(q_hat).T))
# -- Fourth row --
self.assertTrue(np_equal(G[9:12, 9:12], np.ones((3, 3))))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(G)
plt.show()
def test_J(self):
# Setup
cam_q_CI = np.array([0.0, 0.0, 0.0, 1.0])
cam_p_IC = np.array([1.0, 1.0, 1.0])
q_hat_IG = np.array([0.0, 0.0, 0.0, 1.0])
N = 1
J = self.imu_state.J(cam_q_CI, cam_p_IC, q_hat_IG, N)
# Assert
C_CI = C(cam_q_CI)
C_IG = C(q_hat_IG)
# -- First row --
self.assertTrue(np_equal(J[0:3, 0:3], C_CI))
# -- Second row --
self.assertTrue(np_equal(J[3:6, 0:3], skew(dot(C_IG.T, cam_p_IC))))
# -- Third row --
self.assertTrue(np_equal(J[3:6, 12:15], I(3)))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(J)
plt.show()
def test_project(self):
# Load points
points_file = join(test.TEST_DATA_PATH, "house/house.p3d")
points = np.loadtxt(points_file).T
# Setup camera
K = np.eye(3)
R = np.eye(3)
t = np.array([0, 0, 0])
camera = PinholeCameraModel(320, 240, K)
x = camera.project(points, R, t)
# Assert
self.assertEqual(x.shape, (3, points.shape[1]))
self.assertTrue(np.all(x[2, :] == 1.0))
# Plot projection
debug = False
# debug = True
if debug:
plt.figure()
plt.plot(x[0], x[1], 'k. ')
plt.show()
def plot(self, track, track_cam_states, estimates):
plt.figure()
# Feature
feature = T_global_camera * track.ground_truth
plt.plot(feature[0], feature[1],
marker="o", color="red", label="feature")
# Camera states
for cam_state in track_cam_states:
pos = T_global_camera * cam_state.p_G
plt.plot(pos[0], pos[1],
marker="o", color="blue", label="camera")
# Estimates
for i in range(len(estimates)):
cam_state = track_cam_states[i]
cam_pos = T_global_camera * cam_state.p_G
estimate = (T_global_camera * estimates[i]) + cam_pos
plt.plot(estimate[0], estimate[1],
marker="o", color="green")
plt.legend(loc=0)
plt.show()
def summary(self):
"""
This function is used to summary the result.
If you want calculate some other indicator, you can add them here.
:return:
"""
if self._analysis is not None:
self._analysis(self.asset_dict)
# for x in self.asset_dict:
# self.get_benchmark()
# asset_return = (self.asset_dict[x] - self._base_fund) / self._base_fund
# asset_return = asset_return.add_prefix(str(x) + "_")
# print asset_return
# result = pd.merge(asset_return, self._benchmark_data,
# left_index=True, right_index=True, how="inner")
# max_return = self.get_max_return(x, begin=self._begin_date, end=self._end_date)
# print max_return
# # print result
# # if self._analysis is not None:
# # self._analysis(result)
# # result.plot()
# # plt.show()
def x_corr(a,b,center_time_s=1000.0,window_len_s=50.0,plot=True):
center_index = int(center_time_s/a.dt)
window_index = int(window_len_s/(a.dt))
print "center_index is", center_index
print "window_index is", window_index
t1 = a.trace_x[(center_index - window_index) : (center_index + window_index)]
t2 = b.trace_x[(center_index - window_index) : (center_index + window_index)]
print t1
time_window = np.linspace((-window_len_s/2.0), (window_len_s/2), len(t1))
#print time_window
#plt.plot(time_window, t1)
#plt.plot(time_window, t2)
#plt.show()
x_corr_time = correlate(t1, t2)
delay = (np.argmax(x_corr_time) - (len(x_corr_time)/2) ) * a.dt
#print "the delay is ", delay
return delay
def plotLine(self, x_vals, y_vals, x_label, y_label, title, filename=None):
plt.clf()
plt.xlabel(x_label)
plt.xlim(((min(x_vals) - 0.5), (max(x_vals) + 0.5)))
plt.ylabel(y_label)
plt.ylim(((min(y_vals) - 0.5), (max(y_vals) + 0.5)))
plt.title(title)
plt.plot(x_vals, y_vals, c='k', lw=2)
#plt.plot(x_vals, len(x_vals) * y_vals[0], c='r', lw=2)
if filename == None:
plt.show()
else:
plt.savefig(self.outputPath + filename)
def plot_confusion_matrix(cm, genre_list, name, title):
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(genre_list)))
ax.set_xticklabels(genre_list)
ax.xaxis.set_ticks_position("bottom")
ax.set_yticks(range(len(genre_list)))
ax.set_yticklabels(genre_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.show()
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig(
os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight")
def plotKChart(self, misClassDict, saveFigPath):
kList = []
misRateList = []
for k, misClassNum in misClassDict.iteritems():
kList.append(k)
misRateList.append(1.0 - 1.0/k*misClassNum)
fig = plt.figure(saveFigPath)
plt.plot(kList, misRateList, 'r--')
plt.title(saveFigPath)
plt.xlabel('k Num.')
plt.ylabel('Misclassified Rate')
plt.legend(saveFigPath)
plt.grid(True)
plt.savefig(saveFigPath)
plt.show()
################################### PART3 TEST ########################################
# ??
def backtest(config_file, day_trade):
cfg = config.Config(config_file)
cfg.day_trade = day_trade
dfs = load_data(config_file)
trender = strategies[cfg.strategy](**cfg.strategy_parameters)
res = []
for df in dfs:
res.append(trender.backtest(data_frame=df))
final_panel = pd.Panel({os.path.basename(p['path']): df for p, df in
zip(cfg.data_path, res)})
profit_series = final_panel.sum(axis=0)['total_profit'].cumsum()
final_panel.to_excel(cfg.output_file)
if cfg.show:
profit_series.plot()
plt.xlabel('Time')
plt.ylabel('Profit')
plt.legend('Profit')
plt.show()
def get_captcha_image(filename):
screenshot = driver.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
# screenshot.show()
captcha_el = driver.find_element_by_class_name("gt_box")
location = captcha_el.location
size = captcha_el.size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
box = (left, top, right, bottom)
print(box)
if box[0] == 0:
raise(Exception('======='))
captcha_image = screenshot.crop(box)
captcha_image.save(filename) # "%s.png" % uuid.uuid4().hex
print(u'????')
def show_samples(y, ndim, nb=10, cmap=''):
if ndim == 4:
for i in range(nb**2):
plt.subplot(nb, nb, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
else:
x = y[0]
y = y[1]
plt.figure(0)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(x[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.figure(1)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.show()
def fit_data():
data=np.loadtxt('data.dat')
print(data)
params = dict()
params["c"] = {"min" : -np.inf,"max" : np.inf}
result = qudi_fitting.make_lorentzian_fit(axis=data[:,0], data=data[:,3], add_parameters=params)
print(result.fit_report())
plt.plot(data[:,0],-data[:,3]+2,"b-o",label="data mean")
# plt.plot(data[:,0],data[:,1],label="data")
# plt.plot(data[:,0],data[:,2],label="data")
plt.plot(data[:,0],-result.best_fit+2,"r-",linewidth=2.,label="fit")
# plt.plot(data[:,0],result.init_fit,label="init")
plt.xlabel("time (ns)")
plt.ylabel("polarization transfer (arb. u.)")
plt.legend(loc=1)
# plt.savefig("pol20_24repetition_pol.pdf")
# plt.savefig("pol20_24repetition_pol.png")
plt.show()
savedata=[[data[ii,0],-data[ii,3]+2,-result.best_fit[ii]+2] for ii in range(len(data[:,0]))]
np.savetxt("pol_data_fit.csv",savedata)
# print(result.params)
print(result.params)
def plot_roc(y_test, y_pred, label=''):
"""Compute ROC curve and ROC area"""
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic' + label)
plt.legend(loc="lower right")
plt.show()
def plot_confusion_matrix(cm, plot_title, filename, genres=None):
if not genres:
genres = GENRES
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=100.0)
axes = pylab.axes()
axes.set_xticks(range(len(genres)))
axes.set_xticklabels(genres, rotation=45)
axes.set_yticks(range(len(genres)))
axes.set_yticklabels(genres)
axes.xaxis.set_ticks_position("bottom")
pylab.title(plot_title, fontsize=14)
pylab.colorbar()
pylab.xlabel('Predicted class', fontsize=12)
pylab.ylabel('Correct class', fontsize=12)
pylab.grid(False)
#pylab.show()
pylab.savefig(os.path.join(PLOTS_DIR, "cm_%s.eps" % filename), bbox_inches="tight")
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
from matplotlib import pylab
cm = np.asarray(cm, dtype=np.float32)
for i, row in enumerate(cm):
cm[i] = cm[i] / np.sum(cm[i])
#import matplotlib.pyplot as plt
#plt.ion()
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(label_list)))
ax.set_xticklabels(label_list, rotation='vertical')
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks(range(len(label_list)))
ax.set_yticklabels(label_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig('test.jpg')
pylab.show()
def gen_aperture(imgsize,ypos,xpos,radius,pixval=1,showaperture=False,verbose=True):
"""
Generating an aperture image
--- INPUT ---
imgsize The dimensions of the array to return. Expects [y-size,x-size].
The aperture will be positioned in the center of a (+/-x-size/2., +/-y-size/2) sized array
ypos Pixel position in the y direction
xpos Pixel position in the x direction
radius Radius of aperture in pixels
showaperture Display image of generated aperture
verbose Toggle verbosity
--- EXAMPLE OF USE ---
import tdose_utilities as tu
apertureimg = tu.gen_aperture([20,40],10,5,10,showaperture=True)
apertureimg = tu.gen_aperture([2000,4000],900,1700,150,showaperture=True)
"""
if verbose: print ' - Generating aperture in image (2D array)'
y , x = np.ogrid[-ypos:imgsize[0]-ypos, -xpos:imgsize[1]-xpos]
mask = x*x + y*y <= radius**2.
aperture = np.zeros(imgsize)
if verbose: print ' - Assigning pixel value '+str(pixval)+' to aperture'
aperture[mask] = pixval
if showaperture:
if verbose: print ' - Displaying resulting image of aperture'
plt.imshow(aperture,interpolation='none')
plt.title('Generated aperture')
plt.show()
return aperture
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
def residual_multigauss(param, dataimage, nonfinite = 0.0, ravelresidual=True, showimages=False, verbose=False):
"""
Calculating the residual bestween the multigaussian model with the paramters 'param' and the data.
--- INPUT ---
param Parameters of multi-gaussian model to generate. See modelimage_multigauss() header for details
dataimage Data image to take residual
nonfinite Value to replace non-finite entries in residual with
ravelresidual To np.ravel() the residual image set this to True. Needed by scipy.optimize.leastsq()
optimizer function
showimages To show model and residiual images set to True
verbose Toggle verbosity
--- EXAMPLE OF USE ---
import tdose_model_FoV as tmf
param = [18,31,1*0.3,2.1*0.3,1.2*0.3,30*0.3, 110,90,200*0.5,20.1*0.5,15.2*0.5,0*0.5]
dataimg = pyfits.open('/Users/kschmidt/work/TDOSE/mock_cube_sourcecat161213_tdose_mock_cube.fits')[0].data[0,:,:]
residual = tmf.residual_multigauss(param, dataimg, showimages=True)
"""
if verbose: ' - Estimating residual (= model - data) between model and data image'
imgsize = dataimage.shape
xgrid, ygrid = tu.gen_gridcomponents(imgsize)
modelimg = tmf.modelimage_multigauss((xgrid, ygrid),param,imgsize,showmodelimg=showimages, verbose=verbose)
residualimg = modelimg - dataimage
if showimages:
plt.imshow(residualimg,interpolation='none', vmin=1e-5, vmax=np.max(residualimg), norm=mpl.colors.LogNorm())
plt.title('Resdiaul (= model - data) image')
plt.show()
if nonfinite is not None:
residualimg[~np.isfinite(residualimg)] = 0.0
if ravelresidual:
residualimg = np.ravel(residualimg)
return residualimg
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
def plot(ts):
if not plt:
print ""
fig, ax = plt.subplots()
lined = dict()
ax.set_title('Click on legend line to toggle line on/off')
lines = [ax.plot(ts[col], label=col) for col in ts.columns]
leg = ax.legend(loc='best')
for legline, origline in zip(leg.get_lines(), lines):
legline.set_picker(5) # 5 pts tolerance
lined[legline] = origline[0]
def onpick(event):
# on the pick event, find the orig line corresponding to the
# legend proxy line, and toggle the visibility
legline = event.artist
origline = lined[legline]
vis = not origline.get_visible()
origline.set_visible(vis)
# Change the alpha on the line in the legend so we can see what lines
# have been toggled
if vis:
legline.set_alpha(1.0)
else:
legline.set_alpha(0.2)
fig.canvas.draw()
fig.canvas.mpl_connect('pick_event', onpick)
plt.show(False)
def plot(embeddings, labels):
assert embeddings.shape[0] >= len(labels), 'More labels than embeddings'
pylab.figure(figsize=(15, 15)) # in inches
for i, label in enumerate(labels):
x, y = embeddings[i, :]
pylab.scatter(x, y)
pylab.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points',
ha='right', va='bottom')
pylab.show()
def rasta_plp_extractor(x, sr, plp_order=0, do_rasta=True):
spec = log_power_spectrum_extractor(x, int(sr*0.02), int(sr*0.01), 'hamming', False)
bark_filters = int(np.ceil(freq2bark(sr//2)))
wts = get_fft_bark_mat(sr, int(sr*0.02), bark_filters)
'''
plt.figure()
plt.subplot(211)
plt.imshow(wts)
plt.subplot(212)
plt.hold(True)
for i in range(18):
plt.plot(wts[i, :])
plt.show()
'''
bark_spec = np.matmul(wts, spec)
if do_rasta:
bark_spec = np.where(bark_spec == 0.0, np.finfo(float).eps, bark_spec)
log_bark_spec = np.log(bark_spec)
rasta_log_bark_spec = rasta_filt(log_bark_spec)
bark_spec = np.exp(rasta_log_bark_spec)
post_spec = postaud(bark_spec, sr/2.)
if plp_order > 0:
lpcas = do_lpc(post_spec, plp_order)
# lpcas = do_lpc(spec, plp_order) # just for test
else:
lpcas = post_spec
return lpcas
def plot(l, samp, w1, w2, cor):
time_range = numpy.arange(0, l) * (1.0 / samp)
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, w1)
pl.subplot(212)
pl.plot(time_range, w2, c="r")
pl.xlabel("time")
pl.figure(2)
pl.plot(time_range, cor)
pl.show()
def main():
sampling, maxvalue, wave_data = record.record()
# Pick out two channels for our study.
w1, w2 = wave_data[1:3]
nframes = w1.shape[0]
# Cut one channel in the tail, while the other in the head,
# to guarantee same length and first delays second.
cut_time_len = 0.2 # second
cut_len = int(cut_time_len * sampling)
wp1 = w1[:-cut_len]
wp2 = w2[cut_len:]
# Get their reduced (amplitude) version, and
# calculate correlation.
a = numpy.array(wp1, dtype=numpy.double) / maxvalue
b = numpy.array(wp2, dtype=numpy.double) / maxvalue
delay_time = delay.fst_delay_snd(a, b, sampling)
# Plot the channels, also the correlation.
time_range = numpy.arange(0, nframes - cut_len)*(1.0/sampling)
# Still shows the original signal
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, wp1)
pl.subplot(212)
pl.plot(time_range, wp2, c="r")
pl.xlabel("time")
pl.show()
# Print delay
print("Chan 1 delay chan 2 by {0}".format(delay_time))
def main():
sampling, maxvalue, wave_data = record.record()
# Pick out two channels for our study.
w1, w2 = wave_data[0:2]
nframes = w1.shape[0]
# Pad one channel in the head, while the other in the tail,
# to guarantee same length.
pad_time_len = 0.01 # second
pad_len = int(pad_time_len * sampling)
pad_arr = numpy.zeros(pad_len)
wp1 = numpy.concatenate((pad_arr, w1))
wp2 = numpy.concatenate((w2, pad_arr))
# Get their reduced (amplitude) version, and
# calculate correlation.
a = numpy.array(wp1, dtype=numpy.double) / maxvalue
b = numpy.array(wp2, dtype=numpy.double) / maxvalue
delay_time = delay.fst_delay_snd(a, b, sampling)
# Plot the channels, also the correlation.
time_range = numpy.arange(0, nframes + pad_len)*(1.0/sampling)
# Still shows the original signal
pl.figure(1)
pl.subplot(211)
pl.plot(time_range, wp1)
pl.subplot(212)
pl.plot(time_range, wp2, c="r")
pl.xlabel("time")
pl.show()
# Print delay
print("Chan 1 delay chan 2 by {0}".format(delay_time))
def plot_channel(audio, sampling):
channels, nframes = audio.shape[0], audio.shape[1]
time_range = numpy.arange(0, nframes) * (1.0 / sampling)
for i in range(1, channels + 1):
pl.figure(i)
pl.plot(time_range, audio[i - 1])
pl.xlabel("time{0}".format(i))
pl.show()
def generate_box_plot(dataset, methods, position_rmses, orientation_rmses):
num_methods = len(methods)
x_ticks = np.linspace(0., 1., num_methods)
width = 0.3 / num_methods
spacing = 0.3 / num_methods
fig, ax1 = plt.subplots()
ax1.set_ylabel('RMSE position [m]', color='b')
ax1.tick_params('y', colors='b')
fig.suptitle(
"Hand-Eye Calibration Method Error {}".format(dataset), fontsize='24')
bp_position = ax1.boxplot(position_rmses, 0, '',
positions=x_ticks - spacing, widths=width)
plt.setp(bp_position['boxes'], color='blue', linewidth=line_width)
plt.setp(bp_position['whiskers'], color='blue', linewidth=line_width)
plt.setp(bp_position['fliers'], color='blue',
marker='+', linewidth=line_width)
plt.setp(bp_position['caps'], color='blue', linewidth=line_width)
plt.setp(bp_position['medians'], color='blue', linewidth=line_width)
ax2 = ax1.twinx()
ax2.set_ylabel('RMSE Orientation [$^\circ$]', color='g')
ax2.tick_params('y', colors='g')
bp_orientation = ax2.boxplot(
orientation_rmses, 0, '', positions=x_ticks + spacing, widths=width)
plt.setp(bp_orientation['boxes'], color='green', linewidth=line_width)
plt.setp(bp_orientation['whiskers'], color='green', linewidth=line_width)
plt.setp(bp_orientation['fliers'], color='green',
marker='+')
plt.setp(bp_orientation['caps'], color='green', linewidth=line_width)
plt.setp(bp_orientation['medians'], color='green', linewidth=line_width)
plt.xticks(x_ticks, methods)
plt.xlim(x_ticks[0] - 2.5 * spacing, x_ticks[-1] + 2.5 * spacing)
plt.show()
def generate_time_plot(methods, datasets, runtimes_per_method, colors):
num_methods = len(methods)
num_datasets = len(datasets)
x_ticks = np.linspace(0., 1., num_methods)
width = 0.6 / num_methods / num_datasets
spacing = 0.4 / num_methods / num_datasets
fig, ax1 = plt.subplots()
ax1.set_ylabel('Time [s]', color='b')
ax1.tick_params('y', colors='b')
ax1.set_yscale('log')
fig.suptitle("Hand-Eye Calibration Method Timings", fontsize='24')
handles = []
for i, dataset in enumerate(datasets):
runtimes = [runtimes_per_method[dataset][method] for method in methods]
bp = ax1.boxplot(
runtimes, 0, '',
positions=(x_ticks + (i - num_datasets / 2. + 0.5) *
spacing * 2),
widths=width)
plt.setp(bp['boxes'], color=colors[i], linewidth=line_width)
plt.setp(bp['whiskers'], color=colors[i], linewidth=line_width)
plt.setp(bp['fliers'], color=colors[i],
marker='+', linewidth=line_width)
plt.setp(bp['medians'], color=colors[i],
marker='+', linewidth=line_width)
plt.setp(bp['caps'], color=colors[i], linewidth=line_width)
handles.append(mpatches.Patch(color=colors[i], label=dataset))
plt.legend(handles=handles, loc=2)
plt.xticks(x_ticks, methods)
plt.xlim(x_ticks[0] - 2.5 * spacing * num_datasets,
x_ticks[-1] + 2.5 * spacing * num_datasets)
plt.show()
def plot_angular_velocities(title,
angular_velocities,
angular_velocities_filtered,
block=True):
fig = plt.figure()
title_position = 1.05
fig.suptitle(title, fontsize='24')
a1 = plt.subplot(1, 2, 1)
a1.set_title(
"Angular Velocities Before Filtering \nvx [red], vy [green], vz [blue]",
y=title_position)
plt.plot(angular_velocities[:, 0], c='r')
plt.plot(angular_velocities[:, 1], c='g')
plt.plot(angular_velocities[:, 2], c='b')
a2 = plt.subplot(1, 2, 2)
a2.set_title(
"Angular Velocities After Filtering \nvx [red], vy [green], vz [blue]", y=title_position)
plt.plot(angular_velocities_filtered[:, 0], c='r')
plt.plot(angular_velocities_filtered[:, 1], c='g')
plt.plot(angular_velocities_filtered[:, 2], c='b')
plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05)
if plt.get_backend() == 'TkAgg':
mng = plt.get_current_fig_manager()
max_size = mng.window.maxsize()
max_size = (max_size[0], max_size[1] * 0.45)
mng.resize(*max_size)
plt.show(block=block)
def plot_distortion(training_data_instances):
# dimension of a training data instance
d = training_data_instances.shape[1]
# first m instances considered
m = 20
fig, axes = plt.subplots(1, 1)
fig.suptitle("Distortion of random projection", fontsize = "x-large")
for k in [50, 100, 500]:
## generate random projection matrix
random_projection_matrix = generate_random_projection_matrix(k, d)
## random projection
m_instances = training_data_instances[0:m]
projected_m_instances = np.dot(m_instances, np.transpose(random_projection_matrix))
# print random_projected_matrix[0], random_projected_matrix.shape
## evaluate distortion - line chart
m_instances_distortions = []
for i in range(m):
for j in range(i + 1, m):
m_instances_distortions.append(euclidean(projected_m_instances[i], projected_m_instances[j]) / euclidean(m_instances[i], m_instances[j]))
m_instances_distortions = np.array(m_instances_distortions)
mean, std = np.mean(m_instances_distortions), np.std(m_instances_distortions)
# line chart
axes.plot(m_instances_distortions, label = "k=" + str(k))
axes.plot([0, m_instances_distortions.size], [mean, mean], label = "k=" + str(k) + ", mean = " + str(round(mean, 4)))
print "k = ", k, "distortion =", mean, "+-", std
axes.set_xlabel("pairs of instances", fontsize = "large")
axes.set_ylabel("distortion", fontsize = "large")
axes.legend(loc = "center right", fontsize = "medium")
plt.show()
def getGitRepFolder():
# import subprocess
# return subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0].rstrip()
return '/home/ly/workspace/Vanilla'
def plot(self):
from matplotlib.pylab import show, plot, stem
pass
def show(self, r=3, color=255, other=None, title=None):
M = self.drawLandmarks(r, color, other, title)
if title is None:
title = self.name
# my debug
#cv2.imshow(title, M)
return M
def main():
initialize_plotting()
experiment_convergence_kernelerror()
experiment_convergence_testerror()
plt.show()
def hackathon_GBC_model(clf, train, features):
clf.fit(train[features], train["Class"])
probab_of_predict = clf.predict_proba(train[features])[:,1]
predict_train = clf.predict(train[features])
cv_score = cross_val_score(clf, train[features], train["Class"], cv=5, scoring="roc_auc")
print("----------------------Model performance-----------------------")
print("Accuracy score: ", accuracy_score(train["Class"].values, predict_train))
print("AUC: ", roc_auc_score(train["Class"],probab_of_predict) )
print("CV score: Mean - {}, Max - {}, Min - {}, Std - {}".format(np.mean(cv_score), np.max(cv_score),
np.min(cv_score), np.std(cv_score)))
Relative_Feature_importance = pd.Series(clf.feature_importances_, features).sort_values(ascending=False)
Relative_Feature_importance.plot(kind='bar', title='Order of Feature Importance')
plt.ylabel('Feature Importance')
plt.show()
def run_regression_1D_collapsed():
np.random.seed(42)
print "create dataset ..."
Xtrain, ytrain, Xtest, ytest = create_dataset()
alphas = [0.001, 0.1, 0.2, 0.3, 0.5, 0.7, 0.8, 1]
for alpha in alphas:
M = 20
model = vfe.SGPR_collapsed(Xtrain, ytrain, M)
model.optimise(method='L-BFGS-B', alpha=alpha, maxiter=1000, disp=False)
my, vy = model.predict_y(Xtest, alpha)
my = np.reshape(my, ytest.shape)
vy = np.reshape(vy, ytest.shape)
rmse = np.sqrt(np.mean((my - ytest)**2))
ll = np.mean(-0.5 * np.log(2 * np.pi * vy) - 0.5 * (ytest - my)**2 / vy)
nlml, _ = model.objective_function(model.get_hypers(), alpha)
print 'alpha=%.3f, train ml=%3f, test rmse=%.3f, ll=%.3f' % (alpha, nlml, rmse, ll)
# plot(model, Xtrain, ytrain)
# plt.show()
# should produce something like this
# alpha=0.001, train ml=-64.573021, test rmse=0.169, ll=0.348
# alpha=0.100, train ml=-64.616618, test rmse=0.169, ll=0.348
# alpha=0.200, train ml=-64.626655, test rmse=0.169, ll=0.348
# alpha=0.300, train ml=-64.644053, test rmse=0.169, ll=0.348
# alpha=0.500, train ml=-64.756588, test rmse=0.169, ll=0.348
# alpha=0.700, train ml=-68.755871, test rmse=0.169, ll=0.350
# alpha=0.800, train ml=-72.153441, test rmse=0.167, ll=0.349
# alpha=1.000, train ml=-71.305002, test rmse=0.169, ll=0.303