pycityagent 1.1.9__py3-none-any.whl → 1.1.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pycityagent/__init__.py CHANGED
@@ -6,5 +6,6 @@ from .simulator import Simulator
6
6
  from .agent import Agent
7
7
  from .agent_citizen import CitizenAgent
8
8
  from .agent_func import FuncAgent
9
+ from .agent_group import GroupAgent
9
10
 
10
- __all__ = [Simulator, Agent, CitizenAgent, FuncAgent]
11
+ __all__ = [Simulator, Agent, CitizenAgent, FuncAgent, GroupAgent]
@@ -5,4 +5,4 @@ from .action import *
5
5
  from .hub_actions import *
6
6
  from .sim_actions import *
7
7
 
8
- __all__ = [ActionController, Action, HubAction, SimAction, SendUserMessage, SendStreetview, SendPop, PositionUpdate, ShowPath, ShowPosition, SetSchedule, SendAgentMessage]
8
+ __all__ = [ActionController, Action, HubAction, SimAction, SendUserMessage, SendStreetview, SendPop, ShowPath, ShowPosition, SetSchedule, SendAgentMessage]
@@ -13,10 +13,9 @@ class TripAction(Action):
13
13
  async def Forward(self):
14
14
  now = self._agent.Scheduler.now
15
15
  if now.is_set:
16
- # TODO: 目前仅支持传输一张图片至前端
17
16
  '''之前已经将schedule同步至模拟器了'''
18
- if self._agent.Hub != None:
19
- self._agent.Hub.Update(streetview=self._agent.Brain.Sence.sence_buffer['streetview'][0])
17
+ if self._agent.Hub != None and self._agent.Brain.Sence.sence_buffer['streetview'] != None:
18
+ self._agent.Hub.Update(streetview=self._agent.Brain.Sence.sence_buffer['streetview'])
20
19
  else:
21
20
  '''同步schedule至模拟器'''
22
21
  self._agent.Scheduler.now.is_set = True
@@ -1,9 +1,12 @@
1
1
  """AppHub关联Action定义"""
2
2
 
3
- from typing import Callable, Optional, Any
3
+ from typing import Callable, Optional, Any, Union
4
+ from geojson import Feature, FeatureCollection, Point, LineString
5
+ from shapely.geometry import mapping
4
6
  from pycitysim.apphub import AgentMessage
5
7
  from .action import HubAction
6
8
  from PIL.Image import Image
9
+ from ..utils import *
7
10
 
8
11
  class SendUserMessage(HubAction):
9
12
  """
@@ -20,6 +23,8 @@ class SendUserMessage(HubAction):
20
23
  messages = self.get_source()
21
24
  if messages != None:
22
25
  self._agent.Hub.Update(messages = messages)
26
+ else:
27
+ print("Error: without input data")
23
28
 
24
29
  class SendStreetview(HubAction):
25
30
  """
@@ -30,13 +35,14 @@ class SendStreetview(HubAction):
30
35
  super().__init__(agent, source, before)
31
36
 
32
37
  async def Forward(self, images: Optional[list[Image]] = None):
33
- # TODO: 目前只支持发送一张图片
34
38
  if not images == None:
35
- self._agent.Hub.Update(streetview = images[0])
39
+ self._agent.Hub.Update(streetview = images)
36
40
  elif self._source != None:
37
41
  images = self.get_source()
38
42
  if images != None:
39
- self._agent.Hub.Update(streetview = images[0])
43
+ self._agent.Hub.Update(streetview = images)
44
+ else:
45
+ print("Error: without input data")
40
46
 
41
47
  class SendPop(HubAction):
42
48
  """
@@ -53,6 +59,8 @@ class SendPop(HubAction):
53
59
  pop = self.get_source()
54
60
  if pop != None:
55
61
  self._agent.Hub.Update(pop = pop)
62
+ else:
63
+ print("Error: without input data")
56
64
 
57
65
  class PositionUpdate(HubAction):
58
66
  """
@@ -69,27 +77,219 @@ class PositionUpdate(HubAction):
69
77
  longlat = self.get_source()
70
78
  if longlat != None:
71
79
  self._agent.Hub.Update(longlat = longlat)
80
+ else:
81
+ print("Error: without input data")
72
82
 
73
- class ShowPath(HubAction):
83
+ class ShowPosition(HubAction):
74
84
  """
75
- 在地图上展示路径信息
76
- Show a path in frontend map
85
+ 在地图上展示特定地点
86
+ Show a position in frontend map
77
87
  """
78
88
  def __init__(self, agent, source: str = None, before: Callable[[list], Any] = None) -> None:
79
89
  super().__init__(agent, source, before)
80
90
 
81
- async def Forward(self):
82
- # TODO: 相关功能完善
83
- pass
91
+ async def Forward(self, position: Union[int, list[float]], properties: Optional[dict]=None):
92
+ """
93
+ Args:
94
+ - position (Union[int, list[float]])
95
+ - int: 表示poi id
96
+ - list[float]: 具体的position经纬度坐标
97
+ - properties (Optional[dict]): 支持用户添加自定义属性, 默认为None
98
+ - 例如: {'description': "莲花超市"}
99
+ """
100
+ if isinstance(position, int):
101
+ # poi
102
+ if position in self._agent._simulator.map.pois:
103
+ poi = self._agent._simulator.map.pois[position]
104
+ lnglat_p = poi['shapely_lnglat']
105
+ position_feature = Feature(geometry=lnglat_p, properties=properties)
106
+ self._agent.Hub.ShowGeo(FeatureCollection([position_feature]))
107
+ else:
108
+ print("Error: wrong position (wrong poi id)")
109
+ else:
110
+ # longitude latitude
111
+ position_feature = Feature(geometry=Point(position), properties=properties)
112
+ self._agent.Hub.ShowGeo(FeatureCollection([position_feature]))
84
113
 
85
- class ShowPosition(HubAction):
114
+ class ShowAoi(HubAction):
86
115
  """
87
- 在地图上展示特定地点
88
- Show a position in frontend map
116
+ 在地图上显示Aoi
117
+ Show aoi in map
89
118
  """
90
119
  def __init__(self, agent, source: str = None, before: Callable[[list], Any] = None) -> None:
91
120
  super().__init__(agent, source, before)
92
121
 
93
- async def Forward(self):
94
- # TODO: 相关功能完善
95
- pass
122
+ async def Forward(self, aoi_id:int, properties: Optional[dict]=None):
123
+ """
124
+ Args:
125
+ - aoi_id (int): Aoi id
126
+ - properties (Optional[dict]): 支持用户添加自定义属性, 默认为None
127
+ - 例如: {'description': "我居住的小区"}
128
+ """
129
+ properties_default = {
130
+ "stroke-width": 2,
131
+ "stroke-opacity": 1,
132
+ "fill": "#ff2600",
133
+ "fill-opacity": 0.5
134
+ }
135
+ if properties != None:
136
+ properties_default.update(properties)
137
+ if aoi_id in self._agent._simulator.map.aois:
138
+ aoi = self._agent._simulator.map.aois[aoi_id]
139
+ lnglat_poly = aoi['shapely_lnglat']
140
+ aoi_feature = Feature(geometry=lnglat_poly, properties=properties_default)
141
+ self._agent.Hub.ShowGeo(FeatureCollection([aoi_feature]))
142
+ else:
143
+ print("Error: wrong aoi id")
144
+
145
+ class ShowPath(HubAction):
146
+ """
147
+ 在地图上展示路径信息
148
+ Show a path in frontend map
149
+ """
150
+ def __init__(self, agent, source: str = None, before: Callable[[list], Any] = None) -> None:
151
+ super().__init__(agent, source, before)
152
+
153
+ async def Forward(self,
154
+ path: Optional[Union[int, list[list[float]]]]=None,
155
+ start_end: Optional[Union[float, tuple[float, float]]]=None,
156
+ direction: Optional[str]='front',
157
+ properties: Optional[dict]=None):
158
+ """
159
+ Args:
160
+ - path (Optional[Union[int, list[list[float]]]]): 如果为None, 从Reason池中基于source拿取数据
161
+ - int: lane id
162
+ - list[list[float]]: path node
163
+ - start_end: (Optional[Union[float, tuple[float, float]]]): 指定显示范围, 如path是list[list[float]]形式则无效
164
+ - float: 如果仅包含一个float, 则展示从指定位置开始到path结尾的位置
165
+ - tuple[float, end]: 分别表示起点与终点
166
+ - direction (str): 指定前进方向, 支持['front', 'back'], 默认为'front'
167
+ - properties (Optional[dict]): 支持用户添加自定义属性, 默认为None
168
+ """
169
+ properties_default = {'stroke-width': 10, 'stroke-opacity': 0.5}
170
+ if properties != None:
171
+ properties_default.update(properties)
172
+ if path != None:
173
+ if isinstance(path, int):
174
+ # lane id
175
+ if path in self._agent._simulator.map.lanes:
176
+ lane = self._agent._simulator.map.lanes[path]
177
+ nodes = lane['center_line']['nodes']
178
+ path_ls = mapping(lane['shapely_lnglat'])
179
+ path_ls['coordinates'] = list(path_ls['coordinates'])
180
+ for i in range(len(path_ls['coordinates'])):
181
+ path_ls['coordinates'][i] = list(path_ls['coordinates'][i])
182
+ # start-end与direction处理
183
+ if isinstance(start_end, float):
184
+ # start
185
+ if direction == 'back':
186
+ key_index = get_keyindex_in_lane(nodes, start_end, 'back')
187
+ path_ls['coordinates'] = path_ls['coordinates'][:key_index+1]
188
+ path_ls['coordinates'].reverse()
189
+ else:
190
+ key_index = get_keyindex_in_lane(nodes, start_end)
191
+ path_ls['coordinates'] = path_ls['coordinates'][key_index:]
192
+
193
+ path_ls['coordinates'][0] = [
194
+ self._agent.motion['position']['longlat_position']['longitude'],
195
+ self._agent.motion['position']['longlat_position']['latitude']
196
+ ]
197
+ elif isinstance(start_end, tuple) and len(start_end) == 2:
198
+ # start - end
199
+ start = start_end[0]
200
+ end = start_end[1]
201
+ if direction == 'back':
202
+ keyIndex_s = get_keyindex_in_lane(nodes, start, 'back')
203
+ keyIndex_e = get_keyindex_in_lane(nodes, end, 'back')
204
+ path_ls['coordinates'] = path_ls['coordinates'][keyIndex_e:keyIndex_s+1]
205
+ path_ls['coordinates'].reverse()
206
+ xy = get_xy_in_lane(nodes, end, 'back')
207
+ longlat = self._agent._simulator.map.xy2lnglat(x=xy[0], y=xy[1])
208
+ path_ls['coordinates'].append([longlat[0], longlat[1]])
209
+ else:
210
+ keyIndex_s = get_keyindex_in_lane(nodes, start)
211
+ keyIndex_e = get_keyindex_in_lane(nodes, end)
212
+ path_ls['coordinates'] = path_ls['coordinates'][keyIndex_s:keyIndex_e+1]
213
+ xy = get_xy_in_lane(nodes, end)
214
+ longlat = self._agent._simulator.map.xy2lnglat(x=xy[0], y=xy[1])
215
+ path_ls['coordinates'].append([longlat[0], longlat[1]])
216
+ path_ls['coordinates'][0] = [
217
+ self._agent.motion['position']['longlat_position']['longitude'],
218
+ self._agent.motion['position']['longlat_position']['latitude']
219
+ ]
220
+ path_feature = Feature(geometry=path_ls, properties=properties_default)
221
+ self._agent.Hub.ShowGeo(FeatureCollection([path_feature]))
222
+ else:
223
+ print("Error: wrong path (wrong lane id)")
224
+ else:
225
+ # list point
226
+ path_ls = LineString(path)
227
+ path_feature = Feature(geometry=path_ls, properties=properties_default)
228
+ self._agent.Hub.ShowGeo(FeatureCollection([path_feature]))
229
+ elif self._source != None:
230
+ path_coll = self.get_source()
231
+ if path_coll != None:
232
+ path = path_coll['path']
233
+ start_end = path_coll['start_end']
234
+ direction = path_coll['direction']
235
+ properties = path_coll['properties']
236
+ if properties != None:
237
+ properties_default.update(properties)
238
+ if isinstance(path, int):
239
+ # lane id
240
+ if path in self._agent._simulator.map.lanes:
241
+ lane = self._agent._simulator.map.lanes[path]
242
+ nodes = lane['center_line']['nodes']
243
+ path_ls = mapping(lane['shapely_lnglat'])
244
+ path_ls['coordinates'] = list(path_ls['coordinates'])
245
+ for i in range(len(path_ls['coordinates'])):
246
+ path_ls['coordinates'][i] = list(path_ls['coordinates'][i])
247
+ # start-end与direction处理
248
+ if isinstance(start_end, float):
249
+ # start
250
+ if direction == 'back':
251
+ key_index = get_keyindex_in_lane(nodes, start_end, 'back')
252
+ path_ls['coordinates'] = path_ls['coordinates'][:key_index+1]
253
+ path_ls['coordinates'].reverse()
254
+ else:
255
+ key_index = get_keyindex_in_lane(nodes, start_end)
256
+ path_ls['coordinates'] = path_ls['coordinates'][key_index:]
257
+
258
+ path_ls['coordinates'][0] = [
259
+ self._agent.motion['position']['longlat_position']['longitude'],
260
+ self._agent.motion['position']['longlat_position']['latitude']
261
+ ]
262
+ elif isinstance(start_end, tuple) and len(start_end) == 2:
263
+ # start - end
264
+ start = start_end[0]
265
+ end = start_end[1]
266
+ if direction == 'back':
267
+ keyIndex_s = get_keyindex_in_lane(nodes, start, 'back')
268
+ keyIndex_e = get_keyindex_in_lane(nodes, end, 'back')
269
+ path_ls['coordinates'] = path_ls['coordinates'][keyIndex_e:keyIndex_s+1]
270
+ path_ls['coordinates'].reverse()
271
+ xy = get_xy_in_lane(nodes, end, 'back')
272
+ longlat = self._agent._simulator.map.xy2lnglat(x=xy[0], y=xy[1])
273
+ path_ls['coordinates'].append([longlat[0], longlat[1]])
274
+ else:
275
+ keyIndex_s = get_keyindex_in_lane(nodes, start)
276
+ keyIndex_e = get_keyindex_in_lane(nodes, end)
277
+ path_ls['coordinates'] = path_ls['coordinates'][keyIndex_s:keyIndex_e+1]
278
+ xy = get_xy_in_lane(nodes, end)
279
+ longlat = self._agent._simulator.map.xy2lnglat(x=xy[0], y=xy[1])
280
+ path_ls['coordinates'].append([longlat[0], longlat[1]])
281
+ path_ls['coordinates'][0] = [
282
+ self._agent.motion['position']['longlat_position']['longitude'],
283
+ self._agent.motion['position']['longlat_position']['latitude']
284
+ ]
285
+ path_feature = Feature(geometry=path_ls, properties=properties_default)
286
+ self._agent.Hub.ShowGeo(FeatureCollection([path_feature]))
287
+ else:
288
+ print("Error: wrong path (wrong lane id)")
289
+ else:
290
+ # list point
291
+ path_ls = LineString(path)
292
+ path_feature = Feature(geometry=path_ls, properties=properties_default)
293
+ self._agent.Hub.ShowGeo(FeatureCollection([path_feature]))
294
+ else:
295
+ print("Error: without input")
pycityagent/agent.py CHANGED
@@ -22,9 +22,11 @@ class AgentType:
22
22
 
23
23
  - Citizen = 1, 指城市居民类型agent——行动受城市规则限制
24
24
  - Func = 2, 功能型agent——行动规则宽松——本质上模拟器无法感知到Func类型的agent
25
+ - Group = 3, 群体智能体
25
26
  """
26
27
  Citizen = 1
27
28
  Func = 2
29
+ Group = 3
28
30
 
29
31
  class Template:
30
32
  """
@@ -4,6 +4,8 @@ from pycityagent.urbanllm import UrbanLLM
4
4
  from .urbanllm import UrbanLLM
5
5
  from .agent import Agent, AgentType
6
6
  from .image.image import CitizenImage
7
+ from .hubconnector import Waypoint
8
+ import time
7
9
 
8
10
  class CitizenAgent(Agent):
9
11
  """
@@ -54,6 +56,8 @@ class CitizenAgent(Agent):
54
56
  - Schedule Init
55
57
  """
56
58
 
59
+ self._history_trajectory: list[Waypoint] = []
60
+
57
61
  def Bind(self):
58
62
  """
59
63
  - 将智能体绑定到AppHub
@@ -124,8 +128,12 @@ class CitizenAgent(Agent):
124
128
  await self._simulator.GetTime()
125
129
  # * 2. 拉取Agent最新状态
126
130
  resp = await self._client.person_service.GetPerson({'person_id':self._id})
127
- self.base = resp['base']
128
- self.motion = resp['motion']
131
+ self.base = resp['person']['base']
132
+ self.motion = resp['person']['motion']
133
+ longitude = self.motion['position']['longlat_position']['longitude']
134
+ latitude = self.motion['position']['longlat_position']['latitude']
135
+ if self.state == 'trip':
136
+ self._history_trajectory.append(Waypoint([longitude, latitude], int(time.time())))
129
137
  # * 3. Brain工作流
130
138
  await self._brain.Run()
131
139
  # * 4. Commond Controller工作流
pycityagent/agent_func.py CHANGED
@@ -1,10 +1,13 @@
1
1
  """FuncAgent: 功能性智能体及其定义"""
2
2
 
3
+ from typing import Union
3
4
  from pycityagent.urbanllm import UrbanLLM
4
5
  from .urbanllm import UrbanLLM
5
6
  from .agent import Agent, AgentType
6
7
  from .image.image import Image
7
8
  from .ac.hub_actions import PositionUpdate
9
+ from .utils import *
10
+ from .hubconnector import Waypoint
8
11
 
9
12
  class FuncAgent(Agent):
10
13
  """
@@ -15,7 +18,6 @@ class FuncAgent(Agent):
15
18
  def __init__(
16
19
  self,
17
20
  name:str,
18
- id: int,
19
21
  server:str,
20
22
  soul:UrbanLLM=None,
21
23
  simulator=None,
@@ -32,12 +34,6 @@ class FuncAgent(Agent):
32
34
  """
33
35
 
34
36
  super().__init__(name, server, AgentType.Func, soul, simulator)
35
- self._id = id
36
- """
37
- - 智能体Id
38
- - Agent's id
39
- """
40
-
41
37
  self._image = Image(self)
42
38
  """
43
39
  - Func Agent画像——支持自定义内容
@@ -63,23 +59,107 @@ class FuncAgent(Agent):
63
59
  - x (double)
64
60
  - y (double)
65
61
  - z (double)
66
- - direction (double): 方向角
62
+ - direction (double): 朝向-方向角
67
63
  """
68
64
 
69
- async def init_position_aoi(self, aoi_id:int):
65
+ self._posUpdate = PositionUpdate(self)
66
+ self._history_trajectory:list[Waypoint] = []
67
+
68
+ async def set_position_aoi(self, aoi_id:int):
70
69
  """
71
- - 将agent的位置初始化到指定aoi
72
- - 根据指定aoi设置aoi_position, longlat_position以及xy_position
70
+ - 将agent的位置设定到指定aoi
71
+
72
+ Args:
73
+ - aoi_id (int): AOI id
73
74
  """
74
75
  if aoi_id in self._simulator.map.aois:
76
+ if 'aoi_position' in self.motion['position'].keys() and aoi_id == self.motion['position']['aoi_position']['aoi_id']:
77
+ return
75
78
  aoi = self._simulator.map.aois[aoi_id]
79
+ self.motion['position'] = {}
76
80
  self.motion['position']['aoi_position'] = {'aoi_id': aoi_id}
77
81
  self.motion['position']['longlat_position'] = {'longitude': aoi['shapely_lnglat'].centroid.coords[0][0], 'latitude': aoi['shapely_lnglat'].centroid.coords[0][1]}
82
+ # self._history_trajectory.append([self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
78
83
  x, y = self._simulator.map.lnglat2xy(lng=self.motion['position']['longlat_position']['longitude'],
79
84
  lat=self.motion['position']['longlat_position']['latitude'])
80
85
  self.motion['position']['xy_position'] = {'x': x, 'y': y}
81
- pos = PositionUpdate(self)
82
- await pos.Forward(longlat=[self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
86
+ await self._posUpdate.Forward(longlat=[self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
87
+ else:
88
+ print("Error: wrong aoi id")
89
+
90
+ async def set_position_lane(self, lane_id:int, s:float=0.0, direction:Union[float, str]='front'):
91
+ """
92
+ - 将agent的位置设定到指定lane
93
+
94
+ Args:
95
+ - lane_id (int): Lane id
96
+ - s (float): distance from the start point of the lane, default None, if None, then set to the start point
97
+ - direction (Union[float, str]): agent方向角, 默认值为'front'
98
+ - float: 直接设置为给定方向角(atan2计算得到)
99
+ - str: 可选项['front', 'back'], 指定agent的行走方向
100
+ - 对于driving lane而言, 只能朝一个方向通行, 只能是'front'
101
+ - 对于walking lane而言, 可以朝两个方向通行, 可以是'front'或'back'
102
+ """
103
+ if lane_id in self._simulator.map.lanes:
104
+ if 'lane_position' in self.motion['position'].keys() and lane_id == self.motion['position']['lane_position']['lane_id']:
105
+ return
106
+ lane = self._simulator.map.lanes[lane_id]
107
+ if s > lane['length']:
108
+ print("Error: 's' too large")
109
+ self.motion['position'] = {}
110
+ self.motion['position']['lane_position'] = {'lane_id': lane_id, 's': s}
111
+ nodes = lane['center_line']['nodes']
112
+ x, y = get_xy_in_lane(nodes, s)
113
+ longlat = self._simulator.map.xy2lnglat(x=x, y=y)
114
+ self.motion['position']['longlat_position'] = {
115
+ 'longitude': longlat[0],
116
+ 'latitude': longlat[1]
117
+ }
118
+ self.motion['position']['xy_position'] = {
119
+ 'x': x,
120
+ 'y': y
121
+ }
122
+ if isinstance(direction, float):
123
+ self.motion['direction'] = direction
124
+ else:
125
+ # 计算方向角
126
+ direction_ = get_direction_by_s(nodes, s, direction)
127
+ self.motion['direction'] = direction_
128
+ # self._history_trajectory.append([self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
129
+ await self._posUpdate.Forward(longlat=[self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
130
+ else:
131
+ print("Error: wrong lane id")
132
+
133
+ async def set_position_poi(self, poi_id:int, hub:bool=True):
134
+ """
135
+ - 将agent的位置设定到指定poi
136
+
137
+ Args:
138
+ - poi_id (int): Poi id
139
+ """
140
+ if poi_id in self._simulator.map.pois:
141
+ poi = self._simulator.map.pois[poi_id]
142
+ aoi_id = poi['aoi_id']
143
+ if 'aoi_position' in self.motion['position'].keys() and aoi_id == self.motion['position']['aoi_position']['aoi_id']:
144
+ return
145
+ x = poi['position']['x']
146
+ y = poi['position']['y']
147
+ longlat = self._simulator.map.xy2lnglat(x=x, y=y)
148
+ self.motion['position'] = {}
149
+ self.motion['position']['aoi_position'] = {'aoi_id': aoi_id}
150
+ self.motion['position']['longlat_position'] = {
151
+ 'longitude': longlat[0],
152
+ 'latitude': longlat[1]
153
+ }
154
+ self.motion['position']['xy_position'] = {
155
+ 'x': x,
156
+ 'y': y
157
+ }
158
+ # self._history_trajectory.append([self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
159
+ if hub:
160
+ await self._posUpdate.Forward(longlat=[self.motion['position']['longlat_position']['longitude'], self.motion['position']['longlat_position']['latitude']])
161
+ else:
162
+ print("Error: wrong poi id")
83
163
 
84
164
  def Bind(self):
85
165
  """
@@ -0,0 +1,84 @@
1
+ """GroupAgent群体智能体"""
2
+
3
+ from typing import Union, Optional
4
+ from pycityagent.urbanllm import UrbanLLM
5
+ from .urbanllm import UrbanLLM
6
+ from .agent import Agent, AgentType
7
+ from .image.image import Image
8
+ from .ac.hub_actions import PositionUpdate
9
+ from .agent_func import FuncAgent
10
+ from .utils import *
11
+
12
+ class GroupAgent(Agent):
13
+ """
14
+ GroupAgent
15
+ 群体智能体
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ name: str,
21
+ soul: UrbanLLM = None,
22
+ simulator=None
23
+ ) -> None:
24
+ super().__init__(name, simulator.config['simulator']['server'], AgentType.Group, soul, simulator)
25
+ self.agents:list[FuncAgent] = []
26
+ """
27
+ Agent列表
28
+ """
29
+
30
+ def add_agents(self, agents:Optional[list[FuncAgent]]=None, ids: Optional[Union[int, list[int], tuple]]=None, number:Optional[int]=1):
31
+ """
32
+ 添加一个或多个智能体
33
+
34
+ Args:
35
+ - agents: FuncAgent列表
36
+ - ids: 智能体id
37
+ - int: 添加单个智能体
38
+ - list[int]: 添加多个智能体
39
+ - tuple(int, int): 根据范围确定添加智能体个数
40
+ - number: 智能体个数
41
+ - 与int类型ids参数配合使用
42
+ """
43
+ if agents != None:
44
+ self.agents = agents
45
+ elif isinstance(ids, int):
46
+ for i in range(number):
47
+ agent = FuncAgent(
48
+ f"{self._name}_{ids+i}",
49
+ ids+i,
50
+ self._simulator.config['simulator']['server'],
51
+ simulator=self._simulator
52
+ )
53
+ self.agents.append(agent)
54
+ elif isinstance(ids, list):
55
+ for id in ids:
56
+ agent = FuncAgent(
57
+ f"{self._name}_{id}",
58
+ id,
59
+ self._simulator.config['simulator']['server'],
60
+ simulator=self._simulator
61
+ )
62
+ self.agents.append(agent)
63
+ elif isinstance(ids, tuple):
64
+ if len(ids) == 2 and ids[0] <= ids[0]:
65
+ for i in range(ids[0], ids[1]+1):
66
+ agent = FuncAgent(
67
+ f"{self._name}_{i}",
68
+ i,
69
+ self._simulator.config['simulator']['server'],
70
+ simulator=self._simulator
71
+ )
72
+ self.agents.append(agent)
73
+ else:
74
+ raise Exception(f"Error: wrong id tuple: {ids}")
75
+ else:
76
+ raise Exception("Wrong parameter")
77
+
78
+ def ConnectToHub(self, config: dict):
79
+ for agent in self.agents:
80
+ agent.ConnectToHub(config)
81
+
82
+ def Bind(self):
83
+ for agent in self.agents:
84
+ agent.Bind()
@@ -18,6 +18,7 @@ class Brain:
18
18
  感知模块
19
19
  Sence module
20
20
  """
21
+
21
22
  self._memory = MemoryController(agent)
22
23
  """
23
24
  记忆模块
@@ -440,21 +440,21 @@ class WorkingMemory(WMemory):
440
440
  """
441
441
  self.sence = sence
442
442
  # * social message
443
- social_message = sence['social_messages']
444
- for message in social_message:
445
- print(message)
446
- from_id = message['from']
447
- content = message['message']
448
- if from_id in self.msg_agent_unhandle.keys():
449
- self.msg_agent_unhandle[from_id] += [{
450
- 'role': 'user',
451
- 'content': content
452
- }]
453
- else:
454
- self.msg_agent_unhandle[from_id] = [{
455
- 'role': 'user',
456
- 'content': content
457
- }]
443
+ # social_message = sence['social_messages']
444
+ # for message in social_message:
445
+ # print(message)
446
+ # from_id = message['from']
447
+ # content = message['message']
448
+ # if from_id in self.msg_agent_unhandle.keys():
449
+ # self.msg_agent_unhandle[from_id] += [{
450
+ # 'role': 'user',
451
+ # 'content': content
452
+ # }]
453
+ # else:
454
+ # self.msg_agent_unhandle[from_id] = [{
455
+ # 'role': 'user',
456
+ # 'content': content
457
+ # }]
458
458
  # * user message
459
459
  self.msg_user_unhandle = sence['user_messages']
460
460
 
@@ -329,7 +329,7 @@ class Scheduler(BrainFunction):
329
329
  self.schedule_set(True)
330
330
  else:
331
331
  # * 基本行程注册
332
- if self.base_schedule_index >=0 and self.base_schedule[self.base_schedule_index].time <= self._agent._simulator.time:
332
+ if self.base_schedule_index >=0 and len(self.base_schedule) > 0 and self.base_schedule[self.base_schedule_index].time <= self._agent._simulator.time:
333
333
  self.now = self.base_schedule[self.base_schedule_index]
334
334
  if 'aoi_position' in self._agent.motion['position'].keys() and self._agent.motion['position']['aoi_position']['aoi_id'] == self.now.target_id_aoi:
335
335
  # 直接跳过该行程