Ejemplo n.º 1
0
 def __init__(self, p1, p2, p3=None):
     if p3 is None:
         p3 = QgsPoint(p2)
         p2 = self.createMiddlePoint(p1, p3)
     self.p1 = QgsPoint(p1)
     self.p2 = QgsPoint(p2)
     self.p3 = QgsPoint(p3)
Ejemplo n.º 2
0
 def canvasMoveEvent(self, event):
     if self.snapCursorRubberBand:
         self.snapCursorRubberBand.hide()
         self.snapCursorRubberBand.reset(geometryType=QGis.Point)
         self.snapCursorRubberBand = None
     oldPoint = QgsPoint(event.mapPoint())
     event.snapPoint(QgsMapMouseEvent.SnapProjectConfig)
     point = QgsPoint(event.mapPoint())
     if oldPoint != point:
         self.createSnapCursor(point)
     point = QgsPoint(event.mapPoint())   
     if self.qntPoint == 1:
         self.distanceToolTip.canvasMoveEvent(self.geometry[0], point)
         geom = QgsGeometry.fromPolyline([self.geometry[0], point])
         self.rubberBand.setToGeometry(geom, None)
     elif self.qntPoint >= 2:
         self.distanceToolTip.canvasMoveEvent(self.geometry[-1], point)
         if self.free:
             geom = QgsGeometry.fromPolygon([self.geometry+[QgsPoint(point.x(), point.y())]])
             self.rubberBand.setToGeometry(geom, None)             
         else:       
             if (self.qntPoint % 2 == 1): 
                 self.setAvoidStyleSnapRubberBand()
             else:
                 self.setAllowedStyleSnapRubberBand()
             projectedMousePoint = self.projectPoint(self.geometry[-2], self.geometry[-1], point)
             if projectedMousePoint:
                 geom, pf = self.completePolygon(self.geometry, projectedMousePoint)
                 self.rubberBand.setToGeometry(geom, None)
Ejemplo n.º 3
0
Archivo: cow.py Proyecto: brunky37/cow
    def draw_position(self,Latitud,Longitud,v_layer,option):

        #create the provider and add the layer
        pr = v_layer.dataProvider()
        QgsMapLayerRegistry.instance().addMapLayers([v_layer])
        seg = QgsFeature()

        #create the point and paint it
        try:
            point_A = QgsPoint((float(Longitud)-181-6.339908),(float(Latitud)-91+39.478360))
            seg.setGeometry(QgsGeometry.fromPoint(point_A))
            pr.addFeatures( [ seg ] )
            v_layer.updateExtents()
            v_layer.triggerRepaint()
            label=None
            if option==1:
                label=self.dlg.label_6
            elif option==2:
                label=self.dlg.label_7
            elif option==3:
                label=self.dlg.label_8
            if  self.pointInLimits(point_A.x(),point_A.y())==True:
                label.setText("IN")
                self.distances(point_A.x(),point_A.y(),option)

            else:
                label.setText("OUT")

            self.deletePoints(v_layer)
        except:
                pass
Ejemplo n.º 4
0
    def testSubstitutionMap(self):
        """Test that we can use degree symbols in substitutions.
        """
        # Create a point and convert it to text containing a degree symbol.
        myPoint = QgsPoint(12.3, -33.33)
        myCoordinates = myPoint.toDegreesMinutesSeconds(2)
        myTokens = myCoordinates.split(',')
        myLongitude = myTokens[0]
        myLatitude = myTokens[1]
        myText = 'Latitude: %s, Longitude: %s' % (myLatitude, myLongitude)

        # Load the composition with the substitutions
        myComposition = QgsComposition(self.iface.mapCanvas().mapRenderer())
        mySubstitutionMap = {'replace-me': myText}
        myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument, mySubstitutionMap)

        # We should be able to get map0
        myMap = myComposition.getComposerMapById(0)
        myMessage = ('Map 0 could not be found in template %s', myFile)
        assert myMap is not None, myMessage
Ejemplo n.º 5
0
    def _calc_north(self):
        extent = self.canvas.extent()
        if self.canvas.layerCount() == 0 or extent.isEmpty():
            print "No layers or extent"
            return 0

        outcrs = self.canvas.mapSettings().destinationCrs()

        if outcrs.isValid() and not outcrs.geographicFlag():
            crs = QgsCoordinateReferenceSystem()
            crs.createFromOgcWmsCrs("EPSG:4326")

            transform = QgsCoordinateTransform(outcrs, crs)

            p1 = QgsPoint(extent.center())
            p2 = QgsPoint(p1.x(), p1.y() + extent.height() * 0.25)

            try:
                pp1 = transform.transform(p1)
                pp2 = transform.transform(p2)
            except QgsCsException:
                roam.utils.warning("North arrow. Error transforming.")
                return None

            area = QgsDistanceArea()
            area.setEllipsoid(crs.ellipsoidAcronym())
            area.setEllipsoidalMode(True)
            area.setSourceCrs(crs)
            distance, angle, _ = area.computeDistanceBearing(pp1, pp2)
            angle = math.degrees(angle)
            return angle
        else:
            return 0
Ejemplo n.º 6
0
class TestQgsPoint(unittest.TestCase):

    def __init__(self, methodName):
        """Run once on class initialization."""
        unittest.TestCase.__init__(self, methodName)

    def setUp(self):
        self.mPoint = QgsPoint(10.0, 10.0)

    def test_Point(self):
        myExpectedValue = 10.0
        myActualValue = self.mPoint.x()
        myMessage = 'Expected: %s Got: %s' % (myExpectedValue, myActualValue)
        assert myExpectedValue == myActualValue, myMessage

    def test_pointToString(self):
        myExpectedValue = '10, 10'
        myActualValue = self.mPoint.toString()
        myMessage = 'Expected: %s Got: %s' % (myExpectedValue, myActualValue)
        assert myExpectedValue == myActualValue, myMessage

    def test_hash(self):
        a = QgsPoint(2.0, 1.0)
        b = QgsPoint(2.0, 2.0)
        c = QgsPoint(1.0, 2.0)
        d = QgsPoint(1.0, 1.0)
        e = QgsPoint(2.0, 1.0)
        assert a.__hash__() != b.__hash__()
        assert e.__hash__() == a.__hash__()

        mySet = set([a, b, c, d, e])
        assert len(mySet) == 4
Ejemplo n.º 7
0
    def calculateSquare(self, point):
        '''
        point in layer coordinates(QgsPoint)
        '''
        mapCrs = self.canvas.mapSettings().destinationCrs()
        utmCrs = QgsCoordinateReferenceSystem()
        utmCrs.createFromProj4(self.proj4Utm(point))
        ctFwd = QgsCoordinateTransform(mapCrs, utmCrs)
        ctBwd = QgsCoordinateTransform(utmCrs, mapCrs)

        pointGeom = QgsGeometry.fromPoint(point)
        pointGeom.transform(ctFwd)
        pointUtm = QgsPoint(pointGeom.asPoint())

        # calculate d
        d = self.diagonal/(2*(2**0.5))

        l = pointUtm.x() - d
        b = pointUtm.y() - d
        r = pointUtm.x() + d
        t = pointUtm.y() + d

        p1 = QgsGeometry.fromPoint(QgsPoint(l, b))
        p2 = QgsGeometry.fromPoint(QgsPoint(r, b))
        p3 = QgsGeometry.fromPoint(QgsPoint(r, t))
        p4 = QgsGeometry.fromPoint(QgsPoint(l, t))

        p1.transform(ctBwd)
        p2.transform(ctBwd)
        p3.transform(ctBwd)
        p4.transform(ctBwd)

        mapPol = [p1.asPoint(), p2.asPoint(), p3.asPoint(), p4.asPoint(), p1.asPoint()]

        return mapPol
Ejemplo n.º 8
0
 def normalizePoint(self, x, y):
   """Normalize given point. In result, lower-left is (0, 0) and upper-right is (1, 1)."""
   pt = QgsPoint(x, y)
   if self._rotation:
     pt = self.rotatePoint(pt, -self._rotation, self._center)
   rect = self._unrotated_rect
   return QgsPoint((pt.x() - rect.xMinimum()) / rect.width(),
                   (pt.y() - rect.yMinimum()) / rect.height())
Ejemplo n.º 9
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)

        fields = source.fields()
        x_field_index = fields.lookupField(self.parameterAsString(parameters, self.XFIELD, context))
        y_field_index = fields.lookupField(self.parameterAsString(parameters, self.YFIELD, context))
        z_field_index = -1
        if self.parameterAsString(parameters, self.ZFIELD, context):
            z_field_index = fields.lookupField(self.parameterAsString(parameters, self.ZFIELD, context))
        m_field_index = -1
        if self.parameterAsString(parameters, self.MFIELD, context):
            m_field_index = fields.lookupField(self.parameterAsString(parameters, self.MFIELD, context))

        wkb_type = QgsWkbTypes.Point
        if z_field_index >= 0:
            wkb_type = QgsWkbTypes.addZ(wkb_type)
        if m_field_index >= 0:
            wkb_type = QgsWkbTypes.addM(wkb_type)

        target_crs = self.parameterAsCrs(parameters, self.TARGET_CRS, context)

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               fields, wkb_type, target_crs)

        request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
        features = source.getFeatures()
        total = 100.0 / source.featureCount() if source.featureCount() else 0

        for current, feature in enumerate(features):
            if feedback.isCanceled():
                break

            feedback.setProgress(int(current * total))
            attrs = feature.attributes()

            try:
                x = float(attrs[x_field_index])
                y = float(attrs[y_field_index])

                point = QgsPoint(x, y)

                if z_field_index >= 0:
                    try:
                        point.addZValue(float(attrs[z_field_index]))
                    except:
                        point.addZValue(0.0)

                if m_field_index >= 0:
                    try:
                        point.addMValue(float(attrs[m_field_index]))
                    except:
                        point.addMValue(0.0)

                feature.setGeometry(QgsGeometry(point))
            except:
                pass  # no geometry

            sink.addFeature(feature)

        return {self.OUTPUT: dest_id}
Ejemplo n.º 10
0
class Observation():
    def __init__(self, iface, obsType, point, observation, precision):
        memoryLayers = MemoryLayers(iface)
        self.lineLayer = memoryLayers.line_layer()
        self.pointLayer = memoryLayers.point_layer()

        # generate ID;
        self.id = datetime.now().strftime("%Y%m%d%H%M%S%f")

        # obsservations are stored in the lineLayer layer attributes:
        #   0: id
        #   1: observation type
        #   2: x
        #   3: y
        #   4: observation
        #   5: precision

        self.obsType = obsType
        self.point = QgsPoint(point)
        self.observation = observation
        self.precision = precision

    def geometry(self):
        return QgsGeometry()

    def save(self):
        # observation
        f = QgsFeature()
        fields = self.lineLayer.dataProvider().fields()
        f.setFields(fields)
        f["id"] = self.id
        f["type"] = self.obsType
        f["x"] = self.point.x()
        f["y"] = self.point.y()
        f["observation"] = self.observation
        f["precision"] = self.precision
        f.setGeometry(self.geometry())
        ok, l = self.lineLayer.dataProvider().addFeatures([f])
        self.lineLayer.updateExtents()
        self.lineLayer.setCacheImage(None)
        self.lineLayer.triggerRepaint()
        self.lineLayer.featureAdded.emit(l[0].id())  # emit signal so feature is added to snapping index

        # center
        f = QgsFeature()
        fields = self.pointLayer.dataProvider().fields()
        f.setFields(fields)
        f["id"] = self.id
        f.setGeometry(QgsGeometry().fromPoint(self.point))
        ok, l = self.pointLayer.dataProvider().addFeatures([f])
        self.pointLayer.updateExtents()
        self.pointLayer.setCacheImage(None)
        self.pointLayer.triggerRepaint()
        self.pointLayer.featureAdded.emit(l[0].id())  # emit signal so feature is added to snapping index
Ejemplo n.º 11
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.getParameterValue(self.INPUT)
        vlayer = QgsProcessingUtils.mapLayerFromString(source, context)
        output = self.getOutputFromName(self.OUTPUT)

        fields = vlayer.fields()
        x_field_index = fields.lookupField(self.getParameterValue(self.XFIELD))
        y_field_index = fields.lookupField(self.getParameterValue(self.YFIELD))
        z_field_index = None
        if self.getParameterValue(self.ZFIELD):
            z_field_index = fields.lookupField(self.getParameterValue(self.ZFIELD))
        m_field_index = None
        if self.getParameterValue(self.MFIELD):
            m_field_index = fields.lookupField(self.getParameterValue(self.MFIELD))

        wkb_type = QgsWkbTypes.Point
        if z_field_index is not None:
            wkb_type = QgsWkbTypes.addZ(wkb_type)
        if m_field_index is not None:
            wkb_type = QgsWkbTypes.addM(wkb_type)

        crsId = self.getParameterValue(self.TARGET_CRS)
        target_crs = QgsCoordinateReferenceSystem()
        target_crs.createFromUserInput(crsId)

        writer = output.getVectorWriter(fields, wkb_type, target_crs, context)

        features = QgsProcessingUtils.getFeatures(vlayer, context)
        total = 100.0 / QgsProcessingUtils.featureCount(vlayer, context)

        for current, feature in enumerate(features):
            feedback.setProgress(int(current * total))
            attrs = feature.attributes()

            try:
                x = float(attrs[x_field_index])
                y = float(attrs[y_field_index])

                point = QgsPoint(x, y)

                if z_field_index is not None:
                    try:
                        point.addZValue(float(attrs[z_field_index]))
                    except:
                        point.addZValue(0.0)

                if m_field_index is not None:
                    try:
                        point.addMValue(float(attrs[m_field_index]))
                    except:
                        point.addMValue(0.0)

                feature.setGeometry(QgsGeometry(point))
            except:
                pass  # no geometry

            writer.addFeature(feature)

        del writer
Ejemplo n.º 12
0
 def event_dict(self):
     tz = pytz.timezone("Asia/Jakarta")
     timestamp = self.time.astimezone(tz=tz)
     time_format = "%-d-%b-%Y %H:%M:%S"
     timestamp_string = timestamp.strftime(time_format)
     point = QgsPoint(self.longitude, self.latitude)
     coordinates = point.toDegreesMinutesSeconds(2)
     tokens = coordinates.split(",")
     longitude_string = tokens[0]
     latitude_string = tokens[1]
     elapsed_time = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) - self.time
     elapsed_hour = elapsed_time.seconds / 3600
     elapsed_minute = (elapsed_time.seconds / 60) % 60
     event = {
         "report-title": self.tr("Volcanic Ash Impact"),
         "report-timestamp": self.tr("Volcano: %s, Alert Level: %s %s")
         % (self.volcano_name, self.alert_level, timestamp_string),
         "report-province": self.tr("Province: %s") % (self.region,),
         "report-location": self.tr("Longitude %s Latitude %s;" " Eruption Column Height (a.s.l) - %d m")
         % (longitude_string, latitude_string, self.erupction_height),
         "report-elapsed": self.tr("Elapsed time since event %s hour(s) and %s minute(s)")
         % (elapsed_hour, elapsed_minute),
         "header-impact-table": self.tr("Potential impact at each fallout level"),
         "header-nearby-table": self.tr("Nearby places"),
         "header-landcover-table": self.tr("Land Cover Impact"),
         "content-disclaimer": self.tr(
             "The impact estimation is automatically generated and only "
             "takes into account the population, cities and land cover "
             "affected by different levels of volcanic ash fallout at "
             "surface level. The estimate is based on volcanic ash "
             "fallout data from Badan Geologi, population count data "
             "derived by DMInnovation from worldpop.org.uk, place "
             "information from geonames.org, land cover classification "
             "data provided by Indonesian Geospatial Portal at "
             "http://portal.ina-sdi.or.id and software developed by BNPB. "
             "Limitation in the estimates of surface fallout, population "
             "and place names datasets may result in significant "
             "misrepresentation of the on-the-surface situation in the "
             "figures shown here. Consequently decisions should not be "
             "made soley on the information presented here and should "
             "always be verified by ground truthing and other reliable "
             "information sources."
         ),
         "content-notes": self.tr(
             "This report was created using InaSAFE version %s. Visit " "http://inasafe.org for more information. "
         )
         % get_version(),
     }
     return event
Ejemplo n.º 13
0
    def cntr2bugs(self):
        mLayer = self.checklayer()
        if mLayer is not None:
            QApplication.setOverrideCursor(Qt.WaitCursor)

            dlg = editor.Dialog()
            dlg.setModal(True)
            dlg.setWindowTitle("Centroids in BUGS format")

            provider = mLayer.dataProvider()
            e = provider.featureCount()

            ids = []
            x = "x = c("
            y = "y = c("

            feats = provider.getFeatures()
            dlg.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
            dlg.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, e))
            ne = 0
            feat = QgsFeature()
            while feats.nextFeature(feat):
                ne += 1
                dlg.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)
                ids.append(feat.id())

            mod = min(ids)

            for ne in range(mod, e + mod):
                feat = QgsFeature()
                pt = QgsPoint()
                fiter = mLayer.getFeatures(QgsFeatureRequest(ne))
                if fiter.nextFeature(feat):
                    pt = QgsGeometry(feat.geometry().centroid()).asPoint()
                    # pt = QgsGeometry(geom.centroid()).asPoint()

                x += '%s, ' % pt.x()
                y += '%s, ' % pt.y()

            dlg.plainTextEdit.appendPlainText(x[:-2]+')')
            dlg.plainTextEdit.appendPlainText(y[:-2]+')')

            QApplication.restoreOverrideCursor()

            dlg.exec_()
Ejemplo n.º 14
0
    def test_hash(self):
        a = QgsPoint(2.0, 1.0)
        b = QgsPoint(2.0, 2.0)
        c = QgsPoint(1.0, 2.0)
        d = QgsPoint(1.0, 1.0)
        e = QgsPoint(2.0, 1.0)
        assert a.__hash__() != b.__hash__()
        assert e.__hash__() == a.__hash__()

        mySet = set([a, b, c, d, e])
        assert len(mySet) == 4
Ejemplo n.º 15
0
class TestQgsPoint(TestCase):

    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)


    def setUp(self):
        self.mPoint = QgsPoint(10.0, 10.0)

    def test_Point(self):
        myExpectedValue = 10.0
        myActualValue = self.mPoint.x()
        myMessage = 'Expected: %s Got: %s' % (myExpectedValue, myActualValue)
        assert myExpectedValue == myActualValue, myMessage


    def test_pointToString(self):
        myExpectedValue = '10, 10'
        myActualValue = self.mPoint.toString()
        myMessage = 'Expected: %s Got: %s' % (myExpectedValue, myActualValue)
        assert myExpectedValue == myActualValue, myMessage
Ejemplo n.º 16
0
    def processNewData(self, data):
        '''
        Process incoming data from the data provider
        :param data: Positon or attitude data
        :type data: dict
        '''
        if not self.enabled:
            return
        try:
            name = data['name']
            if name in self.messageFilter.keys():
                if data['id'] != self.messageFilter[name]:
                    return
        except:
            pass
        self.extData.update(data)

        if 'lat' in data and 'lon' in data:
            self.position = QgsPoint(data['lon'], data['lat'])
            self.heading = data.get('heading', -9999.9)
            self.depth = data.get('depth', -9999.9)
            try:
                self.coordinates = self.crsXform.transform(self.position)
                self.marker.setMapPosition(self.coordinates)
                if 'time' in data:
                    self.lastFix = data['time']
                    self.newPosition.emit(self.lastFix, self.position,
                                          self.extData.get('depth', -9999.9),
                                          self.extData.get('altitude', -9999.9))
                    self.timer.start(self.timeoutTime)
                    self.timeoutCount = 0
            except QgsCsException:
                pass

        elif self.position is not None:
            if 'depth' in data or 'altitude' in data:
                self.newPosition.emit(self.lastFix, self.position,
                                      self.extData.get('depth', -9999.9),
                                      self.extData.get('altitude', -9999.9))

        if 'heading' in data:
            self.newAttitude.emit(data['heading'], data.get('pitch', 0.0),
                                  data.get('roll', 0.0))
            self.marker.newHeading(data['heading'])
Ejemplo n.º 17
0
    def __init__(self, iface, obsType, point, observation, precision):
        memoryLayers = MemoryLayers(iface)
        self.lineLayer = memoryLayers.line_layer()
        self.pointLayer = memoryLayers.point_layer()

        # generate ID;
        self.id = datetime.now().strftime("%Y%m%d%H%M%S%f")

        # obsservations are stored in the lineLayer layer attributes:
        #   0: id
        #   1: observation type
        #   2: x
        #   3: y
        #   4: observation
        #   5: precision

        self.obsType = obsType
        self.point = QgsPoint(point)
        self.observation = observation
        self.precision = precision
Ejemplo n.º 18
0
 def __init__(self,parent = None,x=0,y=0):
     QWidget.__init__(self,parent)
     self.resize(270, 130)
     
     self._gridLayout = QGridLayout(self)
     self._sbYCoord = QDoubleSpinBox(self)
     self._sbYCoord.setMinimumSize(QSize(0, 30))
     self._sbYCoord.setDecimals(5)
     self._sbYCoord.setMinimum(-180.0)
     self._sbYCoord.setMaximum(180.0)
     self._gridLayout.addWidget(self._sbYCoord, 2, 1, 1, 1)
     self._label_2 = QLabel(self)
     self._label_2.setText(QApplication.translate("CoordinatesWidget","Y-Coordinate"))
     self._gridLayout.addWidget(self._label_2, 2, 0, 1, 1)
     self._label = QLabel(self)
     self._label.setMaximumSize(QSize(80, 16777215))
     self._label.setText(QApplication.translate("CoordinatesWidget","X-Coordinate"))
     self._gridLayout.addWidget(self._label, 1, 0, 1, 1)
     self._sbXCoord = QDoubleSpinBox(self)
     self._sbXCoord.setMinimumSize(QSize(0, 30))
     self._sbXCoord.setDecimals(5)
     self._sbXCoord.setMinimum(-180.0)
     self._sbXCoord.setMaximum(180.0)
     self._gridLayout.addWidget(self._sbXCoord, 1, 1, 1, 1)
     self.vlNotification = QVBoxLayout()
     self._gridLayout.addLayout(self.vlNotification, 0, 0, 1, 2)
     
     #Set X and Y values
     self._sbXCoord.setValue(float(x))
     self._sbYCoord.setValue(float(y))
     
     self._geomPoint = QgsPoint(x,y)
     
     #Use default SRID
     self._srid = 4326
     
     #Connect signals
     self._sbXCoord.valueChanged.connect(self.onXCoordValueChanged)
     self._sbYCoord.valueChanged.connect(self.onYCoordValueChanged)
Ejemplo n.º 19
0
Archivo: arc.py Proyecto: 3nids/linkit
def arc(p1, p2, offset=1):

    # point in middle
    mp = QgsPoint((p1.x()+p2.x())/2, (p1.y()+p2.y())/2)
    # distance between the two points
    d = sqrt(p1.sqrDist(p2))
    # orthogonal direction to segment p1-p2
    az = (p1.azimuth(p2)+90)*pi/180
    # create point distant to segment of offset of segment length, will be center of circular arc
    cp = QgsPoint(mp.x()+d*offset*sin(az),
                  mp.y()+d*offset*cos(az))
    # radius
    r = d*sqrt(4*offset*offset+1)/2
    # calculate start and end azimuth of circular arc
    az1 = cp.azimuth(p1)
    az2 = cp.azimuth(p2)
    if az2 < az1:
        az2 += 360
    # draw arc
    vx = [cp.x()+r*sin(az*pi/180) for az in floatrange(az1, az2, 5)]
    vy = [cp.y()+r*cos(az*pi/180) for az in floatrange(az1, az2, 5)]
    arcLine = [QgsPoint(vx[i], vy[i]) for i in range(len(vx))]
    return QgsGeometry().fromPolyline(arcLine)
Ejemplo n.º 20
0
class MobileItem(QObject):
    '''
    A Mobile Item that reveives its position from a dataprovider
    and is displayed on the canvas
    Could be everything liek vehicles or simple beacons
    '''

    mobileItemCount = 0

    newPosition = pyqtSignal(float, QgsPoint, float, float)
    newAttitude = pyqtSignal(float, float, float)   # heading, pitch, roll
    timeout = pyqtSignal()

    def __init__(self, iface, params={}, parent=None):
        '''
        Constructor
        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        :param params: A dictionary defining all the properties of the item
        :type params: dictionary
        :param parent: Parent object for the new item. Defaults None.
        :type parent: QObject
        '''
        super(MobileItem, self).__init__(parent)

        self.iface = iface
        self.canvas = iface.mapCanvas()
        MobileItem.mobileItemCount += 1
        self.name = params.setdefault('Name', 'MobileItem_' +
                                      str(MobileItem.mobileItemCount))
        self.marker = PositionMarker(self.canvas, params)
        self.marker.setToolTip(self.name)
        self.dataProvider = params.get('provider', dict())
        self.messageFilter = dict()
        self.extData = dict()
        self.coordinates = None
        self.position = None
        self.heading = 0.0
        self.depth = 0.0
        self.lastFix = 0.0
        self.crsXform = QgsCoordinateTransform()
        self.crsXform.setSourceCrs(QgsCoordinateReferenceSystem(4326))
        self.onCrsChange()
        self.canvas.destinationCrsChanged.connect(self.onCrsChange)
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.timeout)
        self.notifyCount = int(params.get('nofixNotify', 0))
        if self.notifyCount:
            self.timer.timeout.connect(self.notifyTimeout)
        self.timeoutCount = 0
        self.timeoutTime = int(params.get('timeout', 3000))
        self.notifyDuration = int(params.get('NotifyDuration', 0))
        self.enabled = True

    def removeFromCanvas(self):
        '''
        Remove the item and its track from the canvas
        '''
        self.marker.removeFromCanvas()

    def properties(self):
        '''
        Return the items properties as dictionary
        :returns: Items properties
        :rtype: dict
        '''
        d = {'Name' : self.name,
             'timeout': self.timeoutTime,
             'nofixNotify': self.notifyCount,
             'enabled': self.enabled,
             'provider' : self.dataProvider}
        d.update(self.marker.properties())
        return d

    def subscribePositionProvider(self, provider, filterId=None):
        '''
        Subscribe the provider for this item
        by connecting to the providers signals
        :param provider: Provider to connect to
        :type provider: DataProvider
        :param filterId: Filter Id for this item
        :type filterId:
        '''
        provider.newDataReceived.connect(self.processNewData)
        if filterId is not None:
            self.messageFilter[provider.name] = filterId
        elif provider.name in self.messageFilter.keys():
            self.messageFilter.pop(provider.name, None)

    def unsubscribePositionProvider(self, provider):
        '''
        Unsubscribe provider by disconnecting the providers signals
        :param provider: Provider to diconnect from
        :type provider: DataProvider
        '''
        try:
            provider.newDataReceived.disconnect(self.processData)
            self.messageFilter.pop(provider.name, None)
        except KeyError:
            pass

    @pyqtSlot(dict)
    def processNewData(self, data):
        '''
        Process incoming data from the data provider
        :param data: Positon or attitude data
        :type data: dict
        '''
        if not self.enabled:
            return
        try:
            name = data['name']
            if name in self.messageFilter.keys():
                if data['id'] != self.messageFilter[name]:
                    return
        except:
            pass
        self.extData.update(data)

        if 'lat' in data and 'lon' in data:
            self.position = QgsPoint(data['lon'], data['lat'])
            self.heading = data.get('heading', -9999.9)
            self.depth = data.get('depth', -9999.9)
            try:
                self.coordinates = self.crsXform.transform(self.position)
                self.marker.setMapPosition(self.coordinates)
                if 'time' in data:
                    self.lastFix = data['time']
                    self.newPosition.emit(self.lastFix, self.position,
                                          self.extData.get('depth', -9999.9),
                                          self.extData.get('altitude', -9999.9))
                    self.timer.start(self.timeoutTime)
                    self.timeoutCount = 0
            except QgsCsException:
                pass

        elif self.position is not None:
            if 'depth' in data or 'altitude' in data:
                self.newPosition.emit(self.lastFix, self.position,
                                      self.extData.get('depth', -9999.9),
                                      self.extData.get('altitude', -9999.9))

        if 'heading' in data:
            self.newAttitude.emit(data['heading'], data.get('pitch', 0.0),
                                  data.get('roll', 0.0))
            self.marker.newHeading(data['heading'])

    @pyqtSlot(float)
    def onScaleChange(self, scale):
        '''
        Slot called when the map is zoomed
        :param scale: New scale
        :type scale: float
        '''
        self.marker.updateSize()

    @pyqtSlot()
    def onCrsChange(self):
        '''
        SLot called when the mapcanvas CRS is changed
        '''
        crsDst = self.canvas.mapSettings().destinationCrs()
        self.crsXform.setDestCRS(crsDst)
        self.marker.updateSize()

    @pyqtSlot(bool)
    def setEnabled(self, enabled):
        '''
        Hide or display the item and its track on the map
        :param enabled: what to do
        :type enabled: bool
        '''
        self.enabled = enabled
        self.marker.setVisible(self.enabled)
        self.marker.resetPosition()
        if self.enabled:
            self.timer.start(self.timeoutTime)
            self.timeoutCount = 0
        else:
            self.timer.stop()

    @pyqtSlot()
    def deleteTrack(self):
        '''
        Delete the track all points
        '''
        self.marker.deleteTrack()

    @pyqtSlot()
    def centerOnMap(self):
        '''
        Center the item on the map
        '''
        if self.coordinates is not None:
            self.canvas.setCenter(self.coordinates)
            self.canvas.refresh()

    def reportPosition(self):
        '''
        Report the position of the item. Used for logging
        :returns: geographic postion, depth and altitude
        :rtype: float, float, float, float
        '''
        if self.position is None:
            return -9999.9, -9999.9, -9999.9, 0.0
        return self.position.y(), self.position.x(), self.depth, self.heading

    @pyqtSlot()
    def notifyTimeout(self):
        self.timeoutCount += 1
        if self.timeoutCount == self.notifyCount:
            msg = self.tr(u'No fix for %s since more than %d seconds!') % (self.name, self.timeoutTime * self.timeoutCount / 1000)
            w = self.iface.messageBar().createMessage(self.tr(u'PosiView Attention'), msg)
            l = QLabel(w)
            m = QMovie(':/plugins/PosiView/hand.gif')
            m.setSpeed(75)
            l.setMovie(m)
            m.setParent(l)
            m.start()
            w.layout().addWidget(l)
            self.iface.messageBar().pushWidget(w, QgsMessageBar.CRITICAL, duration=self.notifyDuration)
Ejemplo n.º 21
0
 def testQgsCircularstringRepr(self):
     cs = QgsCircularString(QgsPoint(1, 2), QgsPoint(2, 3), QgsPoint(3, 4))
     self.assertEqual(cs.__repr__(), '<QgsCircularString: CircularString (1 2, 2 3, 3 4)>')
Ejemplo n.º 22
0
 def testQgsCompoundcurveRepr(self):
     cs = QgsCircularString(QgsPoint(1, 2), QgsPoint(2, 3), QgsPoint(3, 4))
     cc = QgsCompoundCurve()
     cc.addCurve(cs)
     self.assertEqual(cc.__repr__(), '<QgsCompoundCurve: CompoundCurve (CircularString (1 2, 2 3, 3 4))>')
Ejemplo n.º 23
0
    def map(self, p):
        # move to origin (translation part 1)
        p = QgsPoint(p.x() - self.dx1, p.y() - self.dy1)
        # scale
        p = QgsPoint(self.ds * p.x(), self.ds * p.y())
        # rotation
        p = QgsPoint(
            math.cos(self.da) * p.x() - math.sin(self.da) * p.y(), math.sin(self.da) * p.x() + math.cos(self.da) * p.y()
        )
        # remove to right spot (translation part 2)
        p = QgsPoint(p.x() + self.dx2, p.y() + self.dy2)

        return p
Ejemplo n.º 24
0
    def processAlgorithm(self, progress):
        extent = str(self.getParameterValue(self.EXTENT)).split(',')

        spacing = float(self.getParameterValue(self.SPACING))
        inset = float(self.getParameterValue(self.INSET))
        randomize = self.getParameterValue(self.RANDOMIZE)
        isSpacing = self.getParameterValue(self.IS_SPACING)

        extent = QgsRectangle(float(extent[0]), float(extent[2]),
                              float(extent[1]), float(extent[3]))

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))
        mapCRS = iface.mapCanvas().mapSettings().destinationCrs()

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fields, QgsWkbTypes.Point, mapCRS)

        if randomize:
            seed()

        area = extent.width() * extent.height()
        if isSpacing:
            pSpacing = spacing
        else:
            pSpacing = sqrt(area / spacing)

        f = QgsFeature()
        f.initAttributes(1)
        f.setFields(fields)

        count = 0
        total = 100.0 / (area / pSpacing)
        y = extent.yMaximum() - inset

        extent_geom = QgsGeometry.fromRect(extent)
        extent_engine = QgsGeometry.createGeometryEngine(
            extent_geom.geometry())
        extent_engine.prepareGeometry()

        while y >= extent.yMinimum():
            x = extent.xMinimum() + inset
            while x <= extent.xMaximum():
                if randomize:
                    geom = QgsGeometry().fromPoint(
                        QgsPoint(
                            uniform(x - (pSpacing / 2.0),
                                    x + (pSpacing / 2.0)),
                            uniform(y - (pSpacing / 2.0),
                                    y + (pSpacing / 2.0))))
                else:
                    geom = QgsGeometry().fromPoint(QgsPoint(x, y))

                if extent_engine.intersects(geom.geometry()):
                    f.setAttribute('id', count)
                    f.setGeometry(geom)
                    writer.addFeature(f)
                    x += pSpacing
                    count += 1
                    progress.setPercentage(int(count * total))
            y = y - pSpacing
        del writer
Ejemplo n.º 25
0
 def testQgsCircleRepr(self):
     c = QgsCircle(QgsPoint(1, 1), 2.0)
     self.assertEqual(c.__repr__(), '<QgsCircle: Circle (Center: Point (1 1), Radius: 2, Azimuth: 0)>')
Ejemplo n.º 26
0
    def processAlgorithm(self, context, feedback):
        layer = QgsProcessingUtils.mapLayerFromString(
            self.getParameterValue(self.INPUT_VECTOR), context)
        startPoint = self.getParameterValue(self.START_POINT)
        endPoint = self.getParameterValue(self.END_POINT)
        strategy = self.getParameterValue(self.STRATEGY)

        directionFieldName = self.getParameterValue(self.DIRECTION_FIELD)
        forwardValue = self.getParameterValue(self.VALUE_FORWARD)
        backwardValue = self.getParameterValue(self.VALUE_BACKWARD)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        speedFieldName = self.getParameterValue(self.SPEED_FIELD)
        defaultSpeed = self.getParameterValue(self.DEFAULT_SPEED)
        tolerance = self.getParameterValue(self.TOLERANCE)

        fields = QgsFields()
        fields.append(QgsField('start', QVariant.String, '', 254, 0))
        fields.append(QgsField('end', QVariant.String, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 20, 7))

        writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(
            fields, QgsWkbTypes.LineString, layer.crs(), context)

        tmp = startPoint.split(',')
        startPoint = QgsPoint(float(tmp[0]), float(tmp[1]))
        tmp = endPoint.split(',')
        endPoint = QgsPoint(float(tmp[0]), float(tmp[1]))

        directionField = -1
        if directionFieldName is not None:
            directionField = layer.fields().lookupField(directionFieldName)
        speedField = -1
        if speedFieldName is not None:
            speedField = layer.fields().lookupField(speedFieldName)

        director = QgsVectorLayerDirector(layer, directionField, forwardValue,
                                          backwardValue, bothValue,
                                          defaultDirection)

        distUnit = iface.mapCanvas().mapSettings().destinationCrs().mapUnits()
        multiplier = QgsUnitTypes.fromUnitToUnitFactor(
            distUnit, QgsUnitTypes.DistanceMeters)
        if strategy == 0:
            strategy = QgsNetworkDistanceStrategy()
        else:
            strategy = QgsNetworkSpeedStrategy(speedField, defaultSpeed,
                                               multiplier * 1000.0 / 3600.0)
            multiplier = 3600

        director.addStrategy(strategy)
        builder = QgsGraphBuilder(
            iface.mapCanvas().mapSettings().destinationCrs(), True, tolerance)
        feedback.pushInfo(self.tr('Building graph...'))
        snappedPoints = director.makeGraph(builder, [startPoint, endPoint])

        feedback.pushInfo(self.tr('Calculating shortest path...'))
        graph = builder.graph()
        idxStart = graph.findVertex(snappedPoints[0])
        idxEnd = graph.findVertex(snappedPoints[1])

        tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
        if tree[idxEnd] == -1:
            raise GeoAlgorithmExecutionException(
                self.tr('There is no route from start point to end point.'))

        route = []
        cost = 0.0
        current = idxEnd
        while current != idxStart:
            cost += graph.edge(tree[current]).cost(0)
            route.append(
                graph.vertex(graph.edge(tree[current]).inVertex()).point())
            current = graph.edge(tree[current]).outVertex()

        route.append(snappedPoints[0])
        route.reverse()

        self.setOutputValue(self.TRAVEL_COST, cost / multiplier)

        feedback.pushInfo(self.tr('Writing results...'))
        geom = QgsGeometry.fromPolyline(route)
        feat = QgsFeature()
        feat.setFields(fields)
        feat['start'] = startPoint.toString()
        feat['end'] = endPoint.toString()
        feat['cost'] = cost / multiplier
        feat.setGeometry(geom)
        writer.addFeature(feat)
        del writer
Ejemplo n.º 27
0
    def testExportFeatures(self):
        """ Test exporting feature collections """

        fields = QgsFields()
        fields.append(QgsField("name", QVariant.String))
        fields.append(QgsField("cost", QVariant.Double))
        fields.append(QgsField("population", QVariant.Int))

        feature = QgsFeature(fields, 5)
        feature.setGeometry(QgsGeometry(QgsPoint(5, 6)))
        feature.setAttributes(['Valsier Peninsula', 6.8, 198])

        exporter = QgsJsonExporter()

        # single feature
        expected = """{ "type": "FeatureCollection",
    "features":[
{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}
]}"""
        self.assertEqual(exporter.exportFeatures([feature]), expected)

        # multiple features
        feature2 = QgsFeature(fields, 6)
        feature2.setGeometry(QgsGeometry(QgsPoint(7, 8)))
        feature2.setAttributes(['Henry Gale Island', 9.7, 38])

        expected = """{ "type": "FeatureCollection",
    "features":[
{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
},
{
   "type":"Feature",
   "id":6,
   "geometry":
   {"type": "Point", "coordinates": [7, 8]},
   "properties":{
      "name":"Henry Gale Island",
      "cost":9.7,
      "population":38
   }
}
]}"""
        self.assertEqual(exporter.exportFeatures([feature, feature2]), expected)
Ejemplo n.º 28
0
    def testJSONExporter(self):
        """ test converting features to GeoJSON """
        fields = QgsFields()
        fields.append(QgsField("name", QVariant.String))
        fields.append(QgsField("cost", QVariant.Double))
        fields.append(QgsField("population", QVariant.Int))

        feature = QgsFeature(fields, 5)
        feature.setGeometry(QgsGeometry(QgsPoint(5, 6)))
        feature.setAttributes(['Valsier Peninsula', 6.8, 198])

        exporter = QgsJsonExporter()

        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        # test with linestring for bbox inclusion
        l = QgsLineString()
        l.setPoints([QgsPoint(5, 6), QgsPoint(15, 16)])
        feature.setGeometry(QgsGeometry(QgsLineString(l)))

        expected = """{
   "type":"Feature",
   "id":5,
   "bbox":[5, 6, 15, 16],
   "geometry":
   {"type": "LineString", "coordinates": [ [5, 6], [15, 16]]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        # test that precision is respected
        feature.setGeometry(QgsGeometry(QgsPoint(5.444444444, 6.333333333)))
        exporter.setPrecision(3)
        self.assertEqual(exporter.precision(), 3)
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5.444, 6.333]},
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)
        feature.setGeometry(QgsGeometry(QgsPoint(5, 6)))
        exporter.setPrecision(17)

        # test that attribute subset is respected
        exporter.setAttributes([0, 2])
        self.assertEqual(exporter.attributes(), [0, 2])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        exporter.setAttributes([1])
        self.assertEqual(exporter.attributes(), [1])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "cost":6.8
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)
        exporter.setAttributes([])

        # text excluding attributes

        exporter.setExcludedAttributes([1])
        self.assertEqual(exporter.excludedAttributes(), [1])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula",
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        exporter.setExcludedAttributes([1, 2])
        self.assertEqual(exporter.excludedAttributes(), [1, 2])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "name":"Valsier Peninsula"
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        exporter.setExcludedAttributes([0, 1, 2])
        self.assertEqual(exporter.excludedAttributes(), [0, 1, 2])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":null
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        # test that excluded attributes take precedence over included

        exporter.setAttributes([1, 2])
        exporter.setExcludedAttributes([0, 1])
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":{
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        exporter.setAttributes([])
        exporter.setExcludedAttributes([])

        # test excluding geometry
        exporter.setIncludeGeometry(False)
        self.assertEqual(exporter.includeGeometry(), False)
        feature.setGeometry(QgsGeometry(QgsLineString(l)))

        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":null,
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)
        exporter.setIncludeGeometry(True)

        feature.setGeometry(QgsGeometry(QgsPoint(5, 6)))

        # test excluding attributes
        exporter.setIncludeAttributes(False)
        self.assertEqual(exporter.includeAttributes(), False)
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":
   {"type": "Point", "coordinates": [5, 6]},
   "properties":null
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)

        exporter.setIncludeGeometry(False)
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":null,
   "properties":null
}"""
        self.assertEqual(exporter.exportFeature(feature), expected)
        exporter.setIncludeAttributes(True)

        # test overriding ID
        expected = """{
   "type":"Feature",
   "id":29,
   "geometry":null,
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198
   }
}"""
        self.assertEqual(exporter.exportFeature(feature, id=29), expected)

        # test injecting extra attributes
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":null,
   "properties":{
      "name":"Valsier Peninsula",
      "cost":6.8,
      "population":198,
      "extra":"val1",
      "extra2":2
   }
}"""
        self.assertEqual(exporter.exportFeature(feature, extraProperties={"extra": "val1", "extra2": 2}), expected)

        exporter.setIncludeAttributes(False)
        expected = """{
   "type":"Feature",
   "id":5,
   "geometry":null,
   "properties":{
      "extra":"val1",
      "extra2":{"nested_map":5,
"nested_map2":"val"},
      "extra3":[1,2,3]
   }
}"""
        expected2 = """{
   "type":"Feature",
   "id":5,
   "geometry":null,
   "properties":{
      "extra":"val1",
      "extra2":{"nested_map":5,"nested_map2":"val"},
      "extra3":[1,2,3]
   }
}"""
        exp_f = exporter.exportFeature(feature, extraProperties={"extra": "val1", "extra2": {"nested_map": 5, "nested_map2": "val"}, "extra3": [1, 2, 3]})
        self.assertTrue(exp_f == expected or exp_f == expected2)
        exporter.setIncludeGeometry(True)
Ejemplo n.º 29
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT, context)

        fields = source.fields()
        x_field_index = fields.lookupField(
            self.parameterAsString(parameters, self.XFIELD, context))
        y_field_index = fields.lookupField(
            self.parameterAsString(parameters, self.YFIELD, context))
        z_field_index = -1
        if self.parameterAsString(parameters, self.ZFIELD, context):
            z_field_index = fields.lookupField(
                self.parameterAsString(parameters, self.ZFIELD, context))
        m_field_index = -1
        if self.parameterAsString(parameters, self.MFIELD, context):
            m_field_index = fields.lookupField(
                self.parameterAsString(parameters, self.MFIELD, context))

        wkb_type = QgsWkbTypes.Point
        if z_field_index >= 0:
            wkb_type = QgsWkbTypes.addZ(wkb_type)
        if m_field_index >= 0:
            wkb_type = QgsWkbTypes.addM(wkb_type)

        target_crs = self.parameterAsCrs(parameters, self.TARGET_CRS, context)

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields, wkb_type,
                                               target_crs)

        request = QgsFeatureRequest().setFlags(QgsFeatureRequest.NoGeometry)
        features = source.getFeatures()
        total = 100.0 / source.featureCount() if source.featureCount() else 0

        for current, feature in enumerate(features):
            if feedback.isCanceled():
                break

            feedback.setProgress(int(current * total))
            attrs = feature.attributes()

            try:
                x = float(attrs[x_field_index])
                y = float(attrs[y_field_index])

                point = QgsPoint(x, y)

                if z_field_index >= 0:
                    try:
                        point.addZValue(float(attrs[z_field_index]))
                    except:
                        point.addZValue(0.0)

                if m_field_index >= 0:
                    try:
                        point.addMValue(float(attrs[m_field_index]))
                    except:
                        point.addMValue(0.0)

                feature.setGeometry(QgsGeometry(point))
            except:
                pass  # no geometry

            sink.addFeature(feature)

        return {self.OUTPUT: dest_id}
Ejemplo n.º 30
0
    def processAlgorithm(self, parameters, context, feedback):
        uavImage = self.parameterAsRasterLayer(parameters, self.INPUT, context)
        feedback.pushInfo(self.tr('Processing image source: ')+self.tr(uavImage.source()))

        sourceCRS = self.parameterAsCrs(parameters, self.SOURCE_CRS, context)
        if sourceCRS is None or not sourceCRS.isValid():
            sourceCRS = uavImage.crs()

        destinationCRS = self.parameterAsCrs(parameters, self.DESTINATION_CRS, context)
        if destinationCRS is None or not destinationCRS.isValid():
            feedback.pushInfo(self.tr('Getting destination CRS from source image'))
            destinationCRS = sourceCRS

        feedback.pushInfo(self.tr('Source CRS is: ')+self.tr(sourceCRS.authid()))
        feedback.pushInfo(self.tr('Destination CRS is: ')+self.tr(destinationCRS.authid()))

        # set fields for footprint and nadir vectors
        fields = QgsFields()
        # fields.append(QgsField('gimball_pitch', QVariant.Double))
        # fields.append(QgsField('gimball_roll', QVariant.Double))
        # fields.append(QgsField('gimball_jaw', QVariant.Double))
        # fields.append(QgsField('relative_altitude', QVariant.Double))
        # fields.append(QgsField('image', QVariant.String))
        # fields.append(QgsField('camera_model', QVariant.String))
        # fields.append(QgsField('camera_vertical_FOV', QVariant.Double))
        # fields.append(QgsField('camera_horizontal_FOV', QVariant.Double))

        # (footprintSink, footprint_dest_id) = self.parameterAsSink(
        #     parameters,
        #     self.OUTPUT_FOOTPRINT,
        #     context,
        #     fields,
        #     QgsWkbTypes.Polygon,
        #     destinationCRS)
        # if footprintSink is None:
        #     raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT_FOOTPRINT))

        (nadirSink, nadir_dest_id) = self.parameterAsSink(
            parameters,
            self.OUTPUT_NADIR,
            context,
            fields,
            QgsWkbTypes.Point,
            destinationCRS)
        if nadirSink is None:
            raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT_NADIR))

        horizontalFOV = self.parameterAsDouble(parameters, self.HORIZONTAL_FOV, context)
        verticalFOV = self.parameterAsDouble(parameters, self.VERTICAL_FOV, context)
        useImageRatio = self.parameterAsBoolean(parameters, self.USE_IMAGE_RATIO_FOR_VERTICAL_FOV, context)
        verticalFOV_multiplier = self.parameterAsDouble(parameters, self.VERTICAL_FOV_MULTIPLIER, context)

        nadirToBottomOffset = self.parameterAsDouble(parameters, self.NADIR_TO_BOTTOM_OFFSET, context)
        nadirToupperOffset = self.parameterAsDouble(parameters, self.NADIR_TO_UPPPER_OFFSET, context)

        # extract exif and XMP data
        try:
            gdal.UseExceptions()
            dataFrame = gdal.Open(uavImage.source(), gdal.GA_ReadOnly)
            domains = dataFrame.GetMetadataDomainList()

            # get exif metadata
            exifTags = dataFrame.GetMetadata()
            for key, value in exifTags.items():
                #print(key, ':', value)
                pass

            # select metadata from XMP domain only
            droneMetadata = {}
            for domain in domains:
                metadata = dataFrame.GetMetadata(domain)

                # skip not relevant tags
                if isinstance(metadata, dict):
                    for key, value in metadata.items():
                        #print(domain, "--", key, ":", value)
                        pass

                # probably XMPs
                if isinstance(metadata, list):
                    if domain == 'xml:XMP':
                        # parse xml
                        root = ElementTree.XML(metadata[0])
                        xmldict = XmlDictConfig(root)

                        # skip first element containing only description and domain info
                        subdict = list(xmldict.values())[0]

                        # get XMP tags
                        subdict = list(subdict.values())[0]
                        # parse XMP stuffs removing head namespace in the key 
                        # e.g.
                        #    {http://www.dji.com/drone-dji/1.0/}AbsoluteAltitude
                        # become
                        #    AbsoluteAltitude
                        for key, value in subdict.items():
                            #print(domain, '--', key, value)
                            key = key.split('}')[1]
                            droneMetadata[key] = value

        except Exception as ex:
            raise QgsProcessingException(str(ex))
        
        # extract all important tagged information about the image

        # get image lat/lon that will be the coordinates of nadir point
        # converted to destination CRS
        lat = _convert_to_degress(exifTags['EXIF_GPSLatitude'])
        emisphere = exifTags['EXIF_GPSLatitudeRef']
        lon = _convert_to_degress(exifTags['EXIF_GPSLongitude'])
        lonReference = exifTags['EXIF_GPSLongitudeRef']

        if emisphere == 'S':
            lat = -lat
        if lonReference == 'W':
            lon = -lon

        exifDateTime = exifTags['EXIF_DateTime']
        feedback.pushInfo("EXIF_DateTime: "+exifDateTime)

        exifImageWidth = exifTags['EXIF_PixelXDimension']
        exifImageLength = exifTags['EXIF_PixelYDimension']
        imageRatio = float(exifImageWidth)/float(exifImageLength)
        feedback.pushInfo("EXIF_PixelXDimension: "+exifImageWidth)
        feedback.pushInfo("EXIF_PixelYDimension: "+exifImageLength)
        feedback.pushInfo("Image ratio: "+str(imageRatio))

        # drone especific metadata
        droneMaker = exifTags['EXIF_Make']
        droneModel = exifTags['EXIF_Model']
        feedback.pushInfo("EXIF_Make: "+droneMaker)
        feedback.pushInfo("EXIF_Model: "+droneModel)

        # drone maker substitute XMP drone dictKey
        dictKey = droneMaker

        relativeAltitude = float(droneMetadata['RelativeAltitude'])
        feedback.pushInfo(self.tr("XMP {}:RelativeAltitude: ".format(dictKey))+str(relativeAltitude))

        gimballRoll = float(droneMetadata['GimbalRollDegree'])
        gimballPitch = float(droneMetadata['GimbalPitchDegree'])
        gimballYaw = float(droneMetadata['GimbalYawDegree'])
        feedback.pushInfo("XMP {}:GimbalRollDegree: ".format(dictKey)+str(gimballRoll))
        feedback.pushInfo("XMP {}:GimbalPitchDegree: ".format(dictKey)+str(gimballPitch))
        feedback.pushInfo("XMP {}:GimbalYawDegree: ".format(dictKey)+str(gimballYaw))

        flightRoll = float(droneMetadata['FlightRollDegree'])
        flightPitch = float(droneMetadata['FlightPitchDegree'])
        flightYaw = float(droneMetadata['FlightYawDegree'])
        feedback.pushInfo("XMP {}:FlightRollDegree: ".format(dictKey)+str(flightRoll))
        feedback.pushInfo("XMP {}:FlightPitchDegree: ".format(dictKey)+str(flightPitch))
        feedback.pushInfo("XMP {}:FlightYawDegree: ".format(dictKey)+str(flightYaw))

        feedback.pushInfo(self.tr("Horizontal FOV: ")+str(horizontalFOV))
        if useImageRatio:
            verticalFOV = (horizontalFOV/imageRatio)*verticalFOV_multiplier
            feedback.pushInfo(self.tr("Vertical FOV basing on image ratio: ")+str(verticalFOV))
        else:
            feedback.pushInfo(self.tr("Vertical FOV: ")+str(verticalFOV))

        # do calculation inspired by:
        # https://photo.stackexchange.com/questions/56596/how-do-i-calculate-the-ground-footprint-of-an-aerial-camera
        # distance of the nearest point to nadir (bottom distance)
        bottomDistance = relativeAltitude*(math.tan(math.radians(90 - gimballPitch - 0.5*verticalFOV)))
        # distance of the farest point to nadir (upper distance)
        upperDistance = relativeAltitude*(math.tan(math.radians(90 - gimballPitch + 0.5*verticalFOV)))

        feedback.pushInfo(self.tr("Northing (degree): ")+str(gimballYaw))
        feedback.pushInfo(self.tr("Nadir to bottom distance (metre): ")+str(bottomDistance))
        feedback.pushInfo(self.tr("Nadir to upper distance (metre): ")+str(upperDistance))

        # populate nadir layer
        droneLocation = QgsPoint(lon, lat)
        tr = QgsCoordinateTransform(sourceCRS, destinationCRS, QgsProject.instance())
        droneLocation.transform(tr)
        feedback.pushInfo(self.tr("Nadir coordinates (lon, lat): ")+'{}, {}'.format(droneLocation.x(), droneLocation.y()))

        nadirGeometry = QgsGeometry.fromPointXY(QgsPointXY(droneLocation.x(), droneLocation.y()))
        feature = QgsFeature()
        feature.setGeometry(nadirGeometry)
        nadirSink.addFeature(feature, QgsFeatureSink.FastInsert)

        # create a memory layer with nadir point to be input to "native:wedgebuffers" algorithm
        # it's not possible to use directly the FeatureSink becaseu can't be accepted by processing.run.
        # the reason is that a generic sink can be also NOT a layer but a more generic sink where features
        # can't be recovered.
        tempNadirLayer = QgsVectorLayer('Point?crs={}'.format(destinationCRS.authid()), 'tempNadirLayer', 'memory' )
        provider = tempNadirLayer.dataProvider()
        feature = QgsFeature()
        feature.setGeometry(nadirGeometry)
        provider.addFeatures([feature])

        # create polygon using wedge buffer processign algorithm
        parameters = {
            'INPUT': tempNadirLayer,
            'AZIMUTH': gimballYaw,
            'WIDTH': horizontalFOV,
            'OUTER_RADIUS': abs(bottomDistance) + nadirToBottomOffset,
            'INNER_RADIUS': abs(upperDistance) + nadirToupperOffset,
            'OUTPUT': parameters[self.OUTPUT_FOOTPRINT]
        }
        wedge_buffer_result = processing.run("native:wedgebuffers", 
                                            parameters,
                                            is_child_algorithm=True,
                                            context = context,
                                            feedback = feedback)

        # Return the results
        results = {
            self.OUTPUT_FOOTPRINT: wedge_buffer_result['OUTPUT'],
            self.OUTPUT_NADIR: nadir_dest_id,
        }
        return results
Ejemplo n.º 31
0
    def processAlgorithm(self, parameters, context, feedback):
        source = self.parameterAsSource(parameters, self.INPUT_VECTOR, context)

        raster_layer = self.parameterAsRasterLayer(parameters,
                                                   self.INPUT_RASTER, context)
        rasterPath = raster_layer.source()

        rasterDS = gdal.Open(rasterPath, gdal.GA_ReadOnly)
        geoTransform = rasterDS.GetGeoTransform()

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))
        fields.append(QgsField('poly_id', QVariant.Int, '', 10, 0))
        fields.append(QgsField('point_id', QVariant.Int, '', 10, 0))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               QgsWkbTypes.Point,
                                               raster_layer.crs())

        outFeature = QgsFeature()
        outFeature.setFields(fields)

        fid = 0
        polyId = 0
        pointId = 0

        features = source.getFeatures(QgsFeatureRequest().setDestinationCrs(
            raster_layer.crs()))
        total = 100.0 / source.featureCount() if source.featureCount() else 0
        for current, f in enumerate(features):
            if feedback.isCanceled():
                break

            if not f.hasGeometry():
                continue

            geom = f.geometry()
            bbox = geom.boundingBox()

            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startRow,
             startColumn) = raster.mapToPixel(xMin, yMax, geoTransform)
            (endRow, endColumn) = raster.mapToPixel(xMax, yMin, geoTransform)

            # use prepared geometries for faster intersection tests
            engine = QgsGeometry.createGeometryEngine(geom.constGet())
            engine.prepareGeometry()

            for row in range(startRow, endRow + 1):
                for col in range(startColumn, endColumn + 1):
                    if feedback.isCanceled():
                        break

                    (x, y) = raster.pixelToMap(row, col, geoTransform)
                    point = QgsPoint(x, y)

                    if engine.contains(point):
                        outFeature.setGeometry(QgsGeometry(point))
                        outFeature['id'] = fid
                        outFeature['poly_id'] = polyId
                        outFeature['point_id'] = pointId

                        fid += 1
                        pointId += 1

                        sink.addFeature(outFeature, QgsFeatureSink.FastInsert)

            pointId = 0
            polyId += 1

            feedback.setProgress(int(current * total))

        return {self.OUTPUT: dest_id}
Ejemplo n.º 32
0
 def testQgsPointRepr(self):
     p = QgsPoint(123.456, 987.654, 100)
     self.assertTrue(p.__repr__().startswith('<QgsPoint: PointZ (123.456'))
    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        GTFSDir = self.dlg.GTFSLocation.text()
        StopsFile = self.dlg.StopsFile.text()
        stopID = self.dlg.stopID.text()
        ###StopsShapefileName = self.dlg.StopsShapefileName.text()
        StopsShapefileName = "stops"
        AddToMapCanvas = False
        ##GenerateTransitServiceData = True
        SkipCalculationServiceData = False
        TrailheadData_shp = self.dlg.TrailheadData.text()
        BufferDistance = self.dlg.BufferDistance.text()
        th_id_field = self.dlg.th_id_field.text()
        th_name_field = self.dlg.th_name_field.text()
        outputGeoJSON = self.dlg.outputGeoJSON.text()
        PostGISExpr = self.dlg.tbPostGISExpr.text()		
        AddToMapCanvas = self.dlg.cbAddToMapCanvas.isChecked() # returns True if checked
        SkipCalculationServiceData = self.dlg.SkipCalculationServiceData.isChecked() # returns True if checked
        ###trailBufferShpName = self.dlg.trailBufferShpName.text()
        #in_format = []
        #in_format.append("Shapefile")
        #in_format.append("PostGIS")
        #self.dlg.comboBox.addItems(in_format)		
        trailBufferShpName = "trailBuff"
        working_dir_name = self.dlg.working_dir.text()
        #
        ##shapefile_th = self.dlg.checkBoxShapefile.isChecked() # returns True if checked
        ##postGIS_th = self.dlg.checkBoxPostGIS.isChecked()
        #
        shapefile_th = self.dlg.radioButtonShapefile.isChecked() # returns True if checked
        postGIS_th = self.dlg.radioButtonPostGIS.isChecked()
        #
        host_name = self.dlg.host_name.text()
        port = self.dlg.port.text()
        database_name = self.dlg.database_name.text()
        uname = self.dlg.uname.text()
        password = self.dlg.password.text()
        postGIS_table_name = self.dlg.postGIS_table_name.text()
        #
        InputDataSpecified = False
        if shapefile_th:
            InputDataSpecified = True
        if postGIS_th:
            InputDataSpecified = True
        #postGIS_th = True
        #shapefile_th = True		
        working_dir = os.path.join(GTFSDir, working_dir_name)
        #if working_dir doesn't exist, create it
        if not os.path.exists(working_dir):
          	os.makedirs(working_dir)   
        TATShp = os.path.join(working_dir, "TAToutput.shp")
        TATdShp = os.path.join(working_dir, "TATdoutput.shp")
        THShp = os.path.join(working_dir, "TH.shp")
        #
        DList_TrailsStops = defaultdict(list)
        #
        #####output_shp = 
        ##output_file = open(filename, 'w')
        # See if OK was pressed
        if result:
            if InputDataSpecified:
				start_time = datetime.datetime.now().replace(microsecond=0)
				stop_id = "UNK"
				stop_name = "UNK"
				stop_lat = "UNK"
				stop_lon = "UNK"
				c_stop_id = 0
				c_stop_name = 0
				c_stop_lat = 0
				c_stop_lon = 0
				counter = 0
				text_file = os.path.join(GTFSDir, StopsFile)
				#text_file = 'C:/UWGIS/Geog569/Data/Test/stops.txt' 
				##
				EPSG_code = 4326
				EPSG_code_WM = 3857
				crsSrc = QgsCoordinateReferenceSystem(4326)    # WGS 84
				crsDest = QgsCoordinateReferenceSystem(3857)  # WGS 84 / Web Mercator
				xform = QgsCoordinateTransform(crsSrc, crsDest)
				rev_xform = QgsCoordinateTransform(crsDest, crsSrc)
				##
				#StopsShapefilePath = os.path.join(GTFSDir, StopsShapefileName + ".shp")
				#StopsShapefileBufferPath = os.path.join(GTFSDir, StopsShapefileName + "BUFF.shp")
				#StopsShapefilePathWM = os.path.join(GTFSDir, StopsShapefileName + "WM.shp")
				StopsShapefilePath = os.path.join(working_dir, StopsShapefileName + ".shp")
				StopsShapefileBufferPath = os.path.join(working_dir, StopsShapefileName + "BUFF.shp")
				StopsShapefilePathWM = os.path.join(working_dir, StopsShapefileName + "WM.shp")
				##
				spatialReference = osgeo.osr.SpatialReference() #will create a spatial reference locally to tell the system what the reference will be
				spatialReference.ImportFromEPSG(int(EPSG_code)) #here we define this reference to be the EPSG code
				driver = osgeo.ogr.GetDriverByName('ESRI Shapefile') # will select the driver for our shp-file creation.
				##
				index = 0
				spatialReferenceWM = osgeo.osr.SpatialReference() #will create a spatial reference locally to tell the system what the reference will be			
				spatialReferenceWM.ImportFromEPSG(int(EPSG_code_WM)) #here we define this reference to be the EPSG code
				driver = osgeo.ogr.GetDriverByName('ESRI Shapefile') # will select the driver for our shp-file creation.
				# create layer
				#if shapefile_th_rb:
				#    print "USING Shapefiles!"
				#if postGIS_th_rb:
				#    print "USING PostGIS!"			
				##vl = QgsVectorLayer("Point", "stop_points", "memory")
				vl = QgsVectorLayer("Point?crs=EPSG:3857", "stop_points", "memory")
				##vl.spatialReference
				pr = vl.dataProvider()
				#
				# changes are only possible when editing the layer
				vl.startEditing()
				# add fields
				pr.addAttributes([QgsField("stop_id", QVariant.String),QgsField("stop_name", QVariant.Int),QgsField("stop_lat", QVariant.Double),QgsField("stop_lon", QVariant.Double)])
				index = 0
				###print "two"
				fieldnames = []
				stop_lat = 0
				stop_lon = 0
				c_stop_id = 0
				c_stop_name = 0
				c_stop_lat = 0
				c_stop_lon = 0
				with open(text_file, 'r') as f:
					first_line = f.readline()
				fl = first_line.split(",")
				counter = 0
				for f in fl:
					fieldnames.append(f)
					#for f in fl:
					#print f
					if f == "stop_id":
						c_stop_id = counter
					if f == "stop_name":
						c_stop_name = counter
					if f == "stop_lat":
						c_stop_lat = counter
						#print "stop_lat is in column ", c_stop_lat
						#print c_stop_lat
					if f == "stop_lon":
						c_stop_lon = counter
						#print "stop_lon is in column ", c_stop_lon
						##print c_stop_lon
						##print "three"
					counter = counter + 1
					#
				with open(text_file, 'r') as f:
					lines = f.readlines()
					for line in lines:
						h = '"'					
						if h in line:
							count = line.count(h)
							print "Removed quote from line" + str(count)
							while count > 0:
								#print [pos for pos, char in enumerate(line) if char == c]
								cc = [pos for pos, char in enumerate(line) if char == h]
								d = ','
								#print [pos for pos, char in enumerate(line) if char == d]
								dd = [pos for pos, char in enumerate(line) if char == d]
								startP = cc[0]
								endP = cc[1]
								for ddd in dd:
									if (ddd > startP) and (ddd < endP):
										extraCommaPos = ddd
										line1 = line[0:startP]  
										line2 = line[(startP + 1):extraCommaPos]
										line3 = line[(extraCommaPos + 1):(endP)]
										line4 = line[(endP + 1):-1]
										lineMod = line1 + line2 + line3 + line4
										#print line
										#print "Comma removed"
										#print lineMod
										line = lineMod
										count = line.count(h)
						l = str(line).split(",")
						if l[c_stop_id] != "stop_id":
							stop_id = l[c_stop_id]
						if l[c_stop_name] != "stop_name":
							stop_name = l[c_stop_name]
						if l[c_stop_lat] != "stop_lat":
							stop_lat = float(l[c_stop_lat])
						if l[c_stop_lon] != "stop_lon":
							stop_lon = float(l[c_stop_lon])
						if type(stop_lat) == float:
							if type (stop_lon) == float:
								fet = QgsFeature()
								stop_pt_WM = xform.transform(QgsPoint(stop_lon,stop_lat))
								###print "Transformed point:", stop_pt_WM
								#fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(stop_lon, stop_lat)))
								fet.setGeometry(QgsGeometry.fromPoint(stop_pt_WM))
								fet.setAttributes([stop_id, stop_name, stop_lat, stop_lon])
								pr.addFeatures([fet])
								vl.commitChanges()
				#
				# add layer to the legend
				stops_extent = vl.extent()
				xmin = stops_extent.xMinimum()			            
				ymin = stops_extent.yMinimum()
				xmax = stops_extent.xMaximum()
				ymax = stops_extent.yMaximum()
				##QgsMapLayerRegistry.instance().addMapLayer(vl)
				#
				# Add trailheads from postGIS if postGIS_th = True 			
				#
				if postGIS_th:
					uri = QgsDataSourceURI()
					# set host name, port, database name, username and password
					#uri.setConnection("localhost", "5432", "dbname", "johny", "xxx")
					uri.setConnection(host_name, port, database_name, uname, password)
					print "made PostGIS connection successfully"
					# set database schema, table name, geometry column and optionally
					# subset (WHERE clause)
					#uri.setDataSource("public", "roads", "the_geom", "cityid = 2643")
					#uri.setDataSource("public", postGIS_table_name, "geom", PostGISExpr)
					uri.setDataSource("public", postGIS_table_name, "geom", PostGISExpr)
					#
					#vlayer = QgsVectorLayer(uri.uri(), "layer name you like", "postgres")
					DB_TH_layer = QgsVectorLayer(uri.uri(), "DB_TH_layer", "postgres")
					if AddToMapCanvas:
						QgsMapLayerRegistry.instance().addMapLayer(DB_TH_layer)
					#
					stop_extent = QgsVectorLayer("Polygon?crs=EPSG:4326", "stop_extent", "memory")
					pr = stop_extent.dataProvider()
					stop_extent.startEditing()
					#
					fet = QgsFeature()
					#fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(stop_lon, stop_lat)))
					#
					stop_ex_SW = rev_xform.transform(QgsPoint(xmin, ymin))
					stop_ex_NW = rev_xform.transform(QgsPoint(xmin, ymax))
					stop_ex_NE = rev_xform.transform(QgsPoint(xmax, ymax))
					stop_ex_SE = rev_xform.transform(QgsPoint(xmax, ymin))
					print "Stops layer extent (lower):", stop_ex_SW
					print "Stops layer extent (upper):", stop_ex_NE			
					##fet.setGeometry(QgsGeometry.fromPolygon([[QgsPoint(xmin,ymin),QgsPoint(xmin,ymax), QgsPoint(xmax,ymax), QgsPoint(xmax,ymin), QgsPoint(xmin,ymin)]]))
					fet.setGeometry(QgsGeometry.fromPolygon([[stop_ex_SW, stop_ex_NW, stop_ex_NE, stop_ex_SE, stop_ex_SW]]))
					pr.addFeatures([fet])
					stop_extent.commitChanges()
					if AddToMapCanvas:
						QgsMapLayerRegistry.instance().addMapLayer(stop_extent)
					#
					print "overlay points! - using extent from stops"
					overlayAnalyzer = QgsOverlayAnalyzer()
					overlayAnalyzer.intersection(DB_TH_layer, stop_extent, THShp)
					TH_layer = QgsVectorLayer(THShp, "TH_layer", "ogr")
					if not TH_layer.isValid():
						print "TH.shp layer failed to load!"	
					########## this adds trailheads to the map canvas ########QgsMapLayerRegistry.instance().addMapLayer(TH_layer)
					iter = TH_layer.getFeatures()
					#for feature in iter:
					#    geomIn = feature.geometry()
					#    #print geom.vectorType()
					#    featgeom = geomIn.exportToWkt()
					#    print featgeom
					#    geom = QgsGeometry.fromWkt(featgeom)
					#    #print geom2 #= QgsGeometry.fromWkt(featgeom)
					#    #if geom.isMultipart:
					#    #    print "multi"
					#    feature_name = feature['name']
					#    feature_id = feature['FEAT_ID']
					#    print "geom.asPoint()"
					#    print geom.asPoint()
					#
				# add trailhead layer from shapefile if selected (assumes it is stored in WGS 84)
				#
				if shapefile_th:
					trailhead_layer = QgsVectorLayer(TrailheadData_shp, "trailhead_layer", "ogr")
					######### this adds trailsheads to map canvas############QgsMapLayerRegistry.instance().addMapLayer(trailhead_layer)
					if not trailhead_layer.isValid():
						print "trailhead layer failed to load!"
				# 
				# create trailhead layer in Web Mercator
				#
				vltWM = QgsVectorLayer("Point?crs=EPSG:3857", "trailhead_points_WM", "memory")
				prtWM = vltWM.dataProvider()
				#
				# changes - including adding fields - are only possible when editing the layer
				vltWM.startEditing()
				prtWM.addAttributes([QgsField("name", QVariant.String),QgsField("FEAT_ID", QVariant.Int)])
				#
				#  Get the features from the trailhead layer that is loaded, from shp or db
				#  and convert to a WM dataset
				#
				if shapefile_th:
					iter = trailhead_layer.getFeatures()
					print "using shape"
					for feature in iter:
						geom = feature.geometry()
						feature_name = feature['name']
						feature_id = feature['FEAT_ID']
						th_x = geom.asPoint().x()	
						th_y = geom.asPoint().y()
						print th_x, th_y
						trailhead_pt_WM = xform.transform(QgsPoint(geom.asPoint()))
						fet = QgsFeature()
						fet.setGeometry(QgsGeometry.fromPoint(trailhead_pt_WM))
						fet.setAttributes([feature_name, feature_id])
						prtWM.addFeatures([fet])
						vltWM.commitChanges()
				if postGIS_th:
					trailhead_layer = QgsVectorLayer(THShp, "trailhead_layer", "ogr")
					iter = trailhead_layer.getFeatures()
					print "using postGIS"
					for feature in iter:
						geomIn = feature.geometry()
						featgeom = geomIn.exportToWkt()
						#featgeom = featgeom.replace("MultiPoint", "POINT")					
						#featgeom = featgeom.replace("((", "(")					
						#featgeom = featgeom.replace("))", ")")					
						#featgeom = '"' + str(featgeom) + '"'
						geoString1 = featgeom.split('((')
						geoString2 = geoString1[1].split('))')
						#geoString22 = geoString2[0]	
						geoString = geoString2[0].split(' ')
						ptX = float(geoString[0])					                    
						ptY = float(geoString[1])
						#ptX = geoString[0]					
						#ptY = geoString[1]
						#geomString = '"POINT (' + str(ptX) + " " + str(ptY) + ')"'
						geomString = '"POINT (' + str(ptX) + " " + str(ptY) + ')"'
						#print geomString	
						#geom = QgsGeometry.fromWkt(geomString)
						geom = QgsGeometry.fromPoint(QgsPoint(ptX, ptY))
						#geom = QgsGeometry.fromWkt("POINT (-122.24501049999997804 47.86390650000004143)")
						###geom = feature.geometry()
						###feature_name = feature['name']
						###feature_id = feature['FEAT_ID']
						feature_name = feature[th_name_field]
						feature_id = feature[th_id_field]
						trailhead_pt_WM = xform.transform(QgsPoint(geom.asPoint()))
						fet = QgsFeature()
						fet.setGeometry(QgsGeometry.fromPoint(trailhead_pt_WM))
						fet.setAttributes([feature_name, feature_id])
						prtWM.addFeatures([fet])
						vltWM.commitChanges()
						###fet = QgsFeature()
						#####feature.asPoint()
						####print feature
						###fet.setGeometry(QgsGeometry.fromPoint(trailhead_pt_WM))
						###fet.setAttributes([feature_name, feature_id])
						###prtWM.addFeatures([fet])
						###vltWM.commitChanges()
						###fet.setGeometry(QgsGeometry.fromPoint(trailhead_pt_WM))
						###fet.setGeometry(geom)
						###fet.setAttributes([feature_name, feature_id])
						####print "geom"
						####print geom
						###trailhead_pt_WM = xform.transform(QgsPoint(geom.asPoint()))
						###prtWM.addFeatures([fet])
						###vltWM.commitChanges()
				#	
				#	Add WM trailheads to the map canvas
				#
				#print "PostGISExpr"
				#print PostGISExpr
				#if PostGISExpr == "":
				#	print "NO EXPR!"
				if AddToMapCanvas:
					QgsMapLayerRegistry.instance().addMapLayer(vltWM)
				#QgsMapLayerRegistry.instance().addMapLayer(vltWM)
				#	Buffer stops
				vltb = QgsVectorLayer("Point?crs=EPSG:3857", "trailhead_buffer_dissolved", "memory")
				#
				#QgsGeometryAnalyzer().dissolve(vlt, vltb, onlySelectedFeatures=False, uniqueIdField=-1, p=None)
				#	Buffer stops
				geometryanalyzer = QgsGeometryAnalyzer()
				geometryanalyzer.buffer(vltWM, StopsShapefileBufferPath + ".shp", int(BufferDistance), False, False, -1)
				trailheadBuffer_layer = QgsVectorLayer(StopsShapefileBufferPath + ".shp", "trailhead_buffer_layer", "ogr")
				if AddToMapCanvas:
				    QgsMapLayerRegistry.instance().addMapLayer(trailheadBuffer_layer)
				# 
				geometryanalyzer.buffer(vltWM, StopsShapefileBufferPath + "d.shp", int(BufferDistance), False, True, -1)
				#trailheadBufferd_layer = QgsVectorLayer(StopsShapefileBufferPath + "d.shp", "trailhead_buffer_d", "ogr")
				trailheadBufferd_layer = QgsVectorLayer(StopsShapefileBufferPath + "d.shp", "trailhead_buffer_d", "ogr")
				if AddToMapCanvas:
				    QgsMapLayerRegistry.instance().addMapLayer(trailheadBufferd_layer)
				# 
				# overlay - using dissolved buffer
				# 
				print "overlay points! - using dissolved buffers"
				overlayAnalyzer = QgsOverlayAnalyzer()
				#overlayAnalyzer.intersection(vl, vlt, "C:/UWGIS/Geog569/Data/Test/TAToutput.shp")
				overlayAnalyzer.intersection(vl, trailheadBufferd_layer, TATdShp)
				TATd_layer = QgsVectorLayer(TATdShp, "TransitStops_diss_layer", "ogr")
				###TATd_layer = QgsVectorLayer(TATdShp, "TrAccTrailheads_diss_layer", "ogr")
				if not TATd_layer.isValid():
					print "TATd layer failed to load!"	
				if AddToMapCanvas:
				    QgsMapLayerRegistry.instance().addMapLayer(TATd_layer)
				iter = TATd_layer.getFeatures()
				stopList = []
				for feature in iter:
					# retrieve every feature with its geometry and attributes
					feature_id = feature[stopID]
					stopList.append(feature_id)				
					#feature_id = feature['FEAT_ID']
				#for s in stopList:
				#	print s
				#
				# overlay - using the indivdual buffered points
				# this can be used to compute distance between trailhaeds and each stop in its buffer
				#				
				print "overlay points! - using dissolved buffers"
				overlayAnalyzer = QgsOverlayAnalyzer()
				#overlayAnalyzer.intersection(vl, vlt, "C:/UWGIS/Geog569/Data/Test/TAToutput.shp")
				overlayAnalyzer.intersection(vl, trailheadBuffer_layer, TATShp)
				TAT_layer = QgsVectorLayer(TATShp, "TransitStops_NonDissolved_layer", "ogr")
				#TAT_layer = QgsVectorLayer(TATShp, "TrAccTrailheads_layer", "ogr")
				if not TAT_layer.isValid():
					print "TAT layer failed to load!"	
				if AddToMapCanvas:
				    QgsMapLayerRegistry.instance().addMapLayer(TAT_layer)
				iter = TAT_layer.getFeatures()
				THstopList = []
				for feature in iter:
					# retrieve every feature with its geometry and attributes
					###trailhead_name = feature['name']
					trailhead_id = feature[th_id_field]				
					feature_id = feature[th_id_field]
					TH_Stop = str(trailhead_id) + ":" +  str(feature_id)				
					#print feature['stop_id']
					THstopList.append(TH_Stop)
					DList_TrailsStops[trailhead_id].append(feature_id)
					#feature_id = feature['FEAT_ID']
				#for s in THstopList:
				#	print s
				#for s in DList_TrailsStops:
				#	print s, DList_TrailsStops[s]
				#	#print DList_TrailsStops[s]
				print xmin, ymin, xmax, ymax
				fet = QgsFeature()
				stop_pt_WM = rev_xform.transform(QgsPoint(xmin, ymin))
				print "Stops layer extent (lower):", stop_pt_WM
				#fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(stop_lon, stop_lat)))
				stop_pt_WM = rev_xform.transform(QgsPoint(xmax, ymax))
				print "Stops layer extent (upper):", stop_pt_WM
				print self.plugin_dir
				sys.argv = [GTFSDir, stopList]
				missing_files = []
				all_files_present = True
				fn_stop_times = "stop_times.txt"
				f_stop_times = os.path.join(GTFSDir, fn_stop_times)
				if not os.path.exists(f_stop_times):
					all_files_present = False   
					missing_files.append(fn_stop_times)   
				fn_stops = "stops.txt"
				f_stops = os.path.join(GTFSDir, fn_stops)
				if not os.path.exists(f_stops):
					all_files_present = False   
					missing_files.append(fn_stops)   
				fn_trips = "trips.txt"
				f_trips = os.path.join(GTFSDir, fn_trips)
				if not os.path.exists(f_trips):
					all_files_present = False   
					missing_files.append(fn_trips)   
				fn_routes = "routes.txt"
				f_routes = os.path.join(GTFSDir, fn_routes)
				if not os.path.exists(f_routes):
					all_files_present = False   
					missing_files.append(fn_routes)   
				fn_agency = "agency.txt"
				f_agency = os.path.join(GTFSDir, fn_agency)
				if not os.path.exists(f_agency):
					all_files_present = False   
					missing_files.append(fn_agency)   
				#if working_dir doesn't exist, create it
				###if os.path.exists(f_stop_times):			
				if all_files_present:
				    if not SkipCalculationServiceData:
					    print "starting service analysis...this might take some time"   
					    SummarizeTransitService = os.path.join(self.plugin_dir, "SummarizeTransitService.py")
					    execfile(SummarizeTransitService)
				else:
					print "The GTFS appears to be incomplete.  The following files seem to be missing."   				
					#print "The GTFS appears to be incomplete.  Check that all parts are present and try again."   				
					for f in missing_files:
						print f
					##create empty dictionary
				##  BEGIN DISTANCE CODE!
				distance_dictionary = {}
				DList_TH_stops = defaultdict(list)
				### (temporarily) set ref to TAT in case
				##Enter data into Dictionary
				iter = vltWM.getFeatures()
				#iter = TAToutput.getFeatures()
				##THstopList = []
				for feature in iter:
					##identifies attributes for future use
					#print "Feature ID %d: " % feature.id()
					trailhead_id = feature[str('FEAT_ID')]
					#print trailhead_id
					geom = feature.geometry()
					th_x = geom.asPoint().x()	
					th_y = geom.asPoint().y()
					th_point = QgsPoint(th_x,th_y)
					#transit_stop_id = feature['stop_id']
					iter_stops = TAT_layer.getFeatures() ###[new layer here?]
					for stop_feature in iter_stops:
						stop_id = stop_feature[str('stop_id')]
						th_id = stop_feature[str('FEAT_ID')]
						if th_id == trailhead_id:
							stop_geom = stop_feature.geometry()
							stop_id = stop_feature['stop_id']
							DList_TH_stops[th_id].append(stop_id)
							stop_x = stop_geom.asPoint().x()	
							stop_y = stop_geom.asPoint().y()
							s_point = QgsPoint(stop_x,stop_y)
							stop_distance = 0
							a = numpy.array(th_point)
							b = numpy.array(s_point)
							##stop_distance = numpy.sqrt(numpy.sum(a-b)**2)
							stop_distance =  math.sqrt(th_point.sqrDist(s_point))
							#print th_id
							#print stop_id
							#print stop_distance
							####print math.sqrt(th_point.sqrDist(s_point))
							th_stop = str(trailhead_id) + ":" + str(stop_id)
							distance_dictionary[th_stop] = stop_distance
							#if stop_distance < BufferDistance:
							#    distance_dictionary[th_stop] = stop_distance 		
				##outputGeoJSON
				vl_outTH = QgsVectorLayer("Point?crs=EPSG:4326", "stop_points", "memory")
				pr_outTH = vl_outTH.dataProvider()
				#
				# changes are only possible when editing the layer
				vl_outTH.startEditing()
				# add fields
				##pr_outTH.addAttributes([QgsField(th_id_field, QVariant.Int),QgsField(th_name_field, QVariant.String),QgsField("number_stops_nearby", QVariant.Int),QgsField("stops_near", QVariant.String),QgsField("stops_near_dist", QVariant.String)])
				pr_outTH.addAttributes([QgsField(th_id_field, QVariant.Int),QgsField(th_name_field, QVariant.String),QgsField("number_stops_nearby", QVariant.Int),QgsField("stops_near", QVariant.String),QgsField("stops_distances", QVariant.String)])
				index = 0
				iter = trailhead_layer.getFeatures()
				for feature in iter:
					geom = feature.geometry()
					feature_id = feature[th_id_field]
					feature_name = feature[th_name_field]
					#stops_near = str(DList_TH_stops[feature_id])
					num_stops_near = 0
					stops_near_in = DList_TH_stops[feature_id]
					stops_near = []
					for t in stops_near_in:
						#print t
						if not t in stops_near:
							stops_near.append(t)					
					stops_near.sort() 
					num_stops_near = len(stops_near)
					stops_near = str(stops_near)
					stops_near = stops_near.replace("u'", "")
					stops_near = stops_near.replace("'", "")
					stops_near = stops_near.replace("[", "")
					stops_near = stops_near.replace("]", "")
					#print stops_near
					dist_list = []
					stop_list = []
					stop_dist_list = []					
					stops_near_L = DList_TH_stops[feature_id]
					stops_near_L.sort()
					for s in stops_near_L:
						#print s
						k = str(feature_id) + ":" + str(s)
						dist = distance_dictionary[k]
						dist = int(dist)
						#stop_list_data = str(s) + ', '
						#dist_list_data = str(dist) + ', '
						dist_list_data = '{stop_id: ' + str(s) + ', distance ' + str(dist) + '}'
						if not dist_list_data in dist_list:
							dist_list.append(dist_list_data)					
							stop_list.append(s)
							stop_dist_list.append(dist)
					#dist_list.sort() 
					#trailhead_pt_WM = xform.transform(QgsPoint(geom.asPoint()))
					#print "dist_list"
					#print dist_list
					#dist_list = dist_list.replace("u'", "")
					#dist_list = dist_list.replace("'", "")
					dist_list = str(dist_list)
					dist_list = dist_list.replace("[", "")
					dist_list = dist_list.replace("]", "")
					dist_list = dist_list.replace("'", "")
					fet = QgsFeature()
					fet.setGeometry(geom)
					stop_list = str(stop_list)
					stop_list = stop_list.replace("u'", "'")
					stop_dist_list = str(stop_dist_list)
					#fet.setGeometry(QgsGeometry.fromPoint(geom))
					#fet.setAttributes([feature_id, feature_name, num_stops_near, stops_near, dist_list])
					fet.setAttributes([feature_id, feature_name, num_stops_near, stop_list, stop_dist_list])
					pr_outTH.addFeatures([fet])
					vl_outTH.commitChanges()
				GeoJSONfile = os.path.join(GTFSDir, outputGeoJSON)
				writeString = ""
				QgsVectorFileWriter.writeAsVectorFormat(vl_outTH, GeoJSONfile, "utf-8", None, "GeoJSON")
				#file = open(GeoJSONfile, "w")
				##file.write(fieldnames + "\n")
				#iter = vltWM.getFeatures()
				#for feature in iter:
				#	##identifies attributes for future use
				#	#print "Feature ID %d: " % feature.id()
				#	trailhead_id = feature[str('FEAT_ID')]
				#	#trailhead_id = feature['FEAT_ID']
				#	geom = feature.geometry()
				#    th_x = geom.asPoint().x()	
				#    th_y = geom.asPoint().y()
				#    writeLine = ''
				#    writeLine = '{ "type": "Feature", "properties": { "FEAT_ID": ' + str(trailhead_id) # + '\n'
				#    #writeLine = writeLine  + ' "STOPS_NEARBY": ' + str(DList_TH_stops[trailhead_id])  ###'\n'
				#    writeLine = writeLine  + ' "STOPS_NEARBY": ' + DList_TH_stops[trailhead_id]  ###'\n'
				#    writeLine = writeLine  + '				}, "geometry": { "type": "Point", "coordinates": [ '
				#    writeLine = writeLine  + str(th_x) + ' ' + str(th_x) + ' ] } }'
				#    writeLine = writeLine  + ', \n'
				#    writeString = writeString + writeLine 
				#file.write(writeString)
				#file.close()
				end_time = datetime.datetime.now().replace(microsecond=0)
				print(end_time-start_time)
				print "done"
            else:
				print "Input trailhead data was not specified"
Ejemplo n.º 34
0
def centroid_intersection_stats(band, geometry, pixel_offset_x, pixel_offset_y,
                                cells_x, cells_y, cell_size_x, cell_size_y,
                                raster_box, no_data):
    """Stats where centroid of each cell must intersect the polygon.

    :param band: A valid band from a raster layer.
    :type band: GDALRasterBand

    :param geometry: A valid polygon geometry.
    :type geometry: QgsGeometry

    :param pixel_offset_x: Left offset for raster window.
    :type pixel_offset_x: int

    :param pixel_offset_y: Offset from bottom for raster window.
    :type pixel_offset_y: int

    :param cells_x: Width of the raster window.
    :type cells_x: int

    :param cells_y: Height of the raster window.
    :type cells_y: int

    :param cell_size_x: Size in the x direction of a single cell.
    :type cell_size_x: float

    :param cell_size_y: Size in the y direction of a single cell.
    :type cell_size_y: float

    :param raster_box: Box defining the extents of the raster.
    :type raster_box: QgsRectangle

    :param no_data: Value for no data in the raster.
    :type no_data: int, float

    :returns: Sum, Count - sum of the values of all pixels and the count of
        pixels that intersect with the geometry.
    :rtype: (float, int)
    """
    cell_center_x = (raster_box.yMaximum() - pixel_offset_y * cell_size_y -
                     cell_size_y / 2)
    count = 0
    geometry_sum = 0
    buffer_x_size = cells_x
    buffer_y_size = 1  # read in a single row at a time
    cells_to_read_x = cells_x
    cells_to_read_y = 1  # read in a single row at a time

    for i in range(0, cells_y):
        scanline = band.ReadRaster(pixel_offset_x, pixel_offset_y + i,
                                   cells_to_read_x, cells_to_read_y,
                                   buffer_x_size, buffer_y_size,
                                   gdal.GDT_Float32)
        # Note that the returned scanline is of type string, and contains
        # xsize*4 bytes of raw binary floating point data. This can be
        # converted to Python values using the struct module from the standard
        # library:
        values = struct.unpack('f' * cells_to_read_x, scanline)
        # print values
        if values is None:
            continue

        cell_center_y = (raster_box.xMinimum() + pixel_offset_x * cell_size_x +
                         cell_size_x / 2)

        for j in range(0, cells_x):
            point = QgsPoint(cell_center_y, cell_center_x)
            if geometry.contains(point):
                if values[j] != no_data:
                    geometry_sum += values[j]
                    count += 1

            cell_center_y += cell_size_x
        # Move down one row
        cell_center_x -= cell_size_y

    return geometry_sum, count
Ejemplo n.º 35
0
from qgis.core import (
    QgsFeature,
    QgsGeometry,
    QgsPoint,
    QgsFeatureRequest,
    QgsExpression,
    QgsProject,
    QgsOfflineEditing,
)


# Tet features, fields: [id, name, geometry]
# "id" is used as a pk to retriev features by attribute
TEST_FEATURES = [
    (1, 'name 1', QgsPoint(9, 45)),
    (2, 'name 2', QgsPoint(9.5, 45.5)),
    (3, 'name 3', QgsPoint(9.5, 46)),
    (4, 'name 4', QgsPoint(10, 46.5)),
]

# Additional features for insert test
TEST_FEATURES_INSERT = [
    (5, 'name 5', QgsPoint(9.7, 45.7)),
    (6, 'name 6', QgsPoint(10.6, 46.6)),
]


class OfflineTestBase(object):

    """Generic test methods for all online providers"""
Ejemplo n.º 36
0
    def __init__(self, parent, rnavType, category, position_0, position_1, position_List, flagStr = None):
        QDialog.__init__(self, parent)
        self.flagStrName = flagStr
#         self.resize(326, 310)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setMargin(3)
        self.verticalLayout.setObjectName(("verticalLayout"))
        self.groupBox = QGroupBox(self)
        self.groupBox.setTitle((""))
        self.groupBox.setObjectName(("groupBox"))
        self.verticalLayout_2 = QVBoxLayout(self.groupBox)
        self.verticalLayout_2.setSpacing(0)
        self.verticalLayout_2.setMargin(3)
        self.verticalLayout_2.setObjectName(("verticalLayout_2"))
        self.groupBox_5 = QGroupBox(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.groupBox_5.sizePolicy().hasHeightForWidth())
        self.groupBox_5.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_5.setFont(font)
        self.groupBox_5.setObjectName(("groupBox_5"))
        self.horizontalLayout_19 = QHBoxLayout(self.groupBox_5)
        self.horizontalLayout_19.setSpacing(0)
        self.horizontalLayout_19.setMargin(0)
        self.horizontalLayout_19.setObjectName(("horizontalLayout_19"))
        self.frame_18 = QFrame(self.groupBox_5)
        self.frame_18.setFrameShape(QFrame.StyledPanel)
        self.frame_18.setFrameShadow(QFrame.Raised)
        self.frame_18.setObjectName(("frame_18"))
        self.verticalLayout_13 = QVBoxLayout(self.frame_18)
        self.verticalLayout_13.setSpacing(0)
        self.verticalLayout_13.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_13.setObjectName(("verticalLayout_13"))
        self.frame_19 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_19.sizePolicy().hasHeightForWidth())
        self.frame_19.setSizePolicy(sizePolicy)
        self.frame_19.setFrameShape(QFrame.StyledPanel)
        self.frame_19.setFrameShadow(QFrame.Raised)
        self.frame_19.setObjectName(("frame_19"))
        self.horizontalLayout_20 = QHBoxLayout(self.frame_19)
        self.horizontalLayout_20.setSpacing(0)
        self.horizontalLayout_20.setMargin(0)
        self.horizontalLayout_20.setObjectName(("horizontalLayout_20"))
        self.label_9 = QLabel(self.frame_19)
        self.label_9.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_9.setFont(font)
        self.label_9.setObjectName(("label_9"))
        self.horizontalLayout_20.addWidget(self.label_9)
        self.txtTHR_X = QLineEdit(self.frame_19)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtTHR_X.sizePolicy().hasHeightForWidth())
        self.txtTHR_X.setSizePolicy(sizePolicy)
        self.txtTHR_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_X.setFont(font)
        self.txtTHR_X.setObjectName(("txtTHR_X"))
        self.horizontalLayout_20.addWidget(self.txtTHR_X)
        self.verticalLayout_13.addWidget(self.frame_19)
        self.frame_20 = QFrame(self.frame_18)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_20.sizePolicy().hasHeightForWidth())
        self.frame_20.setSizePolicy(sizePolicy)
        self.frame_20.setFrameShape(QFrame.StyledPanel)
        self.frame_20.setFrameShadow(QFrame.Raised)
        self.frame_20.setObjectName(("frame_20"))
        self.horizontalLayout_21 = QHBoxLayout(self.frame_20)
        self.horizontalLayout_21.setSpacing(0)
        self.horizontalLayout_21.setMargin(0)
        self.horizontalLayout_21.setObjectName(("horizontalLayout_21"))
        self.label_10 = QLabel(self.frame_20)
        self.label_10.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_10.setFont(font)
        self.label_10.setObjectName(("label_10"))
        self.horizontalLayout_21.addWidget(self.label_10)
        self.txtTHR_Y = QLineEdit(self.frame_20)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtTHR_Y.sizePolicy().hasHeightForWidth())
        self.txtTHR_Y.setSizePolicy(sizePolicy)
        self.txtTHR_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtTHR_Y.setFont(font)
        self.txtTHR_Y.setObjectName(("txtTHR_Y"))
        self.horizontalLayout_21.addWidget(self.txtTHR_Y)
        self.verticalLayout_13.addWidget(self.frame_20)
        self.horizontalLayout_19.addWidget(self.frame_18)
        self.frame_21 = QFrame(self.groupBox_5)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_21.sizePolicy().hasHeightForWidth())
        self.frame_21.setSizePolicy(sizePolicy)
        self.frame_21.setMaximumSize(QSize(30, 70))
        self.frame_21.setFrameShape(QFrame.StyledPanel)
        self.frame_21.setFrameShadow(QFrame.Raised)
        self.frame_21.setObjectName(("frame_21"))
        self.verticalLayout_14 = QVBoxLayout(self.frame_21)
        self.verticalLayout_14.setSpacing(0)
        self.verticalLayout_14.setMargin(0)
        self.verticalLayout_14.setObjectName(("verticalLayout_14"))
        self.btnCaptureRunwayTHR = QToolButton(self.frame_21)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnCaptureRunwayTHR.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayTHR.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayTHR.setMaximumSize(QSize(16777215, 47))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/coordinate_capture.png")), QIcon.Normal, QIcon.Off)
        self.btnCaptureRunwayTHR.setIcon(icon)
        self.btnCaptureRunwayTHR.setObjectName(("btnCaptureRunwayTHR"))
        self.verticalLayout_14.addWidget(self.btnCaptureRunwayTHR)
#         self.btnToolTHR = QToolButton(self.frame_21)
#         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
#         sizePolicy.setHorizontalStretch(0)
#         sizePolicy.setVerticalStretch(0)
#         sizePolicy.setHeightForWidth(self.btnToolTHR.sizePolicy().hasHeightForWidth())
#         self.btnToolTHR.setSizePolicy(sizePolicy)
#         self.btnToolTHR.setMaximumSize(QSize(16777215, 20))
#         icon1 = QIcon()
#         icon1.addPixmap(QPixmap(("Resource/sort2.png")), QIcon.Normal, QIcon.Off)
#         self.btnToolTHR.setIcon(icon1)
#         self.btnToolTHR.setObjectName(("btnToolTHR"))
#         self.verticalLayout_14.addWidget(self.btnToolTHR)
        self.horizontalLayout_19.addWidget(self.frame_21)
        self.verticalLayout_2.addWidget(self.groupBox_5)
        self.groupBox_4 = QGroupBox(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.groupBox_4.sizePolicy().hasHeightForWidth())
        self.groupBox_4.setSizePolicy(sizePolicy)
        font = QFont()
        font.setFamily(("Arial"))
        self.groupBox_4.setFont(font)
        self.groupBox_4.setObjectName(("groupBox_4"))
        self.horizontalLayout_16 = QHBoxLayout(self.groupBox_4)
        self.horizontalLayout_16.setSpacing(0)
        self.horizontalLayout_16.setMargin(0)
        self.horizontalLayout_16.setObjectName(("horizontalLayout_16"))
        self.frame_14 = QFrame(self.groupBox_4)
        self.frame_14.setFrameShape(QFrame.StyledPanel)
        self.frame_14.setFrameShadow(QFrame.Raised)
        self.frame_14.setObjectName(("frame_14"))
        self.verticalLayout_11 = QVBoxLayout(self.frame_14)
        self.verticalLayout_11.setSpacing(0)
        self.verticalLayout_11.setContentsMargins(-1, -1, 0, -1)
        self.verticalLayout_11.setObjectName(("verticalLayout_11"))
        self.frame_15 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_15.sizePolicy().hasHeightForWidth())
        self.frame_15.setSizePolicy(sizePolicy)
        self.frame_15.setFrameShape(QFrame.StyledPanel)
        self.frame_15.setFrameShadow(QFrame.Raised)
        self.frame_15.setObjectName(("frame_15"))
        self.horizontalLayout_17 = QHBoxLayout(self.frame_15)
        self.horizontalLayout_17.setSpacing(0)
        self.horizontalLayout_17.setMargin(0)
        self.horizontalLayout_17.setObjectName(("horizontalLayout_17"))
        self.label_7 = QLabel(self.frame_15)
        self.label_7.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_7.setFont(font)
        self.label_7.setObjectName(("label_7"))
        self.horizontalLayout_17.addWidget(self.label_7)
        self.txtEND_X = QLineEdit(self.frame_15)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtEND_X.sizePolicy().hasHeightForWidth())
        self.txtEND_X.setSizePolicy(sizePolicy)
        self.txtEND_X.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_X.setFont(font)
        self.txtEND_X.setObjectName(("txtEND_X"))
        self.horizontalLayout_17.addWidget(self.txtEND_X)
        self.verticalLayout_11.addWidget(self.frame_15)
        self.frame_16 = QFrame(self.frame_14)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_16.sizePolicy().hasHeightForWidth())
        self.frame_16.setSizePolicy(sizePolicy)
        self.frame_16.setFrameShape(QFrame.StyledPanel)
        self.frame_16.setFrameShadow(QFrame.Raised)
        self.frame_16.setObjectName(("frame_16"))
        self.horizontalLayout_18 = QHBoxLayout(self.frame_16)
        self.horizontalLayout_18.setSpacing(0)
        self.horizontalLayout_18.setMargin(0)
        self.horizontalLayout_18.setObjectName(("horizontalLayout_18"))
        self.label_8 = QLabel(self.frame_16)
        self.label_8.setMaximumSize(QSize(60, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_8.setFont(font)
        self.label_8.setObjectName(("label_8"))
        self.horizontalLayout_18.addWidget(self.label_8)
        self.txtEND_Y = QLineEdit(self.frame_16)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtEND_Y.sizePolicy().hasHeightForWidth())
        self.txtEND_Y.setSizePolicy(sizePolicy)
        self.txtEND_Y.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtEND_Y.setFont(font)
        self.txtEND_Y.setObjectName(("txtEND_Y"))
        self.horizontalLayout_18.addWidget(self.txtEND_Y)
        self.verticalLayout_11.addWidget(self.frame_16)
        self.horizontalLayout_16.addWidget(self.frame_14)
        self.frame_17 = QFrame(self.groupBox_4)
        self.frame_17.setMaximumSize(QSize(30, 16777215))
        self.frame_17.setFrameShape(QFrame.StyledPanel)
        self.frame_17.setFrameShadow(QFrame.Raised)
        self.frame_17.setObjectName(("frame_17"))
        self.verticalLayout_12 = QVBoxLayout(self.frame_17)
        self.verticalLayout_12.setSpacing(0)
        self.verticalLayout_12.setMargin(0)
        self.verticalLayout_12.setObjectName(("verticalLayout_12"))
        self.btnCaptureRunwayEND = QToolButton(self.frame_17)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnCaptureRunwayEND.sizePolicy().hasHeightForWidth())
        self.btnCaptureRunwayEND.setSizePolicy(sizePolicy)
        self.btnCaptureRunwayEND.setMaximumSize(QSize(16777215, 47))
        self.btnCaptureRunwayEND.setIcon(icon)
        self.btnCaptureRunwayEND.setObjectName(("btnCaptureRunwayEND"))
        self.verticalLayout_12.addWidget(self.btnCaptureRunwayEND)
#         self.btnToolEND = QToolButton(self.frame_17)
#         sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
#         sizePolicy.setHorizontalStretch(0)
#         sizePolicy.setVerticalStretch(0)
#         sizePolicy.setHeightForWidth(self.btnToolEND.sizePolicy().hasHeightForWidth())
#         self.btnToolEND.setSizePolicy(sizePolicy)
#         self.btnToolEND.setMaximumSize(QSize(16777215, 20))
#         self.btnToolEND.setIcon(icon1)
#         self.btnToolEND.setObjectName(("btnToolEND"))
#         self.verticalLayout_12.addWidget(self.btnToolEND)
        self.horizontalLayout_16.addWidget(self.frame_17)
        self.verticalLayout_2.addWidget(self.groupBox_4)
        self.lbl1 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        self.lbl1.setFont(font)
        self.lbl1.setText((""))
        self.lbl1.setAlignment(Qt.AlignCenter)
        self.lbl1.setWordWrap(False)
        self.lbl1.setMargin(0)
        self.lbl1.setObjectName(("lbl1"))
        self.verticalLayout_2.addWidget(self.lbl1)
        self.lbl2 = QLabel(self.groupBox)
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lbl2.setFont(font)
        self.lbl2.setText((""))
        self.lbl2.setAlignment(Qt.AlignCenter)
        self.lbl2.setObjectName(("lbl2"))
        self.verticalLayout_2.addWidget(self.lbl2)
        self.frame_22 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_22.sizePolicy().hasHeightForWidth())
        self.frame_22.setSizePolicy(sizePolicy)
        self.frame_22.setFrameShape(QFrame.StyledPanel)
        self.frame_22.setFrameShadow(QFrame.Raised)
        self.frame_22.setObjectName(("frame_22"))
        self.horizontalLayout_22 = QHBoxLayout(self.frame_22)
        self.horizontalLayout_22.setSpacing(0)
        self.horizontalLayout_22.setMargin(0)
        self.horizontalLayout_22.setObjectName(("horizontalLayout_22"))
        self.label_11 = QLabel(self.frame_22)
        self.label_11.setMinimumSize(QSize(170, 0))
        self.label_11.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_11.setFont(font)
        self.label_11.setObjectName(("label_11"))
        self.horizontalLayout_22.addWidget(self.label_11)
        self.txtForm = QLineEdit(self.frame_22)
        self.txtForm.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtForm.sizePolicy().hasHeightForWidth())
        self.txtForm.setSizePolicy(sizePolicy)
        self.txtForm.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtForm.setFont(font)
        self.txtForm.setObjectName(("txtForm"))
        self.horizontalLayout_22.addWidget(self.txtForm)
        self.verticalLayout_2.addWidget(self.frame_22)
        self.frame_23 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_23.sizePolicy().hasHeightForWidth())
        self.frame_23.setSizePolicy(sizePolicy)
        self.frame_23.setFrameShape(QFrame.StyledPanel)
        self.frame_23.setFrameShadow(QFrame.Raised)
        self.frame_23.setObjectName(("frame_23"))
        self.horizontalLayout_23 = QHBoxLayout(self.frame_23)
        self.horizontalLayout_23.setSpacing(0)
        self.horizontalLayout_23.setMargin(0)
        self.horizontalLayout_23.setObjectName(("horizontalLayout_23"))
        self.label_12 = QLabel(self.frame_23)
        self.label_12.setMinimumSize(QSize(170, 0))
        self.label_12.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.label_12.setFont(font)
        self.label_12.setObjectName(("label_12"))
        self.horizontalLayout_23.addWidget(self.label_12)
        self.txtBearing = QLineEdit(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtBearing.sizePolicy().hasHeightForWidth())
        self.txtBearing.setSizePolicy(sizePolicy)
        self.txtBearing.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtBearing.setFont(font)
        self.txtBearing.setObjectName(("txtBearing"))
        self.horizontalLayout_23.addWidget(self.txtBearing)
        self.btnCaptureBearing = QToolButton(self.frame_23)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnCaptureBearing.sizePolicy().hasHeightForWidth())
        self.btnCaptureBearing.setSizePolicy(sizePolicy)
        self.btnCaptureBearing.setMaximumSize(QSize(16777215, 25))
        self.btnCaptureBearing.setStyleSheet((""))
        self.btnCaptureBearing.setIcon(icon)
        self.btnCaptureBearing.setObjectName(("btnCaptureBearing"))
        self.horizontalLayout_23.addWidget(self.btnCaptureBearing)
        self.verticalLayout_2.addWidget(self.frame_23)
        self.frame_24 = QFrame(self.groupBox)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frame_24.sizePolicy().hasHeightForWidth())
        self.frame_24.setSizePolicy(sizePolicy)
        self.frame_24.setFrameShape(QFrame.StyledPanel)
        self.frame_24.setFrameShadow(QFrame.Raised)
        self.frame_24.setObjectName(("frame_24"))
        self.horizontalLayout_24 = QHBoxLayout(self.frame_24)
        self.horizontalLayout_24.setSpacing(0)
        self.horizontalLayout_24.setMargin(0)
        self.horizontalLayout_24.setObjectName(("horizontalLayout_24"))
        self.lblDistance = QLabel(self.frame_24)
        self.lblDistance.setMinimumSize(QSize(170, 0))
        self.lblDistance.setMaximumSize(QSize(180, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        font.setBold(False)
        font.setWeight(50)
        self.lblDistance.setFont(font)
        self.lblDistance.setObjectName(("lblDistance"))
        self.horizontalLayout_24.addWidget(self.lblDistance)
        self.txtDistance = QLineEdit(self.frame_24)
        self.txtDistance.setEnabled(False)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.txtDistance.sizePolicy().hasHeightForWidth())
        self.txtDistance.setSizePolicy(sizePolicy)
        self.txtDistance.setMaximumSize(QSize(16777215, 16777215))
        font = QFont()
        font.setFamily(("Arial"))
        self.txtDistance.setFont(font)
        self.txtDistance.setObjectName(("txtDistance"))
        self.horizontalLayout_24.addWidget(self.txtDistance)
        self.btnCaptureDistance = QToolButton(self.frame_24)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnCaptureDistance.sizePolicy().hasHeightForWidth())
        self.btnCaptureDistance.setSizePolicy(sizePolicy)
        self.btnCaptureDistance.setMaximumSize(QSize(16777215, 23))
        self.btnCaptureDistance.setStyleSheet((""))
        self.btnCaptureDistance.setIcon(icon)
        self.btnCaptureDistance.setObjectName(("btnCaptureDistance"))
        self.horizontalLayout_24.addWidget(self.btnCaptureDistance)
        self.verticalLayout_2.addWidget(self.frame_24)
        self.verticalLayout.addWidget(self.groupBox)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(("buttonBox"))
        self.verticalLayout.addWidget(self.buttonBox)
        self.btnCaptureDistance.clicked.connect(self.method_9)
        self.btnCaptureBearing.clicked.connect(self.method_8)
        self.txtEND_X.textChanged.connect(self.method_4)
        self.txtEND_Y.textChanged.connect(self.method_4)
        self.txtTHR_X.textChanged.connect(self.method_4)
        self.txtTHR_Y.textChanged.connect(self.method_4)
        self.type = rnavType
        self.category = category
        self.resultPosionList = position_List
        self.MinBearing2 = 0
        self.MaxBearing2= 0
        self.waypoint = None
        self.distanceMeasureTool = MeasureTool(define._canvas, self.txtDistance, DistanceUnits.NM)
        self.bearingTool = CaptureBearingTool(define._canvas, self.txtBearing)
        self.CaptureTHRCoordTool = CaptureCoordinateTool(define._canvas, self.txtTHR_X, self.txtTHR_Y)
        self.CaptureTHRCoordTool.rubberBandClick.setColor(Qt.green)        
        self.CaptureENDCoordTool = CaptureCoordinateTool(define._canvas, self.txtEND_X, self.txtEND_Y)
        self.CaptureENDCoordTool.rubberBandClick.setColor(Qt.blue)
        if rnavType == RnavCommonWaypoint.FAWP or rnavType == RnavCommonWaypoint.MAWP:
            self.from1 = position_0
            
            self.resize(326, 310)
            if position_List[0] != None:        
                self.setThrPosition(position_List[0].x(),position_List[0].y())
                self.CaptureTHRCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[0].x(),position_List[0].y()))
#                 self.CaptureTHRCoordTool.rubberBandClick.show()
            if position_List[1] != None: 
                self.setEndPosition(position_List[1].x(),position_List[1].y())
                self.CaptureENDCoordTool.rubberBandClick.addPoint(QgsPoint(position_List[1].x(),position_List[1].y()))
#             self.setWaypoint(position_List[2])
        else:
            self.from1 = position_1
            num = RnavWaypoints.smethod_0(position_0, position_1)
            self.MinBearing = RnavWaypoints.smethod_7(rnavType, category, num)
            self.MaxBearing= RnavWaypoints.smethod_8(rnavType, category, num)
            self.MinDistance = RnavWaypoints.smethod_4(rnavType, category)
            if flagStr == "Y-Bar":
                if (rnavType == RnavCommonWaypoint.IAWP1):
                    self.setBearing(self.MaxBearing)
                elif (rnavType != RnavCommonWaypoint.IAWP3):
                    self.setBearing(num)
                else:
                    self.setBearing(self.MinBearing)
            else:
                if (rnavType == RnavCommonWaypoint.IAWP1):
                    self.setBearing(self.MinBearing)
                elif (rnavType != RnavCommonWaypoint.IAWP3):
                    self.setBearing(num)
                else:
                    self.setBearing(self.MaxBearing)
#             if self.txtDistance.isEnabled():
#             self.setDistance(RnavWaypoints.smethod_6(rnavType, category).NauticalMiles)
#             self.setWaypoint(position_List.pop(0))
        self.method_4()
        self.retranslateUi()
        QObject.connect(self.buttonBox, SIGNAL(("accepted()")), self.btnCalculate_Click)
        QObject.connect(self.buttonBox, SIGNAL(("rejected()")), self.reject)
#         QMetaObject.connectSlotsByName(Dialog)
        
#         self.btnToolEND.clicked.connect(self.removeEnd)
#         self.btnToolTHR.clicked.connect(self.removeThr)
        self.btnCaptureRunwayTHR.clicked.connect(self.captureTHR)
        self.btnCaptureRunwayEND.clicked.connect(self.captureEND)
Ejemplo n.º 37
0
 def testQgsEllipseRepr(self):
     e = QgsEllipse(QgsPoint(1, 2), 2.0, 3.0)
     self.assertEqual(e.__repr__(), '<QgsEllipse: Ellipse (Center: Point (1 2), Semi-Major Axis: 3, Semi-Minor Axis: 2, Azimuth: 180)>')
Ejemplo n.º 38
0
    def processAlgorithm(self, feedback):
        layer = dataobjects.getLayerFromString(
            self.getParameterValue(self.POINTS))
        weightField = self.getParameterValue(self.WEIGHT)
        uniqueField = self.getParameterValue(self.UID)

        if weightField is None:
            weightIndex = -1
        else:
            weightIndex = layer.fields().lookupField(weightField)

        if uniqueField is None:
            uniqueIndex = -1
        else:
            uniqueIndex = layer.fields().lookupField(uniqueField)

        fieldList = [
            QgsField('MEAN_X', QVariant.Double, '', 24, 15),
            QgsField('MEAN_Y', QVariant.Double, '', 24, 15),
            QgsField('UID', QVariant.String, '', 255)
        ]

        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fieldList, QgsWkbTypes.Point, layer.crs())

        features = vector.features(layer)
        total = 100.0 / len(features)
        means = {}
        for current, feat in enumerate(features):
            feedback.setProgress(int(current * total))
            if uniqueIndex == -1:
                clazz = "Single class"
            else:
                clazz = str(feat.attributes()[uniqueIndex]).strip()
            if weightIndex == -1:
                weight = 1.00
            else:
                try:
                    weight = float(feat.attributes()[weightIndex])
                except:
                    weight = 1.00

            if weight < 0:
                raise GeoAlgorithmExecutionException(
                    self.
                    tr('Negative weight value found. Please fix your data and try again.'
                       ))

            if clazz not in means:
                means[clazz] = (0, 0, 0)

            (cx, cy, totalweight) = means[clazz]
            geom = QgsGeometry(feat.geometry())
            geom = vector.extractPoints(geom)
            for i in geom:
                cx += i.x() * weight
                cy += i.y() * weight
                totalweight += weight
            means[clazz] = (cx, cy, totalweight)

        current = 0
        total = 100.0 / len(means)
        for (clazz, values) in list(means.items()):
            outFeat = QgsFeature()
            cx = values[0] / values[2]
            cy = values[1] / values[2]
            meanPoint = QgsPoint(cx, cy)

            outFeat.setGeometry(QgsGeometry.fromPoint(meanPoint))
            outFeat.setAttributes([cx, cy, clazz])
            writer.addFeature(outFeat)
            current += 1
            feedback.setProgress(int(current * total))

        del writer
Ejemplo n.º 39
0
 def testQgsCurvepolygonRepr(self):
     cp = QgsCurvePolygon()
     cs = QgsCircularString(QgsPoint(1, 10), QgsPoint(2, 11), QgsPoint(1, 10))
     cp.setExteriorRing(cs)
     self.assertEqual(cp.__repr__(), '<QgsCurvePolygon: CurvePolygon (CircularString (1 10, 2 11, 1 10))>')
Ejemplo n.º 40
0
    def testMeasureMultiPolygon(self):
        # +-+-+ +-+-+
        # |   | |   |
        # + +-+ +-+ +
        # | |     | |
        # +-+     +-+
        polygon = QgsGeometry.fromMultiPolygon([[[
            QgsPoint(0, 0),
            QgsPoint(1, 0),
            QgsPoint(1, 1),
            QgsPoint(2, 1),
            QgsPoint(2, 2),
            QgsPoint(0, 2),
            QgsPoint(0, 0),
        ]],
                                                [[
                                                    QgsPoint(4, 0),
                                                    QgsPoint(5, 0),
                                                    QgsPoint(5, 2),
                                                    QgsPoint(3, 2),
                                                    QgsPoint(3, 1),
                                                    QgsPoint(4, 1),
                                                    QgsPoint(4, 0),
                                                ]]])

        da = QgsDistanceArea()
        area = da.measureArea(polygon)
        assert area == 6, 'Expected:\n%f\nGot:\n%f\n' % (6, area)

        perimeter = da.measurePerimeter(polygon)
        assert perimeter == 16, "Expected:\n%f\nGot:\n%f\n" % (16, perimeter)
Ejemplo n.º 41
0
    def processAlgorithm(self, progress):
        layer = dataobjects.getObjectFromUri(
                self.getParameterValue(self.INPUT_VECTOR))
        startPoint = self.getParameterValue(self.START_POINT)
        strategy = self.getParameterValue(self.STRATEGY)
        travelCost = self.getParameterValue(self.TRAVEL_COST)

        directionFieldName = self.getParameterValue(self.DIRECTION_FIELD)
        forwardValue = self.getParameterValue(self.VALUE_FORWARD)
        backwardValue = self.getParameterValue(self.VALUE_BACKWARD)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        speedFieldName = self.getParameterValue(self.SPEED_FIELD)
        defaultSpeed = self.getParameterValue(self.DEFAULT_SPEED)
        tolerance = self.getParameterValue(self.TOLERANCE)

        tmp = startPoint.split(',')
        startPoint = QgsPoint(float(tmp[0]), float(tmp[1]))

        directionField = -1
        if directionFieldName is not None:
            directionField = layer.fields().lookupField(directionFieldName)
        speedField = -1
        if speedFieldName is not None:
            speedField = layer.fields().lookupField(speedFieldName)

        director = QgsVectorLayerDirector(layer,
                                          directionField,
                                          forwardValue,
                                          backwardValue,
                                          bothValue,
                                          defaultDirection)

        distUnit = iface.mapCanvas().mapSettings().destinationCrs().mapUnits()
        multiplier = QgsUnitTypes.fromUnitToUnitFactor(distUnit, QgsUnitTypes.DistanceMeters)
        if strategy == 0:
            strategy = QgsNetworkDistanceStrategy()
        else:
            strategy = QgsNetworkSpeedStrategy(speedField,
                                               defaultSpeed,
                                               multiplier * 1000.0 / 3600.0)

        director.addStrategy(strategy)
        builder = QgsGraphBuilder(iface.mapCanvas().mapSettings().destinationCrs(),
                                  iface.mapCanvas().hasCrsTransformEnabled(),
                                  tolerance)
        progress.setInfo(self.tr('Building graph...'))
        snappedPoints = director.makeGraph(builder, [startPoint])

        progress.setInfo(self.tr('Calculating service area...'))
        graph = builder.graph()
        idxStart = graph.findVertex(snappedPoints[0])

        tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
        vertices = []
        for i, v in enumerate(cost):
            if v > travelCost and tree[i] != -1:
                vertexId = graph.edge(tree [i]).outVertex()
                if cost[vertexId] <= travelCost:
                    vertices.append(i)

        upperBoundary = []
        lowerBoundary = []
        for i in vertices:
            upperBoundary.append(graph.vertex(graph.edge(tree[i]).inVertex()).point())
            lowerBoundary.append(graph.vertex(graph.edge(tree[i]).outVertex()).point())

        progress.setInfo(self.tr('Writting results...'))

        fields = QgsFields()
        fields.append(QgsField('type', QVariant.String, '', 254, 0))
        fields.append(QgsField('start', QVariant.String, '', 254, 0))

        feat = QgsFeature()
        feat.setFields(fields)

        geomUpper = QgsGeometry.fromMultiPoint(upperBoundary)
        geomLower = QgsGeometry.fromMultiPoint(lowerBoundary)

        writer = self.getOutputFromName(
            self.OUTPUT_POINTS).getVectorWriter(
                fields,
                QgsWkbTypes.MultiPoint,
                layer.crs())

        feat.setGeometry(geomUpper)
        feat['type'] = 'upper'
        feat['start'] = startPoint.toString()
        writer.addFeature(feat)

        feat.setGeometry(geomLower)
        feat['type'] = 'lower'
        feat['start'] = startPoint.toString()
        writer.addFeature(feat)

        del writer

        writer = self.getOutputFromName(
            self.OUTPUT_POLYGON).getVectorWriter(
                fields,
                QgsWkbTypes.Polygon,
                layer.crs())

        geom = geomUpper.convexHull()
        feat.setGeometry(geom)
        feat['type'] = 'upper'
        feat['start'] = startPoint.toString()
        writer.addFeature(feat)

        geom = geomLower.convexHull()
        feat.setGeometry(geom)
        feat['type'] = 'lower'
        feat['start'] = startPoint.toString()
        writer.addFeature(feat)
        del writer
Ejemplo n.º 42
0
    def processAlgorithm(self, progress):
        layer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT_VECTOR))
        startPoint = self.getParameterValue(self.START_POINT)
        endPoints = dataobjects.getObjectFromUri(
            self.getParameterValue(self.END_POINTS))
        strategy = self.getParameterValue(self.STRATEGY)

        directionFieldName = self.getParameterValue(self.DIRECTION_FIELD)
        forwardValue = self.getParameterValue(self.VALUE_FORWARD)
        backwardValue = self.getParameterValue(self.VALUE_BACKWARD)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        speedFieldName = self.getParameterValue(self.SPEED_FIELD)
        defaultSpeed = self.getParameterValue(self.DEFAULT_SPEED)
        tolerance = self.getParameterValue(self.TOLERANCE)

        fields = QgsFields()
        fields.append(QgsField('start', QVariant.String, '', 254, 0))
        fields.append(QgsField('end', QVariant.String, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 20, 7))

        feat = QgsFeature()
        feat.setFields(fields)

        writer = self.getOutputFromName(
            self.OUTPUT_LAYER).getVectorWriter(
                fields.toList(),
                QgsWkbTypes.LineString,
                layer.crs())

        tmp = startPoint.split(',')
        startPoint = QgsPoint(float(tmp[0]), float(tmp[1]))

        directionField = -1
        if directionFieldName is not None:
            directionField = layer.fields().lookupField(directionFieldName)
        speedField = -1
        if speedFieldName is not None:
            speedField = layer.fields().lookupField(speedFieldName)

        director = QgsVectorLayerDirector(layer,
                                          directionField,
                                          forwardValue,
                                          backwardValue,
                                          bothValue,
                                          defaultDirection)

        distUnit = iface.mapCanvas().mapSettings().destinationCrs().mapUnits()
        multiplier = QgsUnitTypes.fromUnitToUnitFactor(distUnit, QgsUnitTypes.DistanceMeters)
        if strategy == 0:
            strategy = QgsNetworkDistanceStrategy()
        else:
            strategy = QgsNetworkSpeedStrategy(speedField,
                                               defaultSpeed,
                                               multiplier * 1000.0 / 3600.0)
            multiplier = 3600

        director.addStrategy(strategy)
        builder = QgsGraphBuilder(iface.mapCanvas().mapSettings().destinationCrs(),
                                  iface.mapCanvas().hasCrsTransformEnabled(),
                                  tolerance)

        progress.setInfo(self.tr('Loading end points...'))
        request = QgsFeatureRequest()
        request.setFlags(request.flags() ^ QgsFeatureRequest.SubsetOfAttributes)
        features = vector.features(endPoints, request)
        count = len(features)

        points = [startPoint]
        for f in features:
            points.append(f.geometry().asPoint())

        progress.setInfo(self.tr('Building graph...'))
        snappedPoints = director.makeGraph(builder, points)

        progress.setInfo(self.tr('Calculating shortest paths...'))
        graph = builder.graph()

        idxStart = graph.findVertex(snappedPoints[0])
        tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
        route = []

        total = 100.0 / count
        for i in range(1, count + 1):
            idxEnd = graph.findVertex(snappedPoints[i])

            if tree[idxEnd] == -1:
                msg = self.tr('There is no route from start point ({}) to end point ({}).'.format(startPoint.toString(), points[i].toString()))
                progress.setText(msg)
                ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, msg)
                continue

            cost = 0.0
            current = idxEnd
            while current != idxStart:
                cost += graph.edge(tree[current]).cost(0)
                route.append(graph.vertex(graph.edge(tree[current]).inVertex()).point())
                current = graph.edge(tree[current]).outVertex()

            route.append(snappedPoints[0])
            route.reverse()

            geom = QgsGeometry.fromPolyline(route)
            feat.setGeometry(geom)
            feat['start'] = startPoint.toString()
            feat['end'] = points[i].toString()
            feat['cost'] = cost / multiplier
            writer.addFeature(feat)

            route[:] = []

            progress.setPercentage(int(i * total))

        del writer
Ejemplo n.º 43
0
def valRaster(x, y, rLayer):

    z = rLayer.dataProvider().identify(QgsPoint(
        x, y), QgsRaster.IdentifyFormatValue).results()[1]
    return z
Ejemplo n.º 44
0
    def processAlgorithm(self, feedback):
        layer = dataobjects.getLayerFromString(
            self.getParameterValue(self.INPUT_VECTOR))
        startPoint = self.getParameterValue(self.START_POINT)
        endPoints = dataobjects.getLayerFromString(
            self.getParameterValue(self.END_POINTS))
        strategy = self.getParameterValue(self.STRATEGY)

        directionFieldName = self.getParameterValue(self.DIRECTION_FIELD)
        forwardValue = self.getParameterValue(self.VALUE_FORWARD)
        backwardValue = self.getParameterValue(self.VALUE_BACKWARD)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        speedFieldName = self.getParameterValue(self.SPEED_FIELD)
        defaultSpeed = self.getParameterValue(self.DEFAULT_SPEED)
        tolerance = self.getParameterValue(self.TOLERANCE)

        fields = QgsFields()
        fields.append(QgsField('start', QVariant.String, '', 254, 0))
        fields.append(QgsField('end', QVariant.String, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 20, 7))

        feat = QgsFeature()
        feat.setFields(fields)

        writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(
            fields.toList(), QgsWkbTypes.LineString, layer.crs())

        tmp = startPoint.split(',')
        startPoint = QgsPoint(float(tmp[0]), float(tmp[1]))

        directionField = -1
        if directionFieldName is not None:
            directionField = layer.fields().lookupField(directionFieldName)
        speedField = -1
        if speedFieldName is not None:
            speedField = layer.fields().lookupField(speedFieldName)

        director = QgsVectorLayerDirector(layer, directionField, forwardValue,
                                          backwardValue, bothValue,
                                          defaultDirection)

        distUnit = iface.mapCanvas().mapSettings().destinationCrs().mapUnits()
        multiplier = QgsUnitTypes.fromUnitToUnitFactor(
            distUnit, QgsUnitTypes.DistanceMeters)
        if strategy == 0:
            strategy = QgsNetworkDistanceStrategy()
        else:
            strategy = QgsNetworkSpeedStrategy(speedField, defaultSpeed,
                                               multiplier * 1000.0 / 3600.0)
            multiplier = 3600

        director.addStrategy(strategy)
        builder = QgsGraphBuilder(
            iface.mapCanvas().mapSettings().destinationCrs(), True, tolerance)

        feedback.pushInfo(self.tr('Loading end points...'))
        request = QgsFeatureRequest()
        request.setFlags(request.flags()
                         ^ QgsFeatureRequest.SubsetOfAttributes)
        features = vector.features(endPoints, request)
        count = len(features)

        points = [startPoint]
        for f in features:
            points.append(f.geometry().asPoint())

        feedback.pushInfo(self.tr('Building graph...'))
        snappedPoints = director.makeGraph(builder, points)

        feedback.pushInfo(self.tr('Calculating shortest paths...'))
        graph = builder.graph()

        idxStart = graph.findVertex(snappedPoints[0])
        tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
        route = []

        total = 100.0 / count
        for i in range(1, count + 1):
            idxEnd = graph.findVertex(snappedPoints[i])

            if tree[idxEnd] == -1:
                msg = self.tr(
                    'There is no route from start point ({}) to end point ({}).'
                    .format(startPoint.toString(), points[i].toString()))
                feedback.setProgressText(msg)
                ProcessingLog.addToLog(ProcessingLog.LOG_WARNING, msg)
                continue

            cost = 0.0
            current = idxEnd
            while current != idxStart:
                cost += graph.edge(tree[current]).cost(0)
                route.append(
                    graph.vertex(graph.edge(tree[current]).inVertex()).point())
                current = graph.edge(tree[current]).outVertex()

            route.append(snappedPoints[0])
            route.reverse()

            geom = QgsGeometry.fromPolyline(route)
            feat.setGeometry(geom)
            feat['start'] = startPoint.toString()
            feat['end'] = points[i].toString()
            feat['cost'] = cost / multiplier
            writer.addFeature(feat)

            route[:] = []

            feedback.setProgress(int(i * total))

        del writer
Ejemplo n.º 45
0
    def clip_voronoi(self, edges, c, width, height, extent, exX, exY):
        """Clip voronoi function based on code written for Inkscape.
        Copyright (C) 2010 Alvin Penner, [email protected]
        """

        def clip_line(x1, y1, x2, y2, w, h, x, y):
            if x1 < 0 - x and x2 < 0 - x:
                return [0, 0, 0, 0]
            if x1 > w + x and x2 > w + x:
                return [0, 0, 0, 0]
            if x1 < 0 - x:
                y1 = (y1 * x2 - y2 * x1) / (x2 - x1)
                x1 = 0 - x
            if x2 < 0 - x:
                y2 = (y1 * x2 - y2 * x1) / (x2 - x1)
                x2 = 0 - x
            if x1 > w + x:
                y1 = y1 + (w + x - x1) * (y2 - y1) / (x2 - x1)
                x1 = w + x
            if x2 > w + x:
                y2 = y1 + (w + x - x1) * (y2 - y1) / (x2 - x1)
                x2 = w + x
            if y1 < 0 - y and y2 < 0 - y:
                return [0, 0, 0, 0]
            if y1 > h + y and y2 > h + y:
                return [0, 0, 0, 0]
            if x1 == x2 and y1 == y2:
                return [0, 0, 0, 0]
            if y1 < 0 - y:
                x1 = (x1 * y2 - x2 * y1) / (y2 - y1)
                y1 = 0 - y
            if y2 < 0 - y:
                x2 = (x1 * y2 - x2 * y1) / (y2 - y1)
                y2 = 0 - y
            if y1 > h + y:
                x1 = x1 + (h + y - y1) * (x2 - x1) / (y2 - y1)
                y1 = h + y
            if y2 > h + y:
                x2 = x1 + (h + y - y1) * (x2 - x1) / (y2 - y1)
                y2 = h + y
            return [x1, y1, x2, y2]

        lines = []
        hasXMin = False
        hasYMin = False
        hasXMax = False
        hasYMax = False
        for edge in edges:
            if edge[1] >= 0 and edge[2] >= 0:
                # Two vertices
                [x1, y1, x2, y2] = clip_line(
                    c.vertices[edge[1]][0],
                    c.vertices[edge[1]][1],
                    c.vertices[edge[2]][0],
                    c.vertices[edge[2]][1],
                    width,
                    height,
                    exX,
                    exY,
                )
            elif edge[1] >= 0:
                # Only one vertex
                if c.lines[edge[0]][1] == 0:
                    # Vertical line
                    xtemp = c.lines[edge[0]][2] / c.lines[edge[0]][0]
                    if c.vertices[edge[1]][1] > (height + exY) / 2:
                        ytemp = height + exY
                    else:
                        ytemp = 0 - exX
                else:
                    xtemp = width + exX
                    ytemp = (c.lines[edge[0]][2] - (width + exX) *
                             c.lines[edge[0]][0]) / c.lines[edge[0]][1]
                [x1, y1, x2, y2] = clip_line(
                    c.vertices[edge[1]][0],
                    c.vertices[edge[1]][1],
                    xtemp,
                    ytemp,
                    width,
                    height,
                    exX,
                    exY,
                )
            elif edge[2] >= 0:
                # Only one vertex
                if c.lines[edge[0]][1] == 0:
                    # Vertical line
                    xtemp = c.lines[edge[0]][2] / c.lines[edge[0]][0]
                    if c.vertices[edge[2]][1] > (height + exY) / 2:
                        ytemp = height + exY
                    else:
                        ytemp = 0.0 - exY
                else:
                    xtemp = 0.0 - exX
                    ytemp = c.lines[edge[0]][2] / c.lines[edge[0]][1]
                [x1, y1, x2, y2] = clip_line(
                    xtemp,
                    ytemp,
                    c.vertices[edge[2]][0],
                    c.vertices[edge[2]][1],
                    width,
                    height,
                    exX,
                    exY,
                )
            if x1 or x2 or y1 or y2:
                lines.append(QgsPoint(x1 + extent.xMinimum(),
                                      y1 + extent.yMinimum()))
                lines.append(QgsPoint(x2 + extent.xMinimum(),
                                      y2 + extent.yMinimum()))
                if 0 - exX in (x1, x2):
                    hasXMin = True
                if 0 - exY in (y1, y2):
                    hasYMin = True
                if height + exY in (y1, y2):
                    hasYMax = True
                if width + exX in (x1, x2):
                    hasXMax = True
        if hasXMin:
            if hasYMax:
                lines.append(QgsPoint(extent.xMinimum() - exX,
                                      height + extent.yMinimum() + exY))
            if hasYMin:
                lines.append(QgsPoint(extent.xMinimum() - exX,
                                      extent.yMinimum() - exY))
        if hasXMax:
            if hasYMax:
                lines.append(QgsPoint(width + extent.xMinimum() + exX,
                                      height + extent.yMinimum() + exY))
            if hasYMin:
                lines.append(QgsPoint(width + extent.xMinimum() + exX,
                                      extent.yMinimum() - exY))
        return lines
Ejemplo n.º 46
0
 def mouseMove(self, currentPos):
     if self.isEditing == 1:
         self.myRubberBand.movePoint(QgsPoint(currentPos))
Ejemplo n.º 47
0
    def processAlgorithm(self, progress):
        layer = dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT_VECTOR))

        rasterPath = unicode(self.getParameterValue(self.INPUT_RASTER))

        rasterDS = gdal.Open(rasterPath, gdal.GA_ReadOnly)
        geoTransform = rasterDS.GetGeoTransform()
        rasterDS = None

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))
        fields.append(QgsField('poly_id', QVariant.Int, '', 10, 0))
        fields.append(QgsField('point_id', QVariant.Int, '', 10, 0))

        writer = self.getOutputFromName(self.OUTPUT_LAYER).getVectorWriter(
            fields.toList(), QGis.WKBPoint, layer.crs())

        outFeature = QgsFeature()
        outFeature.setFields(fields)
        point = QgsPoint()

        fid = 0
        polyId = 0
        pointId = 0

        current = 0
        features = vector.features(layer)
        total = 100.0 / len(features)
        for f in features:
            geom = f.geometry()
            bbox = geom.boundingBox()

            xMin = bbox.xMinimum()
            xMax = bbox.xMaximum()
            yMin = bbox.yMinimum()
            yMax = bbox.yMaximum()

            (startRow, startColumn) = raster.mapToPixel(xMin, yMax, geoTransform)
            (endRow, endColumn) = raster.mapToPixel(xMax, yMin, geoTransform)

            for row in xrange(startRow, endRow + 1):
                for col in xrange(startColumn, endColumn + 1):
                    (x, y) = raster.pixelToMap(row, col, geoTransform)
                    point.setX(x)
                    point.setY(y)

                    if geom.contains(point):
                        outFeature.setGeometry(QgsGeometry.fromPoint(point))
                        outFeature['id'] = fid
                        outFeature['poly_id'] = polyId
                        outFeature['point_id'] = pointId

                        fid += 1
                        pointId += 1

                        writer.addFeature(outFeature)

            pointId = 0
            polyId += 1

            current += 1
            progress.setPercentage(int(current * total))

        del writer
Ejemplo n.º 48
0
Archivo: Grid.py Proyecto: jpsalv/QGIS
    def _lineGrid(self, sink, bbox, hSpacing, vSpacing, hOverlay, vOverlay, feedback):
        feat = QgsFeature()

        if hOverlay > 0:
            hSpace = [hSpacing - hOverlay, hOverlay]
        else:
            hSpace = [hSpacing, hSpacing]

        if vOverlay > 0:
            vSpace = [vSpacing - vOverlay, vOverlay]
        else:
            vSpace = [vSpacing, vSpacing]

        count = 0
        id = 1

        # latitude lines
        count_max = bbox.height() / vSpacing
        count_update = count_max * 0.10
        y = bbox.yMaximum()
        while y >= bbox.yMinimum():
            if feedback.isCanceled():
                break

            pt1 = QgsPoint(bbox.xMinimum(), y)
            pt2 = QgsPoint(bbox.xMaximum(), y)
            line = QgsLineString([pt1, pt2])
            feat.setGeometry(QgsGeometry(line))
            feat.setAttributes([bbox.xMinimum(),
                                y,
                                bbox.xMaximum(),
                                y,
                                id,
                                y])
            sink.addFeature(feat, QgsFeatureSink.FastInsert)
            y = y - vSpace[count % 2]
            id += 1
            count += 1
            if int(math.fmod(count, count_update)) == 0:
                feedback.setProgress(int(count / count_max * 50))

        feedback.setProgress(50)

        # longitude lines
        # counters for progressbar - update every 5%
        count = 0
        count_max = bbox.width() / hSpacing
        count_update = count_max * 0.10
        x = bbox.xMinimum()
        while x <= bbox.xMaximum():
            if feedback.isCanceled():
                break

            pt1 = QgsPoint(x, bbox.yMaximum())
            pt2 = QgsPoint(x, bbox.yMinimum())
            line = QgsLineString([pt1, pt2])
            feat.setGeometry(QgsGeometry(line))
            feat.setAttributes([x,
                                bbox.yMaximum(),
                                x,
                                bbox.yMinimum(),
                                id,
                                x])
            sink.addFeature(feat, QgsFeatureSink.FastInsert)
            x = x + hSpace[count % 2]
            id += 1
            count += 1
            if int(math.fmod(count, count_update)) == 0:
                feedback.setProgress(50 + int(count / count_max * 50))
Ejemplo n.º 49
0
    def do_operation(self):
        """ perform create mapping scheme operation """
        
        # input/output verification already performed during set input/ouput
        fp_layer = self.inputs[0].value
        zone_field = self.inputs[1].value

        # aggregate footprint into grids
        logAPICall.log('aggregate statistic for grid ...', logAPICall.DEBUG)
        total_features = fp_layer.dataProvider().featureCount()
        if total_features > MAX_FEATURES_IN_MEMORY:
            # use bsddb to store temporary lat/lon
            tmp_db_file = '%sdb_%s.db' % (self._tmp_dir, get_unique_filename())
            db = bsddb.btopen(tmp_db_file, 'c')
            use_db = True
        else:
            db = {}
            use_db = False

        zone_idx = layer_field_index(fp_layer, zone_field)
        for f in layer_features(fp_layer):
            geom = f.geometry()
            zone_str = str(f.attributeMap()[zone_idx].toString())
            centroid  = geom.centroid().asPoint()
            # use floor, this truncates all points within grid to grid's
            # bottom-left corner                        
            x = math.floor(centroid.x() / DEFAULT_GRID_SIZE)
            y = math.floor(centroid.y() / DEFAULT_GRID_SIZE)
            key = '%s %d %d' % (zone_str, x,y)
            if db.has_key(key):
                db[key] = str(int(db[key]) + 1)
            else:
                db[key] = '1'
        
        # output grid
        logAPICall.log('create grid ...', logAPICall.DEBUG)
        fields = {
            0 : QgsField(self._lon_field, QVariant.Double),
            1 : QgsField(self._lat_field, QVariant.Double),
            2 : QgsField(CNT_FIELD_NAME, QVariant.Double),
            3 : QgsField(zone_field, QVariant.String),
        }
        grid_layername = 'grid_%s' % get_unique_filename()
        grid_file = '%s%s.shp' % (self._tmp_dir, grid_layername)
        try:
            writer = QgsVectorFileWriter(grid_file, "utf-8", fields, QGis.WKBPoint , self._crs, "ESRI Shapefile")
            f = QgsFeature()
            for key, val in db.iteritems():
                (zone_str, x, y) = key.split(' ')
                # point were aggregated to grid's bottom-left corner
                # add half grid size to place point at center of grid
                point = QgsPoint(int(x)*DEFAULT_GRID_SIZE+(DEFAULT_GRID_SIZE/2.0), 
                                 int(y)*DEFAULT_GRID_SIZE+(DEFAULT_GRID_SIZE/2.0))
                f.setGeometry(QgsGeometry.fromPoint(point))
                f.addAttribute(0, QVariant(point.x()))
                f.addAttribute(1, QVariant(point.y()))
                f.addAttribute(2, QVariant(val))
                f.addAttribute(3, QVariant(zone_str))
                writer.addFeature(f)
            del writer
        except Exception as err:
            remove_shapefile(grid_file)
            raise OperatorError("error creating joined grid: " % err, self.__class__)
        
        grid_layer = load_shapefile(grid_file, grid_layername)
        if not grid_layer:
            raise OperatorError('Error loading created grid file' % (grid_file), self.__class__)
                
        # clean up                
        if use_db:
            db.close()
            os.remove(tmp_db_file)
            
        # done
        self.outputs[0].value = grid_layer
        self.outputs[1].value = grid_file
Ejemplo n.º 50
0
    def processAlgorithm(self, parameters, context, feedback):
        spacing = self.parameterAsDouble(parameters, self.SPACING, context)
        inset = self.parameterAsDouble(parameters, self.INSET, context)
        randomize = self.parameterAsBool(parameters, self.RANDOMIZE, context)
        isSpacing = self.parameterAsBool(parameters, self.IS_SPACING, context)
        crs = self.parameterAsCrs(parameters, self.CRS, context)
        extent = self.parameterAsExtent(parameters, self.EXTENT, context, crs)

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               QgsWkbTypes.Point, crs)
        if sink is None:
            raise QgsProcessingException(
                self.invalidSinkError(parameters, self.OUTPUT))

        if randomize:
            seed()

        area = extent.width() * extent.height()
        if isSpacing:
            pSpacing = spacing
        else:
            pSpacing = sqrt(area / spacing)

        f = QgsFeature()
        f.initAttributes(1)
        f.setFields(fields)

        count = 0
        id = 0
        total = 100.0 / (area / pSpacing)
        y = extent.yMaximum() - inset

        extent_geom = QgsGeometry.fromRect(extent)
        extent_engine = QgsGeometry.createGeometryEngine(
            extent_geom.constGet())
        extent_engine.prepareGeometry()

        while y >= extent.yMinimum():
            x = extent.xMinimum() + inset
            while x <= extent.xMaximum():
                if feedback.isCanceled():
                    break

                if randomize:
                    geom = QgsGeometry(
                        QgsPoint(
                            uniform(x - (pSpacing / 2.0),
                                    x + (pSpacing / 2.0)),
                            uniform(y - (pSpacing / 2.0),
                                    y + (pSpacing / 2.0))))
                else:
                    geom = QgsGeometry(QgsPoint(x, y))

                if extent_engine.intersects(geom.constGet()):
                    f.setAttributes([id])
                    f.setGeometry(geom)
                    sink.addFeature(f, QgsFeatureSink.FastInsert)
                    x += pSpacing
                    id += 1

                count += 1
                feedback.setProgress(int(count * total))

            y = y - pSpacing

        return {self.OUTPUT: dest_id}
Ejemplo n.º 51
0
    def snapGeometry(self, geometry, snapTolerance, mode=PreferNodes):
        """
        Snaps a QgsGeometry in the reference layer
        :param geometry: QgsGeometry
        :param snapTolerance: float
        :param mode: DsgGeometrySnapper.PreferNodes or DsgGeometrySnapper.PreferClosest
        :return:
        """
        center = QgsPointV2(geometry.boundingBox().center())

        # Get potential reference features and construct snap index
        refGeometries = []
        searchBounds = geometry.boundingBox()
        searchBounds.grow(snapTolerance)
        # filter by bounding box to get candidates
        refFeatureIds = self.index.intersects(searchBounds)

        # End here in case we don't find candidates
        if len(refFeatureIds) == 0:
            return geometry

        # speeding up the process to consider only intersecting geometries
        refFeatureRequest = QgsFeatureRequest().setFilterFids(refFeatureIds)
        for refFeature in self.referenceLayer.getFeatures(refFeatureRequest):
            refGeometry = refFeature.geometry()
            segments = self.breakQgsGeometryIntoSegments(refGeometry)
            # testing intersection
            for segment in segments:
                if segment.intersects(searchBounds):
                    refGeometries.append(segment)

        # End here in case we don't find geometries
        if len(refGeometries) == 0:
            return geometry

        # building geometry index
        refDict, index = self.buildReferenceIndex(refGeometries)
        refSnapIndex = DsgSnapIndex(center, 10*snapTolerance)
        for geom in refGeometries:
            refSnapIndex.addGeometry(geom.geometry())

        # Snap geometries
        subjGeom = geometry.geometry().clone()
        subjPointFlags = []

        # Pass 1: snap vertices of subject geometry to reference vertices
        for iPart in xrange(subjGeom.partCount()):
            subjPointFlags.append([])
            for iRing in xrange(subjGeom.ringCount(iPart)):
                subjPointFlags[iPart].append([])
                for iVert in xrange(self.polyLineSize(subjGeom, iPart, iRing)):
                    vidx = QgsVertexId(iPart, iRing, iVert, QgsVertexId.SegmentVertex)
                    p = QgsPointV2(subjGeom.vertexAt(vidx))
                    pF = QgsPoint(p.toQPointF())
                    snapPoint, snapSegment = refSnapIndex.getSnapItem(p, snapTolerance)
                    success = snapPoint or snapSegment
                    if not success:
                        subjPointFlags[iPart][iRing].append(DsgGeometrySnapper.Unsnapped )
                    else:
                        if mode == DsgGeometrySnapper.PreferNodes:
                            # Prefer snapping to point
                            if snapPoint:
                                subjGeom.moveVertex(vidx, snapPoint.getSnapPoint(p))
                                subjPointFlags[iPart][iRing].append(DsgGeometrySnapper.SnappedToRefNode)
                            elif snapSegment:
                                subjGeom.moveVertex( vidx, snapSegment.getSnapPoint(p))
                                subjPointFlags[iPart][iRing].append(DsgGeometrySnapper.SnappedToRefSegment)
                        elif mode == DsgGeometrySnapper.PreferClosest:
                            nodeSnap = None
                            segmentSnap = None
                            distanceNode = sys.float_info.max
                            distanceSegment = sys.float_info.max
                            if snapPoint:
                                nodeSnap = snapPoint.getSnapPoint(p)
                                nodeSnapF = QgsPoint(nodeSnap.toQPointF())
                                distanceNode = nodeSnapF.sqrDist(pF)
                            if snapSegment:
                                segmentSnap = snapSegment.getSnapPoint(p)
                                segmentSnapF = QgsPoint(segmentSnap.toQPointF())
                                distanceSegment = segmentSnapF.sqrDist(pF)
                            if snapPoint and (distanceNode < distanceSegment):
                                subjGeom.moveVertex( vidx, nodeSnap )
                                subjPointFlags[iPart][iRing].append(DsgGeometrySnapper.SnappedToRefNode)
                            elif snapSegment:
                                subjGeom.moveVertex(vidx, segmentSnap)
                                subjPointFlags[iPart][iRing].append(DsgGeometrySnapper.SnappedToRefSegment)

        #nothing more to do for points
        if isinstance(subjGeom, QgsPointV2):
            return QgsGeometry(subjGeom)
        
        # SnapIndex for subject feature
        subjSnapIndex = DsgSnapIndex(center, 10*snapTolerance)
        subjSnapIndex.addGeometry(subjGeom)
        
        origSubjGeom = subjGeom.clone()
        origSubjSnapIndex = DsgSnapIndex(center, 10*snapTolerance)
        origSubjSnapIndex.addGeometry(origSubjGeom)
        
        # Pass 2: add missing vertices to subject geometry
        for refGeom in refGeometries:
            for iPart in xrange(refGeom.geometry().partCount()):
                for iRing in xrange(refGeom.geometry().ringCount(iPart)):
                    for iVert in xrange(self.polyLineSize(refGeom.geometry(), iPart, iRing)):
                        point = refGeom.geometry().vertexAt(QgsVertexId(iPart, iRing, iVert, QgsVertexId.SegmentVertex))
                        # QgsPoint used to calculate squared distance
                        pointF = QgsPoint(point.toQPointF())
                        snapPoint, snapSegment = subjSnapIndex.getSnapItem(point, snapTolerance)
                        success = snapPoint or snapSegment
                        if success:
                            # Snap to segment, unless a subject point was already snapped to the reference point
                            if snapPoint and (QgsPoint(snapPoint.getSnapPoint(point).toQPointF()).sqrDist(pointF) < 1E-16):
                                continue
                            elif snapSegment:
                                # Look if there is a closer reference segment, if so, ignore this point
                                pProj = snapSegment.getSnapPoint(point)
                                pProjF = QgsPoint(pProj.toQPointF())
                                closest = refSnapIndex.getClosestSnapToPoint(point, pProj)
                                closestF = QgsPoint(closest.toQPointF())
                                if pProjF.sqrDist(pointF) > pProjF.sqrDist(closestF):
                                    continue
                                # If we are too far away from the original geometry, do nothing
                                if not origSubjSnapIndex.getSnapItem(point, snapTolerance):
                                    continue
                                idx = snapSegment.idxFrom
                                subjGeom.insertVertex(QgsVertexId(idx.vidx.part, idx.vidx.ring, idx.vidx.vertex + 1, QgsVertexId.SegmentVertex), point)
                                subjPointFlags[idx.vidx.part][idx.vidx.ring].insert(idx.vidx.vertex + 1, DsgGeometrySnapper.SnappedToRefNode )
                                subjSnapIndex = DsgSnapIndex(center, 10*snapTolerance)
                                subjSnapIndex.addGeometry(subjGeom)

        # Pass 3: remove superfluous vertices: all vertices which are snapped to a segment and not preceded or succeeded by an unsnapped vertex
        for iPart in xrange(subjGeom.partCount()):
            for iRing in xrange(subjGeom.ringCount(iPart)):
                ringIsClosed = subjGeom.vertexAt(QgsVertexId(iPart, iRing, 0, QgsVertexId.SegmentVertex)) == subjGeom.vertexAt(QgsVertexId(iPart, iRing, subjGeom.vertexCount( iPart, iRing ) - 1, QgsVertexId.SegmentVertex))
                nVerts = self.polyLineSize(subjGeom, iPart, iRing)
                iVert = 0
                while iVert < nVerts:
                    iPrev = ( iVert - 1 + nVerts ) % nVerts
                    iNext = ( iVert + 1 ) % nVerts
                    pMid = subjGeom.vertexAt(QgsVertexId( iPart, iRing, iVert, QgsVertexId.SegmentVertex))
                    pPrev = subjGeom.vertexAt(QgsVertexId( iPart, iRing, iPrev, QgsVertexId.SegmentVertex))
                    pNext = subjGeom.vertexAt(QgsVertexId( iPart, iRing, iNext, QgsVertexId.SegmentVertex))

                    pointOnSeg = self.projPointOnSegment( pMid, pPrev, pNext)
                    pointOnSegF = QgsPoint(pointOnSeg.toQPointF())
                    pMidF = QgsPoint(pMid.toQPointF())
                    dist = pointOnSegF.sqrDist(pMidF)

                    if subjPointFlags[iPart][iRing][iVert] == DsgGeometrySnapper.SnappedToRefSegment \
                     and subjPointFlags[iPart][iRing][iPrev] != DsgGeometrySnapper.Unsnapped \
                     and subjPointFlags[iPart][iRing][iNext] != DsgGeometrySnapper.Unsnapped \
                     and dist < 1E-12:
                        if (ringIsClosed and nVerts > 3 ) or ( not ringIsClosed and nVerts > 2 ):
                            subjGeom.deleteVertex(QgsVertexId(iPart, iRing, iVert, QgsVertexId.SegmentVertex))
                            del subjPointFlags[iPart][iRing][iVert]
                            iVert -= 1
                            nVerts -= 1
                        else:
                            # Don't delete vertices if this would result in a degenerate geometry
                            break
                    iVert += 1
        return QgsGeometry(subjGeom)
Ejemplo n.º 52
0
 def setUp(self):
     self.mPoint = QgsPoint(10.0, 10.0)
Ejemplo n.º 53
0
 def testQgsPointRepr(self):
     p = QgsPoint(123.456, 987.654, 100)
     self.assertTrue(p.__repr__().startswith('<QgsPoint: PointZ (123.456'))
Ejemplo n.º 54
0
def UpdateBeamsData(packet, cornerPointUL, cornerPointUR, cornerPointLR,
                    cornerPointLL, ele):
    ''' Update Beams Values '''
    lat = packet.SensorLatitude
    lon = packet.SensorLongitude
    alt = packet.SensorTrueAltitude

    beamsLyr = qgsu.selectLayerByName(Beams_lyr)

    try:
        if all(v is not None for v in [
                beamsLyr, lat, lon, alt, cornerPointUL, cornerPointUR,
                cornerPointLR, cornerPointLL
        ]) and all(v >= 2 for v in [
                len(cornerPointUL),
                len(cornerPointUR),
                len(cornerPointLR),
                len(cornerPointLL)
        ]):
            beamsLyr.startEditing()
            if beamsLyr.featureCount() == 0:

                # UL
                featureUL = QgsFeature()
                featureUL.setAttributes(
                    [lon, lat, alt, cornerPointUL[1], cornerPointUL[0]])
                featureUL.setGeometry(
                    QgsLineString(QgsPoint(lon, lat, alt),
                                  QgsPoint(cornerPointUL[1],
                                           cornerPointUL[0])))
                beamsLyr.addFeatures([featureUL])
                # UR
                featureUR = QgsFeature()
                featureUR.setAttributes(
                    [lon, lat, alt, cornerPointUR[1], cornerPointUR[0]])
                featureUR.setGeometry(
                    QgsLineString(QgsPoint(lon, lat, alt),
                                  QgsPoint(cornerPointUR[1],
                                           cornerPointUR[0])))
                beamsLyr.addFeatures([featureUR])
                # LR
                featureLR = QgsFeature()
                featureLR.setAttributes(
                    [lon, lat, alt, cornerPointLR[1], cornerPointLR[0]])
                featureLR.setGeometry(
                    QgsLineString(QgsPoint(lon, lat, alt),
                                  QgsPoint(cornerPointLR[1],
                                           cornerPointLR[0])))
                beamsLyr.addFeatures([featureLR])
                # LL
                featureLL = QgsFeature()
                featureLL.setAttributes(
                    [lon, lat, alt, cornerPointLL[1], cornerPointLL[0]])
                featureLL.setGeometry(
                    QgsLineString(QgsPoint(lon, lat, alt),
                                  QgsPoint(cornerPointLL[1],
                                           cornerPointLL[0])))
                beamsLyr.addFeatures([featureLL])

            else:
                # UL
                beamsLyr.dataProvider().changeAttributeValues({
                    1: {
                        0: lon,
                        1: lat,
                        2: alt,
                        3: cornerPointUL[1],
                        4: cornerPointUL[0]
                    }
                })
                beamsLyr.dataProvider().changeGeometryValues({
                    1:
                    QgsGeometry(
                        QgsLineString(
                            QgsPoint(lon, lat, alt),
                            QgsPoint(cornerPointUL[1], cornerPointUL[0])))
                })
                # UR
                beamsLyr.dataProvider().changeAttributeValues({
                    2: {
                        0: lon,
                        1: lat,
                        2: alt,
                        3: cornerPointUR[1],
                        4: cornerPointUR[0]
                    }
                })
                beamsLyr.dataProvider().changeGeometryValues({
                    2:
                    QgsGeometry(
                        QgsLineString(
                            QgsPoint(lon, lat, alt),
                            QgsPoint(cornerPointUR[1], cornerPointUR[0])))
                })
                # LR
                beamsLyr.dataProvider().changeAttributeValues({
                    3: {
                        0: lon,
                        1: lat,
                        2: alt,
                        3: cornerPointLR[1],
                        4: cornerPointLR[0]
                    }
                })
                beamsLyr.dataProvider().changeGeometryValues({
                    3:
                    QgsGeometry(
                        QgsLineString(
                            QgsPoint(lon, lat, alt),
                            QgsPoint(cornerPointLR[1], cornerPointLR[0])))
                })
                # LL
                beamsLyr.dataProvider().changeAttributeValues({
                    4: {
                        0: lon,
                        1: lat,
                        2: alt,
                        3: cornerPointLL[1],
                        4: cornerPointLL[0]
                    }
                })
                beamsLyr.dataProvider().changeGeometryValues({
                    4:
                    QgsGeometry(
                        QgsLineString(
                            QgsPoint(lon, lat, alt),
                            QgsPoint(cornerPointLL[1], cornerPointLL[0])))
                })

            CommonLayer(beamsLyr)
            # 3D Style
            if ele:
                SetDefaultBeams3DStyle(beamsLyr)

    except Exception as e:
        qgsu.showUserAndLogMessage(
            QCoreApplication.translate("QgsFmvUtils",
                                       "Failed Update Beams Layer! : "),
            str(e))
    return
Ejemplo n.º 55
0
    def processAlgorithm(self, feedback):
        radius = self.getParameterValue(self.DISTANCE)
        horizontal = self.getParameterValue(self.HORIZONTAL)
        output = self.getOutputFromName(self.OUTPUT_LAYER)

        layer = dataobjects.getLayerFromString(
            self.getParameterValue(self.INPUT_LAYER))

        writer = output.getVectorWriter(layer.fields(), layer.wkbType(),
                                        layer.crs())

        features = vector.features(layer)

        total = 100.0 / len(features)

        duplicates = dict()
        for current, f in enumerate(features):
            wkt = f.geometry().exportToWkt()
            if wkt not in duplicates:
                duplicates[wkt] = [f.id()]
            else:
                duplicates[wkt].extend([f.id()])

            feedback.setProgress(int(current * total))

        current = 0
        total = 100.0 / len(duplicates)
        feedback.setProgress(0)

        fullPerimeter = 2 * math.pi

        for (geom, fids) in list(duplicates.items()):
            count = len(fids)
            if count == 1:
                f = next(
                    layer.getFeatures(QgsFeatureRequest().setFilterFid(
                        fids[0])))
                writer.addFeature(f)
            else:
                angleStep = fullPerimeter / count
                if count == 2 and horizontal:
                    currentAngle = math.pi / 2
                else:
                    currentAngle = 0

                old_point = QgsGeometry.fromWkt(geom).asPoint()

                request = QgsFeatureRequest().setFilterFids(fids).setFlags(
                    QgsFeatureRequest.NoGeometry)
                for f in layer.getFeatures(request):
                    sinusCurrentAngle = math.sin(currentAngle)
                    cosinusCurrentAngle = math.cos(currentAngle)
                    dx = radius * sinusCurrentAngle
                    dy = radius * cosinusCurrentAngle

                    new_point = QgsPoint(old_point.x() + dx,
                                         old_point.y() + dy)
                    out_feature = QgsFeature()
                    out_feature.setGeometry(QgsGeometry.fromPoint(new_point))
                    out_feature.setAttributes(f.attributes())

                    writer.addFeature(out_feature)
                    currentAngle += angleStep

            current += 1
            feedback.setProgress(int(current * total))

        del writer
Ejemplo n.º 56
0
 def testQgsLineStringRepr(self):
     ls = QgsLineString([QgsPoint(10, 2), QgsPoint(10, 1), QgsPoint(5, 1)])
     self.assertEqual(ls.__repr__(), '<QgsLineString: LineString (10 2, 10 1, 5 1)>')
Ejemplo n.º 57
0
    def testLengthMeasureAndUnits(self):
        """Test a variety of length measurements in different CRS and ellipsoid modes, to check that the
           calculated lengths and units are always consistent
        """

        da = QgsDistanceArea()
        da.setSourceCrs(3452)
        da.setEllipsoidalMode(False)
        da.setEllipsoid("NONE")
        daCRS = QgsCoordinateReferenceSystem()
        daCRS = da.sourceCrs()

        # We check both the measured length AND the units, in case the logic regarding
        # ellipsoids and units changes in future
        distance = da.measureLine(QgsPoint(1, 1), QgsPoint(2, 3))
        units = da.lengthUnits()

        print(("measured {} in {}".format(distance,
                                          QgsUnitTypes.toString(units))))
        assert ((abs(distance - 2.23606797) < 0.00000001
                 and units == QgsUnitTypes.DistanceDegrees)
                or (abs(distance - 248.52) < 0.01
                    and units == QgsUnitTypes.DistanceMeters))

        da.setEllipsoid("WGS84")
        distance = da.measureLine(QgsPoint(1, 1), QgsPoint(2, 3))
        units = da.lengthUnits()

        print(("measured {} in {}".format(distance,
                                          QgsUnitTypes.toString(units))))
        assert ((abs(distance - 2.23606797) < 0.00000001
                 and units == QgsUnitTypes.DistanceDegrees)
                or (abs(distance - 248.52) < 0.01
                    and units == QgsUnitTypes.DistanceMeters))

        da.setEllipsoidalMode(True)
        distance = da.measureLine(QgsPoint(1, 1), QgsPoint(2, 3))
        units = da.lengthUnits()

        print(("measured {} in {}".format(distance,
                                          QgsUnitTypes.toString(units))))
        # should always be in Meters
        self.assertAlmostEqual(distance, 247555.57, delta=0.01)
        self.assertEqual(units, QgsUnitTypes.DistanceMeters)

        # test converting the resultant length
        distance = da.convertLengthMeasurement(
            distance, QgsUnitTypes.DistanceNauticalMiles)
        self.assertAlmostEqual(distance, 133.669, delta=0.01)

        # now try with a source CRS which is in feet
        da.setSourceCrs(27469)
        da.setEllipsoidalMode(False)
        # measurement should be in feet
        distance = da.measureLine(QgsPoint(1, 1), QgsPoint(2, 3))
        units = da.lengthUnits()
        print(("measured {} in {}".format(distance,
                                          QgsUnitTypes.toString(units))))
        self.assertAlmostEqual(distance, 2.23606797, delta=0.000001)
        self.assertEqual(units, QgsUnitTypes.DistanceFeet)

        # test converting the resultant length
        distance = da.convertLengthMeasurement(distance,
                                               QgsUnitTypes.DistanceMeters)
        self.assertAlmostEqual(distance, 0.6815, delta=0.001)

        da.setEllipsoidalMode(True)
        # now should be in Meters again
        distance = da.measureLine(QgsPoint(1, 1), QgsPoint(2, 3))
        units = da.lengthUnits()
        print(("measured {} in {}".format(distance,
                                          QgsUnitTypes.toString(units))))
        self.assertAlmostEqual(distance, 0.67953772, delta=0.000001)
        self.assertEqual(units, QgsUnitTypes.DistanceMeters)

        # test converting the resultant length
        distance = da.convertLengthMeasurement(distance,
                                               QgsUnitTypes.DistanceFeet)
        self.assertAlmostEqual(distance, 2.2294, delta=0.001)
Ejemplo n.º 58
0
    def processAlgorithm(self, progress):
        layer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.VECTOR))
        fieldName = self.getParameterValue(self.FIELD)
        minDistance = float(self.getParameterValue(self.MIN_DISTANCE))
        strategy = self.getParameterValue(self.STRATEGY)

        fields = QgsFields()
        fields.append(QgsField('id', QVariant.Int, '', 10, 0))
        writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(
            fields, QgsWkbTypes.Point, layer.crs())

        da = QgsDistanceArea()

        features = vector.features(layer)
        for current, f in enumerate(features):
            fGeom = f.geometry()
            bbox = fGeom.boundingBox()
            if strategy == 0:
                pointCount = int(f[fieldName])
            else:
                pointCount = int(round(f[fieldName] * da.measureArea(fGeom)))

            if strategy == 0 and pointCount == 0:
                continue

            index = QgsSpatialIndex()
            points = dict()

            nPoints = 0
            nIterations = 0
            maxIterations = pointCount * 200
            total = 100.0 / pointCount

            random.seed()

            while nIterations < maxIterations and nPoints < pointCount:
                rx = bbox.xMinimum() + bbox.width() * random.random()
                ry = bbox.yMinimum() + bbox.height() * random.random()

                pnt = QgsPoint(rx, ry)
                geom = QgsGeometry.fromPoint(pnt)
                if geom.within(fGeom) and \
                   vector.checkMinDistance(pnt, index, minDistance, points):
                    f = QgsFeature(nPoints)
                    f.initAttributes(1)
                    f.setFields(fields)
                    f.setAttribute('id', nPoints)
                    f.setGeometry(geom)
                    writer.addFeature(f)
                    index.insertFeature(f)
                    points[nPoints] = pnt
                    nPoints += 1
                    progress.setPercentage(int(nPoints * total))
                nIterations += 1

            if nPoints < pointCount:
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_INFO,
                    self.tr('Can not generate requested number of random '
                            'points. Maximum number of attempts exceeded.'))

            progress.setPercentage(0)

        del writer
Ejemplo n.º 59
0
    def processAlgorithm(self, feedback):
        layer = dataobjects.getObjectFromUri(
            self.getParameterValue(self.INPUT_VECTOR))
        startPoint = self.getParameterValue(self.START_POINT)
        endPoint = self.getParameterValue(self.END_POINT)
        strategy = self.getParameterValue(self.STRATEGY)

        directionFieldName = self.getParameterValue(self.DIRECTION_FIELD)
        forwardValue = self.getParameterValue(self.VALUE_FORWARD)
        backwardValue = self.getParameterValue(self.VALUE_BACKWARD)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        bothValue = self.getParameterValue(self.VALUE_BOTH)
        defaultDirection = self.getParameterValue(self.DEFAULT_DIRECTION)
        speedFieldName = self.getParameterValue(self.SPEED_FIELD)
        defaultSpeed = self.getParameterValue(self.DEFAULT_SPEED)
        tolerance = self.getParameterValue(self.TOLERANCE)

        fields = QgsFields()
        fields.append(QgsField('start', QVariant.String, '', 254, 0))
        fields.append(QgsField('end', QVariant.String, '', 254, 0))
        fields.append(QgsField('cost', QVariant.Double, '', 20, 7))

        writer = self.getOutputFromName(
            self.OUTPUT_LAYER).getVectorWriter(
                fields.toList(),
                QgsWkbTypes.LineString,
                layer.crs())

        tmp = startPoint.split(',')
        startPoint = QgsPoint(float(tmp[0]), float(tmp[1]))
        tmp = endPoint.split(',')
        endPoint = QgsPoint(float(tmp[0]), float(tmp[1]))

        directionField = -1
        if directionFieldName is not None:
            directionField = layer.fields().lookupField(directionFieldName)
        speedField = -1
        if speedFieldName is not None:
            speedField = layer.fields().lookupField(speedFieldName)

        director = QgsVectorLayerDirector(layer,
                                          directionField,
                                          forwardValue,
                                          backwardValue,
                                          bothValue,
                                          defaultDirection)

        distUnit = iface.mapCanvas().mapSettings().destinationCrs().mapUnits()
        multiplier = QgsUnitTypes.fromUnitToUnitFactor(distUnit, QgsUnitTypes.DistanceMeters)
        if strategy == 0:
            strategy = QgsNetworkDistanceStrategy()
        else:
            strategy = QgsNetworkSpeedStrategy(speedField,
                                               defaultSpeed,
                                               multiplier * 1000.0 / 3600.0)
            multiplier = 3600

        director.addStrategy(strategy)
        builder = QgsGraphBuilder(iface.mapCanvas().mapSettings().destinationCrs(),
                                  iface.mapCanvas().hasCrsTransformEnabled(),
                                  tolerance)
        feedback.pushInfo(self.tr('Building graph...'))
        snappedPoints = director.makeGraph(builder, [startPoint, endPoint])

        feedback.pushInfo(self.tr('Calculating shortest path...'))
        graph = builder.graph()
        idxStart = graph.findVertex(snappedPoints[0])
        idxEnd = graph.findVertex(snappedPoints[1])

        tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0)
        if tree[idxEnd] == -1:
            raise GeoAlgorithmExecutionException(
                self.tr('There is no route from start point to end point.'))

        route = []
        cost = 0.0
        current = idxEnd
        while current != idxStart:
            cost += graph.edge(tree[current]).cost(0)
            route.append(graph.vertex(graph.edge(tree[current]).inVertex()).point())
            current = graph.edge(tree[current]).outVertex()

        route.append(snappedPoints[0])
        route.reverse()

        self.setOutputValue(self.TRAVEL_COST, cost / multiplier)

        feedback.pushInfo(self.tr('Writing results...'))
        geom = QgsGeometry.fromPolyline(route)
        feat = QgsFeature()
        feat.setFields(fields)
        feat['start'] = startPoint.toString()
        feat['end'] = endPoint.toString()
        feat['cost'] = cost / multiplier
        feat.setGeometry(geom)
        writer.addFeature(feat)
        del writer
Ejemplo n.º 60
0
    def testAreaMeasureAndUnits(self):
        """Test a variety of area measurements in different CRS and ellipsoid modes, to check that the
           calculated areas and units are always consistent
        """

        da = QgsDistanceArea()
        da.setSourceCrs(3452)
        da.setEllipsoidalMode(False)
        da.setEllipsoid("NONE")
        daCRS = QgsCoordinateReferenceSystem()
        daCRS = da.sourceCrs()

        polygon = QgsGeometry.fromPolygon([[
            QgsPoint(0, 0),
            QgsPoint(1, 0),
            QgsPoint(1, 1),
            QgsPoint(2, 1),
            QgsPoint(2, 2),
            QgsPoint(0, 2),
            QgsPoint(0, 0),
        ]])

        # We check both the measured area AND the units, in case the logic regarding
        # ellipsoids and units changes in future
        area = da.measureArea(polygon)
        units = da.areaUnits()

        print(("measured {} in {}".format(area, QgsUnitTypes.toString(units))))
        assert ((abs(area - 3.0) < 0.00000001
                 and units == QgsUnitTypes.AreaSquareDegrees)
                or (abs(area - 37176087091.5) < 0.1
                    and units == QgsUnitTypes.AreaSquareMeters))

        da.setEllipsoid("WGS84")
        area = da.measureArea(polygon)
        units = da.areaUnits()

        print(("measured {} in {}".format(area, QgsUnitTypes.toString(units))))
        assert ((abs(area - 3.0) < 0.00000001
                 and units == QgsUnitTypes.AreaSquareDegrees)
                or (abs(area - 37176087091.5) < 0.1
                    and units == QgsUnitTypes.AreaSquareMeters))

        da.setEllipsoidalMode(True)
        area = da.measureArea(polygon)
        units = da.areaUnits()

        print(("measured {} in {}".format(area, QgsUnitTypes.toString(units))))
        # should always be in Meters Squared
        self.assertAlmostEqual(area, 37416879192.9, delta=0.1)
        self.assertEqual(units, QgsUnitTypes.AreaSquareMeters)

        # test converting the resultant area
        area = da.convertAreaMeasurement(area, QgsUnitTypes.AreaSquareMiles)
        self.assertAlmostEqual(area, 14446.7378, delta=0.001)

        # now try with a source CRS which is in feet
        polygon = QgsGeometry.fromPolygon([[
            QgsPoint(1850000, 4423000),
            QgsPoint(1851000, 4423000),
            QgsPoint(1851000, 4424000),
            QgsPoint(1852000, 4424000),
            QgsPoint(1852000, 4425000),
            QgsPoint(1851000, 4425000),
            QgsPoint(1850000, 4423000)
        ]])
        da.setSourceCrs(27469)
        da.setEllipsoidalMode(False)
        # measurement should be in square feet
        area = da.measureArea(polygon)
        units = da.areaUnits()
        print(("measured {} in {}".format(area, QgsUnitTypes.toString(units))))
        self.assertAlmostEqual(area, 2000000, delta=0.001)
        self.assertEqual(units, QgsUnitTypes.AreaSquareFeet)

        # test converting the resultant area
        area = da.convertAreaMeasurement(area, QgsUnitTypes.AreaSquareYards)
        self.assertAlmostEqual(area, 222222.2222, delta=0.001)

        da.setEllipsoidalMode(True)
        # now should be in Square Meters again
        area = da.measureArea(polygon)
        units = da.areaUnits()
        print(("measured {} in {}".format(area, QgsUnitTypes.toString(units))))
        self.assertAlmostEqual(area, 184149.37, delta=1.0)
        self.assertEqual(units, QgsUnitTypes.AreaSquareMeters)

        # test converting the resultant area
        area = da.convertAreaMeasurement(area, QgsUnitTypes.AreaSquareYards)
        self.assertAlmostEqual(area, 220240.8172549, delta=1.0)