def ezrc(fontSize=22., lineWidth=2., labelSize=None, tickmajorsize=10,
tickminorsize=5, figsize=(8, 6)):
"""
slides - Define params to make pretty fig for slides
"""
from pylab import rc, rcParams
if labelSize is None:
labelSize = fontSize + 5
rc('figure', figsize=figsize)
rc('lines', linewidth=lineWidth)
rcParams['grid.linewidth'] = lineWidth
rcParams['font.sans-serif'] = ['Helvetica']
rcParams['font.serif'] = ['Helvetica']
rcParams['font.family'] = ['Times New Roman']
rc('font', size=fontSize, family='serif', weight='bold')
rc('axes', linewidth=lineWidth, labelsize=labelSize)
rc('legend', borderpad=0.1, markerscale=1., fancybox=False)
rc('text', usetex=True)
rc('image', aspect='auto')
rc('ps', useafm=True, fonttype=3)
rcParams['xtick.major.size'] = tickmajorsize
rcParams['xtick.minor.size'] = tickminorsize
rcParams['ytick.major.size'] = tickmajorsize
rcParams['ytick.minor.size'] = tickminorsize
rcParams['text.latex.preamble'] = ["\\usepackage{amsmath}"]
python类rc()的实例源码
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 plot_trajectories(self):
pylab.clf()
pylab.rc('text', usetex=True)
pylab.rc('font', size=18)
pylab.subplot(121)
self.plot_com()
pylab.subplot(122)
self.plot_zmp()
def plot_measurements(time_points, ydata):
pl.rc("text", usetex = True)
pl.rc("font", family="serif")
pl.subplot2grid((4, 2), (0, 0))
pl.plot(time_points, ydata[:,0])
pl.title("Considered measurement data")
pl.xlabel("t")
pl.ylabel("X", rotation = 0, labelpad = 20)
pl.subplot2grid((4, 2), (1, 0))
pl.plot(time_points, ydata[:,1])
pl.xlabel("t")
pl.ylabel("Y", rotation = 0, labelpad = 15)
pl.subplot2grid((4, 2), (2, 0))
pl.plot(time_points, ydata[:,2])
pl.xlabel("t")
pl.ylabel(r"\phi", rotation = 0, labelpad = 15)
pl.subplot2grid((4, 2), (3, 0))
pl.plot(time_points, ydata[:,3])
pl.xlabel("t")
pl.ylabel("v", rotation = 0, labelpad = 20)
pl.subplot2grid((4, 2), (0, 1), rowspan = 4)
pl.plot(ydata[:,0], ydata[:, 1])
pl.title("Considered racecar track (measured)")
pl.xlabel("X")
pl.ylabel("Y", rotation = 0, labelpad = 20)
pl.show()
def plot_simulation_results_initial_controls(time_points, y_sim):
pl.rc("text", usetex = True)
pl.rc("font", family="serif")
pl.subplot2grid((4, 2), (0, 0))
pl.plot(time_points, y_sim[:,0])
pl.title("Simulation results for initial controls")
pl.xlabel("t")
pl.ylabel("X", rotation = 0, labelpad = 20)
pl.subplot2grid((4, 2), (1, 0))
pl.plot(time_points, y_sim[:,1])
pl.xlabel("t")
pl.ylabel("Y", rotation = 0, labelpad = 15)
pl.subplot2grid((4, 2), (2, 0))
pl.plot(time_points, y_sim[:,2])
pl.xlabel("t")
pl.ylabel(r"\phi", rotation = 0, labelpad = 15)
pl.subplot2grid((4, 2), (3, 0))
pl.plot(time_points, y_sim[:,3])
pl.xlabel("t")
pl.ylabel("v", rotation = 0, labelpad = 20)
pl.subplot2grid((4, 2), (0, 1), rowspan = 4)
pl.plot(y_sim[:,0], y_sim[:, 1])
pl.title("Simulated race car path for initial controls")
pl.xlabel("X")
pl.ylabel("Y", rotation = 0, labelpad = 20)
pl.show()
def drawDf(pl, df, title=''):
pl.figure
if title != '':
if agl.is_utf8(title):
title = title.decode('utf8')
#pl.title(title, fontproperties=getFont())
if not isinstance(df, type(None)):
pl.rc('font', family='simhei')
df.plot(title=title)
pl.show()
pl.close()
def drawTwoDf(pl, df1, df2, title=''):
"""?????df"""
pl.figure
pl.rc('font', family='simhei')
if title != '':
if agl.is_utf8(title):
title = title.decode('utf8')
fig = pl.gcf()
ax1 = fig.add_subplot(211)
df1.plot(ax=ax1, title=title)
ax2 = fig.add_subplot(212)
df2.plot(ax=ax2)
pl.show()
pl.close()
def rc(self, *args, **kwargs):
pl.rc(*args, **kwargs)
def showFourier(self):
psd2D = np.log(np.abs(self.four)**2+1)
(height,width) = psd2D.shape
py.figure(figsize=(10,10*height/width),facecolor='white')
py.clf()
py.rc('text',usetex=True)
py.xlabel(r'$\omega_1$',fontsize=24)
py.ylabel(r'$\omega_2$',fontsize=24)
py.xticks(fontsize=16)
py.yticks(fontsize=16)
py.imshow( psd2D, cmap='Greys_r',extent=[-pi,pi,-pi,pi],aspect='auto')
py.show()
def analyse_(self, inputs, outputs, idx2word, inputs_unk=None, return_attend=False, name=None, display=False):
def cut_zero(sample, idx2word, ppp=None, Lmax=None):
if Lmax is None:
Lmax = self.config['dec_voc_size']
if ppp is None:
if 0 not in sample:
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample]
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample[:sample.index(0)]]
else:
if 0 not in sample:
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample, ppp)]
idz = sample.index(0)
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample[:idz], ppp[:idz])]
if inputs_unk is None:
result, _, ppp = self.generate_(inputs[None, :],
return_attend=return_attend)
else:
result, _, ppp = self.generate_(inputs_unk[None, :],
return_attend=return_attend)
source = '{}'.format(' '.join(cut_zero(inputs.tolist(), idx2word, Lmax=len(idx2word))))
target = '{}'.format(' '.join(cut_zero(outputs.tolist(), idx2word, Lmax=len(idx2word))))
decode = '{}'.format(' '.join(cut_zero(result, idx2word)))
if display:
print source
print target
print decode
idz = result.index(0)
p1, p2 = [np.asarray(p) for p in zip(*ppp)]
print p1.shape
import pylab as plt
# plt.rc('text', usetex=True)
# plt.rc('font', family='serif')
visualize_(plt.subplots(), 1 - p1[:idz, :].T, grid=True, name=name)
visualize_(plt.subplots(), 1 - p2[:idz, :].T, name=name)
# visualize_(plt.subplots(), 1 - np.mean(p2[:idz, :], axis=1, keepdims=True).T)
return target == decode
def analyse_(self, inputs, outputs, idx2word, inputs_unk=None, return_attend=False, name=None, display=False):
def cut_zero(sample, idx2word, ppp=None, Lmax=None):
if Lmax is None:
Lmax = self.config['dec_voc_size']
if ppp is None:
if 0 not in sample:
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample]
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample[:sample.index(0)]]
else:
if 0 not in sample:
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample, ppp)]
idz = sample.index(0)
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample[:idz], ppp[:idz])]
if inputs_unk is None:
result, _, ppp = self.generate_(inputs[None, :],
return_attend=return_attend)
else:
result, _, ppp = self.generate_(inputs_unk[None, :],
return_attend=return_attend)
source = '{}'.format(' '.join(cut_zero(inputs.tolist(), idx2word, Lmax=len(idx2word))))
target = '{}'.format(' '.join(cut_zero(outputs.tolist(), idx2word, Lmax=len(idx2word))))
decode = '{}'.format(' '.join(cut_zero(result, idx2word)))
if display:
print(source)
print(target)
print(decode)
idz = result.index(0)
p1, p2 = [np.asarray(p) for p in zip(*ppp)]
print(p1.shape)
import pylab as plt
# plt.rc('text', usetex=True)
# plt.rc('font', family='serif')
visualize_(plt.subplots(), 1 - p1[:idz, :].T, grid=True, name=name)
visualize_(plt.subplots(), 1 - p2[:idz, :].T, name=name)
# visualize_(plt.subplots(), 1 - np.mean(p2[:idz, :], axis=1, keepdims=True).T)
return target == decode
def plot_simulation_results_initial_and_optimized_controls(time_points, \
y_sim_init, y_sim_opt):
pl.rc("text", usetex = True)
pl.rc("font", family="serif")
pl.subplot2grid((4, 2), (0, 0))
pl.plot(time_points, y_sim_init[:,0], label = "initial")
pl.plot(time_points, y_sim_opt[:,0], label = "optimized")
pl.title("Simulation results for initial and optimized control")
pl.xlabel("$t$")
pl.ylabel("$X$", rotation = 0)
pl.legend(loc = "lower left")
pl.subplot2grid((4, 2), (1, 0))
pl.plot(time_points, y_sim_init[:,1], label = "initial")
pl.plot(time_points, y_sim_opt[:,1], label = "optimized")
pl.xlabel("$t$")
pl.ylabel("$Y$", rotation = 0)
pl.legend(loc = "lower left")
pl.subplot2grid((4, 2), (2, 0))
pl.plot(time_points, y_sim_init[:,2], label = "initial")
pl.plot(time_points, y_sim_opt[:,2], label = "optimized")
pl.xlabel("$t$")
pl.ylabel("$\psi$", rotation = 0)
pl.legend(loc = "lower left")
pl.subplot2grid((4, 2), (3, 0))
pl.plot(time_points, y_sim_init[:,3], label = "initial")
pl.plot(time_points, y_sim_opt[:,3], label = "optimized")
pl.xlabel("$t$")
pl.ylabel("$v$", rotation = 0)
pl.legend(loc = "upper left")
pl.subplot2grid((4, 2), (0, 1), rowspan = 4)
pl.plot(y_sim_init[:,0], y_sim_init[:,1], label = "initial")
pl.plot(y_sim_opt[:,0], y_sim_opt[:,1], label = "optimized")
pl.title("Simulated race car path for initial and optimized controls")
pl.xlabel("$X$")
pl.ylabel("$Y$", rotation = 0)
pl.legend(loc = "lower left")
pl.show()
def plot_initial_and_optimized_controls(time_points, \
udata_init, udata_opt, umin, umax):
pl.rc("text", usetex = True)
pl.rc("font", family="serif")
pl.subplot2grid((2, 1), (0, 0))
pl.step(time_points[:-1], udata_init[:,0], label = "$\delta_{init}$")
pl.step(time_points[:-1], udata_init[:,1], label = "$D_{init}$")
pl.plot([time_points[0], time_points[-2]], [umin[0], umin[0]], \
color = "b", linestyle = "dashed", label = "$\delta_{min}$")
pl.plot([time_points[0], time_points[-2]], [umax[0], umax[0]], \
color = "b", linestyle = "dotted", label = "$\delta_{max}$")
pl.plot([time_points[0], time_points[-2]], [umin[1], umin[1]], \
color = "g", linestyle = "dashed", label = "$D_{min}$")
pl.plot([time_points[0], time_points[-2]], [umax[1], umax[1]], \
color = "g", linestyle = "dotted", label = "$D_{max}$")
pl.ylabel("$\delta,\,D$", rotation = 0)
pl.ylim(-0.6, 1.1)
pl.title("Initial and optimized controls")
pl.legend(loc = "upper right")
pl.subplot2grid((2, 1), (1, 0))
pl.step(time_points[:-1], udata_opt[:,0], label = "$\delta_{opt,coll}$")
pl.step(time_points[:-1], udata_opt[:,1], label = "$D_{opt,coll}$")
pl.plot([time_points[0], time_points[-2]], [umin[0], umin[0]], \
color = "b", linestyle = "dashed", label = "$\delta_{min}$")
pl.plot([time_points[0], time_points[-2]], [umax[0], umax[0]], \
color = "b", linestyle = "dotted", label = "$\delta_{max}$")
pl.plot([time_points[0], time_points[-2]], [umin[1], umin[1]], \
color = "g", linestyle = "dashed", label = "$D_{min}$")
pl.plot([time_points[0], time_points[-2]], [umax[1], umax[1]], \
color = "g", linestyle = "dotted", label = "$D_{max}$")
pl.xlabel("$t$")
pl.ylabel("$\delta,\,D$", rotation = 0)
pl.ylim(-0.6, 1.1)
pl.legend(loc = "upper right")
pl.show()
def analyse_(self, inputs, outputs, idx2word, inputs_unk=None, return_attend=False, name=None, display=False):
def cut_zero(sample, idx2word, ppp=None, Lmax=None):
if Lmax is None:
Lmax = self.config['dec_voc_size']
if ppp is None:
if 0 not in sample:
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample]
return ['{}'.format(idx2word[w].encode('utf-8'))
if w < Lmax else '{}'.format(idx2word[inputs[w - Lmax]].encode('utf-8'))
for w in sample[:sample.index(0)]]
else:
if 0 not in sample:
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample, ppp)]
idz = sample.index(0)
return ['{0} ({1:1.1f})'.format(
idx2word[w].encode('utf-8'), p)
if w < Lmax
else '{0} ({1:1.1f})'.format(
idx2word[inputs[w - Lmax]].encode('utf-8'), p)
for w, p in zip(sample[:idz], ppp[:idz])]
if inputs_unk is None:
result, _, ppp = self.generate_(inputs[None, :],
return_attend=return_attend)
else:
result, _, ppp = self.generate_(inputs_unk[None, :],
return_attend=return_attend)
source = '{}'.format(' '.join(cut_zero(inputs.tolist(), idx2word, Lmax=len(idx2word))))
target = '{}'.format(' '.join(cut_zero(outputs.tolist(), idx2word, Lmax=len(idx2word))))
decode = '{}'.format(' '.join(cut_zero(result, idx2word)))
if display:
print source
print target
print decode
idz = result.index(0)
p1, p2 = [np.asarray(p) for p in zip(*ppp)]
print p1.shape
import pylab as plt
# plt.rc('text', usetex=True)
# plt.rc('font', family='serif')
visualize_(plt.subplots(), 1 - p1[:idz, :].T, grid=True, name=name)
visualize_(plt.subplots(), 1 - p2[:idz, :].T, name=name)
# visualize_(plt.subplots(), 1 - np.mean(p2[:idz, :], axis=1, keepdims=True).T)
return target == decode