def visualize_labeled_z(z_batch, label_batch, dir=None):
fig = pylab.gcf()
fig.set_size_inches(20.0, 16.0)
pylab.clf()
colors = ["#2103c8", "#0e960e", "#e40402","#05aaa8","#ac02ab","#aba808","#151515","#94a169", "#bec9cd", "#6a6551"]
for n in xrange(z_batch.shape[0]):
result = pylab.scatter(z_batch[n, 0], z_batch[n, 1], c=colors[label_batch[n]], s=40, marker="o", edgecolors='none')
classes = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
recs = []
for i in range(0, len(colors)):
recs.append(mpatches.Rectangle((0, 0), 1, 1, fc=colors[i]))
ax = pylab.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(recs, classes, loc="center left", bbox_to_anchor=(1.1, 0.5))
pylab.xticks(pylab.arange(-4, 5))
pylab.yticks(pylab.arange(-4, 5))
pylab.xlabel("z1")
pylab.ylabel("z2")
pylab.savefig("%s/labeled_z.png" % dir)
python类subplot()的实例源码
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_dim_ordering() == 'th':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
def removeIllumination2(self, size, title = ''):
out = ndimage.filters.gaussian_filter(self.image, size)
pylab.figure()
pylab.subplot(2,2,1)
pylab.axis('off')
pylab.imshow(self.image)
pylab.subplot(2,2,2)
pylab.axis('off')
pylab.imshow(out)
pylab.subplot(2,2,3)
pylab.axis('off')
pylab.imshow(self.image - out)
pylab.subplot(2,2,4)
pylab.axis('off')
pylab.imshow(self.smooth - out)
if title != '':
pylab.savefig(title)
pylab.close()
else:
pylab.show()
self.smooth -= out
return self.image - out
def plot(self, outpath=''):
pylab.figure(figsize = (17,10))
diff = self.f2-self.f3
pylab.subplot(2,1,1)
pylab.plot(range(self.lengthSeq), self.f2, 'r-', label = "f2")
pylab.plot(range(self.lengthSeq), self.f3, 'g-', label = "f3")
pylab.xlim([0., self.lengthSeq])
pylab.tick_params(axis='both', which='major', labelsize=25)
pylab.subplot(2,1,2)
diff2 = diff/self.f3
diff2 /= np.max(diff2)
pylab.plot(range(self.lengthSeq), diff2, 'b-', label = "Rescaled (by max) difference / f3")
pylab.xlabel("Temps (en images)", fontsize = 25)
pylab.tick_params(axis='both', which='major', labelsize=25)
pylab.xlim([0., self.lengthSeq])
#pylab.legend(loc= 2, prop = {'size':15})
pylab.savefig(outpath)
pylab.close()
def plotAgainstGFP_hist2d(self):
fig1 = pylab.figure(figsize = (20, 15))
print len(self.GFP)
for i in xrange(min(len(data.cat), 4)):
print len(self.GFP[self.categories == i])
vect = []
pylab.subplot(2,2,i+1)
pop = self.GFP[self.categories == i]
print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
H, xedges, yedges = np.histogram2d(self.angles[self.categories == i], self.GFP[self.categories == i], bins = 10)
hist = pylab.hist2d(self.GFP[self.categories == i], self.angles[self.categories == i], bins = 10, cmap = pylab.cm.Reds, normed = True)
pylab.clim(0.,0.035)
pylab.colorbar()
pylab.title(data.cat[i])
pylab.xlabel('GFP score')
pylab.ylabel('Angle (degree)')
pylab.xlim([-4.2, -1])
pylab.show()
def bootstrap_extradata(self, nBoot, extradataA, nbins = 20):
pops =[]
meanpop = [[] for i in data.cat]
pylab.figure(figsize = (14,14))
for i in xrange(min(4, len(extradataA))):
#pylab.subplot(2,2,i+1)
if i ==0:
pylab.title("Bootstrap on means", fontsize = 20.)
pop = extradataA[i]# & (self.GFP > 2000)]#
for index in xrange(nBoot):
newpop = np.random.choice(pop, size=len(pop), replace=True)
#meanpop[i].append(np.mean(newpop))
pops.append(newpop)
pylab.legend()
#pylab.title(cat[i])
pylab.xlabel("Angle(degree)", fontsize = 15)
pylab.xlim([0., 90.])
for i in xrange(len(extradataA)):
for j in xrange(i+1, len(extradataA)):
statT, pvalue = scipy.stats.ttest_ind(pops[i], pops[j], equal_var=False)
print "cat{0} & cat{1} get {2} ({3})".format(i,j, pvalue,statT)
pylab.savefig("/users/biocomp/frose/frose/Graphics/FINALRESULTS-diff-f3/mean_nBootstrap{0}_bins{1}_GFPsup{2}_FLO_{3}.png".format(nBoot, nbins, 'all', randint(0,999)))
def view_waveforms_clusters(data, halo, threshold, templates, amps_lim, n_curves=200, save=False):
nb_templates = templates.shape[1]
n_panels = numpy.ceil(numpy.sqrt(nb_templates))
mask = numpy.where(halo > -1)[0]
clust_idx = numpy.unique(halo[mask])
fig = pylab.figure()
square = True
center = len(data[0] - 1)//2
for count, i in enumerate(xrange(nb_templates)):
if square:
pylab.subplot(n_panels, n_panels, count + 1)
if (numpy.mod(count, n_panels) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_panels*(n_panels - 1)):
pylab.setp(pylab.gca(), xticks=[])
subcurves = numpy.where(halo == clust_idx[count])[0]
for k in numpy.random.permutation(subcurves)[:n_curves]:
pylab.plot(data[k], '0.5')
pylab.plot(templates[:, count], 'r')
pylab.plot(amps_lim[count][0]*templates[:, count], 'b', alpha=0.5)
pylab.plot(amps_lim[count][1]*templates[:, count], 'b', alpha=0.5)
xmin, xmax = pylab.xlim()
pylab.plot([xmin, xmax], [-threshold, -threshold], 'k--')
pylab.plot([xmin, xmax], [threshold, threshold], 'k--')
#pylab.ylim(-1.5*threshold, 1.5*threshold)
ymin, ymax = pylab.ylim()
pylab.plot([center, center], [ymin, ymax], 'k--')
pylab.title('Cluster %d' %i)
if nb_templates > 0:
pylab.tight_layout()
if save:
pylab.savefig(os.path.join(save[0], 'waveforms_%s' %save[1]))
pylab.close()
else:
pylab.show()
del fig
def view_performance(file_name, triggers, lims=(150,150)):
params = CircusParser(file_name)
N_e = params.getint('data', 'N_e')
N_total = params.getint('data', 'N_total')
sampling_rate = params.getint('data', 'sampling_rate')
do_temporal_whitening = params.getboolean('whitening', 'temporal')
do_spatial_whitening = params.getboolean('whitening', 'spatial')
spike_thresh = params.getfloat('detection', 'spike_thresh')
file_out_suff = params.get('data', 'file_out_suff')
N_t = params.getint('detection', 'N_t')
nodes, edges = get_nodes_and_edges(params)
chunk_size = N_t
if do_spatial_whitening:
spatial_whitening = load_data(params, 'spatial_whitening')
if do_temporal_whitening:
temporal_whitening = load_data(params, 'temporal_whitening')
thresholds = load_data(params, 'thresholds')
try:
result = load_data(params, 'results')
except Exception:
result = {'spiketimes' : {}, 'amplitudes' : {}}
curve = numpy.zeros((len(triggers), len(result['spiketimes'].keys()), lims[1]+lims[0]), dtype=numpy.int32)
count = 0
for count, t_spike in enumerate(triggers):
for key in result['spiketimes'].keys():
elec = int(key.split('_')[1])
idx = numpy.where((result['spiketimes'][key] > t_spike - lims[0]) & (result['spiketimes'][key] < t_spike + lims[0]))
curve[count, elec, t_spike - result['spiketimes'][key][idx]] += 1
pylab.subplot(111)
pylab.imshow(numpy.mean(curve, 0), aspect='auto')
return curve
def view_raw_templates(file_name, n_temp=2, square=True):
N_e, N_t, N_tm = templates.shape
if not numpy.iterable(n_temp):
if square:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2]
else:
idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp]
else:
idx = n_temp
import matplotlib.colors as colors
my_cmap = pylab.get_cmap('winter')
cNorm = colors.Normalize(vmin=0, vmax=N_e)
scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap)
pylab.figure()
for count, i in enumerate(idx):
if square:
pylab.subplot(n_temp, n_temp, count + 1)
if (numpy.mod(count, n_temp) != 0):
pylab.setp(pylab.gca(), yticks=[])
if (count < n_temp*(n_temp - 1)):
pylab.setp(pylab.gca(), xticks=[])
else:
pylab.subplot(len(idx), 1, count + 1)
if count != (len(idx) - 1):
pylab.setp(pylab.gca(), xticks=[])
for j in xrange(N_e):
colorVal = scalarMap.to_rgba(j)
pylab.plot(templates[j, :, i], color=colorVal)
pylab.title('Template %d' %i)
pylab.tight_layout()
pylab.show()
def get_performance(file_name, name):
a, b = os.path.splitext(os.path.basename(file_name))
file_name, ext = os.path.splitext(file_name)
file_out = os.path.join(os.path.abspath(file_name), a)
data = {}
result = h5py.File(file_out + '.basis.hdf5')
data['spatial'] = result.get('spatial')[:]
data['temporal'] = numpy.zeros(61) #result.get('temporal')[:]
pylab.figure()
pylab.subplot(121)
pylab.imshow(data['spatial'], interpolation='nearest')
pylab.title('Spatial')
pylab.xlabel('# Electrode')
pylab.ylabel('# Electrode')
pylab.colorbar()
pylab.subplot(122)
pylab.title('Temporal')
pylab.plot(data['temporal'])
pylab.xlabel('Time [ms]')
x, y = pylab.xticks()
pylab.xticks(x, (x-x[-1]//2)//10)
pylab.tight_layout()
plot_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))
plot_path = os.path.join(plot_path, 'plots')
plot_path = os.path.join(plot_path, 'whitening')
if not os.path.exists(plot_path):
os.makedirs(plot_path)
output = os.path.join(plot_path, '%s.pdf' %name)
pylab.savefig(output)
return data
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 plotgrid(data,d=10,shape=(30,30)):
"""Plot a list of images on a grid."""
ion()
gray()
clf()
for i in range(min(d*d,len(data))):
subplot(d,d,i+1)
row = data[i]
if shape is not None: row = row.reshape(shape)
imshow(row)
ginput(1,timeout=0.1)
def showgrid(l,cols=None,n=400,titles=None,xlabels=None,ylabels=None,**kw):
if "cmap" not in kw: kw["cmap"] = cm.gray
if "interpolation" not in kw: kw["interpolation"] = "nearest"
n = minimum(n,len(l))
if cols is None: cols = int(sqrt(n))
rows = (n+cols-1)//cols
for i in range(n):
pylab.xticks([]) ;pylab.yticks([])
pylab.subplot(rows,cols,i+1)
pylab.imshow(l[i],**kw)
if titles is not None: pylab.title(str(titles[i]))
if xlabels is not None: pylab.xlabel(str(xlabels[i]))
if ylabels is not None: pylab.ylabel(str(ylabels[i]))
def resetplot():
import matplotlib
import pylab as plt
kw = {}
for p in ['bottom', 'top', 'left', 'right', 'hspace', 'wspace']:
kw[p] = matplotlib.rcParams['figure.subplot.' + p]
plt.subplots_adjust(**kw)
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_facade_cuts(self):
facade_sig = self.facade_edge_scores.sum(0)
facade_cuts = find_facade_cuts(facade_sig, dilation_amount=self.facade_merge_amount)
mu = np.mean(facade_sig)
sigma = np.std(facade_sig)
w = self.rectified.shape[1]
pad=10
gs1 = pl.GridSpec(5, 5)
gs1.update(wspace=0.5, hspace=0.0) # set the spacing between axes.
pl.subplot(gs1[:3, :])
pl.imshow(self.rectified)
pl.vlines(facade_cuts, *pl.ylim(), lw=2, color='black')
pl.axis('off')
pl.xlim(-pad, w+pad)
pl.subplot(gs1[3:, :], sharex=pl.gca())
pl.fill_between(np.arange(w), 0, facade_sig, lw=0, color='red')
pl.fill_between(np.arange(w), 0, np.clip(facade_sig, 0, mu+sigma), color='blue')
pl.plot(np.arange(w), facade_sig, color='blue')
pl.vlines(facade_cuts, facade_sig[facade_cuts], pl.xlim()[1], lw=2, color='black')
pl.scatter(facade_cuts, facade_sig[facade_cuts])
pl.axis('off')
pl.hlines(mu, 0, w, linestyle='dashed', color='black')
pl.text(0, mu, '$\mu$ ', ha='right')
pl.hlines(mu + sigma, 0, w, linestyle='dashed', color='gray',)
pl.text(0, mu + sigma, '$\mu+\sigma$ ', ha='right')
pl.xlim(-pad, w+pad)
def on_epoch_end(self, epoch, logs={}):
self.model.save_weights(os.path.join(self.output_dir, 'weights%02d.h5' % (epoch)))
self.show_edit_distance(256)
word_batch = next(self.text_img_gen)[0]
res = decode_batch(self.test_func, word_batch['the_input'][0:self.num_display_words])
if word_batch['the_input'][0].shape[0] < 256:
cols = 2
else:
cols = 1
for i in range(self.num_display_words):
pylab.subplot(self.num_display_words // cols, cols, i + 1)
if K.image_data_format() == 'channels_first':
the_input = word_batch['the_input'][i, 0, :, :]
else:
the_input = word_batch['the_input'][i, :, :, 0]
pylab.imshow(the_input.T, cmap='Greys_r')
pylab.xlabel('Truth = \'%s\'\nDecoded = \'%s\'' % (word_batch['source_str'][i], res[i]))
fig = pylab.gcf()
fig.set_size_inches(10, 13)
pylab.savefig(os.path.join(self.output_dir, 'e%02d.png' % (epoch)))
pylab.close()
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 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 test_discretization(nmpc, nb_steps):
dT = nmpc.preview.dT
pylab.ion()
pylab.clf()
ax = pylab.subplot(311)
ax.set_color_cycle(['r', 'g', 'b'])
pylab.plot(
[sum(dT[:i]) for i in xrange(len(dT))],
nmpc.preview.P, marker='o')
pylab.plot(
pylab.linspace(0., sum(dT), nb_steps + 1),
[x[0:3] for x in nmpc.preview.discretize(nb_steps)],
marker='s', linestyle='--')
ax = pylab.subplot(312)
ax.set_color_cycle(['r', 'g', 'b'])
pylab.plot(
[sum(dT[:i]) for i in xrange(len(dT))],
nmpc.preview.V, marker='o')
pylab.plot(
pylab.linspace(0., sum(dT), nb_steps + 1),
[x[3:6] for x in nmpc.preview.discretize(nb_steps)],
marker='s', linestyle='--')
ax = pylab.subplot(313)
ax.set_color_cycle(['r', 'g', 'b'])
pylab.plot(
[sum(dT[:i]) for i in xrange(len(dT))],
nmpc.preview.Z, marker='o')
pylab.plot(
pylab.linspace(0., sum(dT), nb_steps + 1),
[x[6:9] for x in nmpc.preview.discretize(nb_steps)],
marker='s', linestyle='--')