def generate_barchart(video_captions_ranking, th2, similarity_or_distance='similarity'): """ """ num_sentences_discarded = [] for video_id in video_captions_ranking.keys(): if similarity_or_distance == 'similarity': num_sentences_discarded.append( len([ a[1] for a in video_captions_ranking[video_id] if a[1] < th2 ])) elif similarity_or_distance == 'distance': num_sentences_discarded.append( len([ a[1] for a in video_captions_ranking[video_id] if a[1] > th2 ])) plt.jet() lines = plt.plot(range(config.first_video, config.last_video), num_sentences_discarded) plt.setp(lines, linewidth=2, color='r') plt.xlabel('Training videos') plt.ylabel('Discarded sentences') # plt.title('Discarded sentences per video') plt.grid(True) # plt.show() plt.savefig(config.barchart_path) plt.close()
def baltimore_kde(data): def fkde(x): return abs(np.sum(kdeimmat[kdeimmat > x]) * .0005 ** 2 - 0.95) X, Y = makegrid(data) kdeimmat = np.zeros(X.shape) kernel = stats.gaussian_kde(data.T) for i in xrange(X.shape[0]): for j in xrange(X.shape[1]): kdeimmat[i, j] = kernel.evaluate(np.array([X[i, j], Y[i, j]])) plt.jet() plt.imshow(kdeimmat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('baltimore_kde.pdf') thresh = opt.fmin(fkde, 10)[0] bools = kdeimmat > thresh mat = np.zeros(X.shape) mat += bools plt.imshow(mat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('kdeavoid.pdf')
def test_pca_white(sh=(12, 12), m=500, eps=0.1, rc=(10, 10), out_dir="img"): # Visualize examples in r x c grid of pca whitened images. # Also show that the covariance matrix of whitening data # is a diagonal matrix with descending values x = test_pca_input(sh, m) pca = PCA(x) x_white, mean = pca.whiten_pca(x, eps=eps) rows, cols = rc f, axes = plt.subplots(rows, cols, sharex='col', sharey='row') plt.subplots_adjust(hspace=0.1, wspace=0) plt.jet() for r in range(rows): for c in range(cols): axes[r][c].imshow(x_white[:, r*cols + c].reshape(sh)) axes[r][c].axis('off') path = os.path.join(out_dir, "pca_filters_{}_{}_{}.png".format(sh, m, eps)) print("saving {}...".format(path)) plt.savefig(path, bbox_inches='tight') cv = np.dot(x_white, x_white.T) plt.clf() plt.imshow(cv) plt.show()
def visualize_tsne(arrs): plt.figure(figsize=(20, 10)) plt.title("Original Dimension: ", arrs.shape[1]) plt.jet() embedded = TSNE(n_components=2).fit_transform(arrs) plt.scatter(embedded[:, 0], embedded[:, 1], c=y_test) print( plt.colorbar() visualize_tsne(representations[4]) ##### plt.show() # Sequential model API # Look at console for printed summary # model.get_config() -> Dictionary containing the configuration of the model # model.get_weights() -> Gets the weights of the model as numpy arrays # model.to_json() -> Only the architecture # model.to_yaml() -> Only the architecture also # model.save_weights('autoencoder1_weights.h5') # model.load_weights('autoencoder1_weights.h5', by_name=False) -> # load by name if using different architecture # model.layers # List of layers addedd to the model #
def demoCDIRECT(maxiter=25): """ Test and visualize cDIRECT on a 2D function. This will draw the contours of the target function, the final set of rectangles and mark the optimum with a red dot. """ import matplotlib.pyplot as plt def foo(x): """ Code for the Shekel function S5. The dimensionality of x is 2. The minimum is at [4.0, 4.0]. """ # return min(-.5, -sum(1./(dot(x-a, x-a)+c) for a, c in SHEKELPARAMS)) return sin(x[0] * 2) + abs(x[0] - 15) + sin(x[1]) + .2 * abs(x[1] - 6) # def foo(x): # # several local minima, global minimia is at bottom left # return 2.5 + sin((x[0]-.4)*8)+sin((x[1]+.5)*5) + .1* sum(sin(x[0]*50)) + .1* sum(sin(x[1]*50))+ x[0]*.1 - x[1] * .1 bounds = [(1.2, 28.), (0.1, 13.)] optv, optx = cdirect(foo, bounds, maxiter=maxiter) print('***** opt val =', optv) print('***** opt x =', optx) plt.figure(2) plt.clf() # plot rectangles c0 = [(i / 100.) * (bounds[0][1] - bounds[0][0]) + bounds[0][0] for i in range(101)] c1 = [(i / 100.) * (bounds[1][1] - bounds[1][0]) + bounds[1][0] for i in range(101)] z = array([[foo([i, j]) for i in c0] for j in c1]) ax = plt.subplot(111) B = [array([1.2, 0.1]), array([28., 13.])] for line in open('finalrecs.txt').readlines(): dat = line.strip().split(',') lb = array([double(x) for x in dat[0].split()]) * (B[1] - B[0]) + B[0] ub = array([double(x) for x in dat[1].split()]) * (B[1] - B[0]) + B[0] ax.add_artist( plt.Rectangle(lb, ub[0] - lb[0], ub[1] - lb[1], fc='y', ec='k', lw=1, alpha=0.25, fill=True)) ax.plot(optx[0], optx[1], 'ro') cs = ax.contour(c0, c1, z, 10) ax.clabel(cs) plt.jet() ax.set_xlim(bounds[0]) ax.set_ylim(bounds[1]) ax.set_xlabel('x[0]') ax.set_ylabel('x[1]') ax.set_title('final optimum')
def makeConfMat(estClasses, gtClasses, outFilename, numClasses = None, plotLabels = False): #If not defined, find number of unique numbers in gtClasses if numClasses == None: numClasses = len(np.unique(gtClasses)) #X axis is est, y axis is gt #First index is y, second is x confMat = np.zeros((numClasses, numClasses)) numInstances = len(estClasses) for (gtIdx, estIdx) in zip(gtClasses.astype(int), estClasses.astype(int)): confMat[gtIdx, estIdx] += 1 plt.jet() plt.matshow(confMat) plt.colorbar() plt.xlabel("Est class") plt.ylabel("True class") plt.title("Confusion matrix") ax = plt.gca() ax.xaxis.set_ticks_position('bottom') #Plot labels for each field if plotLabels: for i in range(numClasses): for j in range(numClasses): labelStr = generateStatString(confMat, i, j) #text receives x, y coord of plot ax.text(j, i, labelStr, fontweight='bold', horizontalalignment='center', verticalalignment='center', bbox={'facecolor':'white'}, fontsize=6) #plt.show() plt.savefig(outFilename)
def plot_matched_image(org_img_path, figures, nrows=1, ncols=1): """Plot a dictionary of figures. Parameters ---------- figures : <title, figure> dictionary ncols : number of columns of subplots wanted in the display nrows : number of rows of subplots wanted in the figure """ fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows + 1) # plot orignal one img_np = mpimg.imread(org_img_path) axeslist.ravel()[0].imshow(img_np, cmap=plt.jet()) axeslist.ravel()[0].set_title(org_img_path) axeslist.ravel()[0].set_axis_off() # plot the matched images for ind, title in zip(range(len(figures)), figures): img_file = os.path.join(IMAGE_PATH, figures[ind]) img_np = mpimg.imread(img_file) axeslist.ravel()[ind + 1].imshow(img_np, cmap=plt.jet()) axeslist.ravel()[ind + 1].set_title(title) axeslist.ravel()[ind + 1].set_axis_off() plt.tight_layout() # optional plt.show() return
def plotear(xi,yi,zi): # mask inner circle interior1 = sqrt(((xi+1.5)**2) + (yi**2)) < 1.0 interior2 = sqrt(((xi-1.5)**2) + (yi**2)) < 1.0 zi[interior1] = ma.masked zi[interior2] = ma.masked p.figure(figsize=(16,10)) pyplot.jet() max=2.8 min=0.4 steps = 50 levels=list() labels=list() for i in range(0,steps): levels.append(int((max-min)/steps*100*i)*0.01+min) for i in range(0,steps/2): labels.append(levels[2*i]) CSF = p.contourf(xi,yi,zi,levels,norm=colors.LogNorm()) CS = p.contour(xi,yi,zi,levels, format='%.3f', labelsize='18') p.clabel(CS,labels,inline=1,fontsize=9) p.title('electrostatic potential of two spherical colloids, R=lambda/3',fontsize=24) p.xlabel('z-coordinate (3*lambda)',fontsize=18) p.ylabel('radial coordinate r (3*lambda)',fontsize=18) # add a vertical bar with the color values cbar = p.colorbar(CSF,ticks=labels,format='%.3f') cbar.ax.set_ylabel('potential (reduced units)',fontsize=18) cbar.add_lines(CS) p.show()
def visualize_tsne(arrs): plt.figure(figsize=(20, 10)) plt.title("Original Dimension: ", arrs.shape[1]) plt.jet() embedded = TSNE(n_components=2).fit_transform(arrs) plt.scatter(embedded[:, 0], embedded[:, 1], c=y_test) plt.colorbar()
def plot_bins(category,num_bins, city): ''' takes a category and city and plots the bins for it ''' a, b = make_bins(category, num_bins, city) c = [] max_ratio = 0 for i in xrange(len(a)): c.append([]) for j in xrange(len(a[i])): try: ratio = a[i][j]/float(b[i][j]) c[i].append(ratio) if ratio > max_ratio: max_ratio = ratio # print i,j,max_ratio except ZeroDivisionError: c[i].append('NA') # print c for i in xrange(len(c)): for j in xrange(len(c[i])): if c[i][j] == 'NA': c[i][j] = max_ratio plt.imshow(c, interpolation='none', alpha = 1) max_lat, min_lat, max_lon, min_lon = city_edges(city) plt.xticks([0,len(c[0])-1],[min_lon, max_lon]) plt.yticks([0,len(c)-1],[min_lat, max_lat]) plt.jet() cb = plt.colorbar() #make color bar cb.set_ticks([max_ratio, 0]) #two ticks cb.set_ticklabels(['high concentration', 'low concentration']) # put text labels on them
def plot_saccade_stats(sac,bins=36, fig=None): """ Draws individual saccades (polar coordinatess), directional histogram, individual saccades (cartesian coordinates), and a histogram of saccade peak velocities """ if fig is None: fig = plt.figure() dx = sac.xf - sac.xi dy = sac.yf - sac.yi radii = sac.amplitude thetas = np.arctan2(dy, dx) theta_bins = np.linspace(-np.pi,np.pi,bins+1) theta_hist = np.histogram(thetas,bins=theta_bins) plt.jet() plt.title("individual saccades") # XXX: there's an interesting artifact if we use sac.amplitude as the # sac_length in the scatter plot below sac_length = np.sqrt((dx**2+dy**2)) plt.subplot(221,polar=True) plt.scatter(thetas,sac_length,alpha=.5,c=sac.amplitude,s=sac.vpeak/10.0) plt.colorbar() plt.subplot(222,polar=True) plt.title("Directional histogram") bars = plt.bar(theta_bins[:-1],theta_hist[0],width=(2*np.pi)/bins, alpha=.5) plt.subplot(223) plt.scatter(dx,dy,alpha=.5,c=sac.amplitude,s=sac.vpeak/10.0) #plt.hist(sac_length,bins=100) #plt.xlabel("saccade lengths (pixels)") plt.subplot(224) plt.hist(sac.vpeak,bins=100) plt.xlabel("saccade peak velocities")
def plot_percent_traffic(category, num_bins, city): ''' plots percent traffic (review_counts) of category in bin ''' a, b =bin_by_review_count(category, num_bins, city) c = [] max_ratio = 0 for i in xrange(len(a)): c.append([]) for j in xrange(len(a[i])): try: ratio = a[i][j]/float(b[i][j]) c[i].append(ratio) if ratio > max_ratio: max_ratio = ratio # print i,j,max_ratio except ZeroDivisionError: c[i].append('NA') # print c for i in xrange(len(c)): for j in xrange(len(c[i])): if c[i][j] == 'NA': c[i][j] = 0 plt.imshow(c, interpolation='none', alpha = 1) max_lat, min_lat, max_lon, min_lon = city_edges(city) plt.xticks([0,len(c[0])-1],[min_lon, max_lon]) plt.yticks([0,len(c)-1],[min_lat, max_lat]) plt.jet() cb = plt.colorbar() #make color bar cb.set_ticks([0,max_ratio]) #two ticks cb.set_ticklabels(['low traffic','lots of traffic']) # put text labels on them
def detect(img_path, model_name, fsize, fig1, fig2): # constants fsize_in = 256 stride_in = 16 img = readTiff(img_path) row_in, col_in = img.shape[1:] row = row_in * fsize / fsize_in col = col_in * fsize / fsize_in stride = row * stride_in / row_in img = resize(img, (row, col)) model = Model(model_name) region, heatmap = ret_img(img, fsize, stride, model) region = resize(region, (row_in, col_in)) map_max, map_min = np.max(heatmap), np.min(heatmap) map_range = map_max - map_min heatmap = (heatmap - map_min) / map_range if map_range > 0 else np.zeros_like(heatmap) # plot region = filters.sobel(region) region = np.where(region > 0, 255, 0) region = dilation(region, square(8)) region = 255 - region region = np.array(region, np.uint8) region = Image.fromarray(region) region.save(path + fig1) plt.figure(figsize=(10, 10)) cax = plt.matshow(heatmap, fignum=1, interpolation='nearest') plt.xticks([]) plt.yticks([]) plt.colorbar(cax, fraction=0.046, pad=0.04) plt.jet() plt.savefig(path + fig2)
def FMMdd(e, v, permutation, names, drawnow=False): e = np.array(e).T[permutation, :] v = np.array(v).T[permutation, :] names = np.array(names)[permutation] medoids = e.diagonal() == 1 N, K = e.shape plt.clf() plt.jet() ticks = np.arange(0, N, step=1) tick_labels = names plt.subplot(1, 2, 1) im = plt.matshow(e, fignum=0) plt.xticks([]) plt.yticks(ticks, tick_labels) plt.colorbar(im) for i in np.arange(-.5, N - .5, step=1): plt.plot([-.5, K - .5], [i, i], color='black', linewidth=1) for i in np.arange(-.5, K - .5, step=1): plt.plot([i, i], [-.5, N - .5], color='black', linewidth=1) plt.subplot(1, 2, 2) im = plt.matshow(v, fignum=0) plt.xticks([]) plt.yticks(ticks, tick_labels) plt.colorbar(im) for i in np.arange(-.5, N - .5, step=1): plt.plot([-.5, K - .5], [i, i], color='black', linewidth=1) for i in np.arange(-.5, K - .5, step=1): plt.plot([i, i], [-.5, N - .5], color='black', linewidth=1) if drawnow: plt.draw() plt.pause(0.001)
def plot_dboundaries(xx, yy, z, z_p): plt.pcolormesh(xx, yy, z, alpha=0.1) plt.jet() nclasses = z_p.shape[1] for j in range(nclasses): plt.contour(xx, yy, z_p[:, j].reshape(ngrid, ngrid), [0.5], lw=3, colors='k')
def image_gen(dataName, initValue, finalValue, increment,imgdpi): for i in range(initValue,finalValue,increment): if not os.path.exists(dataName+"r_"+str(i)+"_abspsi2.png"): real=open(dataName + '_' + str(i)).read().splitlines() img=open(dataName + 'i_' + str(i)).read().splitlines() a_r = numpy.asanyarray(real,dtype='f8') #64-bit double a_i = numpy.asanyarray(img,dtype='f8') #64-bit double a = a_r[:] + 1j*a_i[:] b = np.reshape(a,(xDim,yDim)) f = plt.imshow(abs(b)**2) plt.jet() plt.gca().invert_yaxis() plt.savefig(dataName+"r_"+str(i)+"_abspsi2.png",dpi=imgdpi) plt.close() g = plt.imshow(np.angle(b)) plt.gca().invert_yaxis() plt.savefig(dataName+"r_"+str(i)+"_phi.png",dpi=imgdpi) plt.close() f = plt.imshow(abs(np.fft.fftshift(np.fft.fft2(b)))**2) plt.gca().invert_yaxis() plt.jet() plt.savefig(dataName+"p_"+str(i)+"_abspsi2.png",dpi=imgdpi) plt.close() g = plt.imshow(np.angle(np.fft.fftshift(np.fft.fft2(b)))) plt.gca().invert_yaxis() plt.savefig(dataName+"p_"+str(i)+"_phi.png",dpi=imgdpi) plt.close() print "Saved figure: " + str(i) + ".png" plt.close() else: print "File(s) " + str(i) +".png already exist."
def heatmap_spearman(df, sample_name): # df_spearman_NS import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns plt.rcParams['figure.figsize'] = [50, 50] df_spearman_pivot = df.pivot('index1', 'index2', 'spearman') df_spearman_pivot # heatmap by plt.pcolor() plt.pcolor(df_spearman_pivot) plt.xticks(np.arange(0, len(df_spearman_pivot.columns), 1), df_spearman_pivot.columns) plt.yticks(np.arange(0, len(df_spearman_pivot.index), 1), df_spearman_pivot.index) plt.title('Heatmap of spearman correlation for '+sample_name, fontsize=20) #healthy_colonic_tissue plt.xlabel('index1', fontsize=14) plt.ylabel('index2', fontsize=14) plt.jet() plt.colorbar() plt.grid() plt.xticks(rotation=60) imagename="heatmap_spearman_"+sample_name+".png" plt.savefig(imagename) #healthy_colonic_tissue plt.show() return df_spearman_pivot
def plotDensity2d(U, n=50, addContour=True): xlim, ylim = [0, 1], [0, 1] # U.getBounds() x = np.linspace(xlim[0], xlim[1], n) y = np.linspace(ylim[0], ylim[1], n) X, Y = np.meshgrid(x, y) Z = np.ones((n, n)) for i in xrange(len(X)): for j, (xi, yi) in enumerate(zip(X[i], Y[i])): Z[i, j] = U.pdf([xi, 1 - yi]) # np.savetxt('density2d.csv', z.reshape(n * n, 3), delimiter=' ') plt.imshow(Z, interpolation='bicubic', aspect='auto', extent=[xlim[0], xlim[1], ylim[0], ylim[1]]) plt.jet() cbar = plt.colorbar() cbar.ax.set_ylabel(r'$\hat{f}(\xi_1, \xi_2)$') if addContour: cs = plt.contour(X, 1 - Y, Z, colors='black') plt.clabel(cs, inline=1, fontsize=18)
def baltimore_gmm(data): def fgmm(x): return abs(np.sum(gmmimmat[gmmimmat > x]) * .0005 ** 2 - 0.95) model = gmm.GMM(3) model.train(data, random=False) X, Y = makegrid(data) gmmimmat = np.zeros(X.shape) for i in xrange(X.shape[0]): for j in xrange(X.shape[1]): gmmimmat[i, j] = model.dgmm(np.array([X[i, j], Y[i, j]])) plt.jet() plt.imshow(gmmimmat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('baltimore_gmm.pdf') thresh = opt.fmin(fgmm, 10)[0] bools = gmmimmat > thresh mat = np.zeros(X.shape) mat += bools plt.imshow(mat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('gmmavoid.pdf')
def draw(ax, mu, Sigma): # 描画のクリア ax.collections = [] # 等高線を描画 xlist = np.linspace(-5, 5, 50) ylist = np.linspace(-5, 5, 50) x,y = np.meshgrid(xlist,ylist) z = np.zeros((50,50)) for i in range(len(ylist)): for j in range(len(xlist)): xx = np.array([[xlist[j]], [ylist[i]]]) z[i,j] = gaussian(xx, mu, Sigma) cs = ax.pcolor(x, y, z) plt.colorbar(cs) plt.jet() #plt.bone() ax.contour(x, y, z, np.linspace(0.0001,0.5,25), colors='k', linewidth=1) # ガウス分布の平均を描画 ax.scatter(mu[0], mu[1], c='b', marker='x') # 軸の調整 ax.set_xlim(-5,5) ax.set_ylim(-5,5) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('2D Normal distribution') ax.grid() plt.draw()
def baltimore_kde(data): def fkde(x): return abs(np.sum(kdeimmat[kdeimmat > x]) * .0005**2 - 0.95) X, Y = makegrid(data) kdeimmat = np.zeros(X.shape) kernel = stats.gaussian_kde(data.T) for i in xrange(X.shape[0]): for j in xrange(X.shape[1]): kdeimmat[i, j] = kernel.evaluate(np.array([X[i, j], Y[i, j]])) plt.jet() plt.imshow(kdeimmat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('baltimore_kde.pdf') thresh = opt.fmin(fkde, 10)[0] bools = kdeimmat > thresh mat = np.zeros(X.shape) mat += bools plt.imshow(mat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('kdeavoid.pdf')
def baltimore_gmm(data): def fgmm(x): return abs(np.sum(gmmimmat[gmmimmat > x]) * .0005**2 - 0.95) model = gmm.GMM(3) model.train(data, random=False) X, Y = makegrid(data) gmmimmat = np.zeros(X.shape) for i in xrange(X.shape[0]): for j in xrange(X.shape[1]): gmmimmat[i, j] = model.dgmm(np.array([X[i, j], Y[i, j]])) plt.jet() plt.imshow(gmmimmat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('baltimore_gmm.pdf') thresh = opt.fmin(fgmm, 10)[0] bools = gmmimmat > thresh mat = np.zeros(X.shape) mat += bools plt.imshow(mat, origin='lower') plt.ylim([0, X.shape[0]]) plt.xlim([0, X.shape[1]]) plt.savefig('gmmavoid.pdf')
def test_pca_white(sh=(12, 12), m=500, eps=0.1, rc=(10, 10), out_dir="img"): # Visualize examples in r x c grid of pca whitened images. # Also show that the covariance matrix of whitening data # is a diagonal matrix with descending values x = test_pca_input(sh, m) pca = PCA(x) x_white, mean = pca.whiten_pca(x, eps=eps) rows, cols = rc f, axes = plt.subplots(rows, cols, sharex='col', sharey='row') plt.subplots_adjust(hspace=0.1, wspace=0) plt.jet() for r in range(rows): for c in range(cols): axes[r][c].imshow(x_white[:, r * cols + c].reshape(sh)) axes[r][c].axis('off') path = os.path.join(out_dir, "pca_filters_{}_{}_{}.png".format(sh, m, eps)) print("saving {}...".format(path)) plt.savefig(path, bbox_inches='tight') cv = np.dot(x_white, x_white.T) plt.clf() plt.imshow(cv) plt.show()
def plot(self, poly=20): correction = findAngle(self.e) printD("correction: ", correction) #for a cyclic trajectory if mag(self.e) < 1: lo = -1 * np.pi hi = np.pi printD("is cyclic") #for a non-cyclic trajectory else: lo = self.entranceState[2] hi = self.exitState[2] printD("is not cyclic") x = [] y = [] step = [] printD("iAnom,fAnom: ", lo, hi) printD("semi-major: ", self.a, "\n eccentricity:", mag(self.e)) #temp denotes true anomaly for temp in range(poly): ang = lo + (hi - lo) / (poly - 1) * temp #calculation of dist (see Basyal 2.26) dist = abs(self.a * (1 - mag(self.e)**2) / (1 + mag(self.e) * np.cos(ang))) r = rotateBy(np.array([dist * np.cos(ang), dist * np.sin(ang)]), correction) #r = rotateBy(np.array([dist*np.cos(ang),dist*np.sin(ang)]), 0) #printD(ang) #printD(r,dist,"\n") printD(r[0], r[1]) x.append(r[0]) y.append(r[1]) step.append(ang) soi = self.soi tra = plt.axes() if mag(self.e) < 1: tra.scatter(x, y, marker='x', c='blue') else: tra.scatter(x, y, marker='x', c='green') #soi range circle = plt.Circle((0, 0), soi, color='red', fill=False) tra.add_artist(circle) #be in color plt.jet() #SoI size tra.set_xlim(-1.25 * soi, 1.25 * soi) tra.set_ylim(-1.25 * soi, 1.25 * soi) #set x-y ratio to be equal, to look more realistic tra.set_aspect('equal') for i, txt in enumerate(step): tra.annotate(("f=%.2f" % txt), (x[i] + 1000, y[i])) plt.show()
def demoDIRECT(): """ Test and visualize DIRECT on a 2D function. This will draw the contours of the target function, the final set of rectangles and mark the optimum with a red dot. """ def foo(x): """ Code for the Shekel function S5. The dimensionality of x is 2. The minimum is at [4.0, 4.0]. """ return np.sin(x[:, 0] * 2) + np.abs(x[:, 0] - 15) + np.sin( x[:, 1]) + .2 * np.abs(x[:, 1] - 6) bounds = [(1.2, 28.), (0.1, 13.)] optimum, report = direct(foo, bounds, maxsample=100, debug=True) plt.figure(1) plt.clf() # plot rectangles c0 = [(i / 50.) * (bounds[0][1] - bounds[0][0]) + bounds[0][0] for i in range(51)] c1 = [(i / 50.) * (bounds[1][1] - bounds[1][0]) + bounds[1][0] for i in range(51)] z = np.array([[foo(np.array([[i, j]]))[0] for i in c0] for j in c1]) ax = plt.subplot(111) for rect in report['rectangles']: ax.add_artist( plt.Rectangle(rect.lb, rect.ub[0] - rect.lb[0], rect.ub[1] - rect.lb[1], fc='y', ec='k', lw=1, alpha=0.25, fill=True)) # ax.plot([x[0] for _,x in report['fmin evolution']], [x[1] for _,x in report['fmin evolution']], 'go') ax.plot([optimum[1][0]], [optimum[1][1]], 'ro') # ax.text(rect.center[0], rect.center[1], '%.3f'%rect.y) cs = ax.contour(c0, c1, z, 10) ax.clabel(cs) plt.jet() ax.set_xlim(bounds[0]) ax.set_ylim(bounds[1]) ax.set_xlabel('x[0]') ax.set_ylabel('x[1]') ax.set_title('final rectangles') # ax = plt.subplot(122) # fminevol = [y for y,_ in report['fmin evolution']] # ax.plot(range(len(fminevol)), fminevol, 'k-', lw=2) # ax.set_ylim(min(fminevol)-0.01, max(fminevol)+0.01) # ax.grid() # ax.set_title('optimization evolution') # ax.set_xlabel('iteration') # ax.set_ylabel('fmin') plt.show()
def visualize_tsne(self): plt.jet() encoded_imgs_embedded = TSNE(n_components=2).fit_transform( self.encoded_imgs) plt.scatter(encoded_imgs_embedded[:, 0], encoded_imgs_embedded[:, 1], c=self.y_test) plt.colorbar()
def plot_contour_plot(plot_array, x_vals, y_vals, title, xlabel, ylabel): pyplot.jet() cont = pyplot.contourf(x_vals, y_vals, plot_array, range(0, 100, 5)) pyplot.colorbar(cont) pyplot.title(title) pyplot.xlabel(xlabel) pyplot.ylabel(ylabel) pyplot.show()
def draw(data, name): #cb_min,cb_max:カラーバーの下端と上端の値 plt.figure(figsize=(10, 4)) #図の縦横比を指定する plt.contourf(data, 100) plt.colorbar() plt.savefig("wakam" + name + ".png") plt.jet() plt.savefig("jet" + name + ".png") plt.show()
def draw_Cloudmap(self,points_centrol,B_magnitude): grid_x,grid_y=np.mgrid[0:1:800j,0:1:600j] grid=griddata(points_centrol,B_magnitude,(grid_x,grid_y),method='linear') pl.imshow(grid.T, aspect='auto', extent=(0,1,0,1), origin='lower',interpolation='bilinear') pl.title('Cloud_map') pl.colorbar() pl.jet() pl.show()
def struct_fact(density,name,imgdpi): fig, ax = plt.subplots() #f = plt.quiver(gx,gy) f = plt.imshow((np.abs(np.fft.fftshift(np.fft.fft2(density)))),cmap=plt.get_cmap('prism')) cbar = fig.colorbar(f) cbar.set_clim(1e6,1e11) plt.jet() plt.savefig(name + "_struct_log10.png",dpi=imgdpi) plt.close()
def heatMap(distanceMatrix, save=False, saveAt=".pdf"): plt.figure() plt.imshow(distanceMatrix, interpolation='none') plt.jet() plt.colorbar() if save: plt.savefig(saveAt) else: plt.show()
def heatmap_plot(data, size, ratio, dir_name): im = plt.imshow(data, interpolation='none', aspect=ratio) # change the aspect if needed plt.xticks(range(size)) plt.jet() plt.colorbar() plt.clim(0,BAR_RANGE) # plt.show() plt.savefig(dir_name + 'comp.png') plt.close()
def frame_histo_stats(image_array, plot=True): """Plots a frame with a colorbar, its histogram and some statistics: mean, median, maximum, minimum and standard deviation values. Parameters ---------- image_array : array_like The input frame. plot : {True, False}, bool optional If True plots the frame and the histogram with the values. Return ------ mean : float Mean value of array. median : float Median value of array. std : float Standard deviation of array. maxim : int or float Maximum value. minim " int or float Minimum value. """ vector = image_array.flatten() mean = vector.mean() median = np.median(vector) maxim = vector.max() minim = vector.min() std = vector.std() if plot is True: fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(14,5)) ax0, ax1 = axes.flat bins = np.sqrt(vector.shape[0]) txt = 'Mean = {:.3f}\n'.format(mean) + \ 'Median = {:.3f}\n'.format(median) +\ 'Stddev = {:.3f}\n'.format(std) +\ 'Max = {:.3f}\n'.format(maxim) +\ 'Min = {:.3f}\n\n'.format(minim) ax0.hist(vector, bins=bins, label=txt, alpha=0.5, histtype='stepfilled') ax0.set_yscale('log') ax0.set_title('Histogram') ax0.text(0.98, 0.98, txt, transform=ax0.transAxes, fontsize=12, verticalalignment='top', horizontalalignment='right') ima = ax1.imshow(image_array, interpolation="nearest", origin ="lower", cmap='CMRmap') ax1.set_title('Frame') ax1.grid('off') fig.colorbar(ima) plt.jet() plt.show() return mean, median, std, maxim, minim
def scaleAxis(data,dataName,label,value,imgdpi): fig, ax = plt.subplots() ax.xaxis.set_major_locator(ScaledLocator(dx=dx)) ax.xaxis.set_major_formatter(ScaledLocator(dx=dx)) f = plt.imshow(abs(data)**2) cbar = fig.colorbar(f) plt.gca().invert_yaxis() plt.jet() plt.savefig(dataName+"r_"+str(value)+"_"+label +".png",dpi=imgdpi) plt.close()
def run3Dheatmap(X): plt.imshow(data, interpolation='none', aspect=3./20) plt.xticks(range(3), ['a', 'b', 'c']) plt.jet() plt.colorbar() plt.show()
def plot_visual(scoreMatrix): data = py.array(scoreMatrix, py.int32) plt.imshow(data, interpolation='none') plt.xlabel('Sequence 2') plt.ylabel('Sequence 1') plt.title('Local Alignment Score F') plt.jet() plt.colorbar() plt.show()
def run3Dheatmap(X): plt.imshow(data, interpolation='none', aspect=3. / 20) plt.xticks(range(3), ['a', 'b', 'c']) plt.jet() plt.colorbar() plt.show()
def opPot(dataName,imgdpi): data = open(dataName).read().splitlines() a = numpy.asanyarray(data,dtype='f8') b = np.reshape(a,(xDim,yDim)) fig, ax = plt.subplots() f = plt.imshow((b)) plt.gca().invert_yaxis() cbar = fig.colorbar(f) plt.jet() plt.savefig(dataName + ".png",dpi=imgdpi) plt.close()
def LocationThresh_View(examples,figsize,video_dict,reference,crop,tracking_params): #load video plt.figure(figsize=figsize) cap = cv2.VideoCapture(video_dict['fpath']) cap_max = int(cap.get(7)) #get max frames. 7 is index of total frames cap_max = int(video_dict['end']) if video_dict['end'] is not None else cap_max #define cropping values try: Xs=[crop.data['x0'][0],crop.data['x1'][0]] Ys=[crop.data['y0'][0],crop.data['y1'][0]] fxmin,fxmax=int(min(Xs)), int(max(Xs)) fymin,fymax=int(min(Ys)), int(max(Ys)) except: fxmin,fxmax=0,reference.shape[1] fymin,fymax=0,reference.shape[0] #examine random frames for x in range (1,examples+1): #analyze frame f=np.random.randint(0,cap_max) #select random frame cap.set(1,f) #sets frame to be next to be grabbed ret,dif,com = Locate(cap,crop,reference,tracking_params) #get frame difference from reference #plot original frame plt.subplot(2,examples,x) cap.set(1,f) #resets frame position ret, frame = cap.read() #read frame frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frame = frame[fymin:fymax,fxmin:fxmax] plt.annotate('COM', xy=(com[1], com[0]), xytext=(com[1]-20, com[0]-20), color='red', size=15, arrowprops=dict(facecolor='red')) plt.title('Frame: {f}'.format(f=f)) plt.imshow(frame) plt.gray() #plot difference plt.subplot(2,examples,(x+examples)) plt.annotate('COM', xy=(com[1], com[0]), xytext=(com[1]-20, com[0]-20), color='white', size=15, arrowprops=dict(facecolor='white')) plt.imshow(dif) plt.jet() #release cap when done cap.release()
def heatmap_plot(data, size_x, size_y, dir_name): im = plt.imshow(data, interpolation='none', aspect=1.0) # 1.0 = square cell plt.xlim([0.5, size_x + 0.5]) plt.ylim([0.5, size_y + 0.5]) plt.xticks(range(1, size_x + 1), fontsize=X_SIZE) plt.yticks(list(reversed(range(1, size_y + 1))), fontsize=Y_SIZE) plt.jet() cb = plt.colorbar() cb.ax.tick_params(labelsize=CB_SIZE) plt.clim(0,BAR_RANGE) plt.set_cmap('gray_r') plt.savefig(dir_name + 'comp.png') plt.close()
def plotdataarray(self): """Plot the image array return axes """ self.ob_plot = self.slotfig.add_axes([0.10,0.10,0.8,0.80], autoscale_on=True) plt.setp(plt.gca(),xticks=[],yticks=[]) plt.jet() self.array=self.struct[int(self.pid[self.id])].data self.imarr=self.ob_plot.imshow(self.array,origin='lower') #Plot the apertures self.cbox,=self.plotbox('#00FF00',self.cx[self.id],self.cy[self.id],self.radius,self.npoint,self.naxis1, self.naxis2) self.tbox,=self.plotbox('#FFFF00',self.tx[self.id],self.ty[self.id],self.radius,self.npoint,self.naxis1, self.naxis2)
def __plotHeatmap(self, data): figure = plt.figure(figsize=(FIG_SIZE_X,FIG_SIZE_Y), dpi=FIG_DPI); ax1 = plt.subplot(111); plt.imshow(data, origin="lower"); plt.xlabel('x'); plt.ylabel('y'); plt.colorbar(); plt.jet(); (ny,nx) = data.shape; ax1.set_xticks(range(0,nx,5)); ax1.set_yticks(range(0,ny,5)); ax1.axis('tight'); return figure;
def test_segment_sweep(vna, wts): # tau must already be canceled vna.set_average_factor(1) vna.do_enable_averaging() use_segment_sweep(vna) xs = vna.do_get_xaxis() ys = vna.do_get_data(fmt='PLOG', opc=True) import matplotlib.pyplot as plt plt.figure() weights = np.interp(xs, wts[0], wts[1]) plt.scatter(ys[0], ys[1], c=weights, s=100, cmap='jet') plt.jet() plt.show() return ys, wts
def plot_zeropoint(pars): """ Plot 2d histogram. Pars will be a dictionary containing: data, figure_id, vmax, title_str, xp,yp, searchrad """ from matplotlib import pyplot as plt xp = pars['xp'] yp = pars['yp'] searchrad = int(pars['searchrad'] + 0.5) plt.figure(num=pars['figure_id']) plt.clf() if pars['interactive'] is True: plt.ion() else: plt.ioff() a = plt.imshow(pars['data'], vmin=0, vmax=pars['vmax'], interpolation='nearest') plt.jet() #gray() plt.colorbar() plt.title(pars['title_str']) plt.plot(xp + searchrad, yp + searchrad, color='red', marker='+', markersize=24) plt.plot(searchrad, searchrad, color='yellow', marker='+', markersize=120) plt.text(searchrad, searchrad, "Offset=0,0", verticalalignment='bottom', color='yellow') plt.xlabel("Offset in X (pixels)") plt.ylabel("Offset in Y (pixels)") if pars['plotname']: suffix = pars['plotname'][-4:] if '.' not in suffix: output += '.png' format = 'png' else: if suffix[1:] in ['png', 'pdf', 'ps', 'eps', 'svg']: format = suffix[1:] plt.savefig(pars['plotname'], format=format)
def demoCDIRECT(maxiter=25): """ Test and visualize cDIRECT on a 2D function. This will draw the contours of the target function, the final set of rectangles and mark the optimum with a red dot. """ import matplotlib.pyplot as plt def foo(x): """ Code for the Shekel function S5. The dimensionality of x is 2. The minimum is at [4.0, 4.0]. """ # return min(-.5, -sum(1./(dot(x-a, x-a)+c) for a, c in SHEKELPARAMS)) return sin(x[0]*2)+abs(x[0]-15) + sin(x[1])+.2*abs(x[1]-6) # def foo(x): # # several local minima, global minimia is at bottom left # return 2.5 + sin((x[0]-.4)*8)+sin((x[1]+.5)*5) + .1* sum(sin(x[0]*50)) + .1* sum(sin(x[1]*50))+ x[0]*.1 - x[1] * .1 bounds = [(1.2, 28.), (0.1, 13.)] optv, optx = cdirect(foo, bounds, maxiter=maxiter) print '***** opt val =', optv print '***** opt x =', optx plt.figure(2) plt.clf() # plot rectangles c0 = [(i/100.)*(bounds[0][1]-bounds[0][0])+bounds[0][0] for i in xrange(101)] c1 = [(i/100.)*(bounds[1][1]-bounds[1][0])+bounds[1][0] for i in xrange(101)] z = array([[foo([i, j]) for i in c0] for j in c1]) ax = plt.subplot(111) B = [array([1.2, 0.1]), array([28., 13.])] for line in open('finalrecs.txt').readlines(): dat = line.strip().split(',') lb = array([double(x) for x in dat[0].split()])*(B[1]-B[0])+B[0] ub = array([double(x) for x in dat[1].split()])*(B[1]-B[0])+B[0] ax.add_artist(plt.Rectangle(lb, ub[0]-lb[0], ub[1]-lb[1], fc='y', ec='k', lw=1, alpha=0.25, fill=True)) ax.plot(optx[0], optx[1], 'ro') cs = ax.contour(c0, c1, z, 10) ax.clabel(cs) plt.jet() ax.set_xlim(bounds[0]) ax.set_ylim(bounds[1]) ax.set_xlabel('x[0]') ax.set_ylabel('x[1]') ax.set_title('final optimum')
def test_pca(sh=(12, 12), m=10, retain=0.9): """ Show plot demonstrating that the covariance matrix of x_tilde is a diagonal matrix with descending values :param sh: shape of image patches to test :param m: The number of samples to load :param retain: Percentage of variance to retain """ x = test_pca_input(sh, m) pca = PCA(x) xt, mean = pca.reduce(x, retain=retain) cov = np.dot(xt, xt.T) plt.jet() plt.imshow(cov) plt.show()
def vectorfield(show=False): """ Data for vectorfield """ R = 7.0 J = 100.0 YY, XX = np.mgrid[-10:10,-10:10] print XX print YY MAG = np.sqrt(XX**2 + YY**2) FIELDX_IN = np.zeros_like(XX) FIELDY_IN = np.zeros_like(YY) FIELDX_OUT = FIELDX_IN.copy() FIELDY_OUT = FIELDY_IN.copy() FIELDX_IN = -1*YY*(J/2.) FIELDY_IN = XX*(J/2.) FIELDX_OUT = ((R**2*J)/(2*(XX**2 + YY**2)))*(-1*YY) FIELDY_OUT = ((R**2*J)/(2*(XX**2 + YY**2)))*(XX) FIELDX = np.zeros_like(XX) FIELDY = np.zeros_like(YY) MAG = np.sqrt(XX**2 + YY**2) FIELDX[MAG<R] = FIELDX_IN[MAG < R] FIELDX[MAG>=R] = FIELDX_OUT[MAG >= R] FIELDY[MAG<R] = FIELDY_IN[MAG < R] FIELDY[MAG>=R] = FIELDY_OUT[MAG >= R] np.savetxt('vectorfield_x.txt', FIELDX) np.savetxt('vectorfield_y.txt', FIELDY) if show: f = plt.figure(199) plt.clf() plt.jet() plt.quiver(FIELDX, FIELDY, (FIELDX**2 + FIELDY**2))
def heatmap(model, xvals, yvals, scores, x_name, y_name, name): fig = plt.figure() plt.imshow(scores, interpolation='nearest', aspect='auto') title = 'Accuracy for ' + model plt.title(title) plt.xticks(range(len(xvals)), xvals) plt.yticks(range(len(yvals)), yvals) plt.xlabel(x_name) plt.ylabel(y_name) plt.jet() plt.colorbar() # plt.show() #if not os.path.exists(plot_dir): # os.makedirs(plot_dir) fig.savefig(name,format='pdf', bbox_='')
def main(): datadir = '/Users/maye/Data/ctx/' atlas_data = read_atlas_report(datadir + 'atlas_report.csv') with open(datadir + 'std_data.pkl') as f: std_data = pickle.load(f) stds = [] l_s = [] longitudes = [] latitudes = [] miss_counter=0 for obsid, std in std_data.iteritems(): std = float(std) if std > 1e10: # some conversion to ISIS fails. continue try: d = atlas_data[obsid] except KeyError: miss_counter+=1 continue l_s.append(float(d['SOLAR_LONGITUDE'])) longitudes.append(float(d['CENTER_LONGITUDE'])) latitudes.append(float(d['CENTER_LATITUDE'])) stds.append(float(std)) d = {} ls_binning = 20 for i in range(180//ls_binning,381//ls_binning): # l_s bins, in steps of 20 degrees d[i]=DataCollector(5,8) maxstd = 0 minstd = 10 for lsubs, std, lon,lat in zip(l_s,stds,longitudes,latitudes): d[lsubs//ls_binning].add((-lat-80)//2,lon//45,std) extent=[0,360,-90,-80] for l_s in d.keys(): print 'doing',l_s plt.clf() plt.imshow(d[l_s].get_mean_image(),extent=extent,vmin=0.0006,vmax=0.066) plt.jet() plt.colorbar() plt.title(str(l_s*ls_binning)+'-'+str(l_s*ls_binning+ls_binning)) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.savefig(str(l_s*ls_binning)+'.pdf')
def raw_data_by_std(self, output_dir=None): fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(self.Z, self.X, c=-self.stds, cmap=plt.jet(), s=25, lw=0.5, clip_on=False, zorder=10) ax.set_yscale('log') ax.set_xlabel('input count') ax.set_ylabel('output count') ax.axis([0, 1200, 1, 1e3]) bar = fig.colorbar(ax.collections[0]) bar.set_label('-1*std(w)') show(fig, output_dir, 'raw_data_std.png')
def plotFunction2d(f, addContour=True, n=101): x = np.linspace(0, 1, n) y = np.linspace(0, 1, n) X, Y = np.meshgrid(x, y) Z = np.ones(n * n).reshape(n, n) print "-" * 60 for i in xrange(len(X)): for j, (xi, yi) in enumerate(zip(X[i], Y[i])): Z[i, j] = f(xi, yi) plt.imshow(Z, interpolation='bilinear', extent=(0, 1, 0, 1)) plt.jet() plt.colorbar() if addContour: cs = plt.contour(X, 1 - Y, Z, colors='black') plt.clabel(cs, inline=1, fontsize=18) return
def heatmap(scores, p1, p2, pvals, model, score_fn): fig = plt.figure() plt.imshow(scores, interpolation="nearest", aspect="auto") title = " ".join([score_fn, "for", model]) plt.title(title) p1_vals = pvals[p1] p2_vals = pvals[p2] plt.xticks(range(len(p1_vals)), p1_vals) plt.yticks(range(len(p2_vals)), p2_vals) plt.xlabel(p1) plt.ylabel(p2) plt.jet() plt.colorbar() # if not os.path.exists(plot_dir): # os.makedirs(plot_dir) plt.show() # plot_path = directory + '/' + title + '.pdf' print plot_path
def plot_zeropoint(pars): """ Plot 2d histogram. Pars will be a dictionary containing: data, figure_id, vmax, title_str, xp,yp, searchrad """ from matplotlib import pyplot as plt xp = pars['xp'] yp = pars['yp'] searchrad = int(pars['searchrad']+0.5) plt.figure(num=pars['figure_id']) plt.clf() if pars['interactive'] is True: plt.ion() else: plt.ioff() a=plt.imshow(pars['data'],vmin=0,vmax=pars['vmax'],interpolation='nearest') plt.jet()#gray() plt.colorbar() plt.title(pars['title_str']) plt.plot(xp+searchrad,yp+searchrad,color='red',marker='+',markersize=24) plt.plot(searchrad,searchrad,color='yellow',marker='+',markersize=120) plt.text(searchrad,searchrad,"Offset=0,0", verticalalignment='bottom',color='yellow') plt.xlabel("Offset in X (pixels)") plt.ylabel("Offset in Y (pixels)") if pars['plotname']: suffix = pars['plotname'][-4:] if '.' not in suffix: output += '.png' format = 'png' else: if suffix[1:] in ['png','pdf','ps','eps','svg']: format=suffix[1:] plt.savefig(pars['plotname'],format=format)
def demoDIRECT(maxiter=25): """ Test and visualize DIRECT on a 2D function. This will draw the contours of the target function, the final set of rectangles and mark the optimum with a red dot. """ def foo(x): """ Code for the Shekel function S5. The dimensionality of x is 2. The minimum is at [4.0, 4.0]. """ return sin(x[0]*2)+abs(x[0]-15) + sin(x[1])+.2*abs(x[1]-6) bounds = [(1.2, 28.), (0.1, 13.)] optimum, report = direct(foo, bounds, debug=True, maxiter=maxiter) plt.figure(1) plt.clf() # plot rectangles c0 = [(i/50.)*(bounds[0][1]-bounds[0][0])+bounds[0][0] for i in xrange(51)] c1 = [(i/50.)*(bounds[1][1]-bounds[1][0])+bounds[1][0] for i in xrange(51)] z = array([[foo([i, j]) for i in c0] for j in c1]) ax = plt.subplot(111) for rect in report['rectangles']: ax.add_artist(plt.Rectangle(rect.lb, rect.ub[0]-rect.lb[0], rect.ub[1]-rect.lb[1], fc='y', ec='k', lw=1, alpha=0.25, fill=True)) # ax.plot([x[0] for _,x in report['fmin evolution']], [x[1] for _,x in report['fmin evolution']], 'go') ax.plot([optimum[1][0]], [optimum[1][1]], 'ro') # ax.text(rect.center[0], rect.center[1], '%.3f'%rect.y) cs = ax.contour(c0, c1, z, 10) ax.clabel(cs) plt.jet() ax.set_xlim(bounds[0]) ax.set_ylim(bounds[1]) ax.set_xlabel('x[0]') ax.set_ylabel('x[1]') ax.set_title('final rectangles')
def __Plot(self, X, Y, Z, xmin, xmax, ymin, ymax): fig = plt.figure() ax = fig.add_subplot(111) ax.set_xscale('log') ax.set_yscale('log') ax.scatter(X,Y,c=Z,cmap = plt.jet(), s=670, lw = 0.6, marker = 's') bar = fig.colorbar(ax.collections[0]) ax.set_xlim([xmin, xmax]) ax.set_ylim([ymin, ymax]) plt.show() fig.savefig('%s.png'%self.name)