brails.utils.geo_tools module

This module defines a class for geospatial analysis and operations.

GeoTools()

A collection of static methods for geospatial analysis and operations.

class brails.utils.geo_tools.GeoTools

Bases: object

A collection of static methods for geospatial analysis and operations.

The GeoTools class provides various utility functions to perform common geospatial tasks, including distance calculations, polygon meshing, plotting, and GeoJSON file handling. The methods leverage Shapely geometries to operate on points and polygons, making it suitable for geographical data manipulation and visualization.

To import the GeoTools class, use:

from brails.utils import GeoTools
static bbox2poly(query_area, output_file='')

Get the boundary polygon for a region based on its coordinates.

This method parses the provided bounding polygon coordinates into a polygon object. The polygon must be defined by at least two pairs of longitude/latitude values (i.e., at least 4 elements) and must have an even number of elements. If a file name is provided in the outfile argument, the resulting polygon is saved to a GeoJSON file.

Parameters:
  • query_area (tuple) – A tuple containing longitude/latitude pairs that define a bounding box. The tuple should contain at least two pairs of coordinates (i.e., 4 values), and the number of elements must be an even number.

  • output_file (str, optional) – If a file name is provided, the resulting polygon will be written to the specified file in GeoJSON format.

Raises:
  • TypeError – If query_area is not a tuple.

  • ValueError – If the tuple has an odd number of elements or fewer than two pairs.

Returns:

  • The bounding polygon as a Shapely Polygon.

  • A human-readable string representation of the bounding polygon.

Return type:

Tuple[Polygon, str]

Example

Simple bounding box (two coordinate pairs):

>>> from brails.utils import GeoTools
>>> coords = (-122.3, 37.85, -122.25, 37.9)
>>> bpoly, description = GeoTools.bbox2poly(coords)
>>> print(bpoly)
POLYGON ((-122.3 37.85, -122.3 37.9, -122.25 37.9, -122.25 37.85,
          -122.3 37.85))
>>> print(description)
the bounding box: (-122.3, 37.85, -122.25, 37.9)

A triangular polygon:

>>> long_coords = (
...     -122.3, 37.85, -122.28, 37.86, -122.26, 37.87, -122.25,
...     37.9
... )
>>> bpoly_long, desc_long = GeoTools.bbox2poly(long_coords)
>>> print(bpoly_long)
POLYGON ((-122.3 37.85, -122.28 37.86, -122.26 37.87, -122.25 37.9,
-122.3 37.85))
>>> print(desc_long)
the bounding polygon: [(-122.3, 37.85), (-122.28, 37.86),
(-122.26, 37.87), (-122.25, 37.9)]
static geometry_to_list_of_lists(geom)

Convert a Shapely geometry into a list of coordinate lists.

Parameters:

geom (BaseGeometry) – A Shapely geometry (such as Point, Polygon)

Returns:

A list of [lon, lat] values or nested list objects for complex geometries.

Return type:

List[List[float]] or List[List[List[float]]]

Examples

>>> from shapely.geometry import Point, Polygon
>>> GeoTools.geometry_to_list_of_lists(Point(1.0, 2.0))
[[1.0, 2.0]]
>>> square = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)])
>>> GeoTools.geometry_to_list_of_lists(square)
[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]
static haversine_dist(p1, p2)

Calculate the Haversine distance between two points.

This function computes the shortest distance over the earth’s surface between two points specified by their latitude and longitude.

Parameters:
  • p1 (tuple) – The first point as a list containing two floating-point values, where the first element is the latitude and the second is the longitude of the point in degrees.

  • p2 (tuple) – The second point as a list containing two floating-point values, where the first element is the latitude and the second is the longitude of the point in degrees.

Returns:

The Haversine distance between the two points in feet.

Return type:

float

Example

>>> p1 = (37.7749, -122.4194)  # San Francisco, CA
>>> p2 = (34.0522, -118.2437)  # Los Angeles, CA
>>> distance = GeoTools.haversine_dist(p1, p2)
>>> round(distance / 5280)  # convert feet to miles
347
static match_points_to_polygons(points, polygons)

Match points to polygons and return the correspondence data.

This function finds Shapely points that fall within given polygons. If multiple points exist within a polygon, it selects the point closest to the polygon’s centroid.

Parameters:
  • points (list[Point]) – A list of Shapely points

  • polygons (list[Polygon]) – A list of Shapely Polygons defined in EPSG 4326 (longitude, latitude).

Returns:

  • A list of matched Shapely points.

  • A dictionary mapping each polygon (represented as a string) to the corresponding matched point.

  • A list of the indices of polygons matched to points, with each index listed in the same order as the list of points.

Return type:

tuple[list, dict, list]

static mesh_polygon(polygon, rows, cols)

Split a Spolygon into a grid of individual rectangular polygons.

This function divides the area of the input polygon into a specified number of rows and columns, creating a mesh of rectangular cells. Each cell is checked for intersection with the input polygon, and only the intersecting parts are returned.

Parameters:
  • polygon (Polygon) – A Shapely Polygon to be meshed.

  • rows (int) – The number of rows to divide the polygon into.

  • cols (int) – The number of columns to divide the polygon into.

Returns:

A list of Shapely Polygons representing the individual rectangular cells that mesh the polygon input.

Return type:

list[Polygon]

Example

>>> from shapely.geometry import Polygon
>>> poly = Polygon([(0, 0), (4, 0), (4, 3), (0, 3)])
>>> cells = GeoTools.mesh_polygon(poly, rows=2, cols=2)
>>> len(cells)
4
>>> # Access coordinates of first cell
>>> cells[0].bounds
(0.0, 0.0, 2.0, 1.5)
static plot_polygon_cells(bpoly, rectangles, output_file='')

Plot a polygon and its rectangular mesh, optionally saving the plot.

This function visualizes a Shapely Polygon or MultiPolygon along with its rectangular mesh of cells. Each cell is plotted in blue, and the base polygon is outlined in black.

Parameters:
  • bpoly (Polygon or MultiPolygon) – A Shapely Polygon or MultiPolygon to plot.

  • rectangles (list[Polygon]) – A list of Shapely Polygon objects representing the rectangular cells that mesh input polygon.

  • output_file (str, optional) – Filename to save the plot as a PNG image. If empty string, the plot is not saved.

Returns:

None

Raises:

ValueError – If output_file is provided and an invalid filename is given.

Example

>>> from shapely.geometry import Polygon
>>> poly = Polygon([(0, 0), (4, 0), (4, 3), (0, 3)])
>>> cells = GeoTools.mesh_polygon(poly, rows=2, cols=2)
>>> GeoTools.plot_polygon_cells(poly, cells)
>>> GeoTools.plot_polygon_cells(
...     poly,
...     cells,
...     output_file='mesh_plot.png'
... )
static write_polygon_to_geojson(poly, output_file)

Write a Shapely Polygon or MultiPolygon to a GeoJSON file.

Parameters:
  • poly (Polygon or MultiPolygon) – A Shapely Polygon or MultiPolygon to be written.

  • output_file (str) – The output filename for the GeoJSON file.

Note

  • This method does not perform validation on the geometry.

  • The file extension will be replaced with ‘.geojson’ if not present.

Returns:

None

Examples

>>> from shapely.geometry import Polygon, MultiPolygon
>>> poly = Polygon([(0, 0), (4, 0), (4, 3), (0, 3)])
>>> GeoTools.write_polygon_to_geojson(poly, 'my_polygon.geojson')
>>> poly1 = Polygon([(0, 0), (2, 0), (2, 2), (0, 2)])
>>> poly2 = Polygon([(3, 0), (5, 0), (5, 2), (3, 2)])
>>> mpoly = MultiPolygon([poly1, poly2])
>>> GeoTools.write_polygon_to_geojson(
...     mpoly,
...     'my_multipolygon.geojson'
... )