Exemple #1
0
def lcp_rast(knights):
    if(knights):
        r.cost(crmap, output=cumul16, outdir=dir16, start_points=startmap, stop_points=targetmap, overwrite = True,flags = 'k')
        v.what_rast(targetmap,raster=cumul16, column=trg_c16)             
        r.drain( cumul16,direction=dir16, output=pr16, drain=pv16, start_points=targetmap, flags = 'dc', overwrite = True)
        v.overlay(ainput=pv16, binput=csmap, operator='and', output=pvc16,overwrite=True) 
        v.overlay(ainput=pv16, binput=csmap, operator='not', output=nogo16,overwrite=True)
    else:
        r.cost(crmap, output=cumul8, outdir=dir8, start_points=startmap, stop_points=targetmap, overwrite = True)
        v.what_rast(targetmap,raster=cumul8, column=trg_c8)
        r.drain( cumul8,direction=dir8, output=pr8, drain=pv8, start_points=targetmap, flags = 'dc', overwrite = True)
        v.overlay(ainput=pv8, binput=csmap, operator='and', output=pvc8,overwrite=True)
        v.overlay(ainput=pv8, binput=csmap, operator='and', output=nogo8,overwrite=True)
def main():
    """
    Builds river reaches for input to the USGS hydrologic model, GSFLOW.
    These reaches link the PRMS stream segments to the MODFLOW grid cells.
    """

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

    options, flags = gscript.parser()
    segments = options['segment_input']
    grid = options['grid_input']
    reaches = options['output']
    elevation = options['elevation']
    Smin = options['s_min']
    h_stream = options['h_stream']
    x1 = options['upstream_easting_column_seg']
    y1 = options['upstream_northing_column_seg']
    x2 = options['downstream_easting_column_seg']
    y2 = options['downstream_northing_column_seg']
    tostream = options['tostream_cat_column_seg']
    # Hydraulic paramters
    STRTHICK = options['strthick']
    STRHC1 = options['strhc1']
    THTS = options['thts']
    THTI = options['thti']
    EPS = options['eps']
    UHC = options['uhc']
    # Build reach maps by overlaying segments on grid
    if len(gscript.find_file(segments, element='vector')['name']) > 0:
        v.extract(input=segments,
                  output='GSFLOW_TEMP__',
                  type='line',
                  quiet=True,
                  overwrite=True)
        v.overlay(ainput='GSFLOW_TEMP__',
                  atype='line',
                  binput=grid,
                  output=reaches,
                  operator='and',
                  overwrite=gscript.overwrite(),
                  quiet=True)
        g.remove(type='vector', name='GSFLOW_TEMP__', quiet=True, flags='f')
    else:
        gscript.fatal('No vector file "' + segments + '" found.')

    # Start editing database table
    reachesTopo = VectorTopo(reaches)
    reachesTopo.open('rw')

    # Rename a,b columns
    reachesTopo.table.columns.rename('a_' + x1, 'x1')
    reachesTopo.table.columns.rename('a_' + x2, 'x2')
    reachesTopo.table.columns.rename('a_' + y1, 'y1')
    reachesTopo.table.columns.rename('a_' + y2, 'y2')
    reachesTopo.table.columns.rename('a_NSEG', 'NSEG')
    reachesTopo.table.columns.rename('a_ISEG', 'ISEG')
    reachesTopo.table.columns.rename('a_stream_type', 'stream_type')
    reachesTopo.table.columns.rename('a_type_code', 'type_code')
    reachesTopo.table.columns.rename('a_cat', 'rnum_cat')
    reachesTopo.table.columns.rename('a_' + tostream, 'tostream')
    reachesTopo.table.columns.rename('a_id', 'segment_id')
    reachesTopo.table.columns.rename('a_OUTSEG', 'OUTSEG')
    reachesTopo.table.columns.rename('b_row', 'row')
    reachesTopo.table.columns.rename('b_col', 'col')
    reachesTopo.table.columns.rename('b_id', 'cell_id')

    # Drop unnecessary columns
    cols = reachesTopo.table.columns.names()
    for col in cols:
        if (col[:2] == 'a_') or (col[:2] == 'b_'):
            reachesTopo.table.columns.drop(col)

    # Add new columns to 'reaches'
    reachesTopo.table.columns.add('KRCH', 'integer')
    reachesTopo.table.columns.add('IRCH', 'integer')
    reachesTopo.table.columns.add('JRCH', 'integer')
    reachesTopo.table.columns.add('IREACH', 'integer')
    reachesTopo.table.columns.add('RCHLEN', 'double precision')
    reachesTopo.table.columns.add('STRTOP', 'double precision')
    reachesTopo.table.columns.add('SLOPE', 'double precision')
    reachesTopo.table.columns.add('STRTHICK', 'double precision')
    reachesTopo.table.columns.add('STRHC1', 'double precision')
    reachesTopo.table.columns.add('THTS', 'double precision')
    reachesTopo.table.columns.add('THTI', 'double precision')
    reachesTopo.table.columns.add('EPS', 'double precision')
    reachesTopo.table.columns.add('UHC', 'double precision')
    reachesTopo.table.columns.add('xr1', 'double precision')
    reachesTopo.table.columns.add('xr2', 'double precision')
    reachesTopo.table.columns.add('yr1', 'double precision')
    reachesTopo.table.columns.add('yr2', 'double precision')

    # Commit columns before editing (necessary?)
    reachesTopo.table.conn.commit()
    reachesTopo.close()

    # Update some columns that can be done now
    reachesTopo.open('rw')
    colNames = np.array(gscript.vector_db_select(reaches, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(reaches, layer=1)['values'].values())
    cats = colValues[:, colNames == 'cat'].astype(int).squeeze()
    nseg = np.arange(1, len(cats) + 1)
    nseg_cats = []
    for i in range(len(cats)):
        nseg_cats.append((nseg[i], cats[i]))
    cur = reachesTopo.table.conn.cursor()
    # Hydrogeologic properties
    cur.execute("update " + reaches + " set STRTHICK=" + str(STRTHICK))
    cur.execute("update " + reaches + " set STRHC1=" + str(STRHC1))
    cur.execute("update " + reaches + " set THTS=" + str(THTS))
    cur.execute("update " + reaches + " set THTI=" + str(THTI))
    cur.execute("update " + reaches + " set EPS=" + str(EPS))
    cur.execute("update " + reaches + " set UHC=" + str(UHC))
    # Grid properties
    cur.execute("update " + reaches + " set KRCH=1")  # Top layer: unchangable
    cur.executemany("update " + reaches + " set IRCH=? where row=?", nseg_cats)
    cur.executemany("update " + reaches + " set JRCH=? where col=?", nseg_cats)
    reachesTopo.table.conn.commit()
    reachesTopo.close()
    v.to_db(map=reaches, columns='RCHLEN', option='length', quiet=True)

    # Still to go after these:
    # STRTOP (added with slope)
    # IREACH (whole next section dedicated to this)
    # SLOPE (need z_start and z_end)

    # Now, the light stuff is over: time to build the reach order
    v.to_db(map=reaches, option='start', columns='xr1,yr1')
    v.to_db(map=reaches, option='end', columns='xr2,yr2')

    # Now just sort by category, find which stream has the same xr1 and yr1 as
    # x1 and y1 (or a_x1, a_y1) and then find where its endpoint matches another
    # starting point and move down the line.
    # v.db.select reaches col=cat,a_id,xr1,xr2 where="a_x1 = xr1"

    # First, get the starting coordinates of each stream segment
    # and a set of river ID's (ordered from 1...N)
    colNames = np.array(gscript.vector_db_select(segments, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(segments, layer=1)['values'].values())
    number_of_segments = colValues.shape[0]
    segment_x1s = colValues[:, colNames == 'x1'].astype(float).squeeze()
    segment_y1s = colValues[:, colNames == 'y1'].astype(float).squeeze()
    segment_ids = colValues[:, colNames == 'id'].astype(float).squeeze()

    # Then move back to the reaches map to produce the ordering
    colNames = np.array(gscript.vector_db_select(reaches, layer=1)['columns'])
    colValues = np.array(
        gscript.vector_db_select(reaches, layer=1)['values'].values())
    reach_cats = colValues[:, colNames == 'cat'].astype(int).squeeze()
    reach_x1s = colValues[:, colNames == 'xr1'].astype(float).squeeze()
    reach_y1s = colValues[:, colNames == 'yr1'].astype(float).squeeze()
    reach_x2s = colValues[:, colNames == 'xr2'].astype(float).squeeze()
    reach_y2s = colValues[:, colNames == 'yr2'].astype(float).squeeze()
    segment_ids__reach = colValues[:, colNames == 'segment_id'].astype(
        float).squeeze()

    for segment_id in segment_ids:
        reach_order_cats = []
        downstream_directed = []
        ssel = segment_ids == segment_id
        rsel = segment_ids__reach == segment_id  # selector
        # Find first segment: x1y1 first here, but not necessarily later
        downstream_directed.append(1)
        _x_match = reach_x1s[rsel] == segment_x1s[ssel]
        _y_match = reach_y1s[rsel] == segment_y1s[ssel]
        _i_match = _x_match * _y_match
        x1y1 = True  # false if x2y2
        # Find cat
        _cat = int(reach_cats[rsel][_x_match * _y_match])
        reach_order_cats.append(_cat)
        # Get end of reach = start of next one
        reach_x_end = float(reach_x2s[reach_cats == _cat])
        reach_y_end = float(reach_y2s[reach_cats == _cat])
        while _i_match.any():
            _x_match = reach_x1s[rsel] == reach_x_end
            _y_match = reach_y1s[rsel] == reach_y_end
            _i_match = _x_match * _y_match
            if _i_match.any():
                _cat = int(reach_cats[rsel][_x_match * _y_match])
                reach_x_end = float(reach_x2s[reach_cats == _cat])
                reach_y_end = float(reach_y2s[reach_cats == _cat])
                reach_order_cats.append(_cat)
        _message = str(len(reach_order_cats)) + ' ' + \
                   str(len(reach_cats[rsel]))
        gscript.message(_message)

        # Reach order to database table
        reach_number__reach_order_cats = []
        for i in range(len(reach_order_cats)):
            reach_number__reach_order_cats.append((i + 1, reach_order_cats[i]))
        reachesTopo = VectorTopo(reaches)
        reachesTopo.open('rw')
        cur = reachesTopo.table.conn.cursor()
        cur.executemany("update " + reaches + " set IREACH=? where cat=?",
                        reach_number__reach_order_cats)
        reachesTopo.table.conn.commit()
        reachesTopo.close()

    # TOP AND BOTTOM ARE OUT OF ORDER: SOME SEGS ARE BACKWARDS. UGH!!!!
    # NEED TO GET THEM IN ORDER TO GET THE Z VALUES AT START AND END

    # 2018.10.01: Updating this to use the computational region for the DEM
    g.region(raster=elevation)

    # Compute slope and starting elevations from the elevations at the start and
    # end of the reaches and the length of each reach]

    gscript.message('Obtaining elevation values from raster: may take time.')
    v.db_addcolumn(map=reaches,
                   columns='zr1 double precision, zr2 double precision')
    zr1 = []
    zr2 = []
    for i in range(len(reach_cats)):
        _x = reach_x1s[i]
        _y = reach_y1s[i]
        #print _x, _y
        _z = float(
            gscript.parse_command('r.what',
                                  map=elevation,
                                  coordinates=str(_x) + ',' +
                                  str(_y)).keys()[0].split('|')[-1])
        zr1.append(_z)
        _x = reach_x2s[i]
        _y = reach_y2s[i]
        _z = float(
            gscript.parse_command('r.what',
                                  map=elevation,
                                  coordinates=str(_x) + ',' +
                                  str(_y)).keys()[0].split('|')[-1])
        zr2.append(_z)

    zr1_cats = []
    zr2_cats = []
    for i in range(len(reach_cats)):
        zr1_cats.append((zr1[i], reach_cats[i]))
        zr2_cats.append((zr2[i], reach_cats[i]))

    reachesTopo = VectorTopo(reaches)
    reachesTopo.open('rw')
    cur = reachesTopo.table.conn.cursor()
    cur.executemany("update " + reaches + " set zr1=? where cat=?", zr1_cats)
    cur.executemany("update " + reaches + " set zr2=? where cat=?", zr2_cats)
    reachesTopo.table.conn.commit()
    reachesTopo.close()

    # Use these to create slope -- backwards possible on DEM!
    v.db_update(map=reaches, column='SLOPE', value='(zr1 - zr2)/RCHLEN')
    v.db_update(map=reaches,
                column='SLOPE',
                value=Smin,
                where='SLOPE <= ' + str(Smin))

    # srtm_local_filled_grid = srtm_local_filled @ 200m (i.e. current grid)
    #  resolution
    # r.to.vect in=srtm_local_filled_grid out=srtm_local_filled_grid col=z type=area --o#
    # NOT SURE IF IT IS BEST TO USE MEAN ELEVATION OR TOP ELEVATION!!!!!!!!!!!!!!!!!!!!!!!
    v.db_addcolumn(map=reaches, columns='z_topo_mean double precision')
    v.what_rast(map=reaches, raster=elevation,
                column='z_topo_mean')  # , query_column='z')
    v.db_update(map=reaches,
                column='STRTOP',
                value='z_topo_mean -' + str(h_stream),
                quiet=True)
Exemple #3
0
def main():
    """
    Builds river reaches for input to the USGS hydrologic model, GSFLOW.
    These reaches link the PRMS stream segments to the MODFLOW grid cells.
    """

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

    options, flags = gscript.parser()
    segments = options["segment_input"]
    grid = options["grid_input"]
    reaches = options["output"]
    elevation = options["elevation"]
    Smin = options["s_min"]
    h_stream = options["h_stream"]
    x1 = options["upstream_easting_column_seg"]
    y1 = options["upstream_northing_column_seg"]
    x2 = options["downstream_easting_column_seg"]
    y2 = options["downstream_northing_column_seg"]
    tostream = options["tostream_cat_column_seg"]
    # Hydraulic paramters
    STRTHICK = options["strthick"]
    STRHC1 = options["strhc1"]
    THTS = options["thts"]
    THTI = options["thti"]
    EPS = options["eps"]
    UHC = options["uhc"]
    # Build reach maps by overlaying segments on grid
    if len(gscript.find_file(segments, element="vector")["name"]) > 0:
        v.extract(
            input=segments,
            output="GSFLOW_TEMP__",
            type="line",
            quiet=True,
            overwrite=True,
        )
        v.overlay(
            ainput="GSFLOW_TEMP__",
            atype="line",
            binput=grid,
            output=reaches,
            operator="and",
            overwrite=gscript.overwrite(),
            quiet=True,
        )
        g.remove(type="vector", name="GSFLOW_TEMP__", quiet=True, flags="f")
    else:
        gscript.fatal('No vector file "' + segments + '" found.')

    # Start editing database table
    reachesTopo = VectorTopo(reaches)
    reachesTopo.open("rw")

    # Rename a,b columns
    reachesTopo.table.columns.rename("a_" + x1, "x1")
    reachesTopo.table.columns.rename("a_" + x2, "x2")
    reachesTopo.table.columns.rename("a_" + y1, "y1")
    reachesTopo.table.columns.rename("a_" + y2, "y2")
    reachesTopo.table.columns.rename("a_NSEG", "NSEG")
    reachesTopo.table.columns.rename("a_ISEG", "ISEG")
    reachesTopo.table.columns.rename("a_stream_type", "stream_type")
    reachesTopo.table.columns.rename("a_type_code", "type_code")
    reachesTopo.table.columns.rename("a_cat", "rnum_cat")
    reachesTopo.table.columns.rename("a_" + tostream, "tostream")
    reachesTopo.table.columns.rename("a_id", "segment_id")
    reachesTopo.table.columns.rename("a_OUTSEG", "OUTSEG")
    reachesTopo.table.columns.rename("b_row", "row")
    reachesTopo.table.columns.rename("b_col", "col")
    reachesTopo.table.columns.rename("b_id", "cell_id")

    # Drop unnecessary columns
    cols = reachesTopo.table.columns.names()
    for col in cols:
        if (col[:2] == "a_") or (col[:2] == "b_"):
            reachesTopo.table.columns.drop(col)

    # Add new columns to 'reaches'
    reachesTopo.table.columns.add("KRCH", "integer")
    reachesTopo.table.columns.add("IRCH", "integer")
    reachesTopo.table.columns.add("JRCH", "integer")
    reachesTopo.table.columns.add("IREACH", "integer")
    reachesTopo.table.columns.add("RCHLEN", "double precision")
    reachesTopo.table.columns.add("STRTOP", "double precision")
    reachesTopo.table.columns.add("SLOPE", "double precision")
    reachesTopo.table.columns.add("STRTHICK", "double precision")
    reachesTopo.table.columns.add("STRHC1", "double precision")
    reachesTopo.table.columns.add("THTS", "double precision")
    reachesTopo.table.columns.add("THTI", "double precision")
    reachesTopo.table.columns.add("EPS", "double precision")
    reachesTopo.table.columns.add("UHC", "double precision")
    reachesTopo.table.columns.add("xr1", "double precision")
    reachesTopo.table.columns.add("xr2", "double precision")
    reachesTopo.table.columns.add("yr1", "double precision")
    reachesTopo.table.columns.add("yr2", "double precision")

    # Commit columns before editing (necessary?)
    reachesTopo.table.conn.commit()
    reachesTopo.close()

    # Update some columns that can be done now
    reachesTopo.open("rw")
    colNames = np.array(gscript.vector_db_select(reaches, layer=1)["columns"])
    colValues = np.array(
        gscript.vector_db_select(reaches, layer=1)["values"].values())
    cats = colValues[:, colNames == "cat"].astype(int).squeeze()
    nseg = np.arange(1, len(cats) + 1)
    nseg_cats = []
    for i in range(len(cats)):
        nseg_cats.append((nseg[i], cats[i]))
    cur = reachesTopo.table.conn.cursor()
    # Hydrogeologic properties
    cur.execute("update " + reaches + " set STRTHICK=" + str(STRTHICK))
    cur.execute("update " + reaches + " set STRHC1=" + str(STRHC1))
    cur.execute("update " + reaches + " set THTS=" + str(THTS))
    cur.execute("update " + reaches + " set THTI=" + str(THTI))
    cur.execute("update " + reaches + " set EPS=" + str(EPS))
    cur.execute("update " + reaches + " set UHC=" + str(UHC))
    # Grid properties
    cur.execute("update " + reaches + " set KRCH=1")  # Top layer: unchangable
    cur.executemany("update " + reaches + " set IRCH=? where row=?", nseg_cats)
    cur.executemany("update " + reaches + " set JRCH=? where col=?", nseg_cats)
    reachesTopo.table.conn.commit()
    reachesTopo.close()
    v.to_db(map=reaches, columns="RCHLEN", option="length", quiet=True)

    # Still to go after these:
    # STRTOP (added with slope)
    # IREACH (whole next section dedicated to this)
    # SLOPE (need z_start and z_end)

    # Now, the light stuff is over: time to build the reach order
    v.to_db(map=reaches, option="start", columns="xr1,yr1")
    v.to_db(map=reaches, option="end", columns="xr2,yr2")

    # Now just sort by category, find which stream has the same xr1 and yr1 as
    # x1 and y1 (or a_x1, a_y1) and then find where its endpoint matches another
    # starting point and move down the line.
    # v.db.select reaches col=cat,a_id,xr1,xr2 where="a_x1 = xr1"

    # First, get the starting coordinates of each stream segment
    # and a set of river ID's (ordered from 1...N)
    colNames = np.array(gscript.vector_db_select(segments, layer=1)["columns"])
    colValues = np.array(
        gscript.vector_db_select(segments, layer=1)["values"].values())
    number_of_segments = colValues.shape[0]
    segment_x1s = colValues[:, colNames == "x1"].astype(float).squeeze()
    segment_y1s = colValues[:, colNames == "y1"].astype(float).squeeze()
    segment_ids = colValues[:, colNames == "id"].astype(float).squeeze()

    # Then move back to the reaches map to produce the ordering
    colNames = np.array(gscript.vector_db_select(reaches, layer=1)["columns"])
    colValues = np.array(
        gscript.vector_db_select(reaches, layer=1)["values"].values())
    reach_cats = colValues[:, colNames == "cat"].astype(int).squeeze()
    reach_x1s = colValues[:, colNames == "xr1"].astype(float).squeeze()
    reach_y1s = colValues[:, colNames == "yr1"].astype(float).squeeze()
    reach_x2s = colValues[:, colNames == "xr2"].astype(float).squeeze()
    reach_y2s = colValues[:, colNames == "yr2"].astype(float).squeeze()
    segment_ids__reach = colValues[:, colNames == "segment_id"].astype(
        float).squeeze()

    for segment_id in segment_ids:
        reach_order_cats = []
        downstream_directed = []
        ssel = segment_ids == segment_id
        rsel = segment_ids__reach == segment_id  # selector
        # Find first segment: x1y1 first here, but not necessarily later
        downstream_directed.append(1)
        _x_match = reach_x1s[rsel] == segment_x1s[ssel]
        _y_match = reach_y1s[rsel] == segment_y1s[ssel]
        _i_match = _x_match * _y_match
        x1y1 = True  # false if x2y2
        # Find cat
        _cat = int(reach_cats[rsel][_x_match * _y_match])
        reach_order_cats.append(_cat)
        # Get end of reach = start of next one
        reach_x_end = float(reach_x2s[reach_cats == _cat])
        reach_y_end = float(reach_y2s[reach_cats == _cat])
        while _i_match.any():
            _x_match = reach_x1s[rsel] == reach_x_end
            _y_match = reach_y1s[rsel] == reach_y_end
            _i_match = _x_match * _y_match
            if _i_match.any():
                _cat = int(reach_cats[rsel][_x_match * _y_match])
                reach_x_end = float(reach_x2s[reach_cats == _cat])
                reach_y_end = float(reach_y2s[reach_cats == _cat])
                reach_order_cats.append(_cat)
        _message = str(len(reach_order_cats)) + " " + str(len(
            reach_cats[rsel]))
        gscript.message(_message)

        # Reach order to database table
        reach_number__reach_order_cats = []
        for i in range(len(reach_order_cats)):
            reach_number__reach_order_cats.append((i + 1, reach_order_cats[i]))
        reachesTopo = VectorTopo(reaches)
        reachesTopo.open("rw")
        cur = reachesTopo.table.conn.cursor()
        cur.executemany(
            "update " + reaches + " set IREACH=? where cat=?",
            reach_number__reach_order_cats,
        )
        reachesTopo.table.conn.commit()
        reachesTopo.close()

    # TOP AND BOTTOM ARE OUT OF ORDER: SOME SEGS ARE BACKWARDS. UGH!!!!
    # NEED TO GET THEM IN ORDER TO GET THE Z VALUES AT START AND END

    # 2018.10.01: Updating this to use the computational region for the DEM
    g.region(raster=elevation)

    # Compute slope and starting elevations from the elevations at the start and
    # end of the reaches and the length of each reach]

    gscript.message("Obtaining elevation values from raster: may take time.")
    v.db_addcolumn(map=reaches,
                   columns="zr1 double precision, zr2 double precision")
    zr1 = []
    zr2 = []
    for i in range(len(reach_cats)):
        _x = reach_x1s[i]
        _y = reach_y1s[i]
        # print _x, _y
        _z = float(
            gscript.parse_command("r.what",
                                  map=elevation,
                                  coordinates=str(_x) + "," +
                                  str(_y)).keys()[0].split("|")[-1])
        zr1.append(_z)
        _x = reach_x2s[i]
        _y = reach_y2s[i]
        _z = float(
            gscript.parse_command("r.what",
                                  map=elevation,
                                  coordinates=str(_x) + "," +
                                  str(_y)).keys()[0].split("|")[-1])
        zr2.append(_z)

    zr1_cats = []
    zr2_cats = []
    for i in range(len(reach_cats)):
        zr1_cats.append((zr1[i], reach_cats[i]))
        zr2_cats.append((zr2[i], reach_cats[i]))

    reachesTopo = VectorTopo(reaches)
    reachesTopo.open("rw")
    cur = reachesTopo.table.conn.cursor()
    cur.executemany("update " + reaches + " set zr1=? where cat=?", zr1_cats)
    cur.executemany("update " + reaches + " set zr2=? where cat=?", zr2_cats)
    reachesTopo.table.conn.commit()
    reachesTopo.close()

    # Use these to create slope -- backwards possible on DEM!
    v.db_update(map=reaches, column="SLOPE", value="(zr1 - zr2)/RCHLEN")
    v.db_update(map=reaches,
                column="SLOPE",
                value=Smin,
                where="SLOPE <= " + str(Smin))

    # srtm_local_filled_grid = srtm_local_filled @ 200m (i.e. current grid)
    #  resolution
    # r.to.vect in=srtm_local_filled_grid out=srtm_local_filled_grid col=z type=area --o#
    # NOT SURE IF IT IS BEST TO USE MEAN ELEVATION OR TOP ELEVATION!!!!!!!!!!!!!!!!!!!!!!!
    v.db_addcolumn(map=reaches, columns="z_topo_mean double precision")
    v.what_rast(map=reaches, raster=elevation,
                column="z_topo_mean")  # , query_column='z')
    v.db_update(map=reaches,
                column="STRTOP",
                value="z_topo_mean -" + str(h_stream),
                quiet=True)
Exemple #4
0
def main(opts, flgs):
    TMPVECT = []
    DEBUG = True if flgs["d"] else False
    atexit.register(cleanup, vect=TMPVECT, debug=DEBUG)
    # check input maps
    rhydro = ["kind_label", "discharge", "id_point", "id_plant"]
    rother = ["kind_label", "discharge", "id_point", "id_plant"]
    ovwr = overwrite()

    try:
        hydro = check_required_columns(opts["hydro"], int(opts["hydro_layer"]),
                                       rhydro, "hydro")
        if opts["other"]:
            other = check_required_columns(opts["other"], opts["other_layer"],
                                           rother, "other")
        else:
            other = None
        # minflow = check_float_or_raster(opts['minflow'])
    except ParameterError as exc:
        exception2error(exc)

    # start working
    hydro.open("r")
    el, mset = (opts["elevation"].split("@") if "@" in opts["elevation"] else
                (opts["elevation"], ""))
    elev = RasterRow(name=el, mapset=mset)
    elev.open("r")
    # import ipdb; ipdb.set_trace()
    plants, skipped = read_plants(
        hydro,
        elev=elev,
        restitution=opts["hydro_kind_turbine"],
        intake=opts["hydro_kind_intake"],
    )
    hydro.close()
    rvname, rvmset = (opts["river"].split("@") if "@" in opts["river"] else
                      (opts["river"], ""))

    vplants = opts["output_plants"] if opts["output_plants"] else "tmpplants"
    # FIXME: I try with tmpplants in my mapset and it doesn'work
    if opts["output_plants"] == "":
        TMPVECT.append(vplants)
    with VectorTopo(rvname, rvmset, mode="r") as river:
        write_plants(plants, vplants, river, elev, overwrite=ovwr)

    if skipped:
        for skip in skipped:
            print("Plant: %r, Point: %r, kind: %r" % skip)
    elev.close()

    # compute a buffer around the plants
    buff = vplants + "buff"
    v.buffer(input=vplants,
             type="line",
             output=buff,
             distance=0.1,
             overwrite=ovwr)
    TMPVECT.append(buff)
    # return all the river segments that are not already with plants
    v.overlay(
        flags="t",
        ainput=opts["river"],
        atype="line",
        binput=buff,
        operator="not",
        output=opts["output_streams"],
        overwrite=ovwr,
    )
Exemple #5
0
def main():
    """
    Build gravity reservoirs in GSFLOW: combines MODFLOW grid and HRU sub-basins
    These define the PRMS soil zone that connects to MODFLOW cells
    """

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

    # I/O
    options, flags = gscript.parser()

    # I/O
    HRUs = options["hru_input"]
    grid = options["grid_input"]
    segments = options["output"]
    # col = options['col']
    gravity_reservoirs = options["output"]

    ############
    # ANALYSIS #
    ############
    """
    # Basin areas
    v.db_addcolumn(map=basins, columns=col)
    v.to_db(map=basins, option='area', units='meters', columns=col)
    """

    # Create gravity reservoirs -- overlay cells=grid and HRUs
    v.overlay(
        ainput=HRUs,
        binput=grid,
        atype="area",
        btype="area",
        operator="and",
        output=gravity_reservoirs,
        overwrite=gscript.overwrite(),
    )
    v.db_dropcolumn(map=gravity_reservoirs,
                    columns="a_cat,a_label,b_cat",
                    quiet=True)
    # Cell and HRU ID's
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=("a_id", "gvr_hru_id"),
                      quiet=True)
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=("b_id", "gvr_cell_id"),
                      quiet=True)
    # Percent areas
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=("a_hru_area_m2", "hru_area_m2"),
                      quiet=True)
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=("b_area_m2", "cell_area_m2"),
                      quiet=True)
    v.db_addcolumn(map=gravity_reservoirs,
                   columns="area_m2 double precision",
                   quiet=True)
    v.to_db(
        map=gravity_reservoirs,
        option="area",
        units="meters",
        columns="area_m2",
        quiet=True,
    )
    v.db_addcolumn(
        map=gravity_reservoirs,
        columns="gvr_cell_pct double precision, gvr_hru_pct double precision",
        quiet=True,
    )
    v.db_update(
        map=gravity_reservoirs,
        column="gvr_cell_pct",
        query_column="100*area_m2/cell_area_m2",
        quiet=True,
    )
    v.db_update(
        map=gravity_reservoirs,
        column="gvr_hru_pct",
        query_column="100*area_m2/hru_area_m2",
        quiet=True,
    )
    v.extract(
        input=gravity_reservoirs,
        output="tmp_",
        where="gvr_cell_pct > 0.001",
        overwrite=True,
        quiet=True,
    )
    g.rename(vector=("tmp_", gravity_reservoirs), overwrite=True, quiet=True)
reach_columns.append('KRCH integer')
reach_columns.append('IRCH integer')
reach_columns.append('JRCH integer')
reach_columns.append('NSEG integer') # = segment_id = ISEG
reach_columns.append('ISEG integer') # = segment_id
reach_columns.append('IREACH integer')
reach_columns.append('RCHLEN integer')
reach_columns.append('STRTOP double precision')
reach_columns.append('SLOPE double precision')
reach_columns.append('STRTHICK double precision')

reach_columns = ",".join(reach_columns)

# Create a map to work with
v.extract(input='streams', output='tmp2', type='line', overwrite=True)
v.overlay(ainput='tmp2', atype='line', binput='grid', output='reaches', operator='and', overwrite=True)

v.db_addcolumn(map='reaches', columns=reach_columns)

# Rename a,b columns
v.db_renamecolumn(map='reaches', column=('a_x1', 'x1'))
v.db_renamecolumn(map='reaches', column=('a_x2', 'x2'))
v.db_renamecolumn(map='reaches', column=('a_y1', 'y1'))
v.db_renamecolumn(map='reaches', column=('a_y2', 'y2'))
v.db_renamecolumn(map='reaches', column=('a_stream_type', 'stream_type'))
v.db_renamecolumn(map='reaches', column=('a_type_code', 'type_code'))
v.db_renamecolumn(map='reaches', column=('a_cat', 'rnum_cat'))
v.db_renamecolumn(map='reaches', column=('a_tostream', 'tostream'))
v.db_renamecolumn(map='reaches', column=('a_id', 'segment_id'))
v.db_renamecolumn(map='reaches', column=('a_OUTSEG', 'OUTSEG'))
v.db_renamecolumn(map='reaches', column=('b_row', 'row'))
def main(opts, flgs):
    TMPVECT = []
    DEBUG = True if flgs['d'] else False
    atexit.register(cleanup, vect=TMPVECT, debug=DEBUG)
    # check input maps
    rhydro = ['kind_label', 'discharge', 'id_point', 'id_plant']
    rother = ['kind_label', 'discharge', 'id_point', 'id_plant']
    ovwr = overwrite()

    try:
        hydro = check_required_columns(opts['hydro'], int(opts['hydro_layer']),
                                       rhydro, 'hydro')
        if opts['other']:
            other = check_required_columns(opts['other'], opts['other_layer'],
                                           rother, 'other')
        else:
            other = None
        #minflow = check_float_or_raster(opts['minflow'])
    except ParameterError as exc:
        exception2error(exc)

    # start working
    hydro.open('r')
    el, mset = (opts['elevation'].split('@') if '@' in opts['elevation'] else
                (opts['elevation'], ''))
    elev = RasterRow(name=el, mapset=mset)
    elev.open('r')
    #import ipdb; ipdb.set_trace()
    plants, skipped = read_plants(hydro,
                                  elev=elev,
                                  restitution=opts['hydro_kind_turbine'],
                                  intake=opts['hydro_kind_intake'])
    hydro.close()
    rvname, rvmset = (opts['river'].split('@') if '@' in opts['river'] else
                      (opts['river'], ''))

    vplants = opts['output_plants'] if opts['output_plants'] else 'tmpplants'
    #FIXME: I try with tmpplants in my mapset and it doesn'work
    if opts['output_plants'] == '':
        TMPVECT.append(vplants)
    with VectorTopo(rvname, rvmset, mode='r') as river:
        write_plants(plants, vplants, river, elev, overwrite=ovwr)

    if skipped:
        for skip in skipped:
            print("Plant: %r, Point: %r, kind: %r" % skip)
    elev.close()

    # compute a buffer around the plants
    buff = vplants + 'buff'
    v.buffer(input=vplants,
             type='line',
             output=buff,
             distance=0.1,
             overwrite=ovwr)
    TMPVECT.append(buff)
    # return all the river segments that are not already with plants
    v.overlay(flags='t',
              ainput=opts['river'],
              atype='line',
              binput=buff,
              operator='not',
              output=opts['output_streams'],
              overwrite=ovwr)


owsConnections = {}
owsConnections['default'] = {
    'dsn' : 'PG:host=523.riedackerhof.ch dbname=gis user=gis password=gisHoch3',
    'url' : 'https://523.riedackerhof.ch:4433/ows?',
    'username' :'gis',
    'password' : 'gisHoch3',
    'layers' : {
        'cultures' : 'ch_gelan_kulturen_2014',
        'fieldblocks' : 'ch_blw_erk2_feldblockkarte',
        'borders' : 'ch_swisstopo_kantone'
        },
    }
    
params = owsConnections['default']

dsn = params['dsn']

g.mapset(flags='c',mapset='solothurn')

v.in_ogr(dsn=dsn, layer=params['layers']['borders'], output='region', 
         where="kantonsnum = 11")
g.region(vect='region')
g.region(flags='p')

v.in_ogr(dsn=dsn, layer=params['layers']['cultures'], output='cultures', flags='r')
v.in_ogr(dsn=dsn, layer=params['layers']['fieldblocks'],output='fieldblocks', flags='r')
v.overlay(ainput='fieldblocks', binput = 'cultures', operator='not', output='fff')
    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))