def plot_dp(storm, datafile1, datafile2=None): #Single file netCDF reading ncf=datafile1 nco=netCDF4.Dataset(ncf) #Get fields to plot lon=nco.variables['longitude'][:] lat=nco.variables['latitude'][:] timeindays=nco.variables['time'][:] dp=nco.variables['dp'][:] triangles=nco.variables['tri'][:,:] reflon=np.linspace(lon.min(),lon.max(),1000) reflat=np.linspace(lat.min(),lat.max(),1000) #reflon=np.linspace(-80.40, -74.75, 1000) #reflat=np.linspace(32.50, 36.60, 1000) #reflon=np.linspace(-75.70, -71.05, 1000) #reflat=np.linspace(38.50, 41.40, 1000) reflon,reflat=np.meshgrid(reflon,reflat) plt.figure(figsize = [6.4, 3.8]) flatness=0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles=triangles-1 # Correct indices for Python's zero-base tri=Triangulation(lon,lat,triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeindays)): plt.clf() ax = plt.axes(projection=ccrs.Mercator()) dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind]) dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S') dstr = dstr[0:8]+' '+dstr[8:17] print('Plotting '+dstr) par=np.double(dp[ind,:]) tli=LinearTriInterpolator(tri,par) par_interp=tli(reflon,reflat) plt.pcolormesh(reflon,reflat,par_interp,vmin=0.0,vmax=360.0,shading='flat',cmap=plt.cm.jet, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) coast = cfeature.GSHHSFeature(scale='high',edgecolor='black',facecolor='none',linewidth=0.25) ax.add_feature(coast) plt.xticks(fontsize=9) plt.yticks(fontsize=9) figtitle = storm.capitalize()+': Peak Dir (deg): '+dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S') dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14] filenm = 'nsem_'+storm+'_dp_'+dtlabel+'.png' plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.1) del(par) del(par_interp)
def plot_trisurf(data, out=None, ax=None, angles=None): if ax is None: fig = plt.figure() ax = fig.gca(projection='3d') Xs, Ys = np.meshgrid(data.coords[data.dims[0]].values, data.coords[data.dims[1]].values) triang = Triangulation(Xs.ravel(), Ys.ravel()) mask = np.any(np.isnan(data.transpose().values.ravel()[triang.triangles]), axis=1) triang.set_mask(mask) values = data.copy(deep=True).transpose().values values[np.isnan(values)] = 0 ax.plot_trisurf(triang, values.ravel(), antialiased=True, cmap=cm.coolwarm, linewidth=0) if angles is not None: ax.view_init(*angles) #plt.show() return ax
def mesh_tri(grid_file): ncmesh = Dataset(grid_file,'r') lon_mesh = np.rad2deg(ncmesh.variables['lonCell'][:])-360.0 #lon_mesh = np.rad2deg(np.mod(ncmesh.variables['lonCell'][:] + np.pi, 2.0*np.pi) - np.pi) lat_mesh = np.rad2deg(ncmesh.variables['latCell'][:]) nEdgesOnCell = ncmesh.variables['nEdgesOnCell'][:] cellsOnCell = ncmesh.variables['cellsOnCell'][:,:] # Triangulate cells triangles = Triangulation(lon_mesh,lat_mesh) # Compute triangulation mask (needs to be vectorized) mask = np.array(np.zeros((triangles.triangles.shape[0],)),dtype=bool) ntri = triangles.neighbors.shape[0] for i in range(ntri): k = 0 for j in range(3): n = triangles.triangles[i,j] if nEdgesOnCell[n] != np.where(cellsOnCell[n,:] != 0)[0].size: # Mask triangles k = k +1 # containing if k == 3: # 3 boundary mask[i] = True # cells triangles.set_mask(mask) return triangles
def plot(self, variable, show=False, index=None): if index is None: self.animation( variable, # show=True, save='/home/jreniel/pyschism/examples/example_1/test.gif', vmin=0, vmax=3, # start_frame=200, # end_frame=300, ) else: var = self.nc[variable] ugrid = UGrid.from_nc_dataset(self.nc) x = ugrid.nodes[:, 0] y = ugrid.nodes[:, 1] triangulation = Triangulation(x, y, ugrid.faces[:, :3]) triangulation.set_mask(self.nc['wetdry_elem'][index]) plt.tricontourf(triangulation, var[index, :], levels=256, cmap='jet') plt.gca().axis('scaled') if show: plt.show()
def buildTriangulation( self, x, y ): trig=None if qgis_qhull_fails: trig=self._buildtrig_workaround(x,y) else: trig=Triangulation(x,y) analyzer=TriAnalyzer(trig) mask=analyzer.get_flat_tri_mask() trig.set_mask(mask) return trig
def makeTri(projx, projy, max_l): tri = Triangulation(projx, projy) triangles = tri.triangles # Mask off unwanted triangles. xtri = projx[triangles] - np.roll(projx[triangles], 1, axis=1) ytri = projy[triangles] - np.roll(projy[triangles], 1, axis=1) ds = np.sqrt(xtri**2 + ytri**2) maxi = np.max(ds, axis=1) tdist = np.mean(ds) tri.set_mask(maxi > max_l) return tri, tdist
def generate_triangles( topology, geometry, mask: Optional[Sequence[bool]] = None ) -> Triangulation: """Convert topology and geometry to triangles - optionally set mask as well. :param topology: Topology of the triangles (connectivity) :param geometry: Geometry of the triangles (location of the nodes) :param mask: Valid matplotlib mask :return: Triangulation object for plotting """ tri = Triangulation(geometry[:, 0], geometry[:, 1], topology) if mask: tri.set_mask(mask) return tri
def plot_magnetic_field_contour(self, ax=None): if ax is None: fig, ax = plt.subplots() else: fig = plt.gcf() ax.set_aspect('equal') from matplotlib.tri import Triangulation, TriAnalyzer, UniformTriRefiner import matplotlib.cm as cm element_to_magnetic_field = self.magnetic_field_per_element() x = [] y = [] Z = [] for group in self.mesh.elements_groups: for element in group.elements: x_center, y_center = element.center x.append(x_center) y.append(y_center) Z.append(element_to_magnetic_field[element].Norm()) tri = Triangulation(x, y) #----------------------------------------------------------------------------- # Improving the triangulation before high-res plots: removing flat triangles #----------------------------------------------------------------------------- # masking badly shaped triangles at the border of the triangular mesh. min_circle_ratio = -1 mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) subdiv = 3 tri_refi, z_test_refi = refiner.refine_field(Z, subdiv=subdiv) levels = npy.arange(0., 1., 0.05) cmap = cm.get_cmap(name='Blues', lut=None) ax.tricontour(tri_refi, z_test_refi, levels=levels, #cmap=cmap, linewidths=[2.0, 0.5, 1.0, 0.5]) # ax.triplot(tri_refi, color='0.97') # ax.triplot(tri, color='0.7') # ax.tricontour(x, y, Z) return ax
def plot_samples(num): samples_hundred = BM_sampling_method(num) tri = Triangulation(samples_hundred[0], samples_hundred[1]) random_gen = np.random.mtrand.RandomState(seed=127260) init_mask_frac = 0.0 min_circle_ratio = .01 subdiv = 3 ntri = tri.triangles.shape[0] print 'hi' mask_init = np.zeros(ntri, dtype=np.bool) masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac)) mask_init[masked_tri] = True tri.set_mask(mask_init) print 'hey' z_exp = experiment_res(tri.x, tri.y) print z_exp mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) tri_refi, z_test_refi = refiner.refine_field(z_exp, subdiv=subdiv) # analytical 'results' for comparison z_expected = experiment_res(tri_refi.x, tri_refi.y) plt.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, linestyles='--') plt.show() x, y = np.mgrid[-1:1:0.001, -1:1:0.001] pos = np.empty(x.shape + (2, )) pos[:, :, 0] = x pos[:, :, 1] = y rv = multivariate_normal([0, 0], [[1.0, 0.0], [0.0, 1.0]]) plt.contour(x, y, rv.pdf(pos))
c2 = np.empty([num,3]) for i in range (num): c1[i, 0] = b1[i, 0] - b1[i, 1] # X c1[i, 1] = b1[i, 1] - b1[i, 2] c1[i, 2] = b1[i, 0] - b1[i, 2] c2[i, 0] = b2[i, 0] - b2[i, 1] # Y c2[i, 1] = b2[i, 1] - b2[i, 2] c2[i, 2] = b2[i, 0] - b2[i, 2] c1 = c1 / 1.67e-04 c2 = c2 / 1.67e-04 n =np.hypot(c1,c2).sum(axis=1) # tri.set_mask(n>0.004) tri.set_mask(n > MA) fig1, ax1 = plt.subplots() ax1.set_aspect('equal') ax1.triplot(tri, 'bo-', lw=1) tcf = ax1.tricontourf(tri, z_test) fig1.colorbar(tcf) ax1.tricontour(tri, z_test, colors='k') ax1.set_title('triplot of Delaunay triangulation') plt.show() newdata = gpd.GeoDataFrame() newdata['geometry'] = None
def plot_wnd(storm, datafile1, datafile2=None): #Single file netCDF reading ncf = datafile1 nco = netCDF4.Dataset(ncf) #Get fields to plot lon = nco.variables['x'][:] lat = nco.variables['y'][:] timeinsec = nco.variables['time'][:] uwnd = nco.variables['windx'][:] vwnd = nco.variables['windy'][:] triangles = nco.variables['element'][:, :] reflon = np.linspace(lon.min(), lon.max(), 1000) reflat = np.linspace(lat.min(), lat.max(), 1000) #reflon=np.linspace(-80.40, -74.75, 1000) #reflat=np.linspace(32.50, 36.60, 1000) #reflon=np.linspace(-75.70, -71.05, 1000) #reflat=np.linspace(38.50, 41.40, 1000) #reflon=np.linspace(-80.40, -73.35, 1000) #reflat=np.linspace(32.50, 39.50, 1000) #reflon=np.linspace(-85.30, -78.50, 1000) #reflat=np.linspace(23.00, 29.70, 1000) reflon, reflat = np.meshgrid(reflon, reflat) plt.figure(figsize=[6.4, 3.8]) flatness = 0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles = triangles - 1 # Correct indices for Python's zero-base tri = Triangulation(lon, lat, triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeinsec)): besttrack = pd.read_csv(PARMnsem + '/storms/' + STORM + '/best_track.txt', header=None, skiprows=4, delim_whitespace=True) plt.clf() ax = plt.axes(projection=ccrs.Mercator()) ax.set_extent([-100.00, -50.00, 4.00, 48.00], crs=ccrs.PlateCarree()) #ax.set_extent([-80.40, -74.75, 32.50, 36.60], crs=ccrs.PlateCarree()) #ax.set_extent([-80.40, -73.35, 32.50, 39.50], crs=ccrs.PlateCarree()) #ax.set_extent([-85.30, -78.50, 23.00, 29.70], crs=ccrs.PlateCarree()) dt = base_info.tide_spin_start_date + datetime.timedelta( seconds=timeinsec[ind]) dstr = datetime.date.strftime(dt, '%Y%m%d%H:%M:%S') dstr = dstr[0:8] + ' ' + dstr[8:17] print('Plotting ' + dstr) par = np.sqrt( np.square(np.double(uwnd[ind, :])) + np.square(np.double(vwnd[ind, :]))) tli = LinearTriInterpolator(tri, par) par_interp = tli(reflon, reflat) plt.pcolormesh(reflon, reflat, par_interp, vmax=60.0, shading='flat', cmap=plt.cm.jet, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) coast = cfeature.GSHHSFeature(scale='high', edgecolor='black', facecolor='none', linewidth=0.25) ax.add_feature(coast) plt.plot(besttrack.iloc[:, 3].values, besttrack.iloc[:, 2].values, 'k--', linewidth=1.0, transform=ccrs.PlateCarree()) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = False gl.ylines = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 6, 'color': 'black'} gl.ylabel_style = {'size': 6, 'color': 'black'} figtitle = storm.capitalize() + ': U10 (m/s): ' + dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt, '%Y%m%d%H%M%S') dtlabel = dtlabel[0:8] + '_' + dtlabel[8:14] filenm = 'nsem_' + storm + '_wnd_' + dtlabel + '.png' plt.savefig(filenm, dpi=150, bbox_inches='tight', pad_inches=0.1) del (par) del (par_interp)
event.canvas.draw() # Create a Triangulation. n_angles = 16 n_radii = 5 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2 * math.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += math.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() triangulation = Triangulation(x, y) xmid = x[triangulation.triangles].mean(axis=1) ymid = y[triangulation.triangles].mean(axis=1) mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0) triangulation.set_mask(mask) # Use the triangulation's default TriFinder object. trifinder = triangulation.get_trifinder() # Setup plot and callbacks. plt.subplot(111, aspect='equal') plt.triplot(triangulation, 'bo-') polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ys update_polygon(-1) plt.gca().add_patch(polygon) plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show()
def visualization(self, savename='figure'): # --> Sets figure. fig = plt.figure() # Mesh arrays. x = self.x[:self.nde] y = self.y[:self.nde] # Vorticity array. vorticity = self.vorticity[:self.nde] # Delaunay triangulation. tri = Triangulation(x, y) # Mask unwanted triangles. radius = 0.5 xmid = tri.x[tri.triangles].mean(axis=1) ymid = tri.y[tri.triangles].mean(axis=1) xc1, yc1 = 0, 0.75 xc2, yc2 = 0, -0.75 xc3, yc3 = -1.5 * np.sqrt(0.75), 0 mask = np.where((xmid - xc1)**2 + (ymid - yc1)**2 < radius**2, 1, 0) mask += np.where((xmid - xc2)**2 + (ymid - yc2)**2 < radius**2, 1, 0) mask += np.where((xmid - xc3)**2 + (ymid - yc3)**2 < radius**2, 1, 0) tri.set_mask(mask) # Plot the vorticity field. ax = fig.gca() cmap = plt.cm.RdBu h = ax.tripcolor(tri, vorticity, shading='gouraud', cmap=cmap) h.set_clim(-4, 4) ax.set_aspect('equal') ax.set_xlim(-5, 20) ax.set_ylim(-4, 4) # Set up the colorbar. divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.1) cb = plt.colorbar(h, cax=cax) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.update_ticks() # Highlight the cylinders. xc, yc, r = 0., 0.75, 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) xc, yc, r = 0., -0.75, 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) xc, yc, r = -1.5 * np.sqrt(0.75), 0., 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) # Titles, labels, ... ax.set_xlabel(r'$x$') ax.locator_params(axis='y', nbins=5) ax.set_ylabel(r'$y$', rotation=0) # Save the figure. fig.savefig(savename + '.png', bbox_inches='tight', dpi=300) return fig, ax
class BaseTrig: """" Base class to be inherited by CTrig (charges) and GTrig (FE calculation). The class handles loading the triangulation, calculating relevant fields and plotting. Has two plotting functions: heatmap to plot spatially varying fields and boundary_plot to plot just the boundary. """ def __init__(self, lattice, p, method): self.method = method self.lattice = lattice self.p = p # porosity self.holes = None # list of hole positions self.boundary = None self.N_holes = None self.tri = None # A matplotlib Tri object. self.real_nodes = None self.mask = None # mask for Tri object, specifies which nodes to plot. self.length_factor = None def calc_tri(self): self.N_holes = self.holes.shape[1] self.tri = Triangulation(*self.lagrange_nodes(only_real=False)) self._set_mask() def _set_mask(self, crop=np.inf): # mask tris which involve a hole c1 = self.tri.triangles.min(axis=1) <= self.N_holes # mask tris with points outside crop c2 = np.abs(self.tri.x[self.tri.triangles]).max(axis=1) > crop c3 = np.abs(self.tri.y[self.tri.triangles]).max(axis=1) > crop self.mask = c1 | c2 | c3 self.tri.set_mask(self.mask) def lagrange_nodes(self, only_real=True): if only_real: return self.real_nodes else: return np.c_[self.holes, self.real_nodes] def euler_nodes(self, only_real=True): nodes = np.array([self.tri.x, self.tri.y]) if only_real: nodes = nodes[:, self.N_holes:] return nodes def deform(self, strain, kind='lin'): """ Deforms the mesh. Kind specifiec by which field to deform the mesh. It can be either 'lin' for linear response or 'mode' for most unstable mode. strain is the amplitude. """ if 'linear'.startswith(kind): H = self.lagrange_nodes()[1].max() - self.lagrange_nodes()[1].min() scale = H * strain / 2 sol = scale * self.d_lin self.stress *= scale elif 'mode'.startswith(kind): sol = strain * self.d_mode else: raise ValueError(f'didnt understand kind={kind}') all_nodes = self.lagrange_nodes(only_real=False) self.tri.x = all_nodes[0] + self.append_shit(sol[0]) self.tri.y = all_nodes[1] + self.append_shit(sol[1]) def heatmap(self, c, ax=None, cbar=True, cmap=None, clim=None, cax=None, crop=None): if ax is None: ax = plt.gca() single_color = c is None if single_color: c = np.full_like(self.lagrange_nodes()[0], 0) clim = [-1, 1] color = (0.2980392156862745, 0.4470588235294118, 0.6901960784313725) cmap = mpl.colors.ListedColormap((color, color)) if clim is None: levels = np.linspace(c.min(), c.max(), 20) else: levels = np.linspace(*clim, 20) if crop: self._set_mask(crop) if cmap is None and not single_color: cmap = sns.color_palette("RdBu_r", 20) cmap = mpl.colors.ListedColormap(cmap) hf = ax.tricontourf(self.tri, self.append_shit(c), levels=levels, cmap=cmap) if not single_color: hc = ax.tricontour(self.tri, self.append_shit(c), levels=levels, colors=['0.25', '0.5', '0.5', '0.5', '0.5'], linewidths=[1.0, 0.5, 0.5, 0.5, 0.5]) ax.set_aspect(1) ax.axis('off') if cbar: if cax is None: cbar = plt.colorbar(hf, ax=ax) else: cbar = plt.colorbar(hf, cax=cax) return ax, cbar def boundary_plot(self, deformation='mode', fill=True, scale=1, ax=None, facecolor='b', edgecolor='None', alpha=1, skip=1): if deformation == 'mode': d = self.d_mode[:, self.boundary] elif deformation == 'lin': d = self.d_lin[:, self.boundary] if ax is None: ax = plt.gca() reference = self.lagrange_nodes()[:, self.boundary] if hasattr(self, 'cyc'): cyc = self.cyc else: print('no cyclifier, calculating') cyc = Cyclifier(reference) self.cyc = cyc print('done') pos = reference + scale * d patch = patchify(cyc(pos, as_patches=True, skip=skip)) patch.set_facecolor(facecolor) patch.set_edgecolor(edgecolor) patch.set_alpha(alpha) patch = ax.add_patch(patch) ax.axis('off') ax.set_xticks([]) ax.set_yticks([]) ax.axis('equal') return patch def append_shit(self, x, fill_value=None): """Prepend zeros to x on hole nodes.""" assert x.ndim == 1 if hasattr(x, 'values'): x = x.values if fill_value is None: fill = x.mean().astype(x.dtype) else: fill = fill_value return np.r_[fill + np.zeros(self.N_holes, dtype=x.dtype), x] @property def sxy(self): return self.stress[2] @property def syy(self): return self.stress[1] @property def sxx(self): return self.stress[0]
event.canvas.draw() # Create a Triangulation. n_angles = 16 n_radii = 5 min_radius = 0.25 radii = np.linspace(min_radius, 0.95, n_radii) angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += math.pi / n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() triangulation = Triangulation(x, y) xmid = x[triangulation.triangles].mean(axis=1) ymid = y[triangulation.triangles].mean(axis=1) mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0) triangulation.set_mask(mask) # Use the triangulation's default TriFinder object. trifinder = triangulation.get_trifinder() # Setup plot and callbacks. plt.subplot(111, aspect='equal') plt.triplot(triangulation, 'bo-') polygon = Polygon([[0, 0], [0, 0]], facecolor='y') # dummy data for xs,ys update_polygon(-1) plt.gca().add_patch(polygon) plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify) plt.show()
def extract_wnd(storm, datafile1, stations, df, lonmin=None, lonmax=None, latmin=None, latmax=None): #Single file netCDF reading #ncf='ww3.field.2018_wnd.nc' ncf = datafile1 nco = netCDF4.Dataset(ncf) #ncf2='ww3.field.2018_dp.nc' #ncf2=datafile2 #nco2=netCDF4.Dataset(ncf2) #Get fields to plot lon = nco.variables['longitude'][:] lat = nco.variables['latitude'][:] pnt_lon = stations.iloc[0, :].values pnt_lat = stations.iloc[1, :].values timeindays = nco.variables['time'][:] uwnd = nco.variables['uwnd'][:] vwnd = nco.variables['vwnd'][:] #timeindays2=nco2.variables['time'][:] #dir=nco2.variables['dp'][:] if lonmin != None: reflon = np.linspace(lonmin, lonmax, 1000) reflat = np.linspace(latmin, latmax, 1000) else: reflon = np.linspace(lon.min(), lon.max(), 1000) reflat = np.linspace(lat.min(), lat.max(), 1000) reflon, reflat = np.meshgrid(reflon, reflat) flatness = 0.10 # flatness is from 0-.5 .5 is equilateral triangle tri = Triangulation(lon, lat) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) #Read obs point locations #data=np.loadtxt('erie_ndbc.loc', comments = '$') #buoylon=data[:,0] #buoylat=data[:,1] plt.figure(figsize=[6.4, 3.8]) df_dates = pd.DataFrame(columns=['Date']) # Loop through each time step and plot results for ind in range(0, len(timeindays)): plt.clf() ax = plt.axes(projection=ccrs.Mercator()) dt = datetime.datetime.combine(datetime.date( 1990, 1, 1), datetime.time( 0, 0)) + datetime.timedelta(days=timeindays[ind]) dstr = datetime.date.strftime(dt, '%Y%m%d%H:%M:%S') dstr = dstr[0:8] + ' ' + dstr[8:17] print('Extracting ' + dstr) par = np.sqrt( np.square(np.double(uwnd[ind, :])) + np.square(np.double(vwnd[ind, :]))) #par2=np.double(dir[ind,:]) tli = LinearTriInterpolator(tri, par) par_interp = tli(pnt_lon, pnt_lat) #print(par_interp) df.loc[len(df)] = par_interp df_dates.loc[len(df_dates)] = pd.to_datetime( dt, format="%Y-%m-%d %H:%M:%S") #line = pd.to_datetime(dt, format="%Y-%m-%d %H:%M:%S") #new_row = pd.DataFrame(par_interp, columns=stations.columns, index=line) #df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False) del (par) del (par_interp) df['Date'] = df_dates df.set_index('Date', inplace=True) return df
# Random points random_gen = np.random.mtrand.RandomState(seed=127260) x_test = random_gen.uniform(-1., 1., size=n_test) y_test = random_gen.uniform(-1., 1., size=n_test) z_test = experiment_res(x_test, y_test) # meshing with Delaunay triangulation tri = Triangulation(x_test, y_test) ntri = tri.triangles.shape[0] # Some invalid data are masked out mask_init = np.zeros(ntri, dtype=np.bool) masked_tri = random_gen.randint(0, ntri, int(ntri*init_mask_frac)) mask_init[masked_tri] = True tri.set_mask(mask_init) #----------------------------------------------------------------------------- # Improving the triangulation before high-res plots: removing flat triangles #----------------------------------------------------------------------------- # masking badly shaped triangles at the border of the triangular mesh. mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv) # analytical 'results' for comparison z_expected = experiment_res(tri_refi.x, tri_refi.y)
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() V = dipole_potential(x, y) # Create the Triangulation; no triangles specified so Delaunay triangulation # created. triang = Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean(axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2)
def plot_cur(storm, datafile1, datafile2=None): #Single file netCDF reading ncf=datafile1 nco=netCDF4.Dataset(ncf) #ncf2=datafile2 #nco2=netCDF4.Dataset(ncf2) #Get fields to plot lon=nco.variables['longitude'][:] lat=nco.variables['latitude'][:] timeindays=nco.variables['time'][:] ucur=nco.variables['ucur'][:] vcur=nco.variables['vcur'][:] triangles=nco.variables['tri'][:,:] #timeindays2=nco2.variables['time'][:] #dir=nco2.variables['dp'][:] reflon=np.linspace(lon.min(),lon.max(),1000) reflat=np.linspace(lat.min(),lat.max(),1000) #reflon=np.linspace(-80.40, -74.75, 1000) #reflat=np.linspace(32.50, 36.60, 1000) #reflon=np.linspace(-75.70, -71.05, 1000) #reflat=np.linspace(38.50, 41.40, 1000) reflon,reflat=np.meshgrid(reflon,reflat) plt.figure(figsize = [6.4, 3.8]) flatness=0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles=triangles-1 # Correct indices for Python's zero-base tri=Triangulation(lon,lat,triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeindays)): plt.clf() ax = plt.axes(projection=ccrs.Mercator()) dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind]) dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S') dstr = dstr[0:8]+' '+dstr[8:17] print('Plotting '+dstr) par=np.sqrt( np.square(np.double(ucur[ind,:])) + np.square(np.double(vcur[ind,:])) ) #par2=np.double(dir[ind,:]) tli=LinearTriInterpolator(tri,par) par_interp=tli(reflon,reflat) #u=np.cos(np.pi/180*(270-par_interp)) #v=np.sin(np.pi/180*(270-par_interp)) plt.pcolormesh(reflon,reflat,par_interp,vmin=0.0,vmax=2.0,shading='flat',cmap=plt.cm.jet, transform=ccrs.PlateCarree()) #plt.contourf(reflon, reflat, par_interp, vmax=60.0, cmap=plt.cm.jet, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) #rowskip=np.floor(par_interp.shape[0]/25) #colskip=np.floor(par_interp.shape[1]/25) rowskip = 50 colskip = 50 #plt.quiver(reflon[0::rowskip,0::colskip],reflat[0::rowskip,0::colskip],\ # u[0::rowskip,0::colskip],v[0::rowskip,0::colskip], \ # scale = 50, color='black',pivot='middle',units='xy',alpha=0.7) coast = cfeature.GSHHSFeature(scale='high',edgecolor='black',facecolor='none',linewidth=0.25) ax.add_feature(coast) plt.xticks(fontsize=9) plt.yticks(fontsize=9) figtitle = storm.capitalize()+': Cur (m/s): '+dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S') dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14] filenm = 'nsem_'+storm+'_cur_'+dtlabel+'.png' plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.1) del(par) del(par_interp)
def plot_wlv(storm, datafile1, datafile2=None, lonmin=None, lonmax=None, latmin=None, latmax=None, domain=None): #Single file netCDF reading ncf=datafile1 nco=netCDF4.Dataset(ncf) ncf2=datafile2 nco2=netCDF4.Dataset(ncf2) #Get fields to plot lon=nco.variables['longitude'][:] lat=nco.variables['latitude'][:] timeindays=nco.variables['time'][:] wlv=nco.variables['wlv'][:] triangles=nco.variables['tri'][:,:] dpt=nco2.variables['dpt'][:] if lonmin != None: reflon=np.linspace(lonmin, lonmax, 1000) reflat=np.linspace(latmin, latmax, 1000) else: reflon=np.linspace(lon.min(),lon.max(),1000) reflat=np.linspace(lat.min(),lat.max(),1000) reflon,reflat=np.meshgrid(reflon,reflat) plt.figure(figsize = [6.4, 3.8]) flatness=0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles=triangles-1 # Correct indices for Python's zero-base tri=Triangulation(lon,lat,triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeindays)): besttrack = pd.read_csv(PARMnsem+'/storms/'+STORM+'/best_track.txt', header=None, skiprows=4, delim_whitespace=True) plt.clf() ax = plt.axes(projection=ccrs.Mercator()) if lonmin != None: ax.set_extent([lonmin, lonmax, latmin, latmax], crs=ccrs.PlateCarree()) dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind]) dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S') dstr = dstr[0:8]+' '+dstr[8:17] print('Plotting '+dstr) par=np.double(wlv[ind,:]) tli=LinearTriInterpolator(tri,par) par_interp=tli(reflon,reflat) plt.pcolormesh(reflon,reflat,par_interp,vmin=-2.0,vmax=2.0, shading='flat',cmap=plt.cm.bwr, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) coast = cfeature.GSHHSFeature(scale='high',edgecolor='black',facecolor='none',linewidth=0.25) ax.add_feature(coast) plt.plot(besttrack.iloc[:,3].values, besttrack.iloc[:,2].values, 'k--', linewidth=1.0, transform=ccrs.PlateCarree()) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = False gl.ylines = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 6, 'color': 'black'} gl.ylabel_style = {'size': 6, 'color': 'black'} figtitle = storm.capitalize()+': WL (m MSL): '+dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt,'%Y%m%d%H%M%S') dtlabel = dtlabel[0:8]+'_'+dtlabel[8:14] filenm = 'nsem_'+storm+'_wlv_'+dtlabel+'_'+domain+'.png' plt.savefig(filenm,dpi=150,bbox_inches='tight',pad_inches=0.1) del(par) del(par_interp)
def extract_wlv(storm, datafile1, stations, df, lonmin=None, lonmax=None, latmin=None, latmax=None): print('Reading', datafile1) #Single file netCDF reading #ncf='ww3.field.2018_wnd.nc' ncf = datafile1 nco = netCDF4.Dataset(ncf) #ncf2='ww3.field.2018_dp.nc' #ncf2=datafile2 #nco2=netCDF4.Dataset(ncf2) #Get fields to plot lon = nco.variables['x'][:] lat = nco.variables['y'][:] pnt_lon = stations.iloc[0, :].values pnt_lat = stations.iloc[1, :].values timeinsec = nco.variables['time'][:] #base_date=nco.variables['time:base_date'] #print(base_date) wlv = nco.variables['zeta'][:] triangles = nco.variables['element'][:, :] #timeindays2=nco2.variables['time'][:] #dir=nco2.variables['dp'][:] if lonmin != None: reflon = np.linspace(lonmin, lonmax, 1000) reflat = np.linspace(latmin, latmax, 1000) else: reflon = np.linspace(lon.min(), lon.max(), 1000) reflat = np.linspace(lat.min(), lat.max(), 1000) reflon, reflat = np.meshgrid(reflon, reflat) flatness = 0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles = triangles - 1 # Correct indices for Python's zero-base tri = Triangulation(lon, lat, triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) #Read obs point locations #data=np.loadtxt('erie_ndbc.loc', comments = '$') #buoylon=data[:,0] #buoylat=data[:,1] df_dates = pd.DataFrame(columns=['Date']) # Loop through each time step and plot results for ind in range(0, len(timeinsec)): #plt.clf() #ax = plt.axes(projection=ccrs.Mercator()) dt = base_info.tide_spin_start_date + datetime.timedelta( seconds=timeinsec[ind]) dstr = datetime.date.strftime(dt, '%Y%m%d%H:%M:%S') dstr = dstr[0:8] + ' ' + dstr[8:17] print('Plotting ' + dstr) par = np.double(wlv[ind, :]) tli = LinearTriInterpolator(tri, par) par_interp = tli(pnt_lon, pnt_lat) #print(par_interp) df.loc[len(df)] = par_interp df_dates.loc[len(df_dates)] = pd.to_datetime( dt, format="%Y-%m-%d %H:%M:%S") #line = pd.to_datetime(dt, format="%Y-%m-%d %H:%M:%S") #new_row = pd.DataFrame(par_interp, columns=stations.columns, index=line) #df = pd.concat([df, pd.DataFrame(new_row)], ignore_index=False) del (par) del (par_interp) df['Date'] = df_dates df.set_index('Date', inplace=True) return df
def mesh_2D(fname, var=None, flabels=None, fformat='csv', xlabel='X axis', ylabel='Y axis', vmins=None, output_path=None): """Visualization of specific variable on a user provided 2D mesh. The provided mesh should contain two columns (x,y coordinates for each mesh point) and be one of :func:`batman.input_output.available_formats`. (x, y) must be respectively the first and second column. Any other column is treated as an extra variable and will be used to plot a figure. If :attr:`var` is not `None`, its content will be used as plotting variables. :param str fname: name of mesh file. :param array_like var: data to be plotted shape (n_coords, n_vars). :param list(str) flabels: names of the variables. :param str fformat: format of the mesh file. :param str xlabel: name of the x-axis. :param str ylabel: name of the y-axis. :param lst(double) vmins: value of the minimal output for data filtering. :param str output_path: name of the output path. :returns: figure. :rtype: Matplotlib figure instances. """ # Read the mesh file io = formater(fformat) mesh = io.read(fname) if var is not None: var = np.asarray(var) else: var = mesh[:, 2:] if flabels is None: flabels = ['y' + str(i) for i in range(var.shape[1])] # Input variables var_len = var.shape[0] if var_len != len(mesh): raise ValueError( 'Variable size not equal: Variable {} - Mesh {}'.format( var_len, len(mesh))) if vmins is None: vmins = [None] * var_len # Meshing with Delaunay triangulation tri = Triangulation(mesh[:, 0], mesh[:, 1]) # Masking badly shaped triangles at the border of the triangular mesh mask = TriAnalyzer(tri).get_flat_tri_mask(0.01) tri.set_mask(mask) # Loop over input parameters figs, axs = [], [] for i, _ in enumerate(var[0]): fig, ax = plt.subplots() figs.append(fig) axs.append(ax) cmap = cm.viridis cmap.set_bad(alpha=0.0) cmap.set_under('w', alpha=0.0) plt.tricontourf(tri, var[:, i], antialiased=True, cmap=cmap, vmin=vmins[i]) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.tick_params(axis='x') plt.tick_params(axis='y') cbar = plt.colorbar() cbar.set_label(flabels[i]) cbar.ax.tick_params() bat.visualization.save_show(output_path, figs, extend='neither') return figs, axs
angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += np.pi / n_angles x = (radii * np.cos(angles)).flatten() y = (radii * np.sin(angles)).flatten() V = dipole_potential(x, y) # Create the Triangulation; no triangles specified so Delaunay triangulation # created. triang = Triangulation(x, y) # Mask off unwanted triangles. triang.set_mask( np.hypot(x[triang.triangles].mean(axis=1), y[triang.triangles].mean( axis=1)) < min_radius) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2)
def plot_cur(storm, datafile1, datafile2=None): #Single file netCDF reading ncf = datafile1 nco = netCDF4.Dataset(ncf) #ncf2=datafile2 #nco2=netCDF4.Dataset(ncf2) #Get fields to plot lon = nco.variables['longitude'][:] lat = nco.variables['latitude'][:] timeindays = nco.variables['time'][:] ucur = nco.variables['ucur'][:] vcur = nco.variables['vcur'][:] triangles = nco.variables['tri'][:, :] #timeindays2=nco2.variables['time'][:] #dir=nco2.variables['dp'][:] reflon = np.linspace(lon.min(), lon.max(), 1000) reflat = np.linspace(lat.min(), lat.max(), 1000) #reflon=np.linspace(-80.40, -73.35, 1000) #reflat=np.linspace(32.50, 39.50, 1000) reflon, reflat = np.meshgrid(reflon, reflat) plt.figure(figsize=[6.4, 3.8]) flatness = 0.10 # flatness is from 0-.5 .5 is equilateral triangle triangles = triangles - 1 # Correct indices for Python's zero-base tri = Triangulation(lon, lat, triangles=triangles) mask = TriAnalyzer(tri).get_flat_tri_mask(flatness) tri.set_mask(mask) # Loop through each time step and plot results for ind in range(0, len(timeindays)): besttrack = pd.read_csv(PARMnsem + '/storms/' + STORM + '/best_track.txt', header=None, skiprows=4, delim_whitespace=True) plt.clf() ax = plt.axes(projection=ccrs.Mercator()) ax.set_extent([-100.00, -50.00, 4.00, 48.00], crs=ccrs.PlateCarree()) #ax.set_extent([-80.40, -73.35, 32.50, 39.50], crs=ccrs.PlateCarree()) dt = base_info.tide_spin_start_date + datetime.timedelta( days=timeindays[ind]) dstr = datetime.date.strftime(dt, '%Y%m%d%H:%M:%S') dstr = dstr[0:8] + ' ' + dstr[8:17] print('Plotting ' + dstr) par = np.sqrt( np.square(np.double(ucur[ind, :])) + np.square(np.double(vcur[ind, :]))) #par2=np.double(dir[ind,:]) tli = LinearTriInterpolator(tri, par) par_interp = tli(reflon, reflat) #u=np.cos(np.pi/180*(270-par_interp)) #v=np.sin(np.pi/180*(270-par_interp)) plt.pcolormesh(reflon, reflat, par_interp, vmin=0.0, vmax=2.0, shading='flat', cmap=plt.cm.jet, transform=ccrs.PlateCarree()) #plt.contourf(reflon, reflat, par_interp, vmax=60.0, cmap=plt.cm.jet, transform=ccrs.PlateCarree()) cb = plt.colorbar() cb.ax.tick_params(labelsize=8) #rowskip=np.floor(par_interp.shape[0]/25) #colskip=np.floor(par_interp.shape[1]/25) rowskip = 50 colskip = 50 #plt.quiver(reflon[0::rowskip,0::colskip],reflat[0::rowskip,0::colskip],\ # u[0::rowskip,0::colskip],v[0::rowskip,0::colskip], \ # scale = 50, color='black',pivot='middle',units='xy',alpha=0.7) coast = cfeature.GSHHSFeature(scale='high', edgecolor='black', facecolor='none', linewidth=0.25) ax.add_feature(coast) plt.plot(besttrack.iloc[:, 3].values, besttrack.iloc[:, 2].values, 'k--', linewidth=1.0, transform=ccrs.PlateCarree()) gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_right = False gl.xlines = False gl.ylines = False gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 6, 'color': 'black'} gl.ylabel_style = {'size': 6, 'color': 'black'} figtitle = storm.capitalize() + ': Cur (m/s): ' + dstr plt.title(figtitle) dtlabel = datetime.date.strftime(dt, '%Y%m%d%H%M%S') dtlabel = dtlabel[0:8] + '_' + dtlabel[8:14] filenm = 'nsem_' + storm + '_cur_' + dtlabel + '.png' plt.savefig(filenm, dpi=150, bbox_inches='tight', pad_inches=0.1) del (par) del (par_interp)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) angles[:, 1::2] += math.pi/n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() V = dipole_potential(x, y) # Create the Triangulation; no triangles specified so Delaunay triangulation # created. triang = Triangulation(x, y) # Mask off unwanted triangles. xmid = x[triang.triangles].mean(axis=1) ymid = y[triang.triangles].mean(axis=1) mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0) triang.set_mask(mask) #----------------------------------------------------------------------------- # Refine data - interpolates the electrical potential V #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3) #----------------------------------------------------------------------------- # Computes the electrical field (Ex, Ey) as gradient of electrical potential #----------------------------------------------------------------------------- tci = CubicTriInterpolator(triang, -V) # Gradient requested here at the mesh nodes but could be anywhere else: (Ex, Ey) = tci.gradient(triang.x, triang.y) E_norm = np.sqrt(Ex**2 + Ey**2)
def density(model, refinement=0): """ Create a Voronoi mesh and calculate the local particle density on its vertices. The local density is calculated as follows: for each vertex, compute the density of each neighbour region as one over the area and assign the average of the neighbouring density to the vertex. Parameters ---------- model : simulation.builder.Model the Model object containing refinement : int (defaults : 0) number of subdivision for refining the mesh (0 == None) Returns ------- tri : matplotlib.tri.Triangulation the triangulation mesh (refined if set as) vert_density : numpy.array the array containing the local denstity associated with the tri mesh Example ------- To plot the result using matplotlib use : .. code-block:: python import matplotlib.pyplot as plt tri, density = data_proc.density(model) plt.tricontour(tri, density) # to draw contours plt.tricontourf(tri, density) # ot draw filled contours plt.show() Note ---- As of now, the numerical results may not be quantitatively accurate but should qualitatively represent the density. """ vor = Voronoi(model.pos) vert_density = np.zeros(max(vor.vertices.shape)) # density vector reg_num = np.zeros(max( vor.vertices.shape)) # nbr of regions per vertex --> averaging for point_index, reg in enumerate(vor.point_region): vertices = vor.regions[reg] if vertices: if -1 not in vertices: area = ConvexHull(vor.vertices[vertices]).area # gets the area vert_density[ vertices] += 1 / area # makes it a density (sort-of) reg_num[vertices] += 1 vert_density /= reg_num # averaging # getting rid of really ugly border points new_vert, vert_density = ( vor.vertices[vor.vertices[:, 0] >= np.min(model.pos[:, 0])], vert_density[vor.vertices[:, 0] >= np.min(model.pos[:, 0])]) new_vert, vert_density = ( new_vert[new_vert[:, 0] <= np.max(model.pos[:, 0])], vert_density[new_vert[:, 0] <= np.max(model.pos[:, 0])]) new_vert, vert_density = ( new_vert[new_vert[:, 1] >= np.min(model.pos[:, 1])], vert_density[new_vert[:, 1] >= np.min(model.pos[:, 1])]) new_vert, vert_density = ( new_vert[new_vert[:, 1] <= np.max(model.pos[:, 1])], vert_density[new_vert[:, 1] <= np.max(model.pos[:, 1])]) # for triangulation refinement tri2 = Triangulation(*new_vert.T) if refinement: tri2.set_mask(TriAnalyzer(tri2).get_flat_tri_mask(0.1)) refiner = UniformTriRefiner(tri2) print(len(tri2.neighbors), vert_density.shape) tri, vert_density = refiner.refine_field(vert_density, subdiv=refinement) else: tri, vert_density = tri2, vert_density return tri, vert_density
z, breaks, linewidths=[0.5, 0.25], colors='saddlebrown') plt.clabel(CS, inline=5, fontsize=8) ax.set_ylabel('X[m]') ax.set_xlabel('Y[m]') plt.grid() plt.savefig('plot.png', dpi=300) plt.show() # Tworzenie mapy hipsometrycznej matplotlib.rcParams['contour.negative_linestyle'] = 'solid' tri = Triangulation(y, x) mask = TriAnalyzer(tri).get_flat_tri_mask(0.02) tri.set_mask(mask) fig, ax = plt.subplots() fig.set_size_inches(10, 15) ax.tick_params(labelsize=15) ax.yaxis.set_major_formatter(FormatStrFormatter('%d')) ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) ax.set_aspect('equal') ax.set_title("Mapa warstwicowa") CS = ax.tricontourf(tri, z, cmap='RdBu') ax.tricontour(tri, z, breaks, linewidths=[0.5, 0.25], colors='saddlebrown') plt.clabel(CS, inline=1, fontsize=10) ax.set_ylabel('X[m]') ax.set_xlabel('Y[m]') plt.grid() plt.savefig('plotHipso.png', dpi=300) plt.show()
# Read data from mesh file ncmesh = Dataset(cfg['mesh_file'], 'r') lon_mesh = np.rad2deg( np.mod(ncmesh.variables['lonCell'][:] + np.pi, 2.0 * np.pi) - np.pi) lat_mesh = np.rad2deg(ncmesh.variables['latCell'][:]) nEdgesOnCell = ncmesh.variables['nEdgesOnCell'][:] cellsOnCell = ncmesh.variables['cellsOnCell'][:, :] # Triangulate cells triangles = Triangulation(lon_mesh, lat_mesh) # Compute triangulation mask (needs to be vectorized) mask = np.array(np.zeros((triangles.triangles.shape[0], )), dtype=bool) ntri = triangles.neighbors.shape[0] for i in range(ntri): k = 0 for j in range(3): n = triangles.triangles[i, j] if nEdgesOnCell[n] != np.where( cellsOnCell[n, :] != 0)[0].size: # Mask triangles k = k + 1 # containing if k == 3: # 3 boundary mask[i] = True # cells triangles.set_mask(mask) # Write out geotiff image output_name = cfg['output_variable'] + '.tif' write_to_geotiff(var, triangles, cfg['nx'], cfg['ny'], cfg['bbox'], output_name)
angles[:, 1::2] += math.pi/n_angles x = (radii*np.cos(angles)).flatten() y = (radii*np.sin(angles)).flatten() z = function_z(x, y) # Now create the Triangulation. # (Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points.) triang = Triangulation(x, y) # Mask off unwanted triangles. xmid = x[triang.triangles].mean(axis=1) ymid = y[triang.triangles].mean(axis=1) mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0) triang.set_mask(mask) #----------------------------------------------------------------------------- # Refine data #----------------------------------------------------------------------------- refiner = UniformTriRefiner(triang) tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3) #----------------------------------------------------------------------------- # Plot the triangulation and the high-res iso-contours #----------------------------------------------------------------------------- plt.figure() plt.gca().set_aspect('equal') plt.triplot(triang, lw=0.5, color='white') levels = np.arange(0., 1., 0.025)
def __init__(self, **kwargs): super(ContourMap, self).__init__(**kwargs) n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3 subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth # plots. Values >3 might result in a very high number of triangles # for the refine mesh: new triangles numbering = (4**subdiv)*ntri init_mask_frac = 0.0 # Float > 0. adjusting the proportion of # (invalid) initial triangles which will be masked # out. Enter 0 for no mask. min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle # ratio below this will be masked if they touch a # border. Suggested value 0.01 ; Use -1 to keep # all triangles. # Random points random_gen = np.random.mtrand.RandomState(seed=127260) x_test = random_gen.uniform(-1., 1., size=n_test) y_test = random_gen.uniform(-1., 1., size=n_test) z_test = experiment_res(x_test, y_test) # meshing with Delaunay triangulation tri = Triangulation(x_test, y_test) ntri = tri.triangles.shape[0] # Some invalid data are masked out mask_init = np.zeros(ntri, dtype=np.bool) masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac)) mask_init[masked_tri] = True tri.set_mask(mask_init) #----------------------------------------------------------------------------- # Improving the triangulation before high-res plots: removing flat triangles #----------------------------------------------------------------------------- # masking badly shaped triangles at the border of the triangular mesh. mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv) # analytical 'results' for comparison z_expected = experiment_res(tri_refi.x, tri_refi.y) # for the demo: loading the 'flat' triangles for plot flat_tri = Triangulation(x_test, y_test) flat_tri.set_mask(~mask) #----------------------------------------------------------------------------- # Now the plots #----------------------------------------------------------------------------- # User options for plots plot_tri = True # plot of base triangulation plot_masked_tri = True # plot of excessively flat excluded triangles plot_refi_tri = False # plot of refined triangulation plot_expected = False # plot of analytical function values for comparison # Graphical options for tricontouring levels = np.arange(0., 1., 0.025) cmap = cm.get_cmap(name='Blues', lut=None) plt.figure() plt.gca().set_aspect('equal') plt.title("Filtering a Delaunay mesh\n" + "(application to high-resolution tricontouring)") # 1) plot of the refined (computed) data countours: plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 0.5, 1.0, 0.5]) # 2) plot of the expected (analytical) data countours (dashed): if plot_expected: plt.tricontour(tri_refi, z_expected, levels=levels, cmap=cmap, linestyles='--') # 3) plot of the fine mesh on which interpolation was done: if plot_refi_tri: plt.triplot(tri_refi, color='0.97') # 4) plot of the initial 'coarse' mesh: if plot_tri: plt.triplot(tri, color='0.7') # 4) plot of the unvalidated triangles from naive Delaunay Triangulation: if plot_masked_tri: plt.triplot(flat_tri, color='red') plt.show()
# Random points random_gen = np.random.RandomState(seed=19680801) x_test = random_gen.uniform(-1., 1., size=n_test) y_test = random_gen.uniform(-1., 1., size=n_test) z_test = experiment_res(x_test, y_test) # meshing with Delaunay triangulation tri = Triangulation(x_test, y_test) ntri = tri.triangles.shape[0] # Some invalid data are masked out mask_init = np.zeros(ntri, dtype=bool) masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac)) mask_init[masked_tri] = True tri.set_mask(mask_init) #----------------------------------------------------------------------------- # Improving the triangulation before high-res plots: removing flat triangles #----------------------------------------------------------------------------- # masking badly shaped triangles at the border of the triangular mesh. mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio) tri.set_mask(mask) # refining the data refiner = UniformTriRefiner(tri) tri_refi, z_test_refi = refiner.refine_field(z_test, subdiv=subdiv) # analytical 'results' for comparison z_expected = experiment_res(tri_refi.x, tri_refi.y)
def visualization(mesh, vorticity, psi=None, savename='figure', var_range=[-4, 4]): # --> Import various utilities from matplotlib. from matplotlib.tri import Triangulation from matplotlib import ticker from matplotlib.patches import Circle from mpl_toolkits.axes_grid1 import make_axes_locatable # --> Get mesh information and build-up the Delaunay triangulation. x, y = mesh.coordinates()[:, 0], mesh.coordinates()[:, 1] tri = Triangulation(x, y) # --> Mask the unwanted triangles. radius = 0.5 xmid = tri.x[tri.triangles].mean(axis=1) ymid = tri.y[tri.triangles].mean(axis=1) xc1, yc1 = 0, 0.75 xc2, yc2 = 0, -0.75 xc3, yc3 = -1.5 * np.sqrt(0.75), 0 mask = np.where((xmid - xc1)**2 + (ymid - yc1)**2 < radius**2, 1, 0) mask += np.where((xmid - xc2)**2 + (ymid - yc2)**2 < radius**2, 1, 0) mask += np.where((xmid - xc3)**2 + (ymid - yc3)**2 < radius**2, 1, 0) tri.set_mask(mask) # --> Get the vorticity field at the mesh nodes. vorticity = vorticity.compute_vertex_values(mesh) #----------------------------------- #----- PLOT THE FIGURE ----- #----------------------------------- # --> Create matplotlib figure. fig = plt.figure() ax = fig.gca() # --> Plot the vorticity field. h = ax.tripcolor(tri, vorticity, shading='gouraud', cmap=plt.cm.RdBu) h.set_clim(var_range[0], var_range[1]) # --> Set the axis. ax.set_aspect('equal') ax.set_xlim(-5, 20) ax.set_ylim(-4, 4) # --> Setup the colorbar. divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.1) cb = plt.colorbar(h, cax=cax) tick_locator = ticker.MaxNLocator(nbins=5) cb.locator = tick_locator cb.update_ticks() # --> Highlight the cylinders. xc, yc, r = 0., 0.75, 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) xc, yc, r = 0., -0.75, 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) xc, yc, r = -1.5 * np.sqrt(0.75), 0., 0.5 circle = Circle((xc, yc), r, facecolor='None', edgecolor='k') ax.add_patch(circle) # --> Titles, labels, ... ax.set_xlabel(r'$x$') ax.locator_params(axis='y', nbins=5) ax.set_ylabel(r'$y$', rotation=0) # --> Save the figure. fig.savefig(savename + '.png', bbox_inches='tight', dpi=300) return