Beispiel #1
0
def main(options, flags):
    #############################################################
    # inizialitation
    #############################################################
    pid = os.getpid()
    DEBUG = flags["d"]
    atexit.register(cleanup, pattern=("tmprgreen_%i*" % pid), debug=DEBUG)
    # TOD_add the possibilities to have q_points
    # required
    discharge = options["discharge"]
    dtm = options["elevation"]
    # basin potential
    basins = options["basins"]
    stream = options["stream"]  # raster
    rivers = options["rivers"]  # vec
    lakes = options["lakes"]  # vec
    E = options["output"]
    threshold = options["threshold"]

    # existing plants
    #    segments = options['segments']
    #    output_segm = options['output_segm']
    #    output_point = options['output_point']
    #    hydro = options['hydro']
    #    hydro_layer = options['hydro_layer']
    #    hydro_kind_intake = options['hydro_kind_intake']
    #    hydro_kind_turbine = options['hydro_kind_turbine']
    #    other = options['other']
    #    other_kind_intake = options['other_kind_intake']
    #    other_kind_turbine = options['other_kind_turbine']

    # optional

    msgr = get_msgr()
    # info = gcore.parse_command('g.region', flags='m')
    # print info
    #############################################################
    # check temporary raster

    if rivers:
        # cp the vector in the current mapset in order to clean it
        tmp_river = "tmprgreen_%i_river" % pid
        to_copy = "%s,%s" % (rivers, tmp_river)
        gcore.run_command("g.copy", vector=to_copy)
        rivers = tmp_river
        gcore.run_command("v.build", map=rivers)
        tmp_dtm_corr = "tmprgreen_%i_dtm_corr" % pid
        dtm_corr(dtm, rivers, tmp_dtm_corr, lakes)
        basins, stream = basin.check_compute_basin_stream(
            basins, stream, tmp_dtm_corr, threshold)
    else:
        basins, stream = basin.check_compute_basin_stream(
            basins, stream, dtm, threshold)

    perc_overlay = check_overlay_rr(discharge, stream)
    # pdb.set_trace()
    try:
        p = float(perc_overlay)
        if p < 90:
            warn = ("Discharge map doesn't overlay all the stream map."
                    "It covers only the %s %% of rivers") % (perc_overlay)
            msgr.warning(warn)
    except ValueError:
        msgr.error("Could not convert data to a float")
    except:
        msgr.error("Unexpected error")

    msgr.message("\Init basins\n")
    # pdb.set_trace()
    #############################################################
    # core
    #############################################################
    basins_tot, inputs = basin.init_basins(basins)

    msgr.message("\nBuild the basin network\n")
    #############################################################
    # build_network(stream, dtm, basins_tot) build relationship among basins
    # Identify the closure point with the r.neigbours module
    # if the difference betwwen the stream and the neighbours
    # is negative it means a new subsanin starts
    #############################################################
    basin.build_network(stream, dtm, basins_tot)
    stream_n = raster2numpy(stream)
    discharge_n = raster2numpy(discharge)
    basin.fill_basins(inputs, basins_tot, basins, dtm, discharge_n, stream_n)

    ###################################################################
    # check if lakes and delate stream in lakes optional
    ###################################################################

    if lakes:
        remove_pixel_from_raster(lakes, stream)

    ####################################################################
    # write results
    ####################################################################
    # if not rivers or debug I write the result in the new vector stream
    msgr.message("\nWrite results\n")

    basin.write_results2newvec(stream, E, basins_tot, inputs)
    power2energy(E, "Etot_kW", 8760)
def main(options, flags):
    TMPRAST = []
    DEBUG = True if flags['d'] else False
    atexit.register(cleanup, raster=TMPRAST, debug=DEBUG)

    elevation = options['elevation']
    plant = options['plant']
    output_struct = options['output_struct']
    input_struct = options['input_struct']
    output_plant = options['output_plant']
    percentage_losses = float(options['percentage_losses'])
    roughness_penstock = float(options['roughness_penstock'])
    ks_derivation = float(options['ks_derivation'])
    turbine_folder = (options['turbine_folder'] if options['turbine_folder']
                      else os.path.join(os.path.abspath('.'), 'turbines'))
    turbine_list = (options['turbine_list'] if options['turbine_list'] else
                    os.path.join(os.path.abspath('.'), 'turbines', 'list.txt'))
    efficiency_shaft = float(options['efficiency_shaft'])
    efficiency_alt = float(options['efficiency_alt'])
    efficiency_transf = float(options['efficiency_transf'])

    #import ipdb; ipdb.set_trace()
    #c = flags['c']
    msgr = get_msgr()

    #import ipdb; ipdb.set_trace()

    TMPRAST.extend(['new_river', 'buff_area'])
    if not gcore.overwrite():
        for m in TMPRAST:
            if gcore.find_file(m)['name']:
                msgr.fatal(_("Temporary raster map %s exists") % (m))
                # FIXME:check if it works for vectors

    if options['output_point']:
        conv_segpoints(plant, options['output_point'])

# FIXME: gross_head coherent with plants
# set the opions to execute the r.green.hydro.structure
    struct_opts = dict(elevation=elevation,
                       plant=plant,
                       output_struct=output_struct,
                       ndigits=options['ndigits'],
                       contour=options['contour'],
                       overwrite=gcore.overwrite())
    if options['resolution']:
        struct_opts['resolution'] = options['resolution']
## --------------------------------------------------------------------------
    if output_struct:
        gcore.run_command('r.green.hydro.structure', **struct_opts)
        gcore.run_command('v.build', map=output_struct)
    else:
        output_struct = input_struct
        # FIXME: check the structure of the input file


## --------------------------------------------------------------------------
    gcore.run_command('g.copy', vector=(plant, output_plant))
    with VectorTopo(output_struct, mode='rw') as struct:
        list_intakeid = compute_losses(struct, options, percentage_losses,
                                       roughness_penstock, ks_derivation)

        compute_power(struct, list_intakeid, turbine_list, turbine_folder,
                      efficiency_shaft, efficiency_alt, efficiency_transf)

    with VectorTopo(output_plant, mode='rw') as out, \
            VectorTopo(output_struct, mode='r') as struct:

        cols = [('tot_losses', 'DOUBLE'), ('net_head', 'DOUBLE'),
                ('e_global', 'DOUBLE'), ('power', 'DOUBLE')]

        add_columns(out, cols)

        scols = 'tot_losses', 'net_head', 'e_global', 'power'
        wherecond = 'plant_id={!r} AND kind LIKE {!r} AND max_power LIKE {!r}'
        for seg in out:
            where = wherecond.format(str(seg.attrs['plant_id']), 'penstock',
                                     'yes')
            sqlcode = struct.table.filters.select(
                ','.join(scols)).where(where).get_sql()
            svalues = struct.table.execute(sqlcode).fetchone()
            if svalues:
                for col, value in zip(scols, svalues):
                    if value:
                        seg.attrs[col] = value
        out.table.conn.commit()

    power2energy(output_plant, 'power', float(options['n']))
def main(options, flags):
    TMPRAST = []
    DEBUG = True if flags["d"] else False
    atexit.register(cleanup, raster=TMPRAST, debug=DEBUG)

    elevation = options["elevation"]
    plant = options["plant"]
    output_struct = options["output_struct"]
    input_struct = options["input_struct"]
    output_plant = options["output_plant"]
    percentage_losses = float(options["percentage_losses"])
    roughness_penstock = float(options["roughness_penstock"])
    ks_derivation = float(options["ks_derivation"])
    turbine_folder = (options["turbine_folder"] if options["turbine_folder"]
                      else os.path.join(os.path.abspath("."), "turbines"))
    turbine_list = (options["turbine_list"] if options["turbine_list"] else
                    os.path.join(os.path.abspath("."), "turbines", "list.txt"))
    efficiency_shaft = float(options["efficiency_shaft"])
    efficiency_alt = float(options["efficiency_alt"])
    efficiency_transf = float(options["efficiency_transf"])

    # import ipdb; ipdb.set_trace()
    # c = flags['c']
    msgr = get_msgr()

    # import ipdb; ipdb.set_trace()

    TMPRAST.extend(["new_river", "buff_area"])
    if not gcore.overwrite():
        for m in TMPRAST:
            if gcore.find_file(m)["name"]:
                msgr.fatal(_("Temporary raster map %s exists") % (m))
                # FIXME:check if it works for vectors

    if options["output_point"]:
        conv_segpoints(plant, options["output_point"])

    # FIXME: gross_head coherent with plants
    # set the opions to execute the r.green.hydro.structure
    struct_opts = dict(
        elevation=elevation,
        plant=plant,
        output_struct=output_struct,
        ndigits=options["ndigits"],
        contour=options["contour"],
        overwrite=gcore.overwrite(),
    )
    if options["resolution"]:
        struct_opts["resolution"] = options["resolution"]
    ## --------------------------------------------------------------------------
    if output_struct:
        gcore.run_command("r.green.hydro.structure", **struct_opts)
        gcore.run_command("v.build", map=output_struct)
    else:
        output_struct = input_struct
        # FIXME: check the structure of the input file
    ## --------------------------------------------------------------------------
    gcore.run_command("g.copy", vector=(plant, output_plant))
    with VectorTopo(output_struct, mode="rw") as struct:
        list_intakeid = compute_losses(struct, options, percentage_losses,
                                       roughness_penstock, ks_derivation)

        compute_power(
            struct,
            list_intakeid,
            turbine_list,
            turbine_folder,
            efficiency_shaft,
            efficiency_alt,
            efficiency_transf,
        )

    with VectorTopo(output_plant,
                    mode="rw") as out, VectorTopo(output_struct,
                                                  mode="r") as struct:

        cols = [
            ("tot_losses", "DOUBLE"),
            ("net_head", "DOUBLE"),
            ("e_global", "DOUBLE"),
            ("power", "DOUBLE"),
        ]

        add_columns(out, cols)

        scols = "tot_losses", "net_head", "e_global", "power"
        wherecond = "plant_id={!r} AND kind LIKE {!r} AND max_power LIKE {!r}"
        for seg in out:
            where = wherecond.format(str(seg.attrs["plant_id"]), "penstock",
                                     "yes")
            sqlcode = (struct.table.filters.select(
                ",".join(scols)).where(where).get_sql())
            svalues = struct.table.execute(sqlcode).fetchone()
            if svalues:
                for col, value in zip(scols, svalues):
                    if value:
                        seg.attrs[col] = value
        out.table.conn.commit()

    power2energy(output_plant, "power", float(options["n"]))
def main(opts, flgs):
    TMPRAST, TMPVECT, DEBUG = [], [], flgs["d"]
    atexit.register(cleanup, raster=TMPRAST, vector=TMPVECT, debug=DEBUG)
    OVW = gcore.overwrite()

    dtm = options["elevation"]
    river = options["river"]  # raster
    discharge_current = options["discharge_current"]  # vec
    discharge_natural = options["discharge_natural"]  # vec
    mfd = options["mfd"]
    len_plant = options["len_plant"]
    len_min = options["len_min"]
    distance = options["distance"]
    output_plant = options["output_plant"]
    area = options["area"]
    buff = options["buff"]
    efficiency = options["efficiency"]
    DEBUG = flags["d"]
    points_view = options["points_view"]
    new_region = options["visibility_resolution"]
    final_vis = options["output_vis"]
    n_points = options["n_points"]
    p_min = options["p_min"]
    percentage = options["percentage"]
    msgr = get_msgr()

    # set the region
    info = gcore.parse_command("g.region", flags="m")
    if (info["nsres"] == 0) or (info["ewres"] == 0):
        msgr.warning("set region to elevation raster")
        gcore.run_command("g.region", raster=dtm)

    pid = os.getpid()

    if area:
        if float(buff):
            area_tmp = "tmp_buff_area_%05d" % pid
            gcore.run_command("v.buffer",
                              input=area,
                              output=area_tmp,
                              distance=buff,
                              overwrite=OVW)
            area = area_tmp
            TMPVECT.append(area)
        oriver = "tmp_river_%05d" % pid
        gcore.run_command(
            "v.overlay",
            flags="t",
            ainput=river,
            binput=area,
            operator="not",
            output=oriver,
            overwrite=OVW,
        )
        river = oriver
        TMPVECT.append(oriver)

    if points_view:
        info_old = gcore.parse_command("g.region", flags="pg")
        set_new_region(new_region)
        pl, mset = points_view.split("@") if "@" in points_view else (
            points_view, "")
        vec = VectorTopo(pl, mapset=mset, mode="r")
        vec.open("r")
        string = "0"
        for i, point in enumerate(vec):
            out = "tmp_visual_%05d_%03d" % (pid, i)
            gcore.run_command(
                "r.viewshed",
                input=dtm,
                output=out,
                coordinates=point.coords(),
                overwrite=OVW,
                memory=1000,
                flags="b",
                max_distance=4000,
            )
            TMPRAST.append(out)
            # we use 4 km sice it the human limit
            string = string + ("+%s" % out)
        # import pdb; pdb.set_trace()

        tmp_final_vis = "tmp_final_vis_%05d" % pid
        formula = "%s = %s" % (tmp_final_vis, string)
        TMPRAST.append(tmp_final_vis)
        mapcalc(formula, overwrite=OVW)
        # change to old region
        set_old_region(info_old)
        TMPVECT.append(tmp_final_vis)
        gcore.run_command(
            "r.to.vect",
            flags="v",
            overwrite=OVW,
            input=tmp_final_vis,
            output=tmp_final_vis,
            type="area",
        )
        if int(n_points) > 0:
            where = "cat<%s" % (n_points)
        else:
            where = "cat=0"
        gcore.run_command(
            "v.db.droprow",
            input=tmp_final_vis,
            where=where,
            output=final_vis,
            overwrite=OVW,
        )
        tmp_river = "tmp_river2_%05d" % pid
        gcore.run_command(
            "v.overlay",
            flags="t",
            ainput=river,
            binput=final_vis,
            operator="not",
            output=tmp_river,
            overwrite=OVW,
        )
        river = tmp_river
        TMPVECT.append(tmp_river)

        # import pdb; pdb.set_trace()

    tmp_disch = "tmp_discharge_%05d" % pid
    if mfd:
        formula = "%s=%s-%s" % (tmp_disch, discharge_current, mfd)
        mapcalc(formula, overwrite=OVW)
        TMPRAST.append(tmp_disch)
        discharge_current = tmp_disch

    elif discharge_natural:
        formula = "%s=%s-%s*%s/100.0" % (
            tmp_disch,
            discharge_current,
            discharge_natural,
            percentage,
        )
        mapcalc(formula, overwrite=OVW)
        formula = "%s=if(%s>0, %s, 0)" % (tmp_disch, tmp_disch, tmp_disch)
        mapcalc(formula, overwrite=True)
        TMPRAST.append(tmp_disch)
        discharge_current = tmp_disch

    gcore.run_command(
        "r.green.hydro.optimal",
        flags="c",
        discharge=discharge_current,
        river=river,
        elevation=dtm,
        len_plant=len_plant,
        output_plant=output_plant,
        distance=distance,
        len_min=len_min,
        efficiency=efficiency,
        p_min=p_min,
    )
    power2energy(output_plant, "pot_power", float(options["n"]))
    print("r.green.hydro.recommended completed!")
def main(opts, flgs):
    TMPRAST, TMPVECT, DEBUG = [], [], flgs['d']
    atexit.register(cleanup, raster=TMPRAST, vector=TMPVECT, debug=DEBUG)
    OVW = gcore.overwrite()

    dtm = options['elevation']
    river = options['river']  # raster
    discharge_current = options['discharge_current']  # vec
    discharge_natural = options['discharge_natural']  # vec
    mfd = options['mfd']
    len_plant = options['len_plant']
    len_min = options['len_min']
    distance = options['distance']
    output_plant = options['output_plant']
    area = options['area']
    buff = options['buff']
    efficiency = options['efficiency']
    DEBUG = flags['d']
    points_view = options['points_view']
    new_region = options['visibility_resolution']
    final_vis = options['output_vis']
    n_points = options['n_points']
    p_min = options['p_min']
    percentage = options['percentage']
    msgr = get_msgr()

    # set the region
    info = gcore.parse_command('g.region', flags='m')
    if (info['nsres'] == 0) or (info['ewres'] == 0):
        msgr.warning("set region to elevation raster")
        gcore.run_command('g.region', raster=dtm)

    pid = os.getpid()

    if area:
        if float(buff):
            area_tmp = 'tmp_buff_area_%05d' % pid
            gcore.run_command('v.buffer',
                              input=area,
                              output=area_tmp,
                              distance=buff,
                              overwrite=OVW)
            area = area_tmp
            TMPVECT.append(area)
        oriver = 'tmp_river_%05d' % pid
        gcore.run_command('v.overlay',
                          flags='t',
                          ainput=river,
                          binput=area,
                          operator='not',
                          output=oriver,
                          overwrite=OVW)
        river = oriver
        TMPVECT.append(oriver)

    if points_view:
        info_old = gcore.parse_command('g.region', flags='pg')
        set_new_region(new_region)
        pl, mset = points_view.split('@') if '@' in points_view else (
            points_view, '')
        vec = VectorTopo(pl, mapset=mset, mode='r')
        vec.open("r")
        string = '0'
        for i, point in enumerate(vec):
            out = 'tmp_visual_%05d_%03d' % (pid, i)
            gcore.run_command(
                'r.viewshed',
                input=dtm,
                output=out,
                coordinates=point.coords(),
                overwrite=OVW,
                memory=1000,
                flags='b',
                max_distance=4000,
            )
            TMPRAST.append(out)
            # we use 4 km sice it the human limit
            string = string + ('+%s' % out)
        #import pdb; pdb.set_trace()

        tmp_final_vis = 'tmp_final_vis_%05d' % pid
        formula = '%s = %s' % (tmp_final_vis, string)
        TMPRAST.append(tmp_final_vis)
        mapcalc(formula, overwrite=OVW)
        # change to old region
        set_old_region(info_old)
        TMPVECT.append(tmp_final_vis)
        gcore.run_command('r.to.vect',
                          flags='v',
                          overwrite=OVW,
                          input=tmp_final_vis,
                          output=tmp_final_vis,
                          type='area')
        if int(n_points) > 0:
            where = 'cat<%s' % (n_points)
        else:
            where = 'cat=0'
        gcore.run_command('v.db.droprow',
                          input=tmp_final_vis,
                          where=where,
                          output=final_vis,
                          overwrite=OVW)
        tmp_river = 'tmp_river2_%05d' % pid
        gcore.run_command('v.overlay',
                          flags='t',
                          ainput=river,
                          binput=final_vis,
                          operator='not',
                          output=tmp_river,
                          overwrite=OVW)
        river = tmp_river
        TMPVECT.append(tmp_river)

        #import pdb; pdb.set_trace()

    tmp_disch = 'tmp_discharge_%05d' % pid
    if mfd:
        formula = '%s=%s-%s' % (tmp_disch, discharge_current, mfd)
        mapcalc(formula, overwrite=OVW)
        TMPRAST.append(tmp_disch)
        discharge_current = tmp_disch

    elif discharge_natural:
        formula = '%s=%s-%s*%s/100.0' % (tmp_disch, discharge_current,
                                         discharge_natural, percentage)
        mapcalc(formula, overwrite=OVW)
        formula = '%s=if(%s>0, %s, 0)' % (tmp_disch, tmp_disch, tmp_disch)
        mapcalc(formula, overwrite=True)
        TMPRAST.append(tmp_disch)
        discharge_current = tmp_disch

    gcore.run_command('r.green.hydro.optimal',
                      flags='c',
                      discharge=discharge_current,
                      river=river,
                      elevation=dtm,
                      len_plant=len_plant,
                      output_plant=output_plant,
                      distance=distance,
                      len_min=len_min,
                      efficiency=efficiency,
                      p_min=p_min)
    power2energy(output_plant, 'pot_power', float(options['n']))
    print('r.green.hydro.recommended completed!')