通过使用网络扩展,以下代码构建了两个多边形(由多个补丁组成)之间的最低成本路径:
to calculate-LCP [ID-polygon-1 ID-polygon-2]
let path []
let path-cost -1
;;;;;;;;;;;;;;;;;;;;;;;;
;; Define polygon edges
ask patches with [plabel != ID-polygon-1] [
ask neighbors with [plabel = ID-polygon-1] [
ask nodes-here [
set color red ] ] ]
ask patches with [plabel != ID-polygon-2] [
ask neighbors with [plabel = ID-polygon-2] [
ask nodes-here [
set color red ] ] ]
;;;;;;;;;;;;;;;;;;;;;;;;
;; Build least-cost path
ask nodes with [color = red] [
foreach sort nodes-on patches with [ID-polygon = ID-polygon-1] [
let node-on-polygon-1 ?
foreach sort nodes-on patches with [ID-polygon = ID-polygon-2] [
let node-on-polygon-2 ?
ask node-on-polygon-1 [
let cost nw:weighted-distance-to node-on-polygon-2 "link-cost"
if path-cost = -1 or cost < path-cost [
set path-cost cost
set path nw:weighted-path-to node-on-polygon-2 "link-cost" ] ] ] ] ]
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Draw least-cost path
foreach path [ ;; trace le least-cost path
ask ? [ set color red
set thickness 0.2 ] ]
end
我使用两个多边形来应用此代码,这些多边形在图中由黑色矩形表示。通过使用profiler扩展,此代码运行了14分钟。
对于每只狼,我想在有狼的多边形和围绕狼的半径3公里范围内的所有多边形之间建立成本最低的路径。这是我的代码:
ask wolves [
set my-list-of-polygons-in-buffer ( [plabel] of patches in-radius 3 )
set my-list-of-polygons-in-buffer remove-duplicates my-list-of-polygons-in-buffer
set my-list-of-polygons-in-buffer remove [plabel] of patch-here my-list-of-polygons-in-buffer
set my-list-of-polygons-in-buffer remove "" my-list-of-polygons-in-buffer
foreach my-list-of-polygons-in-buffer [
let ID-polygon-in-buffer ?
ask patches with [plabel = ID-polygon-in-buffer] [
let LCP calculate-LCP [my-ID-polygon] of myself ID-polygon-in-buffer ] ] ]
问题是我的程序“calculate-LCP”运行得太慢,无法在狼周围的缓冲区中定义最低成本路径(我的模型中有100只狼)。如何加快模型的加速模拟?
非常感谢你的帮助。
答案 0 :(得分:3)
首次设置网络时,您只需拨打nw:set-snapshot turtles links
一次。如果任何权重发生变化,或者添加或删除了任何链接或节点,则需要再次调用它。这应该会极大地加速您的代码。