为何自定义cities breed时NetLogo的nw:load-graphml无法读取x值?
NetLogo NW扩展自定义Breed无法读取GraphML中x属性的问题
问题场景
我在开发NetLogo项目时,使用NW扩展的nw:load-graphml函数加载GraphML文件数据到模型。
正常运行的代码(使用默认turtles品种)
当使用默认海龟品种turtles时,代码能正常读取代表城市x坐标的x值:
extensions [nw] directed-link-breed [ routes route ] routes-own [ days expense km route-type ] turtles-own [ pots node-id x y modern province rank town-name ] to setup clear-all nw:set-context turtles routes nw:load-graphml "orbis.graphml" ask turtles [ show x ] reset-ticks end
异常情况(使用自定义cities品种)
将海龟品种改为自定义的cities后,调用ask cities [show x]无输出,无法读取x值:
extensions [nw] breed [ cities city ] directed-link-breed [ routes route ] routes-own [ days expense km route-type ] cities-own [ pots node-id x y modern province rank town-name ] to setup clear-all nw:set-context cities routes nw:load-graphml "orbis.graphml" ask cities [ show x ] reset-ticks end
GraphML文件节点片段
我的GraphML文件包含带坐标属性的节点,片段如下:
<node id="n0"> <data key="d0">1</data> <data key="d1">50001</data> <data key="d2">0</data> <data key="d3">Raetia</data> <data key="d4">Germany</data> <data key="d5">10.909</data> <data key="d6">60</data> <data key="d7">47.909</data> <data key="d8">1</data> <data key="d9">Abodiacum</data> <data key="d10">0</data> </node>
原因分析
这是因为NetLogo NW扩展的默认行为存在差异:
- 对于默认
turtles品种:NW扩展会自动将GraphML中的坐标类属性(如对应x、y的d5、d7)同时映射到NetLogo内置的xcor/ycor变量,以及你在turtles-own中定义的x/y变量,因此能直接读取到x的值。 - 对于自定义品种(如
cities):NW扩展仅会将GraphML坐标属性映射到NetLogo通用的xcor/ycor变量,不会主动同步到你自定义的cities-own中的x/y变量,导致你读取自定义x变量时无输出(变量未被赋值)。
解决方法
方法1:使用内置坐标变量替代自定义变量
修改cities-own定义,移除自定义的x、y,直接使用NetLogo内置的xcor、ycor:
cities-own [ pots node-id modern province rank town-name ] ; 在setup中改为 ask cities [ show xcor ]
方法2:手动同步内置变量到自定义变量
加载GraphML后,手动将xcor、ycor的值赋值给自定义的x、y变量:
to setup clear-all nw:set-context cities routes nw:load-graphml "orbis.graphml" ask cities [ set x xcor set y ycor show x ] reset-ticks end
方法3:显式指定属性映射关系
使用nw:load-graphml的映射参数,精准指定GraphML数据键与自定义品种变量的对应关系:
to setup clear-all nw:set-context cities routes nw:load-graphml "orbis.graphml" [ node [ ; 直接从GraphML的data键取值赋值给自定义变量 set x (data "d5") set y (data "d7") set node-id (data "d1") set town-name (data "d9") set province (data "d3") ; 其他属性按需映射 ] ] ask cities [ show x ] reset-ticks end
内容的提问来源于stack exchange,提问作者cconsta1
相关产品推荐
相关产品推荐

