You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AnyLogic的Main中获取不同类型智能体?代码问题求助

解决AnyLogic中遍历Atype/Btype智能体的问题

核心问题分析

你代码无法运行的原因有两个:

  1. 方法拼写错误:get_Main()不是AnyLogic的正确写法,获取主代理的标准方法是getMain()(无下划线)。
  2. 集合引用错误:getMain().Atype的写法不成立——Atype是智能体类,并非Main代理中的成员集合,不能直接通过类名引用实例。

两种可行解决方案

方案一:直接过滤所有行人中的目标类型(无需额外组件)

如果Atype和Btype是Pedestrian的子类,可通过主代理的行人集合筛选目标类型:

// 遍历所有Atype智能体
for(Pedestrian ped : getMain().getPedestrians()) {
    if(ped instanceof Atype) {
        Atype a = (Atype) ped;
        // 执行你的计算逻辑,例如调用a的属性/方法
    }
}

// 遍历所有Btype智能体
for(Pedestrian ped : getMain().getPedestrians()) {
    if(ped instanceof Btype) {
        Btype b = (Btype) ped;
        // 执行你的计算逻辑
    }
}

方案二:用Population组件管理特定类型智能体(高效且易维护)

适合需要频繁遍历目标类型智能体的场景:

  1. 在Main代理中添加两个Population组件,分别命名为atypeAgents(类型选择Atype)和btypeAgents(类型选择Btype)。
  2. 打开生成Atype的PedSource,在On agent created事件中添加代码:
    atypeAgents.add((Atype) agent);
    
  3. 打开生成Btype的PedSource,在On agent created事件中添加代码:
    btypeAgents.add((Btype) agent);
    
  4. 若智能体到达目的地后会销毁,需在Atype/Btype的On destroy事件中添加移除代码,避免空引用:
    // Atype的On destroy事件
    getMain().atypeAgents.remove(this);
    
    // Btype的On destroy事件
    getMain().btypeAgents.remove(this);
    
  5. 最后直接遍历Population集合:
    for(Atype a : atypeAgents) {
        // 你的计算逻辑
    }
    
    for(Btype b : btypeAgents) {
        // 你的计算逻辑
    }
    

内容的提问来源于stack exchange,提问作者ruby zou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:36:22