Exemplo n.º 1
0
def to_shp(path, any_features_list, layer_fields, crs, name, encoding, geom_type):
    if path is None:
        if geom_type == 0:
            network = QgsVectorLayer('Point?crs=' + crs.toWkt(), name, "memory")
        else:
            network = QgsVectorLayer('LineString?crs=' + crs.toWkt(), name, "memory")
    else:
        fields = QgsFields()
        for field in layer_fields:
            fields.append(field)
        file_writer = QgsVectorFileWriter(path, encoding, fields, geom_type, crs, "ESRI Shapefile")
        if file_writer.hasError() != QgsVectorFileWriter.NoError:
            print "Error when creating shapefile: ", file_writer.errorMessage()
        del file_writer
        network = QgsVectorLayer(path, name, "ogr")
    pr = network.dataProvider()
    if path is None:
        pr.addAttributes(layer_fields)
    new_features = []
    for i in any_features_list:
        new_feat = QgsFeature()
        new_feat.setFeatureId(i[0])
        new_feat.setAttributes([attr[0] for attr in i[1]])
        new_feat.setGeometry(QgsGeometry(QgsGeometry.fromWkt(str(i[2]))))
        #QgsGeometry()
        new_features.append(new_feat)
    network.startEditing()
    pr.addFeatures(new_features)
    network.commitChanges()
    return network
Exemplo n.º 2
0
    def createGeopkgLayer(self, filepath, featureIterator):
        fields, geomAtt = self._fields()
        qgsfields = QgsFields()
        for f in fields:
            qgsfields.append(f)
        writer = QgsVectorFileWriter(
            filepath,
            "UTF-8",
            qgsfields,
            FeatureTypeHelper.typeNameConverter[geomAtt.type.lower()],
            QgsCoordinateReferenceSystem(geomAtt.SRS),
            driverName="GPKG")

        BATCHSIZE = 500

        def _batch(iterable, size):
            sourceiter = iter(iterable)
            while True:
                batchiter = islice(sourceiter, size)
                try:
                    yield chain([next(batchiter)], batchiter)
                except StopIteration:
                    return

        for batch in _batch(featureIterator, BATCHSIZE):
            success = writer.addFeatures(batch)
            if not success:
                error = writer.errorMessage()
                del writer
                raise Exception("geopkg save: " + error)
        writer.flushBuffer()
        # the only way to close the writer is to call the C++ destructor -- we use sip to do this
        sip.delete(writer)
        del writer  # remove from python
        addAuditTables(filepath)
Exemplo n.º 3
0
def to_shp(path, any_features_list, layer_fields, crs, name, encoding,
           geom_type):
    if path is None:
        if geom_type == 0:
            network = QgsVectorLayer('Point?crs=' + crs.toWkt(), name,
                                     "memory")
        else:
            network = QgsVectorLayer('LineString?crs=' + crs.toWkt(), name,
                                     "memory")
    else:
        fields = QgsFields()
        for field in layer_fields:
            fields.append(field)
        file_writer = QgsVectorFileWriter(path, encoding, fields, geom_type,
                                          crs, "ESRI Shapefile")
        if file_writer.hasError() != QgsVectorFileWriter.NoError:
            print "Error when creating shapefile: ", file_writer.errorMessage()
        del file_writer
        network = QgsVectorLayer(path, name, "ogr")
    pr = network.dataProvider()
    if path is None:
        pr.addAttributes(layer_fields)
    new_features = []
    for i in any_features_list:
        new_feat = QgsFeature()
        new_feat.setFeatureId(i[0])
        new_feat.setAttributes([attr[0] for attr in i[1]])
        new_feat.setGeometry(QgsGeometry(QgsGeometry.fromWkt(str(i[2]))))
        #QgsGeometry()
        new_features.append(new_feat)
    network.startEditing()
    pr.addFeatures(new_features)
    network.commitChanges()
    return network
Exemplo n.º 4
0
 def to_shp(self,
            path,
            name,
            crs,
            encoding,
            geom_type,
            features,
            graph='primal'):
     if graph == 'primal':
         flds = self.edge_qflds
     elif graph == 'dual':
         flds = [
             QgsField('source', QVariant.String),
             QgsField('target', QVariant.String),
             QgsField('cost', QVariant.Int)
         ]
     if path is None:
         network = QgsVectorLayer('MultiLineString?crs=' + crs.toWkt(),
                                  name, "memory")
     else:
         file_writer = QgsVectorFileWriter(path, encoding, flds, geom_type,
                                           crs, "ESRI Shapefile")
         if file_writer.hasError() != QgsVectorFileWriter.NoError:
             print "Error when creating shapefile: ", file_writer.errorMessage(
             )
         del file_writer
         network = QgsVectorLayer(path, name, "ogr")
     # QgsMapLayerRegistry.instance().addMapLayer(network)
     pr = network.dataProvider()
     network.startEditing()
     if path is None:
         pr.addAttributes(flds)
     pr.addFeatures(features)
     network.commitChanges()
     return network
Exemplo n.º 5
0
	def fileHanddler(self, alayer, alist, filedirectory, name):
		crsSrc = alayer.crs()
		crsDes = QgsCoordinateReferenceSystem(crsSrc.authid())
		fieldz = QgsFields()
		fieldz.append(QgsField("Id", QVariant.Int))
		fieldz.append(QgsField("Ré", QVariant.String))
		fieldz.append(QgsField("Norte", QVariant.Double, "double", 23, 2))
		fieldz.append(QgsField("Este", QVariant.Double, "double", 23, 2))
		fieldz.append(QgsField("Longitude", QVariant.String))
		fieldz.append(QgsField("Latitude", QVariant.String))
		fieldz.append(QgsField("Vante", QVariant.String))
		fieldz.append(QgsField("Azimute", QVariant.String))
		fieldz.append(QgsField("Distancia", QVariant.Double, "double", 23, 2))

		writer = QgsVectorFileWriter(filedirectory+'/'+name, "UTF-8", fieldz, QgsWkbTypes.Point, crsDes,
			driverName="ESRI Shapefile")

		if writer.hasError() != QgsVectorFileWriter.NoError:
			print("Error when creating shapefile:", writer.errorMessage())

		writer.addFeatures(alist)
		del writer
		nwLayer = self.iface.addVectorLayer(filedirectory+'/'+name, "", "ogr")
		if not nwLayer:
			print("Layer failed to load!")
		return
Exemplo n.º 6
0
 def create_datasource_from_template(self, datasource):
     fieldSet = QgsFields()
     for fieldDef in FIELDS_TEMPLATE:
         fieldSet.append(self.getFieldFromDefinition(fieldDef))
     writer = QgsVectorFileWriter(datasource, 'UTF-8', fieldSet, QgsWkbTypes.Point, QgsCoordinateReferenceSystem(4326),"ESRI Shapefile")
     if writer.hasError():
         print ("error",writer.errorMessage())
     del writer
Exemplo n.º 7
0
def createShapefile(filePath, name, wkbType, crs, fields, styleURI=None, symbology=None):
    # WARNING This will overwrite existing files
    writer = QgsVectorFileWriter(filePath, 'System', fields, wkbType, crs)
    if writer.hasError():
        utils.debug(writer.errorMessage())
    del writer
    layer = QgsVectorLayer(filePath, name, 'ogr')
    loadStyle(layer, styleURI, symbology)
    return layer
Exemplo n.º 8
0
def create_shplayer_from_template(template, legend=True):
    #print "creating",template['datasource']
    fieldSet = QgsFields()
    for fieldDef in template['fields']:
        fieldSet.append(getFieldFromDefinition(fieldDef))

    writer = QgsVectorFileWriter(template['datasource'], 'UTF-8', fieldSet,
                                 template['geomtype'],
                                 QgsCoordinateReferenceSystem(template['srs']))
    if writer.hasError():
        print writer.errorMessage()
    del writer
    lyr = QgsVectorLayer(template['datasource'], template['name'], 'ogr')
    if template['style']:
        lyr.loadNamedStyle(template['style'])
    if legend:
        QgsMapLayerRegistry.instance().addMapLayer(lyr)
    return lyr
Exemplo n.º 9
0
    def create_reservoirs_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(QgsField(Reservoir.field_name_eid, QVariant.String))
        fields.append(QgsField(Reservoir.field_name_elev, QVariant.Double))
        fields.append(QgsField(Reservoir.field_name_delta_z, QVariant.Double))
        # fields.append(QgsField(Reservoir.field_name_head, QVariant.Double))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QgsWkbTypes.Point, crs, "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 10
0
    def create_pumps_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(QgsField(QgsField(Pump.field_name_eid, QVariant.String)))
        # fields.append(QgsField(QgsField(Pump.field_name_from_node, QVariant.String)))
        # fields.append(QgsField(QgsField(Pump.field_name_to_node, QVariant.String)))
        fields.append(
            QgsField(QgsField(Pump.field_name_param, QVariant.String)))
        fields.append(
            QgsField(QgsField(Pump.field_name_value, QVariant.String)))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QGis.WKBLineString, crs, "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 11
0
def createShapefile(filePath,
                    name,
                    wkbType,
                    crs,
                    fields,
                    styleURI=None,
                    symbology=None):
    # WARNING This will overwrite existing files
    writer = QgsVectorFileWriter(filePath, 'System', fields, wkbType, crs)
    if writer.hasError():
        utils.debug(writer.errorMessage())
    del writer
    layer = QgsVectorLayer(filePath, name, 'ogr')
    loadStyle(layer, styleURI, symbology)
    return layer
Exemplo n.º 12
0
def open_shapefile_writer(vlayer, shapefile_path):
    # Prepare inputs
    fields = vlayer.fields()

    # Create writer
    writer = QgsVectorFileWriter(
        shapefile_path, "utf-8", fields, QGis.WKBMultiPolygon,
        QgsCoordinateReferenceSystem(27700,
                                     QgsCoordinateReferenceSystem.EpsgCrsId),
        'ESRI Shapefile')

    if writer.hasError() != QgsVectorFileWriter.NoError:
        msg = "Error when creating shapefile: {}".format(writer.errorMessage())
        raise rn_except.CannotOpenShapefilePopupError(msg)

    return writer
Exemplo n.º 13
0
    def create_junctions_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(
            QgsField(QgsField(Junction.field_name_eid, QVariant.String)))
        fields.append(
            QgsField(QgsField(Junction.field_name_demand, QVariant.Double)))
        fields.append(QgsField(Junction.field_name_elev, QVariant.Double))
        fields.append(QgsField(Junction.field_name_delta_z, QVariant.Double))
        fields.append(QgsField(Junction.field_name_pattern, QVariant.String))
        fields.append(
            QgsField(Junction.field_name_emitter_coeff, QVariant.Double))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QgsWkbTypes.Point, crs, "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 14
0
    def _createLayer(self, filename, crs, geometries):
        if len(geometries) < 1:
            raise AerogenError(self.tr("No features to write"))
        geom_type = geometries[0].wkbType()

        writer = QgsVectorFileWriter(filename, "UTF-8", QgsFields(),
                                     geom_type, crs, "ESRI Shapefile")

        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise AerogenError(
                'Failed creating Shapefile: {}'.format(writer.errorMessage())
            )

        for geom in geometries:
            fet = QgsFeature()
            fet.setGeometry(geom)
            writer.addFeature(fet)
Exemplo n.º 15
0
    def create_tanks_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(QgsField(Tank.field_name_eid, QVariant.String))
        fields.append(QgsField(Tank.field_name_curve, QVariant.Int))
        fields.append(QgsField(Tank.field_name_diameter, QVariant.Double))
        fields.append(QgsField(Tank.field_name_elev, QVariant.Double))
        fields.append(QgsField(Tank.field_name_delta_z, QVariant.Double))
        fields.append(QgsField(Tank.field_name_level_init, QVariant.Double))
        fields.append(QgsField(Tank.field_name_level_max, QVariant.Double))
        fields.append(QgsField(Tank.field_name_level_min, QVariant.Double))
        fields.append(QgsField(Tank.field_name_vol_min, QVariant.Double))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QgsWkbTypes.Point, crs, "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 16
0
    def create_valves_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(QgsField(QgsField(Valve.field_name_eid,
                                        QVariant.String)))
        fields.append(
            QgsField(QgsField(Valve.field_name_diameter, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Valve.field_name_minor_loss, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Valve.field_name_setting, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Valve.field_name_type, QVariant.String)))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QGis.WKBLineString, crs, "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 17
0
    def _toVectorLayer_geojson (self):        
        crs = QgsCoordinateReferenceSystem()
        crs.createFromUserInput(self.provider.srsName)
        
        fileName = self.xmlFile.replace(".xml", ".geojson")
        fields = QgsFields ()
        map (fields.append, self.provider.fields)
        writer = QgsVectorFileWriter (fileName, "utf-8", fields, QGis.WKBPoint, crs, "GeoJSON")

        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception (writer.errorMessage())
        
        for feature in self.provider.getFeatures():
            self.features.append(feature)
            writer.addFeature(feature)
        
        del writer #Forzar escritura a disco
        
        return QgsVectorLayer( fileName, self.name, "ogr")
Exemplo n.º 18
0
    def create_shp(self):
        fields = QgsFields()
        fields.append(QgsField("setting_id", QVariant.String))
        fields.append(QgsField("raster", QVariant.String))
        fields.append(QgsField("x centre", QVariant.String))
        fields.append(QgsField("y centre", QVariant.String))

        self.shape_path = self.results.log_path.split(".log")[0] + ".shp"
        writer = QgsVectorFileWriter(
            self.shape_path,
            "CP1250",
            fields,
            QgsWkbTypes.Point,
            QgsCoordinateReferenceSystem(),
            "ESRI Shapefile",
        )
        try:
            if writer.hasError() != QgsVectorFileWriter.NoError:
                msg = "Error while creating shapefile: " + str(writer.errorMessage())
                logger.error(msg)
                raise Exception(msg)
            else:
                for pixel_check_dict in self.input_data_shp:
                    raster = pixel_check_dict.get("raster")
                    setting_id = pixel_check_dict.get("setting_id")
                    coords = pixel_check_dict.get("coords")
                    for row in coords:
                        for point in row:
                            point_y = point[0]
                            point_x = point[1]
                            feat = QgsFeature()
                            feat.setGeometry(
                                QgsGeometry.fromPointXY(QgsPointXY(point_x, point_y))
                            )
                            feat.setAttributes([setting_id, raster, point_x, point_y])
                            writer.addFeature(feat)
        except Exception:
            # TODO: there's a "raise" inside the try, there's a raise
            # below. What's the intention?
            logger.exception("Error creating shapefile")
            raise AssertionError("could not write XY point to shp file")
        # delete the writer to flush features to disk
        del writer
Exemplo n.º 19
0
    def _toVectorLayer_geojson(self):
        crs = QgsCoordinateReferenceSystem()
        crs.createFromUserInput(self.provider.srsName)

        fileName = self.xmlFile.replace(".xml", ".geojson")
        fields = QgsFields()
        map(fields.append, self.provider.fields)
        writer = QgsVectorFileWriter(fileName, "utf-8", fields, QGis.WKBPoint,
                                     crs, "GeoJSON")

        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())

        for feature in self.provider.getFeatures():
            self.features.append(feature)
            writer.addFeature(feature)

        del writer  #Forzar escritura a disco

        return QgsVectorLayer(fileName, self.name, "ogr")
Exemplo n.º 20
0
    def create_pipes_shp(shp_file_path, crs=None):

        fields = QgsFields()
        fields.append(QgsField(QgsField(Pipe.field_name_eid, QVariant.String)))
        # fields.append(QgsField(QgsField(Pipe.field_name_demand, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Pipe.field_name_diameter, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Pipe.field_name_length, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Pipe.field_name_roughness, QVariant.Double)))
        fields.append(
            QgsField(QgsField(Pipe.field_name_status, QVariant.String)))
        fields.append(
            QgsField(QgsField(Pipe.field_name_minor_loss, QVariant.Double)))

        writer = QgsVectorFileWriter(shp_file_path, "CP1250", fields,
                                     QgsWkbTypes.LineString, crs,
                                     "ESRI Shapefile")
        if writer.hasError() != QgsVectorFileWriter.NoError:
            raise Exception(writer.errorMessage())
Exemplo n.º 21
0
 def to_shp(self, path, name, crs, encoding, geom_type, features, graph='primal'):
     if graph == 'primal':
         flds = self.edge_qflds
     elif graph == 'dual':
         flds = [QgsField('source', QVariant.String), QgsField('target', QVariant.String),
                        QgsField('cost', QVariant.Int)]
     if path is None:
         network = QgsVectorLayer('MultiLineString?crs=' + crs.toWkt(), name, "memory")
     else:
         file_writer = QgsVectorFileWriter(path, encoding, flds, geom_type,
                                           crs, "ESRI Shapefile")
         if file_writer.hasError() != QgsVectorFileWriter.NoError:
             print "Error when creating shapefile: ", file_writer.errorMessage()
         del file_writer
         network = QgsVectorLayer(path, name, "ogr")
     # QgsMapLayerRegistry.instance().addMapLayer(network)
     pr = network.dataProvider()
     network.startEditing()
     if path is None:
         pr.addAttributes(flds)
     pr.addFeatures(features)
     network.commitChanges()
     return network
Exemplo n.º 22
0
    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_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            filename = os.path.abspath("Sample_Data/sample_data.shp")
            iface.messageBar().pushMessage("Shapefile loaded ...",
                                           QgsMessageBar.INFO)

            source_layer = iface.addVectorLayer(filename, "sample_data", "ogr")
            centroid = QgsVectorLayer('Point', 'Centroid', 'memory')

            fields = QgsFields()
            fields.append(QgsField("code", QVariant.String))
            fields.append(QgsField("x", QVariant.Double))
            fields.append(QgsField("y", QVariant.Double))

            # Define additional attributes already on the layer level
            centroid_layer = QgsVectorFileWriter(
                centroid, "UTF8", fields, QGis.WKBPoint,
                QgsCoordinateReferenceSystem(4326), "ESRI Shapefile")

            if centroid_layer.hasError() != QgsVectorFileWriter.NoError:
                print("Error when creating centroid: ",
                      centroid_layer.errorMessage())
                iface.messageBar().pushMessage("Feature addition failed.",
                                               QgsMessageBar.CRITICAL)

            centroid_layer.startEditing()
            # Loop over all features
            for source_feature in source_layer.getFeatures():
                geometry = source_feature.geometry()
                centroid = geometry.centroid().asPoint()
                pts = [Centroid]
                name = source_feature["code"]

                # Create the new feature with the fields of the ogr layer
                # And set geometry and attribute before adding it to the target layer
                centroid_feature = QgsFeature(source_layer.fields())
                centroid_feature = source_feature.attributes()
                centroid_feature.setAttributes(centroid_feature)
                centroid_feature.setGeometry(centroid)
                centroid_feature['code'] = name
                centroid_layer.addFeature(centroid_feature)

                # Loop centroids to shapefile
                for x, y in pts:
                    centroid_feature = QgsFeature()
                    point = QgsPoint(x, y)
                    centroid_feature.setGeometry(QgsGeometry.fromPoint(point))
                    centroid_feature.setAttributes(attrs)
                    prov.addFeatures([centroid_feature])

            centroid_layer.commitChanges()

            # Add the layer to the registry
            QgsMapLayerRegistry.instance().addMapLayer(centroid_layer)

            # Save centroid layer as csv format
            QgsVectorFileWriter.writeAsVectorFormat(
                centroid_layer,
                r'extract_centroid',
                "utf-8",
                None,
                "CSV",
                layerOptions='GEOMETRY=AS_XYZ')
            iface.messageBar().pushMessage("Extract centroid saved as csv ...",
                                           QgsMessageBar.INFO)
Exemplo n.º 23
0
    def createGis(self) -> None:
        """
        Create TUFLOW GIS Layer(s)
        Use input GIS feature for data
        
        :return: None
        """

        if self.inputs['gis feature'] is not None:
            if self.inputs['output gis'] is not None:
                for gisOutput in self.inputs['output gis']:
                    fields = QgsFields()
                    feat = QgsFeature()
                    feat.setGeometry(self.inputs['gis feature'].geometry())
                    name = os.path.splitext(
                        os.path.basename(self.inputs['output file']))[0]
                    if gisOutput == Refh2.RF:
                        outfile = os.path.join(
                            os.path.dirname(self.inputs['output file']),
                            '2d_rf_{0}_R.shp'.format(name))
                        fields.append(
                            QgsField("Name", QVariant.String, len=100))
                        fields.append(
                            QgsField("f1", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("f2", QVariant.Double, len=15, prec=5))
                        feat.setAttributes(
                            [self.inputs['rainfall name'], 1, 1])
                    elif gisOutput == Refh2.SA_RF:
                        outfile = os.path.join(
                            os.path.dirname(self.inputs['output file']),
                            '2d_sa_rf_{0}_R.shp'.format(name))
                        fields.append(
                            QgsField("Name", QVariant.String, len=100))
                        fields.append(
                            QgsField("Catchment_",
                                     QVariant.Double,
                                     len=15,
                                     prec=5))
                        fields.append(
                            QgsField("Rain_Gauge",
                                     QVariant.Double,
                                     len=15,
                                     prec=5))
                        fields.append(
                            QgsField("IL", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("CL", QVariant.Double, len=15, prec=5))
                        feat.setAttributes([
                            self.inputs['rainfall name'], self.inputs['area'],
                            NULL, NULL, NULL
                        ])
                    elif gisOutput == Refh2.SA:
                        outfile = os.path.join(
                            os.path.dirname(self.inputs['output file']),
                            '2d_sa_{0}_R.shp'.format(name))
                        fields.append(
                            QgsField("Name", QVariant.String, len=100))
                        feat.setAttributes([self.inputs['inflow name']])
                    elif gisOutput == Refh2.BC_2d:
                        outfile = os.path.join(
                            os.path.dirname(self.inputs['output file']),
                            '2d_rf_{0}_L.shp'.format(name))
                        fields.append(QgsField("Type", QVariant.String, len=2))
                        fields.append(QgsField("Flags", QVariant.String,
                                               len=3))
                        fields.append(
                            QgsField("Name", QVariant.String, len=100))
                        fields.append(
                            QgsField("f", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("d", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("td", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("a", QVariant.Double, len=15, prec=5))
                        fields.append(
                            QgsField("b", QVariant.Double, len=15, prec=5))
                        feat.setAttributes([
                            'QT', NULL, self.inputs['inflow name'], NULL, NULL,
                            NULL, NULL, NULL
                        ])
                    elif gisOutput == Refh2.BC_1d:
                        if self.inputs[
                                'gis geometry'] == QgsWkbTypes.PointGeometry:
                            outfile = os.path.join(
                                os.path.dirname(self.inputs['output file']),
                                '1d_bc_{0}_P.shp'.format(name))
                        else:
                            outfile = os.path.join(
                                os.path.dirname(self.inputs['output file']),
                                '1d_bc_{0}_R.shp'.format(name))
                        fields.append(QgsField("Type", QVariant.String, len=2))
                        fields.append(QgsField("Flags", QVariant.String,
                                               len=6))
                        fields.append(QgsField("Name", QVariant.String,
                                               len=50))
                        fields.append(
                            QgsField("Descriptio", QVariant.String, len=250))
                        feat.setAttributes(
                            ['QT', NULL, self.inputs['inflow name'], NULL])
                    writer = QgsVectorFileWriter(outfile,
                                                 "UTF-8",
                                                 fields,
                                                 self.inputs['gis geometry'],
                                                 self.inputs['crs'],
                                                 driverName="ESRI Shapefile")
                    if writer.hasError() != QgsVectorFileWriter.NoError:
                        self.finished.emit(writer.errorMessage())
                        return
                    writer.addFeature(feat)
                    del writer
Exemplo n.º 24
0
def pointAndLine(polygonLayer, projFolder):
    #  Get the Attribute of "mesh_size " from polygon layer imported
    fields = polygonLayer.pendingFields()
    mesh_size_idx = fields.fieldNameIndex("mesh_size")
    FB_idx = fields.fieldNameIndex("ForceBound")

    #  Attributes fields of the point features
    p_fields = QgsFields()
    p_fields.append(QgsField("id", QVariant.Int))
    p_fields.append(QgsField("Name", QVariant.String))
    p_fields.append(QgsField("mesh_size", QVariant.Double))
    p_fields.append(QgsField("Loop", QVariant.Int))
    p_fields.append(QgsField("X", QVariant.Double))
    p_fields.append(QgsField("Y", QVariant.Double))
    p_fields.append(QgsField("Physical", QVariant.String))

    savePath_point = os.path.join(
        projFolder, os.path.join('MainLayers', "polygon-points.shp"))
    Pointwriter = QgsVectorFileWriter(savePath_point, "utf-8", p_fields,
                                      QGis.WKBPoint, None, "ESRI Shapefile")

    #  Attributes field of the line layers
    l_fields = QgsFields()
    l_fields.append(QgsField("id", QVariant.Int))
    l_fields.append(QgsField("Name", QVariant.String))
    l_fields.append(QgsField("Loop", QVariant.Int))
    l_fields.append(QgsField("Line_id", QVariant.Int))
    l_fields.append(QgsField("Start_p", QVariant.Int))
    l_fields.append(QgsField("End_p", QVariant.Int))
    #  Force boundary True is pre-set, the grid-zone must fit the polygon
    #  boundary set in the original polygon layer.
    #  Using Boolean value for boundary attribute field is not supported, thus
    #  0 and 1 is used for False and True. (0 = False, 1 = True)
    l_fields.append(QgsField("ForceBound", QVariant.Int))
    l_fields.append(QgsField("Physical", QVariant.String))

    savePath_line = os.path.join(
        projFolder, os.path.join('MainLayers', "polygon-line.shp"))
    LineWriter = QgsVectorFileWriter(savePath_line, "utf-8", l_fields,
                                     QGis.WKBLineString, None,
                                     "ESRI Shapefile")

    if Pointwriter.hasError() != QgsVectorFileWriter.NoError:
        print "Error when creating shapefile: ", Pointwriter.errorMessage()
    if LineWriter.hasError() != QgsVectorFileWriter.NoError:
        print "Error when creating shapefile: ", LineWriter.errorMessage()

    id_num = 0
    feature_num = 0
    line_id_num = 0

    units = len(str(polygonLayer.featureCount()))
    polygon_info = dict()
    """dict to reference the total number of points and lines inside a
    polygon."""

    #  From the target shapefile layer, cycle through the features to read its
    #  geometery(Assumed polygon layer)
    for feature in polygonLayer.getFeatures():
        #  Read the geometry of feature from polygons in target layer(polygon)
        polygonGeometry = feature.geometry().asPolygon()
        num_in_polygon = 0  # id of the polygon

        #  Loop through all loops inside a polygon
        p_loops = list()
        for i in range(0, len(polygonGeometry)):
            _points = polygonGeometry[i]
            points = list()
            points.append(polygonGeometry[i][0])
            #  There may be repetitive points in polygon, remove the repetive
            #  points before output into shapefile
            #  Build one empty list, and copy the non-repetitive points into the
            #  list
            for j in range(1, len(polygonGeometry[i])):
                #  If the point is not on the same position with previous point,
                #  copy the point to the new point geometry list
                if not _points[j] == _points[j - 1]:
                    points.append(_points[j])
            #  For a polygon, the last point is repetitive with the first point,
            #  remove the last point to make sure no repetitive points in the
            #  list.
            if points[-1] == points[0]:
                points.pop(-1)

            p_loops.append(points)
            #  The loops inside a polygon(If many loops inside a polygon).

        p_units = len(str(num_of_points(polygonGeometry)))

        #  Build-up the point layer
        Pointwriter = writePoints(Pointwriter,
                                  p_loops,
                                  feature,
                                  feature_num=feature.id(),
                                  units=units,
                                  num_in_polygon=num_in_polygon,
                                  mesh_size_idx=mesh_size_idx,
                                  id_num=id_num,
                                  p_units=p_units)

        if FB_idx > -1 and feature[FB_idx] == 0:
            line_FBnd = 0
        else:
            line_FBnd = 1

        #  Build-up the line layer
        LineWriter, line_id = writeLines(LineWriter,
                                         p_loops,
                                         feature,
                                         line_FBnd=line_FBnd,
                                         feature_num=feature.id(),
                                         units=units,
                                         p_units=p_units,
                                         line_id_num=line_id_num)

        loop_num = len(p_loops)
        #  Update the polygon_info dict
        polygon_info.update({
            str(feature_num).zfill(units): {
                'points': num_of_points(polygonGeometry),
                'lines': line_id + 1,
                'loops': loop_num
            }
        })

    #  Delete the shapefile writer and writes into vector layer
    del Pointwriter
    #  Load the created point layer into qgis
    del LineWriter
    #  Load the created line layer into qgis
    pointLayer = QgsVectorLayer(savePath_point,
                                QFileInfo(savePath_point).baseName(), 'ogr')
    lineLayer = QgsVectorLayer(savePath_line,
                               QFileInfo(savePath_line).baseName(), 'ogr')
    return pointLayer, lineLayer
Exemplo n.º 25
0
    def _preparePolygonLayer(self, theQgisLayer):
        """Create a new layer with no intersecting features to self.layer.

        A helper function to align the polygons to the postprocLayer
        polygons. If one input polygon is in two or more postprocLayer polygons
        then it is divided so that each part is within only one of the
        postprocLayer polygons. this allows to aggregate in postrocessing using
        centroid in polygon.

        The function assumes EPSG:4326 but no checks are enforced

        Args:
            theQgisLayer of the file to be processed
        Returns:
            QgisLayer of the processed file

        Raises:
            Any exceptions raised by the InaSAFE library will be propagated.
        """
#        import time
#        startTime = time.clock()

        myMessage = m.Message(
            m.Heading(self.tr('Preclipping input data...')),
            m.Paragraph(self.tr(
                'Modifying %1 to avoid intersections with the aggregation '
                'layer'
            ).arg(theQgisLayer.name())))
        self._sendMessage(myMessage)

        theLayerFilename = str(theQgisLayer.source())
        myPostprocPolygons = self.safeLayer.get_geometry()
        myPolygonsLayer = safe_read_layer(theLayerFilename)
        myRemainingPolygons = numpy.array(myPolygonsLayer.get_geometry())
#        myRemainingAttributes = numpy.array(myPolygonsLayer.get_data())
        myRemainingIndexes = numpy.array(range(len(myRemainingPolygons)))

        #used for unit tests only
        self.preprocessedFeatureCount = 0

        # FIXME (MB) the intersecting array is used only for debugging and
        # could be safely removed
        myIntersectingPolygons = []
        myInsidePolygons = []

        # FIXME (MB) maybe do raw geos without qgis
        #select all postproc polygons with no attributes
        aggregationProvider = self.layer.dataProvider()
        aggregationProvider.select([])

        # copy polygons to a memory layer
        myQgisMemoryLayer = create_memory_layer(theQgisLayer)

        polygonsProvider = myQgisMemoryLayer.dataProvider()
        allPolygonAttrs = polygonsProvider.attributeIndexes()
        polygonsProvider.select(allPolygonAttrs)
        myQgisPostprocPoly = QgsFeature()
        myQgisFeat = QgsFeature()
        myInsideFeat = QgsFeature()
        fields = polygonsProvider.fields()
        myTempdir = temp_dir(sub_dir='preprocess')
        myOutFilename = unique_filename(suffix='.shp',
                                        dir=myTempdir)

        self.keywordIO.copy_keywords(theQgisLayer, myOutFilename)
        mySHPWriter = QgsVectorFileWriter(myOutFilename,
                                          'UTF-8',
                                          fields,
                                          polygonsProvider.geometryType(),
                                          polygonsProvider.crs())
        if mySHPWriter.hasError():
            raise InvalidParameterError(mySHPWriter.errorMessage())
        # end FIXME

        for (myPostprocPolygonIndex,
             myPostprocPolygon) in enumerate(myPostprocPolygons):
            LOGGER.debug('PostprocPolygon %s' % myPostprocPolygonIndex)
            myPolygonsCount = len(myRemainingPolygons)
            aggregationProvider.featureAtId(
                myPostprocPolygonIndex, myQgisPostprocPoly, True, [])
            myQgisPostprocGeom = QgsGeometry(myQgisPostprocPoly.geometry())

            # myPostprocPolygon bounding box values
            A = numpy.array(myPostprocPolygon)
            minx = miny = sys.maxint
            maxx = maxy = -minx
            myPostprocPolygonMinx = min(minx, min(A[:, 0]))
            myPostprocPolygonMaxx = max(maxx, max(A[:, 0]))
            myPostprocPolygonMiny = min(miny, min(A[:, 1]))
            myPostprocPolygonMaxy = max(maxy, max(A[:, 1]))

            # create an array full of False to store if a BB vertex is inside
            # or outside the myPostprocPolygon
            myAreVerticesInside = numpy.zeros(myPolygonsCount * 4,
                                              dtype=numpy.bool)

            # Create Nx2 vector of vertices of bounding boxes
            myBBVertices = []
            # Compute bounding box for each geometry type
            for myPoly in myRemainingPolygons:
                minx = miny = sys.maxint
                maxx = maxy = -minx
                # Do outer ring only as the BB is outside anyway
                A = numpy.array(myPoly)
                minx = min(minx, numpy.min(A[:, 0]))
                maxx = max(maxx, numpy.max(A[:, 0]))
                miny = min(miny, numpy.min(A[:, 1]))
                maxy = max(maxy, numpy.max(A[:, 1]))
                myBBVertices.extend([(minx, miny),
                                    (minx, maxy),
                                    (maxx, maxy),
                                    (maxx, miny)])

            # see if BB vertices are in myPostprocPolygon
            myBBVertices = numpy.array(myBBVertices)
            inside, _ = points_in_and_outside_polygon(myBBVertices,
                                                      myPostprocPolygon)
            # make True if the vertice was in myPostprocPolygon
            myAreVerticesInside[inside] = True

            # myNextIterPolygons has the 0:count indexes
            # myOutsidePolygons has the mapped to original indexes
            # and is overwritten at every iteration because we care only of
            # the outside polygons remaining after the last iteration
            myNextIterPolygons = []
            myOutsidePolygons = []

            for i in range(myPolygonsCount):
                k = i * 4
                myMappedIndex = myRemainingIndexes[i]
                # memory layers counting starts at 1 instead of 0 as in our
                # indexes
                myFeatId = myMappedIndex + 1
                doIntersection = False
                # summ the isInside bool for each of the boundingbox vertices
                # of each poygon. for example True + True + False + True is 3
                myPolygonLocation = numpy.sum(myAreVerticesInside[k:k + 4])

                if myPolygonLocation == 4:
                    # all vertices are inside -> polygon is inside
                    #ignore this polygon from further analysis
                    myInsidePolygons.append(myMappedIndex)
                    polygonsProvider.featureAtId(myFeatId,
                                                 myQgisFeat,
                                                 True,
                                                 allPolygonAttrs)
                    mySHPWriter.addFeature(myQgisFeat)
                    self.preprocessedFeatureCount += 1
#                    LOGGER.debug('Polygon %s is fully inside' %myMappedIndex)
#                    tmpWriter.addFeature(myQgisFeat)

                elif myPolygonLocation == 0:
                    # all vertices are outside
                    # check if the polygon BB is completely outside of the
                    # myPostprocPolygon BB.
                    myPolyMinx = numpy.min(myBBVertices[k:k + 4, 0])
                    myPolyMaxx = numpy.max(myBBVertices[k:k + 4, 0])
                    myPolyMiny = numpy.min(myBBVertices[k:k + 4, 1])
                    myPolyMaxy = numpy.max(myBBVertices[k:k + 4, 1])

                    # check if myPoly is all E,W,N,S of myPostprocPolygon
                    if ((myPolyMinx > myPostprocPolygonMaxx) or
                            (myPolyMaxx < myPostprocPolygonMinx) or
                            (myPolyMiny > myPostprocPolygonMaxy) or
                            (myPolyMaxy < myPostprocPolygonMiny)):
                        #polygon is surely outside
                        myOutsidePolygons.append(myMappedIndex)
                        # we need this polygon in the next iteration
                        myNextIterPolygons.append(i)
                    else:
                        # polygon might be outside or intersecting. consider
                        # it intersecting so it goes into further analysis
                        doIntersection = True
                else:
                    # some vertices are outside some inside -> polygon is
                    # intersecting
                    doIntersection = True

                #intersect using qgis
                if doIntersection:
#                    LOGGER.debug('Intersecting polygon %s' % myMappedIndex)
                    myIntersectingPolygons.append(myMappedIndex)

                    ok = polygonsProvider.featureAtId(myFeatId,
                                                      myQgisFeat,
                                                      True,
                                                      allPolygonAttrs)
                    if not ok:
                        LOGGER.debug('Couldn\'t fetch feature: %s' % myFeatId)
                        LOGGER.debug([str(error) for error in
                                      polygonsProvider.errors()])

                    myQgisPolyGeom = QgsGeometry(myQgisFeat.geometry())
                    myAtMap = myQgisFeat.attributeMap()
#                    for (k, attr) in myAtMap.iteritems():
#                        LOGGER.debug( "%d: %s" % (k, attr.toString()))

                    # make intersection of the myQgisFeat and the postprocPoly
                    # write the inside part to a shp file and the outside part
                    # back to the original QGIS layer
                    try:
                        myIntersec = myQgisPostprocGeom.intersection(
                            myQgisPolyGeom)
#                        if myIntersec is not None:
                        myIntersecGeom = QgsGeometry(myIntersec)

                        #from ftools
                        myUnknownGeomType = 0
                        if myIntersecGeom.wkbType() == myUnknownGeomType:
                            int_com = myQgisPostprocGeom.combine(
                                myQgisPolyGeom)
                            int_sym = myQgisPostprocGeom.symDifference(
                                myQgisPolyGeom)
                            myIntersecGeom = QgsGeometry(
                                int_com.difference(int_sym))
#                        LOGGER.debug('wkbType type of intersection: %s' %
# myIntersecGeom.wkbType())
                        polygonTypesList = [QGis.WKBPolygon,
                                            QGis.WKBMultiPolygon]
                        if myIntersecGeom.wkbType() in polygonTypesList:
                            myInsideFeat.setGeometry(myIntersecGeom)
                            myInsideFeat.setAttributeMap(myAtMap)
                            mySHPWriter.addFeature(myInsideFeat)
                            self.preprocessedFeatureCount += 1
                        else:
                            pass
#                            LOGGER.debug('Intersection not a polygon so '
#                                         'the two polygons either touch '
#                                         'only or do not intersect. Not '
#                                         'adding this to the inside list')
                        #Part of the polygon that is outside the postprocpoly
                        myOutside = myQgisPolyGeom.difference(myIntersecGeom)
#                        if myOutside is not None:
                        myOutsideGeom = QgsGeometry(myOutside)

                        if myOutsideGeom.wkbType() in polygonTypesList:
                            # modifiy the original geometry to the part
                            # outside of the postproc polygon
                            polygonsProvider.changeGeometryValues(
                                {myFeatId: myOutsideGeom})
                            # we need this polygon in the next iteration
                            myOutsidePolygons.append(myMappedIndex)
                            myNextIterPolygons.append(i)

                    except TypeError:
                        LOGGER.debug('ERROR with FID %s', myMappedIndex)

#            LOGGER.debug('Inside %s' % myInsidePolygons)
#            LOGGER.debug('Outside %s' % myOutsidePolygons)
#            LOGGER.debug('Intersec %s' % myIntersectingPolygons)
            if len(myNextIterPolygons) > 0:
                #some polygons are still completely outside of the postprocPoly
                #so go on and reiterate using only these
                nextIterPolygonsIndex = numpy.array(myNextIterPolygons)

                myRemainingPolygons = myRemainingPolygons[
                    nextIterPolygonsIndex]
#                myRemainingAttributes = myRemainingAttributes[
#                                        nextIterPolygonsIndex]
                myRemainingIndexes = myRemainingIndexes[nextIterPolygonsIndex]
                LOGGER.debug('Remaining: %s' % len(myRemainingPolygons))
            else:
                print 'no more polygons to be checked'
                break
#            del tmpWriter

        # here the full polygon set is represented by:
        # myInsidePolygons + myIntersectingPolygons + myNextIterPolygons
        # the a polygon intersecting multiple postproc polygons appears
        # multiple times in the array
        # noinspection PyUnboundLocalVariable
        LOGGER.debug('Results:\nInside: %s\nIntersect: %s\nOutside: %s' % (
            myInsidePolygons, myIntersectingPolygons, myOutsidePolygons))

        #add in- and outside polygons

        for i in myOutsidePolygons:
            myFeatId = i + 1
            polygonsProvider.featureAtId(myFeatId, myQgisFeat, True,
                                         allPolygonAttrs)
            mySHPWriter.addFeature(myQgisFeat)
            self.preprocessedFeatureCount += 1

        del mySHPWriter
#        LOGGER.debug('Created: %s' % self.preprocessedFeatureCount)

        myName = '%s %s' % (theQgisLayer.name(), self.tr('preprocessed'))
        myOutLayer = QgsVectorLayer(myOutFilename, myName, 'ogr')
        if not myOutLayer.isValid():
            #TODO (MB) use a better exception
            raise Exception('Invalid qgis Layer')

        if self.showIntermediateLayers:
            self.keywordIO.update_keywords(myOutLayer, {'title': myName})
            QgsMapLayerRegistry.instance().addMapLayer(myOutLayer)

        return myOutLayer
Exemplo n.º 26
0
    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_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            # current user home path
            filename = os.path.abspath("current_point_feature.shp")

            # load to map canvas
            layer = iface.activeLayer()

            # Export a vector layer directly from features
            # define fields for feature attributes. A QgsFields object is needed
            fields = QgsFields()
            fields.append(QgsField("DATE", QVariant.String))

            writer = QgsVectorFileWriter(filename, "UTF8", fields,
                                         QGis.WKBPoint,
                                         QgsCoordinateReferenceSystem(4326),
                                         "ESRI Shapefile")

            iface.messageBar().pushMessage(
                "Shapefile attributes successfully created.",
                QgsMessageBar.INFO)
            # create shapefile to disk
            layers = QgsVectorLayer(filename, "Current Location", "ogr")

            if not layers.isValid():
                print "Layers %s did not load" % layers.name()
                iface.messageBar().pushMessage("Error creating shapefile.",
                                               QgsMessageBar.CRITICAL)
            iface.messageBar().pushMessage("Shapefile successfully created.",
                                           QgsMessageBar.INFO)
            # style option

            # add layer to map canvas
            QgsMapLayerRegistry.instance().addMapLayers([layers])
            iface.messageBar().pushMessage("Shapefile added to map canvas.",
                                           QgsMessageBar.INFO)

            # check the attributes have been added
            if writer.hasError() != QgsVectorFileWriter.NoError:
                print("Error when creating shapefile: ", writer.errorMessage())
                iface.messageBar().pushMessage("Feature addition failed.",
                                               QgsMessageBar.CRITICAL)

            # Add a feature
            fet = QgsFeature()
            fet.setGeometry(QgsGeometry().fromPoint(QgsPoint(36.5, -0.43)))

            # variable for date attribute
            value = time.strftime("%Y-%m-%d")

            # Add date value to date attribute
            fet.setAttributes([value])
            writer.addFeature(fet)

            # set datetime variable
            d = datetime.datetime.now()
            dt = d.strftime("%Y-%m-%d-%H:%M:%S")
            file = QFileInfo(os.path.abspath('Current Location_' + dt +
                                             '.qgs'))
            project = QgsProject.instance()
            project.write(file)
Exemplo n.º 27
0
    def processSampleRasterAlgorithm(self, pointSpacing, INPUT_EXTENT,
                                     SAMPLE_FILE, OUTPUT_FILE, feedback):
        if (os.path.isfile(OUTPUT_FILE)):
            return 0

        fields = QgsFields()
        fields.append(QgsField("slope", QVariant.Double))

        sampleLayer = QgsRasterLayer(SAMPLE_FILE, 'Reclassified Slope', 'gdal')

        #pointLayerPath = quote(INPUT_POINTS)
        #pointLayer = QgsVectorLayer(pointLayerPath, 'points', 'ogr')
        QgsMessageLog.logMessage(
            'Now generate points: extent={} crs={}'.format(
                INPUT_EXTENT.toString(),
                sampleLayer.crs().description()))
        pointLayer = processing.run('qgis:regularpoints', {
            'EXTENT': INPUT_EXTENT,
            'SPACING': pointSpacing,
            'INSET': 0,
            'IS_SPACING': True,
            'RANDOMIZE': False,
            'CRS': sampleLayer.crs().description(),
            'OUTPUT': 'memory:'
        },
                                    feedback=feedback)['OUTPUT']

        #QgsMessageLog.logMessage("Points done!")
        #QgsMessageLog.logMessage("Now build sample points destination")
        sampledPointsLayerPath = OUTPUT_FILE
        sampledPointsLayer = QgsVectorFileWriter(sampledPointsLayerPath,
                                                 "utf-8", fields,
                                                 QgsWkbTypes.Point,
                                                 sampleLayer.crs(),
                                                 "ESRI Shapefile")

        result = sampledPointsLayer.hasError()
        QgsMessageLog.logMessage(
            "INITIAL ERROR CHECK, CODE: {}, MSG: {}".format(
                result, sampledPointsLayer.errorMessage()))
        if result > 0:
            return result

        #QgsMessageLog.logMessage("Does writer have error? {}, {}".format(sampledPointsLayer.hasError(), sampledPointsLayer.errorMessage()))
        #QgsMessageLog.logMessage("Will sample {} points".format(pointLayer.featureCount()))

        count = pointLayer.featureCount()
        total = 100.0 / count if count else 0
        features = pointLayer.getFeatures(QgsFeatureRequest())
        current = 0
        featureGroups = chunks(features, count, 100)
        QgsMessageLog.logMessage("FEATURE COUNT: {}".format(count))
        for group in featureGroups:
            for feature in group:
                # Stop the algorithm if cancel button has been clicked
                #QgsMessageLog.logMessage("Current: {}".format(current))
                #QgsMessageLog.logMessage("Feature: {}".format(feature))
                if feedback.isCanceled():
                    break
                current = current + 1
                ident = sampleLayer.dataProvider().identify(
                    feature.geometry().asPoint(),
                    QgsRaster.IdentifyFormatValue)
                if (ident.results()[1]) is not None and int(
                        ident.results()[1]) == 1:
                    out_point = QgsFeature(fields)
                    out_point.setGeometry(feature.geometry())
                    out_point.setAttribute('slope', ident.results()[1])
                    sampledPointsLayer.addFeature(out_point,
                                                  QgsFeatureSink.FastInsert)

            # Update the progress bar
            feedback.setProgress(int(current * total))

        result = sampledPointsLayer.hasError()
        del sampledPointsLayer
        return result
# Export a vector layer directly from features
# define fields for feature attributes. A QgsFields object is needed
fields = QgsFields()
fields.append(QgsField("first", QVariant.Int))
fields.append(QgsField("second", QVariant.String))

# Create an instance of vector file writer, which will create the vector file.
# Arguments:
# 1. path to new file (will fail if exists already)
# 2. encoding of the attributes
# 3. field map
# 4. geometry type - from WKBTYPE enum
# 5. layer's spatial reference (instance of
#    QgsCoordinateReferenceSystem) - optional
# 6. driver name for the output file
writer = QgsVectorFileWriter("my_shapes.shp", "CP1250", fields,
                             QGis.WKBPoint, None, "ESRI Shapefile")

if writer.hasError() != QgsVectorFileWriter.NoError:
    print("Error when creating shapefile: ", writer.errorMessage())

# Add a feature
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10)))
fet.setAttributes([1, "text"])
writer.addFeature(fet)

# Delete the writer to flush features to disk
del writer
# Export a vector layer directly from features
# define fields for feature attributes. A QgsFields object is needed
fields = QgsFields()
fields.append(QgsField("first", QVariant.Int))
fields.append(QgsField("second", QVariant.String))

# Create an instance of vector file writer, which will create the vector file.
# Arguments:
# 1. path to new file (will fail if exists already)
# 2. encoding of the attributes
# 3. field map
# 4. geometry type - from WKBTYPE enum
# 5. layer's spatial reference (instance of
#    QgsCoordinateReferenceSystem) - optional
# 6. driver name for the output file
writer = QgsVectorFileWriter("my_shapes.shp", "CP1250", fields, QGis.WKBPoint,
                             None, "ESRI Shapefile")

if writer.hasError() != QgsVectorFileWriter.NoError:
    print("Error when creating shapefile: ", writer.errorMessage())

# Add a feature
fet = QgsFeature()
fet.setGeometry(QgsGeometry.fromPoint(QgsPoint(10, 10)))
fet.setAttributes([1, "text"])
writer.addFeature(fet)

# Delete the writer to flush features to disk
del writer