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
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
python类title()的实例源码
def _do_title_string(self,title_items,cycle):
'''
Create title string
Private method that creates a title string for a cycle plot
out of a list of title_items that are cycle attributes and can
be obtained with self.get
Parameters
----------
title_items : list
A list of cycle attributes.
cycle : scalar
The cycle for which the title string should be created.
Returns
-------
title_string: string
Title string that can be used to decorate plot.
'''
title_string=[]
form_str='%4.1F'
for item in title_items:
num=self.get(item,fname=cycle)
if num > 999:
num=log10(num)
prefix='log '
else:
prefix=''
title_string.append(prefix+item+'='+form_str%num)
tt=''
for thing in title_string:
tt = tt+thing+", "
return tt.rstrip(', ')
def test_abu_evolution(self):
from nugridpy import ppn, utils
import matplotlib
matplotlib.use('agg')
import matplotlib.pylab as mpy
import os
# Perform tests within temporary directory
with TemporaryDirectory() as tdir:
# wget the data for a ppn run from the CADC VOspace
os.system("wget -q --content-disposition --directory '" + tdir + "' "\
+ "'http://www.canfar.phys.uvic.ca/vospace/synctrans?TARGET="\
+ "vos%3A%2F%2Fcadc.nrc.ca%21vospace%2Fnugrid%2Fdata%2Fprojects%2Fppn%2Fexamples%2F"\
+ "ppn_Hburn_simple%2Fx-time.dat&DIRECTION=pullFromVoSpace&PROTOCOL"\
+ "=ivo%3A%2F%2Fivoa.net%2Fvospace%2Fcore%23httpget'")
#nugrid_dir= os.path.dirname(os.path.dirname(ppn.__file__))
#NuPPN_dir= nugrid_dir + "/NuPPN"
#test_data_dir= NuPPN_dir + "/examples/ppn_Hburn_simple/RUN_MASTER"
symbs=utils.symbol_list('lines2')
x=ppn.xtime(tdir)
specs=['PROT','HE 4','C 12','N 14','O 16']
i=0
for spec in specs:
x.plot('time',spec,logy=True,logx=True,shape=utils.linestyle(i)[0],show=False,title='')
i += 1
mpy.ylim(-5,0.2)
mpy.legend(loc=0)
mpy.xlabel('$\log t / \mathrm{min}$')
mpy.ylabel('$\log X \mathrm{[mass fraction]}$')
abu_evol_file = 'abu_evolution.png'
mpy.savefig(abu_evol_file)
self.assertTrue(os.path.exists(abu_evol_file))
def plot1D_mat(a, b, M, title=''):
""" Plot matrix M with the source and target 1D distribution
Creates a subplot with the source distribution a on the left and
target distribution b on the tot. The matrix M is shown in between.
Parameters
----------
a : np.array, shape (na,)
Source distribution
b : np.array, shape (nb,)
Target distribution
M : np.array, shape (na,nb)
Matrix to plot
"""
na, nb = M.shape
gs = gridspec.GridSpec(3, 3)
xa = np.arange(na)
xb = np.arange(nb)
ax1 = pl.subplot(gs[0, 1:])
pl.plot(xb, b, 'r', label='Target distribution')
pl.yticks(())
pl.title(title)
ax2 = pl.subplot(gs[1:, 0])
pl.plot(a, xa, 'b', label='Source distribution')
pl.gca().invert_xaxis()
pl.gca().invert_yaxis()
pl.xticks(())
pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2)
pl.imshow(M, interpolation='nearest')
pl.axis('off')
pl.xlim((0, nb))
pl.tight_layout()
pl.subplots_adjust(wspace=0., hspace=0.2)
def plot_latent(model, y, plot_title=''):
# make prediction on some test inputs
N_test = 300
C = model.get_hypers()['C_emission'][0, 0]
x_test = np.linspace(-10, 8, N_test) / C
x_test = np.reshape(x_test, [N_test, 1])
if isinstance(model, aep.SGPSSM) or isinstance(model, vfe.SGPSSM):
zu = model.dyn_layer.zu
else:
zu = model.sgp_layer.zu
mu, vu = model.predict_f(zu)
# mu, Su = model.dyn_layer.mu, model.dyn_layer.Su
mf, vf = model.predict_f(x_test)
my, vy = model.predict_y(x_test)
# plot function
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.plot(x_test[:,0], kink_true(x_test[:,0]), '-', color='k')
ax.plot(C*x_test[:,0], my[:,0], '-', color='r', label='y')
ax.fill_between(
C*x_test[:,0],
my[:,0] + 2*np.sqrt(vy[:, 0]),
my[:,0] - 2*np.sqrt(vy[:, 0]),
alpha=0.2, edgecolor='r', facecolor='r')
ax.plot(
y[0:model.N-1],
y[1:model.N],
'r+', alpha=0.5)
mx, vx = model.get_posterior_x()
ax.set_xlabel(r'$x_{t-1}$')
ax.set_ylabel(r'$x_{t}$')
plt.title(plot_title)
plt.savefig('/tmp/lincos_'+plot_title+'.png')
# generate a dataset from the lincos function above
def plot_latent(model, y, plot_title=''):
# make prediction on some test inputs
N_test = 200
C = model.get_hypers()['C_emission'][0, 0]
x_test = np.linspace(-4, 6, N_test) / C
x_test = np.reshape(x_test, [N_test, 1])
zu = model.dyn_layer.zu
mu, vu = model.predict_f(zu)
# mu, Su = model.dyn_layer.mu, model.dyn_layer.Su
mf, vf = model.predict_f(x_test)
my, vy = model.predict_y(x_test)
# plot function
fig = plt.figure()
ax = fig.add_subplot(111)
# ax.plot(x_test[:,0], kink_true(x_test[:,0]), '-', color='k')
ax.plot(C*x_test[:,0], my[:,0], '-', color='r', label='y')
ax.fill_between(
C*x_test[:,0],
my[:,0] + 2*np.sqrt(vy[:, 0]),
my[:,0] - 2*np.sqrt(vy[:, 0]),
alpha=0.2, edgecolor='r', facecolor='r')
# ax.plot(zu, mu, 'ob')
# ax.errorbar(zu, mu, yerr=3*np.sqrt(vu), fmt='ob')
# ax.plot(x_test[:,0], mf[:,0], '-', color='b')
# ax.fill_between(
# x_test[:,0],
# mf[:,0] + 2*np.sqrt(vf[:,0]),
# mf[:,0] - 2*np.sqrt(vf[:,0]),
# alpha=0.2, edgecolor='b', facecolor='b')
ax.plot(
y[0:model.N-1],
y[1:model.N],
'r+', alpha=0.5)
mx, vx = model.get_posterior_x()
ax.set_xlabel(r'$x_{t-1}$')
ax.set_ylabel(r'$x_{t}$')
ax.set_xlim([-4, 6])
# ax.set_ylim([-7, 7])
plt.title(plot_title)
# plt.savefig('/tmp/kink_'+plot_title+'.pdf')
plt.savefig('/tmp/kink_'+plot_title+'.png')
def plot_prediction_MC(model, y_train, y_test, plot_title=''):
T = y_test.shape[0]
x_samples, my, vy = model.predict_forward(T, prop_mode=PROP_MC)
T_train = y_train.shape[0]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.arange(T_train), y_train[:, 0], 'k+-')
ttest = np.arange(T_train, T_train+T)
ttest = np.reshape(ttest, [T, 1])
loglik, ranks = compute_log_lik(np.exp(2*model.sn), y_test, my[:, :, 0].T)
red = 0.1
green = 0. * red
blue = 1. - red
color = np.array([red, green, blue]).T
for k in np.argsort(ranks):
ax.plot(ttest, my[:, k, 0], '-', color=color*ranks[k], alpha=0.5)
# ax.plot(np.tile(ttest, [1, my.shape[1]]), my[:, :, 0], '-x', color='r', alpha=0.3)
# ax.plot(np.tile(ttest, [1, my.shape[1]]), x_samples[:, :, 0], 'x', color='m', alpha=0.3)
ax.plot(ttest, y_test, 'ro')
ax.set_xlim([T_train-5, T_train + T])
plt.title(plot_title)
plt.savefig('/tmp/kink_pred_MC_'+plot_title+'.pdf')
# plt.savefig('/tmp/kink_pred_MC_'+plot_title+'.png')
# generate a dataset from the kink function above
def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"):
"""
Generate a lexical dispersion plot.
:param text: The source text
:type text: list(str) or enum(str)
:param words: The target words
:type words: list of str
:param ignore_case: flag to set if case should be ignored when searching text
:type ignore_case: bool
"""
try:
from matplotlib import pylab
except ImportError:
raise ValueError('The plot function requires matplotlib to be installed.'
'See http://matplotlib.org/')
text = list(text)
words.reverse()
if ignore_case:
words_to_comp = list(map(str.lower, words))
text_to_comp = list(map(str.lower, text))
else:
words_to_comp = words
text_to_comp = text
points = [(x,y) for x in range(len(text_to_comp))
for y in range(len(words_to_comp))
if text_to_comp[x] == words_to_comp[y]]
if points:
x, y = list(zip(*points))
else:
x = y = ()
pylab.plot(x, y, "b|", scalex=.1)
pylab.yticks(list(range(len(words))), words, color="b")
pylab.ylim(-1, len(words))
pylab.title(title)
pylab.xlabel("Word Offset")
pylab.show()
def plot_word_freq_dist(text):
fd = text.vocab()
samples = [item for item, _ in fd.most_common(50)]
values = [fd[sample] for sample in samples]
values = [sum(values[:i+1]) * 100.0/fd.N() for i in range(len(values))]
pylab.title(text.name)
pylab.xlabel("Samples")
pylab.ylabel("Cumulative Percentage")
pylab.plot(values)
pylab.xticks(range(len(samples)), [str(s) for s in samples], rotation=90)
pylab.show()
def tabulate(self, *args, **kwargs):
"""
Tabulate the given samples from the frequency distribution (cumulative),
displaying the most frequent sample first. If an integer
parameter is supplied, stop after this many samples have been
plotted.
:param samples: The samples to plot (default is all samples)
:type samples: list
:param cumulative: A flag to specify whether the freqs are cumulative (default = False)
:type title: bool
"""
if len(args) == 0:
args = [len(self)]
samples = [item for item, _ in self.most_common(*args)]
cumulative = _get_kwarg(kwargs, 'cumulative', False)
if cumulative:
freqs = list(self._cumulative_frequencies(samples))
else:
freqs = [self[sample] for sample in samples]
# percents = [f * 100 for f in freqs] only in ProbDist?
width = max(len("%s" % s) for s in samples)
width = max(width, max(len("%d" % f) for f in freqs))
for i in range(len(samples)):
print("%*s" % (width, samples[i]), end=' ')
print()
for i in range(len(samples)):
print("%*d" % (width, freqs[i]), end=' ')
print()
def plot_velocity(self, timestamps, vel_true, vel_est):
N = vel_est.shape[1]
t = timestamps[:N]
vel_true = vel_true[:, :N]
vel_est = vel_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Velocity")
# X axis
plt.subplot(311)
plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Y axis
plt.subplot(312)
plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Z axis
plt.subplot(313)
plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
def plot_attitude(self, timestamps, att_true, att_est):
# Setup
N = att_est.shape[1]
t = timestamps[:N]
att_true = att_true[:, :N]
att_est = att_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Attitude")
# X axis
plt.subplot(311)
plt.plot(t, att_true[0, :], color="red", label="Ground_truth")
plt.plot(t, att_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Y axis
plt.subplot(312)
plt.plot(t, att_true[1, :], color="red", label="Ground_truth")
plt.plot(t, att_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Z axis
plt.subplot(313)
plt.plot(t, att_true[2, :], color="red", label="Ground_truth")
plt.plot(t, att_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
def plot_velocity(self, timestamps, vel_true, vel_est):
N = vel_est.shape[1]
t = timestamps[:N]
vel_true = vel_true[:, :N]
vel_est = vel_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Velocity")
# X axis
plt.subplot(311)
plt.plot(t, vel_true[0, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Y axis
plt.subplot(312)
plt.plot(t, vel_true[1, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
# Z axis
plt.subplot(313)
plt.plot(t, vel_true[2, :], color="red", label="Ground_truth")
plt.plot(t, vel_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.xlabel("Date Time")
plt.ylabel("ms^-1")
plt.legend(loc=0)
def plot_attitude(self, timestamps, att_true, att_est):
# Setup
N = att_est.shape[1]
t = timestamps[:N]
att_true = att_true[:, :N]
att_est = att_est[:, :N]
# Figure
plt.figure()
plt.suptitle("Attitude")
# X axis
plt.subplot(311)
plt.plot(t, att_true[0, :], color="red", label="Ground_truth")
plt.plot(t, att_est[0, :], color="blue", label="Estimate")
plt.title("x-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Y axis
plt.subplot(312)
plt.plot(t, att_true[1, :], color="red", label="Ground_truth")
plt.plot(t, att_est[1, :], color="blue", label="Estimate")
plt.title("y-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
# Z axis
plt.subplot(313)
plt.plot(t, att_true[2, :], color="red", label="Ground_truth")
plt.plot(t, att_est[2, :], color="blue", label="Estimate")
plt.title("z-axis")
plt.legend(loc=0)
plt.xlabel("Date Time")
plt.ylabel("rad s^-1")
def plot_storage(self, storage):
plt.figure()
plt.plot(range(len(storage)), storage)
plt.title("Num of tracks over time")
plt.xlabel("Frame No.")
plt.ylabel("Num of Tracks")
def imageSegy(Data):
"""
imageSegy(Data)
Image segy Data
"""
import matplotlib.pylab as plt
plt.imshow(Data)
plt.title('pymat test')
plt.grid(True)
plt.show()
#%%
def wiggle(Data,SH,skipt=1,maxval=8,lwidth=.1):
"""
wiggle(Data,SH)
"""
import matplotlib.pylab as plt
t = range(SH['ns'])
# t = range(SH['ns'])*SH['dt']/1000000;
for i in range(0,SH['ntraces'],skipt):
# trace=zeros(SH['ns']+2)
# dtrace=Data[:,i]
# trace[1:SH['ns']]=Data[:,i]
# trace[SH['ns']+1]=0
trace=Data[:,i]
trace[0]=0
trace[SH['ns']-1]=0
plt.plot(i+trace/maxval,t,color='black',linewidth=lwidth)
for a in range(len(trace)):
if (trace[a]<0):
trace[a]=0;
# pylab.fill(i+Data[:,i]/maxval,t,color='k',facecolor='g')
plt.fill(i+Data[:,i]/maxval,t,'k',linewidth=0)
plt.title(SH['filename'])
plt.grid(True)
plt.show()
#%%
demo_mds.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def plot_demo_1():
X = np.c_[np.ones(5), 2 * np.ones(5), 10 * np.ones(5)].T
y = np.array([0, 1, 2])
fig = pylab.figure(figsize=(10, 4))
ax = fig.add_subplot(121, projection='3d')
ax.set_axis_bgcolor('white')
mds = manifold.MDS(n_components=3)
Xtrans = mds.fit_transform(X)
for cl, color, marker in zip(np.unique(y), colors, markers):
ax.scatter(
Xtrans[y == cl][:, 0], Xtrans[y == cl][:, 1], Xtrans[y == cl][:, 2], c=color, marker=marker, edgecolor='black')
pylab.title("MDS on example data set in 3 dimensions")
ax.view_init(10, -15)
mds = manifold.MDS(n_components=2)
Xtrans = mds.fit_transform(X)
ax = fig.add_subplot(122)
for cl, color, marker in zip(np.unique(y), colors, markers):
ax.scatter(
Xtrans[y == cl][:, 0], Xtrans[y == cl][:, 1], c=color, marker=marker, edgecolor='black')
pylab.title("MDS on example data set in 2 dimensions")
filename = "mds_demo_1.png"
pylab.savefig(os.path.join(CHART_DIR, filename), bbox_inches="tight")
demo_mi.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def _plot_mi_func(x, y):
mi = mutual_info(x, y)
title = "NI($X_1$, $X_2$) = %.3f" % mi
pylab.scatter(x, y)
pylab.title(title)
pylab.xlabel("$X_1$")
pylab.ylabel("$X_2$")
demo_corr.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def _plot_correlation_func(x, y):
r, p = pearsonr(x, y)
title = "Cor($X_1$, $X_2$) = %.3f" % r
pylab.scatter(x, y)
pylab.title(title)
pylab.xlabel("$X_1$")
pylab.ylabel("$X_2$")
f1 = scipy.poly1d(scipy.polyfit(x, y, 1))
pylab.plot(x, f1(x), "r--", linewidth=2)
# pylab.xticks([w*7*24 for w in [0,1,2,3,4]], ['week %i'%(w+1) for w in
# [0,1,2,3,4]])