diff --git a/.gitignore b/.gitignore index f778d73..13bbd8e 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ cache/ dist/ *egg-info/ __* +docs/ \ No newline at end of file diff --git a/pycityagent/__init__.py b/pycityagent/__init__.py index 0741268..5a08b1f 100644 --- a/pycityagent/__init__.py +++ b/pycityagent/__init__.py @@ -1,3 +1,7 @@ +""" +Pycityagent: 城市智能体构建框架 +""" + from .simulator import Simulator from .agent import Agent from .agent_citizen import CitizenAgent diff --git a/pycityagent/ac/ac.py b/pycityagent/ac/ac.py index 3d4eeb4..0469532 100644 --- a/pycityagent/ac/ac.py +++ b/pycityagent/ac/ac.py @@ -1,3 +1,5 @@ +"""命令控制器类及其定义""" + from typing import Any, Optional, Union from .action import Action from .citizen_actions.trip import TripAction diff --git a/pycityagent/ac/action.py b/pycityagent/ac/action.py index 098c147..68abdf9 100644 --- a/pycityagent/ac/action.py +++ b/pycityagent/ac/action.py @@ -1,3 +1,5 @@ +"""Action类及其定义""" + from abc import ABC, abstractclassmethod from typing import Callable, Any @@ -15,6 +17,9 @@ class ActionType: Hub = 2 Comp = 3 class Action: + """ + - Action + """ def __init__(self, agent, type:ActionType, source: str = None, before:Callable[[list], Any] = None) -> None: ''' 默认初始化 @@ -47,9 +52,11 @@ async def Forward(self): '''接口函数''' class SimAction(Action): + """SimAction: 模拟器关联Action""" def __init__(self, agent, source: str = None, before: Callable[[list], Any] = None) -> None: super().__init__(agent, ActionType.Sim, source, before) class HubAction(Action): + """HubAction: Apphub关联Action""" def __init__(self, agent, source: str = None, before: Callable[[list], Any] = None) -> None: super().__init__(agent, ActionType.Hub, source, before) \ No newline at end of file diff --git a/pycityagent/ac/controled.py b/pycityagent/ac/controled.py deleted file mode 100644 index 6ac7c28..0000000 --- a/pycityagent/ac/controled.py +++ /dev/null @@ -1,13 +0,0 @@ -import time -from .action import Action -from pycitysim.apphub import AgentMessage - -class ControledAction(Action): - '''Converse行为控制器''' - def __init__(self, agent) -> None: - super().__init__(agent) - - async def Forward(self): - req = {'person_id': self._agent._id, 'schedules': []} - await self._agent._client.person_service.SetSchedule(req) - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '我已理解您的意思,正在修改我的行程', None, None)]) \ No newline at end of file diff --git a/pycityagent/ac/converse.py b/pycityagent/ac/converse.py deleted file mode 100644 index fe434d3..0000000 --- a/pycityagent/ac/converse.py +++ /dev/null @@ -1,31 +0,0 @@ -import time -from .action import Action -from pycitysim.apphub import AgentMessage - -class ConverseAction(Action): - '''Converse行为控制器''' - def __init__(self, agent) -> None: - super().__init__(agent) - - async def Forward(self): - target_agent_ids = self._agent.Brain.Memory.Working.Reason['agent_message_handle_resp'][0] - if len(target_agent_ids) == 0: - return - messages = self._agent.Brain.Memory.Working.Reason['agent_message_handle_resp'][1] - req = {'messages': []} - if len(target_agent_ids) != len(messages): - print("Warning: the number of target agent and message are not aligned, only sends matched messages") - rng = min(len(target_agent_ids), len(messages)) - for i in range(rng): - dic = {} - dic['from'] = self._agent._id - dic['to'] = target_agent_ids[i] - dic['message'] = messages[i] - req['messages'].append(dic) - # * 发送至模拟器 - await self._agent._client.social_service.Send(req=req) - - # * 发送至AppHub - if self._agent.Hub != None and messages[0] != 'End': - # * 将信息中的第一条不同至pop - self._agent.Hub.Update(pop=messages[0]) \ No newline at end of file diff --git a/pycityagent/ac/hub_actions.py b/pycityagent/ac/hub_actions.py index 5ecc5a0..04e5d48 100644 --- a/pycityagent/ac/hub_actions.py +++ b/pycityagent/ac/hub_actions.py @@ -1,3 +1,5 @@ +"""AppHub关联Action定义""" + from typing import Callable, Optional, Any from pycitysim.apphub import AgentMessage from .action import HubAction diff --git a/pycityagent/ac/idle.py b/pycityagent/ac/idle.py deleted file mode 100644 index a3969b3..0000000 --- a/pycityagent/ac/idle.py +++ /dev/null @@ -1,17 +0,0 @@ -import time -from .action import Action -from pycitysim.apphub import AgentMessage - -class IdleAction(Action): - '''idle行为控制器''' - def __init__(self, agent) -> None: - super().__init__(agent) - - async def Forward(self): - if len(self._agent.base['schedules']) > 0: - req = {'person_id': self._agent._id, 'schedules': []} - await self._agent._client.person_service.SetSchedule(req) - if self._agent.Hub != None: - self._agent.Hub.Update() - - \ No newline at end of file diff --git a/pycityagent/ac/shop.py b/pycityagent/ac/shop.py deleted file mode 100644 index 7cd9714..0000000 --- a/pycityagent/ac/shop.py +++ /dev/null @@ -1,80 +0,0 @@ -from .action import Action -from pycitysim.apphub import AgentMessage -import time - -def encap_msg(msg, role='user', **kwargs): - dialog = {'role': role, 'content': msg} - dialog.update(kwargs) - return dialog - -class ShopAction(Action): - '''Shop行为控制器''' - def __init__(self, agent) -> None: - super().__init__(agent) - - async def Forward(self): - # * 与模拟器对接 - 暂时没有 - # * 与AppHub对接 - profile = self._agent.Image.get_profile() - self.consumption(profile) - - def consumption(self, profile, mall_info): - dialogs = [] - system_prompt = f''' - 你是一个在北京工作和生活的人。 - {profile} - 现在是2024年1月。 - 你需要为下一周的基本生活购买必需品。 - ''' - dialogs.append(encap_msg(system_prompt, 'system')) - actions_format = ['''{{'商品': 购买的商品的列表,'购买量': 每个商品的购买量,一个列表, '解释': '这种购买方式的原因'}}'''] - actions_candidates = ['''【食品】 - 米:10元/公斤 - 面粉:7.5元/公斤 - 新鲜蔬菜(如菠菜):7元/500克 - 水果(如苹果):15元/公斤 - 猪肉:30元/公斤 - 鸡肉:20元/公斤 - 鸡蛋:1.5元/个 - 牛奶:10元/升''', - '''【清洁用品】 - 洗衣液:30元/瓶 - 洗洁精:20元/瓶 - 垃圾袋:0.3元/个''', - '''【个人护理用品】 - 牙膏:10元/支 - 洗发水:30元/瓶 - 沐浴露:35元/瓶 - 面巾纸:5元/包''', - '''【其他】 - 矿泉水:1.7元/瓶 - 面包:8元/个 - 辣条:3元/包'''] - - user_prompt = f''' - 首先确定你的消费预算。以如下格式回答,不要有冗余的文本! - {{'消费预算': 一个代表购买必需品需要消耗的钱的数量的数字}} - ''' - dialogs.append(encap_msg(user_prompt)) - # * 对接一:确定消费预算 - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '我正在确定消费预算......', None, None)]) - msg = self._agent._soul.text_request(dialogs) - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我的消费预算是: {msg}'), None, None]) - - dialogs.append(encap_msg(msg, 'assistant')) - - # * 对接二:购物选择 - for cand in actions_candidates: - user_prompt = f''' - 购物中心里有 - {cand} - 你要买哪些商品,以如下格式回答,不要有冗余的文本! - {actions_format[0]} - ''' - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我看到了\n {cand}', None, None)]) - dialogs.append(encap_msg(user_prompt)) - msg = self._agent._soul.text_request(dialogs) - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'我的购买选择是: {msg}', None, None)]) - dialogs.append(encap_msg(msg, 'assistant')) - - self._agent.Hub.Update([AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), '购物完成', None, None)]) \ No newline at end of file diff --git a/pycityagent/ac/sim_actions.py b/pycityagent/ac/sim_actions.py index dc6cb03..6fa119c 100644 --- a/pycityagent/ac/sim_actions.py +++ b/pycityagent/ac/sim_actions.py @@ -1,3 +1,5 @@ +"""Simulator相关Action定义""" + import time from typing import Callable, Optional, Any from .action import SimAction diff --git a/pycityagent/ac/trip.py b/pycityagent/ac/trip.py deleted file mode 100644 index 0f683b6..0000000 --- a/pycityagent/ac/trip.py +++ /dev/null @@ -1,37 +0,0 @@ -import time -from .action import Action -from pycitysim.apphub import AgentMessage - -class TripAction(Action): - '''Trip行为控制器''' - def __init__(self, agent) -> None: - super().__init__(agent) - - async def Forward(self): - now = self._agent.Scheduler.now - if now.is_set: - '''之前已经将schedule同步至模拟器了''' - if self._agent.Hub != None: - self._agent.Hub.Update(streetview=self._agent.Brain.Sence.sence_buffer['streetview']) - else: - '''同步schedule至模拟器''' - self._agent.Scheduler.now.is_set = True - departure_time = now.time - mode = now.mode - aoi_id = now.target_id_aoi - poi_id = now.target_id_poi - end = {'aoi_position': {'aoi_id': aoi_id, 'poi_id': poi_id}} - activity = now.description - trips = [{'mode': mode, 'end': end, 'departure_time': departure_time, 'activity': activity}] - set_schedule = [{'trips': trips, 'loop_count': 1, 'departure_time': departure_time}] - - # * 与模拟器对接 - req = {'person_id': self._agent._id, 'schedules': set_schedule} - await self._agent._client.person_service.SetSchedule(req) - - # * 与AppHub对接 - if self._agent.Hub != None: - messages = [AgentMessage(self._agent.Hub._agent_id, int(time.time()*1000), f'已到达出发时间, {activity}', None, None)] - self._agent.Hub.Update(messages) - - \ No newline at end of file diff --git a/pycityagent/agent.py b/pycityagent/agent.py index 77f2caf..3ae7fdf 100644 --- a/pycityagent/agent.py +++ b/pycityagent/agent.py @@ -1,3 +1,5 @@ +"""智能体模板类及其定义""" + from abc import ABC, abstractmethod from typing import Optional, Union, Callable import PIL.Image as Image @@ -26,7 +28,8 @@ class AgentType: class Template: """ - The basic template of Agent + - 模板基类 + - The basic template class """ def __init__(self, name, server, type:AgentType, soul:UrbanLLM=None, simulator=None) -> None: self._name = name @@ -61,7 +64,8 @@ def Step(self): class Agent(Template): """ - Agent + - 智能体基类 + - Agent base class """ def __init__( self, @@ -71,41 +75,51 @@ def __init__( soul:UrbanLLM=None, simulator=None ) -> None: + """ + 初始化 Init + + Args: + - name (str): 智能体名称; name of your agent + - server (str): 模拟器grpc服务地址; server address of simulator + - type (AgentType): 智能体类型; type of agent + - soul (UrbanLLM): 基础模型模块; base model + - simulator (Simulator): 模拟器对象; simulator + """ super().__init__(name, server, type, soul, simulator) self._hub_connector = None """ - HubConnector: 用于和AppHub对接——可以通过Agent.connectToHub进行绑定 - HubConnector: the connection between agent and AppHub, you can use 'Agent.connectToHub' to create the connection + - HubConnector: 用于和AppHub对接——可以通过Agent.connectToHub进行绑定 + - HubConnector: the connection between agent and AppHub, you can use 'Agent.connectToHub' to create the connection """ self._brain = Brain(self) """ - Agent的大脑 - The Agent's Brain + - Agent的大脑 + - The Agent's Brain """ self._cc = CommandController(self) """ - Agent的命令控制器 - The Agent's CommondController + - Agent的命令控制器 + - The Agent's CommondController """ self._st = StateTransformer() """ - 与Agent关联的状态转移器 - The related StateTransformer + - 与Agent关联的状态转移器 + - The related StateTransformer """ self._ac = ActionController(self) """ - Agent的行为控制器 - The Agent's ActionController + - Agent的行为控制器 + - The Agent's ActionController """ self._step_with_action = True """ - Step函数是否包含action执行 —— 当有自定义action需求(特指包含没有指定source的Action)时可置该选项为False并通过自定义方法执行action操作 + - Step函数是否包含action执行 —— 当有自定义action需求(特指包含没有指定source的Action)时可置该选项为False并通过自定义方法执行action操作 """ def ConnectToHub(self, config:dict): @@ -154,36 +168,36 @@ def set_streetview_config(self, config:dict): def enable_streetview(self): """ - 开启街景相关功能 - Enable Streetview function + - 开启街景相关功能 + - Enable Streetview function """ self._brain.Sence.enable_streeview = True def disable_streetview(self): """ - 关闭街景相关功能 - Disable Streetview function + - 关闭街景相关功能 + - Disable Streetview function """ self._brain.Sence.enable_streeview = False def enable_user_interaction(self): """ - 开启用户交互功能(即在OpenCity控制台中与Agent进行交互) - Enable User Interaction function. The User Interaction function is the ability to interact with the related agent in OpenCity website console. + - 开启用户交互功能(即在OpenCity控制台中与Agent进行交互) + - Enable User Interaction function. The User Interaction function is the ability to interact with the related agent in OpenCity website console. """ self._brain.Memory.Working.enable_user_interaction = True def disable_user_interaction(self): """ - 关闭用户交互功能 - Disable User Interaction function + - 关闭用户交互功能 + - Disable User Interaction function """ self._brain.Memory.Working.enable_user_interaction = False def set_step_with_action(self, flag:bool = None): """ - 默认情况置反step_with_action属性: 即True->False, False->True - 否则根据传入的flag进行设置 + - 默认情况置反step_with_action属性: 即True->False, False->True + - 否则根据传入的flag进行设置 """ if flag != None: self._step_with_action = flag @@ -191,12 +205,13 @@ def set_step_with_action(self, flag:bool = None): self._step_with_action = not self._step_with_action - def sence_config(self, sence_content:Optional[list]=None, sence_radius:int=None): + def sence_config(self, sence_content:Optional[list[str]]=None, sence_radius:int=None): ''' 感知配置 + Sence config Args: - - config: 配置选项——包含需要感知的数据类型 + - sence_content: 配置选项——包含需要感知的数据类型 - time: 时间 - poi: 感兴趣地点 - position: 可达地点 @@ -205,6 +220,7 @@ def sence_config(self, sence_content:Optional[list]=None, sence_radius:int=None) - streetview: 街景 - user_message: 用户交互信息 - agent_message: 智能体交互信息 + - sence_radius (int): 感知半径(m); sence radius ''' if sence_content != None: self._brain._sence.set_sence(sence_content) diff --git a/pycityagent/agent_citizen.py b/pycityagent/agent_citizen.py index 67545c2..999b139 100644 --- a/pycityagent/agent_citizen.py +++ b/pycityagent/agent_citizen.py @@ -1,3 +1,5 @@ +"""CitizenAgent: 城市居民智能体类及其定义""" + from pycityagent.urbanllm import UrbanLLM from .urbanllm import UrbanLLM from .agent import Agent, AgentType @@ -5,8 +7,8 @@ class CitizenAgent(Agent): """ - Citizen Agent - 城市居民智能体 + - Citizen Agent + - 城市居民智能体 """ def __init__( @@ -21,34 +23,41 @@ def __init__( ) -> None: super().__init__(name, server, AgentType.Citizen, soul, simulator) self._id = id + """ + - 智能体ID + - Agent's id + """ + self.base = base """ - Agent/Person的基本属性, Agent指被代理的Person, Person指模拟器中的背景人 - The base attributes of Agent/Person. Agent is the Person being represented. Persons are background persons in simulator + - Agent/Person的基本属性, Agent指被代理的Person, Person指模拟器中的背景人 + - The base attributes of Agent/Person. Agent is the Person being represented. Persons are background persons in simulator - https://cityproto.sim.fiblab.net/#city.agent.v2.Agent """ + self.motion = motion """ - Agent/Person的运动信息 - The motion information of Agent/Person + - Agent/Person的运动信息 + - The motion information of Agent/Person - https://cityproto.sim.fiblab.net/#city.agent.v2.AgentMotion """ self._image = CitizenImage(self) """ - Agent画像 - The Agent's Image + - Agent画像 + - The Agent's Image """ self.Scheduler.schedule_init() """ - 行程初始化 + - 行程初始化 + - Schedule Init """ def Bind(self): """ - 将智能体绑定到AppHub - Bind Agent with AppHub + - 将智能体绑定到AppHub + - Bind Agent with AppHub """ if self._hub_connector == None: print("ERROR: connect with apphub first") @@ -58,37 +67,36 @@ def Bind(self): def enable_economy_behavior(self): """ - 开启经济模拟相关功能(例如购物) - Enable Economy function. Shopping for instance. + - 开启经济模拟相关功能(例如购物) + - Enable Economy function. Shopping for instance. """ self.Brain.Memory.Working.enable_economy = True def disable_economy_behavior(self): """ - 关闭经济模拟相关功能 - Disable Economy function + - 关闭经济模拟相关功能 + - Disable Economy function """ self.Brain.Memory.Working.enable_economy = False def enable_social_behavior(self): """ - 开启社交相关功能 - Enable Social function + - 开启社交相关功能 + - Enable Social function """ self.Brain.Memory.Working.enable_social = True def diable_social_behavior(self): """ - 关闭社交相关功能 - Disable Social function + - 关闭社交相关功能 + - Disable Social function """ self.Brain.Memory.Working.enable_social = False async def Pause(self): """ - 暂停Agent行为使Agent进入'pause'状态 - Pause the Agent, making the agent 'pause' - + - 暂停Agent行为使Agent进入'pause'状态 + - Pause the Agent, making the agent 'pause' """ req = {'person_id': self.base['id'], 'schedules': []} await self._client.person_service.SetSchedule(req) @@ -97,8 +105,8 @@ async def Pause(self): async def Active(self): """ - 恢复Agent行为 - Recover from 'pause' + - 恢复Agent行为 + - Recover from 'pause' """ self._st.pause_back() @@ -133,8 +141,8 @@ async def Step(self, log:bool): def show_yourself(self): """ - Log信息输出 - Pring log message + - Log信息输出 + - Pring log message """ print(f"【State Message】: {self.state}") motion_message = '''''' @@ -149,10 +157,14 @@ def show_yourself(self): @property def Image(self): - """The Agent's Image""" + """ + - The Agent's Image + """ return self._image @property def Scheduler(self): - """The Agent's Scheduler""" + """ + - The Agent's Scheduler + """ return self._brain.Memory.Working.scheduler \ No newline at end of file diff --git a/pycityagent/agent_func.py b/pycityagent/agent_func.py index 32b8f44..ef573da 100644 --- a/pycityagent/agent_func.py +++ b/pycityagent/agent_func.py @@ -1,3 +1,5 @@ +"""FuncAgent: 功能性智能体及其定义""" + from pycityagent.urbanllm import UrbanLLM from .urbanllm import UrbanLLM from .agent import Agent, AgentType @@ -18,16 +20,33 @@ def __init__( soul:UrbanLLM=None, simulator=None, ) -> None: + """ + 初始化 Init + + Args: + - name (str): 智能体名称; name of your agent + - id (int): 智能体Id; id of your agent + - server (str): 模拟器grpc服务地址; server address of simulator + - soul (UrbanLLM): 基础模型模块; base model + - simulator (Simulator): 模拟器对象; simulator + """ + super().__init__(name, server, AgentType.Func, soul, simulator) self._id = id + """ + - 智能体Id + - Agent's id + """ + self._image = Image(self) """ - Func Agent画像——支持自定义内容 + - Func Agent画像——支持自定义内容 """ self.motion = {'id': id, 'position': {}, 'direction': 0} """ Func Agent状态信息——与agent的sence高度相关 + Keys: - id (int): 即agent id - position (https://cityproto.sim.fiblab.net/#city.geo.v2.Position): 即agent当前的位置描述信息 - lane_position (dict): 当position中包含该key时表示agent当前位于lane上——与aoi_position不可同时存在 @@ -49,8 +68,8 @@ def __init__( async def init_position_aoi(self, aoi_id:int): """ - 将agent的位置初始化到指定aoi - 根据指定aoi设置aoi_position, longlat_position以及xy_position + - 将agent的位置初始化到指定aoi + - 根据指定aoi设置aoi_position, longlat_position以及xy_position """ if aoi_id in self._simulator.map.aois: aoi = self._simulator.map.aois[aoi_id] @@ -64,8 +83,8 @@ async def init_position_aoi(self, aoi_id:int): def Bind(self): """ - 将智能体绑定到AppHub - Bind the Agent with AppHub + - 将智能体绑定到AppHub + - Bind the Agent with AppHub """ if self._hub_connector == None: print("ERROR: connect with apphub first") @@ -74,7 +93,7 @@ def Bind(self): def set_image(self, image: Image): """ - 设置image——支持自由扩展Image + - 设置image——支持自由扩展Image """ self._image = image @@ -104,12 +123,14 @@ async def Step(self, log:bool): def show_yourself(self): """ - Log信息输出 - Pring log message + - Log信息输出 + - Pring log message """ pass @property def Image(self): - """The Agent's Image""" + """ + - The Agent's Image + """ return self._image \ No newline at end of file diff --git a/pycityagent/brain/__init__.py b/pycityagent/brain/__init__.py index da32e21..1a7238d 100644 --- a/pycityagent/brain/__init__.py +++ b/pycityagent/brain/__init__.py @@ -1,4 +1,4 @@ -'''Agent大脑功能组织单位''' +'''智能体大脑''' from .brain import * from .brainfc import * diff --git a/pycityagent/brain/brain.py b/pycityagent/brain/brain.py index 0afd267..c826b41 100644 --- a/pycityagent/brain/brain.py +++ b/pycityagent/brain/brain.py @@ -1,3 +1,4 @@ +"""大脑类""" from abc import ABC, abstractmethod from typing import Optional from .scheduler import Scheduler @@ -6,8 +7,8 @@ class Brain: """ - 大脑模块 - Brain Module + 大脑类 + Brain Class """ def __init__(self, agent) -> None: self._agent = agent diff --git a/pycityagent/brain/brainfc.py b/pycityagent/brain/brainfc.py index 258ef5c..99ac6ae 100644 --- a/pycityagent/brain/brainfc.py +++ b/pycityagent/brain/brainfc.py @@ -1,3 +1,4 @@ +"""大脑功能模板类""" class BrainFunction: """ 大脑功能模块模板类 diff --git a/pycityagent/brain/memory.py b/pycityagent/brain/memory.py index 5e1cf59..cfcd40c 100644 --- a/pycityagent/brain/memory.py +++ b/pycityagent/brain/memory.py @@ -1,3 +1,5 @@ +"""记忆相关类与定义""" + from typing import Any, Optional from abc import ABC, abstractmethod from enum import Enum @@ -61,10 +63,12 @@ def MemoryLoad(self, x): """ class WMemory(Memory): + """WMemory: Working Memory工作记忆类""" def __init__(self, agent) -> None: super().__init__(agent, MemoryType.WM) class LTMemory(Memory): + """LTMemory: Long-Term Memory长时记忆类""" def __init__(self, agent) -> None: super().__init__(agent, MemoryType.LTM) diff --git a/pycityagent/brain/scheduler.py b/pycityagent/brain/scheduler.py index 5bb8f00..a0bc51d 100644 --- a/pycityagent/brain/scheduler.py +++ b/pycityagent/brain/scheduler.py @@ -1,3 +1,5 @@ +"""规划器相关类及定义""" + from enum import Enum import random import time as Time @@ -21,6 +23,7 @@ class ScheduleType(Enum): OTHER = 3 class Schedule: + """Schedule基类——为多种Schedule提供基础模板""" def __init__(self, type) -> None: '''默认初始化''' self.type = type diff --git a/pycityagent/brain/sence.py b/pycityagent/brain/sence.py index 4134bb6..7277f12 100644 --- a/pycityagent/brain/sence.py +++ b/pycityagent/brain/sence.py @@ -1,3 +1,5 @@ +"""大脑感知相关类及其定义""" + from typing import Optional, Union from datetime import datetime import math @@ -335,7 +337,7 @@ async def PerceiveReachablePosition(self, radius:int=None) -> Optional[list[dict else: # agent in lane lane_id = self._agent.motion['position']['lane_position']['lane_id'] # 所在lane_id - lane = copy.deepcopy(self._agnet._simualtor.map.get_lane(lane_id)) # 获取lane信息 + lane = copy.deepcopy(self._agent._simulator.map.get_lane(lane_id)) # 获取lane信息 agent_s = self._agent.motion['position']['lane_position']['s'] # 所处位置——用s距离表示 nodes = lane['center_line']['nodes'] if agent_s == 0: @@ -374,7 +376,7 @@ async def PerceiveReachablePosition(self, radius:int=None) -> Optional[list[dict tmp_s = agent_s - radius_ tmp_s = tmp_s if tmp_s >= 0 else 0 x, y = get_xy_in_lane(nodes, tmp_s, 'back') - longlat = self._agent._simulator.map.xy2loglat(x=x, y=y) + longlat = self._agent._simulator.map.xy2lnglat(x=x, y=y) type = self._lane_type_mapping.get(lane['type'], 'unspecified') positions += [{'lane_id': lane_id, 's': tmp_s, @@ -391,7 +393,7 @@ async def PerceiveReachablePosition(self, radius:int=None) -> Optional[list[dict tmp_s = radius_ tmp_s = tmp_s if tmp_s <= suc_lane_['length'] else suc_lane_['length'] x, y = get_xy_in_lane(suc_lane_nodes, tmp_s) - longlat = self._agent._simulator.map.xy2loglat(x=x, y=y) + longlat = self._agent._simulator.map.xy2lnglat(x=x, y=y) type = self._lane_type_mapping.get(lane['type'], 'unspecified') positions += [{'lane_id': suc_lane_id, 's': tmp_s, @@ -403,7 +405,7 @@ async def PerceiveReachablePosition(self, radius:int=None) -> Optional[list[dict neg_s = agent_s - radius_ neg_s = neg_s if neg_s >= 0 else 0 x, y = get_xy_in_lane(nodes, neg_s, 'back') - longlat = self._agent._simulator.map.xy2loglat(x=x, y=y) + longlat = self._agent._simulator.map.xy2lnglat(x=x, y=y) type = self._lane_type_mapping.get(lane['type'], 'unspecified') positions += [{'lans_id': lane_id, 's': neg_s, @@ -414,7 +416,7 @@ async def PerceiveReachablePosition(self, radius:int=None) -> Optional[list[dict pos_s = agent_s + radius_ pos_s = pos_s if pos_s <= lane['length'] else lane['length'] x, y = get_xy_in_lane(nodes, pos_s) - longlat = self._agent._simulator.map.xy2loglat(x=x, y=y) + longlat = self._agent._simulator.map.xy2lnglat(x=x, y=y) type = self._lane_type_mapping.get(lane['type'], 'unspecified') positions += [{'lans_id': lane_id, 's': neg_s, diff --git a/pycityagent/brain/static.py b/pycityagent/brain/static.py index 1ab6536..21a6ff7 100644 --- a/pycityagent/brain/static.py +++ b/pycityagent/brain/static.py @@ -1,5 +1,5 @@ """ -Static Resources: Poi Type association; Type prefix. +静态数据支持; Static Resources: Poi Type association; Type prefix. """ POI_TYPE_DICT = { "100000": "\u7f8e\u98df", diff --git a/pycityagent/cc/cc.py b/pycityagent/cc/cc.py index 9ec7ab0..a0e351d 100644 --- a/pycityagent/cc/cc.py +++ b/pycityagent/cc/cc.py @@ -1,3 +1,5 @@ +"""命令控制器定义""" + from typing import Any from .idle import * from .shop import * diff --git a/pycityagent/hubconnector/__init__.py b/pycityagent/hubconnector/__init__.py index 79fae0b..c8fc14b 100644 --- a/pycityagent/hubconnector/__init__.py +++ b/pycityagent/hubconnector/__init__.py @@ -1,3 +1,5 @@ +"""AppHub客户端""" + from .hubconnector import * __all__ = [HubConnector] \ No newline at end of file diff --git a/pycityagent/hubconnector/hubconnector.py b/pycityagent/hubconnector/hubconnector.py index b7d9615..fb4ef1f 100644 --- a/pycityagent/hubconnector/hubconnector.py +++ b/pycityagent/hubconnector/hubconnector.py @@ -1,3 +1,5 @@ +"""Apphub客户端定义""" + from typing import Optional import geojson from pycitysim.apphub import AppHubClient, AgentMessage, UserMessage diff --git a/pycityagent/image/__init__.py b/pycityagent/image/__init__.py index a7a2ba5..7543441 100644 --- a/pycityagent/image/__init__.py +++ b/pycityagent/image/__init__.py @@ -1,3 +1,5 @@ +"""智能体画像""" + from .image import * __all__ = [Image, CitizenImage, Scratch, CitizenScratch] \ No newline at end of file diff --git a/pycityagent/image/image.py b/pycityagent/image/image.py index 37e6498..6d76ef1 100644 --- a/pycityagent/image/image.py +++ b/pycityagent/image/image.py @@ -1,3 +1,5 @@ +"""智能体画像类及其定义""" + from typing import Optional import json from abc import ABC, abstractclassmethod @@ -99,6 +101,7 @@ def load_selfie(self, selfie_file:str): print("Not Implemented") class Scratch: + """智能体基础信息""" def __init__(self, scratch: Optional[dict]=None) -> None: if scratch != None: self.forward(scratch) @@ -127,6 +130,7 @@ def get_profile_content(self): return text class CitizenScratch(Scratch): + """CitizenAgent基础信息""" def __init__(self, scratch:Optional[dict]=None) -> None: super().__init__(scratch=scratch) self.name = None diff --git a/pycityagent/simulator.py b/pycityagent/simulator.py index 0749e93..b69f891 100644 --- a/pycityagent/simulator.py +++ b/pycityagent/simulator.py @@ -1,24 +1,26 @@ -from pycitysim import * -from pycitysim.routing import RoutingClient -from pycitysim.sim import CityClient +"""Simulator: 城市模拟器类及其定义""" + from typing import Optional, Union from datetime import datetime, timedelta import asyncio +from pycitysim import * +from pycitysim.routing import RoutingClient +from pycitysim.sim import CityClient from .agent_citizen import CitizenAgent from .agent_func import FuncAgent class SimPerceive: """ - 模拟器感知 - Simulator Perceive + - 模拟器感知 + - Simulator Perceive """ def __init__(self, simualtor) -> None: self._simulator=simualtor async def PerceiveAoisByIds(self, ids:Optional[list[int]]): """ - Simulator视角下的AOI感知 - Perceive AOI from Simulator + - Simulator视角下的AOI感知 + - Perceive AOI from Simulator Args: - ids list[int]: list of aoi id @@ -32,21 +34,50 @@ async def PerceiveAoisByIds(self, ids:Optional[list[int]]): class Simulator: """ - 模拟器 - Simulator + - 模拟器主类 + - Simulator Class """ def __init__(self, config) -> None: self.config = config + """ + - 模拟器配置 + - simulator config + """ + self._client = CityClient(self.config['simulator']['server'], secure=True) + """ + - 模拟器grpc客户端 + - grpc client of simulator + """ + self._perceive = SimPerceive(self) + """ + - 模拟器感知 + - Perceive of simulator + """ + self.map = map.Map( mongo_uri = "mongodb://sim:FiblabSim1001@mgo.db.fiblab.tech:8635/", mongo_db = "srt", mongo_coll = config['map_request']['mongo_coll'], cache_dir = config['map_request']['cache_dir'], ) + """ + - 模拟器地图对象 + - Simulator map object + """ + self.routing = RoutingClient(self.config['route_request']['server']) + """ + - 导航服务grpc客户端 + - grpc client of routing service + """ + self.time = 0 + """ + - 模拟城市当前时间 + - The current time of simulator + """ # * Agent相关 def FindAgentsByArea(self, req: dict, status=None): diff --git a/pycityagent/st/__init__.py b/pycityagent/st/__init__.py index 61ae7cf..0ac795a 100644 --- a/pycityagent/st/__init__.py +++ b/pycityagent/st/__init__.py @@ -1,4 +1,4 @@ -'''State Transformer - Agent状态控制机''' +'''State Controller - Agent状态控制机''' from .st import StateTransformer __all__ = [StateTransformer] \ No newline at end of file diff --git a/pycityagent/st/st.py b/pycityagent/st/st.py index cb6f7be..ae046bd 100644 --- a/pycityagent/st/st.py +++ b/pycityagent/st/st.py @@ -1,3 +1,5 @@ +"""StateTransformer: 状态控制器类及其定义""" + from transitions import Machine from abc import ABC, abstractmethod diff --git a/pycityagent/urbanllm/__init__.py b/pycityagent/urbanllm/__init__.py index 99c6384..2116385 100644 --- a/pycityagent/urbanllm/__init__.py +++ b/pycityagent/urbanllm/__init__.py @@ -1,3 +1,5 @@ +"""智能体智能能力""" + from .urbanllm import * __all__ = [LLMConfig, UrbanLLM] \ No newline at end of file diff --git a/pycityagent/urbanllm/urbanllm.py b/pycityagent/urbanllm/urbanllm.py index edebd5e..415bdec 100644 --- a/pycityagent/urbanllm/urbanllm.py +++ b/pycityagent/urbanllm/urbanllm.py @@ -1,3 +1,5 @@ +"""UrbanLLM: 智能能力类及其定义""" + from openai import OpenAI from http import HTTPStatus import dashscope