Exemple #1
0
def GetListOfMapsets(dbase, location, selectable=False):
    """Get list of mapsets in given GRASS location

    :param dbase: GRASS database path
    :param location: GRASS location
    :param selectable: True to get list of selectable mapsets, otherwise all

    :return: list of mapsets - sorted (PERMANENT first)
    """
    listOfMapsets = list()

    if selectable:
        ret = RunCommand('g.mapset',
                         read=True,
                         flags='l',
                         location=location,
                         dbase=dbase)

        if not ret:
            return listOfMapsets

        for line in ret.rstrip().splitlines():
            listOfMapsets += line.split(' ')
    else:
        for mapset in glob.glob(os.path.join(dbase, location, "*")):
            if os.path.isdir(mapset) and os.path.isfile(
                    os.path.join(dbase, location, mapset, "WIND")):
                listOfMapsets.append(os.path.basename(mapset))

    ListSortLower(listOfMapsets)
    return listOfMapsets
Exemple #2
0
    def OnConnect(self, event):
        """!Button 'Connect' pressed"""
        # 'r.in.wms -l' output changes depending on the parser used.
        # the parsing below depends on the cleaner `xml2` version.
        if not find_program('xml2'):
            GError(_("The 'xml2' parser is required, please install it "
                     "first. You may also try running r.in.wms directly "
                     "from the command line."))
            return

        server = self.server.GetValue()
        if not server:
            self.btn_import.Enable(False)
            return # not reachable

        layers = {}
        ret = RunCommand('r.in.wms',
                         quiet = True,
                         parent = self,
                         read = True,
                         flags = 'l',
                         mapserver = server)
        
        if not ret:
            self.list.LoadData()
            self.btn_import.Enable(False)
            return # no layers found
        
        lastLayer = lastStyle = ''
        for line in ret.splitlines():
            try:
                key, value = line.split(':', 1)
            except ValueError:
                continue
            key = key.strip().lower()
            value = value.strip()
            
            if key == 'layer':
                layers[value] = {}
                lastLayer = value
            elif key == 'title':
                if lastLayer and 'title' not in layers[lastLayer]:
                    layers[lastLayer][key] = value.decode('utf8')
            elif key == 'style':
                if lastLayer:
                    if 'style' not in layers[lastLayer]:
                        layers[lastLayer]['style'] = {}
                    layers[lastLayer]['style'][value] = ''
                    lastStyle = value
            elif key == 'style title':
                if lastLayer:
                    layers[lastLayer]['style'][lastStyle] = value

        # update list of layers
        self.list.LoadData(layers)
        
        if len(layers.keys()) > 0:
            self.btn_import.Enable(True)
        else:
            self.btn_import.Enable(False)
Exemple #3
0
    def _projInfo(self):
        """Return region projection and map units information
        """
        projinfo = dict()
        if not grass.find_program('g.proj', '--help'):
            sys.exit(_("GRASS module '%s' not found. Unable to start map "
                       "display window.") % 'g.proj')
        env = os.environ.copy()
        if self.gisrc:
            env['GISRC'] = self.gisrc
        ret = RunCommand(prog='g.proj', read=True, flags='p', env=env)

        if not ret:
            return projinfo

        for line in ret.splitlines():
            if ':' in line:
                key, val = map(lambda x: x.strip(), line.split(':'))
                if key in ['units']:
                    val = val.lower()
                projinfo[key] = val
            elif "XY location (unprojected)" in line:
                projinfo['proj'] = 'xy'
                projinfo['units'] = ''
                break

        return projinfo
Exemple #4
0
def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
    """Reproject coordinates

    :param coord: coordinates given as tuple
    :param projOut: output projection
    :param projIn: input projection (use location projection settings)

    :return: reprojected coordinates (returned as tuple)
    """
    coors = RunCommand('m.proj',
                       flags=flags,
                       input='-',
                       proj_in=projIn,
                       proj_out=projOut,
                       sep=';',
                       stdin='%f;%f' % (coord[0], coord[1]),
                       read=True)
    if coors:
        coors = coors.split(';')
        e = coors[0]
        n = coors[1]
        try:
            proj = projOut.split(' ')[0].split('=')[1]
        except IndexError:
            proj = ''
        if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
            return (proj, (e, n))
        else:
            try:
                return (proj, (float(e), float(n)))
            except ValueError:
                return (None, None)

    return (None, None)
 def OnUninstall(self, event):
     """Uninstall selected extensions"""
     eList = self._getSelectedExtensions()
     if not eList:
         return
     
     for ext in eList:
         files = RunCommand('g.extension', parent = self, read = True, quiet = True,
                            extension = ext, operation = 'remove').splitlines()
         if len(files) > 10:
             files = files[:10]
             files.append('...')
         dlg = wx.MessageDialog(parent = self,
                                message = _("List of files to be removed:\n%(files)s\n\n"
                                            "Do you want really to remove <%(ext)s> extension?") % \
                                    { 'files' : os.linesep.join(files), 'ext' : ext },
                                caption = _("Remove extension"),
                                style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
         
         if dlg.ShowModal() ==  wx.ID_YES:
             RunCommand('g.extension', flags = 'f', parent = self, quiet = True,
                        extension = ext, operation = 'remove')
     
     self.extList.LoadData()
     
     # update prompt
     globalvar.UpdateGRASSAddOnCommands(eList)
     toolboxesOutdated()
Exemple #6
0
    def _getCategories(self, coords, qdist):
        """Get layer/category pairs for all available
        layers

        :return: True line found or False if not found
        """
        ret = RunCommand('v.what',
                         parent = self,
                         quiet = True,
                         map = self.vectorName,
                         east_north = '%f,%f' % \
                             (float(coords[0]), float(coords[1])),
                         distance = qdist)

        if not ret:
            return False

        for item in ret.splitlines():
            litem = item.lower()
            if "id:" in litem: # get line id
                self.line = int(item.split(':')[1].strip())
            elif "layer:" in litem: # add layer
                layer = int(item.split(':')[1].strip())
                if layer not in self.cats.keys():
                    self.cats[layer] = []
            elif "category:" in litem: # add category
                self.cats[layer].append(int(item.split(':')[1].strip()))

        return True
Exemple #7
0
def GetTempfile(pref=None):
    """Creates GRASS temporary file using defined prefix.

    .. todo::
        Fix path on MS Windows/MSYS

    :param pref: prefer the given path

    :return: Path to file name (string) or None
    """
    ret = RunCommand('g.tempfile',
                     read=True,
                     pid=os.getpid())

    tempfile = ret.splitlines()[0].strip()

    # FIXME
    # ugly hack for MSYS (MS Windows)
    if platform.system() == 'Windows':
        tempfile = tempfile.replace("/", "\\")
    try:
        path, file = os.path.split(tempfile)
        if pref:
            return os.path.join(pref, file)
        else:
            return tempfile
    except:
        return None
Exemple #8
0
    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        self.commandId = -1
        data = self.list.GetLayers()

        data = self._getLayersToReprojetion(2, 3)

        if data is None:
            return

        if not data:
            GMessage(_("No layers selected. Operation canceled."),
                     parent=self)
            return

        dsn = self.dsnInput.GetDsn()
        ext = self.dsnInput.GetFormatExt()

        for layer, output, listId in data:
            userData = {}

            if self.dsnInput.GetType() == 'dir':
                idsn = os.path.join(dsn, layer)
            else:
                idsn = dsn

            # check number of bands
            nBandsStr = RunCommand('r.in.gdal',
                                   flags='p',
                                   input=idsn, read=True)
            nBands = -1
            if nBandsStr:
                try:
                    nBands = int(nBandsStr.rstrip('\n'))
                except:
                    pass
            if nBands < 0:
                GWarning(_("Unable to determine number of raster bands"),
                         parent=self)
            nBands = 1

            userData['nbands'] = nBands
            cmd = self.getSettingsPageCmd()
            cmd.append('input=%s' % dsn)
            cmd.append('output=%s' % output)

            if self.overwrite.IsChecked():
                cmd.append('--overwrite')

            if UserSettings.Get(group='cmd', key='overwrite',
                                subkey='enabled') and '--overwrite' not in cmd:
                cmd.append('--overwrite')

            # run in Layer Manager
            self._giface.RunCmd(
                cmd,
                onDone=self.OnCmdDone,
                userData=userData,
                addLayer=False)
Exemple #9
0
def GetColorTables():
    """Get list of color tables"""
    ret = RunCommand('r.colors',
                     read=True,
                     flags='l')
    if not ret:
        return list()

    return ret.splitlines()
Exemple #10
0
    def GroupSet(self, group, subgroup):
        kwargs = {}
        if subgroup:
            kwargs['subgroup'] = subgroup

        res = RunCommand('i.group',
                         flags='g',
                         group=group,
                         read=True, **kwargs).strip()

        if res.splitlines()[0]:
            bands = res.splitlines()
            self.scatt_mgr.SetBands(bands)
Exemple #11
0
    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.scattertype == "bubble":
            freqflag = "cn"
        else:
            freqflag = "n"

        try:
            ret = RunCommand(
                "r.stats",
                parent=self,
                input="%s,%s" % rpair,
                flags=freqflag,
                nsteps=self.bins,
                sep=",",
                quiet=True,
                read=True,
            )

            if not ret:
                return datalist

            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(",")
                rast1 = rast1.strip()
                if "-" in rast1:
                    if rast1[0] == "-":
                        rast1 = "-" + rast1.split("-")[1]
                    else:
                        rast1 = rast1.split("-")[0]

                rast2 = rast2.strip()
                if "-" in rast2:
                    if rast2[0] == "-":
                        rast2 = "-" + rast2.split("-")[1]
                    else:
                        rast2 = rast2.split("-")[0]

                rast1 = rast1.encode("ascii", "ignore")
                rast2 = rast2.encode("ascii", "ignore")

                datalist.append((rast1, rast2))

            return datalist
        except GException as e:
            GError(parent=self, message=e.value)
            return None
Exemple #12
0
    def CreateDatalist(self, rpair):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []
        
        if self.scattertype == 'bubble': 
            freqflag = 'cn'
        else:
            freqflag = 'n'
                
        try:
            ret = RunCommand("r.stats",
                             parent = self,
                             input = '%s,%s' % rpair,
                             flags = freqflag,
                             nsteps = self.bins,
                             sep = ',',
                             quiet = True,
                             read = True)
            
            if not ret:
                return datalist
            
            for line in ret.splitlines():
                rast1, rast2 = line.strip().split(',')
                rast1 = rast1.strip()
                if '-' in rast1:
                    if rast1[0] == '-':
                        rast1 = '-' + rast1.split('-')[1]
                    else:
                        rast1 = rast1.split('-')[0]

                rast2 = rast2.strip()
                if '-' in rast2:
                    if rast2[0] == '-':
                        rast2 = '-' + rast2.split('-')[1]
                    else:
                        rast2 = rast2.split('-')[0]
                
                rast1 = rast1.encode('ascii', 'ignore')
                rast2 = rast2.encode('ascii', 'ignore')
                    
                datalist.append((rast1,rast2))

            return datalist
        except GException as e:
            GError(parent = self,
                   message = e.value)
            return None
Exemple #13
0
    def GetGroupBands(self, group, subgroup):
        """Get list of raster bands which are in the soubgroup of group with both having same name."""

        kwargs = {}
        if subgroup:
            kwargs['subgroup'] = subgroup

        res = RunCommand('i.group',
                         flags='g',
                         group=group,
                         read = True, **kwargs).strip()
        bands = None
        if res.split('\n')[0]:
            bands = res.split('\n')
            
        return bands
Exemple #14
0
    def CreateDatalist(self, raster):
        """Build a list of cell value, frequency pairs for histogram
            frequency can be in cell counts, percents, or area
        """
        datalist = []

        if self.histtype == 'count':
            freqflag = 'cn'
        if self.histtype == 'percent':
            freqflag = 'pn'
        if self.histtype == 'area':
            freqflag = 'an'

        try:
            ret = RunCommand("r.stats",
                             parent=self,
                             input=raster,
                             flags=freqflag,
                             nsteps=self.bins,
                             sep=',',
                             quiet=True,
                             read=True)

            if not ret:
                return datalist

            for line in ret.splitlines():
                cellval, histval = line.strip().split(',')
                histval = histval.strip()
                if self.raster[raster]['datatype'] != 'CELL':
                    if cellval[0] == '-':
                        cellval = '-' + cellval.split('-')[1]
                    else:
                        cellval = cellval.split('-')[0]

                if self.histtype == 'percent':
                    histval = histval.rstrip('%')

                datalist.append((cellval, histval))

            return datalist
        except GException as e:
            GError(parent=self,
                   message=e.value)
            return None
Exemple #15
0
 def UpdateMapsets(self, location):
     """Update list of mapsets"""
     self.FormerMapsetSelection = wx.NOT_FOUND # for non-selectable item
     
     self.listOfMapsetsSelectable = list()
     self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)
     
     self.lbmapsets.Clear()
     
     # disable mapset with denied permission
     locationName = os.path.basename(location)
     
     ret = RunCommand('g.mapset',
                      read = True,
                      flags = 'l',
                      location = locationName,
                      gisdbase = self.gisdbase)
         
     if ret:
         for line in ret.splitlines():
             self.listOfMapsetsSelectable += line.split(' ')
     else:
         RunCommand("g.gisenv",
                    set = "GISDBASE=%s" % self.gisdbase)
         RunCommand("g.gisenv",
                    set = "LOCATION_NAME=%s" % locationName)
         RunCommand("g.gisenv",
                    set = "MAPSET=PERMANENT")
         # first run only
         self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)
     
     disabled = []
     idx = 0
     for mapset in self.listOfMapsets:
         if mapset not in self.listOfMapsetsSelectable or \
                 os.path.isfile(os.path.join(self.gisdbase,
                                             locationName,
                                             mapset, ".gislock")):
             disabled.append(idx)
         idx +=  1
     
     self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled = disabled)
     
     return self.listOfMapsets
 def OnConnect(self, event):
     """!Connect to the server"""
     server = self.server.GetValue()
     if not server:
         self.btn_import.Enable(False)
         return # not reachable
     
     layers = {}
     ret = RunCommand('r.in.wms2',
                      quiet = True,
                      parent = self,
                      wms_version = "1.3.0",
                      read = True,
                      flags = 'c',
                      mapserver = server)
     
     temp_file = grass.tempfile()
     if temp_file is None:
         grass.fatal(_("Unable to create temporary files"))##TOFO
     
     temp = open(temp_file, "w")
     temp.write(ret.encode('utf-8'))#TODO
     temp.close()
     
     if not ret:
         self.list.LoadData()
         self.btn_import.Enable(False)
         return # no layers found
     
     try:
        self.cap = WMSCapabilities(temp_file)
     except GException as error:
         GError(error, parent = self)
     
     # update list of layers
     self.list.LoadData(self.cap)
     
     if len(layers.keys()) > 0:
         self.btn_import.Enable(True)
     else:
         self.btn_import.Enable(False)
Exemple #17
0
def ListOfMapsets(get='ordered'):
    """Get list of available/accessible mapsets

    :param str get: method ('all', 'accessible', 'ordered')

    :return: list of mapsets
    :return: None on error
    """
    mapsets = []

    if get == 'all' or get == 'ordered':
        ret = RunCommand('g.mapsets',
                         read=True,
                         quiet=True,
                         flags='l',
                         sep='newline')

        if ret:
            mapsets = ret.splitlines()
            ListSortLower(mapsets)
        else:
            return None

    if get == 'accessible' or get == 'ordered':
        ret = RunCommand('g.mapsets',
                         read=True,
                         quiet=True,
                         flags='p',
                         sep='newline')
        if ret:
            if get == 'accessible':
                mapsets = ret.splitlines()
            else:
                mapsets_accessible = ret.splitlines()
                for mapset in mapsets_accessible:
                    mapsets.remove(mapset)
                mapsets = mapsets_accessible + mapsets
        else:
            return None

    return mapsets
Exemple #18
0
    def SelectFromTable(self, layer, cols = '*', where = None):
        """Select records from the table

        Return number of selected records, -1 on error
        """
        if layer <= 0:
            return -1

        nselected = 0

        table = self.layers[layer]["table"] # get table desc
        # select values (only one record)
        if where is None or where is '':
            sql = "SELECT %s FROM %s" % (cols, table)
        else:
            sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
        
        ret = RunCommand('db.select',
                         read = True,
                         quiet = True,
                         flags = 'v',
                         sql= sql,
                         database = self.layers[layer]["database"],
                         driver = self.layers[layer]["driver"])
        
        # self.tables[table][key][1] = str(cat)
        if ret:
            for line in ret.splitlines():
                name, value = line.split('|')
                # casting ...
                if value:
                    if self.tables[table][name]['ctype'] != type(''):
                        value = self.tables[table][name]['ctype'] (value)
                    else:
                        value = GetUnicodeValue(value)
                else:
                    value = None
                self.tables[table][name]['values'].append(value)
                nselected = 1

        return nselected
Exemple #19
0
def switch_mapset_interactively(guiparent, giface, dbase, location, mapset):
    """Switch current mapset. Emits giface.currentMapsetChanged signal."""
    if dbase:
        if RunCommand('g.mapset',
                      parent=guiparent,
                      location=location,
                      mapset=mapset,
                      dbase=dbase) == 0:
            GMessage(parent=guiparent,
                     message=_("Current GRASS database is <%(dbase)s>.\n"
                               "Current location is <%(loc)s>.\n"
                               "Current mapset is <%(mapset)s>.") % {
                                   'dbase': dbase,
                                   'loc': location,
                                   'mapset': mapset
                               })
            giface.currentMapsetChanged.emit(dbase=dbase,
                                             location=location,
                                             mapset=mapset)
    elif location:
        if RunCommand('g.mapset',
                      parent=guiparent,
                      location=location,
                      mapset=mapset) == 0:
            GMessage(parent=guiparent,
                     message=_("Current location is <%(loc)s>.\n"
                               "Current mapset is <%(mapset)s>.") % {
                                   'loc': location,
                                   'mapset': mapset
                               })
            giface.currentMapsetChanged.emit(dbase=None,
                                             location=location,
                                             mapset=mapset)
    else:
        if RunCommand('g.mapset', parent=guiparent, mapset=mapset) == 0:
            GMessage(parent=guiparent,
                     message=_("Current mapset is <%s>.") % mapset)
            giface.currentMapsetChanged.emit(dbase=None,
                                             location=None,
                                             mapset=mapset)
Exemple #20
0
    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command('g.region', flags='p',
                                              delimiter=':')
        pname = polyfile.name.split('/')[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
                   rows=region_settings['rows'], overwrite=True)

        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
                   type='area', overwrite=True)

        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
                   value=1, use='val')
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command('g.region', vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
        RunCommand('g.remove', flags='f', type='vector', name=tmpvector)

        os.unlink(polyfile.name)
        return marea
Exemple #21
0
    def OnUninstall(self, event):
        """Uninstall selected extensions"""
        eList = self._getSelectedExtensions()
        if not eList:
            return

        for ext in eList:
            files = RunCommand('g.extension',
                               parent=self,
                               read=True,
                               quiet=True,
                               extension=ext,
                               operation='remove').splitlines()
            if len(files) > 10:
                files = files[:10]
                files.append('...')
            dlg = wx.MessageDialog(
                parent=self,
                message=_(
                    "List of files to be removed:\n%(files)s\n\n"
                    "Do you want really to remove <%(ext)s> extension?") % {
                        'files': os.linesep.join(files),
                        'ext': ext
                    },
                caption=_("Remove extension"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

            if dlg.ShowModal() == wx.ID_YES:
                RunCommand('g.extension',
                           flags='f',
                           parent=self,
                           quiet=True,
                           extension=ext,
                           operation='remove')

        self.extList.LoadData()

        # update prompt
        globalvar.UpdateGRASSAddOnCommands(eList)
        toolboxesOutdated()
Exemple #22
0
    def _geomAttrbUpdate(self, fids):
        """Update geometry atrributes of currently selected features

        :param fid: list feature id
        """
        mapLayer = self.parent.toolbars["vdigit"].GetLayer()
        vectorName = mapLayer.GetName()
        if self.tree:
            item = self.tree.FindItemByData("maplayer", mapLayer)
            vdigit = self.tree.GetLayerInfo(item, key="vdigit")
        else:
            item = vdigit = None

        if not vdigit or "geomAttr" not in vdigit:
            return

        dbInfo = gselect.VectorDBInfo(vectorName)
        sqlfile = tempfile.NamedTemporaryFile(mode="w")
        for fid in fids:
            for layer, cats in six.iteritems(self.digit.GetLineCats(fid)):
                table = dbInfo.GetTable(layer)
                for attrb, item in six.iteritems(vdigit["geomAttr"]):
                    val = -1
                    if attrb == "length":
                        val = self.digit.GetLineLength(fid)
                        type = attrb
                    elif attrb == "area":
                        val = self.digit.GetAreaSize(fid)
                        type = attrb
                    elif attrb == "perimeter":
                        val = self.digit.GetAreaPerimeter(fid)
                        type = "length"

                    if val < 0:
                        continue
                    val = UnitsConvertValue(val, type, item["units"])

                    for cat in cats:
                        sqlfile.write(
                            "UPDATE %s SET %s = %f WHERE %s = %d;\n" % (
                                table,
                                item["column"],
                                val,
                                dbInfo.GetKeyColumn(layer),
                                cat,
                            ))

            sqlfile.file.flush()
            RunCommand("db.execute",
                       parent=True,
                       quiet=True,
                       input=sqlfile.name)
Exemple #23
0
    def OnMCalcRun(self, event):
        """Builds and runs r.mapcalc statement
        """
        name = self.newmaptxt.GetValue().strip()
        if not name:
            GError(parent=self,
                   message=_("You must enter the name of "
                             "a new raster map to create."))
            return

        if not (name[0] == '"' and name[-1] == '"') and any(
            (char in name) for char in self.charactersToQuote):
            name = '"' + name + '"'

        expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
        if not expr:
            GError(parent=self,
                   message=_("You must enter an expression "
                             "to create a new raster map."))
            return

        seed_flag = seed = None
        if re.search(pattern="rand *\(.+\)", string=expr):
            if self.randomSeed.IsChecked():
                seed_flag = '-s'
            else:
                seed = self.randomSeedText.GetValue().strip()
        if self.log:
            cmd = [self.cmd]
            if seed_flag:
                cmd.append('-s')
            if seed:
                cmd.append("seed={val}".format(val=seed))
            if self.overwrite.IsChecked():
                cmd.append('--overwrite')
            cmd.append(str('expression=%s = %s' % (name, expr)))

            self.log.RunCmd(cmd, onDone=self.OnDone)
            self.parent.Raise()
        else:
            if self.overwrite.IsChecked():
                overwrite = True
            else:
                overwrite = False
            params = dict(expression="%s=%s" % (name, expr),
                          overwrite=overwrite)
            if seed_flag:
                params['flags'] = 's'
            if seed:
                params['seed'] = seed

            RunCommand(self.cmd, **params)
Exemple #24
0
    def ComputeStatitistics(self):
        """!Computes statistics for raster map using 'r.univar' module.

        @return statistic in form of dictionary
        """
        # RunCommand enables to run GRASS module
        res = RunCommand(
            'r.univar',  # module name
            flags='g',  # command flags
            map=self.currentRaster,  # module parameters
            read=True)  # get command output

        return gcore.parse_key_val(res, val_type=float)
Exemple #25
0
    def _rasterize(self, grass_region, layer, cat, out_rast):

        # TODO different thread may be problem when user edits map
        environs = os.environ.copy()
        environs['GRASS_VECTOR_TEMPORARY'] = '1'

        ret, text, msg = RunCommand("v.category",
                                    input=self.vectMap,
                                    getErrorMsg=True,
                                    option='report',
                                    read=True,
                                    env=environs)

        ret, text, msg = RunCommand("v.build",
                                    map=self.vectMap,
                                    getErrorMsg=True,
                                    read=True,
                                    env=environs)

        if ret != 0:
            GException(_("v.build failed:\n%s" % msg))

        environs = os.environ.copy()
        environs["GRASS_REGION"] = grass_region["GRASS_REGION"]
        environs['GRASS_VECTOR_TEMPORARY'] = '1'

        ret, text, msg = RunCommand("v.to.rast",
                                    input=self.vectMap,
                                    use="cat",
                                    layer=str(layer),
                                    cat=str(cat),
                                    output=out_rast,
                                    getErrorMsg=True,
                                    read=True,
                                    overwrite=True,
                                    env=environs)

        if ret != 0:
            GException(_("v.to.rast failed:\n%s" % msg))
Exemple #26
0
 def rename(self):
     """Rename layer"""
     if self.selected_layer and self.new_name:
         string = self.old_name + ',' + self.new_name
         self.ChangeEnvironment(self.GetItemText(self.selected_location),
                                self.GetItemText(self.selected_mapset))
         renamed = 0
         label = _("Renaming") + " " + string + " ..."
         self.showNotification.emit(message=label)
         if (self.GetItemText(self.selected_type) == 'vect'):
             renamed = RunCommand('g.rename', vect=string)
         elif (self.GetItemText(self.selected_type) == 'rast'):
             renamed = RunCommand('g.rename', rast=string)
         else:
             renamed = RunCommand('g.rename', rast3d=string)
         if (renamed == 0):
             self.SetItemText(self.selected_layer, self.new_name)
             label = "g.rename " + self.GetItemText(
                 self.selected_type) + "=" + string + "   -- completed"
             self.showNotification.emit(message=label)
             Debug.msg(1, "LAYER RENAMED TO: " + self.new_name)
         self.RestoreBackup()
Exemple #27
0
    def ImportFile(self, filePath):
        """Tries to import file as vector or raster.

        If successfull sets default region from imported map.
        """
        RunCommand('db.connect', flags='c')
        mapName = os.path.splitext(os.path.basename(filePath))[0]
        vectors = RunCommand('v.in.ogr', input=filePath, flags='l', read=True)

        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        if vectors:
            # vector detected
            returncode, error = RunCommand('v.in.ogr',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        else:
            returncode, error = RunCommand('r.in.gdal',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        wx.EndBusyCursor()

        if returncode != 0:
            GError(parent=self,
                   message=_("Import of <%(name)s> failed.\n"
                             "Reason: %(msg)s") % ({
                                 'name': filePath,
                                 'msg': error
                             }))
        else:
            GMessage(message=_(
                "Data file <%(name)s> imported successfully. "
                "The location's default region was set from this imported map."
            ) % {'name': filePath},
                     parent=self)
Exemple #28
0
 def _initTreeItems(self, locations = [], mapsets = []):
     """Add locations, mapsets and layers to the tree."""
     if not locations:
         locations = GetListOfLocations(self.gisdbase)
     if not mapsets:
         mapsets = ['*']
     
     first = True
     for loc in locations:
         location = loc
         if first:
             self.ChangeEnvironment(location, 'PERMANENT')
             first = False
         else:
             self.ChangeEnvironment(location)
         varloc = self.AppendItem(self.root, loc)
         #get list of all maps in location
         maplist = RunCommand('g.list', flags='mt', type='rast,rast3d,vect', mapset=','.join(mapsets),
                              quiet=True, read=True)
         maplist = maplist.splitlines()
         for ml in maplist:
             # parse
             parts1 = ml.split('/')
             parts2 = parts1[1].split('@')
             mapset = parts2[1]
             mlayer = parts2[0]
             ltype = parts1[0]
             if self.itemExists(mapset, varloc) == False:
                 varmapset = self.AppendItem(varloc, mapset)
             if (self.GetItemText(varmapset) == mapset):
                 if (self.itemExists(ltype, varmapset) == False):
                     vartype = self.AppendItem(varmapset, ltype)
             else:
                 varmapset = self.getItemByName(mapset, varloc)
                 if (self.itemExists(ltype, varmapset) == False):
                     vartype = self.AppendItem(varmapset, ltype)
             self.AppendItem(vartype, mlayer)
     self.RestoreBackup()          
     Debug.msg(1, "Tree filled")    
Exemple #29
0
    def RunAnalysis(self):

        analysis, valid = self.vnet_data.GetParam("analysis")

        params, err_params, flags = self.vnet_data.GetParams()
        relevant_params = self.vnet_data.GetRelevantParams(analysis)

        if not relevant_params:
            return -1

        if not self.vnet_data.InputsErrorMsgs(
                _("Unable to perform analysis."),
                analysis,
                params,
                flags,
                err_params,
                relevant_params,
        ):
            return -2

        if self.results["vect_map"]:
            self.results["vect_map"].DeleteRenderLayer()

        # history - delete data in buffer for hist step
        self.history.DeleteNewHistStepData()

        # create new map (included to history) for result of analysis
        self.results["vect_map"] = self.history.NewTmpVectMapToHist(
            "vnet_tmp_result")

        if not self.results["vect_map"]:
            return False

        # for case there is some map with same name
        # (when analysis does not produce any map, this map would have been shown as result)
        RunCommand(
            "g.remove",
            flags="f",
            type="vector",
            name=self.results["vect_map"].GetVectMapName(),
        )

        # save data from
        self.history._saveAnInputToHist(analysis, params, flags)

        ret = self.analyses.RunAnalysis(
            self.results["vect_map"].GetVectMapName(), params, flags)
        if not ret:
            return -3
        else:
            return 1
Exemple #30
0
    def Load(self, url, full=True):
        """Load list of extensions"""
        self._emptyTree()

        if full:
            flags = 'g'
        else:
            flags = 'l'
        retcode, ret, msg = RunCommand(
            'g.extension', read=True, getErrorMsg=True, url=url, flags=flags, quiet=True)
        if retcode != 0:
            raise GException(_("Unable to load extensions. %s") % msg)

        currentNode = None
        for line in ret.splitlines():
            if full:
                try:
                    key, value = line.split('=', 1)
                except ValueError:
                    key = 'name'
                    value = line

                if key == 'name':
                    try:
                        prefix, name = value.split('.', 1)
                    except ValueError:
                        prefix = ''
                        name = value
                    mainNode = self.mainNodes[self._expandPrefix(prefix)]
                    currentNode = self.model.AppendNode(
                        parent=mainNode, label=value)
                    currentNode.data = {'command': value}
                else:
                    if currentNode is not None:
                        currentNode.data[key] = value
            else:
                try:
                    prefix, name = line.strip().split('.', 1)
                except ValueError:
                    prefix = ''
                    name = line.strip()

                if self._expandPrefix(prefix) == prefix:
                    prefix = ''
                module = prefix + '.' + name
                mainNode = self.mainNodes[self._expandPrefix(prefix)]
                currentNode = self.model.AppendNode(
                    parent=mainNode, label=module)
                currentNode.data = {'command': module,
                                    'keywords': '',
                                    'description': ''}
Exemple #31
0
    def UpdateMapsets(self, location):
        """Update list of mapsets"""
        self.FormerMapsetSelection = wx.NOT_FOUND  # for non-selectable item

        self.listOfMapsetsSelectable = list()
        self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)

        self.lbmapsets.Clear()

        # disable mapset with denied permission
        locationName = os.path.basename(location)

        ret = RunCommand('g.mapset',
                         read=True,
                         flags='l',
                         location=locationName,
                         gisdbase=self.gisdbase)

        if ret:
            for line in ret.splitlines():
                self.listOfMapsetsSelectable += line.split(' ')
        else:
            self.SetLocation(self.gisdbase, locationName, "PERMANENT")
            # first run only
            self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)

        disabled = []
        idx = 0
        for mapset in self.listOfMapsets:
            if mapset not in self.listOfMapsetsSelectable or \
                    get_lockfile_if_present(self.gisdbase,
                                            locationName, mapset):
                disabled.append(idx)
            idx += 1

        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)

        return self.listOfMapsets
    def _runCommand(self, cmd):
        """!Run command to render data
        """
        if self.type == 'wms':
            ret = 0
            msg = ''
            self.renderMgr.Render(cmd)
        else:
            ret, msg = RunCommand(cmd[0],
                                  getErrorMsg=True,
                                  quiet=True,
                                  **cmd[1])

        return ret, msg
Exemple #33
0
    def CleanUp(self):

        ScattPlotsCondsData.CleanUp(self)
        for tmp in six.itervalues(self.cats_rasts_conds):
            grass.try_remove(tmp)
        for tmp in six.itervalues(self.cats_rasts):
            RunCommand("g.remove",
                       flags="f",
                       type="raster",
                       name=tmp,
                       getErrorMsg=True)

        self.cats_rasts = {}
        self.cats_rasts_conds = {}
Exemple #34
0
    def DeleteCategory(self, cat_id):

        ScattPlotsCondsData.DeleteCategory(self, cat_id)

        grass.try_remove(self.cats_rasts_conds[cat_id])
        del self.cats_rasts_conds[cat_id]

        RunCommand("g.remove",
                   flags="f",
                   type="raster",
                   name=self.cats_rasts[cat_id])
        del self.cats_rasts[cat_id]

        return True
Exemple #35
0
def main():
    app = wx.App()

    dlg = MapsetAccess(parent=None)
    dlg.CenterOnScreen()

    if dlg.ShowModal() == wx.ID_OK:
        ms = dlg.GetMapsets()
        RunCommand("g.mapsets",
                   parent=None,
                   mapset="%s" % ",".join(ms),
                   operation="set")

    dlg.Destroy()
Exemple #36
0
    def _updateTtbByGlobalCosts(self, vectMapName, tlayer):
        # TODO get layer number do not use it directly
        intervals = self.turnsData["global"].GetData()

        cmdUpdGlob = [
            "v.db.update",
            "map=",
            self.inputData["input"].GetValue(),
            "layer=%d" % tlayer,
            "column=cost",
        ]

        dbInfo = VectorDBInfo(vectMapName)
        table = dbInfo.GetTable(tlayer)
        driver, database = dbInfo.GetDbSettings(tlayer)

        sqlFile = grass.tempfile()
        sqlFile_f = open(sqlFile, "w")

        for ival in intervals:
            from_angle = ival[0]
            to_angle = ival[1]
            cost = ival[2]

            if to_angle < from_angle:
                to_angle = math.pi * 2 + to_angle
            # if angle < from_angle:
            #    angle = math.pi * 2  + angle

            where = " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1})) OR \
                            ((angle >= {0}) AND (angle >= {0} AND angle < {1}))) AND cost==0.0 ".format(
                str(from_angle), str(to_angle), str(math.pi * 2))

            stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n"
            sqlFile_f.write(stm)

        sqlFile_f.close()

        # TODO improve parser and run in thread

        ret, msg, err = RunCommand(
            "db.execute",
            getErrorMsg=True,
            input=sqlFile,
            read=True,
            driver=driver,
            database=database,
        )

        try_remove(sqlFile)
Exemple #37
0
 def writeCircle(self, circle, rasterName):
     coords = self.mapWindow.Pixel2Cell(circle.point)
     RunCommand(
         "r.circle",
         output=rasterName,
         max=circle.radius,
         coordinate=coords,
         flags="b",
     )
     grass.use_temp_region()
     grass.run_command("g.region", zoom=rasterName)
     region = grass.region()
     marea = MaskedArea(region, rasterName, circle.radius)
     return marea
Exemple #38
0
 def _estimateResampling(self):
     output = RunCommand(
         "r.info",
         flags="g",
         quiet=False,
         read=True,
         map=self.iLayer,
         env=self.iEnv,
         parse=parse_key_val,
     )
     if output["datatype"] == "CELL":
         self.resampling.SetStringSelection("nearest")
     else:
         self.resampling.SetStringSelection("bilinear")
Exemple #39
0
    def DeleteCategory(self, cat_id):

        ScattPlotsCondsData.DeleteCategory(self, cat_id)

        grass.try_remove(self.cats_rasts_conds[cat_id])
        del self.cats_rasts_conds[cat_id]

        RunCommand("g.remove",
                   flags='f',
                   type='rast',
                   pattern=self.cats_rasts[cat_id])
        del self.cats_rasts[cat_id]

        return True
Exemple #40
0
def main():
    app = wx.App()

    dlg = MapsetAccess(parent=None)
    dlg.CenterOnScreen()

    if dlg.ShowModal() == wx.ID_OK:
        ms = dlg.GetMapsets()
        RunCommand('g.mapsets',
                   parent=None,
                   mapset='%s' % ','.join(ms),
                   operation='set')

    dlg.Destroy()
Exemple #41
0
    def CleanUp(self):

        ScattPlotsCondsData.CleanUp(self)
        for tmp in self.cats_rasts_conds.itervalues():
            grass.try_remove(tmp)
        for tmp in self.cats_rasts.itervalues():
            RunCommand("g.remove",
                       flags='f',
                       type='rast',
                       pattern=tmp,
                       getErrorMsg=True)

        self.cats_rasts = {}
        self.cats_rasts_conds = {}
Exemple #42
0
 def _estimateResolution(self):
     output = RunCommand('r.proj',
                         flags='g',
                         quiet=False,
                         read=True,
                         input=self.iLayer,
                         dbase=self.iGisdbase,
                         location=self.iLocation,
                         mapset=self.iMapset,
                         env=self.oEnv).strip()
     params = parse_key_val(output, vsep=' ')
     output = RunCommand('g.region',
                         flags='ug',
                         quiet=False,
                         read=True,
                         env=self.oEnv,
                         parse=lambda x: parse_key_val(x, val_type=float),
                         **params)
     cell_ns = (output['n'] - output['s']) / output['rows']
     cell_ew = (output['e'] - output['w']) / output['cols']
     estimate = (cell_ew + cell_ns) / 2.
     self.resolution.SetValue(str(estimate))
     self.params = params
Exemple #43
0
    def CreateDatalist(self, raster, coords):
        """Build a list of distance, value pairs for points along transect using r.profile
        """
        datalist = []

        # keep total number of transect points to 500 or less to avoid
        # freezing with large, high resolution maps
        region = grass.region()
        curr_res = min(float(region['nsres']), float(region['ewres']))
        transect_rec = 0
        if self.transect_length / curr_res > 500:
            transect_res = self.transect_length / 500
        else:
            transect_res = curr_res

        ret = RunCommand("r.profile",
                         parent=self,
                         input=raster,
                         coordinates=coords,
                         resolution=transect_res,
                         null="nan",
                         quiet=True,
                         read=True)

        if not ret:
            return []

        for line in ret.splitlines():
            dist, elev = line.strip().split(' ')
            if dist is None or dist == '' or dist == 'nan' or \
                    elev is None or elev == '' or elev == 'nan':
                continue
            dist = float(dist)
            elev = float(elev)
            datalist.append((dist, elev))

        return datalist
Exemple #44
0
 def OnDelete(self, event):
     """Delete layer or mapset"""
     if (self.selected_layer):
         string = self.GetItemText(self.selected_layer)
         self.ChangeEnvironment(self.GetItemText(self.selected_location),
                                self.GetItemText(self.selected_mapset))
         removed = 0
         # TODO: rewrite this that it will tell map type in the dialog
         if (self._confirmDialog(question=_(
                 'Do you really want to delete map <{m}>?').format(
                     m=string),
                                 title=_('Delete map')) == wx.ID_YES):
             label = _("Deleting") + " " + string + " ..."
             self.showNotification.emit(message=label)
             if (self.GetItemText(self.selected_type) == 'vect'):
                 removed = RunCommand('g.remove',
                                      flags='f',
                                      type='vect',
                                      pattern=string)
             elif (self.GetItemText(self.selected_type) == 'rast'):
                 removed = RunCommand('g.remove',
                                      flags='f',
                                      type='rast',
                                      pattern=string)
             else:
                 removed = RunCommand('g.remove',
                                      flags='f',
                                      type='rast3d',
                                      pattern=string)
             if (removed == 0):
                 self.Delete(self.selected_layer)
                 Debug.msg(1, "LAYER " + string + " DELETED")
                 label = "g.remove -f type=" + self.GetItemText(
                     self.selected_type
                 ) + " pattern=" + string + "    -- completed"  # generate this message (command) automatically?
                 self.showNotification.emit(message=label)
         self.RestoreBackup()
Exemple #45
0
    def CreateDatalist(self, raster, coords):
        """Build a list of distance, value pairs for points along transect using r.profile
        """
        datalist = []

        # keep total number of transect points to 500 or less to avoid
        # freezing with large, high resolution maps
        region = grass.region()
        curr_res = min(float(region['nsres']), float(region['ewres']))
        transect_rec = 0
        if self.transect_length / curr_res > 500:
            transect_res = self.transect_length / 500
        else:
            transect_res = curr_res

        ret = RunCommand("r.profile",
                         parent=self,
                         input=raster,
                         coordinates=coords,
                         resolution=transect_res,
                         null="nan",
                         quiet=True,
                         read=True)

        if not ret:
            return []

        for line in ret.splitlines():
            dist, elev = line.strip().split(' ')
            if dist is None or dist == '' or dist == 'nan' or \
                    elev is None or elev == '' or elev == 'nan':
                continue
            dist = float(dist)
            elev = float(elev)
            datalist.append((dist, elev))

        return datalist
Exemple #46
0
    def OnCleaningRun(self, event):
        """Builds options and runs v.clean
        """
        self.GetCmdStrings()

        err = list()
        for p, name in ((self.inmap, _('Name of input vector map')),
                        (self.outmap, _('Name for output vector map')),
                        (self.tools_string, _('Tools')), (self.thresh_string,
                                                          _('Threshold'))):
            if not p:
                err.append(_("'%s' not defined") % name)
        if err:
            GError(_("Some parameters not defined. Operation "
                     "canceled.\n\n%s") % '\n'.join(err),
                   parent=self)
            return

        self.SetStatusText(_("Executing selected cleaning operations..."))
        snum = len(self.toolslines.keys())

        if self.log:
            cmd = [
                self.cmd,
                'input=%s' % self.inmap,
                'output=%s' % self.outmap,
                'tool=%s' % self.tools_string,
                'thres=%s' % self.thresh_string
            ]
            if self.ftype_string:
                cmd.append('type=%s' % self.ftype_string)
            if self.overwrite.IsChecked():
                cmd.append('--overwrite')

            self.log.RunCmd(cmd, onDone=self.OnDone)
            self.parent.Raise()
        else:
            if self.overwrite.IsChecked():
                overwrite = True
            else:
                overwrite = False

            RunCommand(self.cmd,
                       input=self.inmap,
                       output=self.outmap,
                       type=self.ftype_string,
                       tool=self.tools_string,
                       thresh=self.thresh_string,
                       overwrite=overwrite)
Exemple #47
0
def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
    """!Reproject coordinates

    @param coord coordinates given as tuple
    @param projOut output projection
    @param projIn input projection (use location projection settings)

    @return reprojected coordinates (returned as tuple)
    """
    if not projIn:
        projIn = RunCommand('g.proj',
                            flags = 'jf',
                            read = True)
    coors = RunCommand('m.proj',
                       flags = flags,
                       proj_in = projIn,
                       proj_out = projOut,
                       stdin = '%f|%f' % (coord[0], coord[1]),
                       read = True)
    if coors:
        coors = coors.split('\t')
        e = coors[0]
        n = coors[1].split(' ')[0].strip()
        try:
            proj = projOut.split(' ')[0].split('=')[1]
        except IndexError:
            proj = ''
        if proj in ('ll', 'latlong', 'longlat') and 'd' not in flags:
            return (proj, (e, n))
        else:
            try:
                return (proj, (float(e), float(n)))
            except ValueError:
                return (None, None)
    
    return (None, None)
 def OnSetDsn(self, event):
     """Input DXF file defined, update list of layer widget"""
     path = event.GetString()
     if not path:
         return 
     
     data = list()        
     ret = RunCommand('v.in.dxf',
                      quiet = True,
                      parent = self,
                      read = True,
                      flags = 'l',
                      input = path)
     if not ret:
         self.list.LoadData()
         return
         
     for line in ret.splitlines():
         layerId = line.split(':')[0].split(' ')[1]
         layerName = line.split(':')[1].strip()
         grassName = GetValidLayerName(layerName)
         data.append((layerId, layerName.strip(), grassName.strip()))
     
     self.list.LoadData(data)
Exemple #49
0
def ReprojectCoordinates(coord, projOut, projIn=None, flags=""):
    """Reproject coordinates

    :param coord: coordinates given as tuple
    :param projOut: output projection
    :param projIn: input projection (use location projection settings)

    :return: reprojected coordinates (returned as tuple)
    """
    coors = RunCommand(
        "m.proj",
        flags=flags,
        input="-",
        proj_in=projIn,
        proj_out=projOut,
        sep=";",
        stdin="%f;%f" % (coord[0], coord[1]),
        read=True,
    )
    if coors:
        coors = coors.split(";")
        e = coors[0]
        n = coors[1]
        try:
            proj = projOut.split(" ")[0].split("=")[1]
        except IndexError:
            proj = ""
        if proj in ("ll", "latlong", "longlat") and "d" not in flags:
            return (proj, (e, n))
        else:
            try:
                return (proj, (float(e), float(n)))
            except ValueError:
                return (None, None)

    return (None, None)
 def OnSetButton(self, event=None):
     """Set default region"""
     ret = RunCommand('g.region',
                      flags='sa',
                      n=self.north,
                      s=self.south,
                      e=self.east,
                      w=self.west,
                      nsres=self.nsres,
                      ewres=self.ewres,
                      t=self.top,
                      b=self.bottom,
                      tbres=self.tbres)
     if ret == 0:
         self.Destroy()
Exemple #51
0
    def OnSetDsn(self, event):
        """Input DXF file defined, update list of layer widget"""
        path = event.GetString()
        if not path:
            return

        data = list()
        ret = RunCommand('v.in.dxf',
                         quiet=True,
                         parent=self,
                         read=True,
                         flags='l',
                         input=path)
        if not ret:
            self.list.LoadData()
            return

        for line in ret.splitlines():
            layerId = line.split(':')[0].split(' ')[1]
            layerName = line.split(':')[1].strip()
            grassName = GetValidLayerName(layerName)
            data.append((layerId, layerName.strip(), grassName.strip()))

        self.list.LoadData(data)
Exemple #52
0
    def _geomAttrbUpdate(self, fids):
        """Update geometry atrributes of currently selected features

        :param fid: list feature id
        """
        mapLayer = self.parent.toolbars['vdigit'].GetLayer()
        vectorName = mapLayer.GetName()
        if self.tree:
            item = self.tree.FindItemByData('maplayer', mapLayer)
            vdigit = self.tree.GetLayerInfo(item, key='vdigit')
        else:
            item = vdigit = None

        if not vdigit or 'geomAttr' not in vdigit:
            return

        dbInfo = gselect.VectorDBInfo(vectorName)
        sqlfile = tempfile.NamedTemporaryFile(mode="w")
        for fid in fids:
            for layer, cats in self.digit.GetLineCats(fid).iteritems():
                table = dbInfo.GetTable(layer)
                for attrb, item in vdigit['geomAttr'].iteritems():
                    val = -1
                    if attrb == 'length':
                        val = self.digit.GetLineLength(fid)
                        type = attrb
                    elif attrb == 'area':
                        val = self.digit.GetAreaSize(fid)
                        type = attrb
                    elif attrb == 'perimeter':
                        val = self.digit.GetAreaPerimeter(fid)
                        type = 'length'

                    if val < 0:
                        continue
                    val = UnitsConvertValue(val, type, item['units'])

                    for cat in cats:
                        sqlfile.write(
                            'UPDATE %s SET %s = %f WHERE %s = %d;\n' %
                            (table, item['column'], val,
                             dbInfo.GetKeyColumn(layer), cat))

            sqlfile.file.flush()
            RunCommand('db.execute',
                       parent=True,
                       quiet=True,
                       input=sqlfile.name)
Exemple #53
0
    def _runAn(self, analysis, output, params, flags, catPts):
        """Called for all v.net.* analysis (except v.net.path)"""

        # Creates part of cmd fro analysis
        cmdParams = [analysis]
        cmdParams.extend(self._setInputParams(analysis, params, flags))
        cmdParams.append("output=" + output)

        cats = self.data.GetAnalysisProperties()["cmdParams"]["cats"]

        if len(cats) > 1:
            for cat in cats:
                if  len(catPts[cat[0]]) < 1:
                    GMessage(parent = self, 
                            message = _("Please choose '%s' and '%s' point.") \
                                        % (cats[0][1], cats[1][1]))
                    return False
        else:
            for cat in cats:
                if  len(catPts[cat[0]]) < 2:
                    GMessage(parent = self, 
                             message = _("Please choose at least two points."))
                    return False      

        # TODO add also to thread for analysis?
        vcatResult = RunCommand("v.category",
                           input = params['input'],
                           option = "report",
                           flags = "g",
                           read = True)     

        vcatResult = vcatResult.splitlines()
        for cat in vcatResult:#TODO
            cat = cat.split()
            if "all" in cat:
                maxCat = int(cat[4])
                break

        layerNum = params["nlayer"]

        pt_ascii, catsNums = self._getAsciiPts (catPts = catPts, 
                                                maxCat = maxCat, 
                                                layerNum = layerNum)

        self.tmpPtsAsciiFile = grass.tempfile()#TODO better tmp files cleanup (make class for managing tmp files)
        tmpPtsAsciiFileOpened = open(self.tmpPtsAsciiFile, 'w')
        tmpPtsAsciiFileOpened.write(pt_ascii)
        tmpPtsAsciiFileOpened.close()

        self.tmpInPts = AddTmpMapAnalysisMsg("vnet_tmp_in_pts", self.tmp_maps)
        if not self.tmpInPts:
            return False

        self.tmpInPtsConnected = AddTmpMapAnalysisMsg("vnet_tmp_in_pts_connected", self.tmp_maps)
        if not self.tmpInPtsConnected:
            return False

        cmdParams.append("input=" + self.tmpInPtsConnected.GetVectMapName())
        cmdParams.append("--overwrite")  
        
        self._setCmdForSpecificAn(cmdParams)
        
        for catName, catNum in catsNums.iteritems():
            if catNum[0] == catNum[1]:
                cmdParams.append(catName + "=" + str(catNum[0]))
            else:
                cmdParams.append(catName + "=" + str(catNum[0]) + "-" + str(catNum[1]))

        # create and run commands which goes to analysis thread
        cmdVEdit = [ 
                    "v.edit",
                    "map=" + self.tmpInPts.GetVectMapName(), 
                    "input=" + self.tmpPtsAsciiFile,
                    "tool=create",
                    "--overwrite", 
                    "-n"                              
                   ]

        self._prepareCmd(cmdVEdit)
        self.goutput.RunCmd(command = cmdVEdit)

        cmdVNet = [
                    "v.net",
                    "points=" + self.tmpInPts.GetVectMapName(), 
                    "input=" + params['input'],
                    "output=" + self.tmpInPtsConnected.GetVectMapName(),
                    "alayer=" +  params["alayer"],
                    "nlayer=" +  params["nlayer"], 
                    "operation=connect",
                    "thresh=" + str(params["max_dist"]),             
                    "--overwrite"                         
                  ] #TODO snapping to nodes optimization

        self._prepareCmd(cmdVNet)
        self.goutput.RunCmd(command = cmdVNet)

        self._prepareCmd(cmdParams)
        self.goutput.RunCmd(command = cmdParams, onDone = self._runAnDone)
Exemple #54
0
 def Load(self, url, full = False):
     """!Load list of extensions"""
     self.DeleteAllItems()
     self.root = self.AddRoot(_("Menu tree"))
     self._initTree()
     
     if full:
         flags = 'g'
     else:
         flags = 'l'
     ret = RunCommand('g.extension.py', read = True, parent = self,
                      svnurl = url,
                      flags = flags, quiet = True)
     if not ret:
         return
     
     mdict = dict()
     for line in ret.splitlines():
         if full:
             try:
                 key, value = line.split('=', 1)
             except ValueError:
                 key = 'name'
                 value = line
             
             if key == 'name':
                 try:
                     prefix, name = value.split('.', 1)
                 except ValueError:
                     prefix = ''
                     name = value
                 if prefix not in mdict:
                     mdict[prefix] = dict()
                 mdict[prefix][name] = dict()
             else:
                 mdict[prefix][name][key] = value
         else:
             try:
                 prefix, name = line.strip().split('.', 1)
             except:
                 prefix = ''
                 name = line.strip()
             
             if self._expandPrefix(prefix) == prefix:
                 prefix = ''
                 
             if prefix not in mdict:
                 mdict[prefix] = dict()
                 
             mdict[prefix][name] = { 'command' : prefix + '.' + name }
     
     for prefix in mdict.keys():
         prefixName = self._expandPrefix(prefix)
         item = self._findItem(prefixName)
         names = mdict[prefix].keys()
         names.sort()
         for name in names:
             if prefix:
                 text = prefix + '.' + name
             else:
                 text = name
             new = self.AppendItem(parentId = item,
                                   text = text)
             data = dict()
             for key in mdict[prefix][name].keys():
                 data[key] = mdict[prefix][name][key]
             
             self.SetPyData(new, data)
     
     self._loaded = True
Exemple #55
0
    def SetupProfile(self):
        """!Create coordinate string for profiling. Create segment list for
           transect segment markers.
        """

        #
        # create list of coordinate points for r.profile
        #                
        dist = 0
        cumdist = 0
        self.coordstr = ''
        lasteast = lastnorth = None
        
        region = grass.region()
        insideRegion = True
        if len(self.mapwin.polycoords) > 0:
            for point in self.mapwin.polycoords:
                if not (region['w'] <= point[0] <= region['e'] and region['s'] <= point[1] <= region['n']):
                    insideRegion = False
                # build string of coordinate points for r.profile
                if self.coordstr == '':
                    self.coordstr = '%d,%d' % (point[0], point[1])
                else:
                    self.coordstr = '%s,%d,%d' % (self.coordstr, point[0], point[1])

        if not insideRegion:
            GWarning(message = _("Not all points of profile lie inside computational region."),
                     parent = self)

        if len(self.rasterList) == 0:
            return

        # title of window
        self.ptitle = _('Profile of')

        #
        # create list of coordinates for transect segment markers
        #
        if len(self.mapwin.polycoords) > 0:
            self.seglist = []
            for point in self.mapwin.polycoords:
                # get value of raster cell at coordinate point
                ret = RunCommand('r.what',
                                 parent = self,
                                 read = True,
                                 input = self.rasterList[0],
                                 east_north = '%d,%d' % (point[0],point[1]))
                
                val = ret.splitlines()[0].split('|')[3]
                if val == None or val == '*': continue
                val = float(val)
                
                # calculate distance between coordinate points
                if lasteast and lastnorth:
                    dist = math.sqrt(math.pow((lasteast-point[0]),2) + math.pow((lastnorth-point[1]),2))
                cumdist += dist
                
                #store total transect length
                self.transect_length = cumdist

                # build a list of distance,value pairs for each segment of transect
                self.seglist.append((cumdist,val))
                lasteast = point[0]
                lastnorth = point[1]

            # delete extra first segment point
            try:
                self.seglist.pop(0)
            except:
                pass

        #
        # create datalist of dist/value pairs and y labels for each raster map
        #    
        self.ylabel = ''
        i = 0
        
        for r in self.raster.iterkeys():
            self.raster[r]['datalist'] = []
            datalist = self.CreateDatalist(r, self.coordstr)
            if len(datalist) > 0:   
                self.raster[r]['datalist'] = datalist

                # update ylabel to match units if they exist           
                if self.raster[r]['units'] != '':
                    self.ylabel += '%s (%d),' % (r['units'], i)
                i += 1

                # update title
                self.ptitle += ' %s ,' % r.split('@')[0]

        self.ptitle = self.ptitle.rstrip(',')
            
        if self.ylabel == '':
            self.ylabel = _('Raster values')
        else:
            self.ylabel = self.ylabel.rstrip(',')
Exemple #56
0
 def __init__(self, parent, id = wx.ID_ANY, size = (800, 600),
              title = _("Set default region extent and resolution"), location = None):
     wx.Dialog.__init__(self, parent, id, title, size = size)
     panel = wx.Panel(self, id = wx.ID_ANY)
     
     self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
     
     self.parent = parent
     self.location = location
     
     #
     # default values
     #
     # 2D
     self.north = 1.0
     self.south = 0.0
     self.east = 1.0
     self.west = 0.0
     self.nsres = 1.0
     self.ewres = 1.0
     # 3D
     self.top = 1.0
     self.bottom = 0.0
     #         self.nsres3 = 1.0
     #         self.ewres3 = 1.0
     self.tbres  = 1.0
     
     #
     # inputs
     #
     # 2D
     self.tnorth = self.MakeTextCtrl(text = str(self.north), size = (150, -1), parent = panel)
     self.tsouth = self.MakeTextCtrl(str(self.south), size = (150, -1), parent = panel)
     self.twest = self.MakeTextCtrl(str(self.west), size = (150, -1), parent = panel)
     self.teast = self.MakeTextCtrl(str(self.east), size = (150, -1), parent = panel)
     self.tnsres = self.MakeTextCtrl(str(self.nsres), size = (150, -1), parent = panel)
     self.tewres = self.MakeTextCtrl(str(self.ewres), size = (150, -1), parent = panel)
     
     #
     # labels
     #
     self.lrows  = self.MakeLabel(parent = panel)
     self.lcols  = self.MakeLabel(parent = panel)
     self.lcells = self.MakeLabel(parent = panel)
     
     #
     # buttons
     #
     self.bset = self.MakeButton(text = _("&Set region"), id = wx.ID_OK, parent = panel)
     self.bcancel = wx.Button(panel, id = wx.ID_CANCEL)
     self.bset.SetDefault()
     
     #
     # image
     #
     self.img = wx.Image(os.path.join(globalvar.IMGDIR, "qgis_world.png"),
                         wx.BITMAP_TYPE_PNG).ConvertToBitmap()
     
     #
     # set current working environment to PERMANENT mapset
     # in selected location in order to set default region (WIND)
     #
     envval = {}
     ret = RunCommand('g.gisenv',
                      read = True)
     if ret:
         for line in ret.splitlines():
             key, val = line.split('=')
             envval[key] = val
         self.currlocation = envval['LOCATION_NAME'].strip("';")
         self.currmapset = envval['MAPSET'].strip("';")
         if self.currlocation != self.location or self.currmapset != 'PERMANENT':
             RunCommand('g.gisenv',
                        set = 'LOCATION_NAME=%s' % self.location)
             RunCommand('g.gisenv',
                        set = 'MAPSET=PERMANENT')
     else:
         dlg = wx.MessageBox(parent = self,
                             message = _('Invalid location selected.'),
                             caption = _("Error"), style = wx.ID_OK | wx.ICON_ERROR)
         return
     
     #
     # get current region settings
     #
     region = {}
     ret = RunCommand('g.region',
                      read = True,
                      flags = 'gp3')
     if ret:
         for line in ret.splitlines():
             key, val = line.split('=')
             region[key] = float(val)
     else:
         dlg = wx.MessageBox(parent = self,
                             message = _("Invalid region"),
                             caption = _("Error"), style = wx.ID_OK | wx.ICON_ERROR)
         dlg.ShowModal()
         dlg.Destroy()
         return
     
     #
     # update values
     # 2D
     self.north = float(region['n'])
     self.south = float(region['s'])
     self.east = float(region['e'])
     self.west = float(region['w'])
     self.nsres = float(region['nsres'])
     self.ewres = float(region['ewres'])
     self.rows = int(region['rows'])
     self.cols = int(region['cols'])
     self.cells = int(region['cells'])
     # 3D
     self.top = float(region['t'])
     self.bottom = float(region['b'])
     #         self.nsres3 = float(region['nsres3'])
     #         self.ewres3 = float(region['ewres3'])
     self.tbres = float(region['tbres'])
     self.depth = int(region['depths'])
     self.cells3 = int(region['cells3'])
     
     #
     # 3D box collapsable
     #
     self.infoCollapseLabelExp = _("Click here to show 3D settings")
     self.infoCollapseLabelCol = _("Click here to hide 3D settings")
     self.settings3D = wx.CollapsiblePane(parent = panel,
                                          label = self.infoCollapseLabelExp,
                                          style = wx.CP_DEFAULT_STYLE |
                                          wx.CP_NO_TLW_RESIZE | wx.EXPAND)
     self.MakeSettings3DPaneContent(self.settings3D.GetPane())
     self.settings3D.Collapse(False) # FIXME
     self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnSettings3DPaneChanged, self.settings3D)
     
     #
     # set current region settings
     #
     self.tnorth.SetValue(str(self.north))
     self.tsouth.SetValue(str(self.south))
     self.twest.SetValue(str(self.west))
     self.teast.SetValue(str(self.east))
     self.tnsres.SetValue(str(self.nsres))
     self.tewres.SetValue(str(self.ewres))
     self.ttop.SetValue(str(self.top))
     self.tbottom.SetValue(str(self.bottom))
     #         self.tnsres3.SetValue(str(self.nsres3))
     #         self.tewres3.SetValue(str(self.ewres3))
     self.ttbres.SetValue(str(self.tbres))
     self.lrows.SetLabel(_("Rows: %d") % self.rows)
     self.lcols.SetLabel(_("Cols: %d") % self.cols)
     self.lcells.SetLabel(_("Cells: %d") % self.cells)
     
     #
     # bindings
     #
     self.Bind(wx.EVT_BUTTON, self.OnSetButton, self.bset)
     self.Bind(wx.EVT_BUTTON, self.OnCancel, self.bcancel)
     self.tnorth.Bind(wx.EVT_TEXT,   self.OnValue)
     self.tsouth.Bind(wx.EVT_TEXT,   self.OnValue)
     self.teast.Bind(wx.EVT_TEXT,    self.OnValue)
     self.twest.Bind(wx.EVT_TEXT,    self.OnValue)
     self.tnsres.Bind(wx.EVT_TEXT,   self.OnValue)
     self.tewres.Bind(wx.EVT_TEXT,   self.OnValue)
     self.ttop.Bind(wx.EVT_TEXT,     self.OnValue)
     self.tbottom.Bind(wx.EVT_TEXT,  self.OnValue)
     #         self.tnsres3.Bind(wx.EVT_TEXT,  self.OnValue)
     #         self.tewres3.Bind(wx.EVT_TEXT,  self.OnValue)
     self.ttbres.Bind(wx.EVT_TEXT,   self.OnValue)
     
     self.__DoLayout(panel)
     self.SetMinSize(self.GetBestSize())
     self.minWindowSize = self.GetMinSize()
     wx.CallAfter(self.settings3D.Collapse, True)