Example #1
0
    def Query(self, x, y):
        """Query active layers from both mapwindows.

        :param x,y: coordinates
        """
        rasters = ([layer.GetName() for layer in
                    self.GetFirstMap().GetListOfLayers(ltype='raster', active=True)],
                   [layer.GetName() for layer in
                    self.GetSecondMap().GetListOfLayers(ltype='raster', active=True)])
        vectors = ([layer.GetName() for layer in
                    self.GetFirstMap().GetListOfLayers(ltype='vector', active=True)],
                   [layer.GetName() for layer in
                    self.GetSecondMap().GetListOfLayers(ltype='vector', active=True)])

        if not (rasters[0] + rasters[1] + vectors[0] + vectors[1]):
            GMessage(parent=self,
                     message=_('No raster or vector map layer selected for querying.'))
            return

        # set query snap distance for v.what at map unit equivalent of 10 pixels
        qdist = 10.0 * ((self.GetFirstMap().region['e'] -
                         self.GetFirstMap().region['w']) / self.GetFirstMap().width)

        east, north = self.GetFirstWindow().Pixel2Cell((x, y))

        # use display region settings instead of computation region settings
        self.tmpreg = os.getenv("GRASS_REGION")
        os.environ["GRASS_REGION"] = self.GetFirstMap().SetRegion(windres=False)

        result = []
        if rasters[0]:
            result.extend(grass.raster_what(map=rasters[0], coord=(east, north),
                                            localized=True))
        if vectors[0]:
            result.extend(grass.vector_what(map=vectors[0], coord=(east, north), distance=qdist))
        if rasters[1]:
            result.extend(grass.raster_what(map=rasters[1], coord=(east, north),
                                            localized=True))
        if vectors[1]:
            result.extend(grass.vector_what(map=vectors[1], coord=(east, north), distance=qdist))

        self._QueryMapDone()

        result = PrepareQueryResults(coordinates=(east, north), result=result)
        if self._queryDialog:
            self._queryDialog.Raise()
            self._queryDialog.SetData(result)
        else:
            self._queryDialog = QueryDialog(parent=self, data=result)
            self._queryDialog.Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
            self._queryDialog.redirectOutput.connect(lambda output: self._giface.WriteLog(output))
            self._queryDialog.Show()
Example #2
0
    def SelectByPoint(self, queryCoords, qdist):
        """!Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        data = grass.vector_what(
            map=self.map, coord=(float(queryCoords[0]), float(queryCoords[1])), distance=float(qdist)
        )

        if len(data) < 1:
            return None

        # process attributes
        table = data[0]["Table"]
        for key, value in data[0]["Attributes"].iteritems():
            if len(value) < 1:
                value = None
            else:
                if self.tables[table][key]["ctype"] != types.StringType:
                    value = self.tables[table][key]["ctype"](value)
                else:
                    value = unicodeValue(value)
            self.tables[table][key]["values"].append(value)

        ret = dict()
        for key, value in data[0].iteritems():
            if key == "Attributes":
                continue
            ret[key] = list()
            ret[key].append(value)

        return ret
Example #3
0
    def SelectByPoint(self, queryCoords, qdist):
        """Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        try:
            data = grass.vector_what(
                map=self.map,
                coord=(float(queryCoords[0]), float(queryCoords[1])),
                distance=float(qdist),
            )
        except grass.ScriptError:
            GError(
                parent=None,
                message=_(
                    "Failed to query vector map <{map}>. "
                    "Check database settings and topology."
                ).format(map=self.map),
            )

        if len(data) < 1 or all(("Table" not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ["Category", "Layer", "Table", "Id"]:
            ret[key] = list()

        for record in data:
            if "Table" not in record:
                continue

            table = record["Table"]
            for key, value in six.iteritems(record["Attributes"]):
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]["ctype"] != str:
                        value = self.tables[table][key]["ctype"](value)
                    else:
                        value = GetUnicodeValue(value)
                self.tables[table][key]["values"].append(value)

            for key, value in six.iteritems(record):
                if key == "Attributes":
                    continue
                if key in ret:
                    ret[key].append(value)
            if "Id" not in record.keys():
                ret["Id"].append(None)

        return ret
Example #4
0
    def SelectByPoint(self, queryCoords, qdist):
        """Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        try:
            data = grass.vector_what(
                map=self.map, coord=(
                    float(
                        queryCoords[0]), float(
                        queryCoords[1])), distance=float(qdist))
        except grass.ScriptError:
            GError(
                parent=None, message=_(
                    "Failed to query vector map <{map}>. "
                    "Check database settings and topology.").format(
                    map=self.map))

        if len(data) < 1 or all(('Table' not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ['Category', 'Layer', 'Table', 'Id']:
            ret[key] = list()

        for record in data:
            if not 'Table' in record:
                continue

            table = record['Table']
            for key, value in six.iteritems(record['Attributes']):
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]['ctype'] != types.StringType:
                        value = self.tables[table][key]['ctype'](value)
                    else:
                        value = GetUnicodeValue(value)
                self.tables[table][key]['values'].append(value)

            for key, value in six.iteritems(record):
                if key == 'Attributes':
                    continue
                if key in ret:
                    ret[key].append(value)
            if 'Id' not in record.keys():
                ret['Id'].append(None)

        return ret
Example #5
0
    def SelectByPoint(self, queryCoords, qdist):
        """Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        try:
            data = grass.vector_what(
                map=self.map, coord=(
                    float(
                        queryCoords[0]), float(
                        queryCoords[1])), distance=float(qdist))
        except grass.ScriptError:
            GError(
                parent=None, message=_(
                    "Failed to query vector map <{map}>. "
                    "Check database settings and topology.").format(
                    map=self.map))

        if len(data) < 1 or all(('Table' not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ['Category', 'Layer', 'Table', 'Id']:
            ret[key] = list()

        for record in data:
            if not 'Table' in record:
                continue

            table = record['Table']
            for key, value in record['Attributes'].iteritems():
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]['ctype'] != types.StringType:
                        value = self.tables[table][key]['ctype'](value)
                    else:
                        value = GetUnicodeValue(value)
                self.tables[table][key]['values'].append(value)

            for key, value in record.iteritems():
                if key == 'Attributes':
                    continue
                if key in ret:
                    ret[key].append(value)
            if 'Id' not in record.keys():
                ret['Id'].append(None)

        return ret
Example #6
0
    def SelectByPoint(self, queryCoords, qdist):
        """!Get attributes by coordinates (all available layers)

        Return line id or None if no line is found"""
        line = None
        nselected = 0

        data = grass.vector_what(map=self.map,
                                 coord=(float(queryCoords[0]),
                                        float(queryCoords[1])),
                                 distance=float(qdist))

        if len(data) < 1 or all(('Table' not in record) for record in data):
            return None

        # process attributes
        ret = dict()
        for key in ['Category', 'Layer', 'Table', 'Id']:
            ret[key] = list()

        for record in data:
            if not 'Table' in record:
                continue

            table = record['Table']
            for key, value in record['Attributes'].iteritems():
                if len(value) < 1:
                    value = None
                else:
                    if self.tables[table][key]['ctype'] != types.StringType:
                        value = self.tables[table][key]['ctype'](value)
                    else:
                        value = unicodeValue(value)
                self.tables[table][key]['values'].append(value)

            for key, value in record.iteritems():
                if key == 'Attributes':
                    continue
                if key in ret:
                    ret[key].append(value)
            if 'Id' not in record.keys():
                ret['Id'].append(None)

        return ret
Example #7
0
    def QuerySelectedMap(self):
        """Return w.what info from last clicked coords on display

        """
        self.mapName = self.GetSelectedMap()
        if not self.mapName:
            return {}

        mapInfo = self.mapWin.GetMap()
        threshold = 10.0 * ((mapInfo.region['e'] - mapInfo.region['w']) / mapInfo.width)
        try:
            query = grass.vector_what(map=[self.mapName],
                                      coord=self.mapWin.GetLastEN(),
                                      distance=threshold, skip_attributes=True)
        except grass.ScriptError:
            GError(parent=self,
                   message=_("Failed to query vector map(s) <%s>.") % self.map)
            return None

        return query[0]
Example #8
0
    def QuerySelectedMap(self):
        """Return w.what info from last clicked coords on display

        """
        self.mapName = self.GetSelectedMap()
        if not self.mapName:
            return {}

        mapInfo = self.mapWin.GetMap()
        threshold = 10.0 * (
            (mapInfo.region['e'] - mapInfo.region['w']) / mapInfo.width)
        try:
            query = grass.vector_what(map=[self.mapName],
                                      coord=self.mapWin.GetLastEN(),
                                      distance=threshold, skip_attributes=True)
        except grass.ScriptError:
            GError(parent=self,
                   message=_("Failed to query vector map(s) <%s>.") % self.map)
            return None

        return query[0]
Example #9
0
    def Query(self, x, y):
        """Query active layers from both mapwindows.

        :param x,y: coordinates
        """
        rasters = (
            [layer.GetName()
             for layer in self.GetFirstMap().GetListOfLayers(
                 ltype='raster', active=True)],
            [layer.GetName()
             for layer in self.GetSecondMap().GetListOfLayers(
                 ltype='raster', active=True)])
        vectors = (
            [layer.GetName()
             for layer in self.GetFirstMap().GetListOfLayers(
                 ltype='vector', active=True)],
            [layer.GetName()
             for layer in self.GetSecondMap().GetListOfLayers(
                 ltype='vector', active=True)])

        if not (rasters[0] + rasters[1] + vectors[0] + vectors[1]):
            GMessage(
                parent=self,
                message=_(
                    'No raster or vector map layer selected for querying.'))
            return

        # set query snap distance for v.what at map unit equivalent of 10
        # pixels
        qdist = 10.0 * (
            (self.GetFirstMap().region['e'] - self.GetFirstMap().region['w']) /
            self.GetFirstMap().width)

        east, north = self.GetFirstWindow().Pixel2Cell((x, y))

        # use display region settings instead of computation region settings
        self.tmpreg = os.getenv("GRASS_REGION")
        os.environ["GRASS_REGION"] = self.GetFirstMap(
        ).SetRegion(windres=False)

        result = []
        if rasters[0]:
            result.extend(
                grass.raster_what(
                    map=rasters[0],
                    coord=(east, north),
                    localized=True))
        if vectors[0]:
            result.extend(
                grass.vector_what(
                    map=vectors[0],
                    coord=(east, north),
                    distance=qdist))
        if rasters[1]:
            result.extend(
                grass.raster_what(
                    map=rasters[1],
                    coord=(east, north),
                    localized=True))
        if vectors[1]:
            result.extend(
                grass.vector_what(
                    map=vectors[1],
                    coord=(east, north),
                    distance=qdist))

        self._QueryMapDone()

        result = PrepareQueryResults(coordinates=(east, north), result=result)
        if self._queryDialog:
            self._queryDialog.Raise()
            self._queryDialog.SetData(result)
        else:
            self._queryDialog = QueryDialog(parent=self, data=result)
            self._queryDialog.Bind(wx.EVT_CLOSE, self._oncloseQueryDialog)
            self._queryDialog.redirectOutput.connect(
                lambda output: self._giface.WriteLog(output))
            self._queryDialog.Show()
Example #10
0
    def _getSTVDData(self, timeseries):
        """Load data and read properties
        :param list timeseries: a list of timeseries
        """

        mode = None
        unit = None
        cats = None
        attribute = self.attribute.GetValue()
        if self.cats.GetValue() != '':
            cats = self.cats.GetValue().split(',')
        if cats and self.poi:
            GMessage(message=_("Both coordinates and categories are set, "
                               "coordinates will be used. The use categories "
                               "remove text from coordinate form"))
        if not attribute or attribute == '':
            GError(parent=self,
                   showTraceback=False,
                   message=_("With Vector temporal dataset you have to select"
                             " an attribute column"))
            return
        columns = ','.join(['name', 'start_time', 'end_time', 'id', 'layer'])
        for series in timeseries:
            name = series[0]
            fullname = name + '@' + series[1]
            etype = series[2]
            sp = tgis.dataset_factory(etype, fullname)
            if not sp.is_in_db(dbif=self.dbif):
                GError(message=_("Dataset <%s> not found in temporal "
                                 "database") % (fullname),
                       parent=self,
                       showTraceback=False)
                return
            sp.select(dbif=self.dbif)

            rows = sp.get_registered_maps(dbif=self.dbif,
                                          order="start_time",
                                          columns=columns,
                                          where=None)

            self.timeDataV[name] = OrderedDict()
            self.timeDataV[name]['temporalDataType'] = etype
            self.timeDataV[name]['temporalType'] = sp.get_temporal_type()
            self.timeDataV[name]['granularity'] = sp.get_granularity()

            if mode is None:
                mode = self.timeDataV[name]['temporalType']
            elif self.timeDataV[name]['temporalType'] != mode:
                GError(parent=self,
                       showTraceback=False,
                       message=_(
                           "Datasets have different temporal type ("
                           "absolute x relative), which is not allowed."))
                return
            self.timeDataV[name]['unit'] = None  # only with relative
            if self.timeDataV[name]['temporalType'] == 'relative':
                start, end, self.timeDataV[name][
                    'unit'] = sp.get_relative_time()
                if unit is None:
                    unit = self.timeDataV[name]['unit']
                elif self.timeDataV[name]['unit'] != unit:
                    GError(message=_("Datasets have different time unit which"
                                     " is not allowed."),
                           parent=self,
                           showTraceback=False)
                    return
            if self.poi:
                self.plotNameListV.append(name)
                # TODO set an appropriate distance, right now a big one is set
                # to return the closer point to the selected one
                out = grass.vector_what(map='pois_srvds',
                                        coord=self.poi.coords(),
                                        distance=10000000000000000)
                if len(out) != len(rows):
                    GError(parent=self,
                           showTraceback=False,
                           message=_("Difference number of vector layers and "
                                     "maps in the vector temporal dataset"))
                    return
                for i in range(len(rows)):
                    row = rows[i]
                    values = out[i]
                    if str(row['layer']) == str(values['Layer']):
                        lay = "{map}_{layer}".format(map=row['name'],
                                                     layer=values['Layer'])
                        self.timeDataV[name][lay] = {}
                        self.timeDataV[name][lay]['start_datetime'] = row[
                            'start_time']
                        self.timeDataV[name][lay]['end_datetime'] = row[
                            'start_time']
                        self.timeDataV[name][lay]['value'] = values[
                            'Attributes'][attribute]
            else:
                wherequery = ''
                cats = self._getExistingCategories(rows[0]['name'], cats)
                totcat = len(cats)
                ncat = 1
                for cat in cats:
                    if ncat == 1 and totcat != 1:
                        wherequery += '{k}={c} or'.format(c=cat, k="{key}")
                    elif ncat == 1 and totcat == 1:
                        wherequery += '{k}={c}'.format(c=cat, k="{key}")
                    elif ncat == totcat:
                        wherequery += ' {k}={c}'.format(c=cat, k="{key}")
                    else:
                        wherequery += ' {k}={c} or'.format(c=cat, k="{key}")

                    catn = "cat{num}".format(num=cat)
                    self.plotNameListV.append("{na}+{cat}".format(na=name,
                                                                  cat=catn))
                    self.timeDataV[name][catn] = OrderedDict()
                    ncat += 1
                for row in rows:
                    lay = int(row['layer'])
                    catkey = self._parseVDbConn(row['name'], lay)
                    if not catkey:
                        GError(parent=self,
                               showTraceback=False,
                               message=_(
                                   "No connection between vector map {vmap} "
                                   "and layer {la}".format(vmap=row['name'],
                                                           la=lay)))
                        return
                    vals = grass.vector_db_select(
                        map=row['name'],
                        layer=lay,
                        where=wherequery.format(key=catkey),
                        columns=attribute)
                    layn = "lay{num}".format(num=lay)
                    for cat in cats:
                        catn = "cat{num}".format(num=cat)
                        if layn not in self.timeDataV[name][catn].keys():
                            self.timeDataV[name][catn][layn] = {}
                        self.timeDataV[name][catn][layn][
                            'start_datetime'] = row['start_time']
                        self.timeDataV[name][catn][layn]['end_datetime'] = row[
                            'end_time']
                        self.timeDataV[name][catn][layn]['value'] = vals[
                            'values'][int(cat)][0]
        self.unit = unit
        self.temporalType = mode
        return
Example #11
0
    def _getSTVDData(self, timeseries):
        """Load data and read properties
        :param list timeseries: a list of timeseries
        """

        mode = None
        unit = None
        cats = None
        attribute = self.attribute.GetValue()
        if self.cats.GetValue() != '':
            cats = self.cats.GetValue().split(',')
        if cats and self.poi:
            GMessage(message=_("Both coordinates and categories are set, "
                               "coordinates will be used. The use categories "
                               "remove text from coordinate form"))
        if not attribute or attribute == '':
            GError(parent=self, showTraceback=False,
                   message=_("With Vector temporal dataset you have to select"
                             " an attribute column"))
            return
        columns = ','.join(['name', 'start_time', 'end_time', 'id', 'layer'])
        for series in timeseries:
            name = series[0]
            fullname = name + '@' + series[1]
            etype = series[2]
            sp = tgis.dataset_factory(etype, fullname)
            if not sp.is_in_db(dbif=self.dbif):
                GError(message=_("Dataset <%s> not found in temporal "
                                 "database") % (fullname), parent=self,
                                 showTraceback=False)
                return
            sp.select(dbif=self.dbif)

            rows = sp.get_registered_maps(dbif=self.dbif, order="start_time",
                                          columns=columns, where=None)

            self.timeDataV[name] = OrderedDict()
            self.timeDataV[name]['temporalDataType'] = etype
            self.timeDataV[name]['temporalType'] = sp.get_temporal_type()
            self.timeDataV[name]['granularity'] = sp.get_granularity()

            if mode is None:
                mode = self.timeDataV[name]['temporalType']
            elif self.timeDataV[name]['temporalType'] != mode:
                GError(parent=self, showTraceback=False,
                       message=_("Datasets have different temporal type ("
                                 "absolute x relative), which is not allowed."))
                return
            self.timeDataV[name]['unit'] = None  # only with relative
            if self.timeDataV[name]['temporalType'] == 'relative':
                start, end, self.timeDataV[name]['unit'] = sp.get_relative_time()
                if unit is None:
                    unit = self.timeDataV[name]['unit']
                elif self.timeDataV[name]['unit'] != unit:
                    GError(message=_("Datasets have different time unit which"
                                     " is not allowed."), parent=self,
                           showTraceback=False)
                    return
            if self.poi:
                self.plotNameListV.append(name)
                # TODO set an appropriate distance, right now a big one is set
                # to return the closer point to the selected one
                out = grass.vector_what(map='pois_srvds',
                                        coord=self.poi.coords(),
                                        distance=10000000000000000)
                if len(out) != len(rows):
                    GError(parent=self, showTraceback=False,
                           message=_("Difference number of vector layers and "
                                     "maps in the vector temporal dataset"))
                    return
                for i in range(len(rows)):
                    row = rows[i]
                    values = out[i]
                    if str(row['layer']) == str(values['Layer']):
                        lay = "{map}_{layer}".format(map=row['name'],
                                                     layer=values['Layer'])
                        self.timeDataV[name][lay] = {}
                        self.timeDataV[name][lay]['start_datetime'] = row['start_time']
                        self.timeDataV[name][lay]['end_datetime'] = row['start_time']
                        self.timeDataV[name][lay]['value'] = values['Attributes'][attribute]
            else:
                wherequery = ''
                cats = self._getExistingCategories(rows[0]['name'], cats)
                totcat = len(cats)
                ncat = 1
                for cat in cats:
                    if ncat == 1 and totcat != 1:
                        wherequery += '{k}={c} or'.format(c=cat, k="{key}")
                    elif ncat == 1 and totcat == 1:
                        wherequery += '{k}={c}'.format(c=cat, k="{key}")
                    elif ncat == totcat:
                        wherequery += ' {k}={c}'.format(c=cat, k="{key}")
                    else:
                        wherequery += ' {k}={c} or'.format(c=cat, k="{key}")

                    catn = "cat{num}".format(num=cat)
                    self.plotNameListV.append("{na}+{cat}".format(na=name,
                                                                  cat=catn))
                    self.timeDataV[name][catn] = OrderedDict()
                    ncat += 1
                for row in rows:
                    lay = int(row['layer'])
                    catkey = self._parseVDbConn(row['name'], lay)
                    if not catkey:
                        GError(parent=self, showTraceback=False,
                           message=_("No connection between vector map {vmap} "
                                     "and layer {la}".format(vmap=row['name'],
                                                              la=lay)))
                        return
                    vals = grass.vector_db_select(map=row['name'], layer=lay,
                                                  where=wherequery.format(key=catkey),
                                                  columns=attribute)
                    layn = "lay{num}".format(num=lay)
                    for cat in cats:
                        catn = "cat{num}".format(num=cat)
                        if layn not in self.timeDataV[name][catn].keys():
                            self.timeDataV[name][catn][layn] = {}
                        self.timeDataV[name][catn][layn]['start_datetime'] = row['start_time']
                        self.timeDataV[name][catn][layn]['end_datetime'] = row['end_time']
                        self.timeDataV[name][catn][layn]['value'] = vals['values'][int(cat)][0]
        self.unit = unit
        self.temporalType = mode
        return