latentspace.

Shapely geometry inheritance


  • Custom geometry class with Shapely geometry instance
    • Defining custom class for Polygon
    • shapely.geometry.Polygon has no attributes or functions to get these directly:
      • segments
      • vertices
      • coords
      • ...

  • Inheritance
  • 
        import numpy as np
        from shapely import geometry
        from typing import List, Union
    
    
        class Polygon(geometry.Polygon):
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
    
            def coords(self, to_list: bool = False) -> Union[List[tuple], np.ndarray]:
    
                coords = self.exterior.coords
                if to_list:
                    return list(coords)
    
                return np.array(coords)
    
            def vertices(self) -> List[geometry.Point]:
    
                coords = self.coords(to_list=True)
    
                return [geometry.Point(c) for c in coords]
    
            def segments(self) -> List[geometry.LineString]:
    
                coords = self.coords(to_list=True)
    
                if len(coords) == 0:
                    return []
    
                segments = []
                start_pt = coords[0]
    
                for i in range(len(coords) - 1):
                    end_pt = coords[i + 1]
                    segments.append(geometry.LineString([start_pt, end_pt]))
                    start_pt = end_pt
    
                return segments
                
    
        if __name__ == "__main__":
    
            square = np.array(
                [
                    [0, 0],
                    [0, 1],
                    [1, 1],
                    [1, 0],
                ]
            )
    
            polygon_1 = Polygon(square)
            polygon_2 = Polygon(square + 0.5)
    

  • Visualize properties
    • polygon_1
    • polygon_2
    • polygon_2.vertices()
    • polygon_2.segments()

    • Shapely geometry inheritance
    • polygon_1.intersection(polygon_2).vertices()
    • polygon_1.intersection(polygon_2).segments()
    • 
          Traceback (most recent call last):
          AttributeError: 'Polygon' object has no attribute 'vertices'
      
          Traceback (most recent call last):
          AttributeError: 'Polygon' object has no attribute 'segments'
      

  • Trick for fixing AttributeError
    • Set methods of custom Polygon to the original class
    • 
          for name, method in vars(Polygon).items():
              if callable(method) and not name.startswith('__'):
                  setattr(geometry.Polygon, name, method)
      

      Shapely geometry inheritance