def update_E_PM(self,particles,just_return_dont_update=False): global counter try: counter==None except: counter=0 counter+=1 self.V_point_sources=0 for particle in particles: i = int(round(particle.pos[0]*10**6)) j = int(round(particle.pos[1]*10**6)) """to do: still a bug with particles being outside the period... if not self.contains([particle]): print(self.particles_left.nnz, self.particles_right.nnz, self.particles_top.nnz, self.particles_bottom.nnz)""" """the dielectric constant and minus sign are already done in Fenics""" self.V_point_sources += particle.charge*e*self.point_sources[i,j] tci = LinearTriInterpolator(self.triang_V,self.V_point_sources) # faster interpolator, but not as accurate (Ex, Ey) = tci.gradient(self.triang_V.x,self.triang_V.y) #V = tci(self.triang_V.x,self.triang_V.y) if just_return_dont_update: return -np.array([Ex,Ey])#*3e5 #return np.array([V,V*0]) #for debugging else: self.E_point_sources = -np.array([Ex,Ey])#*3e5
def plot_solution(self, phi, ax=None, **kwargs): """Given the solution vector phi of values at the vertices, plot the solution""" intp = LinearTriInterpolator(self.triang, phi) x, y = self.tri['vertices'].T u, v = intp.gradient(x, y) ax = ax or plt.gca() ax.tripcolor(self.triang, phi) ax.quiver(x, y, u, v, **kwargs)
def spatial_autocorr(tri, U, V, N, alpha): """ Function to estimate autocorrelation in cartesian components of wind velocity, U and V. The 2D spatial autocorrelation is calculated in a squared and structured grid, and represent the correlation of points displaced a distance tau and eta in x and y, respectively. Input: ----- tri - Delaunay triangulation object of unstructured grid. U,V - Arrays with cartesian components of wind speed. N - Number of points in the autocorrelation's squared grid. alpha - Fraction of the spatial domain that will act as the limit for tau and eta increments. Output: ------ r_u,r_v - 2D arrays with autocorrelation function rho(tau,eta) for U and V, respectively. """ # Squared grid of spatial increments tau = np.linspace(-alpha * (np.max(tri.x) - np.min(tri.x)), alpha * (np.max(tri.x) - np.min(tri.x)), N) eta = np.linspace(-alpha * (np.max(tri.y) - np.min(tri.y)), alpha * (np.max(tri.y) - np.min(tri.y)), N) tau, eta = np.meshgrid(tau, eta) # De-meaning of U and V. The mean U and V in the whole scan is used U = U - np.nanmean(U) V = V - np.nanmean(V) # Interpolator object to estimate U and V fields when translated by # (tau,eta) U_int = LinearTriInterpolator(tri, U) V_int = LinearTriInterpolator(tri, V) # Autocorrelation is calculated just for non-empty scans if len(U[~np.isnan(U)]) > 0: # autocorr() function over the grid tau and eta. r_u = [ autocorr(tri, U, U_int, t, e) for t, e in zip(tau.flatten(), eta.flatten()) ] r_v = [ autocorr(tri, V, V_int, t, e) for t, e in zip(tau.flatten(), eta.flatten()) ] else: r_u = np.empty(len(tau.flatten())) r_u[:] = np.nan r_v = np.empty(len(tau.flatten())) r_v[:] = np.nan return (r_u, r_v)
def triang_and_interp(star_node, W_star): '''Does a triangulation on the psi-theta space, performs an interpolation there and then outputs the plot.''' from scipy.ndimage import gaussian_filter psi_star_p, psi_star_m = psi_star_nodes(star_node, W_star) Pi = np.linspace(min(psi), max(psi), 400) Ti = np.linspace(min(thetas), max(thetas), 400) (PI, TI) = np.meshgrid(Pi, Ti) triangObject = Triangulation(psi, thetas) tcp = LinearTriInterpolator(triangObject, psi_star_p) tcm = LinearTriInterpolator(triangObject, psi_star_m) tcp_int = tcp(PI, TI) tcm_int = tcm(PI, TI) p_filt = gaussian_filter(tcp_int, 1.5) m_filt = gaussian_filter(tcm_int, 1.5) psi_theta_plot(PI, TI, p_filt, m_filt, W_star)
def write_to_geotiff(val, tri, nx, ny, bbox, fout): # Generate raster points to interpolate from mesh xinterp = np.linspace(bbox[0], bbox[1], nx) yinterp = np.linspace(bbox[2], bbox[3], ny) Xinterp, Yinterp = np.meshgrid(xinterp, yinterp) # Calculate transformation factors originX = xinterp[0] originY = yinterp[-1] xres = (xinterp[-1] - xinterp[0]) / float(nx) yres = (yinterp[-1] - yinterp[0]) / float(ny) # Intrepolate solution onto raster points interp = LinearTriInterpolator(tri, val) interp_vals = interp(Xinterp.ravel(), Yinterp.ravel()).data raster = np.reshape(interp_vals, Xinterp.shape) raster = raster[::-1] # Create and write geotiff driver = gdal.GetDriverByName('GTiff') outRaster = driver.Create(fout, nx, ny, 1, gdal.GDT_Float32) outRaster.SetGeoTransform((originX, xres, 0, originY, 0, -yres)) outband = outRaster.GetRasterBand(1) outband.WriteArray(raster) outRasterSRS = osr.SpatialReference() outRasterSRS.ImportFromEPSG(4326) outRaster.SetProjection(outRasterSRS.ExportToWkt()) outband.FlushCache()
def _streamplot(ax, tri, vvals, spacing=1.0, density=None, **kwargs): xmin, xmax = min(tri.x), max(tri.x) ymin, ymax = min(tri.y), max(tri.y) nx = int((xmax - xmin) / spacing) ny = int((ymax - ymin) / spacing) x = np.linspace(xmin, xmax, nx + 2)[1:-1] y = np.linspace(ymin, ymax, ny + 2)[1:-1] xgrid, ygrid = np.meshgrid(x, y) u = LinearTriInterpolator(tri, vvals[:, 0])(xgrid, ygrid) v = LinearTriInterpolator(tri, vvals[:, 1])(xgrid, ygrid) if density is None: density = 1 / spacing ax.streamplot(x, y, u, v, density=density, color='black')
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 gradient( solution, variable, *, gradient_norm=True, plot=True, color_style: COLOR_STYLE_TYPE = "equal", mask=None, **kwargs ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: """Compute and plot the gradient of a scalar field. :param solution: The solution structure :param variable: Name of the variable :param gradient_norm: Should the norm be computed :param plot: Should the data be plotted :param color_style: How to symmetrize the colormap (False/None, 'full', 'equal') :param mask: Valid matplotlib mask see generate_mask :param kwargs: :return: Computed field as a scalar or vector field """ mpl_kwargs, fish2fem_kwargs = split_mpl_kwargs(kwargs) triangles, data = generate_triangles_for_2d( solution, variable, mask=mask, **fish2fem_kwargs ) topology = triangles.triangles geometry = list(zip(triangles.x, triangles.y)) interpolator = LinearTriInterpolator(triangles, -data) (e_x, e_y) = interpolator.gradient(triangles.x, triangles.y) if gradient_norm: norm = field_norm(e_x, e_y) if plot: mesh_plot_2d( None, None, color_style=color_style, mask=mask, topology=topology, geometry=geometry, data=data, **kwargs ) return norm else: plt.quiver(triangles.x, triangles.y, e_x, e_y, **mpl_kwargs) return e_x, e_y
def f(x, interp_mode): xgr = xg.ravel() ygr = yg.ravel() if interp_mode == 'linear': interp = LinearTriInterpolator(triang, x) else: interp = CubicTriInterpolator(triang, x) return interp(xgr, ygr).reshape(grid_pts)
def spectra_fft(tri, grid, U, V): """ Function to estimate autocorrelation from a single increment in cartesian coordinates(tau, eta) Input: ----- tri - Delaunay triangulation object of unstructured grid. grid - Squared, structured grid to apply FFT. U, V - Arrays with cartesian components of wind speed. Output: ------ r_u,r_v - 2D arrays with autocorrelation function rho(tau,eta) for U and V, respectively. """ U = U - np.nanmean(U) V = V - np.nanmean(V) dx = np.max(np.diff(grid[0].flatten())) dy = np.max(np.diff(grid[1].flatten())) n = grid[0].shape[0] m = grid[1].shape[0] U_int = np.reshape( LinearTriInterpolator(tri, U)(grid[0].flatten(), grid[1].flatten()).data, grid[0].shape) V_int = np.reshape( LinearTriInterpolator(tri, V)(grid[0].flatten(), grid[1].flatten()).data, grid[1].shape) #zero padding U_int[np.isnan(U_int)] = 0.0 V_int[np.isnan(V_int)] = 0.0 fftU = np.fft.fftshift(np.fft.fft2(U_int)) fftV = np.fft.fftshift(np.fft.fft2(V_int)) fftUV = fftU * np.conj(fftV) Suu = 2 * (np.abs(fftU)**2) / (n * m * dx * dy) Svv = 2 * (np.abs(fftV)**2) / (n * m * dx * dy) Suv = 2 * np.real(fftUV) / (n * m * dx * dy) kx = 1 / (2 * dx) ky = 1 / (2 * dy) k1 = kx * np.linspace(-1, 1, len(Suu)) k2 = ky * np.linspace(-1, 1, len(Suu)) return (Suu, Svv, Suv, k1, k2)
def get_n60_n2000_interpolator(): """Get interpolator for N60 to N2000 height system change, data from MML.""" df_points = get_n60_n2000_points() df_tri = get_n60_n2000_triangulation() triangles = df_tri.replace(df_points.index.values, np.arange(df_points.shape[0], dtype=int)).values interpolator_ = Triangulation(df_points["X"], df_points["Y"], triangles) interpolator = LinearTriInterpolator(interpolator_, df_points["diff"]) return interpolator
def velocity_from_phi(self, phi, x=None, y=None): """Interpolate velocity solution in vertex positions Velocity solution is: u = \grad(\phi) + \Gamma u_pf where \phi is the solution of phi at the vertices, and u_pf the standard point vortex, with magnitude Gamma stored in the (N+1)-th entry of the solution vector.""" assert (x is None) == ( y is None), "Provide either both or neither x and y arguments" if x is None: x, y = self.tri['vertices'].T N = len(phi) - 1 # first normal interpolation phi gradient intp = LinearTriInterpolator(self.triang, phi[:N]) u, v = intp.gradient(x, y) # then add point vortex solution Gamma = phi[-1] r2 = (x - self.x_c)**2 + y**2 u += -y / r2 * Gamma / 2 / np.pi v += (x - self.x_c) / r2 * Gamma / 2 / np.pi return u, v
def calc_l2_error_simplex_based(mesh, u_tilde_function, u): """ Calculates the L2 error of the solution by adding it up over the individual simplices :param mesh: The mesh to compute on :param u_tilde_function: The analytical solution :param u: The solution array :return: The L2 error """ def error_integrant_reference(y, x, p1_ref, u_function, j, v0_coord, det, fz): co = (x, y) xc = np.array([[x], [y]]) x0 = np.array([[v0_coord[0]], [v0_coord[1]]]) x_new = j.dot(xc) + x0 trival = fz(x_new[0], x_new[1]) return np.asscalar(trival - u_function.value((x_new[0], x_new[1])))**2 atraf = AffineTransformation() p1_ref = P1ReferenceElement() error = 0 m_ref = Mesh(88, 88) triangles = m_ref.triangles trianglesarr = np.zeros((len(mesh.triangles), 3)) i = 0 for triangle in mesh.triangles: trianglesarr[i, :] = triangle.v i += 1 triObj = Triangulation(mesh.vertices[0, :], mesh.vertices[1, :], trianglesarr) fz = LinearTriInterpolator(triObj, u[:, 0]) vertices = m_ref.vertices for n in range(len(m_ref.triangles)): v0_coord = (vertices[0, triangles[n].v0], vertices[1, triangles[n].v0]) v1_coord = (vertices[0, triangles[n].v1], vertices[1, triangles[n].v1]) v2_coord = (vertices[0, triangles[n].v2], vertices[1, triangles[n].v2]) atraf.set_target_cell(v0_coord, v1_coord, v2_coord) j = atraf.get_jacobian() det = atraf.get_determinant() ans, err = gauss_legendre_reference(error_integrant_reference, args=(p1_ref, u_tilde_function, j, v0_coord, det, fz)) error += ans * np.abs(det) return np.sqrt(error)
def __init__(self, RZ, psin, tri, Bgrid, sml_nphi): self.RZ = RZ self.R0, self.Z0 = RZ[0, :] self.psin = psin self.tri = tri self.triObj = Triangulation(RZ[:, 0], RZ[:, 1], tri) self.theta = self.calc_theta(RZ[:, 0], RZ[:, 1]) ##find x-point, to exclude from interpolator #Bpol = np.sqrt(np.sum(Bgrid[:,0:2]**2.,axis=1)) #ind = np.argmin(Bpol[10:])+10 #eq_x_r,eq_x_z = RZ[ind,:] #goodinds = ~((psin>=1) | ((psin<=1) & (RZ[:,1]>eq_x_z))) #mask = np.all(goodinds[tri],axis=1) #self.triObj_psintheta = Triangulation(self.psin,self.theta,self.tri,mask=mask) #self.fRZ2psin = LinearTriInterpolator(self.triObj_psintheta,self.RZ[:,0]) #self.fpsintheta2Z = LinearTriInterpolator(self.triObj_psintheta,self.RZ[:,1]) self.fRZ2psin = LinearTriInterpolator(self.triObj, self.psin) self.Binterp = LinearNDInterpolator(RZ, Bgrid, fill_value=np.inf) self.sml_nphi = sml_nphi
def open(self, filename, name): super(Flood, self).open(filename, name) self.lon = [ self.data.shape(i).points[0][0] for i in xrange(self.data.numRecords) ] self.lat = [ self.data.shape(i).points[0][1] for i in xrange(self.data.numRecords) ] self.val = [ self.data.record(i)[1] for i in xrange(self.data.numRecords) ] t = Triangulation(self.lon, self.lat) self.interpolator = LinearTriInterpolator(t, self.val) self.unit = 'probability'
def _setup_Te_interpolator(self, kind='linear'): """setup interpolator for measured Te :param string kind: default is 'linear', can be 'cubic' or 'linear' """ self._Delaunay = Delaunay(self._points) self._triangulation = triangulation.Triangulation( self._Y, self._X, triangles=self._Delaunay.simplices) self._trifinder = DelaunayTriFinder(self._Delaunay, self._triangulation) if kind == 'linear': self._kind = kind self._Te_interpolator = LinearTriInterpolator( self._triangulation, self._Te, trifinder=self._trifinder) elif kind == 'cubic': self._kind = kind self._Te_interpolator = CubicTriInterpolator( self._triangulation, self._Te, trifinder=self._trifinder) else: raise ValueError('Wrong kind of interpolation: {0}. Available \ options are "linear" and "cubic".'.format(kind))
with open('smartwindows/Variables/point_sources_with_glass.pkl', 'rb') as f: point_sources = pickle.load(f) with open('smartwindows/Variables/voltages_with_glass.pkl', 'rb') as f: V1, V2, V3, V4 = pickle.load(f) trifinder = triang.get_trifinder() y_b = 0.0e-5 y_t = 5.0e-5 t = 1.5e-5 x_1 = 0.0 x_2 = 20e-5 b = 5e-5 tci = LinearTriInterpolator(triang, V1) (Ex, Ey) = tci.gradient(triang.x, triang.y) E = -np.array([Ex, Ey]) x = np.linspace(0, 20e-5, 200 / 4) y = np.linspace(0 - 1.5e-5, 5e-5 + 1.5e-5, (50 + 2 * 15) / 4) X, Y = np.meshgrid(x, y) def get_field_here(field, pos: np.ndarray) -> np.ndarray: tr = trifinder(*pos) i = triang.triangles[tr] v0 = np.array([triang.x[i[0]], triang.y[i[0]]]) v1 = np.array([triang.x[i[1]], triang.y[i[1]]]) v2 = np.array([triang.x[i[2]], triang.y[i[2]]]) norm = np.array([
tri.set_mask(mask) ##################### nitr = 5 for itr in range(nitr): nfname = 'dep_smooth_itr_' + str(100 + itr) + '.nc' os.system('cp -f ' + fname + ' ' + nfname) os.system('echo Log smoothing &> log.txt ') for itr in range(nitr): print ' > Calculate gradient ..', itr, nitr os.system('echo ' + str(itr) + ' from ' + str(nitr) + ' >> log.txt ') os.system('echo "************************************" >> log.txt ') tci = LinearTriInterpolator(tri, dep) (ddep_dx, ddep_dy) = tci.gradient(UTMx, UTMy) grad_dep = np.sqrt(ddep_dx**2 + ddep_dy**2) grad_lim = 0.35 [ind] = np.where(grad_dep > grad_dep.max() * grad_lim) ####### if vv: fig, ax = adcp.make_map(res='m') vmin = 0 vmax = 0.5 dv = (vmax - vmin) / 50.0 levels = np.arange(vmin, vmax + dv, dv) cf1 = ax.tricontourf( trip, grad_dep, levels=levels, cmap=cmaps.jetMinWi,
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
def __init__(self, triang, ux, uy, **kwargs): self.Ix = LinearTriInterpolator(triang, ux) self.Iy = LinearTriInterpolator(triang, uy)
p_in_data /= np.max(p_in_data) spd_data /= np.max(spd_data) eff_data /= np.max(eff_data) x = np.concatenate( (np.transpose(p_in_data[0:-1][None]), np.transpose(spd_data[0:-1][None])), 1) y = np.concatenate( (np.transpose(spd_data[1:][None]), np.transpose(eff_data[1:][None])), 1) # fig = plt.figure() # plt.plot(x[:,0], x[:,1],'r.') # plt.show() # exit() triObj = Triangulation(x[:, 0], x[:, 1]) pre_plant_s = LinearTriInterpolator(triObj, y[:, 0]) pre_plant_p = LinearTriInterpolator(triObj, y[:, 1]) def plant_s(p_in, spd): out = pre_plant_s(p_in, spd) # if np.isnan(out): # breakpoint() # out = 1 return out def plant_p(p_in, spd): out = pre_plant_p(p_in, spd) # if np.isnan(out): # out = 1
def update_E_electrodes(self, x=[0,0,0,0]): self.V_electrodes = x[0]*self.V1 + x[1]*self.V2 + x[2]*self.V3 + x[3]*self.V4 tci = LinearTriInterpolator(self.triang_V,self.V_electrodes) # faster interpolator, but not as accurate (Ex, Ey) = tci.gradient(self.triang_V.x,self.triang_V.y) self.E_electrodes = -np.array([Ex,Ey])
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 __call__(self, plot): # These need to be in code_length x0, x1 = (v.in_units("code_length") for v in plot.xlim) y0, y1 = (v.in_units("code_length") for v in plot.ylim) # These are in plot coordinates, which may not be code coordinates. xx0, xx1 = plot._axes.get_xlim() yy0, yy1 = plot._axes.get_ylim() plot._axes.hold(True) numPoints_x = plot.image._A.shape[0] numPoints_y = plot.image._A.shape[1] # Multiply by dx and dy to go from data->plot dx = (xx1 - xx0) / (x1 - x0) dy = (yy1 - yy0) / (y1 - y0) # We want xi, yi in plot coordinates xi, yi = np.mgrid[xx0:xx1:numPoints_x / (self.factor * 1j), yy0:yy1:numPoints_y / (self.factor * 1j)] data = self.data_source or plot.data if plot._type_name in ['CuttingPlane', 'Projection', 'Slice']: if plot._type_name == 'CuttingPlane': x = data["px"] * dx y = data["py"] * dy z = data[self.field] elif plot._type_name in ['Projection', 'Slice']: #Makes a copy of the position fields "px" and "py" and adds the #appropriate shift to the copied field. AllX = np.zeros(data["px"].size, dtype='bool') AllY = np.zeros(data["py"].size, dtype='bool') XShifted = data["px"].copy() YShifted = data["py"].copy() dom_x, dom_y = plot._period for shift in np.mgrid[-1:1:3j]: xlim = ((data["px"] + shift * dom_x >= x0) & (data["px"] + shift * dom_x <= x1)) ylim = ((data["py"] + shift * dom_y >= y0) & (data["py"] + shift * dom_y <= y1)) XShifted[xlim] += shift * dom_x YShifted[ylim] += shift * dom_y AllX |= xlim AllY |= ylim # At this point XShifted and YShifted are the shifted arrays of # position data in data coordinates wI = (AllX & AllY) # This converts XShifted and YShifted into plot coordinates x = ((XShifted[wI] - x0) * dx).ndarray_view() + xx0 y = ((YShifted[wI] - y0) * dy).ndarray_view() + yy0 z = data[self.field][wI] # Both the input and output from the triangulator are in plot # coordinates if LooseVersion(matplotlib.__version__) < LooseVersion("1.4.0"): from matplotlib.delaunay.triangulate import Triangulation as \ triang zi = triang(x, y).nn_interpolator(z)(xi, yi) else: from matplotlib.tri import Triangulation, LinearTriInterpolator triangulation = Triangulation(x, y) zi = LinearTriInterpolator(triangulation, z)(xi, yi) elif plot._type_name == 'OffAxisProjection': zi = plot.frb[self.field][::self.factor, ::self.factor].transpose() if self.take_log is None: field = data._determine_fields([self.field])[0] self.take_log = plot.ds._get_field_info(*field).take_log if self.take_log: zi = np.log10(zi) if self.take_log and self.clim is not None: self.clim = (np.log10(self.clim[0]), np.log10(self.clim[1])) if self.clim is not None: self.ncont = np.linspace(self.clim[0], self.clim[1], self.ncont) cset = plot._axes.contour(xi, yi, zi, self.ncont, **self.plot_args) plot._axes.set_xlim(xx0, xx1) plot._axes.set_ylim(yy0, yy1) plot._axes.hold(False) if self.label: plot._axes.clabel(cset, **self.label_args)
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 spatial_autocorr_fft(tri, U, V, N_grid=512, auto=False, transform=False, tree=None, interp='Lanczos'): """ Function to estimate autocorrelation from a single increment in cartesian coordinates(tau, eta) Input: ----- tri - Delaunay triangulation object of unstructured grid. N_grid - Squared, structured grid resolution to apply FFT. U, V - Arrays with cartesian components of wind speed. Output: ------ r_u,r_v - 2D arrays with autocorrelation function rho(tau,eta) for U and V, respectively. """ if transform: U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) # Wind direction gamma = np.arctan2(V_mean, U_mean) # Components in matrix of coefficients S11 = np.cos(gamma) S12 = np.sin(gamma) T = np.array([[S11, S12], [-S12, S11]]) vel = np.array(np.c_[U, V]).T vel = np.dot(T, vel) X = np.array(np.c_[tri.x, tri.y]).T X = np.dot(T, X) U = vel[0, :] V = vel[1, :] tri = Triangulation(X[0, :], X[1, :]) mask = TriAnalyzer(tri).get_flat_tri_mask(.05) tri = Triangulation(tri.x, tri.y, triangles=tri.triangles[~mask]) U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) else: # Demeaning U_mean = avetriangles(np.c_[tri.x, tri.y], U, tri) V_mean = avetriangles(np.c_[tri.x, tri.y], V, tri) grid = np.meshgrid(np.linspace(np.min(tri.x), np.max(tri.x), N_grid), np.linspace(np.min(tri.y), np.max(tri.y), N_grid)) U = U - U_mean V = V - V_mean # Interpolated values of wind field to a squared structured grid if interp == 'cubic': U_int = CubicTriInterpolator(tri, U)(grid[0].flatten(), grid[1].flatten()).data V_int = CubicTriInterpolator(tri, V)(grid[0].flatten(), grid[1].flatten()).data U_int = np.reshape(U_int, grid[0].shape) V_int = np.reshape(V_int, grid[0].shape) else: # U_int= lanczos_int_sq(grid,tree,U) # V_int= lanczos_int_sq(grid,tree,V) U_int = LinearTriInterpolator(tri, U)(grid[0].flatten(), grid[1].flatten()).data V_int = LinearTriInterpolator(tri, V)(grid[0].flatten(), grid[1].flatten()).data U_int = np.reshape(U_int, grid[0].shape) V_int = np.reshape(V_int, grid[0].shape) #zero padding U_int[np.isnan(U_int)] = 0.0 V_int[np.isnan(V_int)] = 0.0 fftU = np.fft.fft2(U_int) fftV = np.fft.fft2(V_int) if auto: # Autocorrelation r_u = np.real(np.fft.fftshift(np.fft.ifft2(np.absolute(fftU)** 2))) / len(U_int.flatten()) r_v = np.real(np.fft.fftshift(np.fft.ifft2(np.absolute(fftV)** 2))) / len(U_int.flatten()) r_uv = np.real( np.fft.fftshift(np.fft.ifft2(np.real( fftU * np.conj(fftV))))) / len(U_int.flatten()) dx = np.max(np.diff(grid[0].flatten())) dy = np.max(np.diff(grid[1].flatten())) n = grid[0].shape[0] m = grid[1].shape[0] # Spectra fftU = np.fft.fftshift(fftU) fftV = np.fft.fftshift(fftV) fftUV = fftU * np.conj(fftV) Suu = 2 * (np.abs(fftU)**2) * (dx * dy) / (n * m) Svv = 2 * (np.abs(fftV)**2) * (dx * dy) / (n * m) Suv = 2 * np.real(fftUV) * (dx * dy) / (n * m) k1 = np.fft.fftshift((np.fft.fftfreq(n, d=dx))) k2 = np.fft.fftshift((np.fft.fftfreq(m, d=dy))) if auto: return (r_u, r_v, r_uv, Suu, Svv, Suv, k1, k2) else: return (Suu, Svv, Suv, k1, k2)
def getMeshAndCuts(fileDir, nRi=None, nZi=None, Rmin=Rmin, Rmax=Rmax, Zmin=Zmin, Zmax=Zmax): global loader, ne, pot, psin, RZ, tri, time, psin1d, psin001d, Te1d, ne1d, pot001d, bfield, pot0, dpot, dpot, pot, Tigc1d, nigc1d, i_T_perp, i_E_para, e_T_perp, e_E_para global Nplanes, Ntimes, dt global Ri, Zi, RI, ZI, triObj global sepInds, psinvalues, jcut, Zcut #,psii loader = xgc.load(fileDir, Rmin=Rmin, Rmax=Rmax, Zmin=Zmin, Zmax=Zmax, phi_start=0, phi_end=None) ne = loader.calcNeTotal() pot = loader.calcPotential() print('Rmin = ', loader.Rmin) print('Rmax = ', loader.Rmax) print('Zmin = ', loader.Zmin) print('Zmax = ', loader.Zmax) print('ne.shape = ', ne.shape) # (could have imported * from xgc but this way we see explicitly what we are getting) # arrays psin = loader.psin RZ = loader.RZ tri = loader.tri time = loader.time psin1d = loader.psin1d psin001d = loader.psin001d Te1d = loader.Te1d ne1d = loader.ne1d pot001d = loader.pot001d bfield = loader.bfield pot0 = loader.pot0 dpot = loader.dpot pot = loader.pot #if hasattr(loader,'i_T_perp'): i_T_perp = loader.i_T_perp i_E_para = loader.i_E_para e_T_perp = loader.e_T_perp e_E_para = loader.e_E_para # scalars Zcut = None Nplanes = loader.Nplanes Ntimes = loader.Ntimes dt = loader.dt #setup mesh grid if nRi == None: nRi = 100 if nZi == None: nZi = 100 Ri = np.linspace(loader.Rmin, loader.Rmax, nRi) Zi = np.linspace(loader.Zmin, loader.Zmax, nZi) (RI, ZI) = np.meshgrid(Ri, Zi) # set up to interpolate using the TriInterpolator class. Should be what tricontourf() uses triObj = Triangulation(RZ[:, 0], RZ[:, 1], tri) # get indices of RZ vertices on the separatrix sepInds = np.where(np.abs(loader.psin - 1.0) < 1e-4)[0] # flux surface values on the triangular mesh psinvalues = np.sort(np.array(list(set(np.round( psin, 4))))) # 4 round to 4 decimal places; adjust? # locate j value where Z = Zcut if Zcut == None: Zcut = Zi.mean() jcut = int(round(np.mean(np.where(np.abs(Zi - Zcut) < 1.e-1)))) #print "Zi[0:5] = ",Zi[0:5] #print "Zi[-5:0] = ",Zi[-5:-1] #print "Zcut = ",Zcut print("jcut = ", jcut) # calculate psi(Ri) = psii at the cut tci = LinearTriInterpolator(triObj, psin) psiout = tci(RI, ZI) psii = psiout[ jcut, :] # a 1D array of psin values at each Ri along the cut
for ind in range(0, len(timeindays)): 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,:]) par2=np.double(ucur[ind,:]) par3=np.double(vcur[ind,:]) 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) tli=LinearTriInterpolator(tri,par) par_interp=tli(reflon,reflat) tli2=LinearTriInterpolator(tri,par2) par2_interp=tli2(reflon,reflat) tli3=LinearTriInterpolator(tri,par3) par3_interp=tli3(reflon,reflat) #Set up a Mercator projection basemap plt.clf() #m=Basemap(projection='merc',llcrnrlon=reflon.min(),urcrnrlon=reflon.max(),\ # llcrnrlat=reflat.min(),urcrnrlat=reflat.max(),resolution='h') #x,y=m(reflon,reflat) x = reflon y = reflat u=par2_interp
def slice_to_array(self, slc, offset: float = 0.0, name: str = "Y"): """Converts a PolyData slice to a 2D NumPy array. It is crucial to have the true normal and origin of the slicing plane Parameters ---------- slc : PolyData Slice as slice through a mesh. """ # Get slice if self.debug: print(" Getting Slice") slctemp = slc.copy(deep=True) slctemp.points = (self.rotmat.T @ slctemp.points.T).T # Interpolate slices if self.debug: print(" Creating polydata") # Depending on the slice, column 1 or 2 will contain the points if offset == 0.0: points = np.vstack((slctemp.points[:, 0], slctemp.points[:, 2], np.zeros_like(slctemp.points[:, 2]))).T else: points = np.vstack((slctemp.points[:, 0], slctemp.points[:, 1], np.zeros_like(slctemp.points[:, 1]))).T pc = pv.PolyData(points) if self.debug: print(" Triangulate") mesh = pc.delaunay_2d(alpha=0.5 * 1.5 * lpy.DEG2KM) mesh[self.meshname] = slctemp[self.meshname] # Get triangles from delauney triangulation to be # used for interpolation if self.debug: print(" Reshape Triangles") xy = np.array(mesh.points[:, 0:2]) r, t = lpy.math.cart2pol(xy[:, 0], xy[:, 1]) findlimt = t + 4 * np.pi mint = np.min(findlimt) - 4 * np.pi maxt = np.max(findlimt) - 4 * np.pi cells = mesh.faces.reshape(mesh.n_cells, 4) triangles = np.array(cells[:, 1:4]) # Set maximum slice length (makes no sense otherwise) if mint < -11.25: mint = -11.25 if maxt > 11.25: maxt = 11.25 # Set up intterpolation values dmin = np.min(lpy.base.EARTH_RADIUS_KM - r) dmax = np.max(lpy.base.EARTH_RADIUS_KM - r) dsamp = np.linspace(dmin, dmax, 1000) tsamp = np.linspace(mint, maxt, 1000) tt, dd = np.meshgrid(tsamp, dsamp) # you can add keyword triangles here if you have the triangle array, # size [Ntri,3] if self.debug: print(" Triangulation 2") triObj = Triangulation(t, r, triangles=triangles) # linear interpolation fz = LinearTriInterpolator(triObj, mesh[self.meshname]) Z = fz(tt, lpy.base.EARTH_RADIUS_KM - dd) # Get aspect of the figure aspect = ((maxt - mint) * 180 / np.pi * lpy.DEG2KM) / (dmax - dmin) height = 4.0 width = height * aspect if self.debug: print(" Plotting") # Create figure plt.figure(figsize=(width, height)) plt.imshow(Z, extent=[ mint * 180 / np.pi * lpy.DEG2KM, maxt * 180 / np.pi * lpy.DEG2KM, dmax, dmin ], cmap=self.cmapname, vmin=self.clim[0], vmax=self.clim[1], rasterized=True) from_north = np.abs(self.rotangle * 180 / np.pi) + offset plt.title(rf"$N{from_north:6.2f}^\circ \rightarrow$") plt.xlabel('Offset [km]') plt.ylabel('Depth [km]') if not self.figures_only: plt.show(block=False) plt.savefig( os.path.join( self.outputdir, f"slice_{name}_" f"lat{int(self.latitude+90.0)}_" f"lon{int(self.longitude+180.0)}_" f"N{int(from_north)}_{self.meshname}.pdf")) """
#bfield fb = ad.file(fileDir + 'xgc.bfield.bp') bfield = fb['/node_data[0]/values'][spaceinds, :] fb.close() #tindex f1d = ad.file(fileDir + 'xgc.oneddiag.bp') time = np.unique(f1d['time'][:])[50:] tindex = np.unique(f1d['tindex'][:])[50:] #remove first 50 f1d.close() Ntimes = tindex.size Nplanes = 32 triObj = Triangulation(Rgrid, Zgrid, triGrid) fBR = LinearTriInterpolator(triObj, bfield[:, 0]) fBZ = LinearTriInterpolator(triObj, bfield[:, 1]) #put the required things into the parallel workers #dview.push(dict(Rgrid=Rgrid,Zgrid=Zgrid,triGrid=triGrid)) ## find blobs in each plane, time #blobInds = np.empty((Nplanes,Ntimes),dtype=object) #blobPaths = np.empty((Nplanes,Ntimes),dtype=object) #blobParams = np.empty((Nplanes,Ntimes),dtype=object) #holeInds = np.empty((Nplanes,Ntimes),dtype=object) #holePaths = np.empty((Nplanes,Ntimes),dtype=object) #holeParams = np.empty((Nplanes,Ntimes),dtype=object) #for (it,t) in enumerate(tindex): # print 'Starting time ind '+str(t) # try: