Esempio n. 1
0
def multipoly2poly(inshape, outshape):

    # Get field list
    field_name_list = vf.getFields(inshape)
    
    # Open input and output shapefile
    driver = ogr.GetDriverByName('ESRI Shapefile')
    in_ds = driver.Open(inshape, 0)
    in_lyr = in_ds.GetLayer()
    inLayerDefn = in_lyr.GetLayerDefn()
    srsObj = in_lyr.GetSpatialRef()
    if os.path.exists(outshape):
        driver.DeleteDataSource(outshape)

    out_ds = driver.CreateDataSource(outshape)
    out_lyr = out_ds.CreateLayer('poly', srsObj, geom_type = ogr.wkbPolygon)

    for i in range(0, len(field_name_list)):
	fieldDefn = inLayerDefn.GetFieldDefn(i)
	fieldName = fieldDefn.GetName()
	if fieldName not in field_name_list:
		continue
	out_lyr.CreateField(fieldDefn)

    manageMultiPoly2Poly(in_lyr, out_lyr, field_name_list)
Esempio n. 2
0
def manageFieldShapefile(shapefile, value, areapix):

    # Liste des champs existants
    fieldList = vf.getFields(shapefile)

    # Creation d'un FID unique
    if 'ID' in fieldList:
        DeleteField.deleteField(shapefile, 'ID')
        AddFieldID.addFieldID(shapefile)
        fieldList.remove('ID')
    else:
        AddFieldID.addFieldID(shapefile)

    if cfg.parameters.landCoverField in fieldList:
        DeleteField.deleteField(shapefile, cfg.parameters.landCoverField)
        AddField.addField(shapefile, cfg.parameters.landCoverField, value)
        fieldList.remove(cfg.parameters.landCoverField)
    else:
        AddField.addField(shapefile, cfg.parameters.landCoverField, value)

    if 'Area' in fieldList:
        DeleteField.deleteField(shapefile, 'Area')
        AddFieldArea.addFieldArea(shapefile, areapix)
        fieldList.remove('Area')
    else:
        AddFieldArea.addFieldArea(shapefile, areapix)

    # Suppression des champs initiaux
    for field in fieldList:
        DeleteField.deleteField(shapefile, field)
Esempio n. 3
0
def manageFieldShapefile(shapefile, fieldout, areapix):

    # existing fields
    fieldList = vf.getFields(shapefile)
    #fieldList = [x.lower() for x in fieldList]
    #fieldList.remove(fieldout.lower())
    fieldList.remove(fieldout)

    print fieldList
    # FID creation
    if 'ID' not in fieldList:
        AddFieldID.addFieldID(shapefile)
    else:
        fieldList.remove('ID')

    # Area field creation
    if 'Area' in fieldList:
        DeleteField.deleteField(shapefile, 'Area')
        AddFieldArea.addFieldArea(shapefile, areapix)
        fieldList.remove('Area')
    else:
        AddFieldArea.addFieldArea(shapefile, areapix)

    # Suppression des champs initiaux
    for field in fieldList:
        DeleteField.deleteField(shapefile, field)
def checkGeometryAreaThreshField(shapefile, pixelArea, pix_thresh, outshape):

    tmpfile = []

    # Empty geometry identification
    try:
        outShapefileGeom = vf.checkEmptyGeom(shapefile)
        tmpfile.append(outShapefileGeom)
        print 'Check empty geometries succeeded'
    except Exception as e:
        print 'Check empty geometries did not work for the following error :'
        print e

    # suppression des doubles géométries
    DeleteDuplicateGeometriesSqlite.deleteDuplicateGeometriesSqlite(
        outShapefileGeom)

    # Suppression des multipolygons
    shapefileNoDupspoly = outShapefileGeom[:-4] + 'spoly' + '.shp'
    tmpfile.append(shapefileNoDupspoly)
    try:
        MultiPolyToPoly.multipoly2poly(outShapefileGeom, shapefileNoDupspoly)
        print 'Conversion of multipolygons shapefile to single polygons succeeded'
    except Exception as e:
        print 'Conversion of multipolygons shapefile to single polygons did not work for the following error :'
        print e

    # recalcul des superficies
    try:
        AddFieldArea.addFieldArea(shapefileNoDupspoly, pixelArea)
    except Exception as e:
        print 'Add an Area field did not work for the following error :'
        print e

    # Attribution d'un ID
    fieldList = vf.getFields(shapefileNoDupspoly)
    if 'ID' in fieldList:
        DeleteField.deleteField(shapefileNoDupspoly, 'ID')
        AddFieldID.addFieldID(shapefileNoDupspoly)
    else:
        AddFieldID.addFieldID(shapefileNoDupspoly)

    # Filter by Area
    try:
        SelectBySize.selectBySize(shapefileNoDupspoly, 'Area', pix_thresh,
                                  outshape)
        print 'Selection by size upper {} pixel(s) succeeded'.format(
            pix_thresh)
    except Exception as e:
        print 'Selection by size did not work for the following error :'
        print e

    # Check geometry
    vf.checkValidGeom(outshape)

    # delete tmp file
    for fileDel in tmpfile:
        basefile = os.path.splitext(fileDel)[0]
        os.system('rm {}.*'.format(basefile))
Esempio n. 5
0
def getFieldValues(lyr, feature):

    fieldList = vf.getFields(lyr)

    listFieldValues = []
    for idfield in range(feature.GetFieldCount()):
        listFieldValues.append(
            (idfield, fieldList[idfield], feature.GetField(idfield)))

    return listFieldValues
Esempio n. 6
0
def FileByClass(vectorlayer, field, value, opath):
#def FileByClass(vectorlayer, expression, opath):

        if not isinstance(vectorlayer, osgeo.ogr.Layer):
                ds = vf.openToRead(vectorlayer)
                lyr = ds.GetLayer()
        else:
	        lyr = vectorlayer

        if os.path.splitext(opath)[1] != ".shp":
                print "ESRI Shapefile required for output, output name will be replaced to {}.shp".format(os.path.splitext(opath)[0])
                opath = os.path.splitext(opath)[0] + '.shp'
        
	lyr_dfn = lyr.GetLayerDefn()
	inLayerDefn = lyr.GetLayerDefn()
	field_name_list = []

	if not isinstance(vectorlayer, osgeo.ogr.Layer):
                lyr = ds.GetLayer()
        else:
	        lyr = vectorlayer
      
	fieldList = vf.getFields(lyr)
	if field in fieldList:
		i = fieldList.index(field)
		fieldTypeCode = inLayerDefn.GetFieldDefn(i).GetType()
		fieldType = inLayerDefn.GetFieldDefn(i).GetFieldTypeName(fieldTypeCode)
		values = vf.ListValueFields(vectorlayer, field)
                if fieldType != "String":
			for v in values:
                                if isinstance(value, float) or isinstance(value, int) or isinstance(value, str): 
                                        value = [float(value)]
                                else:
                                        value = list(map(float, value))                                
                                if float(v) in value:
				        lyr.SetAttributeFilter(field + "=" + str(v))
				        vf.CreateNewLayer(lyr, opath)
				        lyr.SetAttributeFilter(None)
                                else:
                                        print "the value {} does not exist, vector file not created".format(v)
		else:
			for v in values:
                                if v in value:
				        lyr.SetAttributeFilter(field + "=\'" + v + "\'")
                                        print opath
				        vf.CreateNewLayer(lyr, opath)
				        lyr.SetAttributeFilter(None)
                                else:
                                        print "the value {} does not exist, vector file not created".format(v)                                        
	else:
		print "Field %s does not exist" %field
		sys.exit(-1)
Esempio n. 7
0
def ListValues(shp):
    fields = vf.getFields(shp)
    print "The name of the fields are: " + ' - '.join(fields)
    field = raw_input("Field to list values: ")
    if not field in fields:
        print 'This field does not exist. Verify!'
        sys.exit(1)
    ds = vf.openToRead(shp)
    layer = ds.GetLayer()
    values = []
    for feat in layer:
        if not feat.GetField(field) in values:
            values.append(feat.GetField(field))
    return values
Esempio n. 8
0
def changeName(filein, fieldin, fieldout):

    fieldList = vf.getFields(filein)
    if fieldout in fieldList:
        print "Field name {} already exists".format(fieldout)
        sys.exit(1)

    # Get input file and field characteritics
    source = ogr.Open(filein, 1)
    layer = source.GetLayer()
    layer_defn = layer.GetLayerDefn()
    i = layer_defn.GetFieldIndex(fieldin)

    # Create the out field with in field characteristics
    try:
        fieldTypeCode = layer_defn.GetFieldDefn(i).GetType()
        fieldWidth = layer_defn.GetFieldDefn(i).GetWidth()
        fieldPrecision = layer_defn.GetFieldDefn(i).GetPrecision()
    except:
        print "Field {} not exists in the input shapefile".format(fieldin)
        sys.exit(0)

    newField = ogr.FieldDefn(fieldout, fieldTypeCode)
    newField.SetWidth(fieldWidth)
    newField.SetPrecision(fieldPrecision)
    layer.CreateField(newField)

    for feat in layer:
        val = feat.GetField(fieldin)
        layer.SetFeature(feat)
        feat.SetField(fieldout, val)
        layer.SetFeature(feat)

    layer = feat = newfield = source = None

    DeleteField.deleteField(filein, fieldin)
Esempio n. 9
0
def gestion_echantillons(Fileconfig, ouputPath):

    cfg = read_config_file(Fileconfig)

    # Global parameters
    res = cfg.parameters.resolution
    area_thresh = int(res) * int(res)
    pix_thresh = cfg.parameters.spatialThreshold

    # Clip input vector files
    if cfg.parameters.cut != '':
        if isinstance(cfg.parameters.cut, config.Sequence):
            for sourceToCut in cfg.parameters.cut:
                clipFile(cfg, ouputPath, sourceToCut)
        else:
            clipFile(cfg, ouputPath, cfg.parameters.cut)

    buff = False
    sources = get_sources(cfg)
    samples_shapefile_source = {}

    os.system("mkdir {}/{}".format(ouputPath, 'final'))

    for source in sources:
        if source in cfg.globalPath or (source.split('_')[0] in cfg.globalPath
                                        and source.split('_')[1]
                                        in cfg.globalPath):
            for classe in sources[source]:

                try:
                    Buffer = cfg.Nomenclature[classe].Buffer
                    buff = True
                except:
                    pass

                if not '_' in source:
                    print 'Traitement de la base de données {} pour la classe {}'.format(
                        source, classe)

                    if buff:
                        outfile_area = gestionSamplesClasse(
                            cfg, classe, source, ouputPath, res, area_thresh,
                            pix_thresh, Buffer)
                    else:
                        outfile_area = gestionSamplesClasse(
                            cfg, classe, source, ouputPath, res, area_thresh,
                            pix_thresh)

                    # gestion finale du fichier
                    gestionFichierFinal(samples_shapefile_source, outfile_area,
                                        ouputPath, source, classe)

                else:
                    complexDataSets = []
                    for sourceBD in source.split('_'):
                        print 'Traitement de la base de données {} pour la classe {}'.format(
                            sourceBD, classe)

                        try:
                            Buffer = cfg.Nomenclature[classe].Buffer[
                                source.split('_').index(sourceBD)]
                        except:
                            Buffer = None

                        if buff and Buffer != 'None':
                            outfile_area = gestionSamplesClasse(
                                cfg, classe, sourceBD, ouputPath, res,
                                area_thresh, pix_thresh, Buffer)
                        else:
                            outfile_area = gestionSamplesClasse(
                                cfg, classe, sourceBD, ouputPath, res,
                                area_thresh, pix_thresh)

                        if outfile_area is not None:
                            complexDataSets.append([sourceBD, outfile_area])

                    # intersection des jeux de données
                    try:
                        priorSource = cfg.Nomenclature[classe].PrioTheme

                        if len([
                                x
                                for x in complexDataSets if priorSource == x[0]
                        ]) != 0:
                            priorPath = [
                                x for x in complexDataSets
                                if priorSource == x[0]
                            ][0][1]
                            secondPath = [
                                x for x in complexDataSets
                                if priorSource != x[0]
                            ][0][1]
                            secondSource = [
                                x for x in complexDataSets
                                if priorSource != x[0]
                            ][0][0]
                            if cfg.parameters.landCoverField not in vf.getFields(
                                    priorPath):
                                print 'No landcover field in {} data source'.format(
                                    priorSource)
                        else:
                            print "the priority source {} not present in sources list".format(
                            )

                        if (priorPath is not None) and (secondPath
                                                        is not None):
                            intersectFilename = ouputPath + '/inter_' + priorSource + '_' + secondSource + '_' + classe + '.shp'
                            #Intersection.intersection(priorPath, secondPath, intersectFilename)
                            command = 'python /home/thierion/Documents/OSO/Dev/vector_tools/IntersectionQGIS.py {} {} {}'.\
                                      format(priorPath, secondPath, intersectFilename)
                            os.system(command)
                        else:
                            # pas d'intersection possible
                            if secondPath is None:
                                intersectFilename = priorPath
                            else:
                                "This case is not yet managed"
                                sys.exit(-1)

                        # gestion des champs
                        # suppression des champs + génération Aire
                        fieldList = vf.getFields(intersectFilename)
                        idxLC = fieldList.index(cfg.parameters.landCoverField)
                        for field in fieldList:
                            if fieldList.index(field) != idxLC:
                                DeleteField.deleteField(
                                    intersectFilename, field)

                        AddFieldID.addFieldID(intersectFilename)
                        AddFieldArea.addFieldArea(intersectFilename,
                                                  area_thresh)

                        samples_shapefile_source = gestionFichierFinal(samples_shapefile_source, intersectFilename, \
                                                                       ouputPath, source, classe)
                    except:
                        for dataset in complexDataSets:
                            samples_shapefile_source = gestionFichierFinal(samples_shapefile_source, dataset[1], \
                                                                           ouputPath, dataset[0], classe)

                buff = False
        else:
            print "No Path for source {} provided while required for classes {}".format(
                source, sources[source])

    # Fusion des echantillons des différents classes pour une source donnée

    dataSourcePriorities = {}
    listpriorities = list(cfg.parameters.priorities)

    maskToMerge = []
    outfilemergemask = ouputPath + '/final/' + cfg.parameters.samplesFileName + '_masks.shp'

    for keysource in samples_shapefile_source:
        outfilemerge = ouputPath + '/final/' + cfg.parameters.samplesFileName + '_' + keysource + '.shp'

        # séparer les couches linéaire de masquage / les couches inexistantes (pas d'échantillons)
        listToMerge = []
        for src in samples_shapefile_source[keysource]:
            if len(samples_shapefile_source[keysource]) != 0:
                if src is not None:
                    if 'mask' not in src:
                        listToMerge.append(src)
                    else:
                        maskToMerge.append(src)

        # Merge des classes par source
        if len(listToMerge) != 0:
            MergeFiles.mergeVectors(listToMerge, outfilemerge)
        elif len(listToMerge) == 1:
            vf.copyShapefile(listToMerge[0], outfilemerge)
        else:
            pass

        # Decoupage avec la grille : cas du parametre areaThresh
        if cfg.parameters.areaThresh != '':
            areaT = int(sqrt(float(cfg.parameters.areaThresh))) * 100.
            if not isinstance(cfg.parameters.sourcesAreaThresh,
                              config.Sequence):
                sourcesAreaThresh = [cfg.parameters.sourcesAreaThresh]
            if keysource in sourcesAreaThresh:
                outgrid = outfilemerge[:-4] + '_grid.shp'
                outgridbuff = outgrid[:-4] + '_buff.shp'
                outfilemergeDiff = outfilemerge[:-4] + 'grid_{}ha.shp'.format(
                    cfg.parameters.areaThresh)
                CreateGrid.create_grid(outfilemerge, outgrid, areaT)
                BufferOgr.bufferPoly(outgrid, outgridbuff, 10)
                command = 'python /home/thierion/Documents/OSO/Dev/vector_tools/DifferenceQGIS.py {} {} {} {}'.\
                          format(outfilemerge, outgridbuff, True, outfilemergeDiff)
                os.system(command)
                outfilemerge = outfilemergeDiff

        # tri des chemins en fonction des priorités pour les opérations de différence
        if '_' not in keysource:
            idx = listpriorities.index(keysource)
            dataSourcePriorities[idx] = outfilemerge

    for keysource in samples_shapefile_source:
        if '_' in keysource:
            outfilemerge = ouputPath + '/final/' + cfg.parameters.samplesFileName + '_' + keysource + '.shp'
            idx1 = listpriorities.index(keysource.split('_')[0])
            idx2 = listpriorities.index(keysource.split('_')[1])
            if idx1 < idx2:
                if idx1 not in dataSourcePriorities.keys():
                    dataSourcePriorities[idx1] = outfilemerge
                else:
                    dataSourcePriorities[idx1 + 0.5] = outfilemerge
            else:
                if idx2 not in dataSourcePriorities.keys():
                    dataSourcePriorities[idx2] = outfilemerge
                else:
                    dataSourcePriorities[idx2 + 0.5] = outfilemerge

    orderedSourcesPaths = [
        value for (key, value) in sorted(dataSourcePriorities.items())
    ]
    orderedSourcesPaths.reverse()

    # Merge des linéaires de masquage
    if len(maskToMerge) != 0:
        MergeFiles.mergeVectors(maskToMerge, outfilemergemask)

    # Différence + masquage final
    nbfiles = len(orderedSourcesPaths)
    indfile = 0
    outpathList = []
    if nbfiles != 1:
        while indfile < nbfiles - 1:
            if indfile == 0:
                output = orderedSourcesPaths[indfile][:-4] + '_' + \
                         os.path.basename(orderedSourcesPaths[indfile + 1]).split('_')[1][:-4] + '.shp'
                outputmerge = orderedSourcesPaths[indfile][:-4] + '_' +  \
                              os.path.basename(orderedSourcesPaths[indfile + 1]).split('_')[1][:-4] + '_merge.shp'
                outpathList.append([
                    orderedSourcesPaths[indfile],
                    orderedSourcesPaths[indfile + 1], output, outputmerge
                ])
            else:
                output = outpathList[indfile - 1][2][:-4] + '_' +  \
                         os.path.basename(orderedSourcesPaths[indfile + 1]).split('_')[1][:-4] + '.shp'
                outputmerge = outpathList[indfile - 1][3][:-10] + '_' + \
                              os.path.basename(orderedSourcesPaths[indfile + 1]).split('_')[1][:-4] + '_merge.shp'
                outpathList.append([
                    outpathList[indfile - 1][3],
                    orderedSourcesPaths[indfile + 1], output, outputmerge
                ])

            indfile += 1

        for listInOuput in outpathList:
            command = 'python /home/thierion/Documents/OSO/Dev/vector_tools/DifferenceQGIS.py {} {} {} {}'.\
                      format(listInOuput[0], listInOuput[1], True,listInOuput[2])
            os.system(command)
            # shapeDifference.shapeDifference(listInOuput[0], listInOuput[1], listInOuput[2], False, None)
            MergeFiles.mergeVectors([listInOuput[1], listInOuput[2]],
                                    listInOuput[3])

        subfinal = outpathList[len(outpathList) - 1][3]

    else:
        subfinal = orderedSourcesPaths[0]

    # Difference avec les masques (réseaux)
    if os.path.exists(outfilemergemask):
        subFinalSsReseaux = subfinal[:-4] + 'ssreseaux.shp'
        command = 'python /home/thierion/Documents/OSO/Dev/vector_tools/DifferenceQGIS.py {} {} {} {}'.\
                  format(subfinal, outfilemergemask, True, subFinalSsReseaux)
        os.system(command)
        #shapeDifference.shapeDifference(subfinal, outfilemergemask, subFinalSsReseaux, False, None)
    else:
        subFinalSsReseaux = subfinal

    # Harmonisation de la couche finale
    try:
        filefinal = ouputPath + '/final/echantillons_OSO_' + cfg.parameters.samplesFileName + '.shp'
        checkGeometryAreaThreshField.checkGeometryAreaThreshField(
            subFinalSsReseaux, area_thresh, pix_thresh, filefinal)
        print "Les échantillons de classification pour la zone {}"\
            " ont été produits dans la couche {}".format(cfg.parameters.samplesFileName, filefinal)
    except:
        print "Un problème de copie a été identifié"

    try:
        vf.RandomSelectionPolygons(filefinal, cfg.parameters.landCoverField, 1,
                                   ouputPath + '/final/', 0.7)
        print "Les échantillons ont été séparés en deux groupes de validation {} et d'apprentissage {}"\
            .format(filefinal[:-4] + '_seed0_val.shp', filefinal[:-4] + '_seed0_learn.shp')
    except:
        print "Problème de tirage aléatoire"
Esempio n. 10
0
def DifferenceFiles(shp1, shp2):
    outShp = vf.copyShp(shp1, 'difference')
    fields = vf.getFields(shp1)
    ds1 = vf.openToRead(shp1)
    ds2 = vf.openToRead(shp2)
    lyr1 = ds1.GetLayer()
    lyr2 = ds2.GetLayer()
    layerDef = lyr1.GetLayerDefn()
    print lyr2.GetFeatureCount()
    for f1 in lyr1:
        lyr2.SetAttributeFilter(None)
        geom1 = f1.GetGeometryRef()
        centroid = geom1.Centroid()
        x = centroid.GetX()
        y = centroid.GetY()
        minX = x - float(distance)
        minY = y - float(distance)
        maxX = x + float(distance)
        maxY = y + float(distance)
        lyr2.SetSpatialFilterRect(float(minX), float(minY), float(maxX),
                                  float(maxY))
        nbfeat2 = lyr2.GetFeatureCount()
        intersection = False
        listFID = []
        copy = False
        for i in range(0, nbfeat2):
            ds3 = vf.openToRead(outShp)
            lyr3 = ds3.GetLayer()
            lyr3.SetSpatialFilterRect(float(minX), float(minY), float(maxX),
                                      float(maxY))
            f2 = lyr2.GetFeature(i)
            print str(f1.GetFID()) + " - " + str(i)
            geom2 = f2.GetGeometryRef()
            if geom1.Intersect(geom2) == True:
                print "True"
                if geom1.Equal(geom2) == True:
                    if vf.VerifyGeom(geom, lyr3) == False:
                        vf.copyFeatInShp(f1, outShp)
                elif geom1.Equal(geom2) == False:
                    newgeom = vf.Difference(geom1, geom2)
                    newgeom2 = ogr.CreateGeometryFromWkb(newgeom.wkb)
                    newgeom2 = geom1.Difference(geom2)
                    #print newgeom2
                    newFeature = ogr.Feature(layerDef)
                    newFeature.SetGeometry(newgeom2)
                    for field in fields:
                        newFeature.SetField(field, f1.GetField(field))
                    if vf.VerifyGeom(newgeom2, lyr3) == False:
                        vf.copyFeatInShp(newFeature, outShp)
                    newFeature.Destroy()
            elif geom1.Intersect(geom2) == False:
                print "False"
                if not vf.VerifyGeom(geom1, lyr3):
                    vf.copyFeatInShp(f1, outShp)
            f2.Destroy()

        f1.Destroy()

    ds2 = vf.openToRead(shp2)
    lyr2 = ds2.GetLayer()
    ds3 = vf.openToWrite(outShp)
    lyr3 = ds3.GetLayer()
    for feat in lyr3:
        geom1 = feat.GetGeometryRef()
        centroid = geom1.Centroid()
        x = centroid.GetX()
        y = centroid.GetY()
        minX = x - float(distance)
        minY = y - float(distance)
        maxX = x + float(distance)
        maxY = y + float(distance)
        lyr2.SetSpatialFilterRect(float(minX), float(minY), float(maxX),
                                  float(maxY))
        nbfeat2 = lyr2.GetFeatureCount()
        intersection = False
        listFID = []
        copy = False
        for i in range(0, nbfeat2):
            f2 = lyr2.GetFeature(i)
            geom2 = f2.GetGeometryRef()
            if geom1.Intersect(geom2) == True:
                lyr3.DeleteFeature(feat.GetFID())
            ds3.ExecuteSQL('REPACK ' + lyr3.GetName())
    return outShp
Esempio n. 11
0
def countByAtt(shpfile, field, storecsv="", val=None):

    ds = vf.openToRead(shpfile)
    fields = vf.getFields(shpfile)
    layer = ds.GetLayer()
    if val is None:
        for feature in layer:
            cl = feature.GetField(field)
            if cl not in classes:
                classes.append(cl)
    else:
        classes.append(val)

    layerDfn = layer.GetLayerDefn()
    fieldTypeCode = layerDfn.GetFieldDefn(fields.index(field)).GetType()
    classes.sort()

    layer.ResetReading()
    totalarea = 0
    if "POLYGON" in vf.getGeomTypeFromFeat(shpfile):
        for feat in layer:
            geom = feat.GetGeometryRef()
            if geom:
                if not math.isnan(geom.GetArea()):
                    totalarea += geom.GetArea()

    stats = []
    for cl in classes:
        if fieldTypeCode == 4:
            layer.SetAttributeFilter(field + " = \"" + str(cl) + "\"")
            featureCount = layer.GetFeatureCount()

            if "POLYGON" in vf.getGeomTypeFromFeat(shpfile):
                area = 0
                for feat in layer:
                    geom = feat.GetGeometryRef()
                    if geom:
                        area += geom.GetArea()
                partcl = area / totalarea * 100

                if storecsv == "" or storecsv is None:
                    print "Class # %s: %s features and a total area of %s (rate : %s)"%(str(cl), \
                                                                                        str(featureCount),\
                                                                                        str(area), \
                                                                                        str(round(partcl,2)))
                stats.append([cl, featureCount, area, partcl])
            else:
                print "Class # %s: %s features"%(str(cl), \
                                                 str(featureCount))
                stats.append([cl, featureCount])

            layer.ResetReading()
        else:
            layer.SetAttributeFilter(field + " = " + str(cl))
            featureCount = layer.GetFeatureCount()

            if "POLYGON" in vf.getGeomTypeFromFeat(shpfile):
                area = 0
                for feat in layer:
                    geom = feat.GetGeometryRef()
                    if geom:
                        area += geom.GetArea()
                partcl = area / totalarea * 100
                if storecsv == "" or storecsv is None:
                    print "Class # %s: %s features and a total area of %s (rate : %s)"%(str(cl), \
                                                                                        str(featureCount),\
                                                                                        str(area),\
                                                                                        str(round(partcl,2)))
                    stats.append([cl, featureCount, area, partcl])
            else:
                print "Class # %s: %s features"%(str(cl), \
                                                 str(featureCount))

                stats.append([cl, featureCount])

            layer.ResetReading()

    if storecsv != "" and storecsv is not None:
        with open(storecsv, "w") as f:
            writer = csv.writer(f)
            writer.writerows(stats)

    return stats
Esempio n. 12
0
def conFieldRecode(shapefile, fieldin, fieldout, valin, valout):

    # open
    ds = ogr.Open(shapefile, 1)
    lyr = ds.GetLayer()

    # fields list
    fieldList = vf.getFields(lyr)
    try:
        indfield = fieldList.index(fieldin)
    except:
        raise Exception(
            "The field {} does not exist in the input shapefile".format(
                fieldin),
            "You must choose one of these existing fields : {}".format(
                ' / '.join(fieldList)))
        sys.exit(-1)

    # Field type
    inLayerDefn = lyr.GetLayerDefn()
    fieldTypeCode = inLayerDefn.GetFieldDefn(indfield).GetType()
    fieldType = inLayerDefn.GetFieldDefn(indfield).GetFieldTypeName(
        fieldTypeCode)
    if fieldout.lower() in [x.lower() for x in fieldList]:
        print "Field '{}' already exists. Existing value of {} field will be changed !!!".format(
            fieldout, fieldout)
    else:
        try:
            new_field = ogr.FieldDefn(fieldout, ogr.OFTInteger)
            lyr.CreateField(new_field)
            print "Field '{}' created".format(fieldout)
        except:
            print("Error while creating field '{}'".format(fieldout))
            sys.exit(-1)

    if fieldType != "String":
        lyr.SetAttributeFilter(fieldin + "=" + str(valin))
        if lyr.GetFeatureCount() != 0:
            try:
                changeValueField(lyr, fieldout, valout)
                print "Field '{}' populated with {} value".format(
                    fieldout, valout)
            except:
                print "Error while populate field '{}'".format(fieldout)
                sys.exit(-1)
        else:
            print "The value '{}' does not exist for the field '{}'".format(
                valin, fieldin)
    else:
        lyr.SetAttributeFilter(fieldin + "=\'" + str(valin) + "\'")
        if lyr.GetFeatureCount() != 0:
            try:
                changeValueField(lyr, fieldout, valout)
                print "Field '{}' populated with {} value".format(
                    fieldout, valout)
            except:
                print "Error while populate field '{}'".format(fieldout)
                sys.exit(-1)
        else:
            print "The value '{}' does not exist for the field '{}'".format(
                valin, fieldin)

    ds.Destroy()
Esempio n. 13
0
def intersection(file1, file2, outfile):

    ds1 = vf.openToRead(file1)
    ds2 = vf.openToRead(file2)

    layer1 = ds1.GetLayer()
    layer2 = ds2.GetLayer()

    if layer1.GetSpatialRef().GetAttrValue(
            "AUTHORITY",
            1) == layer2.GetSpatialRef().GetAttrValue("AUTHORITY", 1):
        srsObj = layer1.GetSpatialRef()
    else:
        print "second shapefile must have the same projection than the first shapefile (EPSG:{} vs. EPSG:{})"\
            .format(layer1.GetSpatialRef().GetAttrValue("AUTHORITY", 1), layer2.GetSpatialRef().GetAttrValue("AUTHORITY", 1))
        sys.exit(-1)

    outDriver = ogr.GetDriverByName("ESRI Shapefile")

    # Find geometry of the intersection
    if defineIntersectGeometry(layer1, layer2) in ['POLYGON', 'MULTIPOLYGON']:
        #if exists, delete it
        if os.path.exists(outfile):
            outDriver.DeleteDataSource(outfile)
        outDataSource = outDriver.CreateDataSource(outfile)

        #Creates the spatial reference of the output layer
        outLayer = outDataSource.CreateLayer("intersect",
                                             srsObj,
                                             geom_type=ogr.wkbPolygon)
    else:
        print "This program only produces POLYGONS intersection"

    # gestion des champs du premier layer
    inLayerDefn = layer1.GetLayerDefn()
    for i in range(0, inLayerDefn.GetFieldCount()):
        fieldDefn = inLayerDefn.GetFieldDefn(i)
        outLayer.CreateField(fieldDefn)

    # gestion des champs du second layer
    inLayerDefn = layer2.GetLayerDefn()
    for i in range(0, inLayerDefn.GetFieldCount()):
        fieldDefn = inLayerDefn.GetFieldDefn(i)
        outLayer.CreateField(fieldDefn)

    # Liste des champs de trois entités
    listfieldin1 = vf.getFields(layer1)
    listfieldin2 = vf.getFields(layer2)
    listfieldout = vf.getFields(outLayer)

    layer1.ResetReading()
    layer2.ResetReading()
    for feature1 in layer1:
        geom1 = feature1.GetGeometryRef()
        for feature2 in layer2:
            geom2 = feature2.GetGeometryRef()
            # select only the intersections
            if geom2.Intersects(geom1):
                intersection = geom2.Intersection(geom1)
                dstfeature = ogr.Feature(outLayer.GetLayerDefn())
                dstfeature.SetGeometry(intersection)
                #gestion des champs
                i = 0
                j = 0
                k = 0
                while i < len(listfieldout):
                    while j < len(listfieldin1):
                        dstfeature.SetField(listfieldout[i],
                                            feature1.GetField(listfieldin1[j]))
                        i += 1
                        j += 1
                    while k < len(listfieldin2):
                        dstfeature.SetField(listfieldout[i],
                                            feature2.GetField(listfieldin2[k]))
                        i += 1
                        k += 1
                outLayer.CreateFeature(dstfeature)
                dstfeature.Destroy()
        layer2.ResetReading()
    outLayer = None
    outDataSource = None