找到点的两个最近邻点

2023-12-29

我想找到每个点的两个最近邻居

数据集:

:p1 :has_position 1 .
:p2 :has_position 2 .
:p3 :has_position 3 .
:p4 :has_position 4 .

预期成绩 :

?POINT  ?NEIGHBORS
"p1"    "p2; p3"
"p2"    "p1; p3"
"p3"    "p2; p4"
"p4"    "p2; p3"

我尝试这样的事情:

SELECT ?POINT ?POS (group_concat(?idPointN;separator='; ' )as ?NEIGHBORS)
WHERE{
    ?idPoint :has_position ?POS .
    ?idPointN :has_position ?POSN . FILTER (?idPoint != ?idPointN)
}
GROUP BY ?POINT ?POS

这将返回点的所有邻居。我想做类似的事情ORDER BY(?POS-?POSN) and limit 2 in the group_concat但我不知道怎么办。

EDIT :

我写这个查询

SELECT ?POINT ?NEIGHBOR
WHERE{
    ?idPoint rdfs:label ?POINT . FILTER(?idN != ?idPoint)
    ?idPoint :has_position ?POS .


    ?idN rdfs:label ?NEIGHBOR .
    ?idN :has_position ?POSN .
}
ORDER BY ?POINT abs(?POS-?POSN)

它为我提供了每个点的所有邻居按最接近的顺序排序。

我怎样才能只拥有最接近的两个?并在同一条线上?


在 SPARQL 中,获取每个内容的前 n 项的查询确实很棘手,而且目前还没有很好的方法来做到这一点。它几乎总是归结为一些奇怪的黑客行为。首先,带前缀声明的数据:

@prefix : <urn:ex:>

:p1 :has_position 1 .
:p2 :has_position 2 .
:p3 :has_position 3 .
:p4 :has_position 4 .

然后查询。这select行中有一个长字符串连接,但这只是为了去掉问题中描述的前缀。在这种情况下,“黑客”是认识到两个最近的点q and r将最大限度地减少数量|p − q| + |p − r|,所以我们可以计算该数量并取值q and r这给了我们。您还需要确保对q and r,否则你会得到重复的结果(因为你可以交换q and r).

prefix : <urn:ex:>

select ?p (concat(strafter(str(?q),str(:)),", ",strafter(str(?r),str(:))) as ?neighbors) {
  ?p :has_position ?pos1 .
  ?q :has_position ?pos2 .
  ?r :has_position ?pos3 .
  filter(?p != ?q && ?p != ?r)
  filter(str(?q) < str(?r))

  filter not exists {
    ?qq :has_position ?pos22 .
    ?rr :has_position ?pos33 .
    filter(?p != ?qq && ?p != ?rr)
    filter(str(?qq) < str(?rr))
    filter((abs(?pos1 - ?pos22) + abs(?pos1 - ?pos33)) < 
           (abs(?pos1 - ?pos2)  + abs(?pos1 - ?pos3)))
  }
}
-------------------
| p   | neighbors |
===================
| :p1 | "p2, p3"  |
| :p2 | "p1, p3"  |
| :p3 | "p2, p4"  |
| :p4 | "p2, p3"  |
-------------------

现在,您还可以使用子查询来执行此操作,该子查询查找每个的最小数量p,然后在外部查询中找到q and r产生它的值:

prefix : <urn:ex:>

select ?p (concat(strafter(str(?q), str(:)), ", ", strafter(str(?r), str(:))) as ?neighbors) {
  { select ?p (min(abs(?pos1 - ?pos2) + abs(?pos1 - ?pos3)) as ?d) {
      ?p :has_position ?pos1 .
      ?q :has_position ?pos2 .
      ?r :has_position ?pos3 .
      filter(?p != ?q && ?p != ?r)
      filter(str(?q) < str(?r))
    }
    group by ?p
  }

  ?p :has_position ?pos1 .
  ?q :has_position ?pos2 .
  ?r :has_position ?pos3 .
  filter(?p != ?q && ?p != ?r)
  filter(str(?q) < str(?r))
  filter(abs(?pos1 - ?pos2) + abs(?pos1 - ?pos3) = ?d)
}
-------------------
| p   | neighbors |
===================
| :p1 | "p2, p3"  |
| :p2 | "p1, p3"  |
| :p3 | "p2, p4"  |
| :p4 | "p2, p3"  |
-------------------
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

找到点的两个最近邻点 的相关文章

随机推荐