vibespatial.api.tools

Submodules

Functions

clip(gdf, mask[, keep_geom_type, sort])

Clip points, lines, or polygon geometries to the mask extent.

geocode(strings[, provider])

Geocode a set of strings and get a GeoDataFrame of the resulting points.

reverse_geocode(points[, provider])

Reverse geocode a set of points and get a GeoDataFrame of the resulting

overlay(df1, df2[, how, keep_geom_type, make_valid])

Perform spatial overlay between two GeoDataFrames.

sjoin(left_df, right_df[, how, predicate, lsuffix, ...])

Spatial join of two GeoDataFrames.

sjoin_nearest(→ vibespatial.api.GeoDataFrame)

Spatial join of two GeoDataFrames based on the distance between their geometries.

collect(x[, multi])

Collect single part geometries into their Multi* counterpart.

Package Contents

vibespatial.api.tools.clip(gdf, mask, keep_geom_type=False, sort=False)

Clip points, lines, or polygon geometries to the mask extent.

Both layers must be in the same Coordinate Reference System (CRS). The gdf will be clipped to the full extent of the clip object.

If there are multiple polygons in mask, data from gdf will be clipped to the total boundary of all polygons in mask.

If the mask is list-like with four elements (minx, miny, maxx, maxy), a faster rectangle clipping algorithm will be used. Note that this can lead to slightly different results in edge cases, e.g. if a line would be reduced to a point, this point might not be returned. The geometry is clipped in a fast but possibly dirty way. The output is not guaranteed to be valid. No exceptions will be raised for topological errors.

Parameters

gdfGeoDataFrame or GeoSeries

Vector layer (point, line, polygon) to be clipped to mask.

maskGeoDataFrame, GeoSeries, (Multi)Polygon, list-like

Polygon vector layer used to clip gdf. The mask’s geometry is dissolved into one geometric feature and intersected with gdf. If the mask is list-like with four elements (minx, miny, maxx, maxy), clip will use a faster rectangle clipping (clip_by_rect()), possibly leading to slightly different results.

keep_geom_typeboolean, default False

If True, return only geometries of original type in case of intersection resulting in multiple geometry types or GeometryCollections. If False, return all resulting geometries (potentially mixed-types).

sortboolean, default False

If True, the results will be sorted in ascending order using the geometries’ indexes as the primary key.

Returns

GeoDataFrame or GeoSeries

Vector data (points, lines, polygons) from gdf clipped to polygon boundary from mask.

See Also

GeoDataFrame.clip : equivalent GeoDataFrame method GeoSeries.clip : equivalent GeoSeries method

Examples

Clip points (grocery stores) with polygons (the Near West Side community):

>>> import geodatasets
>>> chicago = geopandas.read_file(
...     geodatasets.get_path("geoda.chicago_health")
... )
>>> near_west_side = chicago[chicago["community"] == "NEAR WEST SIDE"]
>>> groceries = geopandas.read_file(
...     geodatasets.get_path("geoda.groceries")
... ).to_crs(chicago.crs)
>>> groceries.shape
(148, 8)
>>> nws_groceries = geopandas.clip(groceries, near_west_side)
>>> nws_groceries.shape
(7, 8)
vibespatial.api.tools.geocode(strings, provider=None, **kwargs)

Geocode a set of strings and get a GeoDataFrame of the resulting points.

Parameters

strings : list or Series of addresses to geocode provider : str or geopy.geocoder

Specifies geocoding service to use. If none is provided, will use ‘photon’ (see the Photon’s terms of service at: https://photon.komoot.io).

Either the string name used by geopy (as specified in geopy.geocoders.SERVICE_TO_GEOCODER) or a geopy Geocoder instance (e.g., geopy.geocoders.Photon) may be used.

Some providers require additional arguments such as access keys See each geocoder’s specific parameters in geopy.geocoders

Notes

Ensure proper use of the results by consulting the Terms of Service for your provider.

Geocoding requires geopy. Install it using ‘pip install geopy’. See also https://github.com/geopy/geopy

Examples

>>> df = geopandas.tools.geocode(
...         ["boston, ma", "1600 pennsylvania ave. washington, dc"]
...     )
>>> df
                    geometry                                            address
0  POINT (-71.05863 42.35899)                          Boston, MA, United States
1  POINT (-77.03651 38.89766)  1600 Pennsylvania Ave NW, Washington, DC 20006...
vibespatial.api.tools.reverse_geocode(points, provider=None, **kwargs)

Reverse geocode a set of points and get a GeoDataFrame of the resulting addresses.

The points

Parameters

pointslist or Series of Shapely Point objects.

x coordinate is longitude y coordinate is latitude

providerstr or geopy.geocoder (opt)

Specifies geocoding service to use. If none is provided, will use ‘photon’ (see the Photon’s terms of service at: https://photon.komoot.io).

Either the string name used by geopy (as specified in geopy.geocoders.SERVICE_TO_GEOCODER) or a geopy Geocoder instance (e.g., geopy.geocoders.Photon) may be used.

Some providers require additional arguments such as access keys See each geocoder’s specific parameters in geopy.geocoders

Notes

Ensure proper use of the results by consulting the Terms of Service for your provider.

Reverse geocoding requires geopy. Install it using ‘pip install geopy’. See also https://github.com/geopy/geopy

Examples

>>> from shapely.geometry import Point
>>> df = geopandas.tools.reverse_geocode(
...     [Point(-71.0594869, 42.3584697), Point(-77.0365305, 38.8977332)]
... )
>>> df
                     geometry                                            address
0  POINT (-71.05941 42.35837)       29 Court Sq, Boston, MA 02108, United States
1  POINT (-77.03641 38.89766)  1600 Pennsylvania Ave NW, Washington, DC 20006...
vibespatial.api.tools.overlay(df1, df2, how='intersection', keep_geom_type=None, make_valid=True)

Perform spatial overlay between two GeoDataFrames.

Currently only supports data GeoDataFrames with uniform geometry types, i.e. containing only (Multi)Polygons, or only (Multi)Points, or a combination of (Multi)LineString and LinearRing shapes. Implements several methods that are all effectively subsets of the union.

See the User Guide page ../../user_guide/set_operations for details.

Parameters

df1 : GeoDataFrame df2 : GeoDataFrame how : string

Method of spatial overlay: ‘intersection’, ‘union’, ‘identity’, ‘symmetric_difference’ or ‘difference’.

keep_geom_typebool

If True, return only geometries of the same geometry type as df1 has, if False, return all resulting geometries. Default is None, which will set keep_geom_type to True but warn upon dropping geometries.

make_validbool, default True

If True, any invalid input geometries are corrected with a call to make_valid(), if False, a ValueError is raised if any input geometries are invalid.

Returns

dfGeoDataFrame

GeoDataFrame with new set of polygons and attributes resulting from the overlay

Examples

>>> from shapely.geometry import Polygon
>>> polys1 = geopandas.GeoSeries([Polygon([(0,0), (2,0), (2,2), (0,2)]),
...                               Polygon([(2,2), (4,2), (4,4), (2,4)])])
>>> polys2 = geopandas.GeoSeries([Polygon([(1,1), (3,1), (3,3), (1,3)]),
...                               Polygon([(3,3), (5,3), (5,5), (3,5)])])
>>> df1 = geopandas.GeoDataFrame({'geometry': polys1, 'df1_data':[1,2]})
>>> df2 = geopandas.GeoDataFrame({'geometry': polys2, 'df2_data':[1,2]})
>>> geopandas.overlay(df1, df2, how='union')
    df1_data  df2_data                                           geometry
0       1.0       1.0                POLYGON ((2 2, 2 1, 1 1, 1 2, 2 2))
1       2.0       1.0                POLYGON ((2 2, 2 3, 3 3, 3 2, 2 2))
2       2.0       2.0                POLYGON ((4 4, 4 3, 3 3, 3 4, 4 4))
3       1.0       NaN      POLYGON ((2 0, 0 0, 0 2, 1 2, 1 1, 2 1, 2 0))
4       2.0       NaN  MULTIPOLYGON (((3 4, 3 3, 2 3, 2 4, 3 4)), ((4...
5       NaN       1.0  MULTIPOLYGON (((2 3, 2 2, 1 2, 1 3, 2 3)), ((3...
6       NaN       2.0      POLYGON ((3 5, 5 5, 5 3, 4 3, 4 4, 3 4, 3 5))
>>> geopandas.overlay(df1, df2, how='intersection')
   df1_data  df2_data                             geometry
0         1         1  POLYGON ((2 2, 2 1, 1 1, 1 2, 2 2))
1         2         1  POLYGON ((2 2, 2 3, 3 3, 3 2, 2 2))
2         2         2  POLYGON ((4 4, 4 3, 3 3, 3 4, 4 4))
>>> geopandas.overlay(df1, df2, how='symmetric_difference')
    df1_data  df2_data                                           geometry
0       1.0       NaN      POLYGON ((2 0, 0 0, 0 2, 1 2, 1 1, 2 1, 2 0))
1       2.0       NaN  MULTIPOLYGON (((3 4, 3 3, 2 3, 2 4, 3 4)), ((4...
2       NaN       1.0  MULTIPOLYGON (((2 3, 2 2, 1 2, 1 3, 2 3)), ((3...
3       NaN       2.0      POLYGON ((3 5, 5 5, 5 3, 4 3, 4 4, 3 4, 3 5))
>>> geopandas.overlay(df1, df2, how='difference')
                                            geometry  df1_data
0      POLYGON ((2 0, 0 0, 0 2, 1 2, 1 1, 2 1, 2 0))         1
1  MULTIPOLYGON (((3 4, 3 3, 2 3, 2 4, 3 4)), ((4...         2
>>> geopandas.overlay(df1, df2, how='identity')
   df1_data  df2_data                                           geometry
0         1       1.0                POLYGON ((2 2, 2 1, 1 1, 1 2, 2 2))
1         2       1.0                POLYGON ((2 2, 2 3, 3 3, 3 2, 2 2))
2         2       2.0                POLYGON ((4 4, 4 3, 3 3, 3 4, 4 4))
3         1       NaN      POLYGON ((2 0, 0 0, 0 2, 1 2, 1 1, 2 1, 2 0))
4         2       NaN  MULTIPOLYGON (((3 4, 3 3, 2 3, 2 4, 3 4)), ((4...

See Also

sjoin : spatial join GeoDataFrame.overlay : equivalent method

Notes

Every operation in GeoPandas is planar, i.e. the potential third dimension is not taken into account.

vibespatial.api.tools.sjoin(left_df, right_df, how='inner', predicate='intersects', lsuffix='left', rsuffix='right', distance=None, on_attribute=None, **kwargs)

Spatial join of two GeoDataFrames.

See the User Guide page ../../user_guide/mergingdata for details.

Parameters

left_df, right_df : GeoDataFrames how : string, default ‘inner’

The type of join:

  • ‘left’: use keys from left_df; retain only left_df geometry column

  • ‘right’: use keys from right_df; retain only right_df geometry column

  • ‘inner’: use intersection of keys from both dfs; retain only left_df geometry column

  • ‘outer’: use the union of keys from both dfs; retain a single active geometry column by preferring left geometries and filling unmatched right-only rows from the right geometry column

predicatestring, default ‘intersects’

Binary predicate. Valid values are determined by the spatial index used. You can check the valid values in left_df or right_df as left_df.sindex.valid_query_predicates or right_df.sindex.valid_query_predicates

Available predicates include:

  • 'intersects': True if geometries intersect (boundaries and interiors)

  • 'within': True if left geometry is completely within right geometry

  • 'contains': True if left geometry completely contains right geometry

  • 'contains_properly': True if left geometry contains right geometry and their boundaries do not touch

  • 'overlaps': True if geometries overlap but neither contains the other

  • 'crosses': True if geometries cross (interiors intersect but neither contains the other, with intersection dimension less than max dimension)

  • 'touches': True if geometries touch at boundaries but interiors don’t

  • 'covers': True if left geometry covers right geometry (every point of right is a point of left)

  • 'covered_by': True if left geometry is covered by right geometry

  • 'dwithin': True if geometries are within specified distance (requires distance parameter)

lsuffixstring, default ‘left’

Suffix to apply to overlapping column names (left GeoDataFrame).

rsuffixstring, default ‘right’

Suffix to apply to overlapping column names (right GeoDataFrame).

distancenumber or array_like, optional

Distance(s) around each input geometry within which to query the tree for the ‘dwithin’ predicate. If array_like, must be one-dimesional with length equal to length of left GeoDataFrame. Required if predicate='dwithin'.

on_attributestring, list or tuple

Column name(s) to join on as an additional join restriction on top of the spatial predicate. These must be found in both DataFrames. If set, observations are joined only if the predicate applies and values in specified columns match.

Examples

>>> import geodatasets
>>> chicago = geopandas.read_file(
...     geodatasets.get_path("geoda.chicago_health")
... )
>>> groceries = geopandas.read_file(
...     geodatasets.get_path("geoda.groceries")
... ).to_crs(chicago.crs)
>>> chicago.head()
    ComAreaID  ...                                           geometry
0         35  ...  POLYGON ((-87.60914 41.84469, -87.60915 41.844...
1         36  ...  POLYGON ((-87.59215 41.81693, -87.59231 41.816...
2         37  ...  POLYGON ((-87.62880 41.80189, -87.62879 41.801...
3         38  ...  POLYGON ((-87.60671 41.81681, -87.60670 41.816...
4         39  ...  POLYGON ((-87.59215 41.81693, -87.59215 41.816...
[5 rows x 87 columns]
>>> groceries.head()
    OBJECTID     Ycoord  ...  Category                         geometry
0        16  41.973266  ...       NaN  MULTIPOINT (-87.65661 41.97321)
1        18  41.696367  ...       NaN  MULTIPOINT (-87.68136 41.69713)
2        22  41.868634  ...       NaN  MULTIPOINT (-87.63918 41.86847)
3        23  41.877590  ...       new  MULTIPOINT (-87.65495 41.87783)
4        27  41.737696  ...       NaN  MULTIPOINT (-87.62715 41.73623)
[5 rows x 8 columns]
>>> groceries_w_communities = geopandas.sjoin(groceries, chicago)
>>> groceries_w_communities.head()
   OBJECTID       community                           geometry
0        16          UPTOWN  MULTIPOINT ((-87.65661 41.97321))
1        18     MORGAN PARK  MULTIPOINT ((-87.68136 41.69713))
2        22  NEAR WEST SIDE  MULTIPOINT ((-87.63918 41.86847))
3        23  NEAR WEST SIDE  MULTIPOINT ((-87.65495 41.87783))
4        27         CHATHAM  MULTIPOINT ((-87.62715 41.73623))
[5 rows x 95 columns]

See Also

overlay : overlay operation resulting in a new geometry GeoDataFrame.sjoin : equivalent method

Notes

Every operation in GeoPandas is planar, i.e. the potential third dimension is not taken into account.

vibespatial.api.tools.sjoin_nearest(left_df: vibespatial.api.GeoDataFrame, right_df: vibespatial.api.GeoDataFrame, how: str = 'inner', max_distance: float | None = None, lsuffix: str = 'left', rsuffix: str = 'right', distance_col: str | None = None, exclusive: bool = False) vibespatial.api.GeoDataFrame

Spatial join of two GeoDataFrames based on the distance between their geometries.

Results will include multiple output records for a single input record where there are multiple equidistant nearest or intersected neighbors.

Distance is calculated in CRS units and can be returned using the distance_col parameter.

See the User Guide page https://geopandas.readthedocs.io/en/latest/docs/user_guide/mergingdata.html for more details.

Parameters

left_df, right_df : GeoDataFrames how : string, default ‘inner’

The type of join:

  • ‘left’: use keys from left_df; retain only left_df geometry column

  • ‘right’: use keys from right_df; retain only right_df geometry column

  • ‘inner’: use intersection of keys from both dfs; retain only left_df geometry column

max_distancefloat, default None

Maximum distance within which to query for nearest geometry. Must be greater than 0. The max_distance used to search for nearest items in the tree may have a significant impact on performance by reducing the number of input geometries that are evaluated for nearest items in the tree.

lsuffixstring, default ‘left’

Suffix to apply to overlapping column names (left GeoDataFrame).

rsuffixstring, default ‘right’

Suffix to apply to overlapping column names (right GeoDataFrame).

distance_colstring, default None

If set, save the distances computed between matching geometries under a column of this name in the joined GeoDataFrame.

exclusivebool, default False

If True, the nearest geometries that are equal to the input geometry will not be returned, default False.

Examples

>>> import geodatasets
>>> groceries = geopandas.read_file(
...     geodatasets.get_path("geoda.groceries")
... )
>>> chicago = geopandas.read_file(
...     geodatasets.get_path("geoda.chicago_health")
... ).to_crs(groceries.crs)
>>> chicago.head()
   ComAreaID  ...                                           geometry
0         35  ...  POLYGON ((-87.60914 41.84469, -87.60915 41.844...
1         36  ...  POLYGON ((-87.59215 41.81693, -87.59231 41.816...
2         37  ...  POLYGON ((-87.62880 41.80189, -87.62879 41.801...
3         38  ...  POLYGON ((-87.60671 41.81681, -87.60670 41.816...
4         39  ...  POLYGON ((-87.59215 41.81693, -87.59215 41.816...
[5 rows x 87 columns]
>>> groceries.head()
   OBJECTID     Ycoord  ...  Category                           geometry
0        16  41.973266  ...       NaN  MULTIPOINT ((-87.65661 41.97321))
1        18  41.696367  ...       NaN  MULTIPOINT ((-87.68136 41.69713))
2        22  41.868634  ...       NaN  MULTIPOINT ((-87.63918 41.86847))
3        23  41.877590  ...       new  MULTIPOINT ((-87.65495 41.87783))
4        27  41.737696  ...       NaN  MULTIPOINT ((-87.62715 41.73623))
[5 rows x 8 columns]
>>> groceries_w_communities = geopandas.sjoin_nearest(groceries, chicago)
>>> groceries_w_communities[["Chain", "community", "geometry"]].head(2)
               Chain    community                                geometry
0     VIET HOA PLAZA       UPTOWN   MULTIPOINT ((1168268.672 1933554.35))
1  COUNTY FAIR FOODS  MORGAN PARK  MULTIPOINT ((1162302.618 1832900.224))

To include the distances:

>>> groceries_w_communities = geopandas.sjoin_nearest(groceries, chicago, distance_col="distances")
>>> groceries_w_communities[["Chain", "community", "distances"]].head(2)
               Chain    community  distances
0     VIET HOA PLAZA       UPTOWN        0.0
1  COUNTY FAIR FOODS  MORGAN PARK        0.0

In the following example, we get multiple groceries for Uptown because all results are equidistant (in this case zero because they intersect). In fact, we get 4 results in total:

>>> chicago_w_groceries = geopandas.sjoin_nearest(groceries, chicago, distance_col="distances", how="right")
>>> uptown_results = chicago_w_groceries[chicago_w_groceries["community"] == "UPTOWN"]
>>> uptown_results[["Chain", "community"]]
            Chain community
30  VIET HOA PLAZA    UPTOWN
30      JEWEL OSCO    UPTOWN
30          TARGET    UPTOWN
30       Mariano's    UPTOWN

See Also

sjoin : binary predicate joins GeoDataFrame.sjoin_nearest : equivalent method

Notes

Since this join relies on distances, results will be inaccurate if your geometries are in a geographic CRS.

Every operation in GeoPandas is planar, i.e. the potential third dimension is not taken into account.

vibespatial.api.tools.collect(x, multi=False)

Collect single part geometries into their Multi* counterpart.

Parameters

xan iterable or Series of Shapely geometries, a GeoSeries, or

a single Shapely geometry

multiboolean, default False

if True, force returned geometries to be Multi* even if they only have one component.