コード例 #1
0
    def contourWithFaults(self, rasterLayer, faultLayer, output, progress):
        # bufferLayerName = os.tempnam()+'_buf_layer.shp'
        bufferLayerName = getTempFilename('shp')
        cellSize = min(self.extent.width() / rasterLayer.width(), self.extent.height() / rasterLayer.height())
        provider = rasterLayer.dataProvider()
        rows = rasterLayer.rasterUnitsPerPixelY()
        cols = rasterLayer.rasterUnitsPerPixelX()
        block = provider.block(1, self.extent, rows, cols)
        noDataValue = block.noDataValue()

        if faultLayer is None:
            return

        #Create lines buffer
        QgsGeometryAnalyzer().buffer(faultLayer, bufferLayerName, cellSize, False, False, -1, None)

        bufferLayer = processing.getObject(bufferLayerName)
        provider = bufferLayer.dataProvider()
        provider.addAttributes([QgsField('faultParam', QVariant.Double)])
        bufferLayer.updateFields()

        with edit(bufferLayer):
            new_field_index = bufferLayer.fieldNameIndex('faultParam')
            for f in processing.features(bufferLayer):
                bufferLayer.changeAttributeValue(f.id(), new_field_index, noDataValue)

        fn,ext = os.path.splitext(rasterLayer.source())
        ext = ext.replace('.', '')
        tempRasterName = getTempFilename(ext) #os.tempnam() + '_temp_raster_' + ext
        shutil.copyfile(rasterLayer.source(), tempRasterName)
        processing.runalg('gdalogr:rasterize_over', bufferLayerName, 'faultParam', tempRasterName)
        processing.runalg('gdalogr:contour', tempRasterName, self.Inter, 'ELEV', None, output)
コード例 #2
0
def selectData(sourcenode_single, impedance):
    global streetnet_clip, firestation_point

    pa_name = NameList[sourcenode_single]
    firestation = QgsVectorLayer('Point?crs=epsg:32633', pa_name, 'memory')
    prov = firestation.dataProvider()
    feat = QgsFeature()
    feat.setGeometry(QgsGeometry.fromPoint(PointList[sourcenode_single]))
    prov.addFeatures([feat])

    path_Buffer = path_root + '//Buffer_.shp'
    QgsGeometryAnalyzer().buffer(firestation, path_Buffer, impedance, False,
                                 False, -1)
    Buffer = iface.addVectorLayer(path_Buffer, 'Buffer', 'ogr')

    renderer = Buffer.rendererV2()
    symbol = renderer.symbol()
    symbol.setColor(QColor(0, 0, 200, 20))
    iface.legendInterface().refreshLayerSymbology(Buffer)

    path_Streetnetclip = path_root + '//streetnet_clip.shp'
    processing.runalg("qgis:clip", streetnetwork, path_Buffer,
                      path_Streetnetclip)
    streetnet_clip = iface.addVectorLayer(path_Streetnetclip, 'Streetnetclip',
                                          'ogr')

    renderer = streetnet_clip.rendererV2()
    symbol = renderer.symbol()
    symbol.setColor(QColor(200, 200, 200, 0))
    iface.legendInterface().refreshLayerSymbology(streetnet_clip)

    QgsMapLayerRegistry.instance().addMapLayers([firestation])

    firestation_point = [PointList[sourcenode_single]]
コード例 #3
0
def create_study_area_shapefile(plot_list, buffer_size, output_path):
    uri = "file:///" + plot_list + "?crs=epsg:32737&delimiter=%s&xField=%s&yField=%s" % (
        ";", "Long_X", "Lat_y")
    vlayer = QgsVectorLayer(uri, "VectorLayer", "delimitedtext")

    QgsGeometryAnalyzer().buffer(vlayer, output_path, buffer_size, False,
                                 False, -1)

    filename = os.path.basename(output_path)
    splitted_filename = filename.split(".")
    shape = QgsVectorLayer(output_path, splitted_filename[0], "ogr")
    QgsMapLayerRegistry.instance().addMapLayer(shape)
    return shape
コード例 #4
0
    def get_mask(self):
        openFile = QFileDialog()
        shp_file = QFileDialog.getOpenFileName(self.dlg, ("Select shape file"),
                                               '')

        if shp_file:
            layer = QgsVectorLayer(shp_file, "sub", "ogr")
            features = layer.getFeatures()

            idx = layer.fieldNameIndex('location')
            temp_path = join(self.rasters_path, "temp")
            if not os.path.exists(temp_path):
                mkdir(temp_path)

            for feat in features:
                location = feat.attributes()[idx]
                shapeLocation = os.path.join(temp_path, location + ".shp")
                shapeBuffer = os.path.join(temp_path, location + "_b.shp")
                print shapeBuffer

                general.runalg('qgis:extractbyattribute', shp_file, "location",
                               0, location, shapeLocation)
                self.dlg.textBrowser.append(location)
                feature_path = join(self.rasters_path, location)
                if not os.path.exists(feature_path):
                    mkdir(feature_path)
                location_layer = QgsVectorLayer(shapeLocation, "location",
                                                "ogr")
                QgsGeometryAnalyzer().buffer(location_layer, shapeBuffer, 3000,
                                             False, False,
                                             -1)  #el buffer debe ser parametro
                for raster in self.rasters:
                    gif_name = raster.replace("General.",
                                              location + ".")[:-3] + 'gif'
                    print gif_name
                    clip(shape=shapeBuffer,
                         tiff=join(self.rasters_path, raster),
                         location=location,
                         gif_output=join(feature_path, gif_name))

            time.sleep(2)
            for f in os.listdir(temp_path):
                os.remove(join(temp_path, f))
            try:
                os.rmdir(temp_path)
            except:
                pass
コード例 #5
0
ファイル: Buffer.py プロジェクト: ict4eo/eo4vistrails
    def compute(self):
        layer = self.getInputFromPort('layer')
        dissolve = self.forceGetInputFromPort('dissolve', False)
        distance = self.forceGetInputFromPort('distance', 0.0)
        output_file = self.interpreter.filePool.create_file(suffix='.shp')

        try:
            if 'shapefile' in self.outputPorts:
                #layer, shapefileName, bufferDistance, onlySelectedFeatures,
                # dissolve, bufferDistanceField = -1, p = 0)
                myshape = QgsGeometryAnalyzer.buffer(layer, output_file,
                                                    distance, False,
                                                    dissolve, -1, 0)
            else:
                myshape = None
            self.setResult('shapefile', myshape)

        except Exception, ex:
            self.raiseError(ex)
コード例 #6
0
    def gen_muestreo(self):

		#Se leen los vectores que esten el la lista de capas cargada en QGis
        layers = self.iface.legendInterface().layers()

		#Selecciona la capa de universo muestreal (área de estudio)
        selectedLayerIndex = self.dlg.capaarea.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        area_est = selectedLayer

        #inicio de la edición
        selectedLayer.startEditing()

        #agregar nuevo campo
        selectedLayer.dataProvider().addAttributes([QgsField("Area_Ha", QVariant.Int)])

        #Cierra edicion
        selectedLayer.commitChanges()

        #Activa edicion
        selectedLayer.startEditing()
        idx = selectedLayer.fieldNameIndex( "Area_Ha" )

        #Calculo de área en Ha mediante expresion
        e = QgsExpression( "$area/10000" )
        e.prepare(selectedLayer.pendingFields())
        for f in selectedLayer.getFeatures():
                value = e.evaluate (f)
                selectedLayer.changeAttributeValue (f.id(), idx, value)
        area_est.deselect(0)
        #atualizción de columna
        #cierre de edición
        selectedLayer.updateFields()
        selectedLayer.commitChanges()


        # definición de variables para estimar tamaño de muestra
        marg_error = self.dlg.marg_error.value()
        nivel_conf = self.dlg.nivel_conf.value()
        universo = int(value)

        #selección del tamaño de muestra
        if universo < 100000:
            muestra = (universo * (nivel_conf*nivel_conf * 0.5 * 0.5)) / ((universo - 1) * (marg_error*marg_error) + (nivel_conf * 0.5* 0.5))
            QMessageBox.information(self.dlg,"POBLACION FINITA", "Tamano de muestra: " + str(int(muestra)))

        else:
            muestra = ((nivel_conf**2) * 0.5 * 0.5) / (marg_error**2)
            QMessageBox.information(self.dlg,"POBLACION INFINITA", "Tamano de muestra: " + str(int(muestra)))

        #Se parsea a entero el tamaño de muestra
        muestra_int = int(muestra)

        #Generación de los buffer sobre la capa vías
        # Se leen los vectores que esten el la lista de capas cargada en QGis
        layers = self.iface.legendInterface().layers()

        # Selecciona la capa vial para hacer multibuffer (capa de vías)
        selectedLayerIndex = self.dlg.capavias.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        vias = selectedLayer

        #extracción de vías tipo 1, 2, 3, 4 (aptas para trasporte en automovil)
        processing.runalg('qgis:extractbyattribute', vias, "TIPO_VIA", 5, "4" , "C:/Users/toshiba/Downloads/vias_aptas.shp")
        vias_aptas = iface.addVectorLayer("C:/Users/toshiba/Downloads/vias_aptas.shp", "", "ogr")

        # Generar el buffer de la capa vias aptas
        #processing.runalg('qgis:fixeddistancebuffer', vias_aptas, 500, 5, True, "C:/Users/toshiba/Downloads/buffer_vias500.shp")
        #buffer_vias500 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias500.shp", "", "ogr")

        #processing.runalg('qgis:fixeddistancebuffer', vias_aptas, 1000, 5, True, "C:/Users/toshiba/Downloads/buffer_vias1000.shp")
        #buffer_vias1000 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias1000.shp", "", "ogr")

        #processing.runalg('qgis:fixeddistancebuffer', vias_aptas, 1500, 5, True, "C:/Users/toshiba/Downloads/buffer_vias1500.shp")
        #buffer_vias1500 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias1500.shp", "", "ogr")

        processing.runalg('qgis:fixeddistancebuffer', vias_aptas, 2000, 5, True, "C:/Users/toshiba/Downloads/buffer_vias2000.shp")
        buffer_vias2000 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias2000.shp", "", "ogr")


        #extracción por atributos de suelos con media, alta y muy alta suceptibilidad
  		#Selecciona la capa suelos (capa de suceptibilidad)
        selectedLayerIndex = self.dlg.capasuelos.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        suelos = selectedLayer
        processing.runalg('qgis:extractbyattribute', suelos, "Codigo_Cla", 3, "2" , "C:/Users/toshiba/Downloads/suelos_sal.shp")
        suelos_sal = iface.addVectorLayer("C:/Users/toshiba/Downloads/suelos_sal.shp", "", "ogr")


        #Selección de zonas donde se tomarán las muestras
        #Intersección entre buffer 1km y suelos salinos
        overlayAnalyzer = QgsOverlayAnalyzer()
        overlayAnalyzer.intersection(buffer_vias2000, suelos_sal, "C:/Users/toshiba/Downloads/area_muestreo.shp")
        area_muestreo = iface.addVectorLayer("C:/Users/toshiba/Downloads/area_muestreo.shp", "", "ogr")

        #Unir polígonos del área de muestreo (dissolve)
        from qgis.analysis import QgsGeometryAnalyzer
        lyr =iface.mapCanvas()
        layer = lyr.currentLayer()
        QgsGeometryAnalyzer().dissolve(area_muestreo,"C:/Users/toshiba/Downloads/diss.shp", False, -1 )
        True
        diss = iface.addVectorLayer("C:/Users/toshiba/Downloads/diss.shp", "", "ogr")

        #Generación de sitios de muestreo
        processing.runalg('qgis:randompointsinsidepolygonsfixed', buffer_vias2000, 0, muestra_int, 0, "C:/Users/toshiba/Downloads/sitios_muestreo.shp")
        sitios_muestreo = iface.addVectorLayer("C:/Users/toshiba/Downloads/sitios_muestreo.shp", "", "ogr")


        #agrerar campo "tiempo" a la tabla de atributos de la capa sitios de muestreo
        layer = iface.activeLayer()
        provider = layer.dataProvider()
        field = QgsField("tiempo", QVariant.Double)
        provider.addAttributes([field])
        layer.updateFields()



        #Generar mapa pendiente a partir del DEM
  		#Selecciona el DEM
        selectedLayerIndex = self.dlg.capacurvas.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        dem = selectedLayer

        processing.runalg('gdalogr:slope', dem, 1, True, False,True, 1, "C:/Users/toshiba/Downloads/slope.tif")
        slope = iface.addRasterLayer("C:/Users/toshiba/Downloads/slope.tif", "SLOPE")
        QMessageBox.information(self.dlg, "MENSAJE", "todo corre bien hasta aqui" )
コード例 #7
0
    def runExtract(self):
        '''Process extract
        '''
        # Create or clear log file
        open(getPath(LOG_FILE), 'w').close()

        indexLayerColumn = False

        # Initiate generic error message
        msg_error = u"Erreur lors de l'extraction: merci de vérifier les paramètres saisis."

        # Get directories path
        dstDirectory = self.dlg.leDstPath.text()
        # Empty tmp directory = remove and recreate it
        tmp_dir = os.path.join(self.plugin_directory, 'tmp')

        try:
            if os.path.exists(tmp_dir):
                shutil.rmtree(tmp_dir)
            os.makedirs(tmp_dir)
        except:
            message = 'Unable to remove temporal layer.'
            log()
            log(message, 'ERROR')
            QgsMessageLog.logMessage(unicode(message))

        checked = False
        # If local radio button is activated
        if self.dlg.rb_locale.isChecked():
            checked = 'local'
            # Define source directory
            srcDirectory = self.dlg.leSrcPath.text()
            if not os.path.isdir(srcDirectory):
                srcDirectory = False
            # Get index layer
            indexLayerId = self.dlg.cbIndexLayers.currentIndex()
            if len(self.layers):
                indexLayer = self.layers[indexLayerId]
                # Get colum name of list for index layer
                indexLayerColumnName = self.dlg.cbIndexColumnsName.currentText(
                )
                indexLayerColumn = indexLayer.fieldNameIndex(
                    indexLayerColumnName)

        # If remote radio button is activated
        elif self.dlg.rb_remote.isChecked():
            checked = 'remote'
            # Define source directory
            srcDirectory = self.remote_src['src_directory']
            # Get index layer
            try:
                # Load file from FTP in tmp_dir
                for ext in [
                        '.shp', '.dat', '.dbf', '.shx', '.prj', '.id', '.tab',
                        '.map'
                ]:
                    filename = self.remote_src['index_file'] + ext
                    downloadFileFromFtp(self.local_config, filename,
                                        self.remote_src['index_path'], tmp_dir)
                # Load index file in QGIS
                indexLayerPath = os.path.join(
                    tmp_dir, self.remote_src['index_file'] + '.shp')
                indexLayer = self.iface.addVectorLayer(
                    indexLayerPath, self.remote_src['index_file'] + '.shp',
                    'ogr')
                # Get colum name of list for index layer
                indexLayerColumnName = self.remote_src['index_col_name']
            except Exception as e:
                QgsMessageLog.logMessage(
                    unicode("Can't get index file from FTP or load in QGIS: " +
                            str(e)))

        # Get extent layer
        if len(self.layers):
            extentLayerId = self.dlg.cbExtentLayers.currentIndex()
            extentLayer = self.layers[extentLayerId]
            # Get buffer
            buffer = self.dlg.leBuffer.text()
            # Calculate buffer and create temporal shp layer
            extent_buffer_shp = 'extent_buffer.shp'
            extentLayerBufferPath = os.path.join(tmp_dir, extent_buffer_shp)
            QgsGeometryAnalyzer().buffer(extentLayer, extentLayerBufferPath,
                                         int(buffer), False, False, -1)

            extentLayerBuffer = QgsVectorLayer(extentLayerBufferPath,
                                               'extent_buffer_layer', 'ogr')
            extentLayerBuffer_isValid = True
            if not extentLayerBuffer.isValid():
                extentLayerBuffer_isValid = False
                msg_error = "Fichier d'emprise (buffer) non valide."
                log(msg_error, 'ERROR')

        log()
        log('indexLayer CRS: ' + str(indexLayer.crs().authid()))
        log('extentLayer CRS: ' + str(extentLayer.crs().authid()))
        is_crs_equal = True
        if indexLayer.crs().authid() != extentLayerBuffer.crs().authid():
            is_crs_equal = False
            msg_error = "Les systèmes de projection (CRS) des couches 'index' (" + str(
                indexLayer.crs().authid()) + ") et 'emprise/buffer' (" + str(
                    extentLayer.crs().authid()) + ") sont différents."
            log(msg_error, 'ERROR')

        if indexLayerColumn >= 0 and extentLayerBuffer_isValid and srcDirectory and os.path.isdir(
                dstDirectory) and is_crs_equal:
            # Get dalles from index
            dalles_id = []
            dalles_name = []

            for extent_feature in extentLayerBuffer.getFeatures():
                cands = indexLayer.getFeatures(
                    QgsFeatureRequest().setFilterRect(
                        extent_feature.geometry().boundingBox()))
                for index_feature in cands:
                    if extent_feature.geometry().intersects(
                            index_feature.geometry()):
                        attrs = index_feature.attributes()
                        dalles_id.append(index_feature.id())
                        dalle_name = os.path.splitext(
                            os.path.basename(attrs[indexLayerColumn]))[0]
                        dalles_name.append(dalle_name)

            indexLayer.select(dalles_id)

            # Use worker thread to get files list from srcDirectory, check files to copy and copy files
            self.start_worker_files(checked, srcDirectory, dstDirectory,
                                    dalles_name, self.local_config)

        else:
            QgsMessageLog.logMessage(msg_error.encode('utf8'))
            QMessageBox.warning(self.dlg, 'Extraction erreur!', msg_error,
                                QMessageBox.Ok)
コード例 #8
0
    def buffering(self):
        layer = self.road_layer()
        idx = self.buffer_size()
        outputfile = self.ui.linOutput.text()

        QgsGeometryAnalyzer().buffer(layer, outputfile, -1, False, False, idx)
コード例 #9
0
    def gen_muestreo(self):

		#Se leen los vectores que esten el la lista de capas cargada en QGis
        layers = self.iface.legendInterface().layers()

		#Selecciona la capa de universo muestreal (área de estudio)
        selectedLayerIndex = self.dlg.comboBox.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        area_est = selectedLayer

        #inicio de la edición
        selectedLayer.startEditing()

        #agregar nuevo campo
        selectedLayer.dataProvider().addAttributes([QgsField("Area_Ha", QVariant.Int)])

        #Cierra edicion
        selectedLayer.commitChanges()

        #Activa edicion
        selectedLayer.startEditing()
        idx = selectedLayer.fieldNameIndex( "Area_Ha" )

        #Calculo de área en Ha mediante expresion
        e = QgsExpression( "$area/10000" )
        e.prepare(selectedLayer.pendingFields())
        for f in selectedLayer.getFeatures():
                value = e.evaluate (f)
                selectedLayer.changeAttributeValue (f.id(), idx, value)

        area_est.deselect(0)
        #atualizción de columna
        #cierre de edición
        selectedLayer.updateFields()
        selectedLayer.commitChanges()


        # definición de variables para estimar tamaño de muestra
        marg_error = self.dlg.marg_error.value()
        nivel_conf = self.dlg.nivel_conf.value()
        universo = int(value)

        #selección del tamaño de muestra

        if universo < 100000:
            muestra = (universo * (nivel_conf*nivel_conf * 0.5 * 0.5)) / ((universo - 1) * (marg_error*marg_error) + (nivel_conf * 0.5* 0.5))
            QMessageBox.information(self.dlg,"POBLACION FINITA", "Tamano de muestra: " + str(int(muestra)))

        else:
            muestra = ((nivel_conf**2) * 0.5 * 0.5) / (marg_error**2)
            QMessageBox.information(self.dlg,"POBLACION INFINITA", "Tamano de muestra: " + str(int(muestra)))

        #Se parsea a entero el tamaño de muestra
        muestra_int = int(muestra)

        #Generación de los buffer sobre la capa vías
        # Se leen los vectores que esten el la lista de capas cargada en QGis
        layers = self.iface.legendInterface().layers()

        # Selecciona la capa vial para hacer multibuffer (capa de vías)
        selectedLayerIndex = self.dlg.capavias.currentIndex()
        selectedLayer = layers[selectedLayerIndex]

        # Generar el buffer de la capa vias
        vias = selectedLayer
        QgsGeometryAnalyzer().buffer(vias, "C:/Users/toshiba/Downloads/buffer_vias100.shp", 100, False, True, -1)
        QgsGeometryAnalyzer().buffer(vias, "C:/Users/toshiba/Downloads/buffer_vias200.shp", 200, False, True, -1)
        QgsGeometryAnalyzer().buffer(vias, "C:/Users/toshiba/Downloads/buffer_vias300.shp", 300, False, True, -1)
        QgsGeometryAnalyzer().buffer(vias, "C:/Users/toshiba/Downloads/buffer_vias400.shp", 400, False, True, -1)
        QgsGeometryAnalyzer().buffer(vias, "C:/Users/toshiba/Downloads/buffer_vias500.shp", 500, False, True, -1)
        buffer_vias500 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias500.shp", "", "ogr")
        buffer_vias400 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias400.shp", "", "ogr")
        buffer_vias300 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias300.shp", "", "ogr")
        buffer_vias200 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias200.shp", "", "ogr")
        buffer_vias100 = iface.addVectorLayer("C:/Users/toshiba/Downloads/buffer_vias100.shp", "", "ogr")


        #Generación de puntos de muestreo
        processing.runalg('qgis:randompointsinsidepolygonsfixed', vias, 0, muestra_int, 0, "C:/Users/toshiba/Downloads/sitios_muestreo.shp")
        sitios_muestreo = iface.addVectorLayer("C:/Users/toshiba/Downloads/sitios_muestreo.shp", "", "ogr")
        QMessageBox.information(self.dlg, "MENSAJE", "Typo de dato: " + str(type(sitios_muestreo)))


        """""
コード例 #10
0
def potentiel_commercial(Geographie_IRIS, Donnees_Communes, Revenus_IRIS, Population_IRIS, num_iris, friction_deplacement):
	sup_lignes(Donnees_Communes,5)
	sup_lignes(Population_IRIS,5)
	sup_lignes(Revenus_IRIS,5)
	keep_col( Population_IRIS,[1,13,30])
	keep_col(Revenus_IRIS,[1,7])
	keep_col(Donnees_Communes,[1,5,7])
	sup_lignes_null(Population_IRIS)
	sup_lignes_null(Donnees_Communes)
	sup_lignes_null(Revenus_IRIS)
	print("Fichiers prets pour le traitement du pouvoir d'achat")

	
	#Importation des couche et creation des appels
	iris = iface.addVectorLayer("Geographie_IRIS","IRIS","ogr")
	communes = iface.addVectorLayer("Donnees_Communes","COMMUNES","ogr")
	reviris = iface.addVectorLayer("Revenus_IRIS","REV_IRIS","ogr")
	popiris = iface.addVectorLayer("Population_IRIS","POP_IRIS","ogr")

	#Selection de l'IRIS a etudier
	num = num_iris
	it = iris.getFeatures(QgsFeatureRequest().setFilterExpression ( u'"DCOMIRIS" = ' + num) ))
	iris.setSelectedFeatures( [ f.id() for f in it ] )

	#Creation du perimètre de 10km
	QgsGeometryAnalyzer().buffer(iris, "Buffer.shp",10000, True, False, -1)
	buffer = iface.addVectorLayer("Buffer.shp","Buffer","ogr")

	#Creation d'une couche restreinte au perimètre de 10km
	iris.removeSelection()

	processing.runalg('qgis:extractbylocation', iris, buffer, u'within', 0, "Perim.shp")
	perim = iface.addVectorLayer("Perim.shp","Perim","ogr")

	#Jointures des differentes bases de donnees à la couche geographique
	perimField='depcom'
	communesField='field_1'
	joinObject = QgsVectorJoinInfo()
	joinObject.joinLayerId = communes.id()
	joinObject.joinFieldName = communesField
	joinObject.targetFieldName = perimField
	joinObject.memoryCache = True
	perim.addJoin(joinObject)

	perimField='dcomiris'
	popirisField='field_1'
	joinObject = QgsVectorJoinInfo()
	joinObject.joinLayerId = popiris.id()
	joinObject.joinFieldName = popirisField
	joinObject.targetFieldName = perimField
	joinObject.memoryCache = True
	perim.addJoin(joinObject)

	perimField='dcomiris'
	revirisField='field_1'
	joinObject = QgsVectorJoinInfo()
	joinObject.joinLayerId = reviris.id()
	joinObject.joinFieldName = revirisField
	joinObject.targetFieldName = perimField
	joinObject.memoryCache = True
	perim.addJoin(joinObject)

	#Creation de nouvelles colonnes (pouvoir d'achat, distance et potentiel de chaque IRIS)
	perim.dataProvider().addAttributes([QgsField("P_Achat", QVariant.Int), QgsField("Distance", QVariant.Int),QgsField("Potentiel", QVariant.Int)])
	perim.updateFields()

	#Remplissage des nouvelles colonnes
	#Creation d'un appel pour le centroïde de l'IRIS etudie
	it = iris.getFeatures(QgsFeatureRequest().setFilterExpression ( u'"DCOMIRIS" = {0}'.format(num) ))
	for feature in it:
		centro = feature.geometry().centroid()

	n=friction_deplacement

	#Remplissage des colonnes pouvoir d'achat (numero 8) et distance (numero 9)
	distance = QgsDistanceArea()

	features = perim.getFeatures()
	for feature in features:
		if not feature['COMMUNES_Field_2'] is None:
			if feature['REV_IRIS_Field_2'] is None:
				perim.dataProvider().changeAttributeValues({ feature.id() : { 8 : feature['COMMUNES_Field_3']*(feature['POP_IRIS_Field_2']-0.4*feature['POP_IRIS_Field_3']) } })
			else: 
				perim.dataProvider().changeAttributeValues({ feature.id() : { 8 : feature['REV_IRIS_Field_2']*(feature['POP_IRIS_Field_2']-0.4*feature['POP_IRIS_Field_3']) } })		

		centest = feature.geometry().centroid()
		perim.dataProvider().changeAttributeValues({ feature.id() : { 9 : distance.measureLine(centro.asPoint(), centest.asPoint()) } })

	#Remplissage de la colonne potentiel (numero 10)
	features = perim.getFeatures()
	for feature in features:
		if not feature['COMMUNES_Field_2'] is None:
			perim.dataProvider().changeAttributeValues({ feature.id() : { 10 : feature['P_Achat']/(feature['Distance']+200)^n } })

	#Exportation des donnees des IRIS du perimètre dans un CSV, calcule et renvoi du resultat final (somme de la colonne K)
	QgsVectorFileWriter.writeAsVectorFormat(perim, r'perim.csv', "utf-8", None, "CSV")
	pot_com = somme_col('perim.csv', 11)
	
	QgsMapLayerRegistry.instance().removeMapLayers( [iris.id()] )
	QgsMapLayerRegistry.instance().removeMapLayers( [communes.id()] )
	QgsMapLayerRegistry.instance().removeMapLayers( [reviris.id()] )
	QgsMapLayerRegistry.instance().removeMapLayers( [popiris.id()] )
	QgsMapLayerRegistry.instance().removeMapLayers( [buffer.id()] )
	QgsMapLayerRegistry.instance().removeMapLayers( [perim.id()] )
	
	return pot_com
コード例 #11
0
    ###have to be in a directure with only English in it.
    uri = "file:///" + OutputFile2 + file[
        -6:] + '_infra.csv' + "?encoding=GB2312&type=csv&delimiter=,%20%5Ct&xField=X&yField=Y&spatialIndex=no&subsetIndex=no&watchFile=no"
    layer_total_csv = QgsVectorLayer(uri, file[-6:] + '_infra.csv',
                                     'delimitedtext')
    layer_total_csv.setCrs(QgsCoordinateReferenceSystem(4030))
    QgsMapLayerRegistry.instance().addMapLayer(layer_total_csv)
    layer_total_csv = iface.activeLayer()
    layer_total_csv.setCrs(QgsCoordinateReferenceSystem(4030))

    if int(layer_total_csv.featureCount()) > 0:
        extent = layer_boundary_grid.extent()
        iface.mapCanvas().setExtent(extent)
        save_name = OutputFile + file[-6:] + '_buffer' + '.shp'
        layer_infra_buffer = QgsGeometryAnalyzer().buffer(
            layer_total_csv, save_name, 0.0135, False, False, -1)
        data_source = save_name
        layer_name = file[-6:] + '_buffer'
        provider_name = "ogr"
        layer_infra_buffer = iface.addVectorLayer(data_source, layer_name,
                                                  provider_name)

        filename = "infra_buffer_dsv"
        save_name = OutputFile + filename + ".shp"
        processing.runalg("qgis:dissolve", layer_infra_buffer, True, None,
                          save_name)
        data_source = save_name
        layer_name = filename
        provider_name = "ogr"
        layer_infra_dsv = iface.addVectorLayer(data_source, layer_name,
                                               provider_name)
コード例 #12
0
ファイル: qgis_console.py プロジェクト: canng/Qgis_scripts.py
# buffer (QgsVectorLayer *layer, const QString &shapefileName, double bufferDistance, bool onlySelectedFeatures=false, bool dissolve=false, int bufferDistanceField=-1, QProgressDialog *p=0)
# centroids (QgsVectorLayer *layer, const QString &shapefileName, bool onlySelectedFeatures=false, QProgressDialog *p=0)
# convexHull (QgsVectorLayer *layer, const QString &shapefileName, bool onlySelectedFeatures=false, int uniqueIdField=-1, QProgressDialog *p=0)
# dissolve (QgsVectorLayer *layer, const QString &shapefileName, bool onlySelectedFeatures=false, int uniqueIdField=-1, QProgressDialog *p=0)
# simplify (QgsVectorLayer *layer, const QString &shapefileName, double tolerance, bool onlySelectedFeatures=false, QProgressDialog *p=0)
#===================================
from qgis.analysis import QgsGeometryAnalyzer

layer = qgis.utils.iface.mapCanvas().currentLayer()

# or

layer = qgis.utils.iface.activeLayer()

QgsGeometryAnalyzer().buffer(layer,
                             "C:/OpenGeoSuite/data/seoul/buffer_500.shp", 500,
                             False, False, -1)


#===================================
# QgsSpatialIndex
#===================================
# Function to create a spatial index for input QgsVectorDataProvider
def createSpatialIndex(provider):
    spatialIndex = QgsSpatialIndex()

    features = provider.getFeatures()
    for feature in features:
        spatialIndex.insertFeature(feature)

    return spatialIndex
コード例 #13
0
if os.path.isfile(path + "przeciecie.qpj"): os.remove(path + "przeciecie.qpj")

#input - density layer and communication line
gestosc = QgsVectorLayer(density, "gestosc", "ogr")
linia = QgsVectorLayer(line, "linia", "ogr")
#QgsMapLayerRegistry.instance().addMapLayer(gestosc)

#defining area for GrassGIS
ext = gestosc.extent()
a = str(ext.xMinimum())
b = str(ext.xMaximum())
c = str(ext.yMinimum())
d = str(ext.yMaximum())

#makes buffer from points and intersect this buffer with density layer
QgsGeometryAnalyzer().buffer(linia, path + "bufor.shp", bufsize, False, False,
                             -1)
bufor = QgsVectorLayer(path + "bufor.shp", "bufor", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(bufor)
processing.runalg("qgis:intersection", bufor, gestosc, path + "przeciecie.shp")

#add przeciecie layer to registry
przeciecie = QgsVectorLayer(path + "przeciecie.shp", "przeciecie", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(przeciecie)

#calculating population ic each of buffers based on area procentage in each density map district
expression = QgsExpression("$area")
popu = []
for feature in przeciecie.getFeatures():
    value = expression.evaluate(feature)
    #diva = feature.attributes()[2]*value/1000000 #for 1km grid ;crucial point - needs to be determine
    diva = feature.attributes()[11] * value / feature.attributes()[
コード例 #14
0
expression = QgsExpression("$length")
totlen = 0
for feature in linia.getFeatures():
    value = expression.evaluate(feature)
    totlen = totlen + int(value)
pattern(totlen, step)
size = a + ',' + b + ',' + c + ',' + d
processing.runalg("grass:v.segment", linia, path + "rule.txt", size, -1, 0, 1,
                  path + "punkty.shp")

#add points layer to registry
punkty = QgsVectorLayer(path + "punkty.shp", "punkty", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(punkty)

#makes buffer from points and intersect this buffer with density layer
QgsGeometryAnalyzer().buffer(punkty, path + "bufor.shp", bufsize, False, False,
                             -1)
bufor = QgsVectorLayer(path + "bufor.shp", "bufor", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(bufor)
processing.runalg("qgis:intersection", bufor, gestosc, path + "przeciecie.shp")

#add przeciecie layer to registry
przeciecie = QgsVectorLayer(path + "przeciecie.shp", "przeciecie", "ogr")
QgsMapLayerRegistry.instance().addMapLayer(przeciecie)

#calculating population ic each of buffers based on area procentage in each density map district
expression = QgsExpression("$area")
n = int(totlen / step)
offset = n * [0]
for feature in przeciecie.getFeatures():
    value = expression.evaluate(feature)
    #diva = feature.attributes()[2]*value/1000000 #for 1km grid ;crucial point - needs to be determine
コード例 #15
0
#Open qgis
#Open farmers_markets and routes
#make sure farmers_markets is selected
#open this script in qgis and run
import os
from qgis.utils import iface
from qgis.analysis import QgsGeometryAnalyzer
mc = iface.mapCanvas()
layer = mc.currentLayer()

myfilepath = os.path.dirname(
    unicode(qgis.utils.iface.activeLayer().dataProvider().dataSourceUri()))
QgsGeometryAnalyzer().buffer(layer, myfilepath + '/Output/output.shp', 500,
                             False, False, -1)

layer = iface.addVectorLayer(myfilepath + '/Output/output.shp', "buffer",
                             "ogr")
if not layer:
    print "Layer failed to load!"