-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsbehaviors.py
1976 lines (1627 loc) · 66.5 KB
/
sbehaviors.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Defines all the primitive behaviors for the agents.
This file name is sbehaviors coz `s` stands for swarms.
"""
import numpy as np
from py_trees.trees import BehaviourTree
from py_trees.behaviour import Behaviour
from py_trees.composites import Sequence, Selector, Parallel
from py_trees import common, blackboard
import py_trees
from swarms.utils.distangle import get_direction, check_intersect
from swarms.lib.objects import Pheromones, Signal, Cue
import os
import matplotlib
# If there is $DISPLAY, display the plot
if os.name == 'posix' and "DISPLAY" not in os.environ:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class ObjectsStore:
"""Static class to search.
This class provides a find method to search through
Behavior Tree blackboard and agent content.
"""
@staticmethod
def find(blackboard_content, agent_content, name, agent_name):
"""Let this method implement search.
This method find implements a search through
blackboard dictionary. If the object is not found
in blackboard, then agent content is searched.
"""
try:
if name is not None:
objects = blackboard_content[name]
return list(objects)
else:
return list(blackboard_content.values())
except KeyError:
try:
objects = agent_content[name]
return list(objects)
except KeyError:
return []
class NeighbourObjects(Behaviour):
"""Sense behavior for the agents.
Inherits the Behaviors class from py_trees. This
behavior implements the sense function for the agents. This allows
the agents to sense the nearby environment based on the their
sense radius.
"""
def __init__(self, name):
"""Init method for the sense behavior."""
super(NeighbourObjects, self).__init__(name)
def setup(self, timeout, agent, item):
"""Have defined the setup method.
This method defines the other objects required for the
behavior. Agent is the actor in the environment,
item is the name of the item we are trying to find in the
environment and timeout defines the execution time for the
behavior.
"""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.WRITE)
def initialise(self):
"""Everytime initialization. Not required for now."""
pass
def receive_signals(self):
"""Receive signals from other agents.
Since this is the primary behavior for the agents to sense
the environment, we include the receive signal method here.
The agents will be able to
sense the environment and check if
it receives any signals from other agents.
"""
def update(self):
"""
Sense the neighborhood.
This method gets the grid values based on the current location and
radius. The grids are used to search the environment. If the agents
find any objects, it is stored in the behavior tree blackboard which
is a dictionary with sets as values.
"""
# if self.item is None:
# grids = self.agent.model.grid.get_neighborhood(
# self.agent.location, self.agent.radius*4)
# else:
grids = self.agent.model.grid.get_neighborhood(
self.agent.location, 1)
objects = self.agent.model.grid.get_objects_from_list_of_grid(
self.item, grids)
# Need to reset blackboard contents after each sense
self.blackboard.neighbourobj = dict()
if len(objects) >= 1:
if self.agent in objects:
objects.remove(self.agent)
if len(objects) >= 1:
for item in objects:
name = type(item).__name__
# Is the item is not carrable, its location
# and property doesnot change. So we can commit its
# information to memory
# if item.carryable is False and item.deathable is False:
if name in ['Sites', 'Hub', 'Boundary']:
try:
self.agent.shared_content[name].add(item)
except KeyError:
self.agent.shared_content[name] = {item}
else:
# name = name + str(self.agent.name)
try:
self.blackboard.neighbourobj[name].add(item)
except KeyError:
self.blackboard.neighbourobj = dict()
self.blackboard.neighbourobj[name] = {item}
return common.Status.SUCCESS
else:
return common.Status.FAILURE
else:
return common.Status.FAILURE
class NeighbourObjectsDist(Behaviour):
"""Sense behavior for the agents.
Inherits the Behaviors class from py_trees. This
behavior implements the sense function for the agents. This allows
the agents to sense the nearby environment based on the their
sense radius.
"""
def __init__(self, name):
"""Init method for the sense behavior."""
super(NeighbourObjectsDist, self).__init__(name)
def setup(self, timeout, agent, item):
"""Have defined the setup method.
This method defines the other objects required for the
behavior. Agent is the actor in the environment,
item is the name of the item we are trying to find in the
environment and timeout defines the execution time for the
behavior.
"""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.WRITE)
def initialise(self):
"""Everytime initialization. Not required for now."""
pass
def receive_signals(self):
"""Receive signals from other agents.
Since this is the primary behavior for the agents to sense
the environment, we include the receive signal method here.
The agents will be able to
sense the environment and check if
it receives any signals from other agents.
"""
def update(self):
"""
Sense the neighborhood.
This method gets the grid values based on the current location and
radius. The grids are used to search the environment. If the agents
find any objects, it is stored in the behavior tree blackboard which
is a dictionary with sets as values.
"""
# if self.item is None:
# grids = self.agent.model.grid.get_neighborhood(
# self.agent.location, self.agent.radius*4)
# else:
# grids = self.agent.model.grid.get_neighborhood(
# self.agent.location, self.agent.radius)
grids = set()
# for i in range(1, self.agent.model.grid.grid_size):
status = common.Status.FAILURE
# Need to reset blackboard contents after each sense
self.blackboard.neighbourobj = dict()
for i in range(0, self.agent.radius):
x = int(self.agent.location[0] + np.cos(
self.agent.direction) * i)
y = int(self.agent.location[1] + np.sin(
self.agent.direction) * i)
new_location, direction = self.agent.model.grid.check_limits(
(x, y), self.agent.direction)
# grids += self.agent.model.grid.get_neighborhood(new_location, 1)
limits, grid = self.agent.model.grid.find_grid(new_location)
grids.add(grid)
# print(self.agent.name, grid, self.name, round(self.agent.direction, 2), self.id, limits)
# objects = self.agent.model.grid.get_objects(
# self.item, grid)
objects = self.agent.model.grid.get_objects_from_list_of_grid(
self.item, list(grids)
)
# print('nighbourdist', grid, objects, self.agent.location, (new_location), limits)
if len(objects) >= 1:
if self.agent in objects:
objects.remove(self.agent)
for item in objects:
name = type(item).__name__
# Is the item is not carrable, its location
# and property doesnot change. So we can commit its
# information to memory
# if item.carryable is False and item.deathable is False:
# name = name + str(self.agent.name)
if item.passable is False:
try:
self.blackboard.neighbourobj[name].add(item)
except KeyError:
self.blackboard.neighbourobj[name] = {item}
# if status == common.Status.SUCCESS:
# pass
# else:
status = common.Status.SUCCESS
return status
return status
class GoTo(Behaviour):
"""GoTo behavior for the agents.
Inherits the Behaviors class from py_trees. This
behavior implements the GoTo function for the agents. This allows
the agents direct towards the object they want to reach. This behavior
is only concerned with direction alignment not with movement.
"""
def __init__(self, name):
"""Init method for the GoTo behavior."""
super(GoTo, self).__init__(name)
# self.blackboard = Blackboard()
# self.blackboard.neighbourobj = dict()
def setup(self, timeout, agent, item):
"""Have defined the setup method.
This method defines the other objects required for the
behavior. Agent is the actor in the environment,
item is the name of the item we are trying to find in the
environment and timeout defines the execution time for the
behavior.
"""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Everytime initialization. Not required for now."""
pass
def update(self):
"""
Goto towards the object of interest.
This method uses the ObjectsStore abstract class to find the
objects sensed before and agent shared storage. If the agent
find the object of interst in the store then, direction to the
object of interest is computed and agent direction is set to that
direction.
"""
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)
if len(objects) > 0:
objects = self.agent.model.random.choice(objects)
else:
objects = objects[0]
self.agent.direction = get_direction(
objects.location, self.agent.location) % (2 * np.pi)
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior defined to move towards something
class Towards(Behaviour):
"""Towards behaviors.
Changes the direction to go towards the object.
"""
def __init__(self, name):
"""Initialize."""
super(Towards, self).__init__(name)
def setup(self, timeout, agent, item=None):
"""Setup."""
self.agent = agent
def initialise(self):
"""Pass."""
pass
def update(self):
"""Nothing much to do."""
return common.Status.SUCCESS
# Behavior defined to move away from something
class Away(Behaviour):
"""Away behavior."""
def __init__(self, name):
"""Initialize."""
super(Away, self).__init__(name)
def setup(self, timeout, agent, item=None):
"""Setup."""
self.agent = agent
def initialise(self):
"""Pass."""
pass
def update(self):
"""Compute direction and negate it."""
self.agent.direction = (self.agent.direction + np.pi) % (2 * np.pi)
return common.Status.SUCCESS
# Behavior defined for Randomwalk
class RandomWalk(Behaviour):
"""Random walk behaviors."""
def __init__(self, name):
"""Initialize."""
super(RandomWalk, self).__init__(name)
def setup(self, timeout, agent, item=None):
"""Setup."""
self.agent = agent
def initialise(self):
"""Pass."""
pass
def update(self):
"""Compute random direction and set it to agent direction."""
delta_d = self.agent.model.random.normal(0, .1)
self.agent.direction = (self.agent.direction + delta_d) % (2 * np.pi)
return common.Status.SUCCESS
class IsMoveable(Behaviour):
"""Check is the item is moveable."""
def __init__(self, name):
"""Initialize."""
super(IsMoveable, self).__init__(name)
# self.blackboard = Blackboard()
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Get the object and check its movelable property."""
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)
for obj in objects:
if not objects.moveable:
return common.Status.FAILURE
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior defined to move
class Move(Behaviour):
"""Actually move the agent.
Move the agent with any other object fully attached or
partially attached to the agent.
"""
def __init__(self, name):
"""Initialize."""
super(Move, self).__init__(name)
def setup(self, timeout, agent, item=None):
"""Setup."""
self.agent = agent
self.dt = 0.1
def initialise(self):
"""Pass."""
pass
def update_signals(self, old_loc, new_loc):
"""Signal also move along with agents.
Signal is created by the agent. It has certain broadcast radius. It
moves along with the agent. So this move behavior should also be
responsible to move the signals.
"""
try:
for signal in self.agent.signals:
if self.agent.model.grid.move_object(
old_loc, signal, new_loc):
pass
else:
return False
except IndexError:
pass
return True
def update_partial_attached_objects(self):
"""Move logic for partially attached objects."""
try:
for item in self.agent.partial_attached_objects:
accleration = self.agent.force / item.agents[self.agent]
velocity = (accleration * self.dt) / len(item.agents)
direction = self.agent.direction
"""
if np.cos(direction) > 0:
x = int(np.ceil(
item.location[0] + np.cos(direction) * velocity))
y = int(np.ceil(
item.location[1] + np.sin(direction) * velocity))
else:
x = int(np.floor(
item.location[0] + np.cos(direction) * velocity))
y = int(np.floor(
item.location[1] + np.sin(direction) * velocity))
"""
x = int(self.agent.location[0] + np.cos(
direction) * velocity)
y = int(self.agent.location[1] + np.sin(
direction) * velocity)
# object_agent = list(item.agents.keys())
# indx = self.agent.model.random.randint(0, len(object_agent))
# object_agent = object_agent[indx]
object_agent = self.agent
# new_location, direction
# = object_agent.model.grid.check_limits(
# (x, y), direction)
new_location = (x, y)
object_agent.model.grid.move_object(
item.location, item, new_location)
self.agent.direction = direction
item.location = new_location
return True
except (IndexError, ValueError):
return False
def update(self):
"""Move logic for agent and fully carried object."""
# Partially carried object
if not self.update_partial_attached_objects():
self.agent.accleration = self.agent.force / self.agent.get_weight()
self.agent.velocity = self.agent.accleration * 1.0
# print(self.agent.direction, self.agent.velocity, self.agent.location)
x = int(np.round(self.agent.location[0] + np.cos(
self.agent.direction) * self.agent.velocity))
y = int(np.round(self.agent.location[1] + np.sin(
self.agent.direction) * self.agent.velocity))
new_location, direction = self.agent.model.grid.check_limits(
(x, y), self.agent.direction)
# print('from move', self.name, self.agent.location, new_location, direction)
if self.agent.model.grid.move_object(
self.agent.location, self.agent, new_location):
# Now the agent location has been updated, update the signal grids
if not self.update_signals(self.agent.location, new_location):
return common.Status.FAILURE
self.agent.location = new_location
self.agent.direction = direction
# Full carried object moves along the agent
for item in self.agent.attached_objects:
item.location = self.agent.location
else:
return common.Status.FAILURE
else:
new_location = self.agent.partial_attached_objects[0].location
for agent in self.agent.partial_attached_objects[0].agents.keys():
if agent.model.grid.move_object(
agent.location, agent,
new_location):
agent.location = new_location
else:
return common.Status.FAILURE
# Now the agent location has been updated, update the signal grids
if not self.update_signals(self.agent.location, new_location):
return common.Status.FAILURE
return common.Status.SUCCESS
# Behavior define for donot move
class DoNotMove(Behaviour):
"""Stand still behaviors."""
def __init__(self, name):
"""Initialize."""
super(DoNotMove, self).__init__(name)
def setup(self, timeout, agent, item=None):
"""Setup."""
self.agent = agent
def initialise(self):
"""Pass."""
pass
def update(self):
"""Update agent moveable property."""
self.agent.moveable = False
return common.Status.SUCCESS
# Behavior to check carryable attribute of an object
class IsCarryable(Behaviour):
"""Check carryable attribute of the item."""
def __init__(self, name):
"""Initialize."""
super(IsCarryable, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Check carryable property."""
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)[0]
if objects.carryable:
return common.Status.SUCCESS
else:
return common.Status.FAILURE
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior to check carryable attribute of an object
class IsDropable(Behaviour):
"""Check dropable property."""
def __init__(self, name):
"""Initialize."""
super(IsDropable, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Check the dropable attribute."""
status = common.Status.FAILURE
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)
if len(objects) >= 1:
for obj in objects:
if status == common.Status.SUCCESS:
break
if objects.dropable:
status = common.Status.SUCCESS
return status
else:
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.SUCCESS
# Behavior define to check is the item is carrable on its own
class IsSingleCarry(Behaviour):
"""Single carry behavior."""
def __init__(self, name):
"""Initialize."""
super(IsSingleCarry, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Logic to check if the object can be carried by single agent."""
# Logic to carry
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)[0]
if objects.weight:
if self.agent.get_capacity() > objects.calc_relative_weight():
return common.Status.SUCCESS
else:
return common.Status.FAILURE
else:
return common.Status.FAILURE
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior define to check is the item is carrable on its own or not
class IsMultipleCarry(Behaviour):
"""Multiple carry behaviour."""
def __init__(self, name):
"""Initialize."""
super(IsMultipleCarry, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Logic for multiple carry by checking the weights."""
try:
# Logic to carry
# objects = self.blackboard.neighbourobj[self.thing].pop()
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)[0]
if objects.weight:
if self.agent.get_capacity() < objects.weight:
return common.Status.SUCCESS
else:
return common.Status.FAILURE
else:
return common.Status.FAILURE
except (AttributeError, IndexError):
return common.Status.FAILURE
class IsCarrying(Behaviour):
"""Condition check if the agent is carrying something."""
def __init__(self, name):
"""Initialize."""
super(IsCarrying, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
def initialise(self):
"""Pass."""
pass
def update(self):
"""Logic for object carrying check."""
try:
things = []
for item in self.agent.attached_objects:
things.append(type(item).__name__)
if self.item in set(things):
return common.Status.SUCCESS
else:
return common.Status.FAILURE
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior defined to drop the items currently carrying
# class Drop(Behaviour):
# """Drop behavior to drop items which is being carried."""
# def __init__(self, name):
# """Initialize."""
# super(Drop, self).__init__(name)
# def setup(self, timeout, agent, item):
# """Setup."""
# self.agent = agent
# self.item = item
# def initialise(self):
# """Pass."""
# pass
# def update(self):
# """Logic to drop the item."""
# try:
# # Get the objects from the actuators
# objects = list(filter(
# lambda x: type(x).__name__ == self.item,
# self.agent.attached_objects))[0]
# # Grid
# grid = self.agent.model.grid
# static_grids = grid.get_neighborhood(self.agent.location, 1)
# envobjects = self.agent.model.grid.get_objects_from_list_of_grid(None, static_grids)
# dropped = False
# for obj in envobjects:
# if type(obj).__name__ in ['Hub', 'Boundary', 'Obstacles']:
# dropped = True
# obj.dropped_objects.append(objects)
# self.agent.attached_objects.remove(objects)
# objects.agent_name = self.agent.name
# break
# if not dropped:
# self.agent.model.grid.add_object_to_grid(objects.location, objects)
# self.agent.attached_objects.remove(objects)
# objects.agent_name = self.agent.name
# # Temporary fix
# # Store the genome which activated the single carry
# # try:
# # # objects.phenotype['drop'] =
# # # self.agent.individual[0].phenotype
# # objects.phenotype = {
# # self.agent.individual[0].phenotype: self.agent.individual[
# # 0].fitness}
# # return common.Status.SUCCESS
# # except AttributeError:
# # pass
# # objects.agents.remove(self.agent)
# return common.Status.SUCCESS
# except (AttributeError, IndexError):
# return common.Status.FAILURE
class Drop(Behaviour):
"""Drop behavior to drop items which is being carried."""
def __init__(self, name):
"""Initialize."""
super(Drop, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
def initialise(self):
"""Pass."""
pass
def update(self):
"""Logic to drop the item."""
# try:
# Get the objects from the actuators
objects = list(filter(
lambda x: type(x).__name__ == self.item,
self.agent.attached_objects))[0]
# Grid
grid = self.agent.model.grid
static_grids = grid.get_neighborhood(self.agent.location, 1)
envobjects = self.agent.model.grid.get_objects_from_list_of_grid(
None, static_grids)
envobjects = [
e for e in envobjects if type(e).__name__.find('Agent')== -1]
unique_envobjs_name = set(
[type(
envobj).__name__ for envobj in envobjects])
# dropped = False
# print('drop mod', objects, unique_envobjs_name, envobjects)
## If attached object food, can't drop on boundary or obstacles
## If attached object debri, can't drop on hub
def drop(sobject, aobject):
sobject.dropped_objects.append(aobject)
self.agent.attached_objects.remove(aobject)
sobject.agent_name = self.agent.name
return True
if type(objects).__name__ == 'Food':
if (
('Boundary' in unique_envobjs_name) or (
'Obstacles' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Hub' in unique_envobjs_name) and (
'Debris' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Hub' in unique_envobjs_name) and (
'Debris' not in unique_envobjs_name)):
for envobj in envobjects:
if type(envobj).__name__ == 'Hub':
drop(envobj, objects)
return common.Status.SUCCESS
else:
self.agent.model.grid.add_object_to_grid(
objects.location, objects)
self.agent.attached_objects.remove(objects)
objects.agent_name = self.agent.name
return common.Status.SUCCESS
else:
if (
('Hub' in unique_envobjs_name) or (
'Obstacles' in unique_envobjs_name)):
return common.Status.FAILURE
elif (
('Boundary' in unique_envobjs_name)):
for envobj in envobjects:
if type(envobj).__name__ == 'Boundary':
drop(envobj, objects)
return common.Status.SUCCESS
else:
self.agent.model.grid.add_object_to_grid(
objects.location, objects)
self.agent.attached_objects.remove(objects)
objects.agent_name = self.agent.name
return common.Status.SUCCESS
# except (AttributeError, IndexError):
# return common.Status.FAILURE
class DropPartial(Behaviour):
"""Drop behavior for partially attached object."""
def __init__(self, name):
"""Initialize."""
super(DropPartial, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
def initialise(self):
"""Pass."""
pass
def update(self):
"""Logic to drop partially attached object."""
try:
objects = list(filter(
lambda x: type(x).__name__ == self.item,
self.agent.partial_attached_objects))[0]
objects.agents.pop(self.agent)
self.agent.partial_attached_objects.remove(objects)
# If the agent is last to drop reduce the size of the
# food to the half the size of the hub. This indicates
# that the food has been deposited to the hub
if len(objects.agents) == 0:
self.agent.model.grid.remove_object_from_grid(
objects.location, objects)
objects.radius = int(self.agent.model.hub.radius / 2)
objects.location = self.agent.model.hub.location
self.agent.model.grid.add_object_to_grid(
objects.location, objects)
try:
objects.phenotype = {
self.agent.individual[0].phenotype: self.agent.individual[
0].fitness}
return common.Status.SUCCESS
except AttributeError:
pass
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.FAILURE
# Behavior defined to carry the items found
class SingleCarry(Behaviour):
"""Carry behavior."""
def __init__(self, name):
"""Initialize."""
super(SingleCarry, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass
def update(self):
"""Carry logic to carry the object by the agent."""
try:
objects = ObjectsStore.find(
self.blackboard.neighbourobj, self.agent.shared_content,
self.item, self.agent.name)[0]
self.agent.attached_objects.append(objects)
self.agent.model.grid.remove_object_from_grid(
objects.location, objects)
objects.agent_name = self.agent.name
# Add the agent to the object dict
# objects.agents[self.agent] = self.agent.get_capacity()
# Temporary fix
# Store the genome which activated the single carry
# try:
# objects.phenotype = {
# self.agent.individual[0].phenotype: self.agent.individual[
# 0].fitness}
# except AttributeError:
# pass
return common.Status.SUCCESS
except (AttributeError, IndexError):
return common.Status.FAILURE
except ValueError:
self.agent.attached_objects.remove(objects)
return common.Status.FAILURE
class InitiateMultipleCarry(Behaviour):
"""Behavior to initiate multiple carry process."""
def __init__(self, name):
"""Initialize."""
super(InitiateMultipleCarry, self).__init__(name)
def setup(self, timeout, agent, item):
"""Setup."""
self.agent = agent
self.item = item
self.blackboard = blackboard.Client(name=str(agent.name))
self.blackboard.register_key(key='neighbourobj', access=common.Access.READ)
def initialise(self):
"""Pass."""
pass