def computeSunShade(n,h,d,insolname,project):
  strDay = str(d).zfill(3) + "/"
  strHour = str(h).zfill(2) + "/"

  ##fill null values
  #r.null map=insolMONTH_0_DAY_2_HOUR_13_MINUTES_40 null=-1
  grass.run_command("r.null",map = insolname, null = -1)

  ##reclass sun to null and shade to 1
  # r.mapcalc expression='shade = if(insolMONTH_0_DAY_2_HOUR_13_MINUTES_40 == -1,1,null())' --o
  grass.run_command("r.mapcalc",expression = 'shade = if(' + insolname + ' == -1,1 ,null() )', overwrite=True)

  ##set shade color map
  #r.colors map=shade rules=python/colorrules
  grass.run_command("r.colors",map="shade",rules="python/libs/colorrules")


  ##export to png


  ##pokud je dopoledne secist
  #pokud je poledne vyexportovat a vymazat
  #secist
  #r.mapcalc expression='shadeCumulation = shadeCumulation + shade' --o

  if h==12 and n==minutes[0]:
    print(1111666668888)
    exportShadeCumulation(project,d,h)
    grass.run_command("r.mapcalc",expression="shadeCumulation = 0",overwrite=True)



  grass.run_command("r.mapcalc",expression="shadeCumulation = if(isnull(shade),shadeCumulation,shadeCumulation+shade)",overwrite=True)
  #grass.run_command("r.mapcalc",expression="shadeCumulation = if(shadeCumulation)",overwrite=True)
  #grass.run_command("r.info",map='shadeCumulation')
  print("cumul:")
  grass.run_command("r.stats",input = 'shadeCumulation',flags="c")
  print("shade:")
  grass.run_command("r.stats",input = 'shade',flags="c")


  shadePath = project+"/shade/" + strDay + strHour + minutesIndex[minutes.index(str(n))]
  #grass.run_command("r.out.gdal",flags="cf",input="shade", output = shadePath + '.tiff', type="Byte",createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9",overwrite=True)

  #grass.run_command("g.region",region="resortExtent")
  grass.run_command("g.region",n=grass.vector_info('inputJSONextentMask').north,s=grass.vector_info('inputJSONextentMask').south,w=grass.vector_info('inputJSONextentMask').west,e=grass.vector_info('inputJSONextentMask').east)

  grass.run_command("r.out.png",flags="t", input="shade", output = project+"/shade/" + strDay + strHour + minutesIndex[minutes.index(str(n))] + '.png', overwrite=True)
  #gdal_translate -ot Byte -of PNG C:\Users\Loukotka\Dropbox\ESA-2014\vojta\40.tiff C:/Users/Loukotka/Dropbox/ESA-2014/vojta/40png.png
  #gdal_translate -ot "Byte" -of "PNG" spindl3/shade/003/12/10.tiff spindl3/shade/003/12/10.png


  grass.run_command("g.region",rast='inputDEMraster', overwrite=True)
def computeInsolation(n, h, d, insolname, project):
    strDay = str(d).zfill(3) + "/"
    strHour = str(h).zfill(2) + "/"

    # run the solar model
    # r.sun elev=inputDEMraster asp_in=edu_raster_slope slope_in=edu_raster_aspect day=32 time=12.50 incidout=insolname --o
    grass.run_command("r.sun",
                      elev="inputDEMraster",
                      asp_in="edu_raster_slope",
                      slope_in="edu_raster_aspect",
                      day=d,
                      time=str(h) + '.' + str(n),
                      incidout=insolname,
                      overwrite=True)

    # export the outputs to GTiff files
    # r.out.gdal -c -f --o output=compSun.tiff type=Byte input=insolname createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9"

    #grass.run_command("g.region",region="resortExtent")

    grass.run_command("g.region",
                      n=grass.vector_info('inputJSONextentMask').north,
                      s=grass.vector_info('inputJSONextentMask').south,
                      w=grass.vector_info('inputJSONextentMask').west,
                      e=grass.vector_info('inputJSONextentMask').east)

    insolPath = project + "/sun/" + strDay + strHour + minutesIndex[
        minutes.index(str(n))]
    grass.run_command("r.out.gdal",
                      flags="cf",
                      input=insolname,
                      output=insolPath + ".tiff",
                      type="Byte",
                      createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9",
                      overwrite=True)
    call([
        "gdal_translate", '-ot', "Byte", '-of', "PNG", insolPath + '.tiff',
        insolPath + '.png'
    ])
    call(["rm", insolPath + '.tiff'])
    call(["rm", insolPath + '.png.aux.xml'])

    grass.run_command("g.region", rast='inputDEMraster')
def createRegionDefinition(project):
    ##start of write extent
    call(["mkdir", project + "/region"])

    ##regionInfo = grass.run_command("g.region",flags="g")
    ## create extent with boundary as [project]/extent.geojson and save it under resortExtent
    grass.run_command("g.region",
                      save="resortExtent",
                      n=grass.vector_info('inputJSONextentMask').north,
                      s=grass.vector_info('inputJSONextentMask').south,
                      w=grass.vector_info('inputJSONextentMask').west,
                      e=grass.vector_info('inputJSONextentMask').east)
    reg = grass.region()

    f = open(project + '/region/region.json', 'w+')
    print >> f, '{"n":' + str(reg.n) + ',"s":' + str(reg.s) + ',"w":' + str(
        reg.w) + ',"e":' + str(reg.e) + '}'
    f.close()

    grass.run_command("g.region", rast='inputDEMraster')
def computeInsolation(n,h,d,insolname,project):
  strDay = str(d).zfill(3) + "/"
  strHour = str(h).zfill(2) + "/"

  # run the solar model
  # r.sun elev=inputDEMraster asp_in=edu_raster_slope slope_in=edu_raster_aspect day=32 time=12.50 incidout=insolname --o
  grass.run_command("r.sun", elev = "inputDEMraster",asp_in = "edu_raster_slope",slope_in="edu_raster_aspect" ,day=d, time=str(h)+'.'+str(n) ,incidout=insolname,overwrite=True)

  # export the outputs to GTiff files
  # r.out.gdal -c -f --o output=compSun.tiff type=Byte input=insolname createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9"

  #grass.run_command("g.region",region="resortExtent")

  grass.run_command("g.region",n=grass.vector_info('inputJSONextentMask').north,s=grass.vector_info('inputJSONextentMask').south,w=grass.vector_info('inputJSONextentMask').west,e=grass.vector_info('inputJSONextentMask').east)

  insolPath = project+"/sun/" + strDay + strHour + minutesIndex[minutes.index(str(n))]
  grass.run_command("r.out.gdal",flags="cf",input = insolname, output = insolPath +".tiff", type="Byte", createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9",overwrite=True)
  call(["gdal_translate", '-ot', "Byte", '-of', "PNG", insolPath + '.tiff',  insolPath + '.png'])
  call(["rm", insolPath + '.tiff'])
  call(["rm", insolPath + '.png.aux.xml'])

  grass.run_command("g.region",rast='inputDEMraster')
示例#5
0
 def write_stations_snapped(self):
     """Write out the stations_snapped to a vector."""
     types = {'i': 'int', 'f': 'double'}
     # columns
     cols = self.stations_snapped_columns
     cols_dt = [' '.join([i, types[cols[i].dtype.kind]]) for i in cols.keys()]
     cols_fmt = '|'.join(['%'+cols[i].dtype.kind for i in cols.keys()])
     data = np.column_stack(cols.values())
     # create vector if needed
     p = grass.feed_command('v.in.ascii', input='-', x=3, y=4, cat=1, quiet=True,
                            columns=cols_dt, output=self.stations_snapped)
     np.savetxt(p.stdin, data, delimiter='|', fmt=cols_fmt)
     p.stdin.close()
     p.wait()
     # drop x y columns
     grun('v.db.dropcolumn', map=self.stations_snapped, columns='x,y')
     # add other columns
     cat = grass.vector_info(self.stations_snapped)['attribute_primary_key']
     grun('g.copy', vector=self.stations+',stations__tmp', quiet=True)
     catother = grass.vector_info('stations__tmp')['attribute_primary_key']
     grun('v.db.join', map=self.stations_snapped, column=cat,
          other_table='stations__tmp', other_column=catother, quiet=True)
     return
def createRegionDefinition(project):
  ##start of write extent
  call(["mkdir", project+"/region"])

  ##regionInfo = grass.run_command("g.region",flags="g")
  ## create extent with boundary as [project]/extent.geojson and save it under resortExtent
  grass.run_command("g.region",save="resortExtent",n=grass.vector_info('inputJSONextentMask').north,s=grass.vector_info('inputJSONextentMask').south,w=grass.vector_info('inputJSONextentMask').west,e=grass.vector_info('inputJSONextentMask').east)
  reg = grass.region()

  f = open(project+'/region/region.json', 'w+')
  print >>f, '{"n":'+str(reg.n) + ',"s":'+str(reg.s)+',"w":'+str(reg.w) + ',"e":'+str(reg.e)+'}'
  f.close()

  grass.run_command("g.region",rast='inputDEMraster')
示例#7
0
def main():
    # Get the options
    input = options["input"]
    input_name = input.split('@')[0]
    output = options["output"]
    method = options["method"]
    min_cat = None
    max_cat = None
    point = None
    overwrite = grass.overwrite()

    quiet = True

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

    in_info = grass.vector_info(input)
    # check for wild mixture of vector types
    if in_info['points'] > 0 and in_info['boundaries'] > 0:
        grass.fatal(_("The input vector map contains both polygons and points,"
                      " cannot handle mixed types"))

    pid = os.getpid()
    # process points via triangulation, then exit
    if in_info['points'] > 0:
        point = True
        layer = 1  # hardcoded for now
        out_temp = '{inp}_point_tmp_{pid}'.format(inp=input_name, pid=pid)
        if method == 'delaunay':
            grass.message(_("Processing point data (%d points found)...") % in_info['points'])
            grass.run_command('v.delaunay', input=input, layer=layer,
                              output=out_temp, quiet=quiet)

        grass.run_command('v.db.addtable', map=out_temp, quiet=True)
        input = out_temp
        in_info = grass.vector_info(input)

    # process areas
    if in_info['areas'] == 0 and in_info['boundaries'] == 0:
        grass.fatal(_("The input vector map does not contain polygons"))

    out_type = '{inp}_type_{pid}'.format(inp=input_name, pid=pid)
    input_tmp = '{inp}_tmp_{pid}'.format(inp=input_name, pid=pid)
    remove_names = "%s,%s" % (out_type, input_tmp)
    grass.message(_("Processing area data (%d areas found)...") % in_info['areas'])

    try:
        grass.run_command('v.category', layer="2", type='boundary',
                          option='add', input=input, out=input_tmp,
                          quiet=quiet)
    except CalledModuleError:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating layer 2"))
    try:
        grass.run_command('v.db.addtable', map=input_tmp, layer="2",
                          quiet=quiet)
    except CalledModuleError:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating new table for layer 2"))
    try:
        grass.run_command('v.to.db', map=input_tmp, option="sides",
                          columns="left,right", layer="2", quiet=quiet)
    except CalledModuleError:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=input_tmp, quiet=quiet)
        grass.fatal(_("Error populating new table for layer 2"))
    try:
        grass.run_command('v.type', input=input_tmp, output=out_type,
                          from_type='boundary', to_type='line',
                          quiet=quiet, layer="2")
    except CalledModuleError:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=remove_names, quiet=quiet)
        grass.fatal(_("Error converting polygon to line"))
    report = grass.read_command('v.category', flags='g', input=out_type,
                                option='report', quiet=quiet)
    report = decode(report).split('\n')
    for r in report:
        if r.find('centroid') != -1:
            min_cat = report[0].split()[-2]
            max_cat = report[0].split()[-1]
            break
    if min_cat and max_cat:
        try:
            grass.run_command('v.edit', map=out_type, tool='delete',
                              type='centroid', layer=2, quiet=quiet,
                              cats='{mi}-{ma}'.format(mi=min_cat, ma=max_cat))
        except CalledModuleError:
            grass.run_command('g.remove', flags='f', type='vector',
                              name=remove_names, quiet=quiet)
            grass.fatal(_("Error removing centroids"))

    try:
        try:
            # TODO: fix magic numbers for layer here and there
            grass.run_command('v.db.droptable', map=out_type, layer=1,
                              flags='f', quiet=True)
        except CalledModuleError:
            grass.run_command('g.remove', flags='f', type='vector',
                              name=remove_names, quiet=quiet)
            grass.fatal(_("Error removing table from layer 1"))
    # TODO: when this except is happaning, it seems that never, so it seems wrong
    except:
        grass.warning(_("No table for layer %d" % 1))
    try:
        grass.run_command('v.category', input=out_type, option='transfer',
                          output=output, layer="2,1", quiet=quiet,
                          overwrite=overwrite)
    except CalledModuleError:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=remove_names, quiet=quiet)
        grass.fatal(_("Error adding categories"))
    grass.run_command('g.remove', flags='f', type='vector',
                      name=remove_names, quiet=quiet)
    if point:
        grass.run_command('g.remove', flags='f', type='vector',
                          name=out_temp, quiet=quiet)
示例#8
0
文件: v.to.lines.py 项目: caomw/grass
def main():
    # Get the options
    input = options["input"]
    output = options["output"]
    method = options["method"]
    min_cat = None
    max_cat = None
    point = None
    overwrite = grass.overwrite()

    quiet = True

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

    in_info = grass.vector_info(input)
    # check for wild mixture of vector types
    if in_info['points'] > 0 and in_info['boundaries'] > 0:
        grass.fatal(_("The input vector map contains both polygons and points,"
                      " cannot handle mixed types"))

    pid = os.getpid()
    # process points via triangulation, then exit
    if in_info['points'] > 0:
        point = True
        layer = 1  # hardcoded for now
        out_temp = '{inp}_point_tmp_{pid}'.format(inp=input, pid=pid)
        if method == 'delaunay':
            grass.message(_("Processing point data (%d points found)...") % in_info['points'])
            grass.run_command('v.delaunay', input=input, layer=layer,
                              output=out_temp, quiet=quiet)

        grass.run_command('v.db.addtable', map=out_temp, quiet=True)
        input = out_temp
        in_info = grass.vector_info(input)

    # process areas
    if in_info['areas'] == 0 and in_info['boundaries'] == 0:
        grass.fatal(_("The input vector map does not contain polygons"))

    out_type = '{inp}_type_{pid}'.format(inp=input, pid=pid)
    input_tmp = '{inp}_tmp_{pid}'.format(inp=input, pid=pid)
    remove_names = "%s,%s" % (out_type, input_tmp)
    grass.message(_("Processing area data (%d areas found)...") % in_info['areas'])
    if 0 != grass.run_command('v.category', layer="2", type='boundary',
                              option='add', input=input, out=input_tmp,
                              quiet=quiet):
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating layer 2"))
    if 0 != grass.run_command('v.db.addtable', map=input_tmp, layer="2",
                              columns="left integer,right integer",
                              quiet=quiet):
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating new table for layer 2"))
    if 0 != grass.run_command('v.to.db', map=input_tmp, option="sides",
                              columns="left,right", layer="2", quiet=quiet):
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=input_tmp, quiet=quiet)
        grass.fatal(_("Error populating new table for layer 2"))

    if 0 != grass.run_command('v.type', input=input_tmp, output=out_type,
                              from_type='boundary', to_type='line',
                              quiet=quiet, layer="2"):
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=remove_names, quiet=quiet)
        grass.fatal(_("Error converting polygon to line"))
    report = grass.read_command('v.category', flags='g', input=out_type,
                                option='report', quiet=quiet).split('\n')
    for r in report:
        if r.find('centroid') != -1:
            min_cat = report[0].split()[-2]
            max_cat = report[0].split()[-1]
            break
    if min_cat and max_cat:
        if 0 != grass.run_command('v.edit', map=out_type, tool='delete',
                                  type='centroid', layer=2, quiet=quiet,
                                  cats='{mi}-{ma}'.format(mi=min_cat, ma=max_cat)):
            grass.run_command('g.remove', flags='f', type='vect',
                              pattern=remove_names, quiet=quiet)
            grass.fatal(_("Error removing centroids"))

    try:
        if 0 != grass.run_command('v.db.droptable', map=out_type, layer=1,
                                  flags='f', quiet=True):
            grass.run_command('g.remove', flags='f', type='vect',
                              pattern=remove_names, quiet=quiet)
            grass.fatal(_("Error removing table from layer 1"))
    except:
        grass.warning(_("No table for layer %d" % 1))
    if 0 != grass.run_command('v.category', input=out_type, option='transfer',
                              output=output, layer="2,1", quiet=quiet,
                              overwrite=overwrite):
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=remove_names, quiet=quiet)
        grass.fatal(_("Error adding categories"))
    grass.run_command('g.remove', flags='f', type='vect',
                      pattern=remove_names, quiet=quiet)
    if point:
        grass.run_command('g.remove', flags='f', type='vect',
                          pattern=out_temp, quiet=quiet)
示例#9
0
    def StartEditing(self, mapLayer):
        """Start editing selected vector map layer.

        :param mapLayer: MapLayer to be edited
        """
        # check if topology is available (skip for hidden - temporary
        # maps, see iclass for details)
        if (
            not mapLayer.IsHidden()
            and grass.vector_info(mapLayer.GetName())["level"] != 2
        ):
            dlg = wx.MessageDialog(
                parent=self.MapWindow,
                message=_(
                    "Topology for vector map <%s> is not available. "
                    "Topology is required by digitizer.\nDo you want to "
                    "rebuild topology (takes some time) and open the vector map "
                    "for editing?"
                )
                % mapLayer.GetName(),
                caption=_("Digitizer error"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE,
            )
            if dlg.ShowModal() == wx.ID_YES:
                RunCommand("v.build", map=mapLayer.GetName())
            else:
                return

        # deactive layer
        self.Map.ChangeLayerActive(mapLayer, False)

        # clean map canvas
        self.MapWindow.EraseMap()

        # unset background map if needed
        if mapLayer:
            if (
                UserSettings.Get(
                    group="vdigit",
                    key="bgmap",
                    subkey="value",
                    settings_type="internal",
                )
                == mapLayer.GetName()
            ):
                UserSettings.Set(
                    group="vdigit",
                    key="bgmap",
                    subkey="value",
                    value="",
                    settings_type="internal",
                )

            self.parent.SetStatusText(
                _("Please wait, " "opening vector map <%s> for editing...")
                % mapLayer.GetName(),
                0,
            )

        self.MapWindow.pdcVector = PseudoDC()
        self.digit = self.MapWindow.digit = self.digitClass(mapwindow=self.MapWindow)

        self.mapLayer = mapLayer
        # open vector map (assume that 'hidden' map layer is temporary vector
        # map)
        if self.digit.OpenMap(mapLayer.GetName(), tmp=mapLayer.IsHidden()) is None:
            self.mapLayer = None
            self.StopEditing()
            return False

        # check feature type (only for OGR layers)
        self.fType = self.digit.GetFeatureType()
        self.EnableAll()
        self.EnableUndo(False)
        self.EnableRedo(False)

        if self.fType == "point":
            for tool in (
                self.addLine,
                self.addArea,
                self.moveVertex,
                self.addVertex,
                self.removeVertex,
                self.editLine,
            ):
                self.EnableTool(tool, False)
        elif self.fType == "linestring":
            for tool in (self.addPoint, self.addArea):
                self.EnableTool(tool, False)
        elif self.fType == "polygon":
            for tool in (self.addPoint, self.addLine):
                self.EnableTool(tool, False)
        elif self.fType:
            GError(
                parent=self,
                message=_(
                    "Unsupported feature type '%(type)s'. Unable to edit "
                    "OGR layer <%(layer)s>."
                )
                % {"type": self.fType, "layer": mapLayer.GetName()},
            )
            self.digit.CloseMap()
            self.mapLayer = None
            self.StopEditing()
            return False

        # update toolbar
        if self.combo:
            self.combo.SetValue(mapLayer.GetName())
        if "map" in self.parent.toolbars:
            self.parent.toolbars["map"].combo.SetValue(_("Vector digitizer"))

        # here was dead code to enable vdigit button in toolbar
        # with if to ignore iclass
        # some signal (DigitizerStarted) can be emitted here

        Debug.msg(4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())

        # change cursor
        if self.MapWindow.mouse["use"] == "pointer":
            self.MapWindow.SetNamedCursor("cross")

        if not self.MapWindow.resize:
            self.MapWindow.UpdateMap(render=True)

        # respect opacity
        opacity = mapLayer.GetOpacity()

        if opacity < 1.0:
            alpha = int(opacity * 255)
            self.digit.GetDisplay().UpdateSettings(alpha=alpha)

        # emit signal
        layerTree = self._giface.GetLayerTree()
        if layerTree:
            item = layerTree.FindItemByData("maplayer", self.mapLayer)
        else:
            item = None
        self.editingStarted.emit(
            vectMap=mapLayer.GetName(), digit=self.digit, layerItem=item
        )

        return True
示例#10
0
def main():
    global temp_ng, temp_ncin, temp_ncout

    # we discard stderrs when not debugging
    # ideally stderrs should be printed when an exception was raised
    # this would be done easily with StringIO
    # but it doesn't work with subprocess
    if not grass.debug_level():
        nuldev = open(os.devnull, 'w')
    else:
        nuldev = sys.stderr

    # Initalise temporary verctor map names
    temp_ng = "v_lidar_mcc_tmp_ng_" + str(os.getpid())
    temp_ncin = "v_lidar_mcc_tmp_ncin_" + str(os.getpid())
    temp_ncout = "v_lidar_mcc_tmp_ncout_" + str(os.getpid())

    input = options['input']
    g_output = options['ground']
    ng_output = options['nonground']

    # does map exist?
    if not grass.find_file(input, element='vector')['file']:
        grass.fatal(_("Vector map <%s> not found") % input)

    # Count points in input map
    n_input = grass.vector_info(input)['points']

    # does map contain points ?
    if not (n_input > 0):
        grass.fatal(_("Vector map <%s> does not contain points") % input)

    flag_n = flags['n']

    ### Scale domain (l)
    # Evans & Hudak 2007 used scale domains 1 to 3
    l = int(1)
    l_stop = int(options['nl'])
    if (l_stop < 1):
        grass.fatal("The minimum number of scale domains is 1.")

    ### Curvature tolerance threshold (t)
    # Evans & Hudak 2007 used a t-value of 0.3
    t = float(options['t'])
    ###Increase of curvature tolerance threshold for each
    ti = t / 3.0

    ### Convergence threshold (j)
    # Evans & Hudak 2007 used a convergence threshold of 0.3
    j = float(options['j'])
    if (j <= 0):
        grass.fatal("The convergence threshold has to be > 0.")

    ### Tension parameter (f)
    # Evans & Hudak 2007 used a tension parameter 1.5
    f = float(options['f'])
    if (f <= 0):
        grass.fatal("The tension parameter has to be > 0.")

    ### Spline steps parameter (s)
    # Evans & Hudak 2007 used the 12 nearest neighbors
    # (used spline steps $res * 5 before)
    s = int(options['s'])
    if (s <= 0):
        grass.fatal("The spline step parameter has to be > 0.")

    ###Read desired resolution from region
    #Evans & Hudak 2007 used a desired resolution (delta) of 1.5
    gregion = grass.region()
    x_res_fin = gregion['ewres']
    y_res_fin = gregion['nsres']

    # Defineresolution steps in iteration
    n_res_steps = (l_stop + 1) / 2

    # Pass ame of input map to v.outlier
    nc_points = input

    # controls first creation of the output map before patching
    ng_output_exists = False
    # append and do not build topology
    vpatch_flags = 'ab'

    # 7.x requires topology to see z coordinate
    # 7.1 v.patch has flags to use z even without topology
    # see #2433 on Trac and r66822 in Subversion
    build_before_patch = True
    unused, gver_minor, unused = grass.version()['version'].split('.')
    if int(gver_minor) >= 1:
        build_before_patch = False
        # do not expect topology and expect z
        vpatch_flags += 'nz'

    # Loop through scale domaines
    while (l <= l_stop):
        i = 1
        convergence = 100
        if (l < ((l_stop + 1) / 2)):
            xres = x_res_fin / (n_res_steps - (l - 1))
            yres = y_res_fin / (n_res_steps - (l - 1))
        elif (l == ((l_stop + 1) / 2)):
            xres = x_res_fin
            yres = y_res_fin
        else:
            xres = x_res_fin * ((l + 1) - n_res_steps)
            yres = y_res_fin * ((l + 1) - n_res_steps)

        grass.use_temp_region()
        grass.run_command("g.region",
                          s=gregion['s'],
                          w=gregion['w'],
                          nsres=yres,
                          ewres=xres,
                          flags="a")
        xs_s = xres * s
        ys_s = yres * s
        grass.message("Processing scale domain " + str(l) + "...")
        # Repeat application of v.outlier until convergence level is reached
        while (convergence > j):
            grass.verbose("Number of input points in iteration " + str(i) +
                          ": " + str(n_input))
            # Run v.outlier
            if not flag_n:
                grass.run_command('v.outlier',
                                  input=nc_points,
                                  output=temp_ncout,
                                  outlier=temp_ng,
                                  ew_step=xs_s,
                                  ns_step=ys_s,
                                  lambda_=f,
                                  threshold=t,
                                  filter='positive',
                                  overwrite=True,
                                  quiet=True,
                                  stderr=nuldev)
            else:
                grass.run_command('v.outlier',
                                  input=nc_points,
                                  output=temp_ncout,
                                  outlier=temp_ng,
                                  ew_step=xs_s,
                                  ns_step=ys_s,
                                  lambda_=f,
                                  threshold=t,
                                  filter='negative',
                                  overwrite=True,
                                  quiet=True,
                                  stderr=nuldev)

            # Get information about results for calculating convergence level
            ng = grass.vector_info(temp_ng)['points']
            nc = n_input - ng
            n_input = nc
            grass.run_command('g.remove',
                              flags='f',
                              type='vector',
                              name=temp_ncin,
                              quiet=True,
                              stderr=nuldev)
            grass.run_command("g.rename",
                              vector=temp_ncout + "," + temp_ncin,
                              quiet=True,
                              stderr=nuldev)
            nc_points = temp_ncin
            # Give information on process status
            grass.verbose("Unclassified points after iteration " + str(i) +
                          ": " + str(nc))
            grass.verbose("Points classified as non ground after iteration " +
                          str(i) + ": " + str(ng))
            # Set convergence level
            if (nc > 0):
                convergence = float(float(ng) / float(nc))
                if build_before_patch:
                    grass.run_command('v.build', map=temp_ng, stderr=nuldev)
                # Patch non-ground points to non-ground output map
                if ng_output_exists:
                    grass.run_command('v.patch',
                                      input=temp_ng,
                                      output=ng_output,
                                      flags=vpatch_flags,
                                      overwrite=True,
                                      quiet=True,
                                      stderr=nuldev)
                else:
                    grass.run_command('g.copy',
                                      vector=(temp_ng, ng_output),
                                      stderr=nuldev)
                    ng_output_exists = True
            else:
                convergence = 0
            # Give information on convergence level
            grass.verbose("Convergence level after run " + str(i) +
                          " in scale domain " + str(l) + ": " +
                          str(round(convergence, 3)))
            # Increase iterator
            i = i + 1
        # Adjust curvature tolerance and reset scale domain
        t = t + ti
        l = l + 1
        # Delete temporary region
        grass.del_temp_region()

    # Rename temporary map of points whichhave not been classified as non-ground to output vector map containing ground points
    grass.run_command("g.rename",
                      vector=nc_points + "," + g_output,
                      quiet=True,
                      stderr=nuldev)
示例#11
0
def computeSunShade(n, h, d, insolname, project):
    strDay = str(d).zfill(3) + "/"
    strHour = str(h).zfill(2) + "/"

    ##fill null values
    #r.null map=insolMONTH_0_DAY_2_HOUR_13_MINUTES_40 null=-1
    grass.run_command("r.null", map=insolname, null=-1)

    ##reclass sun to null and shade to 1
    # r.mapcalc expression='shade = if(insolMONTH_0_DAY_2_HOUR_13_MINUTES_40 == -1,1,null())' --o
    grass.run_command("r.mapcalc",
                      expression='shade = if(' + insolname +
                      ' == -1,1 ,null() )',
                      overwrite=True)

    ##set shade color map
    #r.colors map=shade rules=python/colorrules
    grass.run_command("r.colors", map="shade", rules="python/libs/colorrules")

    ##export to png

    ##pokud je dopoledne secist
    #pokud je poledne vyexportovat a vymazat
    #secist
    #r.mapcalc expression='shadeCumulation = shadeCumulation + shade' --o

    if h == 12 and n == minutes[0]:
        print(1111666668888)
        exportShadeCumulation(project, d, h)
        grass.run_command("r.mapcalc",
                          expression="shadeCumulation = 0",
                          overwrite=True)

    grass.run_command(
        "r.mapcalc",
        expression=
        "shadeCumulation = if(isnull(shade),shadeCumulation,shadeCumulation+shade)",
        overwrite=True)
    #grass.run_command("r.mapcalc",expression="shadeCumulation = if(shadeCumulation)",overwrite=True)
    #grass.run_command("r.info",map='shadeCumulation')
    print("cumul:")
    grass.run_command("r.stats", input='shadeCumulation', flags="c")
    print("shade:")
    grass.run_command("r.stats", input='shade', flags="c")

    shadePath = project + "/shade/" + strDay + strHour + minutesIndex[
        minutes.index(str(n))]
    #grass.run_command("r.out.gdal",flags="cf",input="shade", output = shadePath + '.tiff', type="Byte",createopt="COMPRESS=DEFLATE,PREDICTOR=2,ZLEVEL=9",overwrite=True)

    #grass.run_command("g.region",region="resortExtent")
    grass.run_command("g.region",
                      n=grass.vector_info('inputJSONextentMask').north,
                      s=grass.vector_info('inputJSONextentMask').south,
                      w=grass.vector_info('inputJSONextentMask').west,
                      e=grass.vector_info('inputJSONextentMask').east)

    grass.run_command("r.out.png",
                      flags="t",
                      input="shade",
                      output=project + "/shade/" + strDay + strHour +
                      minutesIndex[minutes.index(str(n))] + '.png',
                      overwrite=True)
    #gdal_translate -ot Byte -of PNG C:\Users\Loukotka\Dropbox\ESA-2014\vojta\40.tiff C:/Users/Loukotka/Dropbox/ESA-2014/vojta/40png.png
    #gdal_translate -ot "Byte" -of "PNG" spindl3/shade/003/12/10.tiff spindl3/shade/003/12/10.png

    grass.run_command("g.region", rast='inputDEMraster', overwrite=True)
示例#12
0
def getStations(resourcedir='mySWIM',**datakwargs):
    ####### STATIONS ################################################    
    stationsinfo = grass.vector_info(options['stationsvect'])

    # get stations table    
    try: stationstbl = grass.vector_db_select(options['stationsvect'])
    except: grass.fatal('Cant read the attribute table of %s, has it got one?' %options['stationsvect'])
    # make pandas df
    stationstbl = pa.DataFrame(stationstbl['values'].values(),columns=stationstbl['columns'])

    # check if it finds the stationidcolumn
    if len(options['stationidcolumn'])>0:
        if options['stationidcolumn'] not in stationstbl:
            grass.fatal('Cant find stationidcolumn %s' %options['stationidcolumn'])
        idcol = stationstbl[options['stationidcolumn']]
    elif 'stationID' in stationstbl:
        gm('Found stationID column in the subbasinsvect table.')
        idcol = stationstbl['stationID']
    else:
        ### stationID DESIGN #################################################
        gm('''Will use the order of stations in the stationvect as stationIDs and will assign these stationIDs:''')
        idcol = ['s%s' %s for s in range(1,len(stationstbl)+1)]
        gm(idcol)
        # make subbasinID column and upload them
        grun('v.db.addcolumn',map=options['stationsvect'],
                          columns='stationID varchar(5)',quiet=True)
        catcol = stationstbl.icol(1)
        for i,s in enumerate(catcol):
            grun('v.db.update',map=options['stationsvect'], column='stationID',
                 where='%s=%s' %(catcol.name,s), value=idcol[i],quiet=True)
        # make sure the csvdata file is read without header
        datakwargs.update({'names':['time']+idcol,'skiprows':1})
    # set as index
    stationstbl.index = idcol
    stationstbl.index.name='stationID'
    
    # check if it finds the subbasinidcolumn
    if len(options['subbasinidcolumn'])> 0:
        if options['subbasinidcolumn'] not in stationstbl:
            grass.fatal('Cant find subbasinidcolumn %s' %options['subbasinidcolumn'])
        # change name of column to subbasinID
        stationstbl['subbasinID'] = stationstbl[options['subbasinidcolumn']]
        
    elif 'subbasinID' in stationstbl:
        gm('Found subbasinID column in the subbasinsvect table.')
        
    else:
        gm('Will upload subbasinIDs from the subbasins rast to the stationsvect table. Double check them and run the setup again if changed.')
        # first check if in same mapset then stationsvect
        if stationsinfo['mapset'] != grass.gisenv()['MAPSET']:
            grass.warning(' !!! Changing into mapset: %s !!!' %stationsinfo['mapset'])
            grun('g.mapset',mapset=stationsinfo['mapset'],quiet=True)
        grun('v.db.addcolumn',map=options['stationsvect'],
                          columns='subbasinID int',quiet=True)
        grun('v.what.rast',map=options['stationsvect'],
                          raster=options['subbasins'],column='subbasinID',quiet=True)
        subids = grass.vector_db_select(options['stationsvect'],columns='subbasinID')
        stationstbl['subbasinID'] = np.array(subids['values'].values()).flatten()
    # convert subbasinIDs to int
    for i,s in enumerate(stationstbl['subbasinID']):
        try: stationstbl['subbasinID'][i] = int(s)
        except: stationstbl['subbasinID'][i] = np.nan
        
    # report on found subbasinIDs
    gm('Found these subbasinIDs:\n%s' %stationstbl['subbasinID'])
    
    
    # read data
    gm('Attempting to read discharge data. I am expecting a header like this:')
    gm(','.join(['YYYY-MM-DD']+list(idcol)))
    data = pa.read_csv(options['csvdata'],parse_dates=0,index_col=0,**datakwargs)
    data.index.name = 'time'
    # check if read properlyq
    # check if all cats are in csvdata as columns
    for s in stationstbl.index:
        if s not in data:
            grass.warning('Cant find %s in the csvdata table header. This station wont have any data.' %s)
            gm(stationstbl.ix[s].to_string())
            data[s]=np.nan
    # get days per year covered
    peran = (~data.isnull()).astype(int).resample('a','sum')
    peran.index=peran.index.year
    # report
    gm('Overvations found (days per year):')
    for l in peran.to_string().split('\n'): gm(l)
#        # write individual files to resource folder
#        else:
#            path = os.path.join(resourcedir,s+'.pa')
#            sdat = pa.DataFrame({'Q':data[s]})
#            sdat.index.name = 'time'
#            sdat.to_pickle(path)
#            gm('Saved Q data for the station %s to %s in a python.pandas format.' %(s,path))
#            gm(sdat.head().to_string())
#            fpaths += [path]
#    # attach paths to stationstbl
#    stationstbl['data'] = fpaths
            
    # write out table to resourcedir
    path = os.path.join(resourcedir,'observations.csv')
    data.to_csv(path)
    # return as dictionary of stations
    stations = stationstbl.T.to_dict()
    return stations
示例#13
0
    def StartEditing(self, mapLayer):
        """Start editing selected vector map layer.

        :param mapLayer: MapLayer to be edited
        """
        # check if topology is available (skip for hidden - temporary
        # maps, see iclass for details)
        if not mapLayer.IsHidden() and grass.vector_info(
                mapLayer.GetName())['level'] != 2:
            dlg = wx.MessageDialog(
                parent=self.MapWindow,
                message=_(
                    "Topology for vector map <%s> is not available. "
                    "Topology is required by digitizer.\nDo you want to "
                    "rebuild topology (takes some time) and open the vector map "
                    "for editing?") %
                mapLayer.GetName(),
                caption=_("Digitizer error"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
            if dlg.ShowModal() == wx.ID_YES:
                RunCommand('v.build', map=mapLayer.GetName())
            else:
                return

        # deactive layer
        self.Map.ChangeLayerActive(mapLayer, False)

        # clean map canvas
        self.MapWindow.EraseMap()

        # unset background map if needed
        if mapLayer:
            if UserSettings.Get(
                    group='vdigit', key='bgmap', subkey='value',
                    settings_type='internal') == mapLayer.GetName():
                UserSettings.Set(
                    group='vdigit',
                    key='bgmap',
                    subkey='value',
                    value='',
                    settings_type='internal')

            self.parent.SetStatusText(_("Please wait, "
                                        "opening vector map <%s> for editing...") %
                                      mapLayer.GetName(), 0)

        self.MapWindow.pdcVector = wx.PseudoDC()
        self.digit = self.MapWindow.digit = self.digitClass(
            mapwindow=self.MapWindow)

        self.mapLayer = mapLayer
        # open vector map (assume that 'hidden' map layer is temporary vector
        # map)
        if self.digit.OpenMap(
                mapLayer.GetName(),
                tmp=mapLayer.IsHidden()) is None:
            self.mapLayer = None
            self.StopEditing()
            return False

        # check feature type (only for OGR layers)
        self.fType = self.digit.GetFeatureType()
        self.EnableAll()
        self.EnableUndo(False)
        self.EnableRedo(False)

        if self.fType == 'point':
            for tool in (self.addLine, self.addArea, self.moveVertex,
                         self.addVertex, self.removeVertex, self.editLine):
                self.EnableTool(tool, False)
        elif self.fType == 'linestring':
            for tool in (self.addPoint, self.addArea):
                self.EnableTool(tool, False)
        elif self.fType == 'polygon':
            for tool in (self.addPoint, self.addLine):
                self.EnableTool(tool, False)
        elif self.fType:
            GError(
                parent=self,
                message=_(
                    "Unsupported feature type '%(type)s'. Unable to edit "
                    "OGR layer <%(layer)s>.") %
                {'type': self.fType, 'layer': mapLayer.GetName()})
            self.digit.CloseMap()
            self.mapLayer = None
            self.StopEditing()
            return False

        # update toolbar
        if self.combo:
            self.combo.SetValue(mapLayer.GetName())
        if 'map' in self.parent.toolbars:
            self.parent.toolbars['map'].combo.SetValue(_('Vector digitizer'))

        # here was dead code to enable vdigit button in toolbar
        # with if to ignore iclass
        # some signal (DigitizerStarted) can be emitted here

        Debug.msg(
            4, "VDigitToolbar.StartEditing(): layer=%s" %
            mapLayer.GetName())

        # change cursor
        if self.MapWindow.mouse['use'] == 'pointer':
            self.MapWindow.SetNamedCursor('cross')

        if not self.MapWindow.resize:
            self.MapWindow.UpdateMap(render=True)

        # respect opacity
        opacity = mapLayer.GetOpacity()

        if opacity < 1.0:
            alpha = int(opacity * 255)
            self.digit.GetDisplay().UpdateSettings(alpha=alpha)

        # emit signal
        layerTree = self._giface.GetLayerTree()
        if layerTree:
            item = layerTree.FindItemByData('maplayer', self.mapLayer)
        else:
            item = None
        self.editingStarted.emit(
            vectMap=mapLayer.GetName(),
            digit=self.digit, layerItem=item)

        return True
示例#14
0
def main():
    # Import raster and vector
    Module("v.in.ogr", input=opts['test'], layer="test", output="test", overwrite=True)
    info = grass.vector_info("test")
    print("Number of points: %s" % info['points'])
示例#15
0
def setupPro(resourcedir='mySWIM',parfile='mySWIM/myswim.py'):
    '''Set up all files needed for SWIM and mySWIM and write mySWIM resource dirs
    and parameterfile. In this function, grass input arguments are all in options
    without any removal of empty ones ''!
    '''
    # collect parameters in dict
    p = {}
    
    # check if needed params are set
    for e in ['proname','prodir','stationsvect','simf','subbasins','hydrotopes',
              'csvdata']:
        if len(options['proname'])<2: grass.fatal('%s must be set.' %e)
        p[e] = options[e]
    
    # change into prodir as all subsequent paths maybe relative to that
    os.chdir(p['prodir'])

    # check if in same mapset
    stationsinfo = grass.vector_info(options['stationsvect'])
    if stationsinfo['mapset']!=grass.gisenv()['MAPSET']:
        grass.fatal('Must be in same mapset as %s.' %(options['stationsvect']))
  
    # find files in prodir
    ffiles = {'bsn':'.bsn','cod':'.cod','strf':'.str'}
    ffiles = dict([(e,options['proname']+ffiles[e]) for e in ffiles])
    foundf = findFiles(ffiles,findin=p['prodir'])
    # add to pro
    p.update(foundf)
    
    ### check for other swim files
    swimfiles = {'swim':'swim',
                 'soilcio':'soil.cio',
                 'filecio':'file.cio',
                 'figf':p['proname']+'.fig',
                 'runoff':'runoff.dat',
                 'simf':'rvaddQ_subbasin.prn',
                 'conf':'swim.conf',
                 'clim1':'clim1.dat',
                 'clim2':'clim2.dat',
                 'cntab':'cntab.dat',
                 'cropd':'crop.dat',
                 'subcatchf':'subcatch.def',
                 'subcatchbsn':'subcatch.bsn',
                 'wgen':'wgen.dat',
                 'wstor':'wstor.dat'}
    # check for files with warning if not exists
    swimfiles = findFiles(swimfiles,findin=p['prodir'],fatal=False)
    p.update(swimfiles) # only those that were found and not double    
    
    # simf
    p['simf']=options['simf']
    if len(options['simf'])>0 or os.path.exists(options['simf']):
        grass.warning('Simulated discharge file %s not found or not given.' %options['simf'])
    
    # check if mySWIM already exists and if not create dir
    resourcedirs = {'resourcedir':os.path.join(p['prodir'],resourcedir)}
    for n,d in [('Qdir','Q_files'),('clusterdir','lljobs'),('pestdir','pest')]:
        resourcedirs[n] = os.path.join(resourcedir,d)
    for n,d in resourcedirs.items():
        if os.path.exists(d):
            gm('Found the resource dir in: %s' %d)
        else:
            gm('Creating new resource dir in: %s' %d)
            os.makedirs(d)
    # attach to p
    p.update(resourcedirs)
    
    # climate dir
    p['climatedir'] = options['climatedir']
    
    # pest parameters
    p['pestdir'] = os.path.join(resourcedir,'pest')
    p['pestexe'] = os.path.join(resourcedir,'pest/pest')
    p['pestinstructions'] = options['pestinstructions']
    
    # get parameters from bsn file
    try: par,tmplt = swim.readBsnf(p['bsn'])
    except:
        grass.fatal('''Cant read the bsn file properly. Is it formatted like this:\n
        switch parameters
        value  param
        value  param
        ...
        _______________________________________________________________________
        basin, initialisation & calibration parameters
        param  param ... param description blabla
        value  value ... value
        ...
        _______________________________________________________________________
        CO2 EFFECT ON NET PHOTOSYNTHESIS (alpha) & TRANSPIRATION (beta)
        (ialpha,ibeta) = (1,0) OR (1,1) ONLY FOR SCENARIO PERIODS!
        ialpha    ibeta     C3C4crop  CO2-ref   CO2-scen
        0/1       0/1       3/4       346       406-436   OPTIONS & RANGES
        0         0         0         0         0
        _______________________________________________________________________''')
        
    gm('Found these parameters in the bsn file: %s' %','.join(par.keys()))
    gm('Those parameters will be saved in the future!')
    # make parameter save formats
    pfmts = [(e,{True:'14.3f',False:'7.4f'}[par[e]>50]) for e in sorted(par.keys())]
    
    # check if resource files exists and if not create them
    rfiles = {'runsf': [('runID','04i'),('paramID','04i'),('climID','04i'),
                        ('runTIME','26s'),('station','5s'),('NSE','+7.3f'),
                        ('bias','+6.1f'),('start','10s'),('end','10s'),
                        ('purpose','-12s'),('notes','-64s')],
              'paramf': [('paramID','04i')]+pfmts,
              'climsf': [('climID','04i'), ('title','50s'),
                         ('start','10s'), ('end','10s'), ('notes','-64s')]}
    for f in rfiles:
        name = os.path.join(resourcedir,'%s.%s' %(p['proname'],f[:-1]))
        # exists?
        if os.path.exists(name):
            gm('%s file exists in: %s' %(f,name))
            p[f] = name
        else: # create
            writeTxtDB(name,rfiles[f])
            p[f] = name
        # add sqlite tables to same database as self.stations
        tblname = f[:-1]
        sqlTbl(tblname,rfiles[f])
    
    # save sqlitedb
    p['sqlitedb'] = grass.vector_db(options['stationsvect'])[1]['database']
    
    # get stations info and data
    p['stations'] = getStations(resourcedir=resourcedir)
    p['obsf']     = os.path.join(resourcedir,'observations.csv')
    
    # llcmds
    if options['llcmds']!='':
        p['llcmds'] = dict([cmd.split(':') for cmd in options['llcmds'].split(',')])
    
    # write all in p to a parameter file
    parfpath = os.path.join(resourcedir,'myswim.py')
    if os.path.exists(parfpath):
        pars = imp.load_source('myswim',parfpath)
        opars= {e:pars.__getattribute__(e) for e in dir(pars) if e not in p and not e.startswith('__')}
        gm('Previous myswim parameter file found! Preserved these parameter: %r' %opars)
        p.update(opars)
    # now write 
    parf = file(parfpath,'w')
    parf.write('### mySWIM parameter file, saved on: %s\n' %dt.datetime.now())
    for e in sorted(p.keys()): parf.write('%s=%r\n' %(e,p[e]))
    
    gm('All set up! To proceed, uncheck the -0 flag and change into %s' %p['prodir'])
    return
#!/usr/bin/env python

import os
import grass.script as gscript

# set computational region beforehand
grid = 'grid'
       
gscript.run_command('v.mkgrid', type='point', map=grid, overwrite=True)
print gscript.vector_info(grid)['points']
gscript.run_command('v.out.ascii', input=grid, sep='comma', output='grid.txt', overwrite=True)

template = 'grass72 -c grassdata/sonoita/{mapset} --exec python scripts/single_viewshed.py output={out} coord={x},{y} --o && rm -r grassdata/sonoita/{mapset}\n'

with open("grid.txt") as f:
    with open("jobs.txt", "w") as f1:
        for line in f:
            x, y, cat = line.strip().split(',')
            f1.write(template.format(mapset='temp_' + cat, x=x, y=y, out='out_' + cat + '.txt')) 
示例#17
0
def main():
    vmap = options['map']
    curr_mapset = grass.gisenv()['MAPSET']
    mapset = grass.find_file(name = vmap,
                             element = 'vector')['mapset']

    # check if map exists in the current mapset
    if not mapset:
        grass.fatal(_("Vector map <%s> not found") % vmap)
    if mapset != curr_mapset:
        grass.fatal(_("Vector map <%s> not found in the current mapset") % vmap)

    # check for format
    vInfo = grass.vector_info(vmap)
    if vInfo['format'] != 'PostGIS,PostgreSQL':
        grass.fatal(_("Vector map <%s> is not a PG-link") % vmap)

    # default connection
    global pg_conn
    pg_conn = {'driver': 'pg',
                'database': vInfo['pg_dbname']}

    # default topo schema
    if not options['topo_schema']:
        options['topo_schema'] = 'topo_%s' % options['map']

    # check if topology schema already exists
    topo_found = False
    ret = grass.db_select(sql = "SELECT COUNT(*) FROM topology.topology "
                              "WHERE name = '%s'" % options['topo_schema'],
                          **pg_conn)

    if not ret or int(ret[0][0]) == 1:
        topo_found = True

    if topo_found:
        if int(os.getenv('GRASS_OVERWRITE', '0')) == 1:
            # -> overwrite
            grass.warning(_("Topology schema <%s> already exists and will be overwritten") %
                              options['topo_schema'])
        else:
            grass.fatal(_("option <%s>: <%s> exists.") %
                            ('topo_schema', options['topo_schema']))

        # drop topo schema if exists
        execute(sql = "SELECT topology.DropTopology('%s')" % options['topo_schema'],
                msg = _("Unable to remove topology schema"))

    # create topo schema
    schema, table = vInfo['pg_table'].split('.')
    grass.message(_("Creating new topology schema..."))
    execute("SELECT topology.createtopology('%s', find_srid('%s', '%s', '%s'), %s)" %
                (options['topo_schema'], schema, table, vInfo['geometry_column'], options['tolerance']))

    # add topo column to the feature table
    grass.message(_("Adding new topology column..."))
    execute("SELECT topology.AddTopoGeometryColumn('%s', '%s', '%s', '%s', '%s')" %
                (options['topo_schema'], schema, table, options['topo_column'], vInfo['feature_type']))

    # build topology
    grass.message(_("Building PostGIS topology..."))
    execute("UPDATE %s.%s SET %s = topology.toTopoGeom(%s, '%s', 1, %s)" %
                (schema, table, options['topo_column'], vInfo['geometry_column'],
                 options['topo_schema'], options['tolerance']),
            useSelect = False)

    # report summary
    execute("SELECT topology.TopologySummary('%s')" % options['topo_schema'])

    return 0
示例#18
0
def main():
    vmap = options["map"]
    curr_mapset = grass.gisenv()["MAPSET"]
    mapset = grass.find_file(name=vmap, element="vector")["mapset"]

    # check if map exists in the current mapset
    if not mapset:
        grass.fatal(_("Vector map <%s> not found") % vmap)
    if mapset != curr_mapset:
        grass.fatal(_("Vector map <%s> not found in the current mapset") % vmap)

    # check for format
    vInfo = grass.vector_info(vmap)
    if vInfo["format"] != "PostGIS,PostgreSQL":
        grass.fatal(_("Vector map <%s> is not a PG-link") % vmap)

    # default connection
    global pg_conn
    pg_conn = {"driver": "pg", "database": vInfo["pg_dbname"]}

    # default topo schema
    if not options["topo_schema"]:
        options["topo_schema"] = "topo_%s" % options["map"]

    # check if topology schema already exists
    topo_found = False
    ret = grass.db_select(
        sql="SELECT COUNT(*) FROM topology.topology "
        "WHERE name = '%s'" % options["topo_schema"],
        **pg_conn
    )

    if not ret or int(ret[0][0]) == 1:
        topo_found = True

    if topo_found:
        if int(os.getenv("GRASS_OVERWRITE", "0")) == 1:
            # -> overwrite
            grass.warning(
                _("Topology schema <%s> already exists and will be overwritten")
                % options["topo_schema"]
            )
        else:
            grass.fatal(
                _("option <%s>: <%s> exists.") % ("topo_schema", options["topo_schema"])
            )

        # drop topo schema if exists
        execute(
            sql="SELECT topology.DropTopology('%s')" % options["topo_schema"],
            msg=_("Unable to remove topology schema"),
        )

    # create topo schema
    schema, table = vInfo["pg_table"].split(".")
    grass.message(_("Creating new topology schema..."))
    execute(
        "SELECT topology.createtopology('%s', find_srid('%s', '%s', '%s'), %s)"
        % (
            options["topo_schema"],
            schema,
            table,
            vInfo["geometry_column"],
            options["tolerance"],
        )
    )

    # add topo column to the feature table
    grass.message(_("Adding new topology column..."))
    execute(
        "SELECT topology.AddTopoGeometryColumn('%s', '%s', '%s', '%s', '%s')"
        % (
            options["topo_schema"],
            schema,
            table,
            options["topo_column"],
            vInfo["feature_type"],
        )
    )

    # build topology
    grass.message(_("Building PostGIS topology..."))
    execute(
        "UPDATE %s.%s SET %s = topology.toTopoGeom(%s, '%s', 1, %s)"
        % (
            schema,
            table,
            options["topo_column"],
            vInfo["geometry_column"],
            options["topo_schema"],
            options["tolerance"],
        ),
        useSelect=False,
    )

    # report summary
    execute("SELECT topology.TopologySummary('%s')" % options["topo_schema"])

    return 0
示例#19
0
def main():
    # Get the options
    input = options["input"]
    input_name = input.split("@")[0]
    output = options["output"]
    method = options["method"]
    min_cat = None
    max_cat = None
    point = None
    overwrite = grass.overwrite()

    quiet = True

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

    in_info = grass.vector_info(input)
    # check for wild mixture of vector types
    if in_info["points"] > 0 and in_info["boundaries"] > 0:
        grass.fatal(_("The input vector map contains both polygons and points," " cannot handle mixed types"))

    pid = os.getpid()
    # process points via triangulation, then exit
    if in_info["points"] > 0:
        point = True
        layer = 1  # hardcoded for now
        out_temp = "{inp}_point_tmp_{pid}".format(inp=input_name, pid=pid)
        if method == "delaunay":
            grass.message(_("Processing point data (%d points found)...") % in_info["points"])
            grass.run_command("v.delaunay", input=input, layer=layer, output=out_temp, quiet=quiet)

        grass.run_command("v.db.addtable", map=out_temp, quiet=True)
        input = out_temp
        in_info = grass.vector_info(input)

    # process areas
    if in_info["areas"] == 0 and in_info["boundaries"] == 0:
        grass.fatal(_("The input vector map does not contain polygons"))

    out_type = "{inp}_type_{pid}".format(inp=input_name, pid=pid)
    input_tmp = "{inp}_tmp_{pid}".format(inp=input_name, pid=pid)
    remove_names = "%s,%s" % (out_type, input_tmp)
    grass.message(_("Processing area data (%d areas found)...") % in_info["areas"])

    try:
        grass.run_command(
            "v.category", layer="2", type="boundary", option="add", input=input, out=input_tmp, quiet=quiet
        )
    except CalledModuleError:
        grass.run_command("g.remove", flags="f", type="vector", name=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating layer 2"))
    try:
        grass.run_command("v.db.addtable", map=input_tmp, layer="2", columns="left integer,right integer", quiet=quiet)
    except CalledModuleError:
        grass.run_command("g.remove", flags="f", type="vector", name=input_tmp, quiet=quiet)
        grass.fatal(_("Error creating new table for layer 2"))
    try:
        grass.run_command("v.to.db", map=input_tmp, option="sides", columns="left,right", layer="2", quiet=quiet)
    except CalledModuleError:
        grass.run_command("g.remove", flags="f", type="vector", name=input_tmp, quiet=quiet)
        grass.fatal(_("Error populating new table for layer 2"))
    try:
        grass.run_command(
            "v.type", input=input_tmp, output=out_type, from_type="boundary", to_type="line", quiet=quiet, layer="2"
        )
    except CalledModuleError:
        grass.run_command("g.remove", flags="f", type="vector", name=remove_names, quiet=quiet)
        grass.fatal(_("Error converting polygon to line"))
    report = grass.read_command("v.category", flags="g", input=out_type, option="report", quiet=quiet).split("\n")
    for r in report:
        if r.find("centroid") != -1:
            min_cat = report[0].split()[-2]
            max_cat = report[0].split()[-1]
            break
    if min_cat and max_cat:
        try:
            grass.run_command(
                "v.edit",
                map=out_type,
                tool="delete",
                type="centroid",
                layer=2,
                quiet=quiet,
                cats="{mi}-{ma}".format(mi=min_cat, ma=max_cat),
            )
        except CalledModuleError:
            grass.run_command("g.remove", flags="f", type="vector", name=remove_names, quiet=quiet)
            grass.fatal(_("Error removing centroids"))

    try:
        try:
            # TODO: fix magic numbers for layer here and there
            grass.run_command("v.db.droptable", map=out_type, layer=1, flags="f", quiet=True)
        except CalledModuleError:
            grass.run_command("g.remove", flags="f", type="vector", name=remove_names, quiet=quiet)
            grass.fatal(_("Error removing table from layer 1"))
    # TODO: when this except is happaning, it seems that never, so it seems wrong
    except:
        grass.warning(_("No table for layer %d" % 1))
    try:
        grass.run_command(
            "v.category",
            input=out_type,
            option="transfer",
            output=output,
            layer="2,1",
            quiet=quiet,
            overwrite=overwrite,
        )
    except CalledModuleError:
        grass.run_command("g.remove", flags="f", type="vector", name=remove_names, quiet=quiet)
        grass.fatal(_("Error adding categories"))
    grass.run_command("g.remove", flags="f", type="vector", name=remove_names, quiet=quiet)
    if point:
        grass.run_command("g.remove", flags="f", type="vector", name=out_temp, quiet=quiet)