Skip to content

geometry

Handles creation and management of geometries.

This module manages creation of geometries from csv file as well as openstreet data. Contains abstract as well as concrete classes for creating geometries.

Examples:

Get the buildings from chennai and prints one of the building geometry.

>>> from shift.geometry import BuildingsFromPlace
>>> g = BuildingsFromPlace("Chennai, India")
>>> geometries = g.get_geometries()
>>> print(geometries[0])

BuildingGeometry

Bases: Geometry

Implementation for Building geometry.

Source code in shift\geometry.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
class BuildingGeometry(Geometry):
    """Implementation for Building geometry."""

    @property
    def area(self) -> float:
        """float: Area property of a building"""
        return self._area

    @area.setter
    def area(self, area: float) -> None:
        """Setter method for area property of a building"""
        if area < 0:
            raise NegativeAreaError(area)
        self._area = area

    def __repr__(self):
        return (
            f"Building( Latitude = {self.latitude}, "
            + f" Longitude = {self.longitude}, Area = {self.area})"
        )

area() writable property

float: Area property of a building

Source code in shift\geometry.py
111
112
113
114
@property
def area(self) -> float:
    """float: Area property of a building"""
    return self._area

BuildingsFromPlace

Bases: OpenStreetBuildingGeometries

Getting building geometries from a place address within bounding box.

Attributes:

Name Type Description
place str

Any place in string format e.g. chennai, india

max_dist float

Distance in meter from the point to create a bounding box

Source code in shift\geometry.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
class BuildingsFromPlace(OpenStreetBuildingGeometries):
    """Getting building geometries from a place address within bounding box.

    Attributes:
        place (str): Any place in string format e.g. chennai, india
        max_dist (float): Distance in meter from the point
            to create a bounding box
    """

    def __init__(self, place: str, max_dist=1000) -> None:

        """Instantiating the class.

        Args:
            place (str): Any place in string format e.g. chennai, india
            max_dist (float): Distance in meter from the place
                to create a bounding box
        """

        # e.g. Chennai, India
        self.place = place
        self.max_dist = max_dist

    def get_gdf(self) -> pd.DataFrame:
        """Refer to base class for details."""
        return ox.geometries_from_address(
            self.place, {"building": True}, dist=self.max_dist
        )

__init__(place, max_dist=1000)

Instantiating the class.

Parameters:

Name Type Description Default
place str

Any place in string format e.g. chennai, india

required
max_dist float

Distance in meter from the place to create a bounding box

1000
Source code in shift\geometry.py
325
326
327
328
329
330
331
332
333
334
335
336
337
def __init__(self, place: str, max_dist=1000) -> None:

    """Instantiating the class.

    Args:
        place (str): Any place in string format e.g. chennai, india
        max_dist (float): Distance in meter from the place
            to create a bounding box
    """

    # e.g. Chennai, India
    self.place = place
    self.max_dist = max_dist

get_gdf()

Refer to base class for details.

Source code in shift\geometry.py
339
340
341
342
343
def get_gdf(self) -> pd.DataFrame:
    """Refer to base class for details."""
    return ox.geometries_from_address(
        self.place, {"building": True}, dist=self.max_dist
    )

BuildingsFromPoint

Bases: OpenStreetBuildingGeometries

Getting building geometries from single point within bounding box.

Attributes:

Name Type Description
point Sequence

Point in (latitude, longitude) format

max_dist float

Distance in meter from the point to create a bounding box

Source code in shift\geometry.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class BuildingsFromPoint(OpenStreetBuildingGeometries):
    """Getting building geometries from single point within bounding box.

    Attributes:
        point (Sequence): Point in (latitude, longitude) format
        max_dist (float): Distance in meter from the point to
            create a bounding box
    """

    def __init__(self, point: Sequence, max_dist: float = 1000) -> None:

        """Instantiating the class.

        Args:
            point (Sequence): Point in (latitude, longitude) format
            max_dist (float): Distance in meter from the point to
                create a bounding box
        """
        # e.g. (13.242134, 80.275948)
        self.point = point
        self.max_dist = max_dist

    def get_gdf(self) -> pd.DataFrame:
        """Refer to base class for details."""
        return ox.geometries_from_point(
            self.point, {"building": True}, dist=self.max_dist
        )

__init__(point, max_dist=1000)

Instantiating the class.

Parameters:

Name Type Description Default
point Sequence

Point in (latitude, longitude) format

required
max_dist float

Distance in meter from the point to create a bounding box

1000
Source code in shift\geometry.py
296
297
298
299
300
301
302
303
304
305
306
307
def __init__(self, point: Sequence, max_dist: float = 1000) -> None:

    """Instantiating the class.

    Args:
        point (Sequence): Point in (latitude, longitude) format
        max_dist (float): Distance in meter from the point to
            create a bounding box
    """
    # e.g. (13.242134, 80.275948)
    self.point = point
    self.max_dist = max_dist

get_gdf()

Refer to base class for details.

Source code in shift\geometry.py
309
310
311
312
313
def get_gdf(self) -> pd.DataFrame:
    """Refer to base class for details."""
    return ox.geometries_from_point(
        self.point, {"building": True}, dist=self.max_dist
    )

BuildingsFromPolygon

Bases: OpenStreetBuildingGeometries

Getting building geometries from a given polygon.

Attributes:

Name Type Description
polygon

List[list]: Polygon to be used e.g. [[13.242134, 80.275948]]

Source code in shift\geometry.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
class BuildingsFromPolygon(OpenStreetBuildingGeometries):
    """Getting building geometries from a given polygon.

    Attributes:
        polygon: List[list]: Polygon to be used e.g. [[13.242134, 80.275948]]
    """

    def __init__(self, polygon: List[list]) -> None:

        """Instantiating the class.

        Args:
            polygon: List[list]: Polygon to be used
                e.g. [[13.242134, 80.275948]]
        """
        self.polygon = shapely.geometry.Polygon(polygon)

    def get_gdf(self) -> pd.DataFrame:
        """Refer to base class for details."""
        return ox.geometries_from_polygon(self.polygon, {"building": True})

__init__(polygon)

Instantiating the class.

Parameters:

Name Type Description Default
polygon List[list]

List[list]: Polygon to be used e.g. [[13.242134, 80.275948]]

required
Source code in shift\geometry.py
353
354
355
356
357
358
359
360
361
def __init__(self, polygon: List[list]) -> None:

    """Instantiating the class.

    Args:
        polygon: List[list]: Polygon to be used
            e.g. [[13.242134, 80.275948]]
    """
    self.polygon = shapely.geometry.Polygon(polygon)

get_gdf()

Refer to base class for details.

Source code in shift\geometry.py
363
364
365
def get_gdf(self) -> pd.DataFrame:
    """Refer to base class for details."""
    return ox.geometries_from_polygon(self.polygon, {"building": True})

GeometriesFromCSV

Bases: ABC

Interface for getting geometries from CSV file

Attributes:

Name Type Description
csv_file str

Path to csv file

df pd.DataFrame

dataframe holding the content of csv file

Source code in shift\geometry.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class GeometriesFromCSV(ABC):
    """Interface for getting geometries from CSV file

    Attributes:
        csv_file (str): Path to csv file
        df (pd.DataFrame): dataframe holding the content of csv file

    """

    def __init__(self, csv_file: str) -> None:
        """Method for instantiationg the class.

        Args:
            csv_file (str): Path to valid csv file

        Raises:
            FileNotFoundError: If csv file is not found
            NotCompatibleFileError: If the file pssed is not csv
        """

        self.csv_file = csv_file
        if not os.path.exists(csv_file):
            raise FileNotFoundError(csv_file)
        else:
            if not csv_file.endswith(".csv"):
                raise NotCompatibleFileError(csv_file, ".csv")

        self.df = pd.read_csv(csv_file)
        self.validate()

    @abstractmethod
    def validate(self) -> bool:
        """Child class must implement validate method."""
        pass

    @abstractmethod
    def get_geometries(self) -> List[Geometry]:
        """Child class must implement method to return list of geometries."""
        pass

__init__(csv_file)

Method for instantiationg the class.

Parameters:

Name Type Description Default
csv_file str

Path to valid csv file

required

Raises:

Type Description
FileNotFoundError

If csv file is not found

NotCompatibleFileError

If the file pssed is not csv

Source code in shift\geometry.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def __init__(self, csv_file: str) -> None:
    """Method for instantiationg the class.

    Args:
        csv_file (str): Path to valid csv file

    Raises:
        FileNotFoundError: If csv file is not found
        NotCompatibleFileError: If the file pssed is not csv
    """

    self.csv_file = csv_file
    if not os.path.exists(csv_file):
        raise FileNotFoundError(csv_file)
    else:
        if not csv_file.endswith(".csv"):
            raise NotCompatibleFileError(csv_file, ".csv")

    self.df = pd.read_csv(csv_file)
    self.validate()

get_geometries() abstractmethod

Child class must implement method to return list of geometries.

Source code in shift\geometry.py
185
186
187
188
@abstractmethod
def get_geometries(self) -> List[Geometry]:
    """Child class must implement method to return list of geometries."""
    pass

validate() abstractmethod

Child class must implement validate method.

Source code in shift\geometry.py
180
181
182
183
@abstractmethod
def validate(self) -> bool:
    """Child class must implement validate method."""
    pass

Geometry

Bases: ABC

Interface for Geometry object.

Source code in shift\geometry.py
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
class Geometry(ABC):
    """Interface for Geometry object."""

    @property
    def latitude(self) -> float:
        """float: Latitude property of a building"""
        return self._latitude

    @latitude.setter
    def latitude(self, latitude: float) -> None:
        """Setter method for latitude property of a building"""
        if latitude < MIN_LATITUDE or latitude > MAX_LATITUDE:
            raise LatitudeNotInRangeError(latitude)
        self._latitude = latitude

    @property
    def longitude(self) -> float:
        """float: Longitude property of a building"""
        return self._longitude

    @longitude.setter
    def longitude(self, longitude: float) -> None:
        """Setter method for longitude property of a building"""
        if longitude < MIN_LONGITUDE or longitude > MAX_LONGITUDE:
            raise LongitudeNotInRangeError(longitude)
        self._longitude = longitude

    def __eq__(self, other):
        return (
            self.latitude == other.latitude
            and self.longitude == other.longitude
        )

    def __hash__(self):
        return hash((self.latitude, self.longitude))

latitude() writable property

float: Latitude property of a building

Source code in shift\geometry.py
74
75
76
77
@property
def latitude(self) -> float:
    """float: Latitude property of a building"""
    return self._latitude

longitude() writable property

float: Longitude property of a building

Source code in shift\geometry.py
86
87
88
89
@property
def longitude(self) -> float:
    """float: Longitude property of a building"""
    return self._longitude

OpenStreetBuildingGeometries

Bases: OpenStreetGeometries

Concrete implementations of open street building geometries

Source code in shift\geometry.py
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
class OpenStreetBuildingGeometries(OpenStreetGeometries):
    """Concrete implementations of open street building geometries"""

    def get_geometries(self) -> List[Geometry]:
        """Refer to base class for details."""
        # Create container for holding list of geometries
        concrete_geometries = []

        # Get geo dataframe object implemented by
        # child OpenStreet Geometries subclass
        gdf_data = self.get_gdf().to_dict(orient="records")

        # Loop through all the rows in geo dataframe to
        # create list of concrete geometries
        for row in gdf_data:

            # Looping through only either point or polygon geometries
            if row["geometry"].geom_type in ["Point", "Polygon"]:

                if row["geometry"].geom_type == "Point":

                    centre = list(row["geometry"].coords)[0]
                    area = 0

                else:
                    centre = list(row["geometry"].centroid.coords)[0]
                    # By default shapely gives area in square degrees
                    # By assuming the earth to be a perfect square of
                    # 6370 meter square area can be computed as below
                    # but it's not accurate however does the job for now
                    area = row["geometry"].area * 6370**2

                # Create individual geometry
                geometry = BuildingGeometry()
                geometry.latitude = centre[1]
                geometry.longitude = centre[0]
                geometry.area = round(area, 2)

                if geometry not in concrete_geometries:
                    concrete_geometries.append(geometry)

        return concrete_geometries

get_geometries()

Refer to base class for details.

Source code in shift\geometry.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def get_geometries(self) -> List[Geometry]:
    """Refer to base class for details."""
    # Create container for holding list of geometries
    concrete_geometries = []

    # Get geo dataframe object implemented by
    # child OpenStreet Geometries subclass
    gdf_data = self.get_gdf().to_dict(orient="records")

    # Loop through all the rows in geo dataframe to
    # create list of concrete geometries
    for row in gdf_data:

        # Looping through only either point or polygon geometries
        if row["geometry"].geom_type in ["Point", "Polygon"]:

            if row["geometry"].geom_type == "Point":

                centre = list(row["geometry"].coords)[0]
                area = 0

            else:
                centre = list(row["geometry"].centroid.coords)[0]
                # By default shapely gives area in square degrees
                # By assuming the earth to be a perfect square of
                # 6370 meter square area can be computed as below
                # but it's not accurate however does the job for now
                area = row["geometry"].area * 6370**2

            # Create individual geometry
            geometry = BuildingGeometry()
            geometry.latitude = centre[1]
            geometry.longitude = centre[0]
            geometry.area = round(area, 2)

            if geometry not in concrete_geometries:
                concrete_geometries.append(geometry)

    return concrete_geometries

OpenStreetGeometries

Bases: ABC

Interface for getting geometries from OpenStreet data.

Source code in shift\geometry.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
class OpenStreetGeometries(ABC):
    """Interface for getting geometries from OpenStreet data."""

    @abstractmethod
    def get_gdf(self) -> pd.DataFrame:
        """Method to return the geo dataframe containing all the buildings.

        Returns:
            pd.DataFrame: Geo dataframe containing all the buildings.
        """
        pass

    @abstractmethod
    def get_geometries(self) -> List[Geometry]:
        """Method to return all the geometry objects.

        Returns:
            List[Geometry]: list of all the building geometry objects.
        """
        pass

get_gdf() abstractmethod

Method to return the geo dataframe containing all the buildings.

Returns:

Type Description
pd.DataFrame

pd.DataFrame: Geo dataframe containing all the buildings.

Source code in shift\geometry.py
224
225
226
227
228
229
230
231
@abstractmethod
def get_gdf(self) -> pd.DataFrame:
    """Method to return the geo dataframe containing all the buildings.

    Returns:
        pd.DataFrame: Geo dataframe containing all the buildings.
    """
    pass

get_geometries() abstractmethod

Method to return all the geometry objects.

Returns:

Type Description
List[Geometry]

List[Geometry]: list of all the building geometry objects.

Source code in shift\geometry.py
233
234
235
236
237
238
239
240
@abstractmethod
def get_geometries(self) -> List[Geometry]:
    """Method to return all the geometry objects.

    Returns:
        List[Geometry]: list of all the building geometry objects.
    """
    pass

SimpleLoadGeometriesFromCSV

Bases: GeometriesFromCSV

Concrete implementations for getting simple load geometries from CSV file.

Refer to the base class for more deatils on how to construct the object.

Source code in shift\geometry.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
class SimpleLoadGeometriesFromCSV(GeometriesFromCSV):
    """Concrete implementations for getting simple load
    geometries from CSV file.

    Refer to the base class for more deatils on how to construct the
    object.
    """

    def get_geometries(self):
        """Method to get all the gepmetries from csv."""

        # Let's loop through all records and create all the geometries
        concrete_geometries = []

        for record in self.df.to_dict(orient="records"):

            geometry = SimpleLoadGeometry()
            geometry.latitude = record["latitude"]
            geometry.longitude = record["longitude"]
            geometry.kw = record["kw"]

            concrete_geometries.append(geometry)

        return concrete_geometries

    def validate(self):
        """Method to validate the content of csv file."""
        return df_validator(SIMPLELOADGEOMETRY_SCHEMA, self.df)

get_geometries()

Method to get all the gepmetries from csv.

Source code in shift\geometry.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def get_geometries(self):
    """Method to get all the gepmetries from csv."""

    # Let's loop through all records and create all the geometries
    concrete_geometries = []

    for record in self.df.to_dict(orient="records"):

        geometry = SimpleLoadGeometry()
        geometry.latitude = record["latitude"]
        geometry.longitude = record["longitude"]
        geometry.kw = record["kw"]

        concrete_geometries.append(geometry)

    return concrete_geometries

validate()

Method to validate the content of csv file.

Source code in shift\geometry.py
216
217
218
def validate(self):
    """Method to validate the content of csv file."""
    return df_validator(SIMPLELOADGEOMETRY_SCHEMA, self.df)

SimpleLoadGeometry

Bases: Geometry

Implementation for simple load point geometry

Source code in shift\geometry.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class SimpleLoadGeometry(Geometry):
    """Implementation for simple load point geometry"""

    @property
    def kw(self) -> float:
        """float: Area property of a building"""
        return self._kw

    @kw.setter
    def kw(self, kw: float) -> None:
        """Setter method for area property of a building"""
        self._kw = kw

    def __repr__(self):
        return (
            f"Building( Latitude = {self.latitude}, "
            + f"Longitude = {self.longitude}, kW = {self.kw})"
        )

kw() writable property

float: Area property of a building

Source code in shift\geometry.py
133
134
135
136
@property
def kw(self) -> float:
    """float: Area property of a building"""
    return self._kw