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()
python类suptitle()的实例源码
def plot_scattermatrix(df, title = "plot_scattermatrix"):
"""plot a scattermatrix of dataframe df"""
if df is None:
print "plot_scattermatrix: no data passed"
return
from pandas.tools.plotting import scatter_matrix
# df = pd.DataFrame(X, columns=['x1_t', 'x2_t', 'x1_tptau', 'x2_tptau', 'u_t'])
# scatter_data_raw = np.hstack((np.array(Xs), np.array(Ys)))
# scatter_data_raw = np.hstack((Xs, Ys))
# print "scatter_data_raw", scatter_data_raw.shape
pl.ioff()
# df = pd.DataFrame(scatter_data_raw, columns=["x_%d" % i for i in range(scatter_data_raw.shape[1])])
sm = scatter_matrix(df, alpha=0.2, figsize=(10, 10), diagonal='hist')
fig = sm[0,0].get_figure()
fig.suptitle(title)
if SAVEPLOTS:
fig.savefig("fig_%03d_scattermatrix.pdf" % (fig.number), dpi=300)
fig.show()
# pl.show()
def plotaffinegrid(affines, exag=1e3, affineOnly=True, R=0.025, tpre='', bboxes=None):
import pylab as plt
NR = 3
NC = int(ceil(len(affines)/3.))
#R = 0.025 # 1.5 arcmin
#for (exag,affonly) in [(1e2, False), (1e3, True), (1e4, True)]:
plt.clf()
for i,aff in enumerate(affines):
plt.subplot(NR, NC, i+1)
dl = aff.refdec - R
dh = aff.refdec + R
rl = aff.refra - R / aff.rascale
rh = aff.refra + R / aff.rascale
RR,DD = np.meshgrid(np.linspace(rl, rh, 11),
np.linspace(dl, dh, 11))
plotaffine(aff, RR.ravel(), DD.ravel(), exag=exag, affineOnly=affineOnly,
doclf=False,
units='dots', width=2, headwidth=2.5, headlength=3, headaxislength=3)
if bboxes is not None:
for bb in bboxes:
plt.plot(*bb, linestyle='-', color='0.5')
plt.plot(*bboxes[i], linestyle='-', color='k')
setRadecAxes(rl,rh,dl,dh)
plt.xlabel('')
plt.ylabel('')
plt.xticks([])
plt.yticks([])
plt.title('field %i' % (i+1))
plt.subplots_adjust(left=0.05, right=0.95, wspace=0.1)
if affineOnly:
tt = tpre + 'Affine part of transformations'
else:
tt = tpre + 'Transformations'
plt.suptitle(tt + ' (x %g)' % exag)
def plot_marginals(state_space,p,name,t,labels = False):
import matplotlib
#matplotlib.use("PDF")
#matplotlib.rcParams['figure.figsize'] = 5,10
import matplotlib.pyplot as pl
pl.suptitle("time: "+ str(t)+" units")
print("time : "+ str(t))
D = state_space.shape[1]
for i in range(D):
marg_X = np.unique(state_space[:,i])
A = np.where(marg_X[:,np.newaxis] == state_space[:,i].T[np.newaxis,:],1,0)
marg_p = np.dot(A,p)
pl.subplot(int(D/2)+1,2,i+1)
pl.plot(marg_X,marg_p)
pl.axvline(np.sum(marg_X*marg_p),color= 'r')
pl.axvline(marg_X[np.argmax(marg_p)],color='g')
if labels == False:
pl.xlabel("Specie: " + str(i+1))
else:
pl.xlabel(labels[i])
#pl.savefig("Visuals/marginal_"+name+".pdf",format='pdf')
pl.show()
pl.clf()
##Simple Compress : best N-term approximation under the ell_1 norm
#@param state_space the state space shape: (Number of Species X Number of states)
#@param p probability vector
#@param eps the ell_1 error to remove
#@return -Compressed state space
# -Compressed Probs
def plot_marginals(state_space,p,name,t,labels = False,interactive = False):
import matplotlib
import matplotlib.pyplot as pl
if interactive == True:
pl.ion()
pl.clf()
pl.suptitle("time: "+ str(t)+" units")
#print("time : "+ str(t))
D = state_space.shape[1]
for i in range(D):
marg_X = np.unique(state_space[:,i])
A = np.where(marg_X[:,np.newaxis] == state_space[:,i].T[np.newaxis,:],1,0)
marg_p = np.dot(A,p)
pl.subplot(int(D/2)+1,2,i+1)
pl.plot(marg_X,marg_p)
pl.yticks(np.linspace(np.amin(marg_p), np.amax(marg_p), num=3))
pl.axvline(np.sum(marg_X*marg_p),color= 'r')
pl.axvline(marg_X[np.argmax(marg_p)],color='g')
if labels == False:
pl.xlabel("Specie: " + str(i+1))
else:
pl.xlabel(labels[i])
if interactive == True:
pl.draw()
else:
pl.tight_layout()
pl.show()
def plot6(self, filename, title=None):
fig = plt.figure('summary', figsize=(11, 6))
fig.subplots_adjust(wspace=0.4, hspace=0.25)
fdg = r'{.}\!^\circ'
coordstring = ('%.2f, %.2f'%(self.ra, self.dec)).replace('.',fdg)
if title is None:
#title = r'%s; ($\alpha_{2000}$, $\delta_{2000}$, $m-M$) = (%s, %.2f)'%(self.source.name, coordstring, self.isochrone.distance_modulus)
title = r'$(\alpha_{2000}, \delta_{2000}, m-M) = (%s, %.1f)$'%(coordstring, self.isochrone.distance_modulus)
if title:
plt.suptitle(title, fontsize=14)
logger.debug("Drawing smooth stars...")
plt.subplot(2, 3, 1)
self.drawSmoothStars()
logger.debug("Drawing density profile...")
pylab.subplot(2, 3, 2)
self.drawDensityProfile()
logger.debug("Drawing spatial distribution of members...")
pylab.subplot(2, 3, 3)
self.drawMembersSpatial(filename)
logger.debug("Drawing smooth galaxies...")
plt.subplot(2, 3, 4)
self.drawSmoothGalaxies()
logger.debug("Drawing Hess diagram...")
plt.subplot(2,3,5)
self.drawHessDiagram()
logger.debug("Drawing CMD of members...")
pylab.subplot(2, 3, 6)
self.drawMembersCMD(filename)
def rh_e2p_sample_plot(self):
# intro checks
if not self.attr_check(["y_samples"]):
return
pl.ioff()
# 2a. plot sampling results
pl.suptitle("%s step 1 + 2: learning proprio, then learning e2p" % (self.mode,))
ax = pl.subplot(211)
pl.title("Exteroceptive state S_e, extero to proprio mapping p2e")
self.S_ext = ax.plot(self.logs["S_ext"], "k-", alpha=0.8, label="S_e")
p2e = ax.plot(self.logs["P2E_pred"], "r-", alpha=0.8, label="p2e")
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=[handles[i] for i in [0, 2]],
labels=[labels[i] for i in [0, 2]])
ax2 = pl.subplot(212)
pl.title("Proprioceptive state S_p, proprio to extero mapping e2p")
ax2.plot(self.logs["M_prop_pred"], "k-", label="S_p")
# pl.plot(self.logs["E2P_pred"], "y-", label="E2P knn")
ax2.plot(self.y_samples, "g-", label="E2P gmm cond", alpha=0.8, linewidth=2)
ax2.plot(self.logs["X__"][:,:3], "r-", label="goal goal")
for _ in self.y_samples_:
plausibility = _ - self.logs["X__"][:,:3]
# print "_.shape = %s, plausibility.shape = %s, %d" % (_.shape, plausibility.shape, 0)
# print "_", np.sum(_), _ - self.logs["X__"][:,:3]
plausibility_norm = np.linalg.norm(plausibility, 2, axis=1)
print "plausibility = %f" % (np.mean(plausibility_norm))
if np.mean(plausibility_norm) < 0.8: # FIXME: what is that for, for thinning out the number of samples?
ax2.plot(_, "b.", label="E2P gmm samples", alpha=0.2)
handles, labels = ax2.get_legend_handles_labels()
print "handles, labels", handles, labels
legidx = slice(0, 12, 3)
ax2.legend(handles[legidx], labels[legidx])
# ax.legend(handles=[handles[i] for i in [0, 2]],
# labels=[labels[i] for i in [0, 2]])
pl.show()
def rh_e2p_sample_and_drive_plot(self):
# e2pidx = slice(self.numsteps,self.numsteps*2)
e2pidx = slice(0, self.numsteps)
pl.suptitle("%s top: extero goal and extero state, bottom: error_e = |g_e - s_e|^2" % (self.mode,))
pl.subplot(211)
pl.plot(self.logs["goal_ext"][e2pidx])
pl.plot(self.logs["S_ext"][e2pidx])
pl.subplot(212)
pl.plot(np.linalg.norm(self.logs["E_pred_e"][e2pidx], 2, axis=1))
pl.show()
def plot_scattermatrix_reduced(df, title = "plot_scattermatrix_reduced"):
input_cols = [i for i in df.columns if i.startswith("X")]
output_cols = [i for i in df.columns if i.startswith("Y")]
Xs = df[input_cols]
Ys = df[output_cols]
numsamples = df.shape[0]
print "plot_scattermatrix_reduced: numsamples = %d" % numsamples
# numplots = Xs.shape[1] * Ys.shape[1]
# print "numplots = %d" % numplots
gs = gridspec.GridSpec(Ys.shape[1], Xs.shape[1])
pl.ioff()
fig = pl.figure()
fig.suptitle(title)
# alpha = 1.0 / np.power(numsamples, 1.0/(Xs.shape[1] - 0))
alpha = 0.2
print "alpha", alpha
cols = ["k", "b", "r", "g", "c", "m", "y"]
for i in range(Xs.shape[1]):
for j in range(Ys.shape[1]):
# print "i, j", i, j, Xs, Ys
ax = fig.add_subplot(gs[j, i])
ax.plot(Xs.as_matrix()[:,i], Ys.as_matrix()[:,j], "ko", alpha = alpha)
ax.set_xlabel(input_cols[i])
ax.set_ylabel(output_cols[j])
if SAVEPLOTS:
fig.savefig("fig_%03d_scattermatrix_reduced.pdf" % (fig.number), dpi=300)
fig.show()
def process_files(files, basedir='./data', debug=False, rectify=False,
outdir='./data/for-labelme', **kwargs):
attempts = 0
n = len(files)
print "Rectify is set to", rectify
try:
os.makedirs(outdir)
except OSError as e:
pass
if debug:
try:
os.makedirs(os.path.join(outdir, 'debug'))
except OSError as e:
# Directory already exists
pass
for i, f in enumerate(files):
try:
newbasename = rename_file(f, basedir)
newname = os.path.join(outdir, newbasename)
print i + 1, 'of', n, newname
image = imread(f)
if rectify:
try:
meta = {}
rectified = rectify_building(image, meta)
if debug:
import pylab as pl
h = meta['homography']
pl.suptitle('u:{} d:{} l:{} r:{}'.format(h.du, h.dd, h.dl, h.dr))
pl.subplot(221)
pl.imshow(image)
pl.axis('off')
pl.subplot(222)
pl.imshow(meta['building'])
pl.axis('off')
pl.subplot(223)
h.plot_original()
pl.subplot(224)
h.plot_rectified()
pl.savefig(os.path.join(outdir, 'debug', newbasename))
imsave(newname, rectified)
except Exception as e:
print e
pass
else:
imsave(newname, image)
except Exception as e:
print e
def plotTriangle(srcfile,samples,burn=0,**kwargs):
#import triangle
import corner
import ugali.analysis.source
import ugali.analysis.mcmc
#matplotlib.rcParams.update({'text.usetex': True})
source = ugali.analysis.source.Source()
source.load(srcfile,section='source')
params = source.get_params()
results = yaml.load(open(srcfile))['results']
samples = ugali.analysis.mcmc.Samples(samples)
names = samples.names
labels = names
truths = [params[n] for n in names]
chain = samples.get(burn=burn,clip=5)
### Triangle plot
#extents = [[0,15e3],[323.6,323.8],[-59.8,-59.7],[0,0.1],[19.5,20.5]]
kwargs.setdefault('extents',None)
kwargs.setdefault('plot_contours',True)
kwargs.setdefault('plot_datapoints',True)
kwargs.setdefault('verbose',False)
kwargs.setdefault('quantiles',[0.16,0.84])
if len(names) > 1:
fig = corner.corner(chain,labels=labels,truths=truths,**kwargs)
else:
fig = plt.figure()
plt.hist(chain,bins=100)
plt.xlabel(names[0])
try:
text = 'RA,DEC = (%.2f,%.2f)\n'%(results['ra'][0],results['dec'][0])
text += '(m-M,D) = (%.1f, %.0f kpc)\n'%(results['distance_modulus'][0],results['distance'][0])
text += r'$r_h$ = %.1f arcmin'%(results['extension_arcmin'][0])+'\n'
text += 'TS = %.1f\n'%results['ts'][0]
text += 'NSamples = %i\n'%(len(chain))
#plt.figtext(0.65,0.90,text,ha='left',va='top')
except KeyError as e:
logger.warning(str(e))
pass
label = map(str.capitalize,source.name.split('_'))
label[-1] = label[-1].upper()
title = '%s'%' '.join(label)
plt.suptitle(title)
############################################################