gis.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. '''
  2. @author: olivier.massot, sept. 2018
  3. '''
  4. import shapefile
  5. POINT = 1
  6. POLYLINE = 3
  7. POLYGON = 5
  8. SHAPE_NAMES = {0: "(AUCUN)",
  9. 1: "POINT",
  10. 3:"POLYLIGNE",
  11. 5:"POLYGONE",
  12. 8: "MULTI-POINT",
  13. 11: "POINT-Z",
  14. 13: "POLYLIGNE-Z",
  15. 15: "POLYGONE-Z",
  16. 18: "MULTIPOINT-Z",
  17. 21: "POINT-M",
  18. 23: "POLYLIGNE-M",
  19. 25: "POLYGONE-M",
  20. 28: "MULTIPOINT-M",
  21. 31: "MULTI-PATCH",
  22. }
  23. def same_geom(geom1, geom2, buffer = 0):
  24. """ retourne vrai si les deux géométries sont identiques """
  25. if geom1.shapeType == geom2.shapeType:
  26. if geom1.shapeType in (3,5,8,13,15,18,23,25,28,31):
  27. return geom1.bbox == geom2.bbox
  28. else:
  29. return geom1 == geom2
  30. return False
  31. class ShapeError(IOError):
  32. pass
  33. class SridError(IOError):
  34. pass
  35. class ShapeFile():
  36. def __init__(self, path_, srid=None):
  37. self.path_ = path_
  38. self.srid = srid
  39. def __enter__(self):
  40. if not self.path_.isfile():
  41. raise FileNotFoundError("Fichier introuvable")
  42. try:
  43. self.sf = shapefile.Reader(self.path_)
  44. except shapefile.ShapefileException:
  45. raise ShapeError("Fichier Shape illisible")
  46. if not self.sf.shapeType in (POINT, POLYLINE, POLYGON):
  47. raise ShapeError("Type de géométrie non reconnue")
  48. # if self.srid is not None:
  49. # if not self.sf.srid == self.srid:
  50. # raise SridError("Le SRID du fichier doit être '{}'".format(self.srid))
  51. return self
  52. def shape(self):
  53. return self.sf.shapeType
  54. def fields(self):
  55. return [f[0] for f in self.sf.fields if f[0] != 'DeletionFlag']
  56. def records(self):
  57. for record in self.sf.shapeRecords():
  58. yield record
  59. def __exit__(self, exc_type, exc_val, exc_tb):
  60. del self.sf