def main(): A = pl.imread(IMAGE_FILE) i = 1 pc_values = (1, 5, 10, 20, 30, 40) for num_pcs in pc_values: # perform (truncated) pca egvecs, proj, egvals = pca(A, num_pcs) # reconstruct image A_rec = np.dot(egvecs, proj).T + np.mean(A, axis=0) # create sublplot ax = pl.subplot(2, 3, i, frame_on=False) ax.xaxis.set_major_locator(pl.NullLocator()) ax.yaxis.set_major_locator(pl.NullLocator()) # draw pl.imshow(A_rec) pl.title("{} pc's".format(num_pcs)) pl.gray() i += 1 pl.show()
def PlotOutput(): x = len(BAR_BRIGHTNESS) y = len(Nphotons) frameW = 1.5 frameH = 1.5 gapw = 0.05*np.ones(x+1) #gapw[0] = 0.4 gaph = 0.05*np.ones(y+1) #gaph[2] = 0.4 fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) estimlist, estimmaxlist,estimminlist = grab_files() ctr = 0 #plt.text(1,1, "No bar", fontsize=5, rotation=0, color='b') #plt.text(0.55,1, "Bar brightness = 30% outer ring", fontsize=5, rotation=0, color='k') #plt.text(0.55,2, "Bar brightness = 30% outer ring", fontsize=5, rotation=0, color='k') #plt.text(-0.05,0.65, "Nphotons = 1E08", fontsize=5, rotation=90, color='k') #plt.text(-0.05,0.09, "Nphotons = 1E07", fontsize=5, rotation=90, color='k') plt.axis("off") for i in range(x): for j in range(y): dispim = np.power(estimlist[ctr],PWR) dispim = dispim[345:490,375:520] #145 estimmax = np.power(322.5,PWR) #origin set in top-left corner a = plt.axes(fig.axes(i+1,j+1)) plt.text(0.1,6, "%s" %(CAPTION[i]), fontsize=5, rotation=0, color='w') #plt.text(0.1,13, "%.0E" %(Nphotons[j]), fontsize=5, rotation=0, color='w') #plt.text(0.1, 20, "i = %d, j = %d"%(i,j), fontsize=5, rotation=0, color='y') #plt.text(0.1, 25, "ctr = %d"%(ctr), fontsize=5, rotation=0, color='y') p = plt.imshow(dispim,vmax = estimmax,vmin=0,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default ctr += 1 plt.savefig(LOC+estim_plot, dpi=150) plt.close()
def __axes_spmap(self): for x in xrange(self.nh): for y in xrange(self.nv): w = self.horizontal_subplot_size h = self.vertical_subplot_size l = 1.0 - self.right_margin - w * ( x + 1) + 0.5 * self.horizontal_space b = self.bottom_margin + self.ylabel_area + h * y + 0.5 * self.vertical_space axes = pl.axes( [l, b, w - self.horizontal_space, h - self.vertical_space]) axes.cla() if self.showaxislabel and y == 0 and x == self.nh - 1: casalog.post('label "{label}" unit "{unit}"'.format( label=self.spectral_label, unit=self.spectral_unit), priority='DEBUG') if self.spectral_unit is not None and len( self.spectral_unit) > 0: spectral_label = '%s [%s]' % (self.spectral_label, self.spectral_unit) else: spectral_label = self.spectral_label axes.xaxis.set_label_text(spectral_label, size=self.ticksize) if self.normalization_factor < 100 and self.normalization_factor > 0.01: label_text = 'Intensity [%s]' % self.brightnessunit else: label_text = 'Intensity [1e%d x %s]' % ( int(numpy.log10(self.normalization_factor)), self.brightnessunit) axes.yaxis.set_label_text(label_text, size=self.ticksize, rotation='vertical') if self.showtick: axes.xaxis.tick_bottom() axes.yaxis.tick_left() if self.showticklabel: xlocator = pl.AutoLocator() xlocator.set_params(nbins=6, prune='upper') axes.xaxis.set_major_locator(xlocator) ylocator = pl.AutoLocator() ylocator.set_params(nbins=4) axes.yaxis.set_major_locator(ylocator) xformatter = pl.ScalarFormatter(useOffset=False) axes.xaxis.set_major_formatter(xformatter) axes.xaxis.set_tick_params( labelsize=max(self.ticksize - 1, 1)) axes.yaxis.set_tick_params( labelsize=max(self.ticksize - 1, 1)) if y != 0 or x != self.nh - 1: axes.xaxis.set_major_formatter(pl.NullFormatter()) axes.yaxis.set_major_formatter(pl.NullFormatter()) else: axes.xaxis.set_major_formatter(pl.NullFormatter()) axes.yaxis.set_major_formatter(pl.NullFormatter()) else: axes.yaxis.set_major_locator(pl.NullLocator()) axes.xaxis.set_major_locator(pl.NullLocator()) yield axes
def _fill_table(self, ax, header, stats): self._set_crosshair(stats["period"], stats["dm"]) ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) ra = radec_to_str(float(header.find("src_raj").text)) dec = radec_to_str(float(header.find("src_dej").text)) info = (("R.A.", ra), ("Decl.", dec), ("P0", stats["period"]), ("Opt P0", stats["opt_period"]), ("DM", "%.2f" % stats["dm"]), ("Acc", stats["acc"]), ("Harmonic", stats["nh"]), ("Spec S/N", "%.1f" % stats["snr"]), ("Fold S/N", "%.1f" % stats["folded_snr"]), ("Adjacent?", bool(stats["is_adjacent"])), ("Physical?", bool(stats["is_physical"])), ("DDM ratio 1", stats["ddm_count_ratio"]), ("DDM ratio 2", stats["ddm_snr_ratio"]), ("Nassoc", stats["nassoc"])) cell_text = [(val[0], val[1]) for val in info] tab = ax.table(cellText=cell_text, cellLoc="left", colLoc='left', loc="center") tprops = tab.properties() leftcol = [val[0] for val in info] for cell in tprops["child_artists"]: if cell.get_text().get_text() in leftcol: cell.set_width(0.4) else: cell.set_width(0.5) cell.set_linewidth(0) tab.scale(1.0, 2.0) tab.set_fontsize(30)
def PlotOutput(pup,ff): x = len(BAR_BRIGHTNESS) y = len(Nphotons) frameW = 1.5 frameH = 1.5 gapw = 0.05*np.ones(x+1) gapw[0] = 0.2 gaph = 0.05*np.ones(y+1) gaph[2] = 0.2 fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) estimlist, estimmaxlist,estimminlist = grab_files(pup,ff) ctr = 0 plt.text(0.03,1.06, "no bar", fontsize=10, rotation=0, color='k') plt.text(0.32,1.06, "30% ring brightness", fontsize=10, rotation=0, color='k') plt.text(0.76,1.06, "equal brightness", fontsize=10, rotation=0, color='k') plt.text(-0.155,0.85, "$10^7$ photons", fontsize=10, rotation=90, color='k') plt.text(-0.155,0.3, "$10^8$ photons", fontsize=10, rotation=90, color='k') plt.axis("off") for i in range(x): for j in range(y): dispim = np.power(estimlist[ctr],PWR) dispim = dispim[36:46,36:46] estimmax = np.power(estimmaxlist[ctr],PWR) #origin set in top-left corner a = plt.axes(fig.axes(i+1,j+1)) #plt.text(0.1,6, "brightness = %.1f" %(BAR_BRIGHTNESS[i]), fontsize=5, rotation=0, color='w') #plt.text(0.1,13, "%.0E" %(Nphotons[j]), fontsize=5, rotation=0, color='w') #plt.text(0.1, 20, "i = %d, j = %d"%(i,j), fontsize=5, rotation=0, color='y') #plt.text(0.1, 25, "ctr = %d"%(ctr), fontsize=5, rotation=0, color='y') p = plt.imshow(dispim,vmax = estimmax,vmin=0,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default ctr += 1 plt.savefig(LOC+estim_plot%(pup,ff), dpi=150) plt.close()
def PlotOutput(pup,opd,ff,phot,no): x = len(LENGTH) y = len(CONTRAST) frameW = 1.5 frameH = 1.5 gapw = 0.05*np.ones(x+1) gapw[0] = 0.30 gaph = 0.05*np.ones(y+1) #gaph[0] = 0.30 gaph[4] = 0.30 fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) plt.text(-0.1,1.09, "L = 1.0 pix", fontsize=14, rotation=0, color='k') plt.text(0.11,1.09, "L = 1.5 pix", fontsize=14, rotation=0, color='k') plt.text(0.32,1.09, "L = 2.0 pix", fontsize=14, rotation=0, color='k') plt.text(0.53,1.09, "L = 2.5 pix", fontsize=14, rotation=0, color='k') plt.text(0.74,1.09, "L = 3.0 pix", fontsize=14, rotation=0, color='k') plt.text(0.95,1.09, "L = 4.0 pix", fontsize=14, rotation=0, color='k') plt.text(-0.152,1, "C = 5 mag", fontsize=14, rotation=90, color='k') plt.text(-0.152,0.7, "C = 4 mag", fontsize=14, rotation=90, color='k') plt.text(-0.152,0.4, "C = 3 mag", fontsize=14, rotation=90, color='k') plt.text(-0.152,0.1, "C = 2 mag", fontsize=14, rotation=90, color='k') estimlist, estimmaxlist,estimminlist,metricnumlist = grab_files(pup,opd,ff,phot,no) plt.axis("off") ctr = 0 for i in range(x): for j in range(y): dispim = np.power(estimlist[ctr],PWR) dispim = dispim[37:44,37:44] estimmax = np.power(estimmaxlist[ctr],PWR) #origin set in top-left corner a = plt.axes(fig.axes(i+1,j+1)) #plt.text(0.1,6, "length = %.2f" %(LENGTH[i]), fontsize=5, rotation=0, color='w') #plt.text(0.1,13, "C = %.1f" %(CONTRAST[j]), fontsize=5, rotation=0, color='w') #plt.text(0,9, "M = %.2E"%(metricnumlist[ctr]), fontsize=5, rotation=0, color='w') p = plt.imshow(dispim,vmax = estimmax,vmin=0,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC+estim_plot%(no,pup,opd,ff*100,np.log10(phot)), dpi=150) plt.close()
def add_second_axis(ax, axis='x', tick='top', xtick=None, ytick=None, xlim=None, ylim=None, hide_tick_labels=''): """Adds a second axis with different units. """ if xtick == None: _xtick = [0.5, 1, 2.5, 5, 25] xtick = dict( value=1./numpy.asarray(_xtick), label=[r'%s$^{\circ}$' % (item) for item in _xtick] ) if ytick == None: ytick = xtick if xlim == None: xlim = ax.get_xlim() if ylim == None: ylim = ax.get_ylim() corners = ax.get_position().corners() position = [corners[0, 0], corners[0, 1], corners[2, 0]-corners[0, 0], corners[3, 1]-corners[0, 1]] aax = ax.figure.add_axes(position, xscale=ax.get_xscale(), yscale=ax.get_yscale(), frameon=False) tick = tick.split() if axis.find('x') >= 0: if 'top' in tick: aax.xaxis.tick_top() ax.xaxis.tick_bottom() if 'bottom' in tick: aax.xaxis.tick_bottom() ax.xaxis.tick_top() # aax.set_xlim(xlim) aax.set_xticks(xtick['value']) aax.set_xticklabels(xtick['label'], fontsize='x-small') else: aax.xaxis.set_major_locator(pylab.NullLocator()) if axis.find('y') >= 0: if 'left' in tick: aax.yaxis.tick_left() ax.yaxis.tick_right() if 'right' in tick: aax.yaxis.tick_right() ax.yaxis.tick_left() # aax.set_ylim(ylim) aax.set_yticks(ytick['value']) aax.set_yticklabels(ytick['label'], fontsize='x-small') else: aax.yaxis.set_major_locator(pylab.NullLocator()) if hide_tick_labels.find('x') >= 0: pylab.setp(aax.get_xticklabels(), visible=False) if hide_tick_labels.find('y') >= 0: pylab.setp(aax.get_yticklabels(), visible=False) return aax
def borderless_image(image, cmap="hot", fignum=100, filename=None): """Make a nice borderless image.""" plt.figure(fignum) plt.imshow(image, cmap=cmap) plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.show()
def PlotInput(): objectfiles, ob_max, imagefiles, image_max, SNRfiles, snr_max = grab_input( ) x = len(LENGTH) y = len(CONTRAST) INframeW = 0.95 INframeH = 0.95 INgapw = 0.05 * np.ones(x + 1) INgaph = 0.05 * np.ones(y + 1) INfig = FigArray(INframeW, INframeH, INgapw, INgaph) (W, H) = INfig.dimensions() plt.figure(1, figsize=(W, H)) ctr = 0 for i in range(0, x): for j in range(0, y): object = objectfiles[ctr] obmax = ob_max[ctr] obmax = np.power(obmax, PWR) dispobj = np.power(object, PWR) #dispobj = dispobj[410:479,410:479] dispobj = dispobj[37:44, 37:44] a = plt.axes(INfig.axes(i + 1, j + 1)) plt.text(-0.4, 0.5, "L = %.2f pix" % (LENGTH[i]), fontsize=7, rotation=0, color='y') plt.text(-0.4, -0.3, "C = %.1f mag" % (CONTRAST[j]), fontsize=7, rotation=0, color='y') p = plt.imshow(dispobj, vmax=CLP * obmax, vmin=0, cmap='hot', interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC + OBJECT_PLOT, dpi=150)
def PlotIm(L, C): image_files, image_max = get_image(L, C) x = len(Nphotons) y = len(PUPILS) INframeW = 0.95 INframeH = 0.95 INgapw = 0.05 * np.ones(x + 1) INgaph = 0.05 * np.ones(y + 1) INfig = FigArray(INframeW, INframeH, INgapw, INgaph) (W, H) = INfig.dimensions() plt.figure(1, figsize=(W, H)) ctr = 0 for i in range(0, x): for j in range(0, y): image = image_files[ctr] imagemax = image_max[ctr] dispim = np.power(image, PWR) dispim = dispim[36:45, 36:45] a = plt.axes(INfig.axes(i + 1, j + 1)) plt.text(-0.3, 0.5, "%s" % (PUPILS[j]), fontsize=5, rotation=0, color='y') plt.text(-0.3, -0.3, "Nphot = %.0E" % (Nphotons[i]), fontsize=5, rotation=0, color='y') p = plt.imshow(dispim, cmap='hot', interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC + IMAGE_PLOT % (L, C), dpi=150) plt.close()
def plot_harris_points(image,filtered_coords): pylab.figure() pylab.gray() pylab.imshow(image) pylab.plot([p[1] for p in filtered_coords],[p[0] for p in filtered_coords],"*", color="r") pylab.axis("off") pylab.gca().set_axis_off() pylab.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) pylab.margins(0, 0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) pylab.savefig("_1.jpg", bbox_inches='tight', pad_inches=0,dpi=300) pylab.show()
def colorbar(cmin, cmax): """ Create a color bar using the RGB mapping of this module """ E_level_axes = py.gca() cbar_axes, cbar_kw = matplotlib.colorbar.make_axes(E_level_axes) cbar_axes.set_ylim(cmin, cmax) colorwedge = [] crange = 50 for j in range(crange): y = cmin + (j / float(crange)) * (cmax - cmin) color = floatRgb(y, cmin, cmax) colorline = [] for i in range(10): colorline.append(color) colorwedge.append(colorline) wedge_image = py.array(colorwedge, float) A = 30. / (cmax - cmin) logger.debug("colorbar: aspect=%f", A) py.imshow(wedge_image, origin='lower', extent=(-1., 1., cmin, cmax), aspect=A) cbar_axes.xaxis.set_major_locator(py.NullLocator()) cbar_axes.yaxis.tick_right()
def PlotOutput(pup,opd,ff): x = len(LENGTH) y = len(CONTRAST) frameW = 0.95 frameH = 0.95 gapw = 0.05*np.ones(x+1) gaph = 0.05*np.ones(y+1) fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) newobjlist,newobjmaxlist,newobjminlist = grab_files(pup,opd,ff) ctr = 0 for i in range(x): for j in range(y): dispim = np.power(newobjlist[ctr],PWR) dispim = dispim[35:46,35:46] objmax = np.power(newobjmaxlist[ctr],PWR) objmin = np.power(newobjminlist[ctr],PWR) #origin set in top-left corner a = plt.axes(fig.axes(i+1,j+1)) plt.text(0,1, "L = %.2f NIRISS Pixels" %(LENGTH[i]), fontsize=5, rotation=0, color='w') plt.text(0,0, "C = %.1f mag" %(CONTRAST[j]), fontsize=5, rotation=0, color='w') p = plt.imshow(dispim,vmax = objmax,vmin=objmin,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC+newobj_plot%(pup,opd,ff), dpi=150) plt.close()
def main(): A = pl.imread(IMAGE_FILE) # full pca sk_pca = PCA() sk_pca.fit(A) # create scree plot expl_var = pd.DataFrame(sk_pca.explained_variance_ratio_[:20], columns=['pct_expl_var']) expl_var['index'] = range(len(expl_var)) g = (ggplot(expl_var, aes('index', 'pct_expl_var')) + geom_point() + geom_line() + ggtitle('image scree plot')) ggsave(g, 'scree.jpg') i = 1 pc_values = (1, 5, 10, 20, 30, 40) # draw approximated images for num_pcs in pc_values: # perform (truncated) pca egvecs, proj, egvals = pca(A, num_pcs) # reconstruct image A_rec = np.dot(egvecs, proj).T + np.mean(A, axis=0) # create subplot ax = pl.subplot(2, 3, i, frame_on=False) ax.xaxis.set_major_locator(pl.NullLocator()) ax.yaxis.set_major_locator(pl.NullLocator()) # draw pl.imshow(A_rec) pl.title("{} pc's".format(num_pcs)) pl.gray() i += 1 pl.show()
def fits_to_png(ff, outfile, log=False): plt.clf() ax = plt.axes() fim = ff[1].data # replace NaN values with zero for display fim[np.isnan(fim)] = 0.0 # set contrast to something reasonable transform = AsinhStretch() + PercentileInterval(99.5) bfim = transform(fim) ax.imshow(bfim, cmap="gray", origin="lower") circle = plt.Circle((np.shape(fim)[0] / 2 - 1, np.shape(fim)[1] / 2 - 1), 15, color='r', fill=False) ax.add_artist(circle) plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.savefig(outfile, bbox_inches='tight', pad_inches=0)
def PlotOutput(): x = len(PUPILS) y = len(FLAT_FIELD_ERROR) frameW = 1.5 frameH = 1 gapw = 0.1 * np.ones(x + 1) #gapw[0] = 0.2 gaph = 0.1 * np.ones(y + 1) #gaph[4] = 0.2 fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) estimlist = grab_files() ctr = 0 plt.axis("off") for i in range(x): for j in range(y): #origin set in top-left corner a = plt.axes(fig.axes(i + 1, j + 1)) dispim = estimlist[ctr] p = plt.imshow(dispim) a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default ctr += 1 plt.savefig(LOC + figure, dpi=150) plt.close()
def test(testdir='testdata/'): import pylab as plt from matplotlib.pyplot import savefig harmony = harmony_protect() files = file_name(testdir) for i, file in enumerate(files): print(i, file) img = Image.open(file).convert('RGB') ret, hp = harmony.classify_imgpil(img, True) imgblur_general = harmony.general_harmony(img) w, h = img.size ratio = w / h plt.figure(figsize=(9, 4 / ratio)) plt.subplot(1, 3, 1) plt.imshow(img) plt.title('Origin', fontsize=8) plt.axis('off') plt.subplot(1, 3, 2) plt.imshow(img) plt.imshow(hp, alpha=.75) plt.title('Activation', fontsize=8) plt.axis('off') plt.subplot(1, 3, 3) plt.imshow(imgblur_general) plt.title('general', fontsize=8) plt.axis('off') plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0.05, wspace=0.05) plt.margins(0, 0) plt.savefig('results/' + str(i) + '_anti_deepnude.jpg', dpi=160) plt.close()
def graph_spectrogram(mediaFile, tmp_dir, chunk_size, ffmpeg_bin, spectrogramHeight, spectrogram_color_map): def extract_wav(mediaFile, tmp_dir): """ extract wav from media file """ wavTmpPath = "{tmp_dir}{sep}{mediaBaseName}.wav".format( tmp_dir=tmp_dir, sep=os.sep, mediaBaseName=os.path.basename(mediaFile)) if os.path.isfile(wavTmpPath): return wavTmpPath else: p = subprocess.Popen( '"{ffmpeg_bin}" -i "{mediaFile}" -y -ac 1 -vn "{wavTmpPath}"'. format(ffmpeg_bin=ffmpeg_bin, mediaFile=mediaFile, wavTmpPath=wavTmpPath), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, error = p.communicate() out, error = out.decode("utf-8"), error.decode("utf-8") if "does not contain any stream" not in error: return wavTmpPath else: return "" def get_wav_info(wav_file): """ fetch information from wav file Args: wav_file (str): path of wav file Returns: : info on sound int: frame_rate """ wav = wave.open(wav_file, "r") frames = wav.readframes(-1) sound_info = pylab.fromstring(frames, "Int16") frame_rate = wav.getframerate() wav.close() return sound_info, frame_rate if QT_VERSION_STR[0] == "4": matplotlib.use("Qt4Agg") else: matplotlib.use("Qt5Agg") import pylab # do not move. It is important that this line is after the previous one fileName1stChunk = "" mediaBaseName = os.path.basename(mediaFile) wav_file = extract_wav(mediaFile, tmp_dir) if not wav_file: return None sound_info, frame_rate = get_wav_info(wav_file) wav_length = round(len(sound_info) / frame_rate, 3) i = 0 while True: chunkFileName = "{}.{}-{}.{}.{}.spectrogram.png".format( wav_file, i, i + chunk_size, spectrogram_color_map, spectrogramHeight) if not os.path.isfile(chunkFileName): sound_info_slice = sound_info[i * frame_rate:(i + chunk_size) * frame_rate] # complete bitmat spectrogram chunk if shorter than chunk length if len(sound_info_slice) / frame_rate < chunk_size: concat = np.zeros( int((chunk_size - len(sound_info_slice) / frame_rate) + 1) * frame_rate) sound_info_slice = np.concatenate((sound_info_slice, concat)) pylab.figure(num=None, dpi=100, figsize=(int(len(sound_info_slice) / frame_rate), round(spectrogramHeight / 80))) pylab.gca().set_axis_off() pylab.margins(0, 0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) try: pylab.specgram( sound_info_slice, Fs=frame_rate, cmap=matplotlib.pyplot.get_cmap(spectrogram_color_map), scale_by_freq=False) except ValueError: # color_map gray_r is available on all version of matplotlib pylab.specgram(sound_info_slice, Fs=frame_rate, cmap=matplotlib.pyplot.get_cmap("gray_r"), scale_by_freq=False) pylab.savefig(chunkFileName, bbox_inches="tight", pad_inches=0) pylab.clf() pylab.close() if not fileName1stChunk: fileName1stChunk = chunkFileName i += chunk_size if i >= wav_length: break return fileName1stChunk
def PlotPSF(): psf_files, psf_max, SR_list = get_psf() x = len(PUPILS) y = len(OP_PATH_DIFF) INframeW = 1.5 INframeH = 1.5 INgapw = 0.05 * np.ones(x + 1) #INgapw[0] = 0.2 INgaph = 0.05 * np.ones(y + 1) #INgaph[3] = 0.2 INfig = FigArray(INframeW, INframeH, INgapw, INgaph) (W, H) = INfig.dimensions() plt.figure(1, figsize=(W, H)) ctr = 0 for i in range(0, x): for j in range(0, y): psf = psf_files[ctr] psfmax = psf_max[ctr] SR = SR_list[ctr] psfmax = psfmax disp_psf = psf disp_psf = np.power(psf, PWR) #disp_psf = disp_psf[30:55,30:55] a = plt.axes(INfig.axes(i + 1, y - j)) if SR == None: plt.text(0, 45, "%s" % (PUPILS[i]), fontsize=6, rotation=0, color='w') else: plt.text(0, 7.5, "SR = %.2f" % (SR), fontsize=6, rotation=0, color='w') plt.text(0, 3, "OPD = %s" % (OP_PATH_DIFF[j]), fontsize=6, rotation=0, color='w') p = plt.imshow(disp_psf, cmap='hot', interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC + PSF_PLOT, dpi=150)
def PlotOutput(ob,off,pup,NL,C): frameW = 0.95 frameH = 0.95 gapw = 0.05*np.ones(N+1) gaph = 0.05*np.ones(N+1) fig = FigArray(frameW, frameH, gapw, gaph) (W, H) = fig.dimensions() plt.figure(1, figsize=(W, H)) estimfiles,estimmaxlist,residfiles,residmaxlist = grab_files(ob,off,pup,NL,C) ctr = 0 for i in range(N): for j in range(N): dispim = np.power(estimfiles[ctr],PWR) dispim = dispim[35:45,35:45] estimmax = np.power(estimmaxlist[ctr],PWR) #origin set in top-left corner a = plt.axes(fig.axes(i+1,N - j)) #values of SCALES and DELTAS plt.text(0,1, "$s = %.2E}$" %(scales[i]), fontsize=6, rotation=0, color='w') plt.text(0, 0, "$d = %.2f$" %(deltas[j]), fontsize=6, rotation=0, color='w') p = plt.imshow(dispim,vmax = CLP*estimmax,vmin=0,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC+estim_plot%(pup,ob,off,NL,C), dpi=150) ctr = 0 for i in range(N): for j in range(N): dispim = residfiles[ctr] dispim = dispim[35:45,35:45] residmax = residmaxlist[ctr] #origin set in top-left corner a = plt.axes(fig.axes(i+1,N - j)) #values of SCALES and DELTAS plt.text(0,1, "$s = %.2E}$" %(scales[i]), fontsize=6, rotation=0, color='w') plt.text(0, 0, "$d = %.2f$" %(deltas[j]), fontsize=6, rotation=0, color='w') p = plt.imshow(dispim,vmax = residmax,vmin = 0,cmap = 'gist_heat',interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC+resid_plot%(pup,ob,off,NL,C), dpi=150)
locator.set_bounds(zmin, zmax) levs = locator() #levs=10 #levs=N.linspace(zmin,zmax,10) #levs=N.concatenate((levs,[3000])) ax2 = pylab.subplot(1, 2, 2) #print 'hi' #mycontour=pylab.contourf(x,y,z,levs)#, mycontour = ax2.pcolormesh(x, y, z) cmap = pylab.cm.RdBu_r #cmap = pylab.cm.PiYG mycontour.set_cmap(cmap) pylab.axhline(y=220, color='white', linewidth=3.2) pylab.xlabel(r'$2\theta$', fontsize=14) #pylab.ylabel('T (K) ') #levs.set_bounds(zmin, zmax) #mycontour=pylab.contourf(x,y,z,35,extent=(17,19.6,y.min(),y.max()))#,cmap=pylab.cm.jet) #pylab.axis('equal') #pylab.pcolor(qx,qz,counts) #mycontour.set_clim(vmin=160, vmax=500) mycbar = pylab.colorbar() #mycbar.set_clim(vmin=160, vmax=500) ax2.text(.1, .9, '(b)', fontsize=20, transform=ax2.transAxes) pylab.xlim((43.5, 46.5)) pylab.ylim((195, 250)) ax2.yaxis.set_major_formatter(pylab.NullFormatter()) ax2.yaxis.set_major_locator(pylab.NullLocator()) pylab.show()
def TIF_to_jpg(fnameTiff, overwrite=False, saveAs=""): """ given a TIF taken by our cameras, make it a pretty labeled JPG. if the filename contains "f10" or "f20", add appropraite scale bars. automatic contrast adjustment is different depending on if its a DIC image or fluorescent image (which is detected automatically). """ if saveAs == "": saveAs = fnameTiff + ".jpg" if overwrite is False and os.path.exists(saveAs): print("file exists, not overwriting...") return # load the image img = pylab.imread(fnameTiff) img = img / np.max(img) # now the data is from 0 to 1 # determine the old histogram hist1, bins1 = np.histogram(img.ravel(), bins=256, range=(0, 1)) #pylab.plot(bins[:-1],hist) # detect darkfield by average: if np.average(img) < .2: vmin = None vmax = None msg = " | FLU" while np.average(img) < .5: img = np.sqrt(img) msg += "^(.5)" else: msg = " | DIC" percentile = .005 vmin = np.percentile(img.ravel(), percentile) vmax = np.percentile(img.ravel(), 100 - percentile) # determine the new histogram hist2, bins2 = np.histogram(img.ravel(), bins=256, range=(0, 1)) # plot it with resizing magic fig = pylab.figure(facecolor='r') fig.gca().imshow(img, cmap=pylab.gray(), vmin=vmin, vmax=vmax) pylab.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) pylab.gca().xaxis.set_major_locator(pylab.NullLocator()) pylab.gca().yaxis.set_major_locator(pylab.NullLocator()) pylab.axis('off') # resize it to the original size fig.set_size_inches(img.shape[1] / 100, img.shape[0] / 100) # add text msg = "%s | %s" % (os.path.basename(fnameTiff), datetime.datetime.fromtimestamp( os.path.getmtime(fnameTiff))) + msg center = 10 pylab.text(center, center, "%s" % (msg), va="top", color='w', size='small', family='monospace', weight='bold', bbox=dict(facecolor='k', alpha=.5)) # add scale bar scaleWidthPx = False if "f10" in fnameTiff: scaleWidthPx, scaleBarText = 39, "25 um" if "f20" in fnameTiff: scaleWidthPx, scaleBarText = 31, "10 um" if scaleWidthPx: scaleBarPadding = 10 x2, y2 = img.shape[1] - scaleBarPadding, img.shape[0] - scaleBarPadding x1, y1 = x2 - scaleWidthPx, y2 for offset, color, alpha in [[2, 'k', .5], [0, 'w', 1]]: pylab.plot([x1 + offset, x2 + offset], [y1 + offset, y2 + offset], '-', color=color, lw=4, alpha=alpha) pylab.text((x1 + x2) / 2 + offset, y1 - 5 + offset, scaleBarText, color=color, ha="center", weight="bold", alpha=alpha, size="small", va="bottom", family="monospace") # add histogram #pylab.plot(img.shape[1]-bins1[:-1][::-1]*200,-hist1/max(hist1)*100+110,color='g') #pylab.plot(img.shape[1]-bins2[:-1][::-1]*200,-hist2/max(hist2)*100+110,color='b') #pylab.show() # save it pylab.savefig(saveAs, dpi=100) # clean up pylab.close()
evt.append(data_x[counter]) titles.append('x view') if data_u is not None: evt.append(data_u[counter]) titles.append('u view') if data_v is not None: evt.append(data_v[counter]) titles.append('v view') fig = pylab.figure(figsize=(9, 3)) gs = pylab.GridSpec(1, len(evt)) # print np.where(evt == np.max(evt)) # print np.max(evt) for i in range(len(evt)): ax = pylab.subplot(gs[i]) ax.axis('on') ax.xaxis.set_major_locator(pylab.NullLocator()) ax.yaxis.set_major_locator(pylab.NullLocator()) # images are normalized such the max e-dep has val 1, independent # of view, so set vmin, vmax here to keep matplotlib from # normalizing each view on its own minv = 0 cmap = 'jet' if have_times: minv = -1 cmap = 'bwr' im = ax.imshow(evt[i][0], cmap=pylab.get_cmap(cmap), interpolation='nearest', vmin=minv, vmax=1) cbar = pylab.colorbar(im, fraction=0.04)
bottom='off', left='off', right='off') ax1 = fig.add_subplot(311) pl.plot(f_list[np.argmax(chunk_corr[:, 0]), :], lw=1.5, c='k') for i in (pat1_start): pl.axvspan(i, i + width, facecolor='dodgerblue', alpha=0.3, linewidth=0) pl.xlim([0, plot_len]) ax1.xaxis.set_ticks_position('bottom') ax1.yaxis.set_ticks_position('left') ax1.spines['right'].set_color('none') ax1.spines['top'].set_color('none') #plt.yticks( np.arange(0, 1.1, 0.5) ) ax1.xaxis.set_major_locator(pl.NullLocator()) ax2 = fig.add_subplot(312) pl.plot(f_list[np.argmax(chunk_corr[:, 1]), :], lw=1.5, c='k') for i in (pat2_start): pl.axvspan(i, i + width, facecolor='orangered', alpha=0.3, linewidth=0) pl.xlim([0, plot_len]) ax2.xaxis.set_ticks_position('bottom') ax2.yaxis.set_ticks_position('left') ax2.spines['right'].set_color('none') ax2.spines['top'].set_color('none') #plt.yticks( np.arange(0, 1.1, 0.5) ) ax2.xaxis.set_major_locator(pl.NullLocator())
def HR_radius(): # solar temperature T_sun = 5777. # temperature plotting range Tmin = 2000 Tmax = 60000 # luminosity plotting range Lmin = 1.e-4 Lmax = 1.e6 # draw radius lines? (1 = yes, 0 = no) draw_radii = 1 # draw the WD region? draw_WDs = 1 # label the stars by mass? label_masses = 1 #------------------------------------------------------------------------- # main sequence data taken from Carroll & Ostlie, Appendix G nstars = 11 M = numpy.zeros(nstars, numpy.float64) T = numpy.zeros(nstars, numpy.float64) R = numpy.zeros(nstars, numpy.float64) L = numpy.zeros(nstars, numpy.float64) # spectral type spectralTypes = [ 'O8', 'B0', 'B3', 'B5', 'A0', 'A5', 'F5', 'Sun', 'K5', 'M0', 'M5' ] # mass (solar masses) M[:] = [23, 17.5, 7.6, 5.9, 2.9, 1.8, 1.2, 1, 0.67, 0.51, 0.21] # temperature (K) T[:] = [ 35800, 32500, 18800, 15200, 9800, 8190, 6650, T_sun, 4410, 3840, 3170 ] # radius (solar radii) R[:] = [10.0, 6.7, 3.8, 3.2, 2.2, 1.8, 1.2, 1.0, 0.80, 0.63, 0.29] # luminosity (solar luminosities) L[:] = [ 147000, 32500, 1580, 480, 39.4, 12.3, 2.56, 1.0, 0.216, 0.077, 0.0076 ] #------------------------------------------------------------------------- ax = pylab.subplot(111) ax.set_xscale('log') ax.set_yscale('log') # draw and label the main sequence pylab.scatter(T, L, s=100, marker="+", color="r", lw=2) pylab.plot(T, L, 'b-') n = 0 while (n < len(spectralTypes)): if (label_masses): if (M[n] >= 1.0): pylab.text(1.05 * T[n], L[n], "%4.1f $M_\odot$" % (M[n]), fontsize=10, horizontalalignment="right", verticalalignment="center", color="r") else: pylab.text(1.05 * T[n], L[n], "%3.2f $M_\odot$" % (M[n]), fontsize=10, horizontalalignment="right", verticalalignment="center", color="r") pylab.text(0.9 * T[n], L[n], spectralTypes[n]) n += 1 if (draw_radii): # draw in lines of constant radius Rvals = [0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000, 10000] nTpts = 25 dlogT = (math.log10(Tmax) - math.log10(Tmin)) / (nTpts - 1) Tplot = 10.0**(numpy.arange(nTpts) * dlogT + math.log10(Tmin)) n = 0 while (n < len(Rvals)): # L/L_sun = (R/R_sun)**2 (T/T_sun)**4 # compute L in L_sun units L = Rvals[n]**2 * (Tplot / T_sun)**4 pylab.plot(Tplot, L, linestyle='--', color="0.5") # draw in labels -- here we space the T position of the labels equally # in log, by empericallly picking T = 40000 for L = 1.e-4 and # T = 3000 for L = 1.e4, and doing a line in log-space slope = (math.log10(40000) - math.log10(3000)) / (math.log10(1.e-4) - math.log10(1.e4)) xpos = math.log10(40000) + slope * (math.log10(Rvals[n]) - math.log10(1.e-4)) xpos = 10.0**xpos ypos = Rvals[n]**2 * (xpos / T_sun)**4 if (xpos > Tmin and xpos < Tmax and ypos > Lmin and ypos < Lmax): pylab.text(xpos, ypos, "%g $R_\odot$" % (Rvals[n]), color="0.5") n += 1 if (draw_WDs): # draw a box along the R = 0.01 R_sun line to indicate the approximate # position of the white dwarfs L3 = 0.01**2 * (30000. / T_sun)**4 L75 = 0.01**2 * (7500. / T_sun)**4 pylab.fill([30000, 30000, 7500, 7500], [1.5 * L3, 0.66 * L3, 0.66 * L75, 1.5 * L75], alpha=0.20, facecolor="b") L15 = 0.01**2 * (15000. / T_sun)**4 pylab.text(15000, L15, "white dwarfs", color="b", horizontalalignment="center") # draw x-axis (temperature) labels in a few spots Tplot = [40000, 20000, 10000, 5000, 2500] Tlabels = [] n = 0 while (n < len(Tplot)): Tlabels.append("%5.0f" % (Tplot[n])) n += 1 locs, labels = pylab.xticks(Tplot, Tlabels) # reverse the x-axis pylab.axis([Tmin, Tmax, Lmin, Lmax]) ax = pylab.gca() ax.set_xlim(ax.get_xlim()[::-1]) # turn off minor ticks minorLocator = pylab.NullLocator() ax.xaxis.set_minor_locator(minorLocator) pylab.xlabel("$T$ (K)") pylab.ylabel(r"$L/L_\odot$") pylab.subplots_adjust(left=0.125, right=0.95, bottom=0.1, top=0.95) f = pylab.gcf() f.set_size_inches(6.0, 7.0) pylab.savefig("HR_radius.png")
def PlotStuff(): files_list, max_list = get_stuff() x = 2 y = 3 INframeW = 1.5 INframeH = 1.5 INgapw = 0.05 * np.ones(x + 1) INgapw[0] = 0.2 INgaph = 0.05 * np.ones(y + 1) INgaph[3] = 0.2 INfig = FigArray(INframeW, INframeH, INgapw, INgaph) (W, H) = INfig.dimensions() plt.figure(1, figsize=(W, H)) plt.text(-0.08, 1.085, "L = 1 pix, C = 5 mag", fontsize=10, rotation=0, color='k') plt.text(0.53, 1.085, "L = 4 pix, C = 2 mag", fontsize=10, rotation=0, color='k') plt.text(-0.15, 1.04, "detector scale model", fontsize=9, rotation=90, color='k') plt.text(-0.15, 0.65, "NIRISS sim observation", fontsize=9, rotation=90, color='k') plt.text(-0.15, 0.25, "NIRCam sim observation", fontsize=9, rotation=90, color='k') plt.axis('off') ctr = 0 for i in range(0, x): for j in range(0, y): disp = files_list[ctr] disp = np.power(disp, PWR) #disp = disp_psf[30:55,30:55] dispmax = max_list[ctr] dispmax = np.power(dispmax, PWR) a = plt.axes(INfig.axes(i + 1, j + 1)) #plt.text(0,1, '%d' %(ctr), fontsize=6, rotation=0, color='w') p = plt.imshow(disp, vmax=dispmax, vmin=0, cmap='hot', interpolation='nearest') a.xaxis.set_major_locator(plt.NullLocator()) a.yaxis.set_major_locator(plt.NullLocator()) plt.gray() # overrides current and sets default plt.axis("off") ctr += 1 plt.savefig(LOC + STUFF_PLOT, dpi=150)
def plot_erps(erps, data=None, ax=None, pre=0.2, post=None, pre_onset=None, xlabel='time (s)', ylabel='$\mu V$', ylim=None, ymult=1.0, legend=None, xlformat='%4g', ylformat='%4g', loffset=10, alinewidth=2, **kwargs): """Plot multiple ERPs on a new figure. Parameters ---------- erps : list of tuples List of definitions of ERPs. Each tuple should consist of (label, color, onsets) or a dictionary which defines, label, color, onsets, data. Data provided in dictionary overrides 'common' data provided in the next argument `data` data Data for ERPs to be derived from 1D (samples) ax Where to draw (e.g. subplot instance). If None, new figure is created pre : float, optional Duration (seconds) to be plotted prior to onset pre_onset : None or float If data is already in epochs (2D) then pre_onset provides information on how many seconds pre-stimulus were used to generate them. If None, then pre_onset = pre post : None or float Duration (seconds) to be plotted after the onset. If any data is provided with onsets, it can't be None. If None -- plots all time points after onsets ymult : float, optional Multiplier for the values. E.g. if negative-up ERP plot is needed: provide ymult=-1.0 xlformat : str, optional Format of the x ticks ylformat : str, optional Format of the y ticks legend : None or string If not None, legend will be plotted with position argument provided in this argument loffset : int, optional Offset in voxels for axes and tick labels. Different matplotlib frontends might have different opinions, thus offset value might need to be tuned specifically per frontend alinewidth : int, optional Axis and ticks line width **kwargs Additional arguments provided to plot_erp() Examples -------- :: kwargs = {'SR' : eeg.SR, 'pre_mean' : 0.2} fig = plot_erps((('60db', 'b', eeg.erp_onsets['60db']), ('80db', 'r', eeg.erp_onsets['80db'])), data[:, eeg.sensor_mapping['Cz']], ax=fig.add_subplot(1,1,1,frame_on=False), pre=0.2, post=0.6, **kwargs) or :: fig = plot_erps((('60db', 'b', eeg.erp_onsets['60db']), {'color': 'r', 'onsets': eeg.erp_onsets['80db'], 'data' : data[:, eeg.sensor_mapping['Cz']]} ), data[:, eeg.sensor_mapping['Cz']], ax=fig.add_subplot(1,1,1,frame_on=False), pre=0.2, post=0.6, **kwargs) Returns ------- h current fig handler """ if ax is None: fig = pl.figure(facecolor='white') fig.clf() ax = fig.add_subplot(111, frame_on=False) else: fig = pl.gcf() # We don't want original axis being on ax.axison = True labels = [] for erp_def in erps: plot_data = data params = {'ymult' : ymult} # provide custom parameters per ERP if isinstance(erp_def, tuple) and len(erp_def) == 3: params.update( {'label': erp_def[0], 'color': erp_def[1], 'onsets': erp_def[2]}) elif isinstance(erp_def, dict): plot_data = erp_def.pop('data', None) params.update(erp_def) labels.append(params.get('label', '')) # absorb common parameters params.update(kwargs) if plot_data is None: raise ValueError, "Channel %s got no data provided" \ % params.get('label', 'UNKNOWN') plot_erp(plot_data, pre=pre, pre_onset=pre_onset, post=post, ax=ax, **params) # plot_kwargs={'label':label}) if isinstance(erp_def, dict): erp_def['data'] = plot_data # return it back props = dict(color='black', linewidth=alinewidth, markeredgewidth=alinewidth, zorder=1, offset=loffset) def set_limits(): """Helper to set x and y limits""" ax.set_xlim( (-pre, post) ) if ylim != None: ax.set_ylim(*ylim) set_limits() _make_centeredaxis(ax, 0, ai=0, label=xlabel, **props) set_limits() _make_centeredaxis(ax, 0, ai=1, mult=np.sign(ymult), label=ylabel, **props) ax.yaxis.set_major_locator(pl.NullLocator()) ax.xaxis.set_major_locator(pl.NullLocator()) # legend obscures plotting a bit... seems to be plotting # everything twice. Thus disabled by default if legend is not None and np.any(np.array(labels) != ''): pl.legend(labels, loc=legend) fig.canvas.draw() return fig
def Main(): options, _ = MakeOpts().parse_args(sys.argv) assert options.input_filename assert options.first_col and options.second_col print 'Reading species list from', options.input_filename # Read data r = csv.DictReader(open(options.input_filename)) first_col, second_col = options.first_col, options.second_col third_col = options.third_col second_col_key = options.second_col_key or second_col third_col_key = options.third_col_key or third_col filter_values = [] if options.filter_values: filter_values = set(map(str.strip, options.filter_values.split(','))) pairmap = {} all_a = set() all_b = set() all_vals = set() for row in r: a, b = row[first_col].strip(), row[second_col].strip() c = row[third_col].strip() if not a or not b or not c: continue all_a.add(a) all_b.add(b) value = MergeBinary(b, c, second_col_key, third_col_key) if filter_values and value in filter_values: continue all_vals.add(value) pairmap.setdefault(a, []).append(value) a_to_num = dict((v,i) for i,v in enumerate(all_a)) counts = {} for k, v in pairmap.iteritems(): counter = Counter(v) counts[k] = counter x_vals = [] count_array = [] for a_val in all_a: x_vals.append(a_to_num[a_val]) count_array.append(counts.get(a_val, {})) # Plot circle scatter. axes = pylab.axes() colormap = ColorMap(all_vals) y_loc, radius = 1.0, 0.45 PieArray(axes, x_vals, y_loc=y_loc, radius=radius, counts_array=count_array, colormap=colormap) title = options.title or '%s vs. %s' % (options.first_col, options.second_col) pylab.title(title) size_10 = FontProperties(size=10) a_labels = [a or "None given" for a in all_a] axes.yaxis.set_major_locator(pylab.NullLocator()) axes.xaxis.set_major_locator(pylab.NullLocator()) for x, label in enumerate(a_labels): axes.text(x, y_loc - radius - 0.1, str(label), ha='center', va='baseline') handles, labels = axes.get_legend_handles_labels() mapped_labels = dict(zip(labels, handles)) labels = sorted(mapped_labels.keys()) handles = [mapped_labels[k] for k in labels] pylab.legend(handles, labels) pylab.axis('scaled') pylab.axis([-1, len(all_a), 0.0, 2]) pylab.show()
def get_cnn_filters(self, plot=False): #function retrieving filters and plotting them and returning the arrays #initialising stuff saver = tf.train.Saver() init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) #initialise variables #restoring model from saved saver.restore(sess, self.model_path) out = {} out['spatial'] = {} out['spectral'] = {} out['spatial']['weights'] = {} out['spatial']['biases'] = {} out['spectral']['weights'] = {} out['spectral']['biases'] = {} out['spatial']['weights']['conv1'] = sess.graph.get_tensor_by_name( "spatial_conv1_w:0").eval() out['spatial']['weights']['conv2'] = sess.graph.get_tensor_by_name( "spatial_conv2_w:0").eval() out['spatial']['biases']['conv1'] = sess.graph.get_tensor_by_name( "spatial_conv1_b:0").eval() out['spatial']['biases']['conv2'] = sess.graph.get_tensor_by_name( "spatial_conv2_b:0").eval() out['spectral']['weights'][ 'conv1'] = sess.graph.get_tensor_by_name( "spectral_conv1_w:0").eval() out['spectral']['weights'][ 'conv2'] = sess.graph.get_tensor_by_name( "spectral_conv2_w:0").eval() out['spectral']['biases']['conv1'] = sess.graph.get_tensor_by_name( "spectral_conv1_b:0").eval() out['spectral']['biases']['conv2'] = sess.graph.get_tensor_by_name( "spectral_conv2_b:0").eval() if plot: for mode in out.keys(): for ntype in out[mode].keys(): if ntype is 'weights': for layer in out[mode][ntype].keys(): data = out[mode][ntype][layer] Ndata = np.shape(data) Nsub5 = np.around(Ndata[-1] / 5.0) pl.figure() pl.suptitle('{0} {1} {2}'.format( mode, ntype, layer)) for i in range(Ndata[-1]): ax = pl.subplot(5, Nsub5, i + 1) ax.imshow(data[:, :, 0, i], interpolation='nearest', origin='upper') ax.xaxis.set_major_locator(pl.NullLocator()) ax.yaxis.set_major_locator(pl.NullLocator()) return out
""" ax = panel_factory.new_panel(0, 0, 'A', label_position='leftleft') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.yaxis.set_ticks_position("left") ax.xaxis.set_ticks_position("bottom") mask = create_vector_mask(M_base.structure, pops=['5E', '6E']) for ii, iteration in enumerate([1, 2, 3, 4, 5]): pl.plot(data[iteration]['parameters'], np.mean(data[iteration]['results'][:, mask, -1], axis=1), '.-', color=str(ii / 6.)) ax.set_yscale('Log') ax.yaxis.set_minor_locator(pl.NullLocator()) ax.set_yticks(10**np.arange(-1., 3., 1.)) ax.yaxis.set_label_coords(-0.13, 0.55) ax.set_ylabel(r'$\langle \nu_{\{\mathrm{5E,6E}\}} \rangle$') ax.set_xlabel(r'$\kappa$', labelpad=-0.1) ax.set_xlim((1., 1.23)) """ Panel B """ ax = panel_factory.new_panel(1, 0, 'B', label_position=-0.25) ax.yaxis.set_ticks_position('none') ax.xaxis.set_ticks_position('bottom') K_prime1_dict = matrix_to_dict(K_prime1, area_list,