NetLogo中基于属性(如颜色)的社区检测代码需求问询
NetLogo 基于颜色的社区检测(支持环绕模式)
以下是实现你需求的代码,核心用**广度优先搜索(BFS)**处理连通分量,同时手动适配环绕模式的边界邻居判断,能准确标记并计数不同颜色的独立社区(比如红色海龟岛屿在蓝色海龟海洋中的情况)。
变量设置
首先定义全局变量和海龟变量,用于标记社区ID:
globals [ next-community-id ] turtles-own [ my-community ]
核心社区检测逻辑
主检测过程
遍历所有未标记的海龟,为每个独立同色社区分配唯一ID:
to detect-communities ; 初始化社区ID计数器和海龟标记 set next-community-id 1 ask turtles [ set my-community 0 ] ; 对每个未标记的海龟启动BFS,标记整个连通社区 ask turtles with [ my-community = 0 ] [ bfs-mark-community color next-community-id set next-community-id next-community-id + 1 ] end
BFS标记社区(适配环绕模式)
处理8邻域的连通性,同时手动补充环绕模式下的边界邻居:
to bfs-mark-community [ target-color current-id ] let queue (list self) while [ not empty? queue ] [ let current-turtle first queue set queue but-first queue ; 仅处理未标记且颜色匹配的海龟 if current-turtle's my-community = 0 and current-turtle's color = target-color [ ask current-turtle [ set my-community current-id ] ; 基础8邻域邻居(如需4邻域,替换为neighbors4) let neighbors turtles-on neighbors ; 适配环绕模式:补充世界边缘对面的海龟 if current-turtle's xcor = max-pxcor [ set neighbors sentence neighbors turtles-on patch (min-pxcor) current-turtle's ycor ] if current-turtle's xcor = min-pxcor [ set neighbors sentence neighbors turtles-on patch (max-pxcor) current-turtle's ycor ] if current-turtle's ycor = max-pycor [ set neighbors sentence neighbors turtles-on patch current-turtle's xcor (min-pycor) ] if current-turtle's ycor = min-pycor [ set neighbors sentence neighbors turtles-on patch current-turtle's xcor (max-pycor) ] ; 将未标记的同色邻居加入队列继续遍历 let unmarked-neighbors neighbors with [ my-community = 0 and color = target-color ] set queue sentence queue unmarked-neighbors ] ] end
统计社区数量
输出每个颜色对应的独立社区个数:
to report-community-counts ; 生成所有海龟的「颜色-社区ID」对 let color-community-pairs map [ t -> (list t's color t's my-community) ] turtles ; 去重得到唯一的颜色-社区组合 let unique-pairs remove-duplicates color-community-pairs ; 按颜色分组统计并打印结果 foreach remove-duplicates [ c -> c's color ] turtles [ let color-specific filter [ p -> first p = ? ] unique-pairs print (word "颜色 " ? " 的独立社区数量: " length color-specific) ] end
测试示例
快速创建随机海龟并运行检测的示例代码:
to setup clear-all ; 生成500只随机颜色的海龟,模拟多颜色社区场景 create-turtles 500 [ setxy random-xcor random-ycor set color one-of [ red blue green yellow ] ] ; 执行检测并输出结果 detect-communities report-community-counts end
注意事项
- 邻域选择:代码默认用8邻域(
neighbors),如果需要仅上下左右4邻域,替换为neighbors4即可 - 环绕适配:手动判断海龟是否在世界边缘,补充对面patch上的海龟,确保环绕模式下的连通性判断准确
- 社区标记:
my-community为0表示未标记,每个独立社区会被分配唯一的正整数ID,方便后续分析
内容的提问来源于stack exchange,提问作者ThomasC
相关产品推荐
相关产品推荐

