Skip to content

Commit 79a7b06

Browse files
committed
added parent class CellularAgent with a _random_move() private method
1 parent de3c224 commit 79a7b06

File tree

1 file changed

+21
-27
lines changed

1 file changed

+21
-27
lines changed

examples/virus_antibody/agents.py

Lines changed: 21 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,27 @@
99
from collections import deque
1010

1111
import numpy as np
12+
13+
sys.path.insert(0, os.path.abspath("../../../mesa"))
1214
from mesa.experimental.continuous_space import ContinuousSpaceAgent
1315

16+
class CellularAgent(ContinuousSpaceAgent) :
17+
def _random_move(self, speed=1):
18+
"""Random walk in a 2D space."""
19+
perturb = np.array(
20+
[
21+
self.random.uniform(-0.5, 0.5),
22+
self.random.uniform(-0.5, 0.5),
23+
]
24+
)
25+
self.direction = self.direction + perturb
26+
norm = np.linalg.norm(self.direction)
27+
if norm > 0:
28+
self.direction /= norm
29+
self.position += self.direction * speed
30+
1431

15-
class AntibodyAgent(ContinuousSpaceAgent):
32+
class AntibodyAgent(CellularAgent):
1633
"""An Antibody agent. They move randomly until they see a virus, go fight it.
1734
If they lose, stay KO for a bit, lose health and back to random moving.
1835
"""
@@ -113,17 +130,7 @@ def move(self):
113130

114131
# Random walk if no target
115132
elif target is None:
116-
perturb = np.array(
117-
[
118-
self.random.uniform(-0.5, 0.5),
119-
self.random.uniform(-0.5, 0.5),
120-
]
121-
)
122-
self.direction = self.direction + perturb
123-
norm = np.linalg.norm(self.direction)
124-
if norm > 0:
125-
self.direction /= norm
126-
new_pos = self.position + self.direction * self.speed
133+
self._random_move()
127134

128135
# Chase a valid virus target
129136
else:
@@ -161,7 +168,7 @@ def engage_virus(self, virus) -> str:
161168
return "ko"
162169

163170

164-
class VirusAgent(ContinuousSpaceAgent):
171+
class VirusAgent(CellularAgent):
165172
"""A virus agent: random movement, mutation, duplication, passive to antibodies."""
166173

167174
speed = 1
@@ -186,7 +193,7 @@ def __init__(
186193
def step(self):
187194
if self.random.random() < self.duplication_rate:
188195
self.duplicate()
189-
self.move()
196+
self._random_move()
190197

191198
def duplicate(self):
192199
VirusAgent(
@@ -209,17 +216,4 @@ def generate_dna(self, dna=None):
209216
dna[idx] = (dna[idx] - 1) % 10
210217
return dna
211218

212-
def move(self):
213-
# Random walk
214-
perturb = np.array(
215-
[
216-
self.random.uniform(-0.5, 0.5),
217-
self.random.uniform(-0.5, 0.5),
218-
]
219-
)
220-
self.direction = self.direction + perturb
221-
norm = np.linalg.norm(self.direction)
222-
if norm > 0:
223-
self.direction /= norm
224219

225-
self.position += self.direction * self.speed

0 commit comments

Comments
 (0)