def plot(self):
""" Plot the layer data (for debugging)
:return: The current figure
"""
import pylab as pl
aspect = self.nrows / float(self.ncols)
figure_width = 6 #inches
rows = max(1, int(np.sqrt(self.nlayers)))
cols = int(np.ceil(self.nlayers/rows))
# noinspection PyUnresolvedReferences
pallette = {i:rgb for (i, rgb) in enumerate(pl.cm.jet(np.linspace(0, 1, 4), bytes=True))}
f, a = pl.subplots(rows, cols)
f.set_size_inches(6 * cols, 6 * rows)
a = a.flatten()
for i, label in enumerate(self.label_names):
pl.sca(a[i])
pl.title(label)
pl.imshow(self.color_data)
pl.imshow(colorize(self.label_data[:, :, i], pallette), alpha=0.5)
# axis('off')
return f
python类subplots()的实例源码
def _visualize(grid, device, img, gen):
# for debugging:
# show intermediate steps of iteration
# in [vignettingDiscreteSteps]
import pylab as plt
fig, ax = plt.subplots(1, 3)
ax[0].set_title('device')
ax[0].imshow(device, interpolation='none')
ax[1].set_title('average')
ax[1].imshow(grid, interpolation='none')
ax[2].set_title('grid')
im = ax[2].imshow(img, interpolation='none')
for x, y in gen:
ax[2].plot(x, y)
fig.colorbar(im)
plt.show()
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_candidates(self):
"""Plot a representation of candidate periodicity
Size gives the periodicity strength,
color the order of preference
"""
fig, ax = pl.subplots(2, sharex=True)
hues = np.arange(self.ncand)/float(self.ncand)
hsv = np.swapaxes(np.atleast_3d([[hues, np.ones(len(hues)),
np.ones(len(hues))]]), 1, 2)
cols = hsv_to_rgb(hsv).squeeze()
for per in self.periods:
nc = len(per.cand_period)
ax[0].scatter(per.time*np.ones(nc), per.cand_period,
s=per.cand_strength*100,
c=cols[0:nc], alpha=.5)
ax[0].plot(*zip(*[[per.time, float(per.get_preferred_period())]
for per in self.periods]), color='k')
ax[1].plot(self.get_times(), self.get_strength())
def plot_time_freq(self, colors=True, ax=None):
import pylab as pl
if ax is None:
fig, allax = pl.subplots(1)
ax = allax
# make time matrix same shape as others
t = np.outer(self.t, np.ones(self.npeaks))
f = self.f
if colors:
mag = 20*np.log10(self.mag)
ax.scatter(t, f, s=6, c=mag, lw=0)
else:
mag = 100 + 20*np.log10(self.mag)
ax.scatter(t, f, s=mag, lw=0)
pl.xlabel('Time (s)')
pl.ylabel('Frequency (Hz)')
# if colors:
# cs = pl.colorbar(ax=ax)
# cs.set_label('Magnitude (dB)')
# pl.show()
return ax
def sns_triangle(matrix, plt_title, only_class=None):
sns.set(style="white")
# Generate a mask for the upper triangle
mask = np.zeros_like(matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(matrix.as_matrix(), mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=5, yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
title(plt_title)
xlabel('Preprocessed Features')
ylabel('Preprocessed Features')
if only_class is None:
only_class = ''
savefig('images/triangle'+only_class+'.png')
def align_subplots(
N,
M,
xlim=None,
ylim=None,
):
"""make all of the subplots have the same limits, turn off unnecessary ticks"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
xlim[0] = min(xlim[0], pb.xlim()[0])
xlim[1] = max(xlim[1], pb.xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for i in range(N * M):
pb.subplot(N, M, i + 1)
ylim[0] = min(ylim[0], pb.ylim()[0])
ylim[1] = max(ylim[1], pb.ylim()[1])
for i in range(N * M):
pb.subplot(N, M, i + 1)
pb.xlim(xlim)
pb.ylim(ylim)
if i % M:
pb.yticks([])
else:
removeRightTicks()
if i < M * (N - 1):
pb.xticks([])
else:
removeUpperTicks()
def align_subplot_array(axes, xlim=None, ylim=None):
"""
Make all of the axes in the array hae the same limits, turn off unnecessary ticks
use pb.subplots() to get an array of axes
"""
# find sensible xlim,ylim
if xlim is None:
xlim = [np.inf, -np.inf]
for ax in axes.flatten():
xlim[0] = min(xlim[0], ax.get_xlim()[0])
xlim[1] = max(xlim[1], ax.get_xlim()[1])
if ylim is None:
ylim = [np.inf, -np.inf]
for ax in axes.flatten():
ylim[0] = min(ylim[0], ax.get_ylim()[0])
ylim[1] = max(ylim[1], ax.get_ylim()[1])
(N, M) = axes.shape
for (i, ax) in enumerate(axes.flatten()):
ax.set_xlim(xlim)
ax.set_ylim(ylim)
if i % M:
ax.set_yticks([])
else:
removeRightTicks(ax)
if i < M * (N - 1):
ax.set_xticks([])
else:
removeUpperTicks(ax)
def plot(self):
'''
This is a wrapper function to generate the complete sag plot.
It requires datasets with two keys, 'data' and 'heading'. The former should
contain all necessary information (as a subdictionary) to call all the _draw*
functions.
'''
plot_colours = ('r', 'b', 'g', 'y')
f, axes = plt.subplots(3, 1, figsize=(16,7))
ax = plt.subplot(1, 4, 1)
plt.tick_params(labelsize=10)
plt.rcParams.update({'axes.titlesize': 'small', 'axes.labelsize': 'small', 'xtick.labelsize':'small', 'ytick.labelsize':'small'})
for idx, d in enumerate(self.datasets):
self._drawLinearDisplacementsToAxis(ax, d['data']['x'], d['data']['y'],
d['data']['x_err'], d['data']['y_err'],
d['data']['mount_angles'], d['data']['fit_xc'],
d['data']['fit_yc'], d['data']['fit_r'],
d['heading'],
color=plot_colours[idx])
ax = plt.subplot(1, 4, 2, projection='polar')
for idx, d in enumerate(self.datasets):
self._drawRadialDisplacementsToAxis(ax, d['data']['xy_angles_from_12_o_clock'],
(d['data']['x'], d['data']['y']),
d['data']['mount_angles'], label=d['heading'],
color=plot_colours[idx])
ax = plt.subplot(1, 4, 3, projection='polar')
for idx, d in enumerate(self.datasets):
self._drawResidualsToAxis(ax, d['data']['xy_angles_from_12_o_clock'],
d['data']['residuals'], d['data']['mount_angles'],
label=d['heading'], color=plot_colours[idx])
ax = plt.subplot(1, 4, 4, projection='polar')
for idx, d in enumerate(self.datasets):
self._drawAnglesFromMountNormalToAxis(ax, d['data']['xy_angles_from_12_o_clock'],
[angle[2] for angle in
d['data']['angles_from_mount_normal']],
d['data']['mount_angles'],
label=d['heading'], color=plot_colours[idx])
def plotFitResult(fit, show_legend=True, show_plots=True, save_to_file=False,
foldername='', filename='', filetype='png'):
xvals = fit.xvals
yvals = fit.yvals
fit = fit.fitValues(xvals)
fig, ax = plt.subplots(1)
ax.plot(xvals, yvals, label='histogram', linewidth=3)
for n, f in enumerate(fit):
ax.plot(xvals, f, label='peak %i' % (n + 1), linewidth=6)
l2 = ax.legend(loc='upper center', bbox_to_anchor=(0.7, 1.05),
ncol=3, fancybox=True, shadow=True)
l2.set_visible(show_legend)
plt.xlabel('pixel value')
plt.ylabel('number of pixels')
if save_to_file:
p = PathStr(foldername).join(filename).setFiletype(filetype)
plt.savefig(p)
with open(PathStr(foldername).join('%s_params.csv' % filename), 'w') as f:
f.write('#x, #y, #fit\n')
for n, (x, y, ys) in enumerate(zip(xvals, yvals)):
fstr = ', '.join(str(f[n]) for f in fit)
f.write('%s, %s, %s\n' % (x, y, fstr))
if show_plots:
plt.show()
# REMOVE? or into scripts
def make_panel_of_intensity_slices(fn, c_n=9):
M.rcParams.update({'font.size': 13})
intensList = read.extract_arr_from_h5(fn, "/history/intensities", n=c_n)
quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
P.ioff()
intens_len = len(intensList)
sqrt_len = int(N.sqrt(intens_len))
intens_sh = intensList[0].shape
iter_labels = read.create_interval_labels(len(quatList), c_n)[:intens_len]
to_plot = intensList[:intens_len]
quat_label = quatList[N.array(iter_labels)-1][:intens_len]
plot_titles = ["iter_%d, quat_%d"%(ii,jj) for ii,jj in zip(iter_labels, quat_label)]
fig, ax = P.subplots(sqrt_len, sqrt_len, sharex=True, sharey=True, figsize=(1.8*sqrt_len, 2.*sqrt_len))
plt_counter = 0
for r in range(sqrt_len):
for c in range(sqrt_len):
ax[r,c].set_title(plot_titles[plt_counter])
curr_slice = to_plot[plt_counter][intens_sh[0]/2]
curr_slice = curr_slice*(curr_slice>0.) + 1.E-8*(curr_slice<=0.)
ax[r,c].set_title(plot_titles[plt_counter], fontsize=11.5)
im = ax[r,c].imshow(N.log10(curr_slice), vmin=-6.5, vmax=-3.5, aspect='auto', cmap=P.cm.coolwarm)
plt_counter += 1
fig.subplots_adjust(wspace=0.01)
(shx, shy) = curr_slice.shape
(h_shx, h_shy) = (shx/2, shy/2)
xt = N.linspace(0.5*h_shx, shx-.5*h_shx-1, 3).astype('int')
xt_l = N.linspace(-0.5*h_shx, 0.5*h_shx, 3).astype('int')
yt = N.linspace(0, shy-1, 3).astype('int')
yt_l = N.linspace(-1*h_shy, h_shy, 3).astype('int')
P.setp(ax, xticks=xt, xticklabels=xt_l, yticks=yt, yticklabels=yt_l)
cbar_ax = fig.add_axes([0.9, 0.1, 0.025, 0.8])
fig.colorbar(im, cax=cbar_ax, label="log10(intensities)")
img_name = "recon_series.pdf"
P.savefig(img_name, bbox_inches='tight')
print("Image has been saved as %s" % img_name)
P.close(fig)
def make_error_time_plot(fn):
M.rcParams.update({'font.size': 12})
errList = read.extract_arr_from_h5(fn, "/history/error", n=-1)
timesList = read.extract_arr_from_h5(fn, "/history/time", n=-1)
quatList = read.extract_arr_from_h5(fn, "/history/quaternion", n=-1)
quatSwitchPos = N.where(quatList[:-1]-quatList[1:] != 0)[0] + 1
P.ioff()
fig, ax = P.subplots(2, 1, sharex=True, figsize=(6,6))
fig.subplots_adjust(hspace=0.1)
iters = range(1, len(errList)+1)
ax[0].set_title("model change vs iterations")
#ax[0].set_xlabel("iteration")
ax[0].set_ylabel("log10(rms diffraction \nvolume change per voxel)")
err_to_plot = N.log10(errList)
ax[0].plot(iters, err_to_plot, 'k-')
ax[0].plot(iters, err_to_plot, 'ko')
(e_min, e_max) = (err_to_plot.min()-0.3, err_to_plot.max())
e_int = 0.1*(e_max-e_min)
ax[0].plot([1, 1], [e_min, e_max + e_int], 'k-')
ax[0].text(2, e_max+e_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
for n,qs in enumerate(quatSwitchPos):
ax[0].plot([qs+1, qs+1], [e_min, e_max + e_int], 'k-')
ax[0].text(qs, e_max+(1-n)*e_int, "quat%d"%quatList[qs], size=8, rotation=-0, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1') )
ax[1].set_xlabel("iteration")
ax[1].set_ylabel("time per iteration (s)")
ax[1].plot(iters, timesList, 'k-')
ax[1].plot(iters, timesList, 'ko')
(t_min, t_max) = (timesList.min()-100, timesList.max())
t_int = 0.1*(t_max-t_min)
ax[1].plot([1, 1], [t_min, t_max + t_int], 'k-')
ax[1].text(2, t_max+t_int, "quat%d"%quatList[0], size=8, rotation=-0, ha='left', va='center', color='w', bbox=dict(boxstyle="larrow,pad=0.1",facecolor='0.1') )
for n,qs in enumerate(quatSwitchPos):
ax[1].plot([qs+1, qs+1], [t_min, t_max+t_int], 'k-')
ax[1].text(qs+0.5, t_min, "quat%d"%quatList[qs], size=8, rotation=45, ha='right', va='center', color='w', bbox=dict(boxstyle="rarrow,pad=0.1",facecolor='0.1'))
img_name = "time_and_error_plot.pdf"
P.savefig(img_name, bbox_inches='tight')
print("Image has been saved as %s" % img_name)
P.close(fig)
def pieGen(frac, color):
frac = int(frac)
colors = [color, 'w']
fracs = [frac,100-frac]
fig,ax = pylab.subplots(figsize=(1,1))
pie = ax.pie(fracs,colors=colors, shadow=False, startangle=90, counterclock=False)
fname = 'figs/pc_' + str(int(frac)) + '.png'
pylab.savefig(fname)
pylab.close(fig)
def __init__(self) :
self.fig, self.axes = plt.subplots()
FigureCanvas.__init__(self, self.fig)
def get_canva_genome(self) :
# plot_canva
figure, ax = plt.subplots()
addValue = 0
xticks_positions = []
chronames = []
for chromosome, dataPosi in sorted(self.data.iteritems(), key = lambda x : (len(x[0]), x[0])) :
chronames.append(chromosome)
x, y = [], []
maxposi = 0
for posi, snp in sorted(dataPosi.iteritems(), key = lambda x : x[0]) :
genome_posi = posi + addValue
snp.set_genome_posi(genome_posi)
x.append(genome_posi)
y.append(snp.abhet)
maxposi = posi if posi > maxposi else posi
ax.plot(x, y, 'o', markersize=4)
xticks_positions.append((addValue * 2 + maxposi) / 2.0)
addValue += maxposi
ax.set_xlim([0, addValue])
ax.set_xticks(xticks_positions)
ax.set_xticklabels(chronames)
canva = MplCanva(self, None, figure, ax)
canva.mpl_connect('button_press_event', self.click_pressed_genome)
self.adjust_layout()
return canva
def get_canva_chromosome(self, chromosome) :
figure, ax = plt.subplots()
x, y = [], []
for posi, snp in sorted(self.data[chromosome].iteritems(), key = lambda x : x[0]) :
x.append(posi)
y.append(snp.abhet)
ax.plot(x, y, 'o', markersize=4, color="black")
canva = MplCanva(self, chromosome, figure, ax)
canva.mpl_connect('button_press_event', canva.button_pressed)
canva.mpl_connect('motion_notify_event', canva.mouse_move)
canva.mpl_connect('button_release_event', canva.button_released)
self.adjust_layout()
return canva
def stat_all_by_rank(self):
ranks = ['??', '??', '??', '??', '????', '????']
men_infos = Info.objects.filter(gender = '?')
women_infos = Info.objects.filter(gender = '?')
men_ranks = [i.get_rank() for i in men_infos]
women_ranks = [i.get_rank() for i in women_infos]
men_count = [men_ranks.count(r) for r in ranks]
women_count = [women_ranks.count(r) for r in ranks]
ind = np.arange(6)
width = 0.35
fig, ax = pl.subplots(figsize = (5.2, 2.8))
rects1 = ax.bar(ind, men_count, width, color = '#20b2aa')
rects2 = ax.bar(ind + width, women_count, width, color = 'w')
ax.set_ylabel('??', fontproperties = zhfont)
ax.set_xlim(-0.5, 7)
ax.set_xticks(ind+width)
ax.set_xticklabels(ranks, fontproperties = zhfont)
ax.legend((rects1[0], rects2[0]), ('Men', 'Women'), fontsize = 'small')
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2,
1.05 * height,
'%d' % int(height),
ha = 'center',
va='bottom',
)
autolabel(rects1)
autolabel(rects2)
fig.savefig(self.file_path + 'all1.jpg')
fig.clear()
def displayGraph2( nbPillar,g,r, lw):
x1 = []
x2 = []
y1 = []
y2 = []
lines = []
c = []
d2 = copy.deepcopy(g)
while len(d2) > 0:
n1 = d2.keys()[0]
n2 = d2[n1].keys()[0]
c1 = pillar2tocart(n1,nbPillar,r)
c2 = pillar2tocart(n2,nbPillar,r)
#x1.append(c1[0])
#x2.append(c2[0])
#y1.append(c1[1])
#y2.append(c2[1])
lines.append(((c1[0],-c1[1]),(c2[0],-c2[1])))
c.append( (0,0,0,1) )
decreaseWeightEdge(d2,n1,n2)
#lines = plt.plot( np.stack(x1),np.stack(y1),np.stack(x2),np.stack(y2))
#plt.setp(lines, color='white', linewidth=1.0)
#plt.gca().set_axis_bgcolor('black')
lc = mc.LineCollection(lines,colors=np.array(c) ,linewidths=lw)
fig, ax = pl.subplots()
ax.add_collection(lc)
ax.autoscale()
ax.margins(0.1)
fig.show()
#plt.show()
def run(self):
coords = self.opts.coords
names = vars(self.opts).get('names',len(coords)*[''])
labels=[n.lower().replace(' ','_').replace('(','').replace(')','') for n in names]
for name,label,coord in zip(names,labels,coords):
glon,glat = coord[0],coord[1]
print '\t',name,'(%.2f,%.2f)'%(glon,glat)
fig,ax = plt.subplots(1,1,figsize=(8,8))
plotter =ugali.utils.plotting.BasePlotter(glon,glat,self.config,radius=0.5)
plotter.image_kwargs.update(opt='GL',xsize=800)
plotter.drawImage(ax,invert=False)
fig.suptitle(label)
outfile='%s_sdss_image.png'%label
plt.savefig(outfile,dpi=200)
def plot4(self):
fig = pylab.figure(figsize=(8,8))
axes = AxesGrid(fig, 111,nrows_ncols = (2, 2),axes_pad=0.25,
cbar_mode='each',cbar_pad=0,cbar_size='5%',
share_all=True,aspect=True,
label_mode='L')
#fig,axes = plt.subplots(2,2)
#axes = axes.flatten()
#for ax in axes:
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
#plt.sca(axes[0]); self.drawImage(axes[0])
#plt.sca(axes[1]); self.drawStellarDensity(axes[1])
#plt.sca(axes[2]); self.drawMask(axes[2])
#plt.sca(axes[3]); self.drawTS(axes[3])
try: plt.sca(axes[0]); self.drawImage()
except IOError as e: logger.warn(str(e))
plt.sca(axes[1]); self.drawStellarDensity()
plt.sca(axes[2]); self.drawMask()
try: plt.sca(axes[3]); self.drawTS()
except IOError as e: logger.warn(str(e))
axes[0].set_xlim(self.radius,-self.radius)
axes[0].set_ylim(-self.radius,self.radius)
return fig,axes
def plotChernoff(ts,bands='smooth',pdf=False):
fig,ax = plt.subplots(1,1)
drawChernoff(ax,ts,bands,pdf)
def plot_similarity(self, ax=None):
xc = self._calc()
if not ax:
fig, ax = pl.subplots(1)
ln = ax.plot(np.arange(len(xc))-self.nwind+1, xc)
ax.hold('on')
ax.plot(self.cand_period, self.cand_strength, 'o',
color=ln[0].get_color())
def main():
from argparse import ArgumentParser
p = ArgumentParser()
p.add_argument('--grammar', choices=('both', 'medium', 'big'))
p.add_argument('--rollout', choices=('CP', 'DP'))
args = p.parse_args()
CP = ('evalb_avg', 'pops')
DP = ('expected_recall_avg', 'mask')
GRAMMARS = ['medium', 'big'] if args.grammar == 'both' else [args.grammar]
ACC, RUN = DP if args.rollout == 'DP' else CP
pl.ion()
fig1, ax1 = pl.subplots(nrows=3, #sharex=True,
ncols=2, figsize=(10,10))
for i in range(3):
for j in range(2):
ax1[i,j].grid(False)
fig2, ax2 = pl.subplots(nrows=1, #sharex=True,
ncols=2, figsize=(10,5))
for i, GRAMMAR in enumerate(GRAMMARS):
plot(GRAMMAR, ACC, RUN, ax=ax1[:,i], col=i)
plot2(GRAMMAR, ACC, RUN, ax=ax2[i], col=i)
fig1.tight_layout()
fig2.tight_layout()
pl.ioff()
pl.show()
def view_norms(file_name, save=True):
"""
Sanity plot of the norms of the templates.
Parameters
----------
file_name : string
"""
# Retrieve the key parameters.
params = CircusParser(file_name)
norms = load_data(params, 'norm-templates')
N_tm = norms.shape[0] / 2
y_margin = 0.1
# Plot the figure.
fig, ax = pylab.subplots(2, sharex=True)
x = numpy.arange(0, N_tm, 1)
y_cen = norms[0:N_tm]
y_ort = norms[N_tm:2*N_tm]
x_min = -1
x_max = N_tm
y_cen_dif = numpy.amax(y_cen) - numpy.amin(y_cen)
y_cen_min = numpy.amin(y_cen) - y_margin * y_cen_dif
y_cen_max = numpy.amax(y_cen) + y_margin * y_cen_dif
y_ort_dif = numpy.amax(y_ort) - numpy.amin(y_ort)
y_ort_min = numpy.amin(y_ort) - y_margin * y_ort_dif
y_ort_max = numpy.amax(y_ort) + y_margin * y_ort_dif
ax[0].plot(x, y_cen, 'o')
ax[0].set_xlim([x_min, x_max])
ax[0].set_ylim([y_cen_min, y_cen_max])
ax[0].grid()
ax[0].set_title("Norms of the %d templates in %s" %(N_tm, file_name))
ax[0].set_xlabel("template (central component)")
ax[0].set_ylabel("norm")
ax[1].plot(x, y_ort, 'o')
ax[1].set_ylim([y_ort_min, y_ort_max])
ax[1].grid()
ax[1].set_xlabel("template (orthogonal component)")
ax[1].set_ylabel("norm")
# Display the figure.
if save:
fig.savefig("/tmp/norms-templates.pdf")
pylab.close(fig)
else:
fig.show()
return
def generate_(self, inputs, mode='display', return_attend=False, return_all=False):
# assert self.config['sample_stoch'], 'RNNLM sampling must be stochastic'
# assert not self.config['sample_argmax'], 'RNNLM sampling cannot use argmax'
args = dict(k=self.config['sample_beam'],
maxlen=self.config['max_len'],
stochastic=self.config['sample_stoch'] if mode == 'display' else None,
argmax=self.config['sample_argmax'] if mode == 'display' else None,
return_attend=return_attend)
context, _, c_mask, _, Z, R = self.encoder.gtenc(inputs)
# c_mask[0, 3] = c_mask[0, 3] * 0
# L = context.shape[1]
# izz = np.concatenate([np.arange(3), np.asarray([1,2]), np.arange(3, L)])
# context = context[:, izz, :]
# c_mask = c_mask[:, izz]
# inputs = inputs[:, izz]
# context, _, c_mask, _ = self.encoder.encode(inputs)
# import pylab as plt
# # visualize_(plt.subplots(), Z[0][:, 300:], normal=False)
# visualize_(plt.subplots(), context[0], normal=False)
if 'explicit_loc' in self.config:
if self.config['explicit_loc']:
max_len = context.shape[1]
expLoc = np.eye(max_len, self.config['encode_max_len'], dtype='float32')[None, :, :]
expLoc = np.repeat(expLoc, context.shape[0], axis=0)
context = np.concatenate([context, expLoc], axis=2)
sample, score, ppp = self.decoder.get_sample(context, c_mask, inputs, **args)
if return_all:
return sample, score, ppp
if not args['stochastic']:
score = score / np.array([len(s) for s in sample])
idz = score.argmin()
sample = sample[idz]
score = score.min()
ppp = ppp[idz]
else:
score /= float(len(sample))
return sample, np.exp(score), ppp
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_samples(samples, burnin=1000, r_max=35):
from .features import LJPotential
kw_hist = dict(normed=True, bins=100, alpha=0.7, color='k')
fig, ax = plt.subplots(2,3,figsize=(12,8))
ax = ax.flat
names = ('s', 'r_min', 'eps')
xlabels = (r'standard deviation $s$',
r'bead radius $R_\mathrm{CG}$',
r'$\epsilon$')
for i, name in enumerate(names):
x = np.array(samples[name][burnin:])
x = x[~np.isnan(x)]
ax[i].hist(x, **kw_hist)
ax[i].set_xlabel(xlabels[i])
ax[3].scatter(*np.transpose(samples['theta'][burnin:]), alpha=0.2, s=20, color='k')
ax[3].set_xlabel(r'$\lambda_1$')
ax[3].set_ylabel(r'$\lambda_2$')
r, g = rdf(samples['X'][::10],r_max=r_max, bins=100)
ax[4].plot(r, g/g.max(), lw=3, color='k', alpha=0.7)
ax[4].set_xlabel(r'distance [$\AA$]')
ax[4].set_ylabel(r'RDF')
prior = LJPotential()
prior.params[...] = np.mean(samples['theta'][-1000:],0)
R = np.linspace(prior.r_min*0.85, prior.r_min*3, 100) * 2
ax[5].axhline(0.,ls='--', lw=3, color='k')
ax[5].plot(R, prior.profile(R), lw=5, alpha=0.3, color='k', label='CG potential')
ax[5].plot(r, -np.log(g/g.max())-prior.epsilon, lw=2, ls='--', alpha=0.9, color='k', label='PMF')
ax[5].legend()
ax[5].set_xlim(R.min(), R.max())
ax[5].set_ylim(-1.1*prior.epsilon, 2*prior.epsilon)
fig.tight_layout()
return fig
def plot_rels(data, labels=None, colors=None, outfile="rels", latent=None, alpha=0.8, title=''):
ns, n = data.shape
if labels is None:
labels = map(str, range(n))
ncol = 5
nrow = int(np.ceil(float(n * (n - 1) / 2) / ncol))
fig, axs = pylab.subplots(nrow, ncol)
fig.set_size_inches(5 * ncol, 5 * nrow)
pairs = list(combinations(range(n), 2))
if colors is not None:
colors = (colors - np.min(colors)) / (np.max(colors) - np.min(colors))
for ax, pair in zip(axs.flat, pairs):
diff_x = max(data[:, pair[0]]) - min(data[:, pair[0]])
diff_y = max(data[:, pair[1]]) - min(data[:, pair[1]])
ax.set_xlim([min(data[:, pair[0]]) - 0.05 * diff_x, max(data[:, pair[0]]) + 0.05 * diff_x])
ax.set_ylim([min(data[:, pair[1]]) - 0.05 * diff_y, max(data[:, pair[1]]) + 0.05 * diff_y])
ax.scatter(data[:, pair[0]], data[:, pair[1]], c=colors, cmap=pylab.get_cmap("jet"),
marker='.', alpha=alpha, edgecolors='none', vmin=0, vmax=1)
ax.set_xlabel(shorten(labels[pair[0]]))
ax.set_ylabel(shorten(labels[pair[1]]))
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.scatter(data[:, 0], data[:, 1], marker='.')
fig.suptitle(title, fontsize=16)
pylab.rcParams['font.size'] = 12 #6
# pylab.draw()
# fig.set_tight_layout(True)
pylab.tight_layout()
pylab.subplots_adjust(top=0.95)
for ax in axs.flat[axs.size - 1:len(pairs) - 1:-1]:
ax.set_visible(False)
filename = outfile + '.png'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
fig.savefig(outfile + '.png')
pylab.close('all')
return True
# Hierarchical graph visualization utilities
def handle(self, *args, **kwargs):
tz = get_current_timezone()
sessions = CashdeskSession.objects.filter(
cashdesk__name__startswith="Kasse"
).values('id', 'start', 'end', 'cashdesk')
firststart = CashdeskSession.objects.order_by('start').first().start.date()
lastend = CashdeskSession.objects.order_by('-end').first().end.date()
days = (lastend - firststart).days + 1
fig, axs = plt.subplots(math.ceil(days / 2), 2, figsize=(11.69, 8.27), sharey=True)
for i in range(days):
sp = axs[i // 2, i % 2]
x = np.linspace(0, 24, 300)[:-1]
day = firststart + timedelta(days=i)
d = TransactionPosition.objects.filter(
transaction__datetime__lt=firststart + timedelta(days=i + 1),
transaction__datetime__gt=firststart + timedelta(days=i)
).values('transaction__datetime', 'preorder_position')
sp.hist([
[dtf(p['transaction__datetime'].astimezone(tz)) for p in d if p['preorder_position']],
[dtf(p['transaction__datetime'].astimezone(tz)) for p in d if not p['preorder_position']]
], label=[
'Presale transactions',
'Cash transactions'
], bins=np.arange(0, 24.5, 0.5), histtype='barstacked')
sp.set_title(day.strftime("%Y-%m-%d"))
ax2 = sp.twinx()
ax2.plot(x, [opensessions(x, sessions, firststart + timedelta(days=i)) for x in x],
label='Open cashdesks', color='r')
ax2.set_ylim(0, 6)
if i == 0:
ax2.legend(loc='upper left')
elif i == 3:
ax2.set_ylabel('Open cashdesks')
sp.set_xlim(0, 24)
sp.set_xticks(range(0, 25, 2))
axs[1, 1].legend(loc='upper left')
axs[1, 0].set_ylabel(u'Number of Transactions')
axs[2, 0].set_xlabel(u'Time of day')
fig.tight_layout()
fig.suptitle('Cashdesk transactions 33c3')
plt.savefig('transactions.svg')
plt.savefig('transactions.png')
def plot_one_dir(args, directory):
""" The actual plotting code.
Assumes that we'll be plotting from one directory, which usually means
considering one random seed only, however it's better to have multiple
random seeds so this code generalizes. For ES, we should store the output at
*every* timestep, so A['TotalIterations'] should be like np.arange(...), but
this generalizes in case Ray can help me run for many more iterations.
"""
print("Now plotting based on directory {} ...".format(directory))
### Figure 1: The log.txt file.
num = len(ATTRIBUTES)
fig, axes = subplots(num, figsize=(12,3*num))
for (dd, cc) in zip(directory, COLORS):
A = np.genfromtxt(join(args.expdir, dd, 'log.txt'),
delimiter='\t', dtype=None, names=True)
x = A['TotalIterations']
for (i,attr) in enumerate(ATTRIBUTES):
axes[i].plot(x, A[attr], '-', lw=lw, color=cc, label=dd)
axes[i].set_ylabel(attr, fontsize=ysize)
axes[i].tick_params(axis='x', labelsize=tick_size)
axes[i].tick_params(axis='y', labelsize=tick_size)
axes[i].legend(loc='best', ncol=1, prop={'size':legend_size})
plt.tight_layout()
plt.savefig(args.out+'_log.png')
### Figure 2: Error regions.
num = len(directory)
if num == 1:
num+= 1
fig, axes = subplots(1,num, figsize=(12*num,10))
for (i, (dd, cc)) in enumerate(zip(directory, COLORS)):
A = np.genfromtxt(join(args.expdir, dd, 'log.txt'),
delimiter='\t', dtype=None, names=True)
axes[i].plot(A['TotalIterations'], A["FinalAvgReturns"],
color=cc, marker='x', ms=ms, lw=lw)
axes[i].fill_between(A['TotalIterations'],
A["FinalAvgReturns"] - A["FinalStdReturns"],
A["FinalAvgReturns"] + A["FinalStdReturns"],
alpha = error_region_alpha,
facecolor='y')
axes[i].set_ylim(ENV_TO_YLABELS[args.envname])
axes[i].tick_params(axis='x', labelsize=tick_size)
axes[i].tick_params(axis='y', labelsize=tick_size)
axes[i].set_title("Mean Episode Rewards ({})".format(dd), fontsize=title_size)
axes[i].set_xlabel("ES Iterations", fontsize=xsize)
axes[i].set_ylabel("Rewards", fontsize=ysize)
plt.tight_layout()
plt.savefig(args.out+'_rewards_std.png')