Skip to content

polygon: Polygons drawn on results (GeoJSON files) and point in polygon tests

moraine.api.polygon (source). Every name is also moraine.<name> (import moraine as mr).

read_polygons

read_polygons(path: str) -> tuple

Read the polygons of a GeoJSON file written by write_polygons or another program.

Parameters:

Name Type Description Default
path str

GeoJSON file with Polygon or MultiPolygon features (holes are ignored)

required

Returns:

Type Description
tuple

list of polygons, each an (n_vertices, 2) float64 array of (x, y) with the closing vertex removed, and the coordinates, 'lonlat' or 'radar_grid'

write_polygons

write_polygons(path: str, polygons: list, coordinates: str = 'lonlat')

Write polygons to a GeoJSON file (FeatureCollection of Polygon features).

Parameters:

Name Type Description Default
path str

output GeoJSON file

required
polygons list

polygons, each a list of (x, y) vertices, at least 3; the ring is closed in the file

required
coordinates str

'lonlat' (x longitude, y latitude in degrees, standard GeoJSON) or 'radar_grid' (x range, y azimuth pixel coordinates, stored as moraine_coordinates in the file)

'lonlat'

polygons_contain

polygons_contain(polygons: list, x: ndarray, y: ndarray) -> ndarray

Whether points are inside any of the polygons.

Parameters:

Name Type Description Default
polygons list

polygons, each an (n_vertices, 2) array of (x, y) vertices, in the coordinates of x, y

required
x ndarray

x coordinates of the points, any shape

required
y ndarray

y coordinates of the points, same shape as x

required

Returns:

Type Description
ndarray

bool, same shape as x: True inside at least one polygon; points exactly on an edge may be on either side; nan coordinates are outside

Examples

Run when this manual is built; the output follows each snippet.

import os
import tempfile
import numpy as np
import moraine as mr

square = [(14.10, 40.80), (14.15, 40.80), (14.15, 40.85), (14.10, 40.85)]      # (longitude, latitude) vertices
path = os.path.join(tempfile.mkdtemp(), 'areas.geojson')
mr.write_polygons(path, [square])                                               # a GeoJSON FeatureCollection
polygons, coordinates = mr.read_polygons(path)
print(coordinates, polygons[0].shape)

lon = np.array([14.12, 14.20, np.nan])
lat = np.array([40.82, 40.82, 40.82])
print(mr.polygons_contain(polygons, lon, lat))                                 # inside, outside, nan
lonlat (4, 2)
[ True False False]

Polygons drawn in the viewer are saved in the same format; polygon-mask makes masks of rasters or point clouds from them (moraine_coordinates tells longitude / latitude from radar grid coordinates).