def main():
    """
    Creates a hydrologically correct MODFLOW grid that inlcudes minimum
    DEM elevations for all stream cells and mean elevations everywhere else
    """
    """
    dem = 'DEM'
    grid = 'grid_tmp'
    streams = 'streams_tmp'
    streams_MODFLOW = 'streams_tmp_MODFLOW'
    DEM_MODFLOW = 'DEM_coarse'
    resolution = 500
    """

    options, flags = gscript.parser()
    dem = options['dem']
    grid = options['grid']
    streams = options['streams']
    #resolution = float(options['resolution'])
    streams_MODFLOW = options['streams_modflow']
    DEM_MODFLOW = options['dem_modflow']

    # Get number of rows and columns
    colNames = np.array(gscript.vector_db_select(grid, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(grid, layer=1)['values'].values())
    cats = colValues[:, colNames == 'cat'].astype(int).squeeze()
    rows = colValues[:, colNames == 'row'].astype(int).squeeze()
    cols = colValues[:, colNames == 'col'].astype(int).squeeze()
    nRows = np.max(rows)
    nCols = np.max(cols)

    gscript.use_temp_region()

    # Set the region to capture only the channel
    g.region(raster=dem)
    v.to_rast(input=streams,
              output=streams_MODFLOW,
              use='val',
              value=1.0,
              type='line',
              overwrite=gscript.overwrite(),
              quiet=True)
    r.mapcalc('tmp' + " = " + streams_MODFLOW + " * " + dem, overwrite=True)
    g.rename(raster=('tmp', streams_MODFLOW), overwrite=True, quiet=True)
    g.region(vector=grid, rows=nRows, cols=nCols, quiet=True)
    r.resamp_stats(input=streams_MODFLOW,
                   output=streams_MODFLOW,
                   method='average',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.resamp_stats(input=dem,
                   output=DEM_MODFLOW,
                   method='average',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.patch(input=streams_MODFLOW + ',' + DEM_MODFLOW,
            output=DEM_MODFLOW,
            overwrite=True,
            quiet=True)
Esempio n. 2
0
def main():
    """
    Creates a hydrologically correct MODFLOW grid that inlcudes minimum
    DEM elevations for all stream cells and mean elevations everywhere else
    """
    """
    dem = 'DEM'
    grid = 'grid_tmp'
    streams = 'streams_tmp'
    streams_MODFLOW = 'streams_tmp_MODFLOW'
    DEM_MODFLOW = 'DEM_coarse'
    resolution = 500
    """

    options, flags = gscript.parser()
    dem = options['dem']
    grid = options['grid']
    streams = options['streams']
    #resolution = float(options['resolution'])
    streams_MODFLOW = options['streams_modflow']
    DEM_MODFLOW = options['dem_modflow']

    gscript.use_temp_region()

    # Set the region to capture only the channel
    g.region(raster=dem)
    v.to_rast(input=streams,
              output=streams_MODFLOW,
              use='val',
              value=1.0,
              type='line',
              overwrite=gscript.overwrite(),
              quiet=True)
    r.mapcalc('tmp' + " = " + streams_MODFLOW + " * " + dem, overwrite=True)
    g.rename(raster=('tmp', streams_MODFLOW), overwrite=True, quiet=True)
    g.region(raster=DEM_MODFLOW, quiet=True)
    print "ALTERED"
    r.resamp_stats(input=streams_MODFLOW,
                   output=streams_MODFLOW,
                   method='average',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.resamp_stats(input=dem,
                   output=DEM_MODFLOW,
                   method='average',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.patch(input=streams_MODFLOW + ',' + DEM_MODFLOW,
            output=DEM_MODFLOW,
            overwrite=True,
            quiet=True)
Esempio n. 3
0
def main():
    """
    Creates a hydrologically correct MODFLOW grid that inlcudes minimum
    DEM elevations for all stream cells and mean elevations everywhere else
    """
    """
    dem = 'DEM'
    grid = 'grid_tmp'
    streams = 'streams_tmp'
    streams_MODFLOW = 'streams_tmp_MODFLOW'
    DEM_MODFLOW = 'DEM_coarse'
    resolution = 500
    """

    options, flags = gscript.parser()
    dem = options['dem']
    grid = options['grid']
    streams = options['streams']
    resolution = float(options['resolution'])
    streams_MODFLOW = options['streams_modflow']
    DEM_MODFLOW = options['dem_modflow']

    gscript.use_temp_region()

    g.region(raster=dem)
    g.region(vector=grid)
    v.to_rast(input=streams,
              output=streams_MODFLOW,
              use='val',
              value=1.0,
              type='line',
              overwrite=gscript.overwrite(),
              quiet=True)
    r.mapcalc(streams_MODFLOW + " = " + streams_MODFLOW + " * DEM",
              overwrite=True)
    g.region(res=resolution, quiet=True)
    r.resamp_stats(input=streams_MODFLOW,
                   output=streams_MODFLOW,
                   method='minimum',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.resamp_stats(input=dem,
                   output=DEM_MODFLOW,
                   method='average',
                   overwrite=gscript.overwrite(),
                   quiet=True)
    r.patch(input=streams_MODFLOW + ',' + DEM_MODFLOW,
            output=DEM_MODFLOW,
            overwrite=True,
            quiet=True)
Esempio n. 4
0
def main():
    soilloss = options['soilloss']
    soilloss3 = soilloss # + '.3'
    map = options['map']
    parcelnumcol = options['parcelnumcol']
    flag_l = flags['l']
    flag_h = flags['h']
  
    quiet = True
    if gscript.verbosity() > 2:
        quiet=False

    zones = map.split('@')[0] + '.zones'
    v.to_rast( input=map, use='attr', attrcolumn=parcelnumcol,
              output=zones, quiet=quiet)
    
    
    def printStats(table, tablefmt='simple'):
        try:
            from tabulate import tabulate
        except:
            gscript.warning('Install tabulate for pretty printing tabular output ($ pip install tabulate). Using pprint instead...')
            from pprint import pprint
            pprint(statout)
        print tabulate(table,headers='firstrow',tablefmt=tablefmt)
         
    if not flag_h:
        runivar = r.univar(map=soilloss, zones=zones, flags='t', stdout=gscript.PIPE)
        rstats = runivar.outputs.stdout.strip().split('\n')
        #show all available values columns
        #rstats[0].split('|')
        rstatout = []
        for line in range(len(rstats)):
            lineout = []
            for i in (0,7,9,4,5): 
                lineout += (rstats[line].split('|')[i],)
            rstatout.append(lineout)
            
        if flag_l: printStats(rstatout, tablefmt='latex')
        else: printStats(rstatout)
        
    if flag_h:
            
        r.report(map=(zones,soilloss3),units='p',flags='')
Esempio n. 5
0
def main():
    soillossbare = options['soillossbare']
    soillossgrow = options['soillossgrow']
    cfactor = options['cfactor']
    pfactor = options['pfactor']    
    map = options['map']
    factorcols = options['factorcols'].split(',')
    
    quiet = True
    if gscript.verbosity() > 2:
        quiet=False

    if not (cfactor or pfactor):
        if not map:
            gscript.fatal('Please give either factor raster map(s) or vector map with factor(s)')
        elif not factorcols:
            gscript.fatal("Please give 'factorcols' (attribute columns with factor(s))  for <%s>" %map)
        
        factors = ()
        for factorcol in factorcols:
            output = map.split('@')[0] + '.' + factorcol
            gscript.message('Rasterize <%s> with attribute <%s>' %(map, factorcol) 
                + '\n to raster map <%s> ...' %(output) )
            v.to_rast(input=map, use='attr', attrcolumn=factorcol, 
                      output=output, quiet=quiet)
            factors += (output,)
    
    else: factors = (cfactor, pfactor)
    
    gscript.message('Multiply factors <%s> with <%s> ...' %(factors, soillossbare) )
    formula = soillossgrow + '=' + soillossbare 
    for factor in factors:
        formula += '*' + factor
    r.mapcalc(formula)
    
    ## apply color rules
    r.colors(map = soillossgrow,
                    rules = '-', stdin = colorrules['soillossgrow'],
                    quiet = quiet)
Esempio n. 6
0
def main():
    """
    Builds a grid for the MODFLOW component of the USGS hydrologic model,
    GSFLOW.
    """

    options, flags = gscript.parser()
    basin = options['basin']
    pp = options['pour_point']
    raster_input = options['raster_input']
    dx = options['dx']
    dy = options['dy']
    grid = options['output']
    mask = options['mask_output']
    bc_cell = options['bc_cell']
    # basin='basins_tmp_onebasin'; pp='pp_tmp'; raster_input='DEM'; raster_output='DEM_coarse'; dx=dy='500'; grid='grid_tmp'; mask='mask_tmp'
    """
    # Fatal if raster input and output are not both set
    _lena0 = (len(raster_input) == 0)
    _lenb0 = (len(raster_output) == 0)
    if _lena0 + _lenb0 == 1:
        gscript.fatal("You must set both raster input and output, or neither.")
    """

    # Fatal if bc_cell set but mask and grid are false
    if bc_cell != '':
        if (mask == '') or (pp == ''):
            gscript.fatal(
                'Mask and pour point must be set to define b.c. cell')

    # Create grid -- overlaps DEM, three cells of padding
    gscript.use_temp_region()
    reg = gscript.region()
    reg_grid_edges_sn = np.linspace(reg['s'], reg['n'], reg['rows'])
    reg_grid_edges_we = np.linspace(reg['w'], reg['e'], reg['cols'])
    g.region(vector=basin, ewres=dx, nsres=dy)
    regnew = gscript.region()
    # Use a grid ratio -- don't match exactly the desired MODFLOW resolution
    grid_ratio_ns = np.round(regnew['nsres'] / reg['nsres'])
    grid_ratio_ew = np.round(regnew['ewres'] / reg['ewres'])
    # Get S, W, and then move the unit number of grid cells over to get N and E
    # and include 3 cells of padding around the whole watershed
    _s_dist = np.abs(reg_grid_edges_sn - (regnew['s'] - 3. * regnew['nsres']))
    _s_idx = np.where(_s_dist == np.min(_s_dist))[0][0]
    _s = float(reg_grid_edges_sn[_s_idx])
    _n_grid = np.arange(_s, reg['n'] + 3 * grid_ratio_ns * reg['nsres'],
                        grid_ratio_ns * reg['nsres'])
    _n_dist = np.abs(_n_grid - (regnew['n'] + 3. * regnew['nsres']))
    _n_idx = np.where(_n_dist == np.min(_n_dist))[0][0]
    _n = float(_n_grid[_n_idx])
    _w_dist = np.abs(reg_grid_edges_we - (regnew['w'] - 3. * regnew['ewres']))
    _w_idx = np.where(_w_dist == np.min(_w_dist))[0][0]
    _w = float(reg_grid_edges_we[_w_idx])
    _e_grid = np.arange(_w, reg['e'] + 3 * grid_ratio_ew * reg['ewres'],
                        grid_ratio_ew * reg['ewres'])
    _e_dist = np.abs(_e_grid - (regnew['e'] + 3. * regnew['ewres']))
    _e_idx = np.where(_e_dist == np.min(_e_dist))[0][0]
    _e = float(_e_grid[_e_idx])
    # Finally make the region
    g.region(w=str(_w),
             e=str(_e),
             s=str(_s),
             n=str(_n),
             nsres=str(grid_ratio_ns * reg['nsres']),
             ewres=str(grid_ratio_ew * reg['ewres']))
    # And then make the grid
    v.mkgrid(map=grid, overwrite=gscript.overwrite())

    # Cell numbers (row, column, continuous ID)
    v.db_addcolumn(map=grid, columns='id int', quiet=True)
    colNames = np.array(gscript.vector_db_select(grid, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(grid, layer=1)['values'].values())
    cats = colValues[:, colNames == 'cat'].astype(int).squeeze()
    rows = colValues[:, colNames == 'row'].astype(int).squeeze()
    cols = colValues[:, colNames == 'col'].astype(int).squeeze()
    nrows = np.max(rows)
    ncols = np.max(cols)
    cats = np.ravel([cats])
    _id = np.ravel([ncols * (rows - 1) + cols])
    _id_cat = []
    for i in range(len(_id)):
        _id_cat.append((_id[i], cats[i]))
    gridTopo = VectorTopo(grid)
    gridTopo.open('rw')
    cur = gridTopo.table.conn.cursor()
    cur.executemany("update " + grid + " set id=? where cat=?", _id_cat)
    gridTopo.table.conn.commit()
    gridTopo.close()

    # Cell area
    v.db_addcolumn(map=grid, columns='area_m2', quiet=True)
    v.to_db(map=grid,
            option='area',
            units='meters',
            columns='area_m2',
            quiet=True)

    # Basin mask
    if len(mask) > 0:
        # Fine resolution region:
        g.region(n=reg['n'],
                 s=reg['s'],
                 w=reg['w'],
                 e=reg['e'],
                 nsres=reg['nsres'],
                 ewres=reg['ewres'])
        # Rasterize basin
        v.to_rast(input=basin,
                  output=mask,
                  use='val',
                  value=1,
                  overwrite=gscript.overwrite(),
                  quiet=True)
        # Coarse resolution region:
        g.region(w=str(_w),
                 e=str(_e),
                 s=str(_s),
                 n=str(_n),
                 nsres=str(grid_ratio_ns * reg['nsres']),
                 ewres=str(grid_ratio_ew * reg['ewres']))
        r.resamp_stats(input=mask,
                       output=mask,
                       method='sum',
                       overwrite=True,
                       quiet=True)
        r.mapcalc('tmp' + ' = ' + mask + ' > 0', overwrite=True, quiet=True)
        g.rename(raster=('tmp', mask), overwrite=True, quiet=True)
        r.null(map=mask, null=0, quiet=True)
        # Add mask location (1 vs 0) in the MODFLOW grid
        v.db_addcolumn(map=grid,
                       columns='basinmask double precision',
                       quiet=True)
        v.what_rast(map=grid, type='centroid', raster=mask, column='basinmask')
    """
    # Resampled raster
    if len(raster_output) > 0:
        r.resamp_stats(input=raster_input, output=raster_output, method='average', overwrite=gscript.overwrite(), quiet=True)
    """

    # Pour point
    if len(pp) > 0:
        v.db_addcolumn(map=pp,
                       columns=('row integer', 'col integer'),
                       quiet=True)
        v.build(map=pp, quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column='row',
                    query_column='row',
                    quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column='col',
                    query_column='col',
                    quiet=True)

    # Next point downstream of the pour point
    # Requires pp (always) and mask (sometimes)
    # Dependency set above w/ gscript.fatal
    if len(bc_cell) > 0:
        ########## NEED TO USE TRUE TEMPORARY FILE ##########
        # May not work with dx != dy!
        v.to_rast(input=pp, output='tmp', use='val', value=1, overwrite=True)
        r.buffer(input='tmp',
                 output='tmp',
                 distances=float(dx) * 1.5,
                 overwrite=True)
        r.mapcalc('tmp2 = if(tmp==2,1,null()) * ' + raster_input,
                  overwrite=True)
        g.rename(raster=('tmp2', 'tmp'), overwrite=True, quiet=True)
        #r.mapcalc('tmp = if(isnull('+raster_input+',0,(tmp == 2)))', overwrite=True)
        #g.region(rast='tmp')
        #r.null(map=raster_input,
        r.drain(input=raster_input,
                start_points=pp,
                output='tmp2',
                overwrite=True)
        r.mapcalc('tmp3 = tmp2 * tmp', overwrite=True, quiet=True)
        g.rename(raster=('tmp3', 'tmp'), overwrite=True, quiet=True)
        #r.null(map='tmp', setnull=0) # Not necessary: center point removed above
        r.to_vect(input='tmp',
                  output=bc_cell,
                  type='point',
                  column='z',
                  overwrite=gscript.overwrite(),
                  quiet=True)
        v.db_addcolumn(map=bc_cell,
                       columns=('row integer', 'col integer',
                                'x double precision', 'y double precision'),
                       quiet=True)
        v.build(map=bc_cell, quiet=True)
        v.what_vect(map=bc_cell, query_map=grid, column='row', \
                    query_column='row', quiet=True)
        v.what_vect(map=bc_cell, query_map=grid, column='col', \
                    query_column='col', quiet=True)
        v.to_db(map=bc_cell, option='coor', columns=('x,y'))

        # Find out if this is diagonal: finite difference works only N-S, W-E
        colNames = np.array(gscript.vector_db_select(pp, layer=1)['columns'])
        colValues = np.array(
            gscript.vector_db_select(pp, layer=1)['values'].values())
        pp_row = int(colValues[:, colNames == 'row'].astype(int).squeeze())
        pp_col = int(colValues[:, colNames == 'col'].astype(int).squeeze())
        colNames = np.array(
            gscript.vector_db_select(bc_cell, layer=1)['columns'])
        colValues = np.array(
            gscript.vector_db_select(bc_cell, layer=1)['values'].values())
        bc_row = int(colValues[:, colNames == 'row'].astype(int).squeeze())
        bc_col = int(colValues[:, colNames == 'col'].astype(int).squeeze())
        # Also get x and y while we are at it: may be needed later
        bc_x = float(colValues[:, colNames == 'x'].astype(float).squeeze())
        bc_y = float(colValues[:, colNames == 'y'].astype(float).squeeze())
        if (bc_row != pp_row) and (bc_col != pp_col):
            # If not diagonal, two possible locations that are adjacent
            # to the pour point
            _col1, _row1 = str(bc_col), str(pp_row)
            _col2, _row2 = str(pp_col), str(bc_row)
            # Check if either of these is covered by the basin mask
            _ismask_1 = gscript.vector_db_select(grid,
                                                 layer=1,
                                                 where='(row == ' + _row1 +
                                                 ') AND (col ==' + _col1 + ')',
                                                 columns='basinmask')
            _ismask_1 = int(_ismask_1['values'].values()[0][0])
            _ismask_2 = gscript.vector_db_select(grid,
                                                 layer=1,
                                                 where='(row == ' + _row2 +
                                                 ') AND (col ==' + _col2 + ')',
                                                 columns='basinmask')
            _ismask_2 = int(_ismask_2['values'].values()[0][0])
            # If both covered by mask, error
            if _ismask_1 and _ismask_2:
                gscript.fatal(
                    'All possible b.c. cells covered by basin mask.\n\
                             Contact the developer: awickert (at) umn(.)edu')
            # Otherwise, those that keep those that are not covered by basin
            # mask and set ...
            # ... wait, do we want the point that touches as few interior
            # cells as possible?
            # maybe just try setting both and seeing what happens for now!
            else:
                # Get dx and dy
                dx = gscript.region()['ewres']
                dy = gscript.region()['nsres']
                # Build tool to handle multiple b.c. cells?
                bcvect = vector.Vector(bc_cell)
                bcvect.open('rw')
                _cat_i = 2
                if not _ismask_1:
                    # _x should always be bc_x, but writing generalized code
                    _x = bc_x + dx * (int(_col1) - bc_col)  # col 1 at w edge
                    _y = bc_y - dy * (int(_row1) - bc_row)  # row 1 at n edge
                    point0 = Point(_x, _y)
                    bcvect.write(
                        point0,
                        cat=_cat_i,
                        attrs=(None, _row1, _col1, _x, _y),
                    )
                    bcvect.table.conn.commit()
                    _cat_i += 1
                if not _ismask_2:
                    # _y should always be bc_y, but writing generalized code
                    _x = bc_x + dx * (int(_col2) - bc_col)  # col 1 at w edge
                    _y = bc_y - dy * (int(_row2) - bc_row)  # row 1 at n edge
                    point0 = Point(_x, _y)
                    bcvect.write(
                        point0,
                        cat=_cat_i,
                        attrs=(None, _row2, _col2, _x, _y),
                    )
                    bcvect.table.conn.commit()
                # Build database table and vector geometry
                bcvect.build()
                bcvect.close()

    g.region(n=reg['n'],
             s=reg['s'],
             w=reg['w'],
             e=reg['e'],
             nsres=reg['nsres'],
             ewres=reg['ewres'])
Esempio n. 7
0
def euclidean_distance_fields(prefix, region, overwrite=False):
    """
    Generate euclidean distance fields from map corner and centre coordinates

    Parameters
    ----------
    prefix : str
        Name to use as prefix to save distance maps

    region : grass.pygrass.gis.region.Region
        Region

    overwrite : bool
        Whether to overwrite existing maps
    """

    point_topleft = Point(region.west + region.ewres / 2,
                          region.north - region.nsres / 2)
    point_topright = Point(region.east - region.ewres / 2,
                           region.north - region.nsres / 2)
    point_lowerleft = Point(region.west + region.ewres / 2,
                            region.south + region.nsres / 2)
    point_lowerright = Point(region.east - region.ewres / 2,
                             region.south + region.nsres / 2)
    point_centre = Point(
        region.west + (region.east - region.west) / 2,
        region.south + (region.north - region.south) / 2,
    )

    points = {
        "topleft": point_topleft,
        "topright": point_topright,
        "lowerleft": point_lowerleft,
        "lowerright": point_lowerright,
        "centre": point_centre,
    }

    for name, p in points.items():

        point_name = "_".join([prefix, name])

        vect = VectorTopo(name=point_name)
        vect.open(
            mode="w",
            tab_name=point_name,
            tab_cols=[("cat", "INTEGER PRIMARY KEY"), ("name", "TEXT")],
        )
        vect.write(p, ("point", ))
        vect.table.conn.commit()
        vect.close()

        gvect.to_rast(
            input=point_name,
            type="point",
            use="val",
            output=point_name,
            overwrite=overwrite,
        )
        grast.grow_distance(point_name,
                            distance="distance_to_" + point_name,
                            overwrite=overwrite)

        g.remove(name=point_name, type="raster", flags="f")
        g.remove(name=point_name, type="raster", flags="f")
Esempio n. 8
0
def rasterizeCs(reso):
    g.region(res=reso)
    v.to_rast(csmap, output = 'cr', use='attr',attribute_column=fcol, overwrite = True)
Esempio n. 9
0
def main():
    """
    Import any raster or vector data set and add its attribute
    to a GSFLOW data object
    """

    ##################
    # OPTION PARSING #
    ##################

    options, flags = gscript.parser()

    # Parsing
    if options["attrtype"] == "int":
        attrtype = "integer"
    elif options["attrtype"] == "float":
        attrtype = "double precision"
    elif options["attrtype"] == "string":
        attrtype = "varchar"
    else:
        attrtype = ""

    ########################################
    # PROCESS AND UPLOAD TO DATABASE TABLE #
    ########################################

    if options["vector_area"] is not "":
        gscript.use_temp_region()
        g.region(vector=options["map"], res=options["dxy"])
        v.to_rast(
            input=options["vector_area"],
            output="tmp___tmp",
            use="attr",
            attribute_column=options["from_column"],
            quiet=True,
            overwrite=True,
        )
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options["map"],
                            columns=options["column"],
                            quiet=True)
        except:
            pass
        if attrtype is "double precision":
            try:
                gscript.message("Checking for existing column to overwrite")
                v.db_dropcolumn(map=options["map"],
                                columns="tmp_average",
                                quiet=True)
            except:
                pass
            v.rast_stats(
                map=options["map"],
                raster="tmp___tmp",
                column_prefix="tmp",
                method="average",
                flags="c",
                quiet=True,
            )
            g.remove(type="raster", name="tmp___tmp", flags="f", quiet=True)
            v.db_renamecolumn(
                map=options["map"],
                column=["tmp_average", options["column"]],
                quiet=True,
            )

        else:
            try:
                v.db_addcolumn(
                    map=options["map"],
                    columns=options["column"] + " " + attrtype,
                    quiet=True,
                )
            except:
                pass
            gscript.run_command(
                "v.distance",
                from_=options["map"],
                to=options["vector_area"],
                upload="to_attr",
                to_column=options["from_column"],
                column=options["column"],
                quiet=True,
            )
    elif options["vector_points"] is not "":
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options["map"],
                            columns=options["column"],
                            quiet=True)
            v.db_addcolumn(
                map=options["map"],
                columns=options["column"] + " " + attrtype,
                quiet=True,
            )
        except:
            pass
        gscript.run_command(
            "v.distance",
            from_=options["map"],
            to=options["vector_points"],
            upload="to_attr",
            to_column=options["from_column"],
            column=options["column"],
            quiet=True,
        )

    elif options["raster"] is not "":
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options["map"],
                            columns=options["column"],
                            quiet=True)
        except:
            pass
        v.rast_stats(
            map=options["map"],
            raster=options["raster"],
            column_prefix="tmp",
            method="average",
            flags="c",
            quiet=True,
        )
        v.db_renamecolumn(map=options["map"],
                          column=["tmp_average", options["column"]],
                          quiet=True)

    gscript.message("Done.")
Esempio n. 10
0
def main():
    """
    Builds a grid for the MODFLOW component of the USGS hydrologic model,
    GSFLOW.
    """

    options, flags = gscript.parser()
    basin = options["basin"]
    pp = options["pour_point"]
    raster_input = options["raster_input"]
    dx = options["dx"]
    dy = options["dy"]
    grid = options["output"]
    mask = options["mask_output"]
    bc_cell = options["bc_cell"]
    # basin='basins_tmp_onebasin'; pp='pp_tmp'; raster_input='DEM'; raster_output='DEM_coarse'; dx=dy='500'; grid='grid_tmp'; mask='mask_tmp'
    """
    # Fatal if raster input and output are not both set
    _lena0 = (len(raster_input) == 0)
    _lenb0 = (len(raster_output) == 0)
    if _lena0 + _lenb0 == 1:
        gscript.fatal("You must set both raster input and output, or neither.")
    """

    # Fatal if bc_cell set but mask and grid are false
    if bc_cell != "":
        if (mask == "") or (pp == ""):
            gscript.fatal(
                "Mask and pour point must be set to define b.c. cell")

    # Create grid -- overlaps DEM, three cells of padding
    g.region(raster=raster_input, ewres=dx, nsres=dy)
    gscript.use_temp_region()
    reg = gscript.region()
    reg_grid_edges_sn = np.linspace(reg["s"], reg["n"], reg["rows"])
    reg_grid_edges_we = np.linspace(reg["w"], reg["e"], reg["cols"])
    g.region(vector=basin, ewres=dx, nsres=dy)
    regnew = gscript.region()
    # Use a grid ratio -- don't match exactly the desired MODFLOW resolution
    grid_ratio_ns = np.round(regnew["nsres"] / reg["nsres"])
    grid_ratio_ew = np.round(regnew["ewres"] / reg["ewres"])
    # Get S, W, and then move the unit number of grid cells over to get N and E
    # and include 3 cells of padding around the whole watershed
    _s_dist = np.abs(reg_grid_edges_sn - (regnew["s"] - 3.0 * regnew["nsres"]))
    _s_idx = np.where(_s_dist == np.min(_s_dist))[0][0]
    _s = float(reg_grid_edges_sn[_s_idx])
    _n_grid = np.arange(_s, reg["n"] + 3 * grid_ratio_ns * reg["nsres"],
                        grid_ratio_ns * reg["nsres"])
    _n_dist = np.abs(_n_grid - (regnew["n"] + 3.0 * regnew["nsres"]))
    _n_idx = np.where(_n_dist == np.min(_n_dist))[0][0]
    _n = float(_n_grid[_n_idx])
    _w_dist = np.abs(reg_grid_edges_we - (regnew["w"] - 3.0 * regnew["ewres"]))
    _w_idx = np.where(_w_dist == np.min(_w_dist))[0][0]
    _w = float(reg_grid_edges_we[_w_idx])
    _e_grid = np.arange(_w, reg["e"] + 3 * grid_ratio_ew * reg["ewres"],
                        grid_ratio_ew * reg["ewres"])
    _e_dist = np.abs(_e_grid - (regnew["e"] + 3.0 * regnew["ewres"]))
    _e_idx = np.where(_e_dist == np.min(_e_dist))[0][0]
    _e = float(_e_grid[_e_idx])
    # Finally make the region
    g.region(
        w=str(_w),
        e=str(_e),
        s=str(_s),
        n=str(_n),
        nsres=str(grid_ratio_ns * reg["nsres"]),
        ewres=str(grid_ratio_ew * reg["ewres"]),
    )
    # And then make the grid
    v.mkgrid(map=grid, overwrite=gscript.overwrite())

    # Cell numbers (row, column, continuous ID)
    v.db_addcolumn(map=grid, columns="id int", quiet=True)
    colNames = np.array(gscript.vector_db_select(grid, layer=1)["columns"])
    colValues = np.array(
        gscript.vector_db_select(grid, layer=1)["values"].values())
    cats = colValues[:, colNames == "cat"].astype(int).squeeze()
    rows = colValues[:, colNames == "row"].astype(int).squeeze()
    cols = colValues[:, colNames == "col"].astype(int).squeeze()
    nrows = np.max(rows)
    ncols = np.max(cols)
    cats = np.ravel([cats])
    _id = np.ravel([ncols * (rows - 1) + cols])
    _id_cat = []
    for i in range(len(_id)):
        _id_cat.append((_id[i], cats[i]))
    gridTopo = VectorTopo(grid)
    gridTopo.open("rw")
    cur = gridTopo.table.conn.cursor()
    cur.executemany("update " + grid + " set id=? where cat=?", _id_cat)
    gridTopo.table.conn.commit()
    gridTopo.close()

    # Cell area
    v.db_addcolumn(map=grid, columns="area_m2 double precision", quiet=True)
    v.to_db(map=grid,
            option="area",
            units="meters",
            columns="area_m2",
            quiet=True)

    # Basin mask
    if len(mask) > 0:
        # Fine resolution region:
        g.region(
            n=reg["n"],
            s=reg["s"],
            w=reg["w"],
            e=reg["e"],
            nsres=reg["nsres"],
            ewres=reg["ewres"],
        )
        # Rasterize basin
        v.to_rast(
            input=basin,
            output=mask,
            use="val",
            value=1,
            overwrite=gscript.overwrite(),
            quiet=True,
        )
        # Coarse resolution region:
        g.region(
            w=str(_w),
            e=str(_e),
            s=str(_s),
            n=str(_n),
            nsres=str(grid_ratio_ns * reg["nsres"]),
            ewres=str(grid_ratio_ew * reg["ewres"]),
        )
        r.resamp_stats(input=mask,
                       output=mask,
                       method="sum",
                       overwrite=True,
                       quiet=True)
        r.mapcalc("tmp" + " = " + mask + " > 0", overwrite=True, quiet=True)
        g.rename(raster=("tmp", mask), overwrite=True, quiet=True)
        r.null(map=mask, null=0, quiet=True)
        # Add mask location (1 vs 0) in the MODFLOW grid
        v.db_addcolumn(map=grid,
                       columns="basinmask double precision",
                       quiet=True)
        v.what_rast(map=grid, type="centroid", raster=mask, column="basinmask")
    """
    # Resampled raster
    if len(raster_output) > 0:
        r.resamp_stats(input=raster_input, output=raster_output, method='average', overwrite=gscript.overwrite(), quiet=True)
    """

    # Pour point
    if len(pp) > 0:
        v.db_addcolumn(map=pp,
                       columns=("row integer", "col integer"),
                       quiet=True)
        v.build(map=pp, quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column="row",
                    query_column="row",
                    quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column="col",
                    query_column="col",
                    quiet=True)

    # Next point downstream of the pour point
    # Requires pp (always) and mask (sometimes)
    # Dependency set above w/ gscript.fatal
    # g.region(raster='DEM')
    # dx = gscript.region()['ewres']
    # dy = gscript.region()['nsres']
    if len(bc_cell) > 0:
        ########## NEED TO USE TRUE TEMPORARY FILE ##########
        # May not work with dx != dy!
        v.to_rast(input=pp, output="tmp", use="val", value=1, overwrite=True)
        r.buffer(input="tmp",
                 output="tmp",
                 distances=float(dx) * 1.5,
                 overwrite=True)
        r.mapcalc("tmp2 = if(tmp==2,1,null()) * " + raster_input,
                  overwrite=True)
        # r.mapcalc('tmp = if(isnull('+raster_input+',0,(tmp == 2)))', overwrite=True)
        # g.region(rast='tmp')
        # r.null(map=raster_input,
        # g.region(raster=raster_input)
        # r.resample(input=raster_input, output='tmp3', overwrite=True)
        r.resamp_stats(input=raster_input,
                       output="tmp3",
                       method="minimum",
                       overwrite=True)
        r.drain(input="tmp3", start_points=pp, output="tmp", overwrite=True)
        # g.region(w=str(_w), e=str(_e), s=str(_s), n=str(_n), nsres=str(grid_ratio_ns*reg['nsres']), ewres=str(grid_ratio_ew*reg['ewres']))
        # r.resamp_stats(input='tmp2', output='tmp3', overwrite=True)
        # g.rename(raster=('tmp3','tmp2'), overwrite=True, quiet=True)
        r.mapcalc("tmp3 = tmp2 * tmp", overwrite=True, quiet=True)
        g.rename(raster=("tmp3", "tmp"), overwrite=True, quiet=True)
        # r.null(map='tmp', setnull=0) # Not necessary: center point removed above
        r.to_vect(
            input="tmp",
            output=bc_cell,
            type="point",
            column="z",
            overwrite=gscript.overwrite(),
            quiet=True,
        )
        v.db_addcolumn(
            map=bc_cell,
            columns=(
                "row integer",
                "col integer",
                "x double precision",
                "y double precision",
            ),
            quiet=True,
        )
        v.build(map=bc_cell, quiet=True)
        v.what_vect(map=bc_cell,
                    query_map=grid,
                    column="row",
                    query_column="row",
                    quiet=True)
        v.what_vect(map=bc_cell,
                    query_map=grid,
                    column="col",
                    query_column="col",
                    quiet=True)
        v.to_db(map=bc_cell, option="coor", columns=("x,y"))

        # Of the candidates, the pour point is the closest one
        # v.db_addcolumn(map=bc_cell, columns=('dist_to_pp double precision'), quiet=True)
        # v.distance(from_=bc_cell, to=pp, upload='dist', column='dist_to_pp')

        # Find out if this is diagonal: finite difference works only N-S, W-E
        colNames = np.array(gscript.vector_db_select(pp, layer=1)["columns"])
        colValues = np.array(
            gscript.vector_db_select(pp, layer=1)["values"].values())
        pp_row = colValues[:, colNames == "row"].astype(int).squeeze()
        pp_col = colValues[:, colNames == "col"].astype(int).squeeze()
        colNames = np.array(
            gscript.vector_db_select(bc_cell, layer=1)["columns"])
        colValues = np.array(
            gscript.vector_db_select(bc_cell, layer=1)["values"].values())
        bc_row = colValues[:, colNames == "row"].astype(int).squeeze()
        bc_col = colValues[:, colNames == "col"].astype(int).squeeze()
        # Also get x and y while we are at it: may be needed later
        bc_x = colValues[:, colNames == "x"].astype(float).squeeze()
        bc_y = colValues[:, colNames == "y"].astype(float).squeeze()
        if (bc_row != pp_row).all() and (bc_col != pp_col).all():
            if bc_row.ndim > 0:
                if len(bc_row) > 1:
                    for i in range(len(bc_row)):
                        """
                        UNTESTED!!!!
                        And probably unimportant -- having 2 cells with river
                        going through them is most likely going to happen with
                        two adjacent cells -- so a side and a corner
                        """
                        _col1, _row1 = str(bc_col[i]), str(pp_row[i])
                        _col2, _row2 = str(pp_col[i]), str(bc_row[i])
                        # Check if either of these is covered by the basin mask
                        _ismask_1 = gscript.vector_db_select(
                            grid,
                            layer=1,
                            where="(row == " + _row1 + ") AND (col ==" +
                            _col1 + ")",
                            columns="basinmask",
                        )
                        _ismask_1 = int(_ismask_1["values"].values()[0][0])
                        _ismask_2 = gscript.vector_db_select(
                            grid,
                            layer=1,
                            where="(row == " + _row2 + ") AND (col ==" +
                            _col2 + ")",
                            columns="basinmask",
                        )
                        _ismask_2 = int(_ismask_2["values"].values()[0][0])
                        # check if either of these is the other point
                        """
                        NOT DOING THIS YET -- HAVEN'T THOUGHT THROUGH IF
                        ACTUALLY NECESSARY. (And this is an edge case anyway)
                        """
                        # If both covered by mask, error
                        if _ismask_1 and _ismask_2:
                            gscript.fatal(
                                "All possible b.c. cells covered by basin mask.\n\
                                         Contact the developer: awickert (at) umn(.)edu"
                            )

            # If not diagonal, two possible locations that are adjacent
            # to the pour point
            _col1, _row1 = str(bc_col), str(pp_row)
            _col2, _row2 = str(pp_col), str(bc_row)
            # Check if either of these is covered by the basin mask
            _ismask_1 = gscript.vector_db_select(
                grid,
                layer=1,
                where="(row == " + _row1 + ") AND (col ==" + _col1 + ")",
                columns="basinmask",
            )
            _ismask_1 = int(_ismask_1["values"].values()[0][0])
            _ismask_2 = gscript.vector_db_select(
                grid,
                layer=1,
                where="(row == " + _row2 + ") AND (col ==" + _col2 + ")",
                columns="basinmask",
            )
            _ismask_2 = int(_ismask_2["values"].values()[0][0])
            # If both covered by mask, error
            if _ismask_1 and _ismask_2:
                gscript.fatal(
                    "All possible b.c. cells covered by basin mask.\n\
                             Contact the developer: awickert (at) umn(.)edu")
            # Otherwise, those that keep those that are not covered by basin
            # mask and set ...
            # ... wait, do we want the point that touches as few interior
            # cells as possible?
            # maybe just try setting both and seeing what happens for now!
            else:
                # Get dx and dy
                # dx = gscript.region()['ewres']
                # dy = gscript.region()['nsres']
                # Build tool to handle multiple b.c. cells?
                bcvect = vector.Vector(bc_cell)
                bcvect.open("rw")
                _cat_i = 2
                if _ismask_1 != 0:
                    # _x should always be bc_x, but writing generalized code
                    _x = bc_x + float(dx) * (int(_col1) - bc_col
                                             )  # col 1 at w edge
                    _y = bc_y - float(dy) * (int(_row1) - bc_row
                                             )  # row 1 at n edge
                    point0 = Point(_x, _y)
                    bcvect.write(
                        point0,
                        cat=_cat_i,
                        attrs=(None, _row1, _col1, _x, _y),
                    )
                    bcvect.table.conn.commit()
                    _cat_i += 1
                if _ismask_2 != 0:
                    # _y should always be bc_y, but writing generalized code
                    _x = bc_x + float(dx) * (int(_col2) - bc_col
                                             )  # col 1 at w edge
                    _y = bc_y - float(dy) * (int(_row2) - bc_row
                                             )  # row 1 at n edge
                    point0 = Point(_x, _y)
                    bcvect.write(
                        point0,
                        cat=_cat_i,
                        attrs=(None, _row2, _col2, _x, _y),
                    )
                    bcvect.table.conn.commit()
                # Build database table and vector geometry
                bcvect.build()
                bcvect.close()

    g.region(
        n=reg["n"],
        s=reg["s"],
        w=reg["w"],
        e=reg["e"],
        nsres=reg["nsres"],
        ewres=reg["ewres"],
    )
Esempio n. 11
0
def main():
    """
    Import any raster or vector data set and add its attribute
    to a GSFLOW data object
    """

    ##################
    # OPTION PARSING #
    ##################

    options, flags = gscript.parser()

    # Parsing
    if options['attrtype'] == 'int':
        attrtype = 'integer'
    elif options['attrtype'] == 'float':
        attrtype = 'double precision'
    elif options['attrtype'] == 'string':
        attrtype = 'varchar'
    else:
        attrtype = ''

    ########################################
    # PROCESS AND UPLOAD TO DATABASE TABLE #
    ########################################

    if options['vector_area'] is not '':
        gscript.use_temp_region()
        g.region(vector=options['map'], res=options['dxy'])
        v.to_rast(input=options['vector_area'],
                  output='tmp___tmp',
                  use='attr',
                  attribute_column=options['from_column'],
                  quiet=True,
                  overwrite=True)
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options['map'],
                            columns=options['column'],
                            quiet=True)
        except:
            pass
        if attrtype is 'double precision':
            try:
                gscript.message("Checking for existing column to overwrite")
                v.db_dropcolumn(map=options['map'],
                                columns='tmp_average',
                                quiet=True)
            except:
                pass
            v.rast_stats(map=options['map'],
                         raster='tmp___tmp',
                         column_prefix='tmp',
                         method='average',
                         flags='c',
                         quiet=True)
            g.remove(type='raster', name='tmp___tmp', flags='f', quiet=True)
            v.db_renamecolumn(map=options['map'],
                              column=['tmp_average', options['column']],
                              quiet=True)

        else:
            try:
                v.db_addcolumn(map=options['map'],
                               columns=options['column'] + ' ' + attrtype,
                               quiet=True)
            except:
                pass
            gscript.run_command('v.distance',
                                from_=options['map'],
                                to=options['vector_area'],
                                upload='to_attr',
                                to_column=options['from_column'],
                                column=options['column'],
                                quiet=True)
    elif options['vector_points'] is not '':
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options['map'],
                            columns=options['column'],
                            quiet=True)
            v.db_addcolumn(map=options['map'],
                           columns=options['column'] + ' ' + attrtype,
                           quiet=True)
        except:
            pass
        gscript.run_command('v.distance',
                            from_=options['map'],
                            to=options['vector_points'],
                            upload='to_attr',
                            to_column=options['from_column'],
                            column=options['column'],
                            quiet=True)

    elif options['raster'] is not '':
        try:
            gscript.message("Checking for existing column to overwrite")
            v.db_dropcolumn(map=options['map'],
                            columns=options['column'],
                            quiet=True)
        except:
            pass
        v.rast_stats(map=options['map'],
                     raster=options['raster'],
                     column_prefix='tmp',
                     method='average',
                     flags='c',
                     quiet=True)
        v.db_renamecolumn(map=options['map'],
                          column=['tmp_average', options['column']],
                          quiet=True)

    gscript.message("Done.")
Esempio n. 12
0
def main():
    """
    Builds a grid for the MODFLOW component of the USGS hydrologic model,
    GSFLOW.
    """

    options, flags = gscript.parser()
    basin = options['basin']
    pp = options['pour_point']
    raster_input = options['raster_input']
    dx = options['dx']
    dy = options['dy']
    grid = options['output']
    mask = options['mask_output']
    bc_cell = options['bc_cell']
    # basin='basins_tmp_onebasin'; pp='pp_tmp'; raster_input='DEM'; raster_output='DEM_coarse'; dx=dy='500'; grid='grid_tmp'; mask='mask_tmp'
    """
    # Fatal if raster input and output are not both set
    _lena0 = (len(raster_input) == 0)
    _lenb0 = (len(raster_output) == 0)
    if _lena0 + _lenb0 == 1:
        grass.fatal("You must set both raster input and output, or neither.")
    """

    # Create grid -- overlaps DEM, one cell of padding
    gscript.use_temp_region()
    reg = gscript.region()
    reg_grid_edges_sn = np.linspace(reg['s'], reg['n'], reg['rows'])
    reg_grid_edges_we = np.linspace(reg['w'], reg['e'], reg['cols'])
    g.region(vector=basin, ewres=dx, nsres=dy)
    regnew = gscript.region()
    # Use a grid ratio -- don't match exactly the desired MODFLOW resolution
    grid_ratio_ns = np.round(regnew['nsres'] / reg['nsres'])
    grid_ratio_ew = np.round(regnew['ewres'] / reg['ewres'])
    # Get S, W, and then move the unit number of grid cells over to get N and E
    # and include 3 cells of padding around the whole watershed
    _s_dist = np.abs(reg_grid_edges_sn - (regnew['s'] - 3. * regnew['nsres']))
    _s_idx = np.where(_s_dist == np.min(_s_dist))[0][0]
    _s = float(reg_grid_edges_sn[_s_idx])
    _n_grid = np.arange(_s, reg['n'] + 3 * grid_ratio_ns * reg['nsres'],
                        grid_ratio_ns * reg['nsres'])
    _n_dist = np.abs(_n_grid - (regnew['n'] + 3. * regnew['nsres']))
    _n_idx = np.where(_n_dist == np.min(_n_dist))[0][0]
    _n = float(_n_grid[_n_idx])
    _w_dist = np.abs(reg_grid_edges_we - (regnew['w'] - 3. * regnew['ewres']))
    _w_idx = np.where(_w_dist == np.min(_w_dist))[0][0]
    _w = float(reg_grid_edges_we[_w_idx])
    _e_grid = np.arange(_w, reg['e'] + 3 * grid_ratio_ew * reg['ewres'],
                        grid_ratio_ew * reg['ewres'])
    _e_dist = np.abs(_e_grid - (regnew['e'] + 3. * regnew['ewres']))
    _e_idx = np.where(_e_dist == np.min(_e_dist))[0][0]
    _e = float(_e_grid[_e_idx])
    # Finally make the region
    g.region(w=str(_w),
             e=str(_e),
             s=str(_s),
             n=str(_n),
             nsres=str(grid_ratio_ns * reg['nsres']),
             ewres=str(grid_ratio_ew * reg['ewres']))
    # And then make the grid
    v.mkgrid(map=grid, overwrite=gscript.overwrite())

    # Cell numbers (row, column, continuous ID)
    v.db_addcolumn(map=grid, columns='id int', quiet=True)
    colNames = np.array(gscript.vector_db_select(grid, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(grid, layer=1)['values'].values())
    cats = colValues[:, colNames == 'cat'].astype(int).squeeze()
    rows = colValues[:, colNames == 'row'].astype(int).squeeze()
    cols = colValues[:, colNames == 'col'].astype(int).squeeze()
    nrows = np.max(rows)
    ncols = np.max(cols)
    cats = np.ravel([cats])
    _id = np.ravel([ncols * (rows - 1) + cols])
    _id_cat = []
    for i in range(len(_id)):
        _id_cat.append((_id[i], cats[i]))
    gridTopo = VectorTopo(grid)
    gridTopo.open('rw')
    cur = gridTopo.table.conn.cursor()
    cur.executemany("update " + grid + " set id=? where cat=?", _id_cat)
    gridTopo.table.conn.commit()
    gridTopo.close()

    # Cell area
    v.db_addcolumn(map=grid, columns='area_m2', quiet=True)
    v.to_db(map=grid,
            option='area',
            units='meters',
            columns='area_m2',
            quiet=True)

    # Basin mask
    if len(mask) > 0:
        # Fine resolution region:
        g.region(n=reg['n'],
                 s=reg['s'],
                 w=reg['w'],
                 e=reg['e'],
                 nsres=reg['nsres'],
                 ewres=reg['ewres'])
        # Rasterize basin
        v.to_rast(input=basin,
                  output=mask,
                  use='val',
                  value=1,
                  overwrite=gscript.overwrite(),
                  quiet=True)
        # Coarse resolution region:
        g.region(w=str(_w),
                 e=str(_e),
                 s=str(_s),
                 n=str(_n),
                 nsres=str(grid_ratio_ns * reg['nsres']),
                 ewres=str(grid_ratio_ew * reg['ewres']))
        r.resamp_stats(input=mask,
                       output=mask,
                       method='sum',
                       overwrite=True,
                       quiet=True)
        r.mapcalc(mask + ' = ' + mask + ' > 0', overwrite=True, quiet=True)
    """
    # Resampled raster
    if len(raster_output) > 0:
        r.resamp_stats(input=raster_input, output=raster_output, method='average', overwrite=gscript.overwrite(), quiet=True)
    """

    # Pour point
    if len(pp) > 0:
        v.db_addcolumn(map=pp,
                       columns=('row integer', 'col integer'),
                       quiet=True)
        v.build(map=pp, quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column='row',
                    query_column='row',
                    quiet=True)
        v.what_vect(map=pp,
                    query_map=grid,
                    column='col',
                    query_column='col',
                    quiet=True)

    # Next point downstream of the pour point
    if len(bc_cell) > 0:
        ########## NEED TO USE TRUE TEMPORARY FILE ##########
        # May not work with dx != dy!
        v.to_rast(input=pp, output='tmp', use='val', value=1, overwrite=True)
        r.buffer(input='tmp',
                 output='tmp',
                 distances=float(dx) * 1.5,
                 overwrite=True)
        r.mapcalc('tmp = (tmp == 2) * ' + raster_input, overwrite=True)
        r.drain(input=raster_input,
                start_points=pp,
                output='tmp2',
                overwrite=True)
        r.mapcalc('tmp = tmp2 * tmp', overwrite=True)
        r.null(map='tmp', setnull=0)
        r.to_vect(input='tmp',
                  output=bc_cell,
                  type='point',
                  column='z',
                  overwrite=gscript.overwrite(),
                  quiet=True)
        v.db_addcolumn(map=bc_cell,
                       columns=('row integer', 'col integer'),
                       quiet=True)
        v.build(map=bc_cell, quiet=True)
        v.what_vect(map=bc_cell, query_map=grid, column='row', \
                    query_column='row', quiet=True)
        v.what_vect(map=bc_cell, query_map=grid, column='col', \
                    query_column='col', quiet=True)

    g.region(n=reg['n'],
             s=reg['s'],
             w=reg['w'],
             e=reg['e'],
             nsres=reg['nsres'],
             ewres=reg['ewres'])
Esempio n. 13
0
def main():
    soillossin = options['soillossin']
    soillossout = options['soillossout']
    factorold = options['factorold']
    
    factornew = options['factornew']
    map = options['map']
    factorcol = options['factorcol']
    
    flag_p = flags['p'] # patch factornew with factorold
    flag_k = flags['k'] # calculate k-factor components from % clay p_T, silt p_U, stones p_st, humus p_H 

     
    if not factornew:
        factors = {}
        if flag_k:
            gscript.message('Using factor derived from \
                soil components.')
            parcelmap = Vect(map)
            parcelmap.open(mode='rw', layer=1)
            parcelmap.table.filters.select()
            cur = parcelmap.table.execute()
            col_names = [cn[0] for cn in cur.description]
            rows = cur.fetchall()
           
            for col in (u'Kb',u'Ks',u'Kh', u'K'):
                if col not in parcelmap.table.columns:
                    parcelmap.table.columns.add(col,u'DOUBLE')
           
            for row in rows:
                rowid = row[1]
                p_T = row[7]
                p_U = row[8]
                p_st = row[9]
                p_H = row[10]
    
                print("Parzelle mit id %d :" %rowid)
                for sublist in bodenarten:
                    # p_T and p_U
                    if p_T in range(sublist[2],sublist[3]) \
                        and p_U in range(sublist[4],sublist[5]) :
                        print('Bodenart "' + sublist[1] 
                            + '", Kb = ' + str(sublist[6]))
                        Kb = sublist[6]
                        break
                
                for sublist in skelettgehalte:
                    if p_st < sublist[0]:
                        print('Skelettgehaltsklasse bis ' + str(sublist[0]) 
                            + ' , Ks = ' + str(sublist[1]))
                        Ks = sublist[1]
                        break
            
                   
                for sublist in humusgehalte:
                    if p_H < sublist[0]:
                        print('Humusgehaltsklasse bis ' + str(sublist[0]) 
                            + ' , Ks = ' + str(sublist[1]))
                        Kh = sublist[1]
                        break
                
                
                K = Kb * Ks * Kh
                print('K = ' + str(K))
        
                if K > 0:
                    parcelmap.table.execute("UPDATE " +  parcelmap.name 
                        + " SET"
                        + " Kb=" + str(Kb)
                        + ", Ks=" + str(Ks)
                        + ", Kh=" + str(Kh)
                        + ", K=" + str(K)
                        + " WHERE id=" + str(rowid) )
                    parcelmap.table.conn.commit()
                
            parcelmap.close()
            factorcol2 = 'K'
            
            factors['k'] = map.split('@')[0]+'.tmp.'+factorcol2
            v.to_rast(input=map, use='attr',
                   attrcolumn=factorcol2,
                   output=factors['k'])
            r.null(map=factors['k'], setnull='0')

        
        if factorcol:
            gscript.message('Using factor from column %s of \
                    vector map <%s>.' % (factorcol, map) )
                    
            factors['factorcol'] = map.split('@')[0]+'.tmp.' + factorcol
            v.to_rast(input=map, use='attr',
                   attrcolumn=factorcol,
                   output=factors['factorcol'])
            r.null(map=factors['factorcol'], setnull='0')
        
        print factors.keys()
        if not 'k' in factors and not 'factorcol' in factors: 
            gscript.fatal('Please provide either factor \
                raster map or valid vector map with factor column \
                (kfactor) or factor components columns (Kb, Ks, Kh)' )
        
        #if 'k' in factors and 'factorcol' in factors: 
    
        factornew = map.split('@')[0]+'.kfactor'
        if 'k' in factors and 'factorcol' in  factors:
            factornew = map.split('@')[0]+'.kfactor'
            r.patch(input=(factors['factorcol'],factors['k']),
                    output=factornew)
            
        elif 'k' in factors:
            g.copy(rast=(factors['k'],factornew))
            
        elif 'factorcol' in factors:
            g.copy(rast=(factors['factorcol'],factornew))

            
    if flag_p:
        #factorcorr = factorold + '.update'
        r.patch(input=(factornew,factorold), output=factornew)
        
    formula = soillossout + '=' + soillossin \
                + '/' + factorold  \
                + '*' + factornew
    r.mapcalc(formula)
            
    r.colors(map=soillossout, raster=soillossin)
Esempio n. 14
0
    def smeasure():
        gscript.message('Import <%s>' % measuremap.name)
        measuremap.autoimport('measures', overwrite=True, quiet=quiet,
                              where="betrieb_id = %s" % betriebid)
        
        soillossbaremap = maps['soillossbare']
        kfactormap = maps['kfactor']

        if soillossbarecorrmap.exist():
            gscript.message('Using updated soillossbare map.')
            soillossbaremap = soillossbarecorrmap
            kfactormap = Rast(parcelmap.name + '.kfactor')
        
        if flag_b:
            measurebarriermap = Vect(measuremap.name + '_barrier')
            v.extract(input=measuremap.name, where="barrier = 1",
                      output=measurebarriermap.name)
            
            measurefieldblockmap = Vect(measuremap.name + '_fieldblocks')
            v.overlay(ainput=maps['fieldblocks'].name,
                      binput=measurebarriermap.name,\
                      operator='not', 
                      output=measurefieldblockmap.name)
            
            rsoillossbare.inputs.elevation = maps['elevation'].name
            rsoillossbare.inputs.rfactor = maps['rfactor'].name
            rsoillossbare.inputs.kfactor = kfactormap.name
            rsoillossbare.inputs.map = measurefieldblockmap.name
            rsoillossbare.inputs.constant_m = '0.6'
            rsoillossbare.inputs.constant_n = '1.4'


            rsoillossbare.flags.r = True
            rsoillossbare(soillossbare=soillossbarebarriermap.name)
            soillossbaremap = soillossbarebarriermap

        parcelpfactor = parcelmap.name + '.pfactor'
        parcelcfactor = parcelmap.name + '.cfactor'
        v.to_rast(input=parcelmap.name, use='attr', attrcolumn='pfactor',
                  output=parcelpfactor)
        v.to_rast(input=parcelmap.name, use='attr', attrcolumn='cfactor',
                  output=parcelcfactor)
                  
        measurepfactor = measuremap.name + '.pfactor'
        measurecfactor = measuremap.name + '.cfactor'
        v.to_rast(input=measuremap.name, use='attr', attrcolumn='pfactor',
                  output=measurepfactor)
        v.to_rast(input=measuremap.name, use='attr', attrcolumn='cfactor',
                  output=measurecfactor)

        pfactor = parcelmap.name + '.pfactor.measure'
        cfactor = parcelmap.name + '.cfactor.measure'

        r.patch(input=(measurepfactor,parcelpfactor), output=pfactor)
        r.patch(input=(measurecfactor,parcelcfactor), output=cfactor)
        rsoillossgrow.inputs.soillossbare = soillossbaremap.name
        rsoillossgrow.inputs.cfactor = pfactor
        rsoillossgrow.inputs.pfactor = cfactor
        rsoillossgrow(soillossgrow=soillossmeasuremap.name)
        
        rsoillossreclass(soillossmeasuremap.name, 'soillossgrow',flags='')
        gscript.message('Reclassified and colored maps found in <%s.3> and <%s.9> .'%(soillossmeasuremap.name, soillossmeasuremap.name))

        if flag_s:
            gscript.message('\n \n Statistics for soilloss on grown soil <%s> : '%(soillossgrowmap))
            rsoillossstats(soilloss=soillossmeasuremap.name, map=parcelmap.name, parcelnumcol='id')
        
        if not flag_c:
            g.copy(rast=(soillossmeasuremap.name,output))
            gscript.message('Copy made to <%s> for automatic output' %(output))