Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 33 additions & 10 deletions libpysal/graph/_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,18 +264,41 @@ def _kernel(
rows, _ = d_csr.nonzero()
bw_per_row = numpy.zeros(d_csr.shape[0])
numpy.maximum.at(bw_per_row, rows, d_csr.data)
bandwidth = bw_per_row[rows] * 1.0000001
elif bandwidth is None:
bandwidth = numpy.percentile(d.data, 25) if k is None else d.data.max()
elif bandwidth == "auto":
if (kernel == "identity") or (kernel is None):
bandwidth = numpy.nan # ignored by identity
bw_per_row = bw_per_row * 1.0000001

if callable(kernel):
func = kernel
else:
bandwidth = _optimize_bandwidth(d, kernel)
if callable(kernel):
d.data = kernel(d.data, bandwidth)

def func(distances, bw):
return _lps_kernel(
distances, bw, kernel=kernel, taper=taper, decay=decay
)

for i in range(d_csr.shape[0]):
start = d_csr.indptr[i]
end = d_csr.indptr[i + 1]
if start < end:
d_csr.data[start:end] = func(
d_csr.data[start:end], float(bw_per_row[i])
)
d = d_csr.tocsc()

else:
d.data = _lps_kernel(d.data, bandwidth, kernel=kernel, taper=taper, decay=decay)
if bandwidth is None:
bandwidth = numpy.percentile(d.data, 25) if k is None else d.data.max()
elif bandwidth == "auto":
if (kernel == "identity") or (kernel is None):
bandwidth = numpy.nan # ignored by identity
else:
bandwidth = _optimize_bandwidth(d, kernel)

if callable(kernel):
d.data = kernel(d.data, bandwidth)
else:
d.data = _lps_kernel(
d.data, bandwidth, kernel=kernel, taper=taper, decay=decay
)
if taper:
d.eliminate_zeros()
return _sparse_to_arrays(d, ids=ids, resolve_isolates=resolve_isolates)
Expand Down
19 changes: 19 additions & 0 deletions libpysal/graph/tests/test_builders.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,25 @@ def test_adaptive_bandwidth(self):
assert g_adaptive.adjacency.values.mean() == pytest.approx(0.2946159834)
assert g_adaptive.adjacency.values.max() == pytest.approx(0.3978916872)

def test_adaptive_bandwidth_custom_kernel_scalar(self):
"""Ensure adaptive bandwidth provides a scalar float to custom kernels."""
from shapely.geometry import Point

rng = np.random.default_rng(6301)
coords = gpd.GeoSeries([Point(*p) for p in rng.laplace(size=(20, 2)) / 50])

def safe_custom_kernel(distances, bw):
# Capping the bandwidth to a minimum value to prevent division by zero
if bw < 0.001:
bw = 0.001

return np.exp(-distances / bw)

g = graph.Graph.build_kernel(
coords, k=4, bandwidth="adaptive", kernel=safe_custom_kernel
)
assert len(g.adjacency) > 0

def test_knn_intids(self):
g = graph.Graph.build_knn(self.gdf, k=3, coplanar="jitter")

Expand Down
Loading