コード例 #1
0
    def getPoint(self, mapPoint):
        self.set_rad.setEnabled(True)
        # change tool so you don't get more than one POI
        self.canvas.unsetMapTool(self.emitPoint)
        self.canvas.setMapTool(self.userTool)
        # Get the click
        if mapPoint:
            self.atk_pt = QgsPoint(mapPoint)
            self.distance()
            # Specify the geometry type
            layer = QgsVectorLayer('Point?crs=epsg:28992', 'Attack Point',
                                   'memory')

            style = "style_attack.qml"
            qml_path = self.plugin_dir + "/data/" + style
            layer.loadNamedStyle(qml_path)
            layer.triggerRepaint()

            # Set the provider to accept the data source
            prov = layer.dataProvider()

            # Add a new feature and assign the geometry
            feat = QgsFeature()
            feat.setGeometry(QgsGeometry.fromPoint(mapPoint))
            prov.addFeatures([feat])

            # Update extent of the layer
            layer.updateExtents()

            # Add the layer to the Layers panel
            QgsMapLayerRegistry.instance().addMapLayers([layer])
コード例 #2
0
    def evacuateThis(self):
        # Write to log
        time = strftime("%d-%m-%Y %H:%M:%S", localtime())
        evac_type = self.to_evac_info.item(0, 0).text()
        to_evac = self.to_evac_info.item(1, 0).text()
        adr = self.to_evac_info.item(2, 0).text()
        pop = int(self.to_evac_info.item(3, 0).text())
        log_str = time + ":" + "\nBuilding selected for evacuation." \
                               "\nType:\t%s\nName:\t%s\nAddress:\t%s\nPredicted pop:\t%d\n" %(evac_type, to_evac, adr, pop)
        self.log.append(log_str)

        evac_type = self.shelter_info.item(0, 0).text()
        to_evac = self.shelter_info.item(1, 0).text()
        adr = self.shelter_info.item(2, 0).text()
        log_str = "Evacuate to:\nType:\t%s\nName:\t%s\nAddress:\t%s\n" % (
            evac_type, to_evac, adr)
        self.log.append(log_str)

        # Mark things as DONE
        if not (uf.getLegendLayerByName(self.iface, "Done")):
            done = QgsVectorLayer('Point?crs=epsg:28992', 'Done', 'memory')
            QgsMapLayerRegistry.instance().addMapLayers([done])
            style = "style for green marks.qml"
            qml_path = self.plugin_dir + "/data/" + style
            done.loadNamedStyle(qml_path)
            done.triggerRepaint()
        prov = uf.getLegendLayerByName(self.iface, "Done").dataProvider()
        prov.addFeatures([self.evac_feat])
        self.refreshCanvas(uf.getLegendLayerByName(self.iface, "Done"))

        # Store Selected Routes
        lay1 = uf.getLegendLayerByName(self.iface, "Selected Routes")
        if not (lay1):
            selected = QgsVectorLayer('LINESTRING?crs=epsg:28992',
                                      'Selected Routes', 'memory')
            QgsMapLayerRegistry.instance().addMapLayers([selected])
            style = "style_blue_routes.qml"
            qml_path = self.plugin_dir + "/data/" + style
            selected.loadNamedStyle(qml_path)
            selected.triggerRepaint()
            iface.legendInterface().setLayerVisible(selected, False)
        prov = uf.getLegendLayerByName(self.iface,
                                       "Selected Routes").dataProvider()
        if uf.getLegendLayerByName(self.iface, "Routes"):
            route_layer = uf.getLegendLayerByName(self.iface, "Routes")
            feats = route_layer.getFeatures()
        for feat in feats:
            prov.addFeatures([feat])
        self.refreshCanvas(
            uf.getLegendLayerByName(self.iface, "Selected Routes"))

        uf.addFields(lay1, ['number'], [QVariant.Int])
        uf.updateField(lay1, 'number', 'rand(1,100)')

        # Lower capacity of shelter
        layer = uf.getLegendLayerByName(self.iface, "Shelters")
        layer.startEditing()
        cap = int(self.shelter_info.item(3, 0).text())
        m = cap - pop
        if m > 0:
            layer.changeAttributeValue(self.shel_feat.id(), 8, cap - pop)
        else:
            layer.changeAttributeValue(self.shel_feat.id(), 8, 0)
        layer.commitChanges()

        # Change Number of Buildings to Evacuate
        build = uf.getLegendLayerByName(iface, "Buildings to evacuate")
        buildings = build.getFeatures()
        n = 0
        for building in buildings:
            if building.attributes()[2] != 'police' and building.attributes(
            )[2] != 'fire_station':
                n += 1

        ev = uf.getLegendLayerByName(iface, "Selected Routes")
        evacs = ev.getFeatures()
        m = 0
        for evac in evacs:
            m += 1

        self.buildings.clear()
        if n - m > 0:
            self.buildings.append('%s' % (n - m))
        else:
            self.buildings.append('0')

        # Display confirmation message
        self.sent_msg.setVisible(True)
        QTimer.singleShot(3000, lambda: (self.sent_msg.setVisible(False)))

        # Clear selections to start picking new targets
        self.deleteEvac()
コード例 #3
0
    def on_webViewProcessingStatus_loadFinished(self):
        """Task done"""
        QgsMessageLog.logMessage('Load results')
        self.dlg.statusBarProcessing2.setValue(60)
        xmlCropRowsResultsProcessing = (os.path.join(
            self.dlg.inputSharedFolderPath.text(), 'results',
            ('results_' + self.dlg.xmlCoreFile.text())))
        #check if result file exists
        QgsMessageLog.logMessage('XML Result File: ' +
                                 str(xmlCropRowsResultsProcessing))
        QgsMessageLog.logMessage('results_' + self.dlg.xmlCoreFile.text())
        self.dlg.statusBarProcessing2.setValue(65)

        if (os.path.exists(xmlCropRowsResultsProcessing) == False):
            #print("No croprows result file found !")
            QgsMessageLog.logMessage('No croprows result file found !')
        else:
            source = open(xmlCropRowsResultsProcessing, 'rb')
            tree = ET.parse(source)
            root = tree.getroot()
            for filexml in root.findall('filename'):
                resultVectorialFile = filexml.find('result').text
                resultVectorialBufferFile = filexml.find('buffer').text
                #print(resultVectorialFile)
                QgsMessageLog.logMessage(str(resultVectorialFile))
                QgsMessageLog.logMessage(str(resultVectorialBufferFile))
                resultTileFile = filexml.find('tile').text
                #print(resultTileFile)
                QgsMessageLog.logMessage(str(resultTileFile))
                self.dlg.statusBarProcessing2.setValue(60)
                #load result into qgis
                temporalPath = self.dlg.inputSharedFolderPath.text().replace(
                    "/", "\\")
                outputFileMaskPath = os.path.join(temporalPath, "results",
                                                  resultVectorialFile)
                outputFileMaskBufferPath = os.path.join(
                    temporalPath, "results", resultVectorialBufferFile)

                maskVectorLayerExported = QgsVectorLayer(
                    outputFileMaskPath, "croprows_lines", "ogr")
                maskVectorLayerBufferExported = QgsVectorLayer(
                    outputFileMaskBufferPath, "croprows_lines_buffer", "ogr")
                self.dlg.statusBarProcessing2.setValue(70)
                #style for croprows lines result shapefile
                styleCropRows = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_croplines.qml')
                maskVectorLayerExported.loadNamedStyle(styleCropRows)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported)
                QgsProject.instance().addMapLayer(maskVectorLayerExported)
                self.dlg.statusBarProcessing2.setValue(80)

                #style for buffer croprows lines result shapefile
                styleCropRowsBuf = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_buffer.qml')
                maskVectorLayerBufferExported.loadNamedStyle(styleCropRowsBuf)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerBufferExported)
                QgsProject.instance().addMapLayer(
                    maskVectorLayerBufferExported)
                self.dlg.statusBarProcessing2.setValue(85)

                outputFileTilePath = os.path.join(temporalPath, "results",
                                                  resultTileFile)
                maskVectorLayerTileExported = QgsVectorLayer(
                    outputFileTilePath, "croprows_tiles", "ogr")
                self.dlg.statusBarProcessing2.setValue(90)
                #style for croprows tiles geojson
                styleTiles = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_tileindex.qml')
                maskVectorLayerTileExported.loadNamedStyle(styleTiles)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerTileExported)
                QgsProject.instance().addMapLayer(maskVectorLayerTileExported)

                self.dlg.outputfilename.setText(str(outputFileMaskPath))
            self.dlg.statusBarProcessing2.setValue(100)
            source.close()
            del source
        QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)
        QMessageBox.information(
            None, 'Message !',
            "Crop Rows Generation Done !<br><b>Check Crop Rows Results ! <b/>",
            QMessageBox.Ok)
        self.dlg.close()
        reloadPlugin('PACropRows')
コード例 #4
0
    def executeCropRowsClipProcessing(self):
        """Execute Crop Rows STEP 1"""
        QgsMessageLog.logMessage(
            'Excecute Task1: Clip Raster Mosaic by Vector Mask')
        strMosaicRasterFileSelected = self.dlg.comboBoxInputRaster.currentText(
        )
        strMaskVectorFileSelected = self.dlg.comboBoxInputVector.currentText()

        seedValue = 0
        QgsMessageLog.logMessage('Get Seed from user selection')
        if self.dlg.radioButtonSeed1.isChecked() == True:
            seedValue = 1
        elif self.dlg.radioButtonSeed2.isChecked() == True:
            seedValue = 2
        elif self.dlg.radioButtonSeed3.isChecked() == True:
            seedValue = 3
        elif self.dlg.radioButtonSeed4.isChecked() == True:
            seedValue = 4

        if (seedValue == 0):
            QgsMessageLog.logMessage('You must be set a seed value !')
            QMessageBox.critical(None, 'Error!',
                                 "You must be set a <b>seed</b> value !",
                                 QMessageBox.Ok)
            pass
        else:
            QgsMessageLog.logMessage('Seed value: ' + str(seedValue))

        #Start Crop Rows processing
        if strMosaicRasterFileSelected != '' and strMaskVectorFileSelected != '' and seedValue > 0 and self.flagClipTaskDone == 0:
            if self.flagNoCropRaster == False:
                msgboxCrop = "Are you sure that you want to start a <b>Mosaic Clip by Mask</b> process?<br>Keep in mind this task can take a few minutes, even several hours."
            else:
                msgboxCrop = "Are you sure that you want to copy a raster <b>Mosaic</b> into a selected shared folder?<br>Keep in mind this process can take a few minutes, even several hours."
            ret = QMessageBox.question(None, "Mosaic Data Preprocessing",
                                       (msgboxCrop),
                                       QMessageBox.Yes | QMessageBox.No,
                                       QMessageBox.Yes)
            if ret == QMessageBox.Yes:
                #hide step1 button
                self.dlg.btnExecuteClippingTask.setVisible(False)
                QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

                self.dlg.statusBarProcessing.setGeometry(10, 281, 631, 31)

                self.dlg.statusBarProcessing.setValue(1)
                QgsMessageLog.logMessage('Processing Raster ')
                #urlSourceRasterMosaic = QgsMapLayerRegistry.instance().mapLayersByName(strMosaicRasterFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceRasterMosaic = QgsProject.instance().mapLayersByName(
                    strMosaicRasterFileSelected)[0].dataProvider(
                    ).dataSourceUri()
                self.dlg.statusBarProcessing.setValue(5)
                #urlSourceVectorMask = QgsMapLayerRegistry.instance().mapLayersByName(strMaskVectorFileSelected)[0].dataProvider().dataSourceUri()
                urlSourceVectorMask = QgsProject.instance().mapLayersByName(
                    strMaskVectorFileSelected)[0].dataProvider().dataSourceUri(
                    )
                self.dlg.statusBarProcessing.setValue(10)
                urlSourceVectorMaskSplit = urlSourceVectorMask.split("|")[0]
                self.dlg.statusBarProcessing.setValue(20)
                temporalPath = self.dlg.inputSharedFolderPath.text().replace(
                    "/", "\\")
                rasterLyr = QgsRasterLayer(urlSourceRasterMosaic, "masklayer")
                pixelSizeX = rasterLyr.rasterUnitsPerPixelX()
                pixelSizeY = rasterLyr.rasterUnitsPerPixelY()
                self.dlg.statusBarProcessing.setValue(25)

                QgsMessageLog.logMessage(str(urlSourceRasterMosaic))
                QgsMessageLog.logMessage(str(urlSourceVectorMaskSplit))
                QgsMessageLog.logMessage('GDAL Clipper')
                QgsMessageLog.logMessage(str(pixelSizeX))
                QgsMessageLog.logMessage(str(pixelSizeY))

                gdalOSGeoPath = self.dlg.inputGdalOsgeoPath.text().replace(
                    "/", "\\")
                #temporalPath = self.dlg.inputSharedFolderPath.text().replace("/", "\\")
                self.dlg.statusBarProcessing.setValue(30)
                timestr = time.strftime("%Y%m%d-%H%M%S")
                ouputFilenameRasterClip = 'clipfile_' + timestr + '.tif'
                ouputFilenameVectorMask = 'maskfile_' + timestr + '.shp'
                ouputFilenamePrj = 'croprows_' + timestr
                ouputFilenameCropRowsProjectXML = 'croprows_' + timestr + '.xml'
                ouputclipfile_path = os.path.join(temporalPath,
                                                  ouputFilenameRasterClip)
                #temporalPath.replace("/", "\\") + ouputFilenameRasterClip
                self.dlg.statusBarProcessing.setValue(35)

                if self.flagNoCropRaster == True:
                    QgsMessageLog.logMessage(
                        'No Crop option selected - Copy file directly')
                    shutil.copyfile(
                        urlSourceRasterMosaic,
                        os.path.join(ouputclipfile_path[:-4] + '.tif'))
                    self.dlg.statusBarProcessing.setValue(40)
                else:
                    QgsMessageLog.logMessage(
                        'Crop raster by mask option selected - Cliping using GDAL'
                    )
                    #print('C:/Program Files/QGIS 2.14/bin/gdalwarp')
                    gdalWarpSubProcessCommand = '"' + gdalOSGeoPath + "\\" + 'gdalwarp.exe" -dstnodata -9999 -q -cutline ' + urlSourceVectorMaskSplit.replace(
                        "/", "\\") + ' -crop_to_cutline -tr ' + str(
                            pixelSizeX) + ' ' + str(
                                pixelSizeX
                            ) + ' -of GTiff ' + urlSourceRasterMosaic.replace(
                                "/", "\\") + ' ' + ouputclipfile_path
                    QgsMessageLog.logMessage(str(gdalWarpSubProcessCommand))
                    self.dlg.statusBarProcessing.setValue(40)
                    p = subprocess.Popen(gdalWarpSubProcessCommand,
                                         shell=True,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
                    for line in p.stdout.readlines():
                        print(line),
                        retval = p.wait()

                self.dlg.statusBarProcessing.setValue(50)
                QgsMessageLog.logMessage(
                    'Clipper process done check result file ' +
                    ouputclipfile_path)
                #Load result file into map environment
                rasterLayerClipped = QgsRasterLayer(
                    ouputclipfile_path, ouputFilenameRasterClip[:-4])

                pixelSizeXClip = rasterLayerClipped.rasterUnitsPerPixelX()
                pixelSizeYClip = rasterLayerClipped.rasterUnitsPerPixelY()

                imageWClip = rasterLayerClipped.width()
                imageHClip = rasterLayerClipped.height()

                providerRasterLayerClipped = rasterLayerClipped.dataProvider()
                extentRasterLayerClipped = rasterLayerClipped.extent()

                #print(providerRasterLayerClipped)
                #xmin,ymax,xmax,ymin
                imageXminClip = (extentRasterLayerClipped.xMinimum())
                imageYminClip = (extentRasterLayerClipped.yMinimum())
                imageXmaxClip = (extentRasterLayerClipped.xMaximum())
                imageYmaxClip = (extentRasterLayerClipped.yMaximum())
                #origin
                imageXOriginClip = int(
                    round(extentRasterLayerClipped.xMinimum()))
                imageYOriginClip = int(
                    round(extentRasterLayerClipped.yMinimum()))
                #epsg

                proj4crs = rasterLayerClipped.crs()

                QgsMessageLog.logMessage(str(proj4crs.srsid()))
                QgsMessageLog.logMessage(str(proj4crs.toProj4()))
                QgsMessageLog.logMessage(str(proj4crs.authid()))
                QgsMessageLog.logMessage(str(proj4crs.description()))
                QgsMessageLog.logMessage(str(proj4crs.ellipsoidAcronym()))
                QgsMessageLog.logMessage(str(proj4crs.findMatchingProj()))
                QgsMessageLog.logMessage(str(proj4crs.postgisSrid()))
                QgsMessageLog.logMessage(str(proj4crs.toWkt()))

                epsgClip = proj4crs.postgisSrid()
                epsgWKTClip = proj4crs.toWkt()

                #QgsMapLayerRegistry.instance().addMapLayer(rasterLayerClipped)
                QgsProject.instance().addMapLayer(rasterLayerClipped)
                #pass

                self.dlg.statusBarProcessing.setValue(75)
                #copy vector mask
                outputFileMaskPath = os.path.join(temporalPath,
                                                  ouputFilenameVectorMask)
                #temporalPath.replace("/", "\\") + ouputFilenameVectorMask
                temporalVectorLayer = QgsVectorLayer(urlSourceVectorMaskSplit,
                                                     "tmp_polygon", "ogr")
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shp',
                                os.path.join(outputFileMaskPath[:-4] + '.shp'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.dbf',
                                os.path.join(outputFileMaskPath[:-4] + '.dbf'))
                shutil.copyfile(urlSourceVectorMaskSplit[:-4] + '.shx',
                                os.path.join(outputFileMaskPath[:-4] + '.shx'))
                temporalVectorLayerDataProvider = temporalVectorLayer.dataProvider(
                )
                temporalVectorLayerCrs = temporalVectorLayerDataProvider.crs()
                temporalVectorLayerCrsString = temporalVectorLayerCrs.authid()
                temporalVectorLayerEPSGInt = int(
                    temporalVectorLayerCrsString[5:])

                QgsMessageLog.logMessage(str(temporalVectorLayerEPSGInt))
                maskVectorLayerExported = QgsVectorLayer(
                    outputFileMaskPath, ouputFilenameVectorMask[:-4], "ogr")
                crs = maskVectorLayerExported.crs()
                crs.createFromId(temporalVectorLayerEPSGInt)
                maskVectorLayerExported.setCrs(crs)
                maskVectorLayerExported.setCrs(
                    QgsCoordinateReferenceSystem(
                        temporalVectorLayerEPSGInt,
                        QgsCoordinateReferenceSystem.EpsgCrsId))

                styleBoundary = os.path.join(
                    (os.path.dirname(os.path.abspath(__file__))), 'styles',
                    'croprows_style_boundary.qml')
                maskVectorLayerExported.loadNamedStyle(styleBoundary)
                #QgsMapLayerRegistry.instance().addMapLayer(maskVectorLayerExported)
                QgsProject.instance().addMapLayer(maskVectorLayerExported)

                #end copy vector mask

                #TODO: try not to simulate process status, make it real
                for i in range(76, 90):
                    self.dlg.statusBarProcessing.setValue(i)

                #show step2 button
                self.dlg.btnExecuteProcessingFromApi.setVisible(True)

                self.dlg.statusBarProcessing.setValue(95)

                arrXMLOptions = [
                    str(seedValue),
                    str(ouputFilenameRasterClip),
                    str(ouputFilenameVectorMask),
                    str(pixelSizeXClip) + ',-' + str(pixelSizeYClip),
                    str(imageWClip) + ',' + str(imageHClip),
                    str(imageXminClip) + ',' + str(imageYminClip) + ',' +
                    str(imageXmaxClip) + ',' + str(imageYmaxClip),
                    str(imageXOriginClip) + ',' + str(imageYOriginClip),
                    str(epsgClip),
                    str(epsgWKTClip),
                    str(ouputFilenamePrj)
                ]

                #Write XML file
                self.writeXMLFile(ouputFilenameCropRowsProjectXML,
                                  arrXMLOptions)

                self.dlg.xmlCoreFile.setText(
                    str(ouputFilenameCropRowsProjectXML))

                self.dlg.statusBarProcessing.setValue(100)

                QApplication.setOverrideCursor(QtCore.Qt.ArrowCursor)

                self.flagClipTaskDone = 1

                toStep2Msg = QMessageBox.question(
                    None, "Crop Rows processing task start",
                    ("Are you sure that you want to start a <b>Crop Rows</b> processing task ?<br>Keep in mind this process can take a few minutes, even several hours.<br><br>Make sure that <b>Crop Rows - API Server is Running before continue.</b>"
                     ), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if toStep2Msg == QMessageBox.Yes:
                    QgsMessageLog.logMessage('Run Step 2')
                    self.executeCropRowsProcessingFromAPI()
                    pass
                else:
                    QMessageBox.information(
                        None, 'Message !',
                        "You must be run the processing task by manually way !<br>Just click on the button <b>Processing Task (manual)</b>",
                        QMessageBox.Ok)
                    pass
            else:
                QgsMessageLog.logMessage('No Mosaic Clip Process Selected')
                pass
        else:
            QgsMessageLog.logMessage('Missing Required Parameters')
            QgsMessageLog.logMessage('strMosaicRasterFileSelected: ' +
                                     strMosaicRasterFileSelected)
            QgsMessageLog.logMessage('strMaskVectorFileSelected: ' +
                                     strMaskVectorFileSelected)
            QgsMessageLog.logMessage('seedValue: ' + str(seedValue))
            QgsMessageLog.logMessage('flagClipTaskDone: ' +
                                     str(self.flagClipTaskDone))
            QMessageBox.critical(None, 'Error!',
                                 "Missing Required Parameter !",
                                 QMessageBox.Ok)