pysal / libpysal

Core components of Python Spatial Analysis Library
http://pysal.org/libpysal
Other
263 stars 78 forks source link

kernel weight object based on measures of bilateral distances (d_ij) provided by the user? #515

Open lennon-c opened 1 year ago

lennon-c commented 1 year ago

Is it possible to create a kernel weight object based on measures of bilateral distances (d_ij) provided by the user?

I am trying to implement the robust test for S2SLS regressions (GM_lag), which requires providing a kernel object class for the gwk argument. But I am having problems figuring out how to create a kernel object given my data.

I am working with distances between municipalities in Austria based on the shortest driving route between municipalities’ city halls. So, I already have a measure of bilateral distance between city halls, which I would like to use as the input for the creation of kernel weights.

I understand that one can create kernel weights from a geodataframe, but this method will create weights based on the great circle distance.

Any tip or way around?

knaaptime commented 3 months ago

this is now (relatively) straightforward with the Graph class. Assuming you have a dataframe of points representing city halls df and a distance matrix D you would do something like

(this assumes your D matrix is formatted as an adjacency, you might need df.stack() or df.set_index([origin, destination]).reindex(df.index, level=0).reindex(df.index(level=1) or something...)

from libpysal.graph import Graph

# create the generic graph based on pure unweighted distances
unweighted_g = Graph.from_adjacency(D)
# re-weight the sparse matrix
graph = Graph.build_kernel(unweighted_g.sparse, metric='precomputed', ids=df.index)

that metric=precomputed option lets you bypass the dij calculation and pass your own