Como o Shapely não suporta mais do que o GEOS 3.4.0 no momento, será ótimo adicionar outras funções como GEOSSTRtree_nearest no GEOS 3.6.0. Então eu estava tentando adicionar essa função sozinho e encontrei alguns problemas.
O código-fonte do GEOS é como:
const GEOSGeometry *
GEOSSTRtree_nearest (geos::index::strtree::STRtree *tree,
const geos::geom::Geometry *g)
{
return GEOSSTRtree_nearest_r( handle, tree, g);
}
const void* GEOSSTRtree_nearest_generic(GEOSSTRtree *tree,
const void* item,
const GEOSGeometry* itemEnvelope,
GEOSDistanceCallback distancefn,
void* userdata)
{
return GEOSSTRtree_nearest_generic_r( handle, tree, item, itemEnvelope, distancefn, userdata);
}
Então eu adicionei código em strtree.py, ctypes_declarations.py e test.py e tentei executar o teste, mas recebi o erro Falha de segmentação: 11
strtree.py
from shapely.geometry.base import geom_factory
class STRtree:
def nearest(self, geom):
if self._n_geoms == 0:
return None
return geom_factory(lgeos.GEOSSTRtree_nearest(self._tree_handle, geom._geom))
ctypes_declarations.py
def prototype(lgeos, geos_version):
if geos_version >= (3, 6, 0):
lgeos.GEOSSTRtree_nearest.argtypes = [c_void_p, c_void_p]
lgeos.GEOSSTRtree_nearest.restype = c_void_p
teste.py
from shapely.geometry import Point, Polygon
from shapely.strtree import STRtree
a = []
a.append(Polygon([(1,0),(2,0),(2,1),(1,1)]))
a.append(Polygon([(0,2),(1,2),(1,3),(0,3)]))
a.append(Polygon([(-1.5,0),(-2.5,0),(-2.5,-1),(-1.5,-1)]))
tree = STRtree(a)
tree.nearest(Point(0,0))
Eu pensei que meu problema é sobre o processamento de dados entre os ctypes e a geometria, então tentei reimplementar a função shared_path , mas ainda tinha algo errado.
from shapely.geometry import LineString
from shapely.geometry.base import geom_factory
from ctypes import CDLL, c_void_p
dll = CDLL('/Users/*****/anaconda3/lib/python3.7/site-packages/shapely/.dylibs/libgeos_c.1.dylib')
shared_path = dll.GEOSSharedPaths
shared_path.restype = c_void_p
shared_path.argtypes = [c_void_p, c_void_p]
g1 = LineString([((0, 0), (1, 1)), ((-1, 0), (1, 0))])
g2 = LineString([((0, 0), (1, 1)), ((-2, 0), (1, 5))])
geom_factory(shared_path(g1._geom, g2._geom))
Você poderia me ajudar a descobrir isso, thx!
Oi @FuriousRococo , não estou familiarizado com o uso das funções de pesquisa do vizinho mais próximo, mas parece que você está aproximadamente no caminho certo. No entanto, em https://github.com/libgeos/geos/blob/master/capi/geos_c.h.in#L1824 , vejo um sinal de que precisamos usar o método genérico porque os itens em nossa árvore são objetos Python . Acho que você precisará experimentar https://github.com/libgeos/geos/blob/master/capi/geos_c.h.in#L1850 .
Obrigado pelo conselho @sgillies , acho que está funcionando agora.
strtree.py
class STRtree:
def nearest(self, geom):
if self._n_geoms == 0:
return None
envelope = geom.envelope
def callback(item1, item2, distance, userdata):
try:
geom1 = ctypes.cast(item1, ctypes.py_object).value
geom2 = ctypes.cast(item2, ctypes.py_object).value
dist = ctypes.cast(distance, ctypes.POINTER(ctypes.c_double))
lgeos.GEOSDistance(geom1._geom, geom2._geom, dist)
return 1
except:
return 0
item = lgeos.GEOSSTRtree_nearest_generic(self._tree_handle, ctypes.py_object(geom), envelope._geom, \
lgeos.GEOSDistanceCallback(callback), None)
geom = ctypes.cast(item, ctypes.py_object).value
return geom
ctypes_declarations.py
def prototype(lgeos, geos_version):
if geos_version >= (3, 6, 0):
lgeos.GEOSDistanceCallback = CFUNCTYPE(c_int, c_void_p, c_void_p, c_void_p, c_void_p)
lgeos.GEOSSTRtree_nearest_generic.argtypes = [
c_void_p, py_object, c_void_p, lgeos.GEOSDistanceCallback, py_object]
lgeos.GEOSSTRtree_nearest_generic.restype = c_void_p
teste.py
from shapely.geometry import Point, Polygon
from shapely.strtree import STRtree
a = []
a.append(Polygon([(1,0),(2,0),(2,1),(1,1)]))
a.append(Polygon([(0,2),(1,2),(1,3),(0,3)]))
a.append(Polygon([(-1.5,0),(-2.5,0),(-2.5,-1),(-1.5,-1)]))
a.append(Point(0,0.5))
tree = STRtree(a)
pt = tree.nearest(Point(0,0))
print(pt.wkt)
Saída
POINT (0 0.5)
@FuriousRococo Deseja enviar solicitações de pull com este novo recurso?
Obrigado por adicionar o recurso @FuriousRococo. Uma pergunta ao tentar entender essa função mais próxima. Digamos que eu esteja tentando encontrar a estrada mais próxima para um ponto. Portanto, a árvore STR é uma árvore de estradas MultiLineString. Então, neste caso, a estrada mais próxima é dada usando a distância projetada da distância do ponto para o MultiLineStrings? Ou é baseado na menor distância até os centróides das MultiLineStrings que representam as estradas? Obrigada!
Eu escrevi um teste e acho que a função mais próxima verifica cada linha em MultiLineString para ver se a linha mais próxima está dentro de MultiLineString. Aqui está o meu script @asif-rehan
teste.py
from shapely.strtree import STRtree
from shapely.geometry import Point, LineString, MultiLineString
tree_list = [LineString([[0,1],[1,1]])]
tree_list.append(MultiLineString([LineString([[0,0],[1,0]]),LineString([[0,3],[1,3]])]))
tree = STRtree(tree_list)
tree.nearest(Point(0.5,0.25)).wkt
Saída
MULTILINESTRING ((0 0, 1 0), (0 3, 1 3))
Comentários muito úteis
Obrigado pelo conselho @sgillies , acho que está funcionando agora.
strtree.py
ctypes_declarations.py
teste.py
Saída
POINT (0 0.5)