如何在NetLogo购物模型中使用斑块统计以周为单位的时钟周期?
嘿,我来帮你搭建这个NetLogo家庭-超市购物模型,同时搞定周周期时钟和斑块统计的需求!下面是完整的实现方案,分模块给你讲清楚~
1. 完整的基础购物模型代码
先给你一套能跑的基础模型,包含家庭、超市斑块和海龟往返逻辑:
globals [ num-homes ; 家庭斑块数量 num-supermarkets ; 超市斑块数量 ticks-per-day ; 每天的tick数(可自定义) days-per-week ; 每周天数,默认7 current-week ; 当前周数 ] patches-own [ is-home? ; 是否是家庭斑块 is-supermarket? ; 是否是超市斑块 weekly-trips ; 家庭斑块每周的出行次数 weekly-visits ; 超市斑块每周的到访次数 ] turtles-own [ home-patch ; 海龟所属的家庭斑块 target-supermarket ; 目标超市斑块 is-going-out? ; 是否在去超市的路上 ] to setup clear-all set num-homes 20 set num-supermarkets 5 set ticks-per-day 10 set days-per-week 7 set current-week 1 ; 创建家庭斑块 ask n-of num-homes patches [ set is-home? true set is-supermarket? false set pcolor green set weekly-trips 0 ; 每个家庭生成1只海龟 crt 1 [ set home-patch self set is-going-out? false set color yellow set size 1.5 move-to home-patch ] ] ; 创建超市斑块 ask n-of num-supermarkets patches with [not is-home?] [ set is-supermarket? true set is-home? false set pcolor blue set weekly-visits 0 ] reset-ticks end to go ; 检查是否进入新的一周 if ticks mod (ticks-per-day * days-per-week) = 0 and ticks > 0 [ set current-week current-week + 1 ; 重置每周的统计数据(如果需要周环比统计) ask patches [ if is-home? [set weekly-trips 0] if is-supermarket? [set weekly-visits 0] ] print (word "进入第" current-week "周") ] ask turtles [ if not is-going-out? [ ; 随机选择一个超市作为目标 set target-supermarket one-of patches with [is-supermarket?] set is-going-out? true ] if is-going-out? [ ; 向目标超市移动 face target-supermarket fd 1 ; 到达超市后,停留1tick然后返回 if patch-here = target-supermarket [ wait 1 set target-supermarket home-patch set is-going-out? false ; 统计超市到访次数和家庭出行次数 ask home-patch [set weekly-trips weekly-trips + 1] ask patch-here [set weekly-visits weekly-visits + 1] ] ] else [ ; 返回家中 face target-supermarket fd 1 if patch-here = target-supermarket [ ; 到家后停留一段时间再出发(模拟在家的时长) wait ticks-per-day ] ] ] tick end
2. 以周为单位的时钟周期实现细节
这里的核心是把NetLogo原生的tick(基础时间单位)转换成“周”的概念:
- 定义
ticks-per-day和days-per-week两个全局变量,你可以根据模型需求调整(比如每天10tick,每周7天就是70tick为一周) - 在
go过程开头,通过ticks mod (ticks-per-day * days-per-week)判断是否进入新一周,自动更新current-week - 可选操作:每周重置斑块的统计变量,方便单独统计单周数据
你还可以在NetLogo界面添加一个监视器,绑定current-week变量,这样就能直观看到当前是第几周。
3. 斑块统计功能说明
模型里给斑块加了两个针对性的统计变量:
- 家庭斑块的
weekly-trips:记录该家庭每周的出行次数(每次海龟完成往返后+1) - 超市斑块的
weekly-visits:记录该超市每周的到访次数(每次海龟到达后+1)
要可视化这些数据,你可以:
- 添加一个表格组件,选择“斑块”作为数据源,列选
weekly-trips和weekly-visits,就能看到每个斑块的实时统计值 - 添加一个柱状图组件,比如按超市分组展示
weekly-visits,直观对比不同超市的人气 - 如果需要累计统计(而非单周统计),可以去掉每周重置变量的代码,或者新增
total-trips/total-visits变量做累计统计
4. 自定义调整建议
- 可以修改
ticks-per-day来调整时间流速,数值越大,一天的模拟时长越长 - 给海龟添加
shopping-duration变量,模拟不同海龟在超市的停留时长差异 - 给超市添加
capacity变量,当到访人数超过容量时,让海龟排队等待,增加模型的真实性
内容的提问来源于stack exchange,提问作者Dwayne Johnson
相关产品推荐
相关产品推荐

