Skip to content

Instantly share code, notes, and snippets.

@jontwo
Last active June 25, 2022 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jontwo/01d8cbf1e047e36d2fb2f7786ad60e73 to your computer and use it in GitHub Desktop.
Save jontwo/01d8cbf1e047e36d2fb2f7786ad60e73 to your computer and use it in GitHub Desktop.
Repro case for GDAL GetFID/GetFeature issue https://github.com/OSGeo/gdal/issues/5967
"""Repro case for GetFID/GetFeature bug."""
from osgeo import ogr
# some features in increasing size order
WKT1 = 'POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))'
WKT2 = 'POLYGON ((2 0, 2 2, 4 2, 4 0, 2 0))'
WKT3 = 'POLYGON ((5 0, 5 5, 10 5, 10 0, 5 0))'
WKT4 = 'POLYGON ((12 0, 12 8, 20 8, 20 0, 12 0))'
def add_new_feature_to_layer(lyr, wkt):
feat = ogr.Feature(lyr.GetLayerDefn())
feat.SetGeometryDirectly(ogr.Geometry(wkt=wkt))
lyr.CreateFeature(feat)
def main():
drv = ogr.GetDriverByName('Memory')
ds = drv.CreateDataSource('dname')
lyr = ds.CreateLayer('lname', geom_type=ogr.wkbPolygon)
add_new_feature_to_layer(lyr, WKT1)
add_new_feature_to_layer(lyr, WKT4)
add_new_feature_to_layer(lyr, WKT2)
add_new_feature_to_layer(lyr, WKT3)
lyr.SyncToDisk()
areas = [(feat.GetFID(), feat.geometry().Area()) for feat in lyr]
print(f"Areas before: {areas}")
sorted_lyr = ds.ExecuteSQL(f"SELECT * FROM lname ORDER BY OGR_GEOM_AREA ASC")
areas = [(feat.GetFID(), feat.geometry().Area()) for feat in sorted_lyr]
print(f"Areas after: {areas}")
for fid, area in areas:
feat = sorted_lyr.GetFeature(fid)
print(f"Requested FID {fid} (area {area}) got {feat.GetFID()} (area {feat.geometry().Area()})")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment