Skip to content

Commit

Permalink
lint & format `weights/*.py part 2 (#650)
Browse files Browse the repository at this point in the history
* lint&format contiguity.py

* lint&format distance.py

* Update libpysal/weights/contiguity.py

Co-authored-by: Martin Fleischmann <[email protected]>

---------

Co-authored-by: Martin Fleischmann <[email protected]>
  • Loading branch information
jGaboardi and martinfleis authored Nov 14, 2023
1 parent dea50a8 commit bb16950
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 109 deletions.
92 changes: 52 additions & 40 deletions libpysal/weights/contiguity.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# ruff: noqa: B006, N802, N803, N813

import itertools
import warnings

Expand All @@ -6,12 +8,13 @@
from ..cg import voronoi_frames
from ..io.fileio import FileIO
from ._contW_lists import ContiguityWeightsLists
from .raster import da2W, da2WSP
from .util import get_ids, get_points_array
from .weights import WSP, W
from .raster import da2W, da2WSP

try:
from shapely.geometry import Point as shapely_point

from ..cg.shapes import Point as pysal_point

point_type = (shapely_point, pysal_point)
Expand All @@ -27,7 +30,8 @@

class Rook(W):
"""
Construct a weights object from a collection of pysal polygons that share at least one edge.
Construct a weights object from a collection of pysal
polygons that share at least one edge.
Parameters
----------
Expand Down Expand Up @@ -61,7 +65,6 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
Parameters
----------
shapefile : string
name of polygon shapefile including suffix.
sparse : boolean
Expand All @@ -70,7 +73,6 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
Returns
-------
w : W
instance of spatial weights
Expand All @@ -81,7 +83,9 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
>>> wr=Rook.from_shapefile(libpysal.examples.get_path("columbus.shp"), "POLYID")
>>> "%.3f"%wr.pct_nonzero
'8.330'
>>> wr=Rook.from_shapefile(libpysal.examples.get_path("columbus.shp"), sparse=True)
>>> wr=Rook.from_shapefile(
... libpysal.examples.get_path("columbus.shp"), sparse=True
... )
>>> pct_sp = wr.sparse.nnz *1. / wr.n**2
>>> "%.3f"%pct_sp
'0.083'
Expand All @@ -98,10 +102,7 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
:class:`libpysal.weights.contiguity.Rook`
"""
sparse = kwargs.pop("sparse", False)
if idVariable is not None:
ids = get_ids(filepath, idVariable)
else:
ids = None
ids = get_ids(filepath, idVariable) if idVariable is not None else None
w = cls(FileIO(filepath), ids=ids, **kwargs)
w.set_shapefile(filepath, idVariable=idVariable, full=full)
if sparse:
Expand All @@ -121,6 +122,7 @@ def from_iterable(cls, iterable, sparse=False, **kwargs):
support iteration. Can be either Shapely or PySAL shapes.
**kw : keyword arguments
optional arguments for :class:`pysal.weights.W`
See Also
--------
:class:`libpysal.weights.weights.W`
Expand Down Expand Up @@ -251,7 +253,7 @@ def from_xarray(
coords_labels={},
k=1,
include_nodata=False,
n_jobs=1,
n_jobs=1, # noqa ARG003
sparse=True,
**kwargs,
):
Expand All @@ -269,10 +271,12 @@ def from_xarray(
coords_labels : dictionary
Pass dimension labels for coordinates and layers if they do not
belong to default dimensions, which are (band/time, y/lat, x/lon)
e.g. coords_labels = {"y_label": "latitude", "x_label": "longitude", "z_label": "year"}
e.g. coords_labels = {"y_label": "latitude",
"x_label": "longitude", "z_label": "year"}
Default is {} empty dictionary.
sparse : boolean
type of weight object. Default is True. For libpysal.weights.W, sparse = False
type of weight object. Default is True.
For libpysal.weights.W, sparse = False
k : int
Order of contiguity, this will select all neighbors upto kth order.
Default is 1.
Expand Down Expand Up @@ -310,7 +314,8 @@ def from_xarray(

class Queen(W):
"""
Construct a weights object from a collection of pysal polygons that share at least one vertex.
Construct a weights object from a collection of pysal
polygons that share at least one vertex.
Parameters
----------
Expand Down Expand Up @@ -344,17 +349,16 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
Parameters
----------
shapefile : string
name of polygon shapefile including suffix.
idVariable : string
name of a column in the shapefile's DBF to use for ids.
sparse : boolean
If True return WSP instance
If False return W instance
Returns
-------
w : W
instance of spatial weights
Expand All @@ -368,13 +372,15 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
>>> wq=Queen.from_shapefile(libpysal.examples.get_path("columbus.shp"),"POLYID")
>>> "%.3f"%wq.pct_nonzero
'9.829'
>>> wq=Queen.from_shapefile(libpysal.examples.get_path("columbus.shp"), sparse=True)
>>> wq=Queen.from_shapefile(
... libpysal.examples.get_path("columbus.shp"), sparse=True
... )
>>> pct_sp = wq.sparse.nnz *1. / wq.n**2
>>> "%.3f"%pct_sp
'0.098'
Notes
-----
Queen contiguity defines as neighbors any pair of polygons that share at
least one vertex in their polygon definitions.
Expand All @@ -384,10 +390,7 @@ def from_shapefile(cls, filepath, idVariable=None, full=False, **kwargs):
:class:`libpysal.weights.contiguity.Queen`
"""
sparse = kwargs.pop("sparse", False)
if idVariable is not None:
ids = get_ids(filepath, idVariable)
else:
ids = None
ids = get_ids(filepath, idVariable) if idVariable is not None else None
w = cls(FileIO(filepath), ids=ids, **kwargs)
w.set_shapefile(filepath, idVariable=idVariable, full=full)
if sparse:
Expand All @@ -403,10 +406,12 @@ def from_iterable(cls, iterable, sparse=False, **kwargs):
Parameters
----------
iterable : iterable
a collection of of shapes to be cast to PySAL shapes. Must
support iteration. Contents may either be a shapely or PySAL shape.
a collection of of shapes to be cast to PySAL shapes.
Must support iteration. Contents may either be
a shapely or PySAL shape.
**kw : keyword arguments
optional arguments for :class:`pysal.weights.W`
See Also
---------
:class:`libpysal.weights.weights.W`
Expand Down Expand Up @@ -537,7 +542,7 @@ def from_xarray(
coords_labels={},
k=1,
include_nodata=False,
n_jobs=1,
n_jobs=1, # noqa ARG003
sparse=True,
**kwargs,
):
Expand All @@ -555,10 +560,12 @@ def from_xarray(
coords_labels : dictionary
Pass dimension labels for coordinates and layers if they do not
belong to default dimensions, which are (band/time, y/lat, x/lon)
e.g. coords_labels = {"y_label": "latitude", "x_label": "longitude", "z_label": "year"}
e.g. coords_labels = {"y_label": "latitude", "x_label":
"longitude", "z_label": "year"}
Default is {} empty dictionary.
sparse : boolean
type of weight object. Default is True. For libpysal.weights.W, sparse = False
type of weight object. Default is True.
For libpysal.weights.W, sparse = False
k : int
Order of contiguity, this will select all neighbors upto kth order.
Default is 1.
Expand Down Expand Up @@ -598,21 +605,17 @@ def Voronoi(points, criterion="rook", clip="ahull", **kwargs):
"""
Voronoi weights for a 2-d point set
Points are Voronoi neighbors if their polygons share an edge or vertex.
Parameters
----------
points : array
(n,2)
coordinates for point locations
kwargs : arguments to pass to Rook, the underlying contiguity class.
Returns
-------
w : W
instance of spatial weights
Expand All @@ -635,8 +638,8 @@ def Voronoi(points, criterion="rook", clip="ahull", **kwargs):
cls = Rook
else:
raise ValueError(
"Contiguity criterion {} not supported. "
'Only "rook" and "queen" are supported.'.format(criterion)
f"Contiguity criterion {criterion} not supported. "
"Only 'rook' and 'queen' are supported."
)
return cls.from_dataframe(region_df, **kwargs)

Expand Down Expand Up @@ -668,7 +671,7 @@ def _from_dataframe(df, **kwargs):
"Voronoi weights are only"
" implemented for point geometries. "
"You may consider using df.centroid."
)
) from None
coords = numpy.column_stack((x, y))
return Voronoi(coords, **kwargs)

Expand All @@ -685,7 +688,8 @@ def _build(polygons, criterion="rook", ids=None):
polygons : list
list of pysal polygons to use to build contiguity
criterion : string
option of which kind of contiguity to build. Is either "rook" or "queen"
option of which kind of contiguity to build.
Is either "rook" or "queen"
ids : list
list of ids to use to index the neighbor dictionary
Expand All @@ -695,10 +699,12 @@ def _build(polygons, criterion="rook", ids=None):
describing contiguity relations and ids is the list of ids used to index
that dictionary.
NOTE: this is different from the prior behavior of buildContiguity, which
returned an actual weights object. Since this just dispatches for the
classes above, this returns the raw ingredients for a spatial weights
object, not the object itself.
Notes
-----
This is different from the prior behavior of buildContiguity, which
returned an actual weights object. Since this just dispatches for the
classes above, this returns the raw ingredients for a spatial weights
object, not the object itself.
"""
if ids and len(ids) != len(set(ids)):
raise ValueError(
Expand Down Expand Up @@ -727,7 +733,13 @@ def _build(polygons, criterion="rook", ids=None):
neighbors[key] = set(neighbor_data[key])
return (
dict(
list(zip(list(neighbors.keys()), list(map(list, list(neighbors.values())))))
list(
zip(
list(neighbors.keys()),
list(map(list, list(neighbors.values()))),
strict=True,
)
)
),
ids,
)
Expand All @@ -747,4 +759,4 @@ def buildContiguity(polygons, criterion="rook", ids=None):
elif criterion.lower() == "queen":
return Queen(polygons, ids=ids)
else:
raise Exception('Weights criterion "{}" was not found.'.format(criterion))
raise ValueError(f"Weights criterion '{criterion}' was not found.")
Loading

0 comments on commit bb16950

Please sign in to comment.