Example #1
0
    def trigrid(self):
        cells = self.nc.variables['nv'][:].T - 1
        points = self.points.copy()
        g = trigrid.TriGrid(points=points, cells=cells)
        areas = g.areas()
        sel = np.nonzero(areas < 0)[0]
        cells[sel, :] = cells[sel, ::-1]

        # make a clean one with the new cells
        g = trigrid.TriGrid(points=points, cells=cells)
        g.make_edges_from_cells()
        return g
Example #2
0
    def to_trigrid(self,mesh_name=None,skip_edges=False):
        nc = self.nc
        mesh_name = mesh_name or self.mesh_name
        mesh = nc.variables[mesh_name]

        node_x_name,node_y_name = mesh.node_coordinates.split()
        
        node_xy = np.array( [nc.variables[node_x_name][...],
                             nc.variables[node_y_name][...]]).T
        faces = nc.variables[mesh.face_node_connectivity][...]
        edges = nc.variables[mesh.edge_node_connectivity][...] # [N,2]
        g = trigrid.TriGrid(points=node_xy,cells=faces,edges=edges)
        
        if not skip_edges:
            # g.make_edges_from_cells() # this completely recreates the edges
            # instead, we need to discern the edge-cell connectivity from the
            # supplied edges
            pass
        return g
Example #3
0
if __name__ == '__main__':
    pc = PolarisCruise(juliandate=2008232)

    zlf = pc.z_level_field()

    # and plot the new data:

    clf()
    subplot(211)
    zlf.plot_transect()

    subplot(212)
    import trigrid
    g = trigrid.TriGrid(
        suntans_path=
        '/home/rusty/classes/research/suntans/runs/long-delta-250m/rundata')
    g.plot(all_cells=0)
    zlf.plot_surface()

    print("Extrapolated value: ", zlf.extrapolate(550000, 4.2e6, 0))

# # For reference, here are recent cruises that include the Bay Bridge
# Date          Julian Date
# 9/8/2004	2004252
# 9/14/2004	2004258
# 11/3/2004	2004308
# 12/14/2004	2004349
# 12/7/2005	2005341
# 11/22/2005	2005326
# 10/12/2005	2005285
Example #4
0
from sunboundary import modifyBCmarker
import trigrid
import numpy as np
import matplotlib.pyplot as plt

inpath = 'C:/Projects/GOMGalveston/MODELLING/GalvestonCoarseFinal/rundata/'
outpath = 'C:/Projects/GOMGalveston/MODELLING/GalvestonCoarseFinal/grid2'

g = trigrid.TriGrid(suntans_path=inpath)
for j in np.nonzero(g.edges[:, 2] == 3)[0]:
    g.delete_edge(j)
g.renumber()
g.plot()  # matplotlib plot of the edges to see if it did the right thing
g.write_suntans(outpath)
Example #5
0
class Tom(object):
    scale_shps = None
    tele_scale_shps = None
    # NB: this is adjusted by scale_factor before being handed to ApolloniusGraph
    effective_tele_rate = 1.1
    boundary_shp = None
    plot_interval = None
    checkpoint_interval = None
    smooth = 1
    resume_checkpoint_fn = None
    verbosity = 1
    dry_run = 0
    optimize = None
    interior_shps = None
    output_shp = None
    slide_interior = 1
    scale_factor = 1.0
    scale_ratio_for_cutoff = 1.0

    # These are not currently mutable from the command line
    # but could be.
    checkpoint_fn = "checkpoint.pav"
    plot_fn = "partial-grid.pdf"
    boundary_poly_shp = "processed-boundary.shp"
    smoothed_poly_shp = "smoothed-shoreline.shp"
    linestring_join_tolerance = 1.0
    scale_shp_field_name = 'scale'
    density_map = None

    # non-customizable instance variables
    original_boundary_geo = None

    def __init__(self):
        self.scale_shps = []
        self.tele_scale_shps = []

    def usage(self):
        print "tom.py   -h                   # show this help message      "
        print "         -b boundary.shp      # boundary shapefile          "
        print "         -i interior.shp      # interior paving guides      "
        print "         --slide-interior     # Allow nodes on interior lines to slide [default]"
        print "         --rigid-interior     # Force nodes on interior lines to stay put"
        print "         -s scale.shp         # scale shapefile             "
        if field.has_apollonius:
            print "         -a telescoping_scale.shp # auto telescoping scale shapefile"
            print "         -t N.NN              # telescoping rate - defaults to 1.1"
        else:
            print "         [DISABLED] -a telescoping_scale.shp"
        print "         -f N.NN              # factor for adjusting scale globally"
        print "         -C N.NN              # smoothing: min number of cells across a channel"
        print "         -p N                 # output interval for plots   "
        print "         -c N                 # checkpoint interval         "
        print "         -d                   # disable smoothing "
        print "         -o                   # enable optimization "
        print "         -r checkpoint.pav    # resume from a checkpoint    "
        print "         -v N                 # set verbosity level N"
        print "         -n                   # ready the shoreline, but don't mesh it"
        print "         -m x1,y1,x2,y2,dx,dy # output raster of scale field"

        print "         -g output.shp        # output shapefile of grid"

        print " boundary.shp: "
        print "   A shapefile containing either lines or a single polygon.  If "
        print "   lines, they must join together within a tolerance of 1.0 units"
        print " scale.shp:"
        print "   A shapefile containing points with a field 'scale', which gives"
        print "   the desired length of the edges in a region."
        print "   If the CGAL-python library is available, multiple shapefiles can "
        print "   be specified, including LineString layers."
        print " interior.shp:"
        print "   A shapefile containg line segments which will be used to guide the orientation of cells"
        print " output interval N: "
        print "   Every N steps of the algorithm create a PDF of the grid so far"
        print " checkpoint interval N:"
        print "   Every N steps of the algorithm make a backup of the grid and all"
        print "   intermediate information"
        print " resume from checkpoint"
        print "   Loads a previously saved checkpoint file and will continue where it"
        print "   left off."
        print " verbosity level N:"
        print "   Defaults to 1, which prints step numbers."
        print "   0: almost silent"
        print "   1: ~1 line per step"
        print "   2: ~30 lines per step"
        print "   3: ~100 lines per step and will try to plot intermediate stages"
        print " raster of scale field: the given region will be rasterized and output to scale-raster.tif"

    def run(self, argv):
        try:
            opts, rest = getopt.getopt(argv[1:],
                                       'hb:s:a:t:i:c:r:dv:np:om:i:f:g:C:',
                                       ['slide-interior', 'rigid-interior'])
        except getopt.GetoptError, e:
            print e
            print "-" * 80
            self.usage()
            exit(1)

        for opt, val in opts:
            if opt == '-h':
                self.usage()
                exit(1)
            elif opt == '-s':
                self.scale_shps.append(val)
            elif opt == '-a':
                self.tele_scale_shps.append(val)
            elif opt == '-t':
                self.effective_tele_rate = float(val)
            elif opt == '-f':
                self.scale_factor = float(val)
            elif opt == '-b':
                self.boundary_shp = val
            elif opt == '-p':
                self.plot_interval = int(val)
            elif opt == '-c':
                self.checkpoint_interval = int(val)
            elif opt == '-C':
                self.scale_ratio_for_cutoff = float(val)
            elif opt == '-r':
                self.resume_checkpoint_fn = val
            elif opt == '-d':
                self.smooth = 0
            elif opt == '-v':
                self.verbosity = int(val)
            elif opt == '-n':
                self.dry_run = 1
            elif opt == '-o':
                self.optimize = 1
            elif opt == '-m':
                self.density_map = val
            elif opt == '-i':
                if not self.interior_shps:
                    self.interior_shps = []
                self.interior_shps.append(val)
            elif opt == '-g':
                self.output_shp = val
            elif opt == '--slide-interior':
                self.slide_interior = 1
            elif opt == '--rigid-interior':
                self.slide_interior = 0

        self.check_parameters()

        log_fp = open('tom.log', 'wt')
        log_fp.write("TOM log:\n")
        log_fp.write(" ".join(argv))
        log_fp.close()

        if not self.resume_checkpoint_fn:
            bound_args = self.prepare_boundary()
            density_args = self.prepare_density()

            args = {}
            args.update(bound_args)
            args.update(density_args)
            args['slide_internal_guides'] = self.slide_interior

            # Wait until after smoothing to add degenerate interior lines
            # args.update(self.prepare_interiors())

            self.p = paver.Paving(**args)
            self.p.verbose = self.verbosity

            self.p.scale_ratio_for_cutoff = self.scale_ratio_for_cutoff

            if self.smooth:
                self.p.smooth()
                # and write out the smoothed shoreline
                wkb2shp.wkb2shp(self.smoothed_poly_shp, [self.p.poly],
                                overwrite=True)

            int_args = self.prepare_interiors()

            if int_args.has_key('degenerates'):
                for degen in int_args['degenerates']:
                    self.p.clip_and_add_degenerate_ring(degen)
        else:
            self.p = paver.Paving.load_complete(self.resume_checkpoint_fn)
            self.p.verbose = self.verbosity

        if self.dry_run:
            print "dry run..."
        elif self.density_map:
            f = self.p.density
            x1, y1, x2, y2, dx, dy = map(float, self.density_map.split(','))
            bounds = np.array([[x1, y1], [x2, y2]])
            rasterized = f.to_grid(dx=dx, dy=dy, bounds=bounds)
            rasterized.write_gdal("scale-raster.tif")
        else:
            starting_step = self.p.step
            self.create_grid()

            if (not os.path.exists('final.pav')
                ) or self.p.step > starting_step:
                self.p.write_complete('final.pav')
            if (not os.path.exists('final.pdf')
                ) or self.p.step > starting_step:
                self.plot_intermediate(fn='final.pdf', color_by_step=False)

            # write grid as shapefile
            if self.output_shp:
                print "Writing shapefile with %d features (edgse)" % (
                    self.p.Nedges())
                self.p.write_shp(self.output_shp,
                                 only_boundaries=0,
                                 overwrite=1)
                # by reading the suntans grid output back in, we should get boundary edges
                # marked as 1 - self.p probably doesn't have these markers
                g = trigrid.TriGrid(suntans_path='.')
                g.write_shp('trigrid_write.shp',
                            only_boundaries=0,
                            overwrite=1)

            if self.optimize:
                self.run_optimization()
                self.p.write_complete('post-optimize.pav')
                self.plot_intermediate(fn='post-optimize.pdf')
Example #6
0
    areas[i] = dA * sum(wet)
    vols[i] = (dA * (depths[i] - xyz.F[wet])).sum()

    print "%g: %g %g" % (depths[i], areas[i], vols[i])

if 0:
    clf()
    subplot(2, 1, 1)
    plot(depths, areas)
    subplot(2, 1, 2)
    plot(depths, vols)

# load the false deltas:
import trigrid

delta1grid = trigrid.TriGrid(
    sms_fname='/home/rusty/classes/research/meshing/delta_1.grd')
delta2grid = trigrid.TriGrid(
    sms_fname='/home/rusty/classes/research/meshing/delta_2.grd')

dpoints = []
delevs = []

total_false_area = abs(delta1grid.areas()).sum() + abs(
    delta2grid.areas()).sum()

depth_factor = areas[-1] / total_false_area
print "Multiplying depths by: ", depth_factor

for dgrid in [delta1grid, delta2grid]:
    # they're tilings, but go ahead and take the mean area:
    dA = abs(dgrid.areas()).mean()  # the area of one triangle
Example #7
0
def depths_onto_grid(grid_dir,depth_field_thunk,output_dir=None,do_plot=False):
    gridpath = grid_dir
    output_dir = output_dir or grid_dir
    
    g = trigrid.TriGrid(suntans_path=gridpath)

    depth_field = depth_field_thunk()
    
    bathy_offset = sunreader.read_bathymetry_offset()

    vc = g.vcenters()

    elevations = depth_field(vc)

    depths = bathy_offset - elevations

    # combine to one array:
    xyz = concatenate( (vc,depths[:,newaxis]), axis=1)
    savetxt(os.path.join(output_dir,'depth.dat'),xyz)

    # try putting depths on edges, then back-calculate cell depths:
    edgedepths = zeros( (g.Nedges(),3), float64)
    edgedepths[:,:2] = g.edge_centers()

    for j in range(g.Nedges()):
        if j % 1000==0:
            print "%d/%d"%(j,g.Nedges())
        edgedepths[j,2] = bathy_offset - depth_field.value_on_edge(g.points[g.edges[j,:2]])
    savetxt(os.path.join(output_dir,'edgedepth.dat'),edgedepths)    

    # and write a new cell depths file which takes its depth from the edges.
    celldepths = xyz.copy()
    for i in range(g.Ncells()):
        jlist = g.cell2edges(i)
        celldepths[i,2] = edgedepths[jlist,2].max()
    savetxt(os.path.join(output_dir,'depth-fromedges.dat'),celldepths)

    delta = celldepths[:,2] - xyz[:,2]

    if do_plot:
        if 1:
            depths = celldepths
            lognorm = colors.LogNorm(vmin=max(1.0,nanmin(depths[:,2])),
                                     vmax=nanmax( depths[:,2] ) )
            # cmap = gmtcm("BkBlAqGrYeOrReViWh200")
            cmap = load_gradient("oc-sst.cpt")

            figure(figsize=(100,100))
            ax = axes([0,0,1,1])
            ax.set_axis_bgcolor('gray')

            coll = g.plot_scalar(depths[:,2])
            coll.norm = lognorm
            coll.set_cmap(cmap)

            ax.xaxis.set_visible(0)
            ax.yaxis.set_visible(0)

            cax = axes([0.87,0.2,0.03,0.6])
            cbar = colorbar(coll,cax=cax)
        if 1:
            ticks = [2,5,10,20,50,100,200,500]
            cbar.set_ticks(ticks)
            cbar.set_ticklabels(ticks)
            ax.axis('equal')
            savefig(os.path.join(output_dir,'grid_and_bathy.pdf'))