def test_lin_interp(): X = np.array([[0., 0.], [10., 0.], [10., 10.], [0., 10.]]) F = np.array([1., 2., 3., 4.]) f = field.XYZField(X=X, F=F) elev = f.interpolate([2, 3]) out = f.interpolate(X) assert np.allclose(out, F)
def test_peanut(): # like a figure 8, or a peanut r = 100 thetas = np.linspace(0, 2 * np.pi, 1000) peanut = np.zeros((len(thetas), 2), np.float64) peanut[:, 0] = r * (0.5 + 0.3 * np.cos(2 * thetas)) * np.cos(thetas) peanut[:, 1] = r * (0.5 + 0.3 * np.cos(2 * thetas)) * np.sin(thetas) min_pnt = peanut.min(axis=0) max_pnt = peanut.max(axis=0) d_data = np.array([[min_pnt[0], min_pnt[1], 1.5], [min_pnt[0], max_pnt[1], 1.5], [max_pnt[0], min_pnt[1], 8], [max_pnt[0], max_pnt[1], 8]]) density = field.XYZField(X=d_data[:, :2], F=d_data[:, 2]) trifront_wrapper([peanut], density, label='peanut')
def test_peanut(): # like a figure 8, or a peanut r = 100 thetas = np.linspace(0,2*np.pi,1000) peanut = np.zeros( (len(thetas),2), np.float64) peanut[:,0] = r*(0.5+0.3*np.cos(2*thetas))*np.cos(thetas) peanut[:,1] = r*(0.5+0.3*np.cos(2*thetas))*np.sin(thetas) min_pnt = peanut.min(axis=0) max_pnt = peanut.max(axis=0) d_data = np.array([ [min_pnt[0],min_pnt[1], 1.5], [min_pnt[0],max_pnt[1], 1.5], [max_pnt[0],min_pnt[1], 8], [max_pnt[0],max_pnt[1], 8]]) density = field.XYZField(X=d_data[:,:2],F=d_data[:,2]) p=paver.Paving(peanut,density) p.pave_all()
params('west_marsh_fill', src=field.ConstantField(10), priority=105, data_mode='diffuser(),min()', alpha_mode='feather_in(2)') ## # And do something a bit better for the mouth -- pull from # the UCB grid. pdo_grid = unstructured_grid.RgfGrid( "../data/ucb-model/MouthVariation/EpMp/PDO_EpMp.grd") pdo_grid.add_node_field('z_bed_node', -pdo_grid.nodes['depth_node']) # Convert that to a Field pdo_field = field.XYZField(X=pdo_grid.nodes['x'], F=pdo_grid.nodes['z_bed_node']) pdo_field._tri = pdo_grid.mpl_triangulation() ## params('mouth', src=pdo_field, priority=100, data_mode='blur(5)', alpha_mode='feather_in(10.0),blur_alpha(4)') params('lag_thalweg', src=field.ConstantField(0.0), priority=110, data_mode='min()', alpha_mode='feather_in(5.0),blur_alpha(10)')
# leave this test in. if os.path.exists(map_fn): if not os.path.exists(ic_fns[0]): # Get a baseline, global 2D salt field from Polaris/Peterson data if extrap_bay: from sfb_dfm_utils import initial_salinity usgs_init_salt = initial_salinity.samples_from_usgs( run_start, field='salinity') usgs_init_temp = initial_salinity.samples_from_usgs( run_start, field='temperature') cc_salt = initial_salinity.samples_to_cells(usgs_init_salt, g) cc_temp = initial_salinity.samples_to_cells(usgs_init_temp, g) salt_extrap_field = field.XYZField(X=cc_salt[:, :2], F=cc_salt[:, 2]) temp_extrap_field = field.XYZField(X=cc_temp[:, :2], F=cc_temp[:, 2]) salt_extrap_field.build_index() temp_extrap_field.build_index() missing_val = -999 else: missing_val = 32.5 # Scan the coastal model files, find one close to our start date for fn in coastal_files: snap = xr.open_dataset(fn) if snap.time.ndim > 0: snap = snap.isel(time=0) if snap.time > run_start: print("Will use %s for initial condition" % fn)
def set_lsb_bathy(grid): check_bathy() # First, load in the original sfb_dfm grid to get bathymetry log.info("Loading SFB DFM v2 grid") sfb_dfm_grid=xr.open_dataset('sfb_dfm/sfei_v19_net.nc') sfb_X=np.c_[ sfb_dfm_grid.NetNode_x.values, sfb_dfm_grid.NetNode_y.values] sfb_dfm_field=field.XYZField(X=sfb_X, F=sfb_dfm_grid.NetNode_z.values) lsb_X=grid.nodes['x'] # This will set all points within the convex hull of the original # grid. These elevations are used in the output (a) outside the # LSB merged_2m DEM, and (b) to prioritize which nodes to use when # moving depths from edges to nodes. # Could argue that it would be better to pull point elevations here # from the DEM where they overlap. Probably makes very little difference lsb_z=sfb_dfm_field(lsb_X) # still some nans at this point # log.info("Loading LSB dem from %s"%merged_2m_path) dem=field.GdalGrid(merged_2m_path) # # Use the 2m DEM to find an effective minimum depth for each edge covered # by the DEM. edge_min_depths=depth_connectivity.edge_connection_depth(grid,dem,centers='lowest') # move those edge depths to node depths node_depths=depth_connectivity.greedy_edgemin_to_node(grid,lsb_z,edge_min_depths) # Still have some nodes with nan depth, first try filling in with the DEM. missing=np.isnan(node_depths) node_depths[missing]=dem( lsb_X[missing,:] ) # And wrap it up with a more forgiving interpolation from the original sfb_dfm_v2 # grid (about 12 points on the convex hull) still_missing=np.isnan(node_depths) node_depths[still_missing]=sfb_dfm_field.interpolate( lsb_X[still_missing,:], 'nearest' ) assert np.isnan(node_depths).sum()==0 # Update the grid grid.nodes['depth']=node_depths if 0: # caller is going to deal with I/O out_file='lsb_v99_bathy_net.nc' os.path.exists(out_file) and os.unlink(out_file) dfm_grid.write_dfm(grid,out_file) if 0: # plot for development. plt.figure(10).clf() fig,ax=plt.subplots(num=10) edge_mins=grid.nodes['depth'][grid.edges['nodes']].min(axis=1) ecoll=grid.plot_edges(lw=1.5,values=edge_mins) ncoll=grid.plot_nodes(values=grid.nodes['depth']) plt.setp([ecoll,ncoll],clim=[-3,3]) plot_utils.cbar(ncoll,extras=[ecoll]) # Modified in place, but return just in case return grid # QED.
scat = ax.scatter(source_ds.x.values[close_samples, 0], source_ds.x.values[close_samples, 1], 30, close_distances[:, 1]) scat.set_clim([-40, 40]) scat.set_cmap('seismic') ax.axis((647301.6747810617, 647489.8763778533, 4185618.735872294, 4185781.4072091985)) ## # Plot those in the plane: plt.figure(2).clf() fig, (ax, ax_dem) = plt.subplots(2, 1, num=2) valid = np.isfinite(close_distances[:, 0]) f = field.XYZField(X=close_distances[valid], F=source_ds.z.values[close_samples][valid]) clim = [f.F.min(), f.F.max()] scat = ax.scatter(f.X[:, 0], f.X[:, 1], 30, f.F, cmap='jet', clim=clim) fg = f.to_grid(nx=500, ny=500, aspect=5) fg.plot(zorder=-2, ax=ax, cmap='jet', clim=clim) scat2 = ax.scatter([0.0], [0.0], 50, [dem(x_target)], cmap='jet') scat2.set_clim(clim) plt.colorbar(scat2) # and plot things in geographical coordinates
poly_pnts = np.array(poly.exterior) if np.all(poly_pnts[-1] == poly_pnts[0]): poly_pnts = poly_pnts[:-1] new_values = xyz_sub.interpolate(poly_pnts, 'nearest') poly_nodes = [] for pnt, value in zip(poly_pnts, new_values): poly_nodes.append(cdt.add_node(x=pnt, value=value)) from stompy import utils for a, b in utils.circular_pairs(poly_nodes): cdt.add_constraint(a, b) ## xyz_aug = field.XYZField(X=cdt.nodes['x'], F=cdt.nodes['value']) aug_tri = delaunay.Triangulation(xyz_aug.X[:, 0], xyz_aug.X[:, 1], cdt.cells['nodes'][~cdt.cells['deleted']]) xyz_aug._tri = aug_tri dem2 = xyz_aug.to_grid(dx=5, dy=10, interp='linear') ## plt.figure(20).clf() #fig,ax=plt.subplots(1,1,num=20,sharex=True,sharey=True) fig, (ax, ax2) = plt.subplots(1, 2, num=20, sharex=True, sharey=True) plot_wkb.plot_polygon(poly, ax=ax, fc='none')
alpha = 10 # controls the degree of anistropy coords = np.c_[cc[nbrs], alpha * psi[nbrs]] coord0 = np.array([cc[c, 0], cc[c, 1], alpha * psi[c]]) dists = utils.mag(coords - coord0) # Will take the median of a subset of those: N = int(len(dists) * 0.15) subsel = np.argsort(dists)[:N] close_nbrs = nbrs[subsel] d_med[c] = np.median(d_orig[close_nbrs]) plt.figure(13).clf() fig, axs = plt.subplots(1, 3, num=13, sharex=True, sharey=True) axs[0].set_adjustable('box', share=True) clim = [-4, 0] gr.plot_cells(values=d_orig, cmap=turbo, clim=clim, ax=axs[0]) gr.plot_cells(values=d_med, cmap=turbo, clim=clim, ax=axs[1]) gr.plot_cells(values=d_med - d_orig, cmap='coolwarm', clim=[-1, 1], ax=axs[2]) axs[0].axis(zoom) fig.tight_layout() ## from stompy.spatial import field dem_smooth = field.XYZField(gr.cells_center(), d_med).rectify() dem_smooth.write_gdal('dwr_smooth_v01.tif')
## plt.figure(10).clf() fig,ax=plt.subplots(1,1,num=10) img1=dem_crop.plot(clim=[-5,2.2],ax=ax,cmap='gray') gd.contour_node_values(psi_node,40,linewidths=0.5,colors='orange') gd.contour_node_values(phi_node,300,linewidths=0.5,colors='red') ax.axis(zoom) ## # Convert that to rasters phi_fld=field.XYZField(gr.cells_center(),phi).rectify() psi_fld=field.XYZField(gr.cells_center(),psi).rectify() ## # add psi and phi coordinates to condensed. xy=condensed.loc[:,['x','y']].values phi_fld.default_interpolation='linear' psi_fld.default_interpolation='linear' condensed['phi']=phi_fld(xy) condensed['psi']=psi_fld(xy) ## plt.figure(12).clf()
# Checking the coverage of a 2m xyz file from Ed - # seems to be just a 2m merging of the 2m DWR datasets. from stompy.spatial import field ## fn = "/home/rusty/mirrors/ucd-X/UnTRIM/JANET Files/Bay-Delta Bathymetry Data/2m.xyz" xyz = np.loadtxt(fn, delimiter=",") fx = field.XYZField(X=xyz[:, :2], F=xyz[:, 2]) f = fx.rectify(2.0, 2.0) f.write_gdal('2m.tif')
lat_min=sub_ds.lat.values.min() lat_max=sub_ds.lat.values.max() lon_min=sub_ds.lon.values.min() lon_max=sub_ds.lon.values.max() sel=((hy_bathy.Latitude.values>=lat_min) & (hy_bathy.Latitude.values<=lat_max) & (hy_bathy.Longitude.values>=lon_min) & (hy_bathy.Longitude.values<=lon_max)) bathy_xyz=np.c_[ hy_bathy.Longitude.values[sel], hy_bathy.Latitude.values[sel], hy_bathy.bathymetry.isel(MT=0).values[sel] ] bathy_xyz[:,:2]=ll2utm(bathy_xyz[:,:2]) bathy=field.XYZField(X=bathy_xyz[:,:2],F=bathy_xyz[:,2]) ## # counterclockwise along border, north to south. nodes_bc=g.select_nodes_boundary_segment([[457184, 4289741], [592899, 4037040]]) # g.plot_nodes(mask=nodes_bc,ax=ax) # good ## # rotation matrix to take true east/north vector, rotate to local UTM easting/northing # centered on given utm x,y def vec_ll2utm(utm_xy): ll0=utm2ll(utm_xy)