def init_geometry(self):
        """
        Compile a grid with simple polygon cells from the 
        boundaries in bounds_shp
        """
        g = unstructured_grid.UnstructuredGrid()

        for geo in self.bounds['geom']:
            pnts = np.array(geo)

            A = pnts[:-1]
            B = pnts[1:]

            for a, b in zip(A, B):
                na = g.add_or_find_node(x=a)
                nb = g.add_or_find_node(x=b)
                try:
                    j = g.add_edge(nodes=[na, nb])
                except g.GridException:
                    pass

        cycles = g.find_cycles(max_cycle_len=g.Nnodes())

        polys = [geometry.Polygon(g.nodes['x'][cycle]) for cycle in cycles]

        gc = unstructured_grid.UnstructuredGrid(
            max_sides=max([len(cyc) for cyc in cycles]))

        gc.copy_from_grid(g)

        for cyc in cycles:
            gc.add_cell(nodes=cyc)

        self.g = gc
Esempio n. 2
0
    def set_grid(self):
        g = ugrid.UnstructuredGrid(max_sides=4)
        g.add_rectilinear([0, 0], [self.L, self.W], self.nx, self.ny)
        g.orient_edges()
        g.add_cell_field('cell_z_bed', self.z_bed(g.cells_center()))

        super(TwoCell, self).set_grid(g)
Esempio n. 3
0
    def __init__(self,**kw):
        super().__init__(**kw)
        self.set_run_dir(self.run_dir,mode='pristine')
        g=unstructured_grid.UnstructuredGrid(max_sides=4)
        g.add_rectilinear([0,0],
                          [self.L,self.W],
                          nx=1+self.Lcells,ny=1+self.Wcells)
        node_z_bed=-2*np.ones(g.Nnodes())
        # node_z_bed=-2 + ((m_gate5.grid.nodes['x'][:,0] - 50) / 50).clip(0)
        g.add_node_field('node_z_bed',node_z_bed)
        super().__init__(grid=g,
                         run_start=np.datetime64("2010-01-01 00:00"),
                         run_stop =np.datetime64("2010-01-02 00:00"),
                         **kw)
        self.set_bcs()
        self.add_monitor_sections( [ dict(geom=geometry.LineString([[50,0],[50,20]]),
                                          name='at_gate'),
                                     dict(geom=geometry.LineString([[80,0],[80,20]]),
                                          name='downstream') ] )

        self.mdu['geometry','kmx']=self.n_layers
        self.mdu['geometry','Layertype']=2 # 1: sigma, 2: z, 3: read pliz file

        # Turn on salinity:
        self.mdu['physics','salinity']=1
        # Will come back to implement a 3D IC
        self.mdu['physics','InitialSalinity']=15
        self.mdu['physics','Idensform']=2

        # Decrease imposed mixing to simplify tests
        self.mdu['physics','Vicouv']=0.0  # Uniform horizontal eddy viscosity (m2/s)
        self.mdu['physics','Dicouv']=0.0  # eddy diffusivity (m2/s)
        self.mdu['physics','Vicoww']= 1e-6  # Uniform vertical eddy viscosity (m2/s)
        self.mdu['physics','Dicoww']= 1e-6  # Uniform vertical eddy diffusivity (m2/s)
    def make_2D_grid_Cartesian(self, L, nwide=3, show_grid=False):
        """
        Setup unstructured grid for channel n cells wide
        Grid is Cartesian with edge length = self.dx
        """
        nlong = int(L / self.dx)
        ncells = nlong * nwide
        npoints = (nlong + 1) * (nwide + 1)
        nedges = nwide * (nlong + 1) + (nwide + 1) * nlong
        points = np.zeros((npoints, 2), np.float64)
        cells = -1 * np.ones((ncells, 4), np.int32)  # cell nodes
        edges = -1 * np.ones((nedges, 2), np.int32)  # edge nodes
        ipt = 0
        for i in range(nlong + 1):
            x = self.dx * i
            for j in range(nwide + 1):
                y = self.dx * j
                points[ipt, 0] = x
                points[ipt, 1] = y
                ipt += 1
        icell = 0
        for i in range(nlong):
            for j in range(nwide):
                i1 = icell + i
                i2 = i1 + 1
                i3 = icell + nwide + i + 1
                i4 = i3 + 1
                cells[icell, :] = [i3, i4, i2, i1]
                icell += 1
        iedge = 0
        for i in range(nlong):
            for j in range(nwide):
                icell = i * nwide + j
                i1 = icell + i
                i2 = i1 + 1
                i3 = icell + nwide + i + 1
                i4 = i3 + 1
                if j == 0:
                    edges[iedge, :] = [i1, i3]  # bottom
                    iedge += 1
                edges[iedge, :] = [i1, i2]  # left
                iedge += 1
                edges[iedge, :] = [i2, i4]  # top
                iedge += 1
        i = nlong - 1  # last column right edges
        for j in range(nwide):
            icell = i * nwide + j
            i3 = icell + nwide + i + 1
            i4 = i3 + 1
            edges[iedge, :] = [i3, i4]  # top
            iedge += 1
        self.grd = ugrid.UnstructuredGrid(edges=edges,
                                          points=points,
                                          cells=cells,
                                          max_sides=4)
        if show_grid:
            self.grd.plot_edges()
            plt.show()

        return
    def __init__(self, **kw):
        self.set_run_dir(self.run_dir, mode='pristine')
        g = unstructured_grid.UnstructuredGrid(max_sides=4)
        # Sort of Pescadero Lagoon-ish
        g.add_rectilinear([0, 0], [600, 100], nx=60, ny=5)
        node_z_bed = -0.5 * np.ones(g.Nnodes())
        g.add_node_field('node_z_bed', node_z_bed)
        super().__init__(grid=g,
                         run_start=np.datetime64("2010-01-01 00:00"),
                         run_stop=np.datetime64("2010-01-03 00:00"),
                         **kw)
        self.set_bcs()

        self.config_layers()

        self.mdu['output', 'MapFormat'] = 4  # ugrid

        # Turn on salinity:
        self.mdu['physics', 'salinity'] = 1
        self.mdu['physics', 'temperature'] = 0

        self.mdu['physics', 'InitialSalinity'] = 15
        self.mdu['physics', 'Idensform'] = 2

        self.add_monitor_points([
            dict(geom=geometry.Point([10, 50]), name='flow_end'),
            dict(geom=geometry.Point([10, 50]), name='stage_end')
        ])
Esempio n. 6
0
    def __init__(self, **kw):
        super().__init__(run_start=np.datetime64("2010-01-01 00:00"),
                         run_stop=np.datetime64("2010-01-05 00:00"),
                         **kw)

        self.set_run_dir(self.run_dir, mode='pristine')
        g = unstructured_grid.UnstructuredGrid(max_sides=4)
        # Sort of Pescadero Lagoon-ish
        g.add_rectilinear([0, 0], [600, 100], nx=30, ny=5)

        # Sloping bed to better understand uplift.
        # node_z_bed=-0.5*np.ones(g.Nnodes())
        # slopes from 0.5 at x=0 to -0.5 at x=600
        node_z_bed = 0.5 - 1.0 * g.nodes['x'][:, 0] / 600.
        g.add_node_field('node_z_bed', node_z_bed)
        self.set_grid(g)
        self.set_bcs()

        self.mdu['geometry', 'BedLevType'] = 4

        self.config_layers()

        self.mdu['output', 'MapFormat'] = 4  # ugrid

        # Turn on salinity:
        self.mdu['physics', 'salinity'] = 0
        self.mdu['physics', 'temperature'] = 0

        self.mdu['physics', 'InitialSalinity'] = 15
        self.mdu['physics', 'Idensform'] = 2

        self.add_monitor_points([
            dict(geom=geometry.Point([10, 50]), name='flow_end'),
            dict(geom=geometry.Point([10, 50]), name='stage_end')
        ])
Esempio n. 7
0
def thacker_grid():
    thacker_2d_fn='thacker2d-%g.nc'%R
    if not os.path.exists(thacker_2d_fn):
        # Generate a radial grid
        g=unstructured_grid.UnstructuredGrid(max_sides=4)

        # Add guide rings
        scale=R/20.0 # nominal edge length

        nspoke0=4*8
        g.add_quad_ring(0*scale,1*scale,nrows=2,nspokes=nspoke0//4,sides=3,stagger0=0.75)
        g.add_quad_ring(1*scale,2*scale,nrows='stitch',nspokes=nspoke0//4,stagger0=0.25)
        g.add_quad_ring(2*scale,3*scale,nrows=2,nspokes=nspoke0/2,sides=3,stagger0=0.5) 
        g.add_quad_ring(3*scale,4*scale,nrows='stitch',nspokes=nspoke0/2) # row of quads
        g.add_quad_ring(4*scale,5*scale,nrows=2,nspokes=nspoke0) # row of quads
        g.add_quad_ring(5*scale,6*scale,nrows='stitch',nspokes=nspoke0)
        g.add_quad_ring(6*scale,10*scale,5,2*nspoke0)
        g.add_quad_ring(10*scale,11*scale,'stitch',2*nspoke0)
        g.add_quad_ring(11*scale,20*scale,11,4*nspoke0)

        g.make_cells_from_edges()
        g.edge_to_cells(recalc=True)
        g.renumber()
        g.write_ugrid(thacker_2d_fn,overwrite=True)
        
    g=unstructured_grid.UnstructuredGrid.read_ugrid(thacker_2d_fn)
    return g
    def set_grid(self):
        g = ugrid.UnstructuredGrid(max_sides=4)
        g.add_rectilinear([-self.L / 2, 0], [self.L / 2, self.W], self.nx + 1,
                          self.ny)
        g.orient_edges()

        super(SubgridThacker1D, self).set_grid(g)
Esempio n. 9
0
def test_sed_mpi():
    model=base_model()
    
    g=unstructured_grid.UnstructuredGrid(max_sides=4)
    g.add_rectilinear([0,0],[1000,100],101,11)
    g.add_cell_field('depth',-6*np.ones(g.Ncells()))

    model.set_grid(g)

    model.num_procs=4
    model.config['dt']=3.

    # slow down the settling velocities to get some advection mixed in
    model.config['Ws01']= 0.0001     # constant settling velocity for fraction No.1 (m/s)
    model.config['Ws02']= 0.0005     # constant settling velocity for fraction No.2
    model.config['Ws03']=-0.0005     # constant settling velocity for fraction No.3

    geom=np.array([ [1000,0],
                    [1000,100]])
    Q_bc=sun_driver.FlowBC(name="Q_bc",
                           geom=geom,
                           Q=100.0)
    
    model.add_bcs( [Q_bc,
                    sun_driver.ScalarBC(parent=Q_bc,scalar="S",value=2),
                    sun_driver.ScalarBC(parent=Q_bc,scalar="T",value=0)] )

    point_bc=sun_driver.SourceSinkBC(name="bedPoint",
                                     geom=np.array([500,20]),
                                     Q=10)
    model.add_bcs( [point_bc,
                    sun_driver.ScalarBC(parent=point_bc,scalar="S",value=3),
                    sun_driver.ScalarBC(parent=point_bc,scalar="T",value=3)] )
                    
    model.write()

    # leave some dry layers at the surface
    model.ic_ds.eta.values[:]=model.bcs[0].z
    model.ic_ds.salt.values[:]=1.0
    model.ic_ds.temp.values[:]=1.0

    model.write_ic_ds()
        
    for sed_idx in range(3):
        name="sed%d"%(sed_idx+1)
        model.bc_ds['boundary_'+name]=model.bc_ds['boundary_S'].copy()
        model.bc_ds[name]=model.bc_ds['S'].copy()
        model.bc_ds['point_'+name]=model.bc_ds['point_S'].copy()
        
        model.bc_ds['boundary_'+name].values[:]=sed_idx*1.0
        model.bc_ds[name].values[:]=0.0
        model.bc_ds['point_'+name].values[:]=sed_idx*2.0

    model.write_bc_ds()
    
    model.partition()
    model.sun_verbose_flag='-v'
    model.run_simulation()
    return model
Esempio n. 10
0
 def init():
     # inserting a constraint
     dt = unstructured_grid.UnstructuredGrid()
     cdt = cdt_class(dt)
     pnts = [[0, 0], [5, 0], [10, 0], [5, 5], [3, 0], [6, 2], [12, 4]]
     for pnt in pnts:
         dt.add_node(x=pnt)
     return dt, cdt
Esempio n. 11
0
def test_flip1_cgal():
    plot = False
    g = unstructured_grid.UnstructuredGrid()
    cdt = shadow_cdt.ShadowCGALCDT(g)

    pnts = [[0, 0], [8, 0], [10, 5], [5, 5], [3, 0]]

    [g.add_node(x=pnt) for pnt in pnts]
Esempio n. 12
0
    def set_grid(self):
        g = ugrid.UnstructuredGrid(max_sides=4)
        g.add_rectilinear([0, 0], [self.L, self.W], self.nx, self.ny)
        g.orient_edges()

        g.add_node_field('node_z_bed', self.z_bed(g.nodes['x']))
        g.add_cell_field('cell_z_bed', self.z_bed(g.cells_center()))

        super(SwampyBump1D, self).set_grid(g)
Esempio n. 13
0
def test_duplicate_edge():
    ug=unstructured_grid.UnstructuredGrid(max_sides=4)

    n1=ug.add_node(x=[0,0])
    n2=ug.add_node(x=[1,0])

    j1=ug.add_edge(nodes=[n1,n2])

    with assert_raises(unstructured_grid.GridException) as cm:
        j2=ug.add_edge(nodes=[n2,n1])
Esempio n. 14
0
def base_grid():
    g = ugrid.UnstructuredGrid(max_sides=4)

    g.add_rectilinear([0, 0], [L, W], nx, ny)

    # z=0 along lower edge, and 10 on the upper edge.
    # node_depths=-g.nodes['x'][:,1]/10.
    node_depths = dem(g.nodes['x'])

    g.add_node_field('depth', node_depths)
    return g
    def import_ras_geometry(self,
                            hdf_fname,
                            twod_area_name,
                            max_cell_faces,
                            show_grid=False):

        h = h5py.File(hdf_fname, 'r')

        points_xy = h['Geometry/2D Flow Areas/' + twod_area_name +
                      '/FacePoints Coordinate']
        npoints = len(points_xy)
        points = np.zeros((npoints, 2), np.float64)
        for n in range(npoints):
            points[n, 0] = points_xy[n][0]
            points[n, 1] = points_xy[n][1]

        edge_nodes = h['Geometry/2D Flow Areas/' + twod_area_name +
                       '/Faces FacePoint Indexes']
        nedges = len(edge_nodes)
        edges = -1 * np.ones((nedges, 2), dtype=int)
        for j in range(nedges):
            edges[j][0] = edge_nodes[j][0]
            edges[j][1] = edge_nodes[j][1]

        cell_nodes = h['Geometry/2D Flow Areas/' + twod_area_name +
                       '/Cells FacePoint Indexes']
        for i in range(len(cell_nodes)):
            if cell_nodes[i][
                    2] < 0:  # first ghost cell (which are sorted to end of list)
                break
        ncells = i  # don't count ghost cells
        cells = -1 * np.ones((ncells, max_cell_faces), dtype=int)
        for i in range(ncells):
            for k in range(max_cell_faces):
                cells[i][k] = cell_nodes[i][k]

        cell_center_xy = h['Geometry/2D Flow Areas/' + twod_area_name +
                           '/Cells Center Coordinate']
        self.ras_xf = np.array([cell_center_xy[i][0] for i in range(ncells)])
        self.ras_yf = np.array([cell_center_xy[i][1] for i in range(ncells)])

        self.grd = ugrid.UnstructuredGrid(edges=edges,
                                          points=points,
                                          cells=cells,
                                          max_sides=max_cell_faces)

        if show_grid:
            self.grd.plot_edges()
            ax = plt.gca()
            ax.plot(self.ras_xf, self.ras_yf, 'rs', ms=3, mfc='none')
            plt.show()

        return
Esempio n. 16
0
def test_triangle_from_scratch():
    ug=unstructured_grid.UnstructuredGrid(max_sides=4)

    n1=ug.add_node(x=[0,0])
    n2=ug.add_node(x=[1,0])
    n3=ug.add_node(x=[1,1])

    j1=ug.add_edge(nodes=[n1,n2])
    j2=ug.add_edge(nodes=[n2,n3])
    j3=ug.add_edge(nodes=[n3,n1])

    c1=ug.toggle_cell_at_point([0.2,0.2])
Esempio n. 17
0
def test_point_source_1d():
    """
    Create a 1D water column, with a point source at the bed.
    Verifies that all cells with valid thickness (dzz>0.001m)
    have near unity salinity.
    """
    g=unstructured_grid.UnstructuredGrid(max_sides=4)
    g.add_rectilinear([0,0],[10,10],2,2)

    g.add_cell_field('depth',-6*np.ones(g.Ncells()))

    model=sun_driver.SuntansModel()
    model.load_template('point_source_test.dat')
    model.set_grid(g)
    model.run_start=np.datetime64("2018-01-01 00:00")
    model.run_stop =np.datetime64("2018-01-01 10:00")

    source=sun_driver.SourceSinkBC(name='inflow',geom=np.array([5,5]),
                                   z=-10,Q=1.0)
    model.add_bcs(source)
    model.add_bcs( [sun_driver.ScalarBC(parent=source,scalar="S",value=1),
                    sun_driver.ScalarBC(parent=source,scalar="T",value=1)] )

    model.set_run_dir('rundata_point_1d', mode='pristine')
    model.projection='EPSG:26910'

    model.config['dt']=2.5
    model.config['ntout']=1
    model.config['Cmax']=30
    model.config['Nkmax']=10
    model.config['stairstep']=0
    model.config['mergeArrays']=0

    model.write()

    model.ic_ds.eta.values[:]=-5.999
    model.ic_ds.salt.values[:]=1.0
    model.ic_ds.temp.values[:]=1.0
    model.write_ic_ds()

    model.partition()
    model.sun_verbose_flag='-v'
    model.run_simulation()

    ds=xr.open_dataset(model.map_outputs()[0])

    dzz=ds.dzz.values
    dzz_thresh=0.001
    salt=ds.salt.values
    salt_errors=salt[dzz>=dzz_thresh] - 1.0
    
    assert np.max( np.abs(salt_errors) )<0.001
Esempio n. 18
0
def test_pickle():
    ug=unstructured_grid.UnstructuredGrid(max_sides=4)
    def cb(*a,**k):
        pass
    ug.subscribe_after('add_node',cb)
    chk=ug.checkpoint()

    n1=ug.add_node(x=[0,0])
    n2=ug.add_node(x=[1,0])

    j1=ug.add_edge(nodes=[n1,n2])

    ug.write_pickle('blah.pkl')
    ug2=unstructured_grid.UnstructuredGrid.from_pickle('blah.pkl')
Esempio n. 19
0
def test_constraints_dim1_cgal():
    g = unstructured_grid.UnstructuredGrid()
    cdt = shadow_cdt.ShadowCGALCDT(g)
    pnts = [[0, 0], [5, 0], [10, 0]]
    nodes = [g.add_node(x=pnt) for pnt in pnts]

    j0 = g.add_edge(nodes=[nodes[0], nodes[1]])
    j1 = g.add_edge(nodes=[nodes[1], nodes[2]])
    g.delete_edge(j0)
    g.delete_edge(j1)
    try:
        g.add_edge(nodes=[nodes[0], nodes[2]])
        assert False
    except cdt.ConstraintCollinearNode:
        pass  #
Esempio n. 20
0
def process_quad_patch(name, M=None):

    center_idx = np.nonzero(centerlines['name'] == name)[0][0]
    centerline = centerlines['geom'][center_idx]
    if M is None:
        M = centerlines['rows'][center_idx]
    bound = bounds['geom'][bounds['name'] == name][0]

    center = linestring_utils.resample_linearring(np.array(centerline),
                                                  scale,
                                                  closed_ring=0)

    g = unstructured_grid.UnstructuredGrid(max_sides=6)

    # Smooth the exterior

    ext_points = np.array(bound.exterior)
    ext_points = linestring_utils.resample_linearring(ext_points,
                                                      scale,
                                                      closed_ring=True)
    from stompy import filters
    ext_points[:, 0] = filters.lowpass_fir(ext_points[:, 0], 3)
    ext_points[:, 1] = filters.lowpass_fir(ext_points[:, 1], 3)
    smooth_bound = geometry.Polygon(ext_points)

    L = smooth_bound.exterior.length

    def profile(x, s, perp):
        probe_left = geometry.LineString([x, x + L * perp])
        probe_right = geometry.LineString([x, x - L * perp])

        left_cross = smooth_bound.exterior.intersection(probe_left)
        right_cross = smooth_bound.exterior.intersection(probe_right)

        assert left_cross.type == 'Point', "Fix this for multiple intersections"
        assert right_cross.type == 'Point', "Fix this for multiple intersections"

        pnt_left = np.array(left_cross)
        pnt_right = np.array(right_cross)
        d_left = utils.dist(x, pnt_left)
        d_right = utils.dist(x, pnt_right)

        return np.interp(np.linspace(-1, 1, M), [-1, 0, 1],
                         [-d_right, 0, d_left])

    g.add_rectilinear_on_line(center, profile)
    g.renumber()
    return g
Esempio n. 21
0
def test_quad_from_scratch():
    ug=unstructured_grid.UnstructuredGrid(max_sides=4)

    n1=ug.add_node(x=[0,0])
    n2=ug.add_node(x=[1,0])
    n3=ug.add_node(x=[1,1])
    n4=ug.add_node(x=[0,1])

    j1=ug.add_edge(nodes=[n1,n2])
    j2=ug.add_edge(nodes=[n2,n3])
    j3=ug.add_edge(nodes=[n3,n4])
    j4=ug.add_edge(nodes=[n4,n1])

    c1=ug.toggle_cell_at_point([0.2,0.2])
    # and remove it..
    ug.toggle_cell_at_point([0.2,0.2])
Esempio n. 22
0
def test_remove_constraint_cgal():
    g = unstructured_grid.UnstructuredGrid()
    cdt = shadow_cdt.ShadowCGALCDT(g)

    # inserting a constraint
    pnts = [[0, 0], [5, 0], [10, 0], [5, 5], [3, 0], [6, 2], [12, 4]]
    nodes = [g.add_node(x=pnt) for pnt in pnts]

    j0 = g.add_edge(nodes=[nodes[4], nodes[6]])
    nodes.append(g.add_node(x=[7, 0.5]))

    g.delete_edge(j0)
    j1 = g.add_edge(nodes=[nodes[2], nodes[3]])
    j2 = g.add_edge(nodes=[nodes[4], nodes[7]])
    g.delete_edge(j1)
    g.delete_edge(j2)
Esempio n. 23
0
def test_fuzz1_cgal():
    plot = False
    # Fuzzing, regular
    x = np.arange(5)
    y = np.arange(5)

    X, Y = np.meshgrid(x, y)
    xys = np.array([X.ravel(), Y.ravel()]).T

    if plot:
        plt.figure(1).clf()
        fig, ax = plt.subplots(num=1)

        ax.plot(xys[:, 0], xys[:, 1], 'go', alpha=0.4)
        ax.axis([-1, 5, -1, 5])

    idxs = np.zeros(len(xys), 'i8') - 1

    g = unstructured_grid.UnstructuredGrid()
    cdt = shadow_cdt.ShadowCGALCDT(g)

    # definitely slows down as the number of nodes gets larger.
    # starting off with <1s per 100 operations, later more like 2s
    for repeat in range(1):
        print "Repeat: ", repeat
        for step in range(1000):
            if step % 200 == 0:
                print "  step: ", step
            toggle = np.random.randint(len(idxs))
            if idxs[toggle] < 0:
                idxs[toggle] = g.add_node(x=xys[toggle])
            else:
                g.delete_node(idxs[toggle])
                idxs[toggle] = -1

            if plot:
                del ax.lines[1:]
                ax.texts = []
                ax.collections = []
                dt.plot_nodes(labeler=lambda n, nrec: str(n))
                dt.plot_edges(alpha=0.5, lw=2)
                dt.plot_cells(lw=7,
                              facecolor='#ddddff',
                              edgecolor='w',
                              zorder=-5)
                plt.draw()
Esempio n. 24
0
def run_node_insertion(cdt_class):
    g = unstructured_grid.UnstructuredGrid()

    cdt = cdt_class(g)

    pnts = [[0, 0], [5, 0], [10, 0], [5, 5]]

    nA = g.add_node(x=pnts[0])  # This tests insert into empty
    g.add_node(x=pnts[1])  # adjacent_vertex
    g.add_node(x=pnts[2])  # adjacent_vertex
    g.add_node(x=pnts[3])  # adjacent_edge

    g.add_node(x=[3, 0])  # colinear

    g.add_node(x=[6, 2])  # into cell interior
    nB = g.add_node(x=[12, 4])  # collinear cell interior
    return g, cdt  # helps with debugging
Esempio n. 25
0
def base_model(force=True, num_procs=1, run_dir='run-dfm-test'):
    if not force and dflow_model.DFlowModel.run_completed(run_dir):
        model = dflow_model.DFlowModel.load(run_dir)
        return model

    g = unstructured_grid.UnstructuredGrid(max_sides=4)

    ret = g.add_rectilinear([0, 0], [500, 500], 50, 50)

    # sloping N-S from -3 at y=0 to +2 at y=500
    g.add_node_field('depth', -3 + g.nodes['x'][:, 1] / 100)

    model = dflow_model.DFlowModel()
    model.load_template('dflow-template.mdu')
    model.set_grid(g)

    model.num_procs = num_procs

    model.set_run_dir(run_dir, mode='pristine')
    model.run_start = np.datetime64("2018-01-01 00:00")
    model.run_stop = np.datetime64("2018-01-03 00:00")
    dt = np.timedelta64(300, 's')
    t = np.arange(model.run_start - 20 * dt, model.run_stop + 20 * dt, dt)
    # 4h period
    periodic_Q = 50 * np.sin(
        (t - t[0]) / np.timedelta64(1, 's') * 2 * np.pi / (4 * 3600.))
    Q = xr.DataArray(periodic_Q, dims=['time'], coords={'time': t})
    inflow = dflow_model.FlowBC(name='inflow',
                                geom=np.array([[0, 0], [0, 500]]),
                                Q=Q)
    model.add_bcs(inflow)

    model.projection = 'EPSG:26910'
    model.mdu['geometry', 'WaterLevIni'] = 0.0
    model.mdu['output', 'WaqInterval'] = 1800
    model.mdu['output', 'MapInterval'] = 1800
    model.write()

    if not model.is_completed():
        model.partition()
        model.run_model()

    return model
    def build_net(self):
        """
        Build a pseudo grid that has edges for neighbors (like a dual, but including
        a larger neighborhood.
        """
        self.t_dual = self.g

        # transit time network
        self.t_net = unstructured_grid.UnstructuredGrid(extra_node_fields=[
            ('value', np.float64), ('dual_cell', np.int32),
            ('hydro_cell', np.int32)
        ],
                                                        extra_edge_fields=[
                                                            ('Td', np.float64)
                                                        ])

        self.dual_to_net_node = {}  # speed up the reverse lookup
        cc = g.cells_center()
        for c in np.nonzero(self.g.cell_clip_mask(self.clip))[0]:
            n = self.t_net.add_node(x=cc[c],
                                    value=np.nan,
                                    dual_cell=c,
                                    hydro_cell=c)
            self.dual_to_net_node[c] = n

        # Create the neighborhood connectivity
        for n in range(self.t_net.Nnodes()):
            c = self.t_net.nodes['dual_cell'][n]
            # use nodes to get the neighborhood of cells
            c_nodes = self.g.cell_to_nodes(c)
            c_cells = []
            for c_node in c_nodes:
                c_cells += list(self.g.node_to_cells(c_node))
            c_cells = set(c_cells)
            for cnbr in c_cells:
                if (cnbr == c) or (cnbr not in self.dual_to_net_node):
                    # if we clipped the original, this will have a few
                    # hits outside the clip, which we ignore.
                    continue
                try:
                    self.t_net.add_edge(nodes=[n, self.dual_to_net_node[cnbr]])
                except self.t_net.GridException:
                    pass  # b/c the edge is already there - great.
    def make_1D_grid_Cartesian_non_orthog(self, L, show_grid=False):
        """
        Setup unstructured grid for channel 1 cell wide
        Grid is Cartesian with edge length = self.dx
          but then has random displacement of nodes to create non-orothgonality
        """
        ncells = int(L / self.dx)
        npoints = 2 * ncells + 2
        nedges = 3 * ncells + 1
        points = np.zeros((npoints, 2), np.float64)
        # in future if only 3 edges, node4 will have value -1
        cells = -1 * np.ones((ncells, 4), np.int32)  # cell nodes
        edges = -1 * np.ones((nedges, 2), np.int32)  # edge nodes
        max_displacement = 0.4
        for i in range(ncells + 1):  # set node x,y etc.
            disp = 2 * max_displacement * random.random() - max_displacement
            points[2 * i, 0] = self.dx * i + disp
            disp = 2 * max_displacement * random.random() - max_displacement
            points[2 * i, 1] = 0.0 + disp
            disp = 2 * max_displacement * random.random() - max_displacement
            points[2 * i + 1, 0] = self.dx * i + disp
            disp = 2 * max_displacement * random.random() - max_displacement
            points[2 * i + 1, 1] = self.dx + disp
            if i < ncells:
                cells[i, :] = [2 * (i + 1), 2 * (i + 1) + 1, 2 * i + 1, 2 * i]
                # bottom of cell
                edges[3 * i, :] = [2 * (i + 1), 2 * i]
                # left of cell
                edges[3 * i + 1, :] = [2 * i, 2 * i + 1]
                # top of cell
                edges[3 * i + 2, :] = [2 * i + 1, 2 * (i + 1) + 1]
        # far right hand edge
        edges[3 * ncells, :] = [2 * ncells, 2 * ncells + 1]
        self.grd = ugrid.UnstructuredGrid(edges=edges,
                                          points=points,
                                          cells=cells,
                                          max_sides=4)
        if show_grid:
            self.grd.plot_edges()
            plt.show()

        return
Esempio n. 28
0
 def make_sector_grid(self):
     g=unstructured_grid.UnstructuredGrid(max_sides=4)
     g.add_rectilinear([-R,-1], [R,1], nx=2*self.sector_grid_N-1, ny=2)
     sector_angle=2*np.pi / 128
     
     n=g.select_nodes_nearest([0,1]) # will delete this
     n2=g.select_nodes_nearest([0,-1]) # and make triangles with this
     nbrs=g.node_to_nodes(n)
     
     g.delete_node_cascade(n)
     for nbr in nbrs:
         if nbr!=n2:
             g.add_edge(nodes=[nbr,n2])
     
     g.nodes['x'][:,1] = g.nodes['x'][:,1] * g.nodes['x'][:,0]*np.sin(sector_angle/2)
     g.make_cells_from_edges()
     g.renumber()
     g.edge_to_cells(recalc=True)
     g.cells_center(refresh=True)
     
     return g
    def make_1D_grid_equilat_tri(self, L, show_grid=False):
        """
        Setup unstructured grid for channel of equilateral triangles
        Edge length = self.dx
        """
        n = int(L / self.dx)
        ncells = 2 * n
        npoints = 2 * n + 2
        nedges = 4 * n + 1
        points = np.zeros((npoints, 2), np.float64)
        # in future if only 3 edges, node4 will have value -1
        cells = -1 * np.ones((ncells, 3), np.int32)  # cell nodes
        edges = -1 * np.ones((nedges, 2), np.int32)  # edge nodes
        for i in range(n + 1):  # set node x,y etc.
            points[2 * i, 0] = self.dx * i
            points[2 * i, 1] = 0.0
            points[2 * i + 1, 0] = self.dx * i + 0.5 * self.dx
            points[2 * i + 1, 1] = self.dx * np.sqrt(3.) / 2.
            if i < n:
                cells[2 * i, :] = [2 * (i + 1), 2 * i + 1, 2 * i]
                cells[2 * i + 1, :] = [2 * (i + 1) + 1, 2 * i + 1, 2 * (i + 1)]
                # bottom of cell
                edges[4 * i, :] = [2 * (i + 1), 2 * i]
                # left of cell
                edges[4 * i + 1, :] = [2 * i, 2 * i + 1]
                # top of cell
                edges[4 * i + 2, :] = [2 * i + 1, 2 * (i + 1) + 1]
                # diag of cell
                edges[4 * i + 3, :] = [2 * (i + 1), 2 * i + 1]
        # far right hand edge
        edges[4 * n, :] = [npoints - 1, npoints - 2]
        self.grd = ugrid.UnstructuredGrid(edges=edges,
                                          points=points,
                                          cells=cells,
                                          max_sides=3)
        if show_grid:
            self.grd.plot_edges()
            plt.show()

        return
Esempio n. 30
0
def test_undo_00():
    ug=unstructured_grid.UnstructuredGrid()

    n1=ug.add_node(x=[0,0])
    n2=ug.add_node(x=[0,1])
    n3=ug.add_node(x=[0.67,0.5])

    e1=ug.add_edge(nodes=[n1,n2])
    e2=ug.add_edge(nodes=[n1,n3])
    cp=ug.checkpoint()
    e3=ug.add_edge(nodes=[n2,n3])
    c0=ug.add_cell(nodes=[n1,n2,n3])

    assert ug.Ncells()==1
    assert ug.Nedges()==3
    assert ug.Nnodes()==3
    
    ug.revert(cp)

    assert ug.Ncells()==0
    assert ug.Nedges()==2
    assert ug.Nnodes()==3