def show_peeps (G, vmin=EMPTY, vmax=RECOVERED, ticks=range (EMPTY, RECOVERED+1)): """ Displays a checkerboard plot of the world. """ plt.pcolor (G, vmin=vmin, vmax=vmax, edgecolor='black') plt.colorbar (ticks=ticks) plt.axes ().set_aspect ('equal')
def lasso_regression(features, solutions, verbose=0): columns = solutions.columns clf = Lasso(alpha=1e-4, max_iter=5000) print('Training Model... ') clf.fit(features, solutions) feature_coeff = clf.coef_ features_importances = np.zeros((169, 3)) for idx in range(3): features_importance = np.reshape(feature_coeff[idx, :], (169, 8)) features_importance = np.max(features_importance, axis=1) features_importances[:, idx] = features_importance features_importance_max = np.max(features_importances, axis=1) features_importance_max = np.reshape(features_importance_max, (13, 13)) plt.pcolor(features_importance_max) plt.title("Feature importance for HoG") plt.colorbar() plt.xticks(arange(0.5,13.5), range(1, 14)) plt.yticks(arange(0.5,13.5), range(1, 14)) plt.axis([0, 13, 0, 13]) plt.show() print('Done Training') return (clf, columns)
def plot_cell_species(species_name,time): tindex = np.abs(t-time).argmin() astatus = np.zeros((NCells,1)) for i in xrange(NCells): astatus[i] = cdata[i][tindex,IM.get_node_id(species_name)] r8s = get_r8s(time) r25s = get_r25s(time) progenitors = get_progenitors(time) cell_types = [r8s,r25s,progenitors] # plot along x axis plt.figure() gs = gridspec.GridSpec(2,1,height_ratios=[19,1]) # first plot values ax1 = plt.subplot(gs[0]) ax1.xaxis.grid(True,linewidth=0.1,linestyle='-',color='0.4'); colors = cm.Set1(np.linspace(0, 1, 10)) for j in xrange(len(cell_types)): plt.scatter(x_coord[cell_types[j]],astatus[cell_types[j]],color=colors[j],s=50) plt.legend(['R8','R2/5','MP'],loc='best') for j in xrange(len(cell_types)): plt.plot(x_coord[cell_types[j]],astatus[cell_types[j]],'--',color=colors[j]) plt.title(species_name,fontsize=24) plt.xlabel('Cell',labelpad=0) # now plot stripes ax2 = plt.subplot(gs[1],sharex=ax1) xcorners = np.tile(np.linspace(0,NCells,NCells+1)+0.5,(2,1)) ycorners = np.tile(np.array([[0],[1]]),(1,NCells+1)) plt.pcolor(xcorners,ycorners,astatus.T,edgecolors='k') ax2.xaxis.set_visible(False) ax2.yaxis.set_visible(False) plt.show()
def visual(self,vtype=None): if vtype==None: print(self) elif vtype=="syn": tempmat=np.matrix(np.zeros((self._M,self._W))) synvec=[] for i in range(0,self._M): synvec.append(len(self.get_known_words(i))) for j in range(0,self._W): tempmat[i,j]=(self._W-synvec[i]+1)*self._content[i,j] plt.title("Synonymy") plt.xlabel("Words") plt.ylabel("Meanings") plt.gca().invert_yaxis() plt.pcolor(np.array(tempmat),vmin=0,vmax=self._W) elif vtype=="hom": tempmat=np.matrix(np.zeros((self._M,self._W))) homvec=[] for j in range(0,self._W): homvec.append(len(self.get_known_meanings(j))) for i in range(0,self._M): tempmat[i,j]=(self._M-homvec[j]+1)*self._content[i,j] plt.title("Homonymy") plt.xlabel("Words") plt.ylabel("Meanings") plt.gca().invert_yaxis() plt.pcolor(np.array(tempmat),vmin=0,vmax=self._M)
def image(self, point_grid=None, cmap='hot'): """ makes an image of the (2-dimensional) x and predicted y Input: point_grid: a grid constructed with mgrid[...] tuple (max_x0, max_x1) specifying the grid mgrid[0:max_x0:100j, 0:max_x1:100j] defaults to mgrid[0:max(x[:,0]):100j, 0:max(x[:,1]):100j] """ if point_grid is None: point_grid = self.mk_grid('minmax') elif isinstance(point_grid, tuple): point_grid = self.mk_grid(point_grid) n_xgrid = shape(point_grid)[1] n_ygrid = shape(point_grid)[2] positions = vstack(map(ravel, point_grid)).transpose() plt.pcolor(positions[:, 0].reshape(n_xgrid, n_ygrid), positions[:, 1].reshape(n_xgrid, n_ygrid), self.predict_proba(positions)[:, 1] .reshape(n_xgrid, n_ygrid), cmap=cmap) plt.tight_layout() plt.colorbar() plt.xlabel(self.x_name[0]) plt.ylabel(self.x_name[1]) plt.title(self.y_prob_name)
def plot_q_qhat(q, t): # Plot Potential Vorticity plt.clf() plt.subplot(2,1,1) plt.pcolormesh(xx/1e3,yy/1e3,q) plt.colorbar() plt.axes([-Lx/2e3, Lx/2e3, -Ly/2e3, Ly/2e3]) name = "PV at t = %5.2f" % (t/(3600.0*24.0)) plt.title(name) # compute power spectrum and shift ffts qe = np.vstack((q0,-np.flipud(q))) qhat = np.absolute(fftn(qe)) kx = fftshift((parms.ikx/parms.ikx[0,1]).real) ky = fftshift((parms.iky/parms.iky[1,0]).real) qhat = fftshift(qhat) Sx, Sy = int(parms.Nx/2), parms.Ny Sk = 1.5 # Plot power spectrum plt.subplot(2,1,2) #plt.pcolor(kx[Sy:Sy+20,Sx:Sx+20],ky[Sy:Sy+20,Sx:Sx+20],qhat[Sy:Sy+20,Sx:Sx+20]) plt.pcolor(kx[Sy:int(Sk*Sy),Sx:int(Sk*Sx)],ky[Sy:int(Sk*Sy),Sx:int(Sk*Sx)], qhat[Sy:int(Sk*Sy),Sx:int(Sk*Sx)]) plt.axis([0, 10, 0, 10]) plt.colorbar() name = "PS at t = %5.2f" % (t/(3600.0*24.0)) plt.title(name) plt.draw()
def create_subheatmap(intensity, job, host, n, num_hosts): """ Creates a heatmap in a subplot. Arguments: intensity -- the values of the intensity being plotted. Must be same length as job.times job -- the current job being plotted host -- the host being charted n -- the subplot number of the specific host num_hosts -- the total number of hosts to be plotted """ length = job.times.size end = job.end_time start = job.start_time x = NP.linspace(0, (end - start) / 3600.0, length * 1) intensity = NP.array([intensity]*2, dtype=NP.float64) PLT.subplot(num_hosts+1, 1, n) PLT.pcolor(x, NP.array([0, 1]), intensity, cmap=matplotlib.cm.Reds, vmin = 0, vmax = math.ceil(NP.max(intensity)), edgecolors='none') if (n != num_hosts): PLT.xticks([]) else: PLT.xlabel('Hours From Job Beginning') PLT.yticks([]) #PLT.autoscale(enable=True,axis='both',tight=True) host_name = host.replace('.tacc.utexas.edu', '') PLT.ylabel(host_name, fontsize ='small', rotation='horizontal')
def plotq2_cart(outputdir,nframe, m,meth1,meqn,time, points_per_dir,LegVals, xlow,xhigh,ylow,yhigh, mx,my, dx,dy, mx_old,my_old, dx_old,dy_old, xc,yc, xl,yl, qaug): import matplotlib.pyplot as plt import numpy as np plt.figure(1) plt.clf() plt.gca().set_aspect('equal') plt.gca().set_xlim(xl[0,0],xl[mx,0]) plt.gca().set_ylim(yl[0,0],yl[0,my]) plt.pcolor(xl,yl,qaug[:,:,m]) tmp1 = "".join(("q(",str(m+1),") at t = ")) tmp2 = "".join((tmp1,str(time))) title = "".join((tmp2," [DoGPack]")) plt.title(title) plt.draw()
def test_complete(): fig = plt.figure('Figure with a label?', figsize=(10, 6)) plt.suptitle('Can you fit any more in a figure?') # make some arbitrary data x, y = np.arange(8), np.arange(10) data = u = v = np.linspace(0, 10, 80).reshape(10, 8) v = np.sin(v * -0.6) plt.subplot(3, 3, 1) plt.plot(list(xrange(10))) plt.subplot(3, 3, 2) plt.contourf(data, hatches=['//', 'ooo']) plt.colorbar() plt.subplot(3, 3, 3) plt.pcolormesh(data) plt.subplot(3, 3, 4) plt.imshow(data) plt.subplot(3, 3, 5) plt.pcolor(data) plt.subplot(3, 3, 6) plt.streamplot(x, y, u, v) plt.subplot(3, 3, 7) plt.quiver(x, y, u, v) plt.subplot(3, 3, 8) plt.scatter(x, x**2, label='$x^2$') plt.legend(loc='upper left') plt.subplot(3, 3, 9) plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4) ###### plotting is done, now test its pickle-ability ######### # Uncomment to debug any unpicklable objects. This is slow (~200 seconds). # recursive_pickle(fig) result_fh = BytesIO() pickle.dump(fig, result_fh, pickle.HIGHEST_PROTOCOL) plt.close('all') # make doubly sure that there are no figures left assert_equal(plt._pylab_helpers.Gcf.figs, {}) # wind back the fh and load in the figure result_fh.seek(0) fig = pickle.load(result_fh) # make sure there is now a figure manager assert_not_equal(plt._pylab_helpers.Gcf.figs, {}) assert_equal(fig.get_label(), 'Figure with a label?')
def main(grid_size, discount): """ Run linear programming inverse reinforcement learning on the gridworld MDP. Plots the reward function. grid_size: Grid size. int. discount: MDP discount factor. float. """ wind = 0.3 trajectory_length = 3*grid_size gw = gridworld.Gridworld(grid_size, wind, discount) ground_r = np.array([gw.reward(s) for s in range(gw.n_states)]) policy = [gw.optimal_policy_deterministic(s) for s in range(gw.n_states)] r = linear_irl.irl(gw.n_states, gw.n_actions, gw.transition_probability, policy, gw.discount, 1, 5) plt.subplot(1, 2, 1) plt.pcolor(ground_r.reshape((grid_size, grid_size))) plt.colorbar() plt.title("Groundtruth reward") plt.subplot(1, 2, 2) plt.pcolor(r.reshape((grid_size, grid_size))) plt.colorbar() plt.title("Recovered reward") plt.show()
def makePngFileByInterval(self, thisInterval, wvMin, wvMax, maxRate): fn = "%s-%03d-%05d-%05d.png" %\ (self.name, thisInterval, int(wvMin), int(wvMax)) print "now make fn=", fn spectralCubes = self.getSpectralCubes(thisInterval, wvMin, wvMax) cubeSum = None for spectralCube in spectralCubes: cube = spectralCube['cube'].sum(axis=2) effIntTime = spectralCube['effIntTime'] if cubeSum is None: cubeSum = cube effIntTimeSum = effIntTime else: cubeSum += cube effIntTimeSum += effIntTime old_settings = np.seterr(all='ignore') np.seterr(divide='ignore') rate = np.nan_to_num(cubeSum/effIntTimeSum) np.seterr(**old_settings) print fn, rate.min(), rate.max() plt.clf() plt.pcolor(rate, cmap='hot', vmin=0, vmax=maxRate) plt.colorbar() try: os.remove(fn) except OSError: pass plt.title(fn) plt.savefig(fn)
def run_model(G, group, filename, picturename): dynamics=[] initial = [group[i].unification for i in range (11)] dynamics.append(initial) for t in range(10): uni=[] for i in range(11): Idx = G.neighbors(i) connections = {group[i] for i in Idx} x = group[i].influence(connections) if (np.absolute(x)>= group[i].unification) and (np.sign(x)-group[i].unification != 0): group[i].unification = np.sign(x) uni.append(group[i].unification) dynamics.append(uni) ar = np.array(dynamics) import csv fl = open(filename, 'w') writer = csv.writer(fl) for values in ar: writer.writerow(values) fl.close() plt.pcolor(ar) plt.savefig(picturename)
def sorted_heatmap(weights): """Create a sorted heatmap. Plot a matrix such that the biggest row/col values are in the upper left of the heatmap. Args: weights - a 2d numpy array of floats Returns: A plot that can be saved to a file via plt.savefig('file') """ weights = weights.reshape(weights.shape[:2]) row_order = np.array(sorted(weights, key=lambda row: np.sum(row))) col_order = np.array(sorted(row_order.T, key=lambda row: -np.sum(row))).T cMap = plt.get_cmap("Blues") fig1 = plt.figure(1) fig1.add_subplot(1, 1, 1) heatmap = plt.pcolor(col_order[:200, :200], cmap=cMap) plt.colorbar(heatmap) plt.title("Reviewer-Paper Affinities") plt.xlabel("Paper") plt.ylabel("Reviewer") fig2 = plt.figure(2) fig2.add_subplot(1, 1, 1) heatmap = plt.pcolor(col_order[-200:, -200:], cmap=cMap) plt.colorbar(heatmap) plt.title("Reviewer-Paper Affinities") plt.xlabel("Paper") plt.ylabel("Reviewer") return fig1, fig2
def produce_heatmap(model, every = True, save = False): col_label = range(28) row_label = range(28) if every: for i in range(10): plt.pcolor(np.flipud(model[i])) plt.xticks(col_label) plt.yticks(row_label) plt.axis('off') plt.title("HeatMap for %d" % (i)) cb = plt.colorbar() cb.set_label("Frequency") if save: plt.savefig('imgs/%d.png' % (i), bbox_inches='tight') else: plt.show() plt.close() else: plt.pcolor(np.flipud(model)) plt.xticks(col_label) plt.yticks(row_label) plt.axis('off') cb = plt.colorbar() cb.set_label("Frequency") if save: plt.savefig('imgs/temp.png', bbox_inches='tight') else: plt.show() plt.close()
def plot_array(array, title): '''Part 1: Plot an array using pcolor and title it''' plt.ylim(0, array.shape[0]) plt.xlim(0, array.shape[1]) plt.pcolor(array, vmin=0, vmax=1) # 1/up=red, 0/down=blue plt.title(title) plt.show()
def plot_epsilon_map(name,iteration,epsilons,epsilon_map,contacts,n_residues,individual=False): """ Get """ if iteration == 0: mineps = 0. maxeps = 2. if os.path.exists("%s/epsilon_range" % name): temp = np.loadtxt("%s/epsilon_range" % name) mineps = temp[0] maxeps = temp[1] else: mineps = 0 maxeps = max(epsilons) plt.pcolor(epsilon_map,cmap=new_map2,vmin=mineps,vmax=maxeps) cbar = plt.colorbar() cbar.set_clim(mineps,maxeps) plt.xticks(range(0,n_residues+1,10)) plt.yticks(range(0,n_residues+1,10)) if individual: plt.title("%s params after iteration %d" % (name,iteration)) plt.grid(True) plt.xlim(0,n_residues) plt.ylim(0,n_residues)
def plot_zvsz(z_phot, z_true, binning, z_min, z_max): plt.figure(figsize=(13, 7)) plt.subplot(121) plt.plot(z_true, z_phot, 'o', markersize = 1) plt.plot([z_min, z_max], [z_min, z_max], linewidth = 1, color = 'red') plt.axis('scaled') plt.xlim(xmin = z_min, xmax = z_max) plt.ylim(ymin = z_min, ymax = z_max) plt.xlabel("z(true)") plt.ylabel("z(phot)") plt.subplot(122) H = tool.migration_matrix(z_phot, z_true, binning) H = H.T plt.pcolor(binning, binning, H) plt.axis('scaled') plt.xlim(xmin = z_min, xmax = z_max) plt.ylim(ymin = z_min, ymax = z_max) plt.ylabel("z(phot)") plt.xlabel("z(true)") plt.title("Transition Matrix z(true)$\\rightarrow$z(phot)") #plt.colorbar(aspect = 30, orientation = 'horitzontal', fraction = 0.03).set_label("Probability") plt.colorbar(aspect = 30, fraction = 0.03).set_label("Probability") plt.savefig(plot_folder + "zvsz.png", bbox_inches='tight') #plt.savefig(plot_folder + "zvsz.pdf", bbox_inches='tight') plt.close()
def plotHeatmap(data, x_min, x_max, y_min, y_max, filename): """ Plot a heatmap. Args: Data: a 2D list of the data to be plotted x_min, y_min: the minimum coordinate of any data point x_max, y_max: the maximum coordinate any data point filename: where to save this image """ # Generate x and y lists x_points = numpy.linspace(x_min, x_max, len(data[0])) y_points = numpy.linspace(y_min, y_max, len(data)) x, y = numpy.meshgrid(x_points, y_points) # Plot heatmap fig = plt.figure() plt.pcolor(x, y, data, cmap=plt.cm.Blues) plt.axis([x_min, x_max, y_min, y_max]) plt.colorbar() plt.xlabel("Frequency / Hz") plt.ylabel("Y coordinate / mm") fig.savefig(filename, bbox_inches="tight")
def test_cartopy_projection(self): cube = iris.load_cube(tests.get_data_path(("PP", "aPPglob1", "global.pp"))) projections = {} projections["RotatedPole"] = ccrs.RotatedPole(pole_longitude=177.5, pole_latitude=37.5) projections["Robinson"] = ccrs.Robinson() projections["PlateCarree"] = ccrs.PlateCarree() projections["NorthPolarStereo"] = ccrs.NorthPolarStereo() projections["Orthographic"] = ccrs.Orthographic(central_longitude=-90, central_latitude=45) projections["InterruptedGoodeHomolosine"] = ccrs.InterruptedGoodeHomolosine() projections["LambertCylindrical"] = ccrs.LambertCylindrical() # Set up figure fig = plt.figure(figsize=(10, 10)) gs = matplotlib.gridspec.GridSpec(nrows=3, ncols=3, hspace=1.5, wspace=0.5) for subplot_spec, (name, target_proj) in itertools.izip(gs, projections.iteritems()): # Set up axes and title ax = plt.subplot(subplot_spec, frameon=False, projection=target_proj) ax.set_title(name) # Transform cube to target projection new_cube, extent = iris.analysis.cartography.project(cube, target_proj, nx=150, ny=150) # Plot plt.pcolor( new_cube.coord("projection_x_coordinate").points, new_cube.coord("projection_y_coordinate").points, new_cube.data, ) # Add coastlines ax.coastlines() # Tighten up layout gs.tight_layout(plt.gcf()) # Verify resulting plot self.check_graphic(tol=6e-4)
def dispPlot( org, bn, count, potential, mx = 0.1, mn = -0.1, title = '', xlab = r'$X \AA$', ylab = r'$Y \, (\AA)$', lege = '', outFile = None ): """Plots the colormap of potential plot, 2D""" fig = plt.figure(1, figsize = (3.5, 3.)) ax = fig.add_subplot(1,1,1) nbins = len(potential[0]) X = np.arange(org[0], org[0]+ nbins*bn[0], bn[0]) Y = np.arange(org[1], org[1]+ nbins*bn[1], bn[1]) big = max( abs(mn)-abs(0.1*mn), abs(mx)+abs(mx)*0.1) plt.pcolor(X, Y, potential, cmap = 'seismic_r', vmin=-big, vmax=big) plt.colorbar() ax.set_xlim([X[0], X[-1]]) ax.set_ylim([Y[0], Y[-1]]) ax.xaxis.labelpad = -1.4 ax.yaxis.labelpad = -1.4 plt.title(title, fontsize = 13); ax.set_ylabel(ylab, fontsize = 12); ax.set_xlabel(xlab, fontsize = 12) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(10) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(10) if outFile != None: plt.savefig(outFile,bbox_inches='tight', dpi = 300) plt.close()
def calculate_heatmap (path_to_file): print "CALCULATIN HEATMAP" f = open(path_to_file, "r") all_arrays = [] for line in f: array = re.split('\t',line) reads = np.genfromtxt(array) print reads # we want low distances red color in heatmap reads = [-1*read for read in reads] print reads all_arrays.append(reads) #output_0.2_-0.2_3000.0/paraHoxGenome324.txt # labels2 = ['GSX1','PDX1','CDX2','INS_CDX2','INS_GSX1'] # labels2 = ['hoxd3a','hoxd4a','hoxd10a','hoxd11a','hoxd13a'] # labels2 = ['AMHOX2','AMHOX5','AMHOX6','AMHOX9','AMHOX11','AMHOX13','AMHOX15'] #old anphioxus labels2 = ['GPATCH','LNPA','EVX2','Hox15','Hox13','Hox11','Hox9','Hox7', 'Hox6','Hox5','Hox2','MTX','CBX','NFE','MEOX',] ax = plt.subplot(2,1,1) z = np.array(all_arrays) plt.pcolor(z) # plt.set_cmap('gray') plt.colorbar() # c = plt.pcolor(z, edgecolors='w', linewidths=1) plt.axis([0,z.shape[1],0,z.shape[0]]) ax.set_yticklabels(['']+labels2) # plt.xlabel("Genomic Position") plt.show()
def draw(self): filename = self.filename file = open(os.getcwd() + "\\" + filename, 'r') lines = csv.reader(file) # data = [] x = [] y = [] z = [] for line in lines: try: data.append(line) except Exception as e: print e pass # print data for i in range(1, len(data)): try: x.append(float(data[i][0])) y.append(float(data[i][1])) z.append(float(data[i][3])) finally: pass xx = np.array(x) yy = np.array(y) zz = np.array(z) # print np.min(xx) tx = np.linspace(np.min(xx), np.max(xx), 100) ty = np.linspace(np.min(yy), np.max(yy), 100) XI, YI = np.meshgrid(tx, ty) rbf = interpolate.Rbf(xx, yy, zz, epsilon=2) ZI = rbf(XI, YI) # plt.gca().set_aspect(1.0) font = font_manager.FontProperties(family='times new roman', style='italic', size=16) cs = plt.contour(XI, YI, ZI, colors="black") plt.clabel(cs, cs.levels, inline=True, fontsize=10, prop=font) plt.subplot(1, 1, 1) plt.pcolor(XI, YI, ZI, cmap=cm.jet) plt.scatter(xx, yy, 100, zz, cmap=cm.jet) plt.title('interpolation example') plt.xlim(int(xx.min()), int(xx.max())) plt.ylim(int(yy.min()), int(yy.max())) plt.colorbar() plt.savefig("interpolation.jpg") #plt.show() return ZI, XI, YI
def _colormap_plot_array_response(cmaps): """ Plot for illustrating colormaps: array response. :param cmaps: list of :class:`~matplotlib.colors.Colormap` :rtype: None """ import matplotlib.pyplot as plt from obspy.signal.array_analysis import array_transff_wavenumber # generate array coordinates coords = np.array([[10., 60., 0.], [200., 50., 0.], [-120., 170., 0.], [-100., -150., 0.], [30., -220., 0.]]) # coordinates in km coords /= 1000. # set limits for wavenumber differences to analyze klim = 40. kxmin = -klim kxmax = klim kymin = -klim kymax = klim kstep = klim / 100. # compute transfer function as a function of wavenumber difference transff = array_transff_wavenumber(coords, klim, kstep, coordsys='xy') # plot for cmap in cmaps: plt.figure() plt.pcolor(np.arange(kxmin, kxmax + kstep * 1.1, kstep) - kstep / 2., np.arange(kymin, kymax + kstep * 1.1, kstep) - kstep / 2., transff.T, cmap=cmap) plt.colorbar() plt.clim(vmin=0., vmax=1.) plt.xlim(kxmin, kxmax) plt.ylim(kymin, kymax) plt.show()
def nearest(galaxies): midRA = 334.37 midDec = 0.2425 peakLimit = 3.077 #put the positions of all galaxies into one array positions = np.array([]) for gal in galaxies: galaxy = galaxies[gal] x = cmToMpc*DC(galaxy.z)*(galaxy.RA-midRA)*(np.pi/180.) y = cmToMpc*DC(galaxy.z)*(galaxy.dec-midDec)*(np.pi/180.) z = (cmToMpc*DC(galaxy.z)-cmToMpc*(DC(peakLimit))) positions = np.append(positions, [x, y, z]) positions = np.reshape(positions, (-1, 3)) #create the map to save the data nx = 100 ny = 100 xs = np.linspace(-8, 8, nx) yx = np.linspace(-8, 8, ny) map = np.zeros((nx, ny)) #loop through each of the positions in the map for ix in range(nx): for iy in range(ny): xpositions = positions[:,0] ypositions = positions[:,1] zpositions = positions[:,2] distances = np.sqrt((xpositions-xs[ix])**2+(ypositions-yx[iy])**2+(zpositions-peakLimit)**2) print(min(distances)) map[ix,iy] = 1/(min(distances)+10) plt.pcolor(map) plt.show()
def heatmap(df, cmap="OrRd", figsize=(10, 10)): """draw heatmap of df""" plt.figure(figsize=figsize) plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns) plt.yticks(np.arange(0.5, len(df.index), 1), df.index) plt.pcolor(df, cmap=cmap)
def test_2d_iterp(self): import numpy as np from scipy.interpolate import Rbf import matplotlib.pyplot as plt from matplotlib import cm # 2-d tests - setup scattered data x = np.random.rand(3) * 4.0 - 2.0 y = np.random.rand(3) * 4.0 - 2.0 z = x * np.exp(-x ** 2 - y ** 2) ti = np.linspace(-2.0, 2.0, 100) XI, YI = np.meshgrid(ti, ti) # use RBF rbf = Rbf(x, y, z, epsilon=2) ZI = rbf(XI, YI) # plot the result n = plt.Normalize(-2.0, 2.0) plt.subplot(1, 1, 1) plt.pcolor(XI, YI, ZI, cmap=cm.jet) plt.scatter(x, y, 100, z, cmap=cm.jet) plt.title("RBF interpolation - multiquadrics") plt.xlim(-2, 2) plt.ylim(-2, 2) plt.colorbar() plt.show()
def solve(m, computeRhs, bcs, plot = False, filename = ''): h = (1.0 - 0.0) / (m + 1.0) x = np.linspace(0, 1, m + 2) y = np.linspace(0, 1, m + 2) X, Y = np.meshgrid(x, y) matrix = getMatrix(m) f = computeRhs(X[1:-1, 1:-1], Y[1:-1, 1:-1], bcs, h) u = linalg.spsolve(matrix, f) u=u.reshape([m,m]) sol = np.zeros((m+2, m+2)) sol[1:-1, 1:-1] = u # Add boundary conditions values to solution. sol[:, 0] = bcs['left'](y) sol[:, -1] = bcs['right'](y) sol[0, :] = bcs['bottom'](x) sol[-1, :] = bcs['top'](x) # Plot solution. if plot: import matplotlib.pyplot as plt plt.clf() plt.pcolor(X,Y,sol) plt.colorbar() plt.xlabel(r'$x$') plt.ylabel(r'$y$') if filename: plt.savefig(filename) plt.show() return sol, X, Y
def show_heatmap(self, component): """ prints a quick simple heads up heatmap of input component of the mean_set attribute""" fig, ax = plt.subplots() plt.pcolor(self[component]) # see __getitem__ plt.colorbar() plt.title(component) plt.show()
def toImage(self,func): # do log print func func[func>self.para[1]] = np.log10(func[func>self.para[1]]) plt.pcolor(func,cmap = cm.cool) plt.colorbar() plt.show()
def plotOmittedFromGraph(graph, reference_slice, l = "not specified"): omitted = nodesOmitted(graph, reference_slice) omitted[reference_slice] = -1 reshape_parameter = int(ceil(sqrt(len(omitted)))) magic_number = reshape_parameter / 2. padding = ones(reshape_parameter ** 2 - len(omitted)) * .5 to_plot = concatenate([omitted, padding]).reshape((reshape_parameter, reshape_parameter)) * -1 ##setting variables for text annotations x = np.linspace(8./reshape_parameter, reshape_parameter - 8./reshape_parameter, reshape_parameter) y = np.linspace(10./reshape_parameter, reshape_parameter - 8./reshape_parameter, reshape_parameter) plt.figure() plt.title(str(l)) ax = plt.gca() ax.invert_yaxis() plt.pcolor(to_plot,cmap='PiYG') for i in range(reshape_parameter): for j in range(reshape_parameter): plt.text(x[i], y[j], str(i+j*reshape_parameter), color="white", horizontalalignment='center') plt.colorbar()
def calculate(self): global tmax, tmin, n, flag, route0, energy0, dist0, num_it tmax, tmin, flag, n, pack = 0, 0, 0, 0, 0 # считываем, запоминаем температуру try: tmin = round(float(self.num1_entry.get()), 2) tmax = round(float(self.num2_entry.get()), 2) if tmax <= tmin: showerror("Температура", 'Введите корректные значения(tmax>tmin)!') # очищаем поля для ввода self.num1_entry.delete('0', END) self.num2_entry.delete('0', END) tmax, tmin, flag = 0, 0, 0 # на тот случай, если решение повторно ищут, сброс else: flag = 1 # флаг чтобы матрица строилась только после всех правильных вводов. События # onChange или подобного не нашел, поэтому считывание значений с полей Entry # осуществляется по нажатию кнопки except ValueError: showerror("Температура", 'Неправильный формат ввода!') flag = 0 # на тот случай, если решение повторно ищут, сброс # очищаем поля для ввода. больше часа искал эти свойства :( self.num1_entry.delete('0', END) self.num2_entry.delete('0', END) # если температура считана, то считываем число ПК if flag == 1: try: n = int(self.numb_pc.get()) if n <= 1: showerror("Число ПК", 'Введите целое число ПК в сети >1!') self.numb_pc.delete('0', END) n = 0 flag = 1 # на тот случай, если решение повторно ищут, сброс else: flag = 2 except ValueError: showerror("Число ПК", 'Неправильный формат ввода!') flag = 1 # на тот случай, если решение повторно ищут, сброс self.numb_pc.delete('0', END) # если число ПК считано, то считываем объем входящего пакета if flag == 2: try: pack = round(float(self.package.get()), 2) if pack <= 0: showerror("Объем пакета", 'Введите объем входящего пакета >0!') self.package.delete('0', END) pack = 0 flag = 2 # на тот случай, если решение повторно ищут, сброс else: flag = 3 except ValueError: showerror("Объем пакета", 'Неправильный формат ввода!') flag = 2 # на тот случай, если решение повторно ищут, сброс self.package.delete('0', END) # если все входные данные считаны правильно, то создаем первое состояние системы, # а именно, рандомную матрицу стоимостей, начальный маршрут 1..n, считаем начальную энергию и # отображаем их в label'ах if flag == 3: route0, energy0, dist0 = makeS1(n, pack) #route0 self.route0['text'] = route0 #energy0 self.energy0['text'] = energy0 flag = 4 # график матрицы стоимостей до решения # plt.imshow(dist0, cmap='Blues') plt.axis([0, dist0.shape[0], dist0.shape[0], 0]) plt.pcolor(dist0) plt.colorbar() plt.clim(0, np.max(dist0)) fig1 = plt.gcf() # возвращает фигуру fig1.set_size_inches(7.7, 5.2) plt.savefig('D:\\sprite.png', format='png', dpi=50) plt.clf() # img2 = PhotoImage(file='D:\\sprite.png')#почему-то это не работает,хотя в случае с графиком энергии все ОК self.img2 = ImageTk.PhotoImage(Image.open('D:\\sprite.png')) self.distance0.create_image(0, 0, image=self.img2, anchor='nw')
except: tourlist_dic[country] = [num_m] for k, v in tourlist_dic.items(): tourlist_dic[k] = np.array(v) # 1月あたり消費 df = pd.read_csv(csvfile, index_col=0) df = df.dropna(axis=1) for country in df: if country != "インドネシア": # 消費額 arr = np.array(df[country]) map_array = np.array([arr[5:17], arr[17:29], arr[29:41]]) plt.subplot(2, 1, 1) plt.pcolor(map_array) plt.yticks([0.5, 1.5, 2.5], ["2013", "2014", "2015"]) plt.xticks([0.5 + i for i in range(0, 12)], range(1, 13)) plt.title(country + "(上:総消費額, 下:一人当たり消費)", fontproperties=fp) # 一人当たり sr_perone = df[country] / tourlist_dic[country] ar_perone = np.array(sr_perone) map_array = np.array( [ar_perone[5:17], ar_perone[17:29], ar_perone[29:41]]) plt.subplot(2, 1, 2) plt.pcolor(map_array) plt.yticks([0.5, 1.5, 2.5], ["2013", "2014", "2015"]) plt.xticks([0.5 + i for i in range(0, 12)], range(1, 13)) plt.show()
# -*- coding: utf-8 -*- """ Created on Wed Dec 14 10:28:56 2016 @author: jason """ data={'name':['Tim', 'Jim', 'Pam', 'Sam'], 'age': [29, 31, 27, 35], 'ZIP': ['02115','02130','67700','00100'] } import matplotlib.pyplot as plt plt.figure(figsize=(10,10)) plt.pcolor(corr_flavors) plt.colorbar() plt.savefig("corr_flavors.pdf") corr_whisky = pd.DataFrame.corr(flavors.transpose()) plt.figure(figsize=(10,10)) plt.pcolor(corr_whisky) plt.axis("tight") plt.colorbar() plt.savefig("corr_whisky.pdf") whisky["Group"] = pd.Series(model.row_labels_, index=whisky.index) whisky = whisky.ix[np.argsort(model.row_labels_)] whisky=whisky.reset_index(drop=True) plt.figure(figsize=(14,7)) plt.subplot(121) plt.pcolor(corr_whisky)
def post_process(X, Y, u, v, uinf): """ output flowfield quantities """ fig = plt.figure(figsize=(11, 7), dpi=100) plt.subplots_adjust(left=0.075, bottom=0.06, right=0.95, top=0.94, wspace=0.15) xStart = min(X[0, :]) yStart = min(Y[:, 0]) xEnd = max(X[0, :]) yEnd = max(Y[:, 0]) # velocity vectors bs = int(len(u) / 20) if bs < 1: bs = 1 print(bs) plt.subplot(3, 1, 2) levels = [ .99, ] CS3 = plt.contour(X, Y, np.sqrt(u * u + v * v + 1e-5) / uinf, levels, extend='both', cmap='copper') plt.clabel(CS3, inline=1, fontsize=14) plt.quiver(X[::bs, ::bs], Y[::bs, ::bs], u[::bs, ::bs], v[::bs, ::bs]) plt.title('Velocity Vectors and boundary layer thickness, $u = 0.99U_0$') plt.xlabel('X') plt.ylabel('Y') plt.xlim(xStart, xEnd) plt.ylim(yStart, yEnd) plt.subplot(3, 1, 1) #plt.pcolor(X, Y, np.sqrt(u*u+v*v+1e-5)/uinf, cmap='coolwarm') plt.pcolor(X, Y, np.sqrt(u * u + v * v + 1e-5) / uinf, cmap='gist_ncar') plt.colorbar(ticks=[0.0, 0.25, 0.5, 0.75, 1], orientation='horizontal') plt.title('Velocity Contours, $u/U_0$') plt.xlabel('X') plt.ylabel('Y') plt.xlim(xStart, xEnd) plt.ylim(yStart, yEnd) plt.subplot(3, 1, 3) plt.streamplot(X, Y, u, v, density=0.50, linewidth=1, arrowsize=1, arrowstyle='->') plt.title('Streamlines') plt.xlabel('X') plt.ylabel('Y') plt.xlim(xStart, xEnd) plt.ylim(yStart, yEnd) plt.show()
somSize, dataColuns, sigma=1, learning_rate=0.5, neighborhood_function='gaussian') som.pca_weights_init(data) print("Training...") som.train_batch(data, maxEpochs, verbose=True) # random training print("\n...ready!") plt.figure(figsize=(7, 7)) # Plotting the response for each pattern in the iris dataset plt.subplot(2, 1, 1) plt.pcolor(som.distance_map()) # plotting the distance map as background plt.title('Matriz - U') plt.colorbar() plt.subplot(2, 1, 2) frequencies = np.zeros((somSize, somSize)) for position, values in som.win_map(data).items(): frequencies[position[0], position[1]] = len(values) plt.title('Densidade de Dados') plt.pcolor(frequencies) plt.colorbar() ### Imprime mapa em relação aos pesos das colunas ''' headers = 'Nitrogênio Foliar (g/kg),Fósforo(P) (mg/dm³),Potássio(K) (cmol c/dm³),Boro(B) (mg/dm³),Cálcio(Ca) (cmol c/dm³),Magnésio(Mg) (cmol c/dm³),Alumínio(Al) (cmol c/dm³),Sódio(Na) (cmol c/dm³),H+Al (cmol c/dm³),Zinco(Zn) (mg/dm³),Cobre(Cu) (mg/dm³),Manganês(Mn) (mg/dm³),PRNT do calcário' feature_names = headers.split(',')
col = np.unique(col) col, row = np.meshgrid(col, row) v2 = np.squeeze(v2[vald, :]) v2 = v2[:, row, col] zi = zc[vald] lon = lon[row, col] lat = lat[row, col] idxlat = np.argmin(np.abs(((np.abs(lat[:, 0]) - 22)))) G, H = np.meshgrid(lon[idxlat, :], zi) plt.pcolor(G, -H, v2[:, idxlat, :]) plt.colorbar() plt.show() dx = np.diff(lon[idxlat, :], axis=0) * 111 * 1000 # valid only for low latitudes!!! aux = np.zeros([1]) aux[0] = dx[-1] dx = np.concatenate((dx, aux), axis=0) dz = abs(np.diff(zi, axis=0, append=0)) dx, dz = np.meshgrid(dx, dz) transp = np.abs(dx) * np.abs(dz) * v2[:, idxlat, :] transp = transp.sum() print(transp / 1e6) ###############year
plt.xlabel("Attribute Index") plt.ylabel("Quartile Ranges - Normalized") plt.show() # Seems like there are a lot of outliers. Check for class imbalance? print(pd.value_counts(glass['Type'].values)) # we see that there is some imbalance. So, there can be outliers. Also, we should definitely not expect all the data to be in a single group, else this won't be a multi-class classification problem. 76 for most populous to 9 for the least populous. # NO reason to expect proximity across classes - that's what makes this a multi-class classification problem. The average stats are dominated by the members of the most populous classes. # Ensemble methods will perform better here than PLM because ensemble methods can create complex decision boundaries. # Try the parralel coordinates plot? --> like in rocksVMines and using only normalized values. nrows = len(glass.index) for i in range(nrows): dataRow = glass_N.iloc[i, 1:ncol1-1] # in the book, they have not printed the final labels, but it is better to graphically show the labels as well, gives more accurate information. labelColor = glass.iloc[i, ncol1-1]/7.0 dataRow.plot(color=plt.cm.RdYlBu(labelColor), alpha=0.5) plt.xlabel("Attribute Index") plt.ylabel(("Attribute values")) plt.show() corMat = DataFrame(glass.iloc[:,1:-1].corr()) # 1st column is id column, hence neglecting that # last column is target label column, so neglect that plt.pcolor(corMat) plt.show() # Mostly blue in this heat map, hence low correlation. Attributes are thus independent of each other, which is good. Targets are not included in the heat map since they take discrete values and they rob the heat map of their explanatory powers. # From heat maps and parallel coordinates plot, we see that there seems to be some complicated boundary that separates these classes; ensemble methods will work better with more data here.
options={'disp': False}) if (f.fun < f_val): f_val = f.fun m = f.x # Estimate likelihood with Laplace approximation A = pot_hess(m) L = np.linalg.cholesky(A) half_log_det_A = np.sum(np.log(np.diag(L))) lap = -pot_value(m)[0] + lap_c1 - half_log_det_A like_values[i, j] = -lap - pot_value(xd)[0] except: None # If minimize fails set value to previous, otherwise update previous if like_values[i, j] == 0: like_values[i, j] = last_like else: last_like = like_values[i, j] # Output results idx = np.unravel_index(like_values.argmax(), like_values.shape) print("Fitted alpha and beta values:") print(XX[idx], YY[idx] * 2. / 1.4e6, like_values[idx]) np.savetxt("output/laplace_analysis" + str(theta[3]) + ".txt", like_values) plt.pcolor(XX, YY * 2. / 1.4e6, like_values) plt.xlim([np.min(XX), np.max(XX)]) plt.ylim([np.min(YY) * 2. / 1.4e6, np.max(YY) * 2. / 1.4e6]) plt.colorbar() plt.show()
def allele_plot(file, normalize=False, alleles=None, generations=None): """Plot the alleles from each generation from the individuals file. This function creates a plot of the individual allele values as they change through the generations. It creates three subplots, one for each of the best, median, and average individual. The best and median individuals are chosen using the fitness data for each generation. The average individual, on the other hand, is actually an individual created by averaging the alleles within a generation. This function requires the matplotlib library. .. note:: This function only works for single-objective problems. .. figure:: _static/allele_plot.png :alt: Example allele plot :align: center An example image saved from the ``allele_plot`` function. Arguments: - *file* -- a file-like object representing the individuals file produced by the file_observer - *normalize* -- Boolean value stating whether allele values should be normalized before plotting (default False) - *alleles* -- a list of allele index values that should be plotted (default None) - *generations* -- a list of generation numbers that should be plotted (default None) If *alleles* is ``None``, then all alleles are plotted. Similarly, if *generations* is ``None``, then all generations are plotted. """ import matplotlib.pyplot as plt generation_data = [] reader = csv.reader(open(file)) for row in reader: g = int(row[0]) row[3] = row[3].replace('[', '') row[-1] = row[-1].replace(']', '') individual = [float(r) for r in row[3:]] individual.append(float(row[2])) try: generation_data[g] except IndexError: generation_data.append([]) generation_data[g].append(individual) for gen in generation_data: gen.sort(key=lambda x: x[-1]) for j, g in enumerate(gen): gen[j] = g[:-1] best = [] median = [] average = [] for gen in generation_data: best.append(gen[0]) plen = len(gen) if plen % 2 == 1: med = gen[(plen - 1) // 2] else: med = [] for a, b in zip(gen[plen // 2 - 1], gen[plen // 2]): med.append(float(a + b) / 2) median.append(med) avg = [0] * len(gen[0]) for individual in gen: for i, allele in enumerate(individual): avg[i] += allele for i, a in enumerate(avg): avg[i] /= float(len(gen)) average.append(avg) for plot_num, (data, title) in enumerate( zip([best, median, average], ["Best", "Median", "Average"])): if alleles is None: alleles = list(range(len(data[0]))) if generations is None: generations = list(range(len(data))) if normalize: columns = list(zip(*data)) max_col = [max(c) for c in columns] min_col = [min(c) for c in columns] for dat in data: for i, d in enumerate(dat): dat[i] = (d - min_col[i]) / float(max_col[i] - min_col[i]) plot_data = [] for g in generations: plot_data.append([data[g][a] for a in alleles]) sub = plt.subplot(3, 1, plot_num + 1) plt.pcolor(plt.array(plot_data)) plt.colorbar() step_size = max(len(generations) // 7, 1) ytick_locs = list(range(step_size, len(generations), step_size)) ytick_labs = generations[step_size::step_size] plt.yticks(ytick_locs, ytick_labs) plt.ylabel('Generation') if plot_num == 2: xtick_locs = list(range(len(alleles))) xtick_labs = alleles plt.xticks(xtick_locs, xtick_labs) plt.xlabel('Allele') else: plt.setp(sub.get_xticklabels(), visible=False) plt.title(title) plt.show()
def solution(self): global tmax, tmin, n, flag, route0, dist0, energy0, energy_hist, img, num_it #если убрать img, то не будет графика для энергии #self.choose() #print(mode) mode = 1 if self.switch.get() == u'Линейный': mode = 1 if self.switch.get() == u'Коши': mode = 2 if self.switch.get() == u'Тушение': mode = 3 if self.switch.get() == u'Закон Больцмана': mode = 4 if self.switch.get() == u'Экспоненциальный': mode = 5 # try: # mode_tmp=copy.deepcopy(mode) # except NameError: # mode_tmp=1 print(mode) print(self.switch.get()) try: if flag == 4: # если все входные данные правильно введены и произведено решение # сам алгоритм решения #self.choose() #print(mode) # чтобы не нужно было пересчитывать матрицу стоимостей tmin = round(float(self.num1_entry.get()), 2) tmax = round(float(self.num2_entry.get()), 2) n = int(self.numb_pc.get()) pack = round(float(self.package.get()), 2) route, energy, num_it, energy_hist = make_new_state( tmin, tmax, n, route0, dist0, energy0, mode) self.route_end['text'] = route self.energy_end['text'] = energy self.number_iteration['text'] = num_it dist_end = copy.deepcopy(dist0) for i in range(dist0.shape[0]): for j in range(dist0.shape[1]): dist_end[i][j] = dist0[route[i] - 1][route[j] - 1] # цикл ниже делает на графике узнаваемым конечный маршрут shta = 0 for i in range(n - 1): dist_end[route[i] - 1][route[i + 1] - 1] = 2000 * n - 1000 * shta shta = shta + 1 # Строим диаграмму x = np.array([x for x in range(num_it + 1)]) #x[0]=0 # print(x) plt.plot(x, energy_hist, 'r-') # ro- с точками # Задаем интервалы значений по осям X и Y plt.axis( [0, num_it, min(energy_hist) - 20, max(energy_hist) + 20]) # Задаем заголовок диаграммы plt.title(u'Energy (iteration)') # Задаем подписи к осям X и Y plt.xlabel(u'Number of iteration') plt.ylabel(u'Energy') # Включаем сетку plt.grid() fig = plt.gcf() fig.set_size_inches(7.7, 5.2) plt.savefig('D:\\spirit.png', format='png', dpi=50) plt.clf() #img = PhotoImage(file='D:\\spirit.png')#вообще,в этом графике и так работает,но чтобы было одинаково... self.img1 = ImageTk.PhotoImage(Image.open('D:\\spirit.png')) self.energy.create_image(0, 0, image=self.img1, anchor='nw') # график матрицы стоимостей после решения #plt.imshow(dist0, cmap='Blues') plt.axis([0, dist0.shape[0], dist0.shape[0], 0]) plt.pcolor(dist_end) plt.colorbar() plt.clim(0, np.max(dist_end)) fig1 = plt.gcf() # возвращает фигуру fig1.set_size_inches(7.7, 5.2) plt.savefig('D:\\sprite2.png', format='png', dpi=50) plt.clf() # img2 = PhotoImage(file='D:\\sprite.png')#почему-то это не работает,хотя в случае с графиком энергии все ОК self.img3 = ImageTk.PhotoImage(Image.open('D:\\sprite2.png')) self.distance1.create_image(0, 0, image=self.img3, anchor='nw') else: showerror( 'Решение', 'Сначала введите начальные значение и постройте матрицу!') except NameError: showerror( 'Решение', 'Сначала введите начальные значение и постройте матрицу!')
import numpy as np from pandas import * Index= ['aaa','bbb','ccc','ddd','eee'] Cols = ['A', 'B', 'C','D'] df = DataFrame(abs(np.random.randn(5, 4)), index= Index, columns=Cols) print(df) import numpy as np from pandas import DataFrame import matplotlib.pyplot as plt plt.pcolor(df) plt.yticks(np.arange(0.5, len(df.index), 1), df.index) plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns) plt.show()
def test_func_and_derivative(): THETA_ORDER = 50 X_order = 100 s = PyballdDiscretization(X_order, r_h, THETA_ORDER, THETA_MIN, THETA_MAX, L=3 * r_h) R, THETA = s.get_coords_2d() X, THETA = s.get_x2d() f_ana = f(R, THETA) dfdr_ana = dfdr(R, THETA) dfdr_ana[-1] = 0 dfdrdtheta_ana = dfdrdtheta(R, THETA) dfdrdtheta_ana[-1] = 0 dfdr_num = s.differentiate_wrt_R(f_ana, 1, 0) dfdrdtheta_num = s.differentiate_wrt_R(f_ana, 1, 1) plt.plot(X[:, -1], s.dXdR[:, -1], lw=3) plt.xlabel(r'$X$', fontsize=16) plt.ylabel(r'$\partial_r X$', fontsize=16) for postfix in ['.png', '.pdf']: if USE_FIGS_DIR: name = 'figs/domain_dXdr' + postfix else: name = 'domain_dXdr' + postfix plt.savefig(name, bbox_inches='tight') plt.clf() plt.plot(X[:, -1], f_ana[:, -1], 'b-', lw=3) plt.xlabel(r'$X$', fontsize=16) plt.ylabel(TEST_FUNC_NAME, fontsize=16) for postfix in ['.png', '.pdf']: if USE_FIGS_DIR: name = 'figs/domain_test_function_alg' + postfix else: name = 'domain_test_function_alg' + postfix plt.savefig(name, bbox_inches='tight') plt.clf() mx, mz = np.sin(THETA) * R, np.cos(THETA) * R plt.pcolor(mx[:-1, :], mz[:-1, :], f_ana[:-1, :]) plt.xlabel('x', fontsize=16) plt.ylabel('y', fontsize=16) plt.xlim(0, 5) plt.ylim(0, 5) cb = plt.colorbar() cb.set_label(label=TEST_FUNC_NAME, fontsize=16) for postfix in ['.png', '.pdf']: if USE_FIGS_DIR: name = 'figs/domain_test_function_alg_2d' + postfix else: name = 'domain_test_function_alg_2d' + postfix plt.savefig(name, bbox_inches='tight') plt.clf() plt.plot(X[:, -1], dfdr_ana[:, -1], 'b-', lw=3, label='analytic') plt.plot(X[:, -1], dfdr_num[:, -1], 'ro', lw=3, label='numerical') plt.xlabel(r'$(r-r_h)/(1+r-r_h)$', fontsize=16) plt.ylabel(DR_TEST_FUNC_NAME, fontsize=16) plt.legend() for postfix in ['.png', '.pdf']: if USE_FIGS_DIR: name = 'figs/deriv_domain_test_function_alg' + postfix else: name = 'deriv_domain_test_function_alg' + postfix plt.savefig(name, bbox_inches='tight') plt.clf() plt.pcolor(mx[:-1, :], mz[:-1, :], dfdrdtheta_ana[:-1, :]) plt.xlabel('x', fontsize=16) plt.ylabel('y', fontsize=16) cb = plt.colorbar() plt.xlim(0, 5) plt.ylim(0, 5) cb.set_label(label=DR_DTHETA_TEST_FUNC_NAME, fontsize=16) for postfix in ['.png', '.pdf']: name = 'deriv_domain_test_function_alg_2d' + postfix if USE_FIGS_DIR: name = 'figs/' + name plt.savefig(name, bbox_inches='tight') plt.clf()
cdict = { 'red' : ( (0.0, 0.25, .25), (1., 1., 1.), (1., 1., 1.)), 'green': ( (0.0, 0.0, 0.0), (0.,0.,0.), (0., 0., 0.)), 'blue' : ( (0.0, 1.0, 1.0), (1., 1., 1.), (1., 0.45, 0.45)), } cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024) #%% pl.close('all') #%% """100 different amplitude square pulses""" data_100SP = np.load('Z:\Documents\\2018Kesätyö\Koodia\Tunable_qubits_data\Couplingalpha_0\squarepulse_100amplitudes_alpha0.npz') (TS,OS) = np.meshgrid(data_100SP['times'],s.omega[1]*(1-data_100SP['As'])) fidelplot = pl.figure() pl.pcolor(TS,OS,data_100SP['fidelities'],vmin=0,vmax=1) pl.colorbar() pl.title("Fidelity of the gate operation with a square pulse") pl.xlabel("Time (s)") pl.ylabel(r"$\omega_c$") """Calculating the theoretical and numerical optimum curves""" Ts = np.linspace(0.5e-8,5e-7,1000) As = np.zeros(1000) Tsaccur = np.linspace(1e-7,5e-7,100) Asaccur = np.zeros(100) for i in range(0,1000): As[i] = s.theoretical_pulse_amplitude(tcu.square_pulse,Ts[i],s.gef) for i in range(0,100): Asaccur[i] = s.theoretical_pulse_amplitude(tcu.square_pulse,Tsaccur[i],geffint) Os = abs(s.omega[1]*(1-As))
def main(train=True, test=True): # case name case_name = "unNACA0012_f_as_var" case_name_title = r'PIV stride $0.02 \times 0.02$ curlf as var' set_directory(case_name) x_data, y_data, u_data, v_data, p_data, uu_data, uv_data, vv_data, x_domain, y_domain = read_data( ) airfoil_points = read_airfoil("./Data/points_ok.dat") airfoil_array = np.array(airfoil_points) airfoil_array = rotate_points(airfoil_array[:, 0], airfoil_array[:, 1], 0.5, 0, -15 / 180 * math.pi) airfoil_points = airfoil_array.tolist() #domain vertices v_ld = [-0.3, -0.6] v_ru = [2.7, 0.6] figsize = (10, 10 * (v_ru[1] - v_ld[1]) / (v_ru[0] - v_ld[0])) figsize = (8, 3) Nx = int((v_ru[0] - v_ld[0]) * 500) + 1 Ny = int((v_ru[1] - v_ld[1]) * 500) + 1 print('Nx', Nx, 'Ny', Ny) # geometry specification geom1 = dde.geometry.Polygon(airfoil_points) geom2 = dde.geometry.Rectangle(v_ld, v_ru) geom = geom2 - geom1 [x_piv, y_piv, u_piv, v_piv, p_piv] = \ generate_PIV_points(x_data, y_data, u_data, v_data, p_data, 10, 10, v_ld, v_ru, geom, True) piv_points = np.hstack((x_piv, y_piv)) # BC specification # boundaries functions def boundary(x, on_boundary): return on_boundary and not (np.isclose(x[0], v_ld[0]) or np.isclose( x[0], v_ru[0]) or np.isclose(x[1], v_ld[1]) or np.isclose(x[1], v_ru[1])) def boundary_left_free(x, on_boundary): return on_boundary and (np.isclose(x[0], v_ld[0]) or (np.isclose(x[1], v_ru[1]) and x[0] <= -0.3) or (np.isclose(x[1], v_ld[1]) and x[0] <= -0.3)) def boundary_left_full(x, on_boundary): return on_boundary and not ( np.isclose(x[0], v_ru[0]) or (np.isclose(x[1], v_ru[1]) and x[0] > -0.3) or (np.isclose(x[1], v_ld[1]) and x[0] > -0.3)) # BC objects u_piv_points = dde.PointSetBC(piv_points, u_piv, component=0) v_piv_points = dde.PointSetBC(piv_points, v_piv, component=1) bc_wall_u = dde.DirichletBC(geom, func_zeros, boundary, component=0) bc_wall_v = dde.DirichletBC(geom, func_zeros, boundary, component=1) bc_wall_fx = dde.DirichletBC(geom, func_zeros, boundary, component=3) bc_wall_fy = dde.DirichletBC(geom, func_zeros, boundary, component=4) # custom domain points domain_points = generate_domain_points(x_domain, y_domain, geometry=geom) # pde and physics compilation pde = RANSf0var2D(500) if train: data = dde.data.PDE( geom, pde, [ bc_wall_u, bc_wall_v, bc_wall_fx, bc_wall_fy, u_piv_points, v_piv_points ], 100, 1600, solution=None, num_test=100, train_distribution="custom", custom_train_points=domain_points, ) plot_train_points(data, [2, 4, 5, 7], ["airfoil velocities", "forcing", "curl", "piv"], case_name, title=case_name_title, figsize=figsize) else: data = dde.data.PDE(geom, pde, [ bc_wall_u, bc_wall_v, bc_wall_fx, bc_wall_fy, u_piv_points, v_piv_points ], 100, 100, solution=None, num_test=100) # exit(0) # NN model definition layer_size = [2] + [100] * 7 + [6] activation = "tanh" initializer = "Glorot uniform" net = dde.maps.FNN(layer_size, activation, initializer) # PINN definition model = dde.Model(data, net) if train: # Adam optimization loss_weights = [1, 1, 1, 1, 1, 10, 10, 10, 10, 10, 10] model.compile("adam", lr=0.001, loss_weights=loss_weights) checkpointer = dde.callbacks.ModelCheckpoint( f"{case_name}/models/model_{case_name}.ckpt", verbose=1, save_better_only=True, ) loss_update = dde.callbacks.LossUpdateCheckpoint( momentum=0.7, verbose=1, period=1, report_period=100, base_range=[0, 1, 2, 3, 4], update_range=[5, 6, 7, 8, 9, 10]) print('Training for 20000 epochs') losshistory, train_state = model.train( epochs=20000, callbacks=[checkpointer, loss_update], display_every=100) model.save(f"{case_name}/models/model-adam-last") # L-BFGS-B optimization model.compile("L-BFGS-B", loss_weights=loss_weights) losshistory, train_state = model.train() model.save(f"{case_name}/models/model-bfgs-last") if test: model.compile("adam", lr=0.001) model.compile("L-BFGS-B") last_epoch = model.train_state.epoch if not train: last_epoch = 44115 model.restore(f"{case_name}/models/model-bfgs-last-{last_epoch}") x_plot = np.linspace(v_ld[0], v_ru[0], Nx) y_plot = np.linspace(v_ld[1], v_ru[1], Ny) # domain data x_data = x_data.reshape(1501, 601).T y_data = y_data.reshape(1501, 601).T u_data = u_data.reshape(1501, 601).T v_data = v_data.reshape(1501, 601).T p_data = p_data.reshape(1501, 601).T x_dom = np.linspace(-0.3, 2.7, 1501) y_dom = np.linspace(-0.6, 0.6, 601) x_min = np.argmin(np.abs(x_dom - v_ld[0])) x_max = np.argmin(np.abs(x_dom - v_ru[0])) y_min = np.argmin(np.abs(y_dom - v_ld[1])) y_max = np.argmin(np.abs(y_dom - v_ru[1])) print(x_min, x_max, y_min, y_max) x_data = x_data[y_min:y_max + 1, x_min:x_max + 1].T.reshape(-1, 1) y_data = y_data[y_min:y_max + 1, x_min:x_max + 1].T.reshape(-1, 1) u_data = u_data[y_min:y_max + 1, x_min:x_max + 1].T.reshape(-1, 1) v_data = v_data[y_min:y_max + 1, x_min:x_max + 1].T.reshape(-1, 1) p_data = p_data[y_min:y_max + 1, x_min:x_max + 1].T.reshape(-1, 1) z = np.array([np.array([i, j]) for i in x_plot for j in y_plot]) y = model.predict(z) u_star = y[:, 0][:, None] v_star = y[:, 1][:, None] p_star = y[:, 2][:, None] fx_star = y[:, 3][:, None] fy_star = y[:, 4][:, None] curl_f = y[:, 5][:, None] data_dict = { "u_star": u_star, "v_star": v_star, "p_star": p_star, "fx_star": fx_star, "fy_star": fy_star, "curlfvar_star": curl_f, } scipy.io.savemat(f"{case_name}/results.mat", data_dict) zero_index = (x_data < 0) & (x_data > 0) zero_index = zero_index | ((u_data == 0) & (v_data == 0)) no_data_index = zero_index u_star_data = deepcopy(u_star) v_star_data = deepcopy(v_star) p_star_data = deepcopy(p_star) fx_star_data = deepcopy(fx_star) fy_star_data = deepcopy(fy_star) curl_f_data = deepcopy(curl_f) u_star_data[no_data_index] = u_star[no_data_index] * 0 v_star_data[no_data_index] = v_star[no_data_index] * 0 p_star_data[no_data_index] = p_star[no_data_index] * 0 fx_star_data[no_data_index] = fx_star[no_data_index] * 0 fy_star_data[no_data_index] = fy_star[no_data_index] * 0 curl_f_data[no_data_index] = curl_f[no_data_index] * 0 u_star_data = u_star_data.reshape(Nx, Ny).T v_star_data = v_star_data.reshape(Nx, Ny).T p_star_data = p_star_data.reshape(Nx, Ny).T fx_star_data = fx_star_data.reshape(Nx, Ny).T fy_star_data = fy_star_data.reshape(Nx, Ny).T curl_f_data = curl_f_data.reshape(Nx, Ny).T X, Y = np.meshgrid(x_plot, y_plot) plt.figure(figsize=figsize) # plt.title(f'regressed u field for {case_name_title}') plt.pcolor(X, Y, u_star_data) plt.colorbar(label='u') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'u_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'regressed v field for {case_name_title}') plt.pcolor(X, Y, v_star_data) plt.colorbar(label='v') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'v_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'regressed p field for {case_name_title}') plt.pcolor(X, Y, p_star_data) plt.colorbar(label='p') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'p_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'regressed fx field for {case_name_title}') plt.pcolor(X, Y, fx_star_data) plt.colorbar(label='fx') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'fx_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'regressed fy field for {case_name_title}') plt.pcolor(X, Y, fy_star_data) plt.colorbar(label='fy') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'fy_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'regressed var curlf field for {case_name_title}') plt.pcolor(X, Y, -curl_f_data, vmin=-6.13125, vmax=6.26875) plt.colorbar(label=r"$\nabla \times \mathbf{f}$") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'curl_f_var_plot.png'), dpi=400) plt.close() # data error u_star_data = deepcopy(u_star) v_star_data = deepcopy(v_star) p_star_data = deepcopy(p_star) u_star_data[no_data_index] = u_star[no_data_index] * 0 v_star_data[no_data_index] = v_star[no_data_index] * 0 p_star_data[no_data_index] = p_star[no_data_index] * 0 u_star_data = u_star_data.reshape(Nx, Ny).T v_star_data = v_star_data.reshape(Nx, Ny).T p_star_data = p_star_data.reshape(Nx, Ny).T u_true = None v_true = None p_true = None u_true = deepcopy(u_data) v_true = deepcopy(v_data) p_true = deepcopy(p_data) u_true = u_true.reshape(Nx, Ny).T v_true = v_true.reshape(Nx, Ny).T p_true = p_true.reshape(Nx, Ny).T u_err = np.abs(u_true - u_star_data) v_err = np.abs(v_true - v_star_data) p_err = np.abs(p_true - p_star_data) plt.figure(figsize=figsize) # plt.title(f'u field abs error for {case_name_title}') plt.pcolor(X, Y, u_err) plt.colorbar(label='u') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'u_err_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'v field abs error for {case_name_title}') plt.pcolor(X, Y, v_err) plt.colorbar(label='v') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'v_err_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'p field abs error for {case_name_title}') plt.pcolor(X, Y, p_err) plt.colorbar(label='p') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'p_err_plot.png'), dpi=400) plt.close() e = model.predict(z, operator=pde) e_mass = e[0] e_u_momentum = e[1] e_v_momentum = e[2] f_divergence = e[3] f_curl_err = e[4] data_dict.update({ "e_mass": e_mass, "e_u_momentum": e_u_momentum, "e_v_momentum": e_v_momentum, "f_divergence": f_divergence, "fvarerr_residual": f_curl_err }) scipy.io.savemat(f"{case_name}/results.mat", data_dict) e_mass[no_data_index] = e_mass[no_data_index] * 0 e_u_momentum[no_data_index] = e_u_momentum[no_data_index] * 0 e_v_momentum[no_data_index] = e_v_momentum[no_data_index] * 0 f_divergence[no_data_index] = f_divergence[no_data_index] * 0 f_curl_err[no_data_index] = f_curl_err[no_data_index] * 0 e_mass = e_mass.reshape(Nx, Ny).T e_u_momentum = e_u_momentum.reshape(Nx, Ny).T e_v_momentum = e_v_momentum.reshape(Nx, Ny).T f_divergence = f_divergence.reshape(Nx, Ny).T f_curl_err = f_curl_err.reshape(Nx, Ny).T plt.figure(figsize=figsize) # plt.title(f'mass conservation residual for {case_name_title}') plt.pcolor(X, Y, e_mass, vmin=-1, vmax=1) plt.colorbar(label='e_mass') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'e_mass_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'u momentum conservation residual for {case_name_title}') plt.pcolor(X, Y, e_u_momentum, vmin=-1, vmax=1) plt.colorbar(label='e_u_momentum') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'e_u_momentum_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'v momentum conservation residual for {case_name_title}') plt.pcolor(X, Y, e_v_momentum, vmin=-1, vmax=1) plt.colorbar(label='e_v_momentum') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'e_v_momentum_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'fs divergence residual for {case_name_title}') plt.pcolor(X, Y, f_divergence, vmin=-1, vmax=1) plt.colorbar(label='f_divergence') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_divergence_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'f_curl equality residual for {case_name_title}') plt.pcolor(X, Y, f_curl_err, vmin=-1, vmax=1) plt.colorbar(label='f_curl err') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_eql_err_plot.png'), dpi=400) plt.close() def curl_f(X, V): dfsx_y = dde.grad.jacobian(V, X, i=3, j=1) dfsy_x = dde.grad.jacobian(V, X, i=4, j=0) return [dfsy_x - dfsx_y] e = model.predict(z, operator=curl_f) f_curl = e[0] data_dict.update({"f_curl_star": e[0]}) scipy.io.savemat(f"{case_name}/results.mat", data_dict) f_curl[no_data_index] = f_curl[no_data_index] * 0 f_curl = f_curl.reshape(Nx, Ny).T plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl) plt.colorbar(label='f_curl') plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl, vmin=-6.13125, vmax=6.26875) plt.colorbar(label=r"$\nabla \times \mathbf{f}$") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_plot_rescaled.png'), dpi=400) plt.close() def curl_f_alternative(X, V): u = V[:, 0:1] du_xy = dde.grad.hessian(u, X, i=0, j=1) du_yy = dde.grad.hessian(u, X, i=1, j=1) v = V[:, 1:2] dv_xx = dde.grad.hessian(v, X, i=0, j=0) dv_xy = dde.grad.hessian(v, X, i=0, j=1) du_y = dde.grad.jacobian(V, X, i=0, j=1) du_xxy = dde.grad.hessian(du_y, X, i=0, j=0) du_yyy = dde.grad.hessian(du_y, X, i=1, j=1) dv_x = dde.grad.jacobian(V, X, i=1, j=0) dv_xyy = dde.grad.hessian(dv_x, X, i=1, j=1) dv_xxx = dde.grad.hessian(dv_x, X, i=0, j=0) return [ -(u * du_xy + v * du_yy - 1 / 500 * (du_xxy + du_yyy)) + (u * dv_xx + v * dv_xy - 1 / 500 * (dv_xxx + dv_xyy)), -(u * du_xy + v * du_yy) + (u * dv_xx + v * dv_xy), (1 / 500 * (du_xxy + du_yyy)) - (1 / 500 * (dv_xxx + dv_xyy)) ] e = model.predict(z, operator=curl_f_alternative) f_curl_alt = e[0] f_curl_alt_1st = e[1] f_curl_alt_2nd = e[2] data_dict.update({ "curlfalt": f_curl_alt, "curlfalt1st": f_curl_alt_1st, "curlfalt2nd": f_curl_alt_2nd }) scipy.io.savemat(f"{case_name}/results.mat", data_dict) f_curl_alt[no_data_index] = f_curl_alt[no_data_index] * 0 f_curl_alt_1st[no_data_index] = f_curl_alt_1st[no_data_index] * 0 f_curl_alt_2nd[no_data_index] = f_curl_alt_2nd[no_data_index] * 0 f_curl_alt = f_curl_alt.reshape(Nx, Ny).T f_curl_alt_1st = f_curl_alt_1st.reshape(Nx, Ny).T f_curl_alt_2nd = f_curl_alt_2nd.reshape(Nx, Ny).T plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl_alt) plt.colorbar(label=r"$\nabla \times \mathbf{f}$ alt") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_alternative_plot.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl_alt, vmin=-6.13125, vmax=6.26875) plt.colorbar(label=r"$\nabla \times \mathbf{f}$ alt rescaled") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_alternative_plot_rescaled.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl_alt_1st) plt.colorbar(label=r"$\nabla \times \mathbf{f}$ alt 1st") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_alternative_plot_1st.png'), dpi=400) plt.close() plt.figure(figsize=figsize) # plt.title(f'curl fs for {case_name_title}') plt.pcolor(X, Y, f_curl_alt_2nd) plt.colorbar(label=r"$\nabla \times \mathbf{f}$ alt 2nd") plt.xlabel('x/c') plt.ylabel('y/c') plt.tight_layout() plt.savefig(os.path.join(f'{case_name}', 'plots', 'f_curl_alternative_plot_2nd.png'), dpi=400) plt.close() def u_derivatives(X, V): u = V[:, 0:1] du_xy = dde.grad.hessian(u, X, i=0, j=1) du_yy = dde.grad.hessian(u, X, i=1, j=1) v = V[:, 1:2] dv_xx = dde.grad.hessian(v, X, i=0, j=0) dv_xy = dde.grad.hessian(v, X, i=0, j=1) du_y = dde.grad.jacobian(V, X, i=0, j=1) du_x = dde.grad.jacobian(V, X, i=0, j=0) # du_xxy = dde.grad.hessian(du_y, X, i=0, j=0) # du_yyy = dde.grad.hessian(du_y, X, i=1, j=1) dv_x = dde.grad.jacobian(V, X, i=1, j=0) dv_y = dde.grad.jacobian(V, X, i=1, j=1) # dv_xyy = dde.grad.hessian(dv_x, X, i=1, j=1) # dv_xxx = dde.grad.hessian(dv_x, X, i=0, j=0) return [u, v, du_x, du_y, dv_x, dv_y, du_xy, du_yy, dv_xx, dv_xy] e = model.predict(z, operator=u_derivatives) u = e[0] v = e[1] du_x = e[2] du_y = e[3] dv_x = e[4] dv_y = e[5] du_xy = e[6] du_yy = e[7] dv_xx = e[8] dv_xy = e[9] data_dict = { "u": u, "v": v, "dux": du_x, "duy": du_y, "dvx": dv_x, "dvy": dv_y, "duxy": du_xy, "duyy": du_yy, "dvxx": dv_xx, "dvxy": dv_xy } scipy.io.savemat(f"{case_name}/velocity_and_derivatives.mat", data_dict)
print txts["companies"][sz] theNames.append(txts["companies"][sz]) #print datas.shape #print datas[0:10,1:].transpose() fig2 = plt.figure() fig2.add_axes([0.05,0.05,0.87,0.87],xticklabels=theNames, xticks=[1,2,3,4,5,6,7,8,9,10,11],yticklabels=theNames,yticks=[1,2,3,4,5,6,7,8,9,10,11], title="corr matrix (backwards time) 1/6/15 - 1/3/00 10 day sliding window") i=0 imgs=[] theRanges=np.arange(0,12) theY=np.arange(0,12) #print theRanges #print theY imgs.append((plt.pcolor(theRanges, theY, np.zeros((11,11)), norm=plt.Normalize(0, 1)),)) while i+10 <=3774: submat = datas[i:i+10,1:] i=i+1 awz=np.corrcoef(submat.transpose()) #print awz.shape imgs.append((plt.pcolor(theRanges, theY, awz*255, norm=plt.Normalize(0, 1)),)) imgs.append((plt.pcolor(theRanges, theY, np.zeros((11,11)), norm=plt.Normalize(0, 1)),)) im_ani = animation.ArtistAnimation(fig2, imgs, interval=150, repeat_delay=7000, blit=False) plt.colorbar() plt.show() im_ani.save('sample_tech_stock_animation.mp4', fps=10)
pdbref.xyz = t.xyz[index] rmsds = md.rmsd(t,pdbref,0) #for i in xrange(rmsds.shape[0]): # print(rmsds[i]) #index = np.argmin(rmsds) t.superpose(pdbref) #t.save_dcd('T0EG5_aligned.dcd') pdbref.save_pdb('average.pdb') nume = correlation_numpy(t.xyz*10, t.n_frames, t.n_atoms) print(np.amax(nume), np.amin(nume)) np.savetxt("covariance.dat",nume) plt.figure(1) nn = nume.shape[0] plt.pcolor(nume, cmap=plt.cm.seismic, vmin=-1, vmax=1) axes = plt.gca() axes.set_xlim([0,nn]) axes.set_ylim([0,nn]) # DEFINE LABELS RANGE # Residue 70 to 97, every 2 residues z = np.arange(70, 97, 2) labels = np.concatenate((z,z),axis=0) #z2 = np.arange(0, 27, 2) #z3 = np.arange(27, nn, 2) #x = np.concatenate((z2,z3),axis=0) #y = np.concatenate((z2,z3),axis=0) x=np.arange(0,nn,2) y=np.arange(0,nn,2) plt.xticks(x, labels, fontsize=9)# rotation='vertical')
xy = np.c_[xx.ravel(), yy.ravel()] # Create an output array of right dimensions. The values don't matter t = xy[:, 0].reshape(res, res) tt = t.reshape(-1) # Convert to 1D to make the loop easier... # For each X1,X2 pair, calculate the value using a linear model # The actual parameters here were rather unscientifically made up for index, val in enumerate(tt): tt[index] = 32. * index / (res * res) + 18. tt = tt.reshape(res, res) # Convert to 2D again # Now plot these values as a heatmap plt.pcolor(xspace, yspace, tt, cmap='jet') # then add the original datapoints on top as reference ax.scatter(x[:, 0], x[:, 1], s=100, c='w') plt.colorbar() # Label the axes to make the plot understandable ax.set_xlabel('x1 = Height (in)') ax.set_ylabel('x2 = Weight (lbs)') # Adjust the axis limits to remove unimportant areas ax.set_xlim(0, 80) ax.set_ylim(0, 100) # Save as an image file plt.savefig('plot_linreg2d.png')
#y: the known output, i.e. the density or speeds at those given markers #If y is a 2D array, each row corresponds to the output array at the given timestep def interpolate(x, y): plot_vals = [] for i in range(len(y)): pc = sc.PchipInterpolator(x, y[i]) plot_vals.append( pc([i / 10 for i in range(int(x[0] * 10), int(x[-1] * 10) + 1, 1)])) return plot_vals #Plots the density graph in the top left plt.subplot(2, 2, 1) density = interpolate(Marker_Miles, density_values) plt.pcolor(np.transpose(density)) plt.colorbar(label='Density') plt.ylabel('Mile Markers') #Plots the speed in the top right plt.subplot(2, 2, 2) speed_plot = interpolate(Marker_Miles, speed_values) plt.pcolor(np.transpose(speed_plot)) plt.colorbar(label='Speed') #Plots the flow in the bottom left plt.subplot(2, 2, 3) flow_plot = interpolate(Marker_Miles, flow_values) plt.pcolor(np.transpose(flow_plot)) plt.colorbar(label='Flow')
def showMap(blockedMap, targetData, strTitle, strColor, gamma): BORDER_LINES = [ [(3, 2), (5, 2), (5, 3), (9, 3), (9, 1)], # 인천 [(2, 5), (3, 5), (3, 4), (8, 4), (8, 7), (7, 7), (7, 9), (4, 9), (4, 7), (1, 7)], # 서울 [(1, 6), (1, 9), (3, 9), (3, 10), (8, 10), (8, 9), (9, 9), (9, 8), (10, 8), (10, 5), (9, 5), (9, 3)], # 경기도 [(9, 12), (9, 10), (8, 10)], # 강원도 [(10, 5), (11, 5), (11, 4), (12, 4), (12, 5), (13, 5), (13, 4), (14, 4), (14, 2)], # 충청남도 [(11, 5), (12, 5), (12, 6), (15, 6), (15, 7), (13, 7), (13, 8), (11, 8), (11, 9), (10, 9), (10, 8)], # 충청북도 [(14, 4), (15, 4), (15, 6)], # 대전시 [(14, 7), (14, 9), (13, 9), (13, 11), (13, 13)], # 경상북도 [(14, 8), (16, 8), (16, 10), (15, 10), (15, 11), (14, 11), (14, 12), (13, 12)], # 대구시 [(15, 11), (16, 11), (16, 13)], # 울산시 [(17, 1), (17, 3), (18, 3), (18, 6), (15, 6)], # 전라북도 [(19, 2), (19, 4), (21, 4), (21, 3), (22, 3), (22, 2), (19, 2)], # 광주시 [(18, 5), (20, 5), (20, 6)], # 전라남도 [(16, 9), (18, 9), (18, 8), (19, 8), (19, 9), (20, 9), (20, 10)], # 부산시 ] whitelabelmin = (max(blockedMap[targetData]) - min( blockedMap[targetData])) * 0.25 + min(blockedMap[targetData]) datalabel = targetData vmin = min(blockedMap[targetData]) vmax = max(blockedMap[targetData]) mapdata = blockedMap.pivot(index='y', columns='x', values=targetData) masked_mapdata = np.ma.masked_where(np.isnan(mapdata), mapdata) cmapname = strColor plt.figure(figsize=(8, 13)) plt.title(strTitle) plt.pcolor(masked_mapdata, vmin=vmin, vmax=vmax, cmap=cmapname, edgecolor='#aaaaaa', linewidth=0.5) for idx, row in blockedMap.iterrows(): annocolor = 'white' if row[targetData] > whitelabelmin else 'black' dispname = row['shortName'] # 서대문구, 서귀포시 같이 이름이 3자 이상인 경우에 작은 글자로 표시한다. if len(dispname.splitlines()[-1]) >= 3: fontsize, linespacing = 7.5, 1.5 else: fontsize, linespacing = 11, 1.2 plt.annotate(dispname, (row['x'] + 0.5, row['y'] + 0.5), weight='bold', fontsize=fontsize, ha='center', va='center', color=annocolor, linespacing=linespacing) for path in BORDER_LINES: ys, xs = zip(*path) plt.plot(xs, ys, c='black', lw=4) plt.gca().invert_yaxis() plt.axis('off') cb = plt.colorbar(shrink=.1, aspect=10) cb.set_label(targetData) plt.tight_layout() plt.show()
fig = plt.figure(figsize=(12, 8)) gs = gridspec.GridSpec( 2, 2, height_ratios=[4, 1], width_ratios=[20, 1], ) gs.update(wspace=0.05) ax = plt.subplot(gs[0]) x = dates.date2num([p.start_time for p in pr]) t = [datetime(2000, 1, 1, h, 0, 0) for h in range(24)] t.append(datetime(2000, 1, 2, 0, 0, 0)) y = dates.date2num(t) cm = plt.get_cmap('Oranges') plt.pcolor(x, y, hm.transpose().as_matrix(), cmap=cm) ### Now format our axes to be human-readable ax.xaxis.set_major_formatter(dates.DateFormatter('%b %Y')) ax.yaxis.set_major_formatter(dates.DateFormatter('%H:%M')) ax.set_yticks(t[::2]) ax.set_xticks(x[::12]) ax.set_xlim([x[0], x[-1]]) ax.set_ylim([t[0], t[-1]]) ax.tick_params(axis='x', pad=14, length=10, direction='inout') ### pcolor makes it sooo easy to add a color bar! plt.colorbar(cax=plt.subplot(gs[1])) plt.show()
def zview(var, tindex, depth, grid, filename=None, \ cmin=None, cmax=None, clev=None, clb_format='%.2f', \ fill=False, contour=False, d=4, range=None, fts=None, \ title=None, clb=True, pal=None, proj='merc', \ fill_land=False, outfile=None): """ map = zview(var, tindex, depth, grid, {optional switch}) optional switch: - filename if defined, load the variable from file - cmin set color minimum limit - cmax set color maximum limit - clev set the number of color step - fill use contourf instead of pcolor - contour overlay contour (request fill=True) - range set axis limit - fts set font size (default: 12) - title add title to the plot - clb add colorbar (defaul: True) - pal set color map (default: cm.jet) - proj set projection type (default: merc) - fill_land fill land masked area with gray (defaul: True) - outfile if defined, write figure to file plot a constant-z slice of variable var. If filename is provided, var must be a string and the variable will be load from the file. grid can be a grid object or a gridid. In the later case, the grid object correponding to the provided gridid will be loaded. If proj is not None, return a Basemap object to be used with quiver for example. """ # get grid if type(grid).__name__ == 'ROMS_Grid': grd = grid else: grd = pyroms.grid.get_ROMS_grid(grid) # get variable if filename == None: var = var else: data = pyroms.io.Dataset(filename) var = data.variables[var] Np, Mp, Lp = grd.vgrid.z_r[0, :].shape if tindex is not -1: assert len(var.shape) == 4, 'var must be 4D (time plus space).' K, N, M, L = var.shape else: assert len(var.shape) == 3, 'var must be 3D (no time dependency).' N, M, L = var.shape # determine where on the C-grid these variable lies if N == Np and M == Mp and L == Lp: Cpos = 'rho' mask = grd.hgrid.mask_rho if N == Np and M == Mp and L == Lp - 1: Cpos = 'u' mask = grd.hgrid.mask_u if N == Np and M == Mp - 1 and L == Lp: Cpos = 'v' mask = grd.hgrid.mask_v # get constante-z slice if tindex == -1: var = var[:, :, :] else: var = var[tindex, :, :, :] depth = -abs(depth) if fill == True: zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \ Cpos=Cpos) else: zslice, lon, lat = pyroms.tools.zslice(var, depth, grd, \ Cpos=Cpos, vert=True) # plot if cmin is None: cmin = zslice.min() else: cmin = float(cmin) if cmax is None: cmax = zslice.max() else: cmax = float(cmax) if clev is None: clev = 100. else: clev = float(clev) dc = (cmax - cmin) / clev vc = np.arange(cmin, cmax + dc, dc) if pal is None: pal = cm.jet else: pal = pal if fts is None: fts = 12 else: fts = fts #pal.set_over('w', 1.0) #pal.set_under('w', 1.0) #pal.set_bad('w', 1.0) pal_norm = colors.BoundaryNorm(vc, ncolors=256, clip=False) if range is None: lon_min = lon.min() lon_max = lon.max() lon_0 = (lon_min + lon_max) / 2. lat_min = lat.min() lat_max = lat.max() lat_0 = (lat_min + lat_max) / 2. else: lon_min = range[0] lon_max = range[1] lon_0 = (lon_min + lon_max) / 2. lat_min = range[2] lat_max = range[3] lat_0 = (lat_min + lat_max) / 2. # clear figure #plt.clf() if proj is not None: map = Basemap(projection=proj, llcrnrlon=lon_min, llcrnrlat=lat_min, \ urcrnrlon=lon_max, urcrnrlat=lat_max, lat_0=lat_0, lon_0=lon_0, \ resolution='h', area_thresh=5.) #map = pyroms.utility.get_grid_proj(grd, type=proj) x, y = map(lon, lat) if fill_land is True and proj is not None: # fill land and draw coastlines map.drawcoastlines() map.fillcontinents(color='grey') else: if proj is not None: Basemap.pcolor(map, x, y, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd, map) else: plt.pcolor(lon, lat, mask, vmin=-2, cmap=cm.gray) pyroms_toolbox.plot_coast_line(grd) if fill is True: if proj is not None: cf = Basemap.contourf(map, x, y, zslice, vc, cmap = pal, \ norm = pal_norm) else: cf = plt.contourf(lon, lat, zslice, vc, cmap = pal, \ norm = pal_norm) else: if proj is not None: cf = Basemap.pcolor(map, x, y, zslice, cmap=pal, norm=pal_norm) else: cf = plt.pcolor(lon, lat, zslice, cmap=pal, norm=pal_norm) if clb is True: clb = plt.colorbar(cf, fraction=0.075, format=clb_format) for t in clb.ax.get_yticklabels(): t.set_fontsize(fts) if contour is True: if fill is not True: raise Warning, 'Please run again with fill=True to overlay contour.' else: if proj is not None: Basemap.contour(map, x, y, zslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') else: plt.contour(lon, lat, zslice, vc[::d], colors='k', linewidths=0.5, linestyles='solid') if proj is None and range is not None: plt.axis(range) if title is not None: plt.title(title, fontsize=fts + 4) if proj is not None: map.drawmeridians(np.arange(lon_min,lon_max, (lon_max-lon_min)/5.001), \ labels=[0,0,0,1], fmt='%.1f') map.drawparallels(np.arange(lat_min,lat_max, (lat_max-lat_min)/5.001), \ labels=[1,0,0,0], fmt='%.1f') if outfile is not None: if outfile.find('.png') != -1 or outfile.find('.svg') != -1 or \ outfile.find('.eps') != -1: print 'Write figure to file', outfile plt.savefig(outfile, dpi=200, facecolor='w', edgecolor='w', \ orientation='portrait') else: print 'Unrecognized file extension. Please use .png, .svg or .eps file extension.' if proj is None: return else: return map
def draw_heatmap(data): data = np.array(data).T plt.pcolor(data, vmax=100.0, cmap=plt.cm.Blues)
def plot_source_spectrogram(stcs, freq_bins, tmin=None, tmax=None, source_index=None, colorbar=False, show=True): """Plot source power in time-freqency grid. Parameters ---------- stcs : list of SourceEstimate Source power for consecutive time windows, one SourceEstimate object should be provided for each frequency bin. freq_bins : list of tuples of float Start and end points of frequency bins of interest. tmin : float Minimum time instant to show. tmax : float Maximum time instant to show. source_index : int | None Index of source for which the spectrogram will be plotted. If None, the source with the largest activation will be selected. colorbar : bool If true, a colorbar will be added to the plot. show : bool Show figure if True. """ import matplotlib.pyplot as plt # Input checks if len(stcs) == 0: raise ValueError('cannot plot spectrogram if len(stcs) == 0') stc = stcs[0] if tmin is not None and tmin < stc.times[0]: raise ValueError('tmin cannot be smaller than the first time point ' 'provided in stcs') if tmax is not None and tmax > stc.times[-1] + stc.tstep: raise ValueError('tmax cannot be larger than the sum of the last time ' 'point and the time step, which are provided in stcs') # Preparing time-frequency cell boundaries for plotting if tmin is None: tmin = stc.times[0] if tmax is None: tmax = stc.times[-1] + stc.tstep time_bounds = np.arange(tmin, tmax + stc.tstep, stc.tstep) freq_bounds = sorted(set(np.ravel(freq_bins))) freq_ticks = copy.deepcopy(freq_bounds) # Rejecting time points that will not be plotted for stc in stcs: # Using 1e-10 to improve numerical stability stc.crop(tmin - 1e-10, tmax - stc.tstep + 1e-10) # Gathering results for each time window source_power = np.array([stc.data for stc in stcs]) # Finding the source with maximum source power if source_index is None: source_index = np.unravel_index(source_power.argmax(), source_power.shape)[1] # If there is a gap in the frequency bins record its locations so that it # can be covered with a gray horizontal bar gap_bounds = [] for i in range(len(freq_bins) - 1): lower_bound = freq_bins[i][1] upper_bound = freq_bins[i + 1][0] if lower_bound != upper_bound: freq_bounds.remove(lower_bound) gap_bounds.append((lower_bound, upper_bound)) # Preparing time-frequency grid for plotting time_grid, freq_grid = np.meshgrid(time_bounds, freq_bounds) # Plotting the results fig = plt.figure(figsize=(9, 6)) plt.pcolor(time_grid, freq_grid, source_power[:, source_index, :], cmap='Reds') ax = plt.gca() plt.title('Time-frequency source power') plt.xlabel('Time (s)') plt.ylabel('Frequency (Hz)') time_tick_labels = [str(np.round(t, 2)) for t in time_bounds] n_skip = 1 + len(time_bounds) // 10 for i in range(len(time_bounds)): if i % n_skip != 0: time_tick_labels[i] = '' ax.set_xticks(time_bounds) ax.set_xticklabels(time_tick_labels) plt.xlim(time_bounds[0], time_bounds[-1]) plt.yscale('log') ax.set_yticks(freq_ticks) ax.set_yticklabels([np.round(freq, 2) for freq in freq_ticks]) plt.ylim(freq_bounds[0], freq_bounds[-1]) plt.grid(True, ls='-') if colorbar: plt.colorbar() tight_layout(fig=fig) # Covering frequency gaps with horizontal bars for lower_bound, upper_bound in gap_bounds: plt.barh(lower_bound, time_bounds[-1] - time_bounds[0], upper_bound - lower_bound, time_bounds[0], color='#666666') if show: plt.show() return fig
ikp[i, :], ikmap[i, 0] = IndicatorKriging(xcoords[i, :], dcoords, df, nf, pprior, l, krigtype) ikp = np.reshape(ikp, (X.shape[0], X.shape[1], nf)) ikmap = np.reshape(ikmap, (X.shape[0], X.shape[1])) # Sequential Indicator Simulation nsim = 3 sisim = np.zeros((X.shape[0], X.shape[1], nsim)) for i in range(nsim): sim = SeqIndicatorSimulation(xcoords, dcoords, df, nf, pprior, l, krigtype) sisim[:, :, i] = np.reshape(sim, (X.shape[0], X.shape[1])) # # plot results plt.figure(4) plt.subplot(221) plt.pcolor(X, Y, ikp[:, :, 0]) plt.xlabel('X') plt.ylabel('Y') cbar = plt.colorbar() cbar.set_label('Probability valleys', rotation=270) plt.title('Indicator Kriging Probability of facies 0') plt.subplot(222) plt.pcolor(X, Y, ikmap) plt.xlabel('X') plt.ylabel('Y') cbar = plt.colorbar() cbar.set_label('Peaks Valleys', rotation=270) plt.title('Indicator Kriging most likely facies') plt.subplot(223) plt.pcolor(X, Y, sisim[:, :, 0]) plt.xlabel('X')
def test_autoscale_masked(): # Test for #2336. Previously fully masked data would trigger a ValueError. data = np.ma.masked_all((12, 20)) plt.pcolor(data) plt.draw()
# creation of a profile array to use it with pcolor. same dimension of temp and depth [nline, ncol] = shape(tempCruise) sizer = ones((nline, 1), 'float') profileIndex = list(range(ncol)) prof_2D = sizer * profileIndex ##### creation of the plots figure1 = figure(num=None, figsize=(15, 10), dpi=80, facecolor='w', edgecolor='k') # Profile timeseries subplot(311) pcolor(prof_2D, -depthCruise, tempCruise) cbar = colorbar() cbar.ax.set_ylabel(TEMP.long_name + ' in ' + TEMP.units) title(xbt_DATA.title + '\n Cruise ' + cruiseToPlot + '-' + xbt_DATA.XBT_line_description) xlabel('Profile Index') ylabel(DEPTH.long_name + ' in negative ' + DEPTH.units) #plot the LON timesexbt_DATAries ax3 = subplot(234) plot(profileIndex, lonCruise) xlabel('Profile Index') ylabel(xbt_DATA.variables['LONGITUDE'].long_name + ' in ' + xbt_DATA.variables['LONGITUDE'].units) #plot the LAT timeseries
print("Ray generation took {:.3f} seconds on MPI task {:d}".format( raygen_end - raygen_start)) print("That's {:.3e} seconds per ray on this MPI task".format( (raygen_end - raygen_start) / (end_index - start_index))) if comm.rank == 0: plt.figure() # sets up the plot as an Aitoff projection plt.subplot(111, projection="aitoff") # Convert to log scale logH_I = np.log10(H_I + 10.0**-20.0) # Aitoff projection using pcolor plt.pcolor(x, y, logH_I, cmap='plasma') #, vmin=12.5, vmax=21.5) cbar = plt.colorbar(pad=0.02, shrink=0.55) cbar.ax.tick_params(labelsize=6) cbar.set_label(r'log N$_{HI}$ [cm$^{-2}$]', size=8) plt.title(str(ds) + " HI Column Density", y=1.05, size=10) plt.grid(True, alpha=0.5) plt.xticks(fontsize=7) plt.yticks(fontsize=7) plt.savefig('HI_aitoff_' + str(ds) + '.png', bbox_inches='tight', dpi=400) plt.clf() # sets up the plot as an Aitoff projection plt.subplot(111, projection="aitoff") # Convert to log scale
t0 = time.time() ar = view.apply_async(_solve, tstop, dt=0, verbose=True, final_test=final_test, user_action=user_action) if final_test: # this sum is performed element-wise as results finish s = sum(ar) # the L2 norm (RMS) of the result: norm = sqrt(s / num_cells) else: norm = -1 t1 = time.time() print 'vector inner-version, Wtime=%g, norm=%g' % (t1 - t0, norm) # if ns.save is True, then u_hist stores the history of u as a list # If the partion scheme is Nx1, then u can be reconstructed via 'gather': if ns.save and partition[-1] == 1: import matplotlib.pyplot as plt view.execute('u_last=u_hist[-1]') # map mpi IDs to IPython IDs, which may not match ranks = view['my_id'] targets = range(len(ranks)) for idx in range(len(ranks)): targets[idx] = ranks.index(idx) u_last = rc[targets].gather('u_last', block=True) plt.pcolor(u_last) plt.show()
def write_plots(frames, fit_parameters, jitter, directory, peak_strain, dt, min_strain=-0.1, max_strain=0.3): # draw residual plots for each sine fit in x and y t = np.arange(len(frames)) * dt fit = lambda t, sf: sf.eval(t) # TODO show phase for each regression # plot the sine fits first for idot in xrange(len(frames[0])): actual_x = [frame[idot].xpos for frame in frames] actual_y = [frame[idot].ypos for frame in frames] fit_x, fit_y = fit_parameters[idot] plt.clf() plt.plot(t, actual_x, 'b.', t, fit(t, fit_x), 'b-') plt.plot(t, actual_y, 'r.', t, fit(t, fit_y), 'r-') plt.title('Dot %d' % idot) plt.xlabel('Time (s)') plt.ylabel('Displacement (px)') # plt.legend(['in X', 'fit in X', 'in Y', 'fit in Y']) axes = plt.gca() axes.text( 0.95, 0.5, (r'x: $%.2f sin(\frac{2 \pi}{%.2f} t + %.2f) + %.2f$; $R^2=%.4f$' '\n' r'y: $%.2f sin(\frac{2 \pi}{%.2f} t + %.2f) + %.2f$; $R^2=%.4f$' % (fit_x.amplitude, fit_x.period, fit_x.phase, fit_x.offset, fit_x.r2, fit_y.amplitude, fit_y.period, fit_y.phase, fit_y.offset, fit_y.r2)), verticalalignment='center', horizontalalignment='right', transform=axes.transAxes) plt.savefig('%s/dot_%04d_fit.png' % (directory, idot)) # plot the resting and extended coordinates (center_x, center_y, resting_x, resting_y, extended_x, extended_y) = process_coordinates(fit_parameters) plt.clf() plt.axis([ min(extended_x + resting_x) - 50, max(extended_x + resting_x) + 50, max(extended_y + resting_y) + 50, min(extended_y + resting_y) - 50 ]) plt.quiver(resting_x, resting_y, [ext - rest for (ext, rest) in zip(extended_x, resting_x)], [ext - rest for (ext, rest) in zip(extended_y, resting_y)], units='xy', angles='xy', scale=1.0) plt.savefig('%s/coordinates.png' % directory) # plot coordinate system jitter plt.clf() plt.plot(t, jitter[0], t, jitter[1]) plt.legend(['x', 'y']) plt.savefig('%s/center_displacement.png' % directory) plt.clf() center_by_frame = find_center_by_frame(frames) plt.plot(t, zip(*center_by_frame)[0], t, zip(*center_by_frame)[1]) plt.savefig('%s/center_position_post.png' % directory) n = int(sqrt(len(fit_parameters))) min_strain = min_strain or min(peak_strain[0] + peak_strain[1]) max_strain = max_strain or max(peak_strain[0] + peak_strain[1]) matrix = lambda axis: np.array(peak_strain[axis]).reshape(n, n) for (axis, label) in [(0, 'x'), (1, 'y')]: plt.clf() plt.pcolor(matrix(axis), edgecolor='k', vmin=min_strain, vmax=max_strain) for i in range(n): for j in range(n): plt.text(i + 0.5, j + 0.5, "%.4f" % matrix(axis)[j, i], horizontalalignment='center', verticalalignment='center') ax = plt.gca() ax.set_ylim(ax.get_ylim()[::-1]) plt.colorbar(ticks=[-.05, 0, .05, .1, .15, .2, .25]) plt.savefig('%s/peakstrain_%s.png' % (directory, label)) f = open('%s/index.html' % directory, 'w') print >> f, "<!DOCTYPE html>\n<html><head><title>Regression results</title></head><body>" print >> f, '<h1>Dot positions</h1><img src="coordinates.png" />' print >> f, ('<h1>Center displacement (pre-correction)</h1>' '<img src="center_displacement.png" />') print >> f, ('<h1>Center position (post-correction)</h1>' '<img src="center_position_post.png" />') print >> f, ('<h1>Peak strain: x</h1>' '<img src="peakstrain_x.png" />' '<p>Mean peak x strain: %f Standard deviation: %f</p>' % (np.mean(peak_strain[0]), np.std(peak_strain[0]))) print >> f, ('<h1>Peak strain: y</h1>' '<img src="peakstrain_y.png" />' '<p>Mean peak y strain: %f Standard deviation: %f</p>' % (np.mean(peak_strain[1]), np.std(peak_strain[1]))) for idot in xrange(len(frames[0])): print >> f, '<h1>Dot %d</h1><img src="dot_%04d_fit.png" />' % (idot, idot) print >> f, '</body></html>' f.close()
def plot_averaged_diags_over_Africa(omega_data_set_vo, z_data, diags_set_vo): #extract Hadley and Walker over Africa and average it maxFlux = 5 * 10**-3 minFlux = -maxFlux massFlux_lambda = diags_set_vo['massFlux_lambda'] massFlux_teta = diags_set_vo['massFlux_teta'] omega_lambda = diags_set_vo['omega_lambda'] omega_teta = diags_set_vo['omega_teta'] psi_lambda = diags_set_vo['psi_lambda'] psi_teta = diags_set_vo['psi_teta'] fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(25, 10)) #extract range over Africa only #because era lon starts from 0 we have to do the logical or ind = np.logical_or(omega_data_set_vo.lonData >= 360 - 20, omega_data_set_vo.lonData <= 60) currentMassFlux = np.nanmean(massFlux_lambda[:, :, ind], axis=2) # currentOmega = np.nanmean(omega_lambda[:, :, ind], axis=2) currentPsiLambda = np.nanmean(psi_lambda[:, :, ind], axis=2) currentZ = np.nanmean(z_data[:, :, ind], axis=2) currentZ = np.nanmean(currentZ, axis=1) # ind = np.logical_or(vDataSetVO.lonData >= 360-20, vDataSetVO.lonData <= 60) # currentV = np.nanmean(vDataSetVO.fieldData[:, :, ind], axis=2) # ind = np.logical_or(zDataSetVO.lonData >= 360-20, zDataSetVO.lonData <= 60) ax = axes[0] plt.sca(ax) pcolorHandle = plt.pcolor(omega_data_set_vo.latData, currentZ, currentMassFlux, cmap='bwr', vmin=minFlux, vmax=maxFlux) plt.colorbar(pcolorHandle) #pl.quiver(vDataSetVO.latData, vDataSetVO.levelsData, currentV, currentOmega) #draw zero mass flux contour # plotHandle = pl.contour(eraDataSetVO.latData, currentZ, currentMassFlux, levels = [0], colors='k',vmin=minFlux, vmax=maxFlux) #draw psi contours contourHandle = plt.contour(omega_data_set_vo.latData, currentZ, currentPsiLambda, linewidths=3) plt.colorbar(contourHandle, label='psi contour lines') #pl.gca().invert_yaxis() yLoc = currentZ[::2] yTicks = omega_data_set_vo.levelsData[::2] plt.yticks(yLoc, yTicks) # plt.ylim(currentZ[-1], currentZ[10]) plt.xlabel('latitude') plt.ylabel('pressure (hPa)') plt.title('$m_{\lambda}$') ax = axes[1] plt.sca(ax) #extact only 35S to 10 N equatorial belt ind = np.logical_and(omega_data_set_vo.latData >= -35, omega_data_set_vo.latData <= 10) currentData = np.nanmean(massFlux_teta[:, ind, :], axis=1) # ind = np.logical_and(zDataSetVO.latData >= -35, zDataSetVO.latData <= 10) currentZ = np.nanmean(z_data[:, :, ind], axis=2) currentZ = np.nanmean(currentZ, axis=1) currentPsiTeta = np.nanmean(psi_teta[:, ind, :], axis=1) pcolorHandle = plt.pcolor(omega_data_set_vo.lonData, currentZ, currentData, cmap='bwr', vmin=minFlux, vmax=maxFlux) plt.colorbar(pcolorHandle) #draw zero mass flux contour # plotHandle = pl.contour(eraDataSetVO.lonData, currentZ, currentData, levels = [0], colors='k',vmin=minFlux, vmax=maxFlux) #draw psi contours contourHandle = plt.contour(omega_data_set_vo.lonData, currentZ, currentPsiTeta, linewidths=3) plt.colorbar(contourHandle, label='psi contour lines') yLoc = currentZ[::2] yTicks = omega_data_set_vo.levelsData[::2] plt.yticks(yLoc, yTicks) # plt.ylim(currentZ[-1], currentZ[10]) plt.xlabel('longitude') plt.ylabel('pressure (hPa)') plt.title('$m_{\\theta}$') plt.tight_layout() plt.subplots_adjust(top=0.92, wspace=0.1) plt.suptitle('Hadley (20E-60W) & Walker (35S-10N)', fontsize=24)