Exemple #1
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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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 ReadEpsgCodes():
    """Read EPSG codes with g.proj

    :return: dictionary of EPSG code
    """
    epsgCodeDict = dict()

    ret = RunCommand("g.proj", read=True, list_codes="EPSG")

    for line in ret.splitlines():
        code, descr, params = line.split("|")
        epsgCodeDict[int(code)] = (descr, params)

    return epsgCodeDict
Exemple #13
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 #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 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 #16
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
Exemple #17
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
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 == "":
            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 not isinstance("", self.tables[table][name]["ctype"]):
                        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 _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 #20
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',
                         parent=self,
                         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 = unicodeValue(value)
                else:
                    value = None
                self.tables[table][name]['values'].append(value)
                nselected = 1

        return nselected
Exemple #21
0
    def CreateDatalist(self, raster, coords):
        """Build a list of distance, value pairs for points along transect

        Uses r.profile to obtain the data.
        """
        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 #22
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 #23
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 #24
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 #25
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
Exemple #26
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
 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)
    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 = 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)
Exemple #29
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.transect) > 0:
            for point in self.transect:
                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 = '%f,%f' % (point[0], point[1])
                else:
                    self.coordstr = '%s,%f,%f' % (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.transect) > 0:
            self.seglist = []
            for point in self.transect:
                # get value of raster cell at coordinate point
                ret = RunCommand('r.what',
                                 parent=self,
                                 read=True,
                                 map=self.rasterList[0],
                                 coordinates='%f,%f' % (point[0], point[1]))

                val = ret.splitlines()[0].split('|')[3]
                if val is 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 six.iterkeys(self.raster):
            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),' % (self.raster[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 #30
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 #31
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["node_layer"]

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

        # TODO better tmp files cleanup (make class for managing tmp files)
        self.tmpPtsAsciiFile = grass.tempfile()
        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 six.iteritems(catsNums):
            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(),
            "arc_layer=" + params["arc_layer"],
            "node_layer=" + params["node_layer"], "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 #32
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 #33
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)
Exemple #34
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)