Ejemplo n.º 1
0
def main():

    # Get the options
    inputs = options["inputs"]
    sampler = options["sample"]
    samtype = options["samtype"]
    intype = options["intype"]
    separator = grass.separator(options["separator"])
    method = options["method"]
    header = flags["c"]
    spatial = flags["s"]

    # Make sure the temporal database exists
    tgis.init()

    tgis.sample_stds_by_stds_topology(intype, samtype, inputs, sampler, header, separator, method, spatial, True)
Ejemplo n.º 2
0
def main():

    # Get the options
    inputs = options["inputs"]
    sampler = options["sample"]
    samtype = options["samtype"]
    intype = options["intype"]
    separator = grass.separator(options["separator"])
    method = options["method"]
    header = flags["c"]
    spatial = flags["s"]

    # Make sure the temporal database exists
    tgis.init()

    tgis.sample_stds_by_stds_topology(intype, samtype, inputs, sampler, header,
                                      separator, method, spatial, True)
Ejemplo n.º 3
0
def main():
    # Get the options
    input = options["input"]
    output = options["output"]
    strds = options["strds"]
    where = options["where"]
    tempwhere = options["t_where"]

    if output and flags['u']:
        grass.fatal(_("Cannot combine 'output' option and 'u' flag"))
    elif not output and not flags['u']:
        grass.fatal(_("'output' option or 'u' flag must be given"))
    elif not output and flags['u']:
        grass.warning(_("Attribute table of vector {name} will be updated...").format(name=input))

    if where == "" or where == " " or where == "\n":
        where = None

    overwrite = grass.overwrite()

    quiet = True

    if grass.verbosity() > 2:
        quiet = False

    # Check the number of sample strds and the number of columns
    strds_names = strds.split(",")

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    samples = []

    first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)
    # Single space time raster dataset
    if len(strds_names) == 1:
        rows = first_strds.get_registered_maps("name,mapset,start_time,end_time",
                                               tempwhere, "start_time",
                                               dbif)

        if not rows:
            dbif.close()
            grass.fatal(_("Space time raster dataset <%s> is empty") %
                        first_strds.get_id())

        for row in rows:
            start = row["start_time"]
            end = row["end_time"]
            raster_maps = [row["name"] + "@" + row["mapset"], ]

            s = Sample(start, end, raster_maps, first_strds.get_name())
            samples.append(s)
    else:
        # Multiple space time raster datasets
        for name in strds_names[1:]:
            dataset = tgis.open_old_stds(name, "strds", dbif)
            if dataset.get_temporal_type() != first_strds.get_temporal_type():
                grass.fatal(_("Temporal type of space time raster "
                              "datasets must be equal\n<%(a)s> of type "
                              "%(type_a)s do not match <%(b)s> of type "
                              "%(type_b)s" % {"a": first_strds.get_id(),
                               "type_a": first_strds.get_temporal_type(),
                               "b": dataset.get_id(),
                               "type_b": dataset.get_temporal_type()}))

        mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds",
                                                        strds_names,
                                                        strds_names[0],
                                                        False, None,
                                                        "equal", False,
                                                        False)

        for i in xrange(len(mapmatrizes[0])):
            isvalid = True
            mapname_list = []
            for mapmatrix in mapmatrizes:

                entry = mapmatrix[i]

                if entry["samples"]:
                    sample = entry["samples"][0]
                    name = sample.get_id()
                    if name is None:
                        isvalid = False
                        break
                    else:
                        mapname_list.append(name)

            if isvalid:
                entry = mapmatrizes[0][i]
                map = entry["granule"]

                start, end = map.get_temporal_extent_as_tuple()
                s = Sample(start, end, mapname_list, name)
                samples.append(s)

    # Get the layer and database connections of the input vector
    if output:
        gcopy(input, output, 'vector')
    else:
        output = input

    msgr = Messenger()
    perc_curr = 0
    perc_tot = len(samples)
    pymap = Vector(output)
    try:
        pymap.open('r')
    except:
        dbif.close()
        grass.fatal(_("It is not possible to open the new map %s" % output))

    if len(pymap.dblinks) == 0:
        try:
            grass.run_command("v.db.addtable", map=output)
        except CalledModuleError:
            dbif.close()
            grass.fatal(_("Impossible add table to vector %s" % output))
    pymap.close()
    for sample in samples:
        raster_names = sample.raster_names
        # Call v.what.rast for each raster map

        for name in raster_names:
            coltype = "DOUBLE PRECISION"
            # Get raster map type
            raster_map = tgis.RasterDataset(name)
            raster_map.load()
            if raster_map.metadata.get_datatype() == "CELL":
                coltype = "INT"
            day = sample.printDay()
            column_name = "%s_%s" % (sample.strds_name, day)
            column_string = "%s %s" % (column_name, coltype)
            column_string.replace('.', '_')
            try:
                grass.run_command("v.db.addcolumn", map=output,
                                  column=column_string,
                                  overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to add column %s to vector map "
                              "<%s> ") % (column_string, output))
            try:
                grass.run_command("v.what.rast", map=output, raster=name,
                                  column=column_name, where=where,
                                  quiet=quiet)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to run v.what.rast for vector map"
                              " <%s> and raster map <%s>") %
                            (output, str(raster_names)))

        msgr.percent(perc_curr, perc_tot, 1)
        perc_curr += 1

    dbif.close()
Ejemplo n.º 4
0
def main():
    # Get the options
    input = options["input"]
    output = options["output"]
    strds = options["strds"]
    tempwhere = options["t_where"]
    where = options["where"]
    methods = options["method"]
    percentile = options["percentile"]

    overwrite = grass.overwrite()

    quiet = True

    if grass.verbosity() > 2:
        quiet = False

    if where == "" or where == " " or where == "\n":
        where = None

    # Check the number of sample strds and the number of columns
    strds_names = strds.split(",")

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    samples = []

    first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)
    # Single space time raster dataset
    if len(strds_names) == 1:
        granu = first_strds.get_granularity()
        rows = first_strds.get_registered_maps(
            "name,mapset,start_time,end_time", tempwhere, "start_time", dbif)
        if not rows:
            dbif.close()
            grass.fatal(
                _("Space time raster dataset <%s> is empty") %
                first_strds.get_id())

        for row in rows:
            start = row["start_time"]
            end = row["end_time"]
            raster_maps = [
                row["name"] + "@" + row["mapset"],
            ]

            s = Sample(start, end, raster_maps, first_strds.get_name(), granu)
            samples.append(s)
    else:
        # Multiple space time raster datasets
        for name in strds_names[1:]:
            dataset = tgis.open_old_stds(name, "strds", dbif)
            if dataset.get_temporal_type() != first_strds.get_temporal_type():
                grass.fatal(
                    _(
                        "Temporal type of space time raster "
                        "datasets must be equal\n<%(a)s> of type "
                        "%(type_a)s do not match <%(b)s> of type "
                        "%(type_b)s" % {
                            "a": first_strds.get_id(),
                            "type_a": first_strds.get_temporal_type(),
                            "b": dataset.get_id(),
                            "type_b": dataset.get_temporal_type()
                        }))

        mapmatrizes = tgis.sample_stds_by_stds_topology(
            "strds", "strds", strds_names, strds_names[0], False, None,
            "equal", False, False)
        #TODO check granularity for multiple STRDS
        for i in range(len(mapmatrizes[0])):
            isvalid = True
            mapname_list = []
            for mapmatrix in mapmatrizes:

                entry = mapmatrix[i]

                if entry["samples"]:
                    sample = entry["samples"][0]
                    name = sample.get_id()
                    if name is None:
                        isvalid = False
                        break
                    else:
                        mapname_list.append(name)

            if isvalid:
                entry = mapmatrizes[0][i]
                map = entry["granule"]

                start, end = map.get_temporal_extent_as_tuple()
                s = Sample(start, end, mapname_list, name)
                samples.append(s)
    # Get the layer and database connections of the input vector
    if where:
        try:
            grass.run_command("v.extract",
                              input=input,
                              where=where,
                              output=output)
        except CalledModuleError:
            dbif.close()
            grass.fatal(
                _("Unable to run v.extract for vector map"
                  " <%s> and where <%s>") % (input, where))
    else:
        gcopy(input, output, 'vector')

    msgr = Messenger()
    perc_curr = 0
    perc_tot = len(samples)
    pymap = Vector(output)
    try:
        pymap.open('r')
    except:
        dbif.close()
        grass.fatal(_("Unable to create vector map <%s>" % output))
    pymap.close()

    for sample in samples:
        raster_names = sample.raster_names
        # Call v.what.rast for each raster map
        for name in raster_names:
            day = sample.printDay()
            column_name = "%s_%s" % (sample.strds_name, day)
            try:
                grass.run_command("v.rast.stats",
                                  map=output,
                                  raster=name,
                                  column=column_name,
                                  method=methods,
                                  percentile=percentile,
                                  quiet=quiet,
                                  overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(
                    _("Unable to run v.what.rast for vector map"
                      " <%s> and raster map <%s>") % (output, name))

        msgr.percent(perc_curr, perc_tot, 1)
        perc_curr += 1

    dbif.close()
Ejemplo n.º 5
0
def main():
    # Initiate GRASS
    init = vtkGRASSInit()
    init.Init("t.rast.RothCModel")
    init.ExitOnErrorOn()

    module = vtkGRASSModule()
    module.SetDescription("Soil organic carbon computation using the RothC model")
    module.AddKeyword("temporal")
    module.AddKeyword("RothC")

    xmlParam = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetFileInputType())
    xmlParam.SetKey("param")
    xmlParam.RequiredOff()
    xmlParam.SetDescription("The parameter XML file that describes the RothC configuarion ")

    temperature = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    temperature.SetKey("temperature")
    temperature.SetDescription("Input space time raster dataset with "
                               "monthly temperature mean [degree C]"
                               ". This dataset will be used to temporally sample all other.")

    precipitation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    precipitation.SetKey("precipitation")
    precipitation.SetDescription("Input space time raster dataset with "
                                 "monthly accumulated precipitation [mm]")

    radiation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    radiation.SetKey("radiation")
    radiation.SetDescription("Input space time raster dataset with "
                             "global radiation [J/(cm^2 * day)]")

    fertilizer = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    fertilizer.SetKey("fertilizer")
    fertilizer.SetDescription("Input space time raster dataset with organic "
                              "fertilizer of the RothC model [tC/ha]")

    roots = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    roots.SetKey("roots")
    roots.SetDescription("Input space time raster dataset with root residuals of the RothC model [tC/ha]")
    
    shoots = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    shoots.SetKey("shoots")
    shoots.SetDescription("Input space time raster dataset with shoot residuals of the RothC model [tC/ha]")
    
    # Space time raster datasets
    soilCover = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    soilCover.SetKey("soilcover")
    soilCover.SetDescription("Input space time raster dataset with soil cover time series [0;1]")

    fertId = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    fertId.SetKey("fertid")
    fertId.RequiredOff()
    fertId.SetDescription("Input space time raster dataset with fertilizer ids of the RothC model parameter")

    shootId = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    shootId.SetKey("shootid")
    shootId.RequiredOff()
    shootId.SetDescription("Input space time raster dataset with shoot ids of the RothC model parameter")

    rootId = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    rootId.SetKey("rootid")
    rootId.RequiredOff()
    rootId.SetDescription("Input space time raster dataset with root ids of the RothC model parameter")

    # Raster map input
    clayContent = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    clayContent.SetKey("claycontent")
    clayContent.SetDescription("Input raster map with clay content in percent [%]")

    poolDPM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    poolDPM.SetKey("dpmpool")
    poolDPM.SetDescription("Input raster map specifying the DPM pool [tC/ha] at the start "
                           "of the computation (usually from generated by equilibrium run)")

    poolRPM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    poolRPM.SetKey("rpmpool")
    poolRPM.SetDescription("Input raster map specifying the RPM pool [tC/ha] at the start "
                           "of the computation (usually from generated by equilibrium run)")

    poolHUM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    poolHUM.SetKey("humpool")
    poolHUM.SetDescription("Input raster map specifying the HUM pool [tC/ha] at the start "
                           "of the computation (usually from generated by equilibrium run)")

    poolBIO = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    poolBIO.SetKey("biopool")
    poolBIO.SetDescription("Input raster map specifying the BIO pool [tC/ha] at the start "
                           "of the computation (usually from generated by equilibrium run)")

    poolIOM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    poolIOM.SetKey("iompool")
    poolIOM.SetDescription("Input raster map specifying the IOM pool [tC/ha] at the start "
                           "of the computation (usually from generated by equilibrium run)")

    baseName = vtkGRASSOption()
    baseName.SetKey("base")
    baseName.SetTypeToString()
    baseName.MultipleOff()
    baseName.RequiredOn()
    baseName.SetDescription("The base name of the new created raster maps")

    # Soil organic carbon Space time raster datasets
    soc = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSOutputType())
    soc.SetKey("soc")
    soc.SetDescription("Output space time raster dataset with SOC content [tC/ha]")

    # INIT
    paramter = vtkStringArray()
    for arg in sys.argv:
        paramter.InsertNextValue(str(arg))

    if init.Parser(paramter) == False:
        return -1
    # We need to modify the environment settings so that the
    # overwrite flag will be recognized
    os.environ["GRASS_OVERWRITE"] = str(init.Overwrite())
    os.environ["GRASS_VERBOSE"] = str(init.Verbosity())

    messages = vtkGRASSMessagingInterface()
    messages.VerboseMessage("Sampling of input datasets")

    tgis.init()

    inputNames = "%s,%s,%s,%s,%s,%s"%(precipitation.GetAnswer(), radiation.GetAnswer(),
                            soilCover.GetAnswer(), fertilizer.GetAnswer(),
                            roots.GetAnswer(), shoots.GetAnswer())

    if fertId.GetAnswer():
        inputNames += ",%s"%(fertId.GetAnswer())

    if shootId.GetAnswer() and not fertId.GetAnswer():
        print("ERROR: Shoot id and fertilizer id must be set")
        return -1

    if shootId.GetAnswer():
        inputNames += ",%s"%(shootId.GetAnswer())

    if rootId.GetAnswer() and not shootId.GetAnswer():
        print("ERROR: Root id and shoot id must be set")
        return -1

    if rootId.GetAnswer():
        inputNames += ",%s"%(rootId.GetAnswer())

    mapmatrix = tgis.sample_stds_by_stds_topology("strds", "strds", inputNames,
                                           temperature.GetAnswer(), False,
                                 "|", "equal,during,contains", False, True)

    pools = read_pools(poolDPM=poolDPM.GetAnswer(), poolRPM=poolRPM.GetAnswer(),
                       poolHUM=poolHUM.GetAnswer(), poolBIO=poolBIO.GetAnswer(),
                       poolIOM=poolIOM.GetAnswer())

    xml = None
    if xmlParam.GetAnswer():
        xml = vtkTAG2ERothCModelParameter()
        xml.SetFileName(xmlParam.GetAnswer())
        xml.Read()
        xml.GenerateInternalSchemeFromXML()

    RothCModelRun(mapmatrix, pools, clayContent.GetAnswer(), soc.GetAnswer(),
                  baseName.GetAnswer(), xml, -99999, bool(init.Overwrite()))

    return 0
Ejemplo n.º 6
0
def main():
    #lazy imports
    import grass.temporal as tgis

    # Get the options
    input = options["input"]
    output = options["output"]
    vector_output = options["vector_output"]
    strds = options["strds"]
    where = options["where"]
    columns = options["columns"]

    if where == "" or where == " " or where == "\n":
        where = None

    overwrite = grass.overwrite()

    # Check the number of sample strds and the number of columns
    strds_names = strds.split(",")
    column_names = columns.split(",")

    if len(strds_names) != len(column_names):
        grass.fatal(_("The number of columns must be equal to the number of space time raster datasets"))

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    mapset = grass.gisenv()["MAPSET"]

    out_sp = tgis.check_new_stds(output, "stvds", dbif, overwrite)

    samples = []

    first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)

    # Single space time raster dataset
    if len(strds_names) == 1:
        rows = first_strds.get_registered_maps(
            columns="name,mapset,start_time,end_time",
            order="start_time", dbif=dbif)

        if not rows:
            dbif.close()
            grass.fatal(_("Space time raster dataset <%s> is empty") %
                        out_sp.get_id())

        for row in rows:
            start = row["start_time"]
            end = row["end_time"]
            raster_maps = [row["name"] + "@" + row["mapset"],]

            s = Sample(start, end, raster_maps)
            samples.append(s)
    else:
        # Multiple space time raster datasets
        for name in strds_names[1:]:
            dataset = tgis.open_old_stds(name, "strds", dbif)
            if dataset.get_temporal_type() != first_strds.get_temporal_type():
                grass.fatal(_("Temporal type of space time raster datasets must be equal\n"
                              "<%(a)s> of type %(type_a)s do not match <%(b)s> of type %(type_b)s"%
                              {"a":first_strds.get_id(),
                               "type_a":first_strds.get_temporal_type(),
                               "b":dataset.get_id(),
                               "type_b":dataset.get_temporal_type()}))

        mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds", strds_names,
                                                      strds_names[0], False, None,
                                                      "equal", False, False)

        for i in range(len(mapmatrizes[0])):
            isvalid = True
            mapname_list = []
            for mapmatrix in mapmatrizes:

                entry = mapmatrix[i]

                if entry["samples"]:
                    sample = entry["samples"][0]
                    name = sample.get_id()
                    if name is None:
                        isvalid = False
                        break
                    else:
                        mapname_list.append(name)

            if isvalid:
                entry = mapmatrizes[0][i]
                map = entry["granule"]

                start, end = map.get_temporal_extent_as_tuple()
                s = Sample(start, end, mapname_list)
                samples.append(s)

    num_samples = len(samples)

    # Get the layer and database connections of the input vector
    vector_db = grass.vector.vector_db(input)

    # We copy the vector table and create the new layers
    if vector_db:
        # Use the first layer to copy the categories from
        layers = "1,"
    else:
        layers = ""
    first = True
    for layer in range(num_samples):
        layer += 1
        # Skip existing layer
        if vector_db and layer in vector_db and \
           vector_db[layer]["layer"] == layer:
            continue
        if first:
            layers += "%i" % (layer)
            first = False
        else:
            layers += ",%i" % (layer)

    vectmap = vector_output

    # We create a new vector map using the categories of the original map
    try:
        grass.run_command("v.category", input=input, layer=layers,
                          output=vectmap, option="transfer",
                          overwrite=overwrite)
    except CalledModuleError:
        grass.fatal(_("Unable to create new layers for vector map <%s>")
                    % (vectmap))

    title = _("Observaion of space time raster dataset(s) <%s>") % (strds)
    description= _("Observation of space time raster dataset(s) <%s>"
                   " with vector map <%s>") % (strds, input)

    # Create the output space time vector dataset
    out_sp = tgis.open_new_stds(output, "stvds",
                                              first_strds.get_temporal_type(),
                                              title, description,
                                              first_strds.get_semantic_type(),
                                              dbif, overwrite)

    dummy = out_sp.get_new_map_instance(None)

    # Sample the space time raster dataset with the vector
    # map at specific layer with v.what.rast
    count = 1
    for sample in samples:
        raster_names = sample.raster_names

        if len(raster_names) != len(column_names):
            grass.fatal(_("The number of raster maps in a granule must "
                          "be equal to the number of column names"))

        # Create the columns creation string
        columns_string = ""
        for name, column in zip(raster_names, column_names):
            # The column is by default double precision
            coltype = "DOUBLE PRECISION"
            # Get raster map type
            raster_map = tgis.RasterDataset(name)
            raster_map.load()
            if raster_map.metadata.get_datatype() == "CELL":
                coltype = "INT"

            tmp_string = "%s %s," %(column, coltype)
            columns_string += tmp_string

        # Remove last comma
        columns_string = columns_string[0:len(columns_string) - 1]

        # Try to add a column
        if vector_db and count in vector_db and vector_db[count]["table"]:
            try:
                grass.run_command("v.db.addcolumn", map=vectmap,
                                  layer=count, column=columns_string,
                                  overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to add column %s to vector map <%s> "
                              "with layer %i") % (columns_string, vectmap, count))
        else:
            # Try to add a new table
            grass.message("Add table to layer %i" % (count))
            try:
                grass.run_command("v.db.addtable", map=vectmap, layer=count,
                                  columns=columns_string, overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to add table to vector map "
                              "<%s> with layer %i") % (vectmap, count))

        # Call v.what.rast for each raster map
        for name, column in zip(raster_names, column_names):
            try:
                grass.run_command("v.what.rast", map=vectmap,
                                  layer=count, raster=name,
                                  column=column, where=where)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to run v.what.rast for vector map <%s> "
                            "with layer %i and raster map <%s>") %
                            (vectmap, count, str(raster_names)))

        vect = out_sp.get_new_map_instance(dummy.build_id(vectmap,
                                                          mapset, str(count)))
        vect.load()

        start = sample.start
        end = sample.end

        if out_sp.is_time_absolute():
            vect.set_absolute_time(start, end)
        else:
            vect.set_relative_time(
                start, end, first_strds.get_relative_time_unit())

        if vect.is_in_db(dbif):
            vect.update_all(dbif)
        else:
            vect.insert(dbif)

        out_sp.register_map(vect, dbif)
        count += 1

    out_sp.update_from_registered_maps(dbif)
    dbif.close()
Ejemplo n.º 7
0
def main():
    # lazy imports
    import grass.temporal as tgis
    from grass.pygrass.utils import copy as gcopy
    from grass.pygrass.messages import Messenger
    from grass.pygrass.vector import Vector

    # Get the options
    input = options["input"]
    output = options["output"]
    strds = options["strds"]
    where = options["where"]
    tempwhere = options["t_where"]

    if output and flags['u']:
        grass.fatal(_("Cannot combine 'output' option and 'u' flag"))
    elif not output and not flags['u']:
        grass.fatal(_("'output' option or 'u' flag must be given"))
    elif not output and flags['u']:
        grass.warning(
            _("Attribute table of vector {name} will be updated...").format(
                name=input))

    if where == "" or where == " " or where == "\n":
        where = None

    overwrite = grass.overwrite()

    quiet = True

    if grass.verbosity() > 2:
        quiet = False

    # Check the number of sample strds and the number of columns
    strds_names = strds.split(",")

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    samples = []

    first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)
    # Single space time raster dataset
    if len(strds_names) == 1:
        granu = first_strds.get_granularity()
        rows = first_strds.get_registered_maps(
            "name,mapset,start_time,end_time", tempwhere, "start_time", dbif)

        if not rows:
            dbif.close()
            grass.fatal(
                _("Space time raster dataset <%s> is empty") %
                first_strds.get_id())
        for row in rows:
            start = row["start_time"]
            end = row["end_time"]
            raster_maps = [
                row["name"] + "@" + row["mapset"],
            ]

            s = Sample(start, end, raster_maps, first_strds.get_name(), granu)
            samples.append(s)
    else:
        # Multiple space time raster datasets
        for name in strds_names[1:]:
            dataset = tgis.open_old_stds(name, "strds", dbif)
            if dataset.get_temporal_type() != first_strds.get_temporal_type():
                grass.fatal(
                    _(
                        "Temporal type of space time raster "
                        "datasets must be equal\n<%(a)s> of type "
                        "%(type_a)s do not match <%(b)s> of type "
                        "%(type_b)s" % {
                            "a": first_strds.get_id(),
                            "type_a": first_strds.get_temporal_type(),
                            "b": dataset.get_id(),
                            "type_b": dataset.get_temporal_type()
                        }))

        mapmatrizes = tgis.sample_stds_by_stds_topology(
            "strds", "strds", strds_names, strds_names[0], False, None,
            "equal", False, False)
        #TODO check granularity for multiple STRDS
        for i in range(len(mapmatrizes[0])):
            isvalid = True
            mapname_list = []
            for mapmatrix in mapmatrizes:

                entry = mapmatrix[i]

                if entry["samples"]:
                    sample = entry["samples"][0]
                    name = sample.get_id()
                    if name is None:
                        isvalid = False
                        break
                    else:
                        mapname_list.append(name)

            if isvalid:
                entry = mapmatrizes[0][i]
                map = entry["granule"]

                start, end = map.get_temporal_extent_as_tuple()
                s = Sample(start, end, mapname_list, name)
                samples.append(s)

    # Get the layer and database connections of the input vector
    if output:
        gcopy(input, output, 'vector')
    else:
        output = input

    msgr = Messenger()
    perc_curr = 0
    perc_tot = len(samples)
    pymap = Vector(output)
    try:
        pymap.open('r')
    except:
        dbif.close()
        grass.fatal(_("Unable to create vector map <%s>" % output))

    if len(pymap.dblinks) == 0:
        try:
            pymap.close()
            grass.run_command("v.db.addtable", map=output)
        except CalledModuleError:
            dbif.close()
            grass.fatal(
                _("Unable to add table <%s> to vector map <%s>" % output))
    if pymap.is_open():
        pymap.close()

    for sample in samples:
        raster_names = sample.raster_names
        # Call v.what.rast for each raster map

        for name in raster_names:
            coltype = "DOUBLE PRECISION"
            # Get raster map type
            raster_map = tgis.RasterDataset(name)
            raster_map.load()
            if raster_map.metadata.get_datatype() == "CELL":
                coltype = "INT"
            day = sample.printDay()
            column_name = "%s_%s" % (sample.strds_name, day)
            column_string = "%s %s" % (column_name, coltype)
            column_string.replace('.', '_')
            try:
                grass.run_command("v.db.addcolumn",
                                  map=output,
                                  column=column_string,
                                  overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(
                    _("Unable to add column %s to vector map "
                      "<%s> ") % (column_string, output))
            try:
                grass.run_command("v.what.rast",
                                  map=output,
                                  raster=name,
                                  column=column_name,
                                  where=where,
                                  quiet=quiet)
            except CalledModuleError:
                dbif.close()
                grass.fatal(
                    _("Unable to run v.what.rast for vector map"
                      " <%s> and raster map <%s>") %
                    (output, str(raster_names)))

        msgr.percent(perc_curr, perc_tot, 1)
        perc_curr += 1

    dbif.close()
Ejemplo n.º 8
0
def main():
    # Initiate GRASS
    init = vtkGRASSInit()
    init.Init("t.rast.RothCEquilibrium")
    init.ExitOnErrorOn()

    module = vtkGRASSModule()
    module.SetDescription("Compute the RothC soil carbon equilibrium using Brents method")
    module.AddKeyword("temporal")
    module.AddKeyword("RothC")
    
    temperature = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    temperature.SetKey("temperature")
    temperature.SetDescription("Input space time raster dataset with long "
    "term monthly temperature mean [degree C] (at least 12 months)"
                               ". This dataset will be used to temporally sample all other.")
    
    precipitation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    precipitation.SetKey("precipitation")
    precipitation.SetDescription("Input space time raster dataset with long term "
                                 "monthly accumulated precipitation [mm] (at least 12 months)")
    
    radiation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    radiation.SetKey("radiation")
    radiation.SetDescription("Input space time raster dataset with long term monthly "
                             "global radiation [J/(cm^2 * day)] (at least 12 months)")
    
    # Space time raster datasets
    soilCover = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    soilCover.SetKey("soilcover")
    soilCover.SetDescription("Input space time raster dataset with long term monthly "
                             "soil cover (at least 12 months)")
                       
    # Raster map input
    clayContent = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    clayContent.SetKey("claycontent")
    clayContent.SetDescription("Input raster map with clay content in percent [%]")
    
    soilCarbon = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    soilCarbon.SetKey("soc")
    soilCarbon.SetDescription("Input raster map with target SOC [tC/ha]")

    residuals = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterInputType())
    residuals.SetKey("residuals")
    residuals.SetDescription("Input raster map with the initial residuals of the RothC model [tC/ha] "
                             "applied in august of each model year")
    
    output = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    output.SetDescription("The model soil organic carbon result raster map at equilibrium")
    
    poolDPM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    poolDPM.SetKey("dpmpool")
    poolDPM.SetDescription("The model DPM pool result raster map at equilibirum [tC/ha]")
        
    poolRPM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    poolRPM.SetKey("rpmpool")
    poolRPM.SetDescription("The model RPM pool result raster map at equilibirum [tC/ha]")
        
    poolHUM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    poolHUM.SetKey("humpool")
    poolHUM.SetDescription("The model HUM pool result raster map at equilibirum [tC/ha]")
        
    poolBIO = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    poolBIO.SetKey("biopool")
    poolBIO.SetDescription("The model BIO pool result raster map at equilibirum [tC/ha]")
        
    poolIOM = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    poolIOM.SetKey("iompool")
    poolIOM.SetDescription("The model IOM pool result raster map at equilibirum [tC/ha]")
    
    convergence = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    convergence.SetKey("convergence")
    convergence.SetDescription("Convergence raster map, 1 convence, 0 no convergence")
    
    squaredResiduals = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    squaredResiduals.SetKey("squaredresiduals")
    squaredResiduals.SetDescription("The squared residuals  raster map of the Brent optimization")
    """
    Model input start
      * Temperature STRDS name
      * Precipitation STRDS name
      * Radiation STRDS name
      * SoilCover STRDS name
      * Fertilizer STRDS name
      * Residuals STRDS name
    """
    
    modelTemperature = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelTemperature.SetKey("mtemperature")
    modelTemperature.RequiredOff()
    modelTemperature.SetDescription("Input space time raster dataset with monthly temperature mean [degree C]"
                               ". This dataset will be used to temporally sample all other.")
    
    modelPrecipitation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelPrecipitation.SetKey("mprecipitation")
    modelPrecipitation.RequiredOff()
    modelPrecipitation.SetDescription("Input space time raster dataset with "
                                      "accumulated precipitation [mm]")
    
    modelRadiation = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelRadiation.SetKey("mradiation")
    modelRadiation.RequiredOff()
    modelRadiation.SetDescription("Input space time raster dataset with monthly "
                             "global radiation [J/(cm^2 * day)]")
    
    modelResiduals = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelResiduals.SetKey("mresiduals")
    modelResiduals.RequiredOff()
    modelResiduals.SetDescription("Input space time raster dataset with monthly "
                             "residuals tC/ha")
    
    modelFertilizer = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelFertilizer.SetKey("mfertilizer")
    modelFertilizer.RequiredOff()
    modelFertilizer.SetDescription("Input space time raster dataset with monthly "
                             "fertilizer tC/ha")
    
    # Space time raster datasets
    modelSoilCover = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetSTRDSInputType())
    modelSoilCover.SetKey("msoilcover")
    modelSoilCover.RequiredOff()
    modelSoilCover.SetDescription("Input space time raster dataset with monthly soil cover")
    
    """
    Model input end
    """

    residualsOut = vtkGRASSOptionFactory().CreateInstance(vtkGRASSOptionFactory.GetRasterOutputType())
    residualsOut.SetKey("resout")
    residualsOut.SetDescription("The computed residuals raster map to reach equilibirum")
        
    iterations = vtkGRASSOption()
    iterations.SetKey("iterations")
    iterations.MultipleOff()
    iterations.RequiredOff()
    iterations.SetDefaultAnswer("20")
    iterations.SetDescription("The maximum number of iterations to find the equilibrium")
    iterations.SetTypeToInteger()

    years = vtkGRASSOption()
    years.SetKey("years")
    years.MultipleOff()
    years.RequiredOff()
    years.SetDefaultAnswer("300")
    years.SetDescription("The number of years of the provided temporal cycle")
    years.SetTypeToInteger()

    ax = vtkGRASSOption()
    ax.SetKey("ax")
    ax.MultipleOff()
    ax.RequiredOff()
    ax.SetDefaultAnswer("0")
    ax.SetDescription("The lower limit of the residual range")
    ax.SetTypeToDouble()
    
    cx = vtkGRASSOption()
    cx.SetKey("cx")
    cx.MultipleOff()
    cx.RequiredOff()
    cx.SetDefaultAnswer("15")
    cx.SetDescription("The upper limit of the residual range")
    cx.SetTypeToDouble()
    
    
    yearly = vtkGRASSFlag()
    yearly.SetDescription("Compute yearly aggregates for equilibrium run")
    yearly.SetKey('y')
    
    # INIT
    paramter = vtkStringArray()
    for arg in sys.argv:
        paramter.InsertNextValue(str(arg))

    if init.Parser(paramter) == False:
        return -1
    # We need to modify the environment settings so that the
    # overwrite flag will be recognized
    os.environ["GRASS_OVERWRITE"] = str(init.Overwrite())
    os.environ["GRASS_VERBOSE"] = str(init.Verbosity())

    tgis.init()
    messages = vtkGRASSMessagingInterface()

    messages.VerboseMessage("Reading raster maps into memory")

    # We define the line length as 30cm
    lineLengths = vtkDoubleArray()
    lineLengths.InsertNextValue(0.30)
    
    names = vtkStringArray()
    names.InsertNextValue(clayContent.GetAnswer())
    clayReader = vtkGRASSMultiRasterPolyDataLineReader()
    clayReader.SetRasterNames(names)
    clayReader.SetDataName("Clay")
    clayReader.SetLineLengths(lineLengths)
    clayReader.Update()
    
    # We are using the target SOC as initial SOC
    names = vtkStringArray()
    names.InsertNextValue(soilCarbon.GetAnswer())
    InitialCarbon = vtkGRASSMultiRasterPolyDataLineReader()
    InitialCarbon.SetRasterNames(names)
    InitialCarbon.SetDataName("InitialCarbon")
    InitialCarbon.SetLineLengths(lineLengths)
    InitialCarbon.Update()
    
    names = vtkStringArray()
    names.InsertNextValue(soilCarbon.GetAnswer())
    soilCarbonReader = vtkGRASSMultiRasterPolyDataLineReader()
    soilCarbonReader.SetRasterNames(names)
    soilCarbonReader.SetDataName("SoilCarbon")
    soilCarbonReader.SetLineLengths(lineLengths)
    soilCarbonReader.Update()
    
    names = vtkStringArray()
    names.InsertNextValue(residuals.GetAnswer())
    residualsReader = vtkGRASSMultiRasterPolyDataLineReader()
    residualsReader.SetRasterNames(names)
    residualsReader.SetDataName("Residuals")
    residualsReader.SetLineLengths(lineLengths)
    residualsReader.Update()
        
    inputNames = "%s,%s,%s"%(precipitation.GetAnswer(), radiation.GetAnswer(),
                            soilCover.GetAnswer())
    
    mapmatrix = tgis.sample_stds_by_stds_topology("strds", "strds", inputNames,
                                           temperature.GetAnswer(), False,
                                 "|", "equal", False, True)

    dataInputs = []
    
    if len(mapmatrix) > 0:
        
        if len(mapmatrix[0]) < 12:
            messages.FatalError("You must provide at least 12 months of data")
        
        for j in range(12):
            
            dsList = []
            
            for i in range(len(mapmatrix)):
                
                entry = mapmatrix[i][j]
                
                samples = entry["samples"]
                granule = entry["granule"]
                
                if len(samples) > 1:
                    messages.Warning("More than one maps found in sample. "
                                     "Using the first one only.")
                    for sample in samples:
                        print sample.get_id()
                    
                sample = samples[0]
                
                if sample.get_id() == None:
                    messages.FatalError("Gaps are not allowed")
                
                if i == 0:
                    id = sample.get_id()
                    names = vtkStringArray()
                    names.InsertNextValue(id)
                    reader = vtkGRASSMultiRasterPolyDataLineReader()
                    reader.SetRasterNames(names)
                    reader.SetDataName("Precipitation")
                    reader.SetLineLengths(lineLengths)
                    reader.Update()
                    
                    dsList.append(reader.GetOutput())

                if i == 1:
                    id = sample.get_id()
                    names = vtkStringArray()
                    names.InsertNextValue(id)
                    reader = vtkGRASSMultiRasterPolyDataLineReader()
                    reader.SetRasterNames(names)
                    reader.SetDataName("GlobalRadiation")
                    reader.SetLineLengths(lineLengths)
                    reader.Update()
                    
                    dsList.append(reader.GetOutput())

                if i == 2:
                    id = sample.get_id()
                    names = vtkStringArray()
                    names.InsertNextValue(id)
                    reader = vtkGRASSMultiRasterPolyDataLineReader()
                    reader.SetRasterNames(names)
                    reader.SetDataName("SoilCover")
                    reader.SetLineLengths(lineLengths)
                    reader.Update()
                    
                    dsList.append(reader.GetOutput())

            entry = mapmatrix[0][j]
            map = entry["granule"]
            id = map.get_id()
            
            names = vtkStringArray()
            names.InsertNextValue(id)
            reader = vtkGRASSMultiRasterPolyDataLineReader()
            reader.SetRasterNames(names)
            reader.SetDataName("MeanTemperature")
            reader.SetLineLengths(lineLengths)
            reader.Update()
            
            dsList.append(reader.GetOutput())
            
            join = vtkTAG2EDataSetJoinFilter()
            join.AddInput(clayReader.GetOutput())
            join.AddInput(InitialCarbon.GetOutput())
            
            for ds in dsList:
                join.AddInput(ds)
            join.Update()
            
            dataInputs.append(join.GetOutput())
    
    # Create the module input dictionary
    
    """
    Model input start
      * Temperature STRDS name
      * Precipitation STRDS name
      * Radiation STRDS name
      * SoilCover STRDS name
      * Fertilizer STRDS name
      * Residuals STRDS name
    """
    
    ModelRunNames = None

    if modelTemperature.GetAnswer() and \
        modelPrecipitation.GetAnswer() and \
        modelRadiation.GetAnswer() and \
        modelResiduals.GetAnswer() and \
        modelFertilizer.GetAnswer() and \
        modelSoilCover.GetAnswer():
        ModelRunNames = {}
        
        ModelRunNames["Temperature"] = modelTemperature.GetAnswer()
        ModelRunNames["Precipitation"] = modelPrecipitation.GetAnswer()
        ModelRunNames["Radiation"] = modelRadiation.GetAnswer()
        ModelRunNames["SoilCover"] = modelSoilCover.GetAnswer()
        ModelRunNames["Fertilizer"] = modelFertilizer.GetAnswer()
        ModelRunNames["Residuals"] = modelResiduals.GetAnswer()
        ModelRunNames["ClayContent"] = clayContent.GetAnswer()
            
    runType = "monthly"
    if yearly.GetAnswer():
        runType = "yearly"
        
    new_ds, res_ds = RothCEquilibriumRun(Inputs=dataInputs, 
                                 ResidualsInput=residualsReader.GetOutput(), 
                                 SoilCarbonInput=soilCarbonReader.GetOutput(), 
                                 Years=int(years.GetAnswer()), 
                                 NumberOfRuns=int(iterations.GetAnswer()),
                                 ax=float(ax.GetAnswer()), cx=float(cx.GetAnswer()), 
                                 ModelRunNames=ModelRunNames, runType=runType)

    # The layer array needs to be added
    new_ds.GetCellData().AddArray(soilCarbonReader.GetOutput().GetCellData().GetArray("Layer"))

# Write the resulting pools
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(output.GetAnswer())
    writer.SetArrayName("SoilCarbon")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(poolDPM.GetAnswer())
    writer.SetArrayName("DPM")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(poolRPM.GetAnswer())
    writer.SetArrayName("RPM")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(poolHUM.GetAnswer())
    writer.SetArrayName("HUM")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(poolBIO.GetAnswer())
    writer.SetArrayName("BIO")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(poolIOM.GetAnswer())
    writer.SetArrayName("IOM")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(residualsOut.GetAnswer())
    writer.SetArrayName("Residuals")
    writer.SetLayer(1)
    writer.SetInput(res_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(convergence.GetAnswer())
    writer.SetArrayName("Convergence")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
    
    writer = vtkGRASSMultiRasterPolyDataLineWriter()
    writer.SetRasterMapName(squaredResiduals.GetAnswer())
    writer.SetArrayName("SquaredResiduals")
    writer.SetLayer(1)
    writer.SetInput(new_ds)
    writer.Update()
Ejemplo n.º 9
0
def main():

    # Get the options
    input = options["input"]
    output = options["output"]
    vector_output = options["vector_output"]
    strds = options["strds"]
    where = options["where"]
    columns = options["columns"]

    if where == "" or where == " " or where == "\n":
        where = None

    overwrite = grass.overwrite()

    # Check the number of sample strds and the number of columns
    strds_names = strds.split(",")
    column_names = columns.split(",")

    if len(strds_names) != len(column_names):
        grass.fatal(_("The number of columns must be equal to the number of space time raster datasets"))

    # Make sure the temporal database exists
    tgis.init()
    # We need a database interface
    dbif = tgis.SQLDatabaseInterfaceConnection()
    dbif.connect()

    mapset = grass.gisenv()["MAPSET"]

    out_sp = tgis.check_new_stds(output, "stvds", dbif, overwrite)

    samples = []

    first_strds = tgis.open_old_stds(strds_names[0], "strds", dbif)

    # Single space time raster dataset
    if len(strds_names) == 1:
        rows = first_strds.get_registered_maps(
            columns="name,mapset,start_time,end_time", 
            order="start_time", dbif=dbif)

        if not rows:
            dbif.close()
            grass.fatal(_("Space time raster dataset <%s> is empty") %
                        out_sp.get_id())

        for row in rows:
            start = row["start_time"]
            end = row["end_time"]
            raster_maps = [row["name"] + "@" + row["mapset"],]

            s = Sample(start, end, raster_maps)
            samples.append(s)
    else:
        # Multiple space time raster datasets
        for name in strds_names[1:]:
            dataset = tgis.open_old_stds(name, "strds", dbif)
            if dataset.get_temporal_type() != first_strds.get_temporal_type():
                grass.fatal(_("Temporal type of space time raster datasets must be equal\n"
                              "<%(a)s> of type %(type_a)s do not match <%(b)s> of type %(type_b)s"%\
                              {"a":first_strds.get_id(),
                               "type_a":first_strds.get_temporal_type(),
                               "b":dataset.get_id(),
                               "type_b":dataset.get_temporal_type()}))

        mapmatrizes = tgis.sample_stds_by_stds_topology("strds", "strds", strds_names,
                                                      strds_names[0], False, None,
                                                      "equal", False, False)

        for i in range(len(mapmatrizes[0])):
            isvalid = True
            mapname_list = []
            for mapmatrix in mapmatrizes:
                
                entry = mapmatrix[i]

                if entry["samples"]:
                    sample = entry["samples"][0]
                    name = sample.get_id()
                    if name is None:
                        isvalid = False
                        break
                    else:
                        mapname_list.append(name)

            if isvalid:
                entry = mapmatrizes[0][i]
                map = entry["granule"]

                start, end = map.get_temporal_extent_as_tuple()
                s = Sample(start, end, mapname_list)
                samples.append(s)

    num_samples = len(samples)

    # Get the layer and database connections of the input vector
    vector_db = grass.vector.vector_db(input)

    # We copy the vector table and create the new layers
    if vector_db:
        # Use the first layer to copy the categories from
        layers = "1,"
    else:
        layers = ""
    first = True
    for layer in range(num_samples):
        layer += 1
        # Skip existing layer
        if vector_db and layer in vector_db and \
           vector_db[layer]["layer"] == layer:
            continue
        if first:
            layers += "%i" % (layer)
            first = False
        else:
            layers += ",%i" % (layer)

    vectmap = vector_output

    # We create a new vector map using the categories of the original map
    try:
        grass.run_command("v.category", input=input, layer=layers,
                          output=vectmap, option="transfer",
                          overwrite=overwrite)
    except CalledModuleError:
        grass.fatal(_("Unable to create new layers for vector map <%s>")
                    % (vectmap))

    title = _("Observaion of space time raster dataset(s) <%s>") % (strds)
    description= _("Observation of space time raster dataset(s) <%s>"
                   " with vector map <%s>") % (strds, input)

    # Create the output space time vector dataset
    out_sp = tgis.open_new_stds(output, "stvds",
                                              first_strds.get_temporal_type(),
                                              title, description,
                                              first_strds.get_semantic_type(),
                                              dbif, overwrite)

    dummy = out_sp.get_new_map_instance(None)

    # Sample the space time raster dataset with the vector
    # map at specific layer with v.what.rast
    count = 1
    for sample in samples:
        raster_names = sample.raster_names

        if len(raster_names) != len(column_names):
            grass.fatal(_("The number of raster maps in a granule must "
                          "be equal to the number of column names"))

        # Create the columns creation string
        columns_string = ""
        for name, column in zip(raster_names, column_names):
            # The column is by default double precision
            coltype = "DOUBLE PRECISION"
            # Get raster map type
            raster_map = tgis.RasterDataset(name)
            raster_map.load()
            if raster_map.metadata.get_datatype() == "CELL":
                coltype = "INT"

            tmp_string = "%s %s,"%(column, coltype)
            columns_string += tmp_string

        # Remove last comma
        columns_string = columns_string[0:len(columns_string) - 1]

        # Try to add a column
        if vector_db and count in vector_db and vector_db[count]["table"]:
            try:
                grass.run_command("v.db.addcolumn", map=vectmap,
                                  layer=count, column=columns_string,
                                  overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to add column %s to vector map <%s> "
                              "with layer %i") % (columns_string, vectmap, count))
        else:
            # Try to add a new table
            grass.message("Add table to layer %i" % (count))
            try:
                grass.run_command("v.db.addtable", map=vectmap, layer=count,
                                  columns=columns_string, overwrite=overwrite)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to add table to vector map "
                              "<%s> with layer %i") % (vectmap, count))

        # Call v.what.rast for each raster map
        for name, column in zip(raster_names, column_names):
            try:
                grass.run_command("v.what.rast", map=vectmap,
                                  layer=count, raster=name,
                                  column=column, where=where)
            except CalledModuleError:
                dbif.close()
                grass.fatal(_("Unable to run v.what.rast for vector map <%s> "
                            "with layer %i and raster map <%s>") % \
                            (vectmap, count, str(raster_names)))

        vect = out_sp.get_new_map_instance(dummy.build_id(vectmap,
                                                          mapset, str(count)))
        vect.load()
        
        start = sample.start
        end = sample.end
        
        if out_sp.is_time_absolute():
            vect.set_absolute_time(start, end)
        else:
            vect.set_relative_time(
                start, end, first_strds.get_relative_time_unit())

        if vect.is_in_db(dbif):
            vect.update_all(dbif)
        else:
            vect.insert(dbif)

        out_sp.register_map(vect, dbif)
        count += 1

    out_sp.update_from_registered_maps(dbif)
    dbif.close()