Exemplo n.º 1
0
def copyMainLayer(layer, CRS, folder):
    fields = layer.pendingFields()

    layerPath = layer.dataProvider().dataSourceUri().split('|')[0]
    baseName = os.path.split(layerPath)[-1].replace(".shp", '')
    path = os.path.join(
        folder, os.path.join('MainLayers', 'Main_' + str(baseName) + '.shp'))
    if os.path.isfile(path):
        return False

    layerType = QGis.WKBPolygon
    newlayer = QgsVectorFileWriter(path, "utf-8", fields, layerType, CRS,
                                   "ESRI Shapefile")

    for feature in layer.getFeatures():
        NewFeature = QgsFeature()  # Create an empty feature
        NewFeature.setGeometry(feature.geometry())  # Set feature geometry
        NewFeature.setAttributes(feature.attributes())  # Set attributes
        #  Update feature to the new layer
        newlayer.addFeature(NewFeature)
    del newlayer

    newAttr = createNewAttrs(fields)

    newlayer = QgsVectorLayer(path, QFileInfo(path).baseName(), 'ogr')
    newlayer.startEditing()
    #  Add new attribute field to layer
    newlayer.dataProvider().addAttributes(newAttr)
    newlayer.commitChanges()

    newlayer.startEditing()
    fields = newlayer.pendingFields()
    FB_idx = fields.fieldNameIndex("ForceBound")
    Phx_idx = fields.fieldNameIndex("Physical")
    struct_idx = fields.fieldNameIndex("Recombine")
    geo_idx = fields.fieldNameIndex("geoName")
    for feature in newlayer.getFeatures():
        featId = feature.id()
        featureFields = feature.attributes()
        #  If nothing is written in field "ForceBound" and "Physical", write in
        #  1 in "ForceBound" to show force boundary in preset, and fill "Domain"
        #  in "Physical" to express the physical domain in grid generation.
        if type(featureFields[FB_idx]) == QPyNullVariant:
            attr = {FB_idx: 0}
            newlayer.dataProvider().changeAttributeValues({featId: attr})
        if type(featureFields[Phx_idx]) == QPyNullVariant:
            attr = {Phx_idx: "Domain"}
            newlayer.dataProvider().changeAttributeValues({featId: attr})
        if type(featureFields[struct_idx]) == QPyNullVariant:
            attr = {struct_idx: 1}
            newlayer.dataProvider().changeAttributeValues({featId: attr})
        if type(featureFields[geo_idx]) == QPyNullVariant:
            name = "IS+" + str(feature.id() + 1)
            attr = {geo_idx: name}
            newlayer.dataProvider().changeAttributeValues({featId: attr})
    newlayer.commitChanges()

    return newlayer