-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPredatorPreyModel.py
More file actions
executable file
·377 lines (301 loc) · 11.7 KB
/
Copy pathPredatorPreyModel.py
File metadata and controls
executable file
·377 lines (301 loc) · 11.7 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 18 15:08:03 2020
Basic predator-prey agent based model.
Scheme:
1) Choose agent randomly
2) If prey -> move and reproduce with certain probability
3) If predator -> move -> if prey in vision, kill prey and reproduce
with certain probability. Else die with certain probability
@author: Jan-Hendrik Niemann
"""
from mesa import Model, Agent
from mesa.time import RandomActivation
from mesa.space import ContinuousSpace
from mesa.datacollection import DataCollector
class RandomWalker(Agent):
def __init__(self, unique_id, model, pos):
"""
Parameters
----------
pos : tuple
x and y coordinates.
"""
super().__init__(unique_id, model)
self.pos = pos
def move(self):
new_pos = (self.pos[0] + self.model.random.normalvariate(0, 1),
self.pos[1] + self.model.random.normalvariate(0, 1))
self.model.space.move_agent(self, new_pos)
class Prey(RandomWalker):
def __init__(self, unique_id, model, pos, reproduction_probability):
"""
Parameters
----------
pos : tuple
x and y coordinates.
reproduction_probability : float
Reproduction probability.
"""
super().__init__(unique_id, model, pos)
self.breed = 'Prey'
self.reproduction_probability = reproduction_probability
self.dead = False
def step(self):
# If dead, do not do anything
if self.dead:
return None
# Move randomly
self.move()
# Reproduce
if self.model.random.uniform(0, 1) < self.reproduction_probability:
x = self.model.random.uniform(0, self.model.width)
y = self.model.random.uniform(0, self.model.height)
if self.model.local_offspring:
x = self.model.random.normalvariate(self.pos[0], 1)
y = self.model.random.normalvariate(self.pos[1], 1)
offspring = Prey(self.model.next_id(),
self.model,
(x, y),
self.reproduction_probability)
self.model.space.place_agent(offspring, (x, y))
self.model.schedule.add(offspring)
class Predator(RandomWalker):
def __init__(self, unique_id, model, pos, reproduction_probability, mortality, vision):
"""
Parameters
----------
pos : tuple
x and y coordinates.
reproduction_probability : float
Reproduction probability.
mortality : float
Probability of dying
vision : float
Vision radius for search for prey
"""
super().__init__(unique_id, model, pos)
self.breed = 'Predator'
self.vision = vision
self.reproduction_probability = reproduction_probability
self.mortality = mortality
self.dead = False
def step(self):
if self.dead:
return None
# Move randomly
self.move()
# Look
self.update_prey_in_vision()
# Kill prey
if self.prey_in_vision:
prey = self.prey_in_vision[self.random.randint(0, len(self.prey_in_vision) - 1)]
prey.dead = True
self.model.schedule.remove(prey)
self.model.space.remove_agent(prey)
# Reproduce
if self.model.random.uniform(0, 1) < self.reproduction_probability:
x = self.model.random.uniform(0, self.model.width)
y = self.model.random.uniform(0, self.model.height)
if self.model.local_offspring:
x = self.model.random.normalvariate(self.pos[0], 1)
y = self.model.random.normalvariate(self.pos[1], 1)
offspring = Predator(self.model.next_id(),
self.model, (x, y),
self.reproduction_probability,
self.mortality,
self.vision)
self.model.space.place_agent(offspring, (x, y))
self.model.schedule.add(offspring)
# Die
elif not self.prey_in_vision and self.model.random.uniform(0, 1) < self.mortality:
self.dead = True
self.model.schedule.remove(self)
self.model.space.remove_agent(self)
def update_prey_in_vision(self):
self.neighbors = self.model.space.get_neighbors(self.pos,
radius=self.vision)
self.prey_in_vision = []
for agent in self.neighbors:
if agent.breed == 'Prey' and agent.dead is False:
self.prey_in_vision.append(agent)
class PredatorPreyModel(Model):
def __init__(self,
height=100,
width=100,
init_prey=100,
prey_reproduction=0.03,
init_predator=10,
predator_vision=1,
predator_reproduction=0.5,
predator_death=0.02,
local_offspring=False,
max_iters=500,
seed=None):
super().__init__()
self.height = height
self.width = width
self.init_prey = init_prey
self.prey_reproduction = prey_reproduction
self.init_predator = init_predator
self.predator_vision = predator_vision
self.predator_reproduction = predator_reproduction
self.predator_death = predator_death
self.local_offspring = local_offspring
self.iteration = 0
self.max_iters = max_iters
self.schedule = RandomActivation(self)
self.space = ContinuousSpace(height, width, torus=True)
model_reporters = {
'Prey': lambda model: self.count('Prey'),
'Predator': lambda model: self.count('Predator'),
}
self.datacollector = DataCollector(model_reporters=model_reporters)
# Place prey
for i in range(self.init_prey):
x = self.random.uniform(0, self.width)
y = self.random.uniform(0, self.height)
# next_id() starts at 1
prey = Prey(self.next_id(), self, (x, y), self.prey_reproduction)
self.space.place_agent(prey, (x, y))
self.schedule.add(prey)
# Place predators
for i in range(self.init_predator):
x = self.random.uniform(0, self.width)
y = self.random.uniform(0, self.height)
predator = Predator(self.next_id(),
self,
(x, y),
self.predator_reproduction,
self.predator_death,
self.predator_vision)
self.space.place_agent(predator, (x, y))
self.schedule.add(predator)
self.running = True
self.datacollector.collect(self)
def step(self):
"""
Advance the model by one step and collect data.
Returns
-------
None.
"""
self.schedule.step()
self.iteration += 1
self.datacollector.collect(self)
# Stop system if maximum of iterations is reached
if self.iteration > self.max_iters:
self.running = False
return None
def count(self, breed):
"""
Count agent by breed.
Parameters
----------
breed : string
Breed of agent Can be 'Prey' or 'Predator'.
Returns
-------
count : int
Number of agents of type breed.
"""
count = 0
for agent in self.schedule.agents:
if agent.breed == breed:
count += 1
if breed == 'Predator' and count == 0:
self.running = False
return count
def warm_up(self):
for agent in self.schedule.agents:
if agent.breed == 'Prey':
continue
neighbors = self.space.get_neighbors(agent.pos, radius=agent.vision)
for prey in neighbors:
if prey.breed == 'Prey':
x = self.random.uniform(0, self.width)
y = self.random.uniform(0, self.height)
self.space.move_agent(prey, (x, y))
# %%
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
# Parameter setting
height = 100
width = 100
init_prey = 200
prey_reproduction = 0.03
init_predator = 20
predator_vision = 3
predator_reproduction = 0.5
predator_death = 0.02
iters = 1000
local_offspring = False
seed = 0
PPM = PredatorPreyModel(height=height,
width=width,
init_prey=init_prey,
prey_reproduction=prey_reproduction,
init_predator=init_predator,
predator_vision=predator_vision,
predator_reproduction=predator_reproduction,
predator_death=predator_death,
local_offspring=local_offspring,
max_iters=iters,
seed=seed)
# %% Run model
start = time.time()
PPM.run_model()
stop = time.time()
# Get simulation data
model_out = PPM.datacollector.get_model_vars_dataframe()
trajectory = model_out.to_numpy()
print('\nElapsed time: %.4f seconds\n' % (stop - start))
# %% Plot model
fig = plt.figure()
plt.step(np.linspace(0, trajectory.shape[0], trajectory.shape[0]), trajectory[:, 0], color='g')
plt.step(np.linspace(0, trajectory.shape[0], trajectory.shape[0]), trajectory[:, 1], color='r')
plt.legend(('Prey', 'Predator'))
plt.xlabel('Time $t$')
plt.ylabel('Number of agents')
fig = plt.figure()
plt.plot(trajectory[:, 0], trajectory[:, 1], c='k')
plt.xlabel('Number of prey')
plt.ylabel('Number of predators')
# %% Animate model
PPM = PredatorPreyModel(height=height,
width=width,
init_prey=init_prey,
prey_reproduction=prey_reproduction,
init_predator=init_predator,
predator_vision=predator_vision,
predator_reproduction=predator_reproduction,
predator_death=predator_death,
local_offspring=local_offspring,
max_iters=iters,
seed=seed)
fig, ax = plt.subplots(figsize=(6, 6))
def update(idx):
fig.clf()
PPM.step()
num_prey = PPM.count('Prey')
num_predator = PPM.count('Predator')
for agent in PPM.schedule.agents:
x, y = agent.pos
if agent.breed == 'Prey':
plt.plot(x, y, marker='.', c='g', markersize=10)
if agent.breed == 'Predator':
plt.plot(x, y, marker='.', c='r', markersize=10)
circle = plt.Circle((x, y), predator_vision, color='r', fill=True, alpha=0.2)
fig.gca().add_artist(circle)
plt.xlim([0, 100])
plt.ylim([0, 100])
plt.title('Prey ' + str(num_prey) + '\nPredators ' + str(num_predator))
ani = animation.FuncAnimation(fig,
update,
repeat=False,
interval=10,
frames=np.arange(1, iters, 1))