-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecosystem.py
executable file
·1583 lines (1260 loc) · 68 KB
/
ecosystem.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
from random import Random
from math import floor, log
from copy import copy
import types
import threading
#from pylab import *
import math
import numpy as np
import scipy.spatial
from web import Network
from individual import Individual
from configure import ROWS, COLUMNS, MAX_HABITATS, HABITATS, OCCUPIED_CELLS, LOST_HABITAT
from configure import MOVE_RADIUS, MOVE_RADIUS_MUTUALISTS, CAPTURE_PROB, REPRODUCTION_RATE
from configure import INVADER_NUMBER, DOUBLE_HERBIVORY, MATING_SPATIAL_RATIO, INMIGRATION
from configure import HABITAT_LOSS_TYPE, DISPERSAL_KERNEL, SPATIAL_VARIATION
class Ecosystem():
def __init__(self, network, drawing=False):
self.rnd = Random()
self.mutualists = set()
self.mutualistic_producers = set()
self.potential_invaders = []
for n in network.nodes(data=True):
if network.node[n[0]]['invader']:
self.potential_invaders.append(n)
network.remove_node(n[0])
else:
if network.node[n[0]]['mut']:
self.mutualists.add(n[0])
if network.node[n[0]]['mut_prod']:
self.mutualistic_producers.add(n[0])
self.net = network
self.world = []
self.species = self.net.nodes()
self.habitats = range(1,HABITATS+1)
self.habitats_dist = []
self.occupied_habitats = set()
self.realised_net = Network()
self.drawing = drawing
#if self.drawing:
#ion()
#self.fig = figure()
#self.sp_dist_fig = self.fig.add_subplot(111)
#self.sp_dist_plot = None
#self.fig_v = figure()
#self.sp_dist_fig_v = self.fig_v.add_subplot(111)
#self.sp_dist_plot_v = None
self.populations = dict.fromkeys(self.species, 0)
self.species_scl = self.net.get_trophic_levels()
self.new_inds_reproduction = dict.fromkeys(self.species, 0)
self.new_inds_inmigration = dict.fromkeys(self.species, 0)
self.dead_individuals = dict.fromkeys(self.species, 0)
self.species_removed = []
if SPATIAL_VARIATION:
self.centroids = dict.fromkeys(self.species, 0)
self.areas = dict.fromkeys(self.species, 0)
## store these as local data memebers to improve speed:
self.Edges = self.net.edges()# replaced all occurences-better? -- YES!
self.In_degrees = self.net.in_degree()
def initialise_world(self, homogeneous=False):
self._assign_species_habitats(type=2)
b, producers = self.net.basal()
if self.drawing:
Z = []
Z_v = []
if homogeneous:
original_set = set(copy(self.species))
original_set -= producers
ids = list(original_set)
if DOUBLE_HERBIVORY:
for n in self.species_scl.keys():
if self.species_scl[n] == 1:
ids.append(n)
original_pool = copy(ids)
prod_list = list(producers)
for i in range(ROWS):
row = []
dist_row = []
dist_row_v = []
for j in range(COLUMNS):
new_cell = Cell()
if self.rnd.random() <= OCCUPIED_CELLS:
species_id = self.rnd.choice(ids)
#this is done to ensure that all species in the pool are sampled
#are represented in the world by at least one individual
ids.remove(species_id)
if len(ids) == 0:
ids.extend(original_pool)
ind = Individual(species_id)
if species_id in self.mutualists:
ind.become_mutualist()
dist_row.append(max(self.species_scl.values())+1)
else:
dist_row.append(self.species_scl[species_id])
new_cell.visitor = ind
new_cell.habitat = self.rnd.choice(sorted(self.net.node[species_id]['habitats']))
prod_sp_id = self.rnd.choice(prod_list)
while new_cell.habitat not in self.net.node[prod_sp_id]['habitats']:
prod_sp_id = self.rnd.choice(prod_list)
ind_prod = Individual(prod_sp_id)
if prod_sp_id in self.mutualistic_producers:
ind_prod.become_mutualistic_producer()
new_cell.inhabitant = ind_prod
else:
#new_cell.habitat = self.rnd.choice(self.habitats)
prod_sp_id = self.rnd.choice(prod_list)
ind_prod = Individual(prod_sp_id)
if prod_sp_id in self.mutualistic_producers:
ind_prod.become_mutualistic_producer()
new_cell.inhabitant = ind_prod
new_cell.habitat = self.rnd.choice(sorted(self.net.node[prod_sp_id]['habitats']))
dist_row.append(-1)
row.append(new_cell)
dist_row_v.append(-1)
self.world.append(row)
if self.drawing:
Z.append(dist_row)
Z_v.append(dist_row_v)
self._get_species_per_habitat()
else:
self.create_continous_habitats()
dict_sp_habitats = self._get_species_per_habitat()
for i in range(ROWS):
dist_row = []
dist_row_v = []
for j in range(COLUMNS):
cell = self.world[i][j]
if len(dict_sp_habitats[cell.habitat]) == 0:
continue
#we populate the first layer of the world with primary producers
prod_sp_id = self.rnd.choice(dict_sp_habitats[cell.habitat])
while prod_sp_id not in producers:
prod_sp_id = self.rnd.choice(dict_sp_habitats[cell.habitat])
ind_prod = Individual(prod_sp_id)
if prod_sp_id in self.mutualistic_producers:
ind_prod.become_mutualistic_producer()
cell.inhabitant = ind_prod
#we then populate a fraction of the second layer of the world with species other than primary producers
if self.rnd.random() <= OCCUPIED_CELLS:
species_id = self.rnd.choice(dict_sp_habitats[cell.habitat])
while species_id in producers:
species_id = self.rnd.choice(dict_sp_habitats[cell.habitat])
ind = Individual(species_id)
if species_id in self.mutualists:
ind.become_mutualist()
dist_row.append(max(self.species_scl.values())+1)
else:
dist_row.append(self.species_scl[species_id])
cell.visitor = ind
else:
dist_row.append(-1)
dist_row_v.append(-1)
if self.drawing:
Z.append(dist_row)
Z_v.append(dist_row_v)
#if self.drawing:
#z = array(Z)
#self.sp_dist_plot = self.sp_dist_fig.pcolor(z, cmap='gist_rainbow', edgecolors='k', linewidths=0)
#z_v = array(Z_v)
#self.sp_dist_plot_v = self.sp_dist_fig_v.pcolor(z_v, cmap='gist_rainbow', edgecolors='k', linewidths=0)
#self.fig.canvas.draw()
#self.fig_v.canvas.draw()
def _get_species_per_habitat(self):
sp_habitats = dict.fromkeys(self.habitats)
for h in sp_habitats.keys():
sp_habitats[h] = []
for n,atts in self.net.nodes(data=True):
for h in atts['habitats']:
sp_habitats[h].append(n)
self.occupied_habitats.clear()
for h in sp_habitats.keys():
if len(sp_habitats[h]) > 0:
self.occupied_habitats.add(h)
return sp_habitats
def create_continous_habitats(self):
self._init_empty_cells()
cells_per_habitat = floor(float(ROWS*COLUMNS)/len(self.habitats))
for h in self.habitats:
cell_count = 0
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
while self.world[x_coord][y_coord].habitat != None:
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
self.world[x_coord][y_coord].habitat = h
cell_count = 1
x_count = 1
y_count = 0
x_next = 1
y_next = 1
x_offset = -1
y_offset = 1
while cell_count < cells_per_habitat:
if x_count > 0:
x_coord = (x_coord+x_offset)%ROWS
x_count -= 1
if x_count == 0:
x_next += 1
if x_offset == 1:
x_offset = -1
elif x_offset == -1:
x_offset = 1
y_count = y_next
elif y_count > 0:
y_coord = (y_coord+y_offset)%COLUMNS
y_count -= 1
if y_count == 0:
y_next += 1
if y_offset == 1:
y_offset = -1
elif y_offset == -1:
y_offset = 1
x_count = x_next
if self.world[x_coord][y_coord].habitat == None:
self.world[x_coord][y_coord].habitat = h
cell_count += 1
#this piece of code shows a plot displaying the initial arrangement of habitats
#in the ecosystem after initialising it using the algorithm above
# Z = []
# for i in range(ROWS):
# row = []
# for j in range(COLUMNS):
# if self.world[i][j].habitat == None:
# print 'This cell does not have habitat', i, j
# row.append(self.world[i][j].habitat)
# Z.append(array(row))
#
# z = array(Z)
#
# new_fig = figure()
# new_plot = new_fig.add_subplot(111)
# new_plot.pcolor(z, edgecolors='k', linewidths=1)
# draw()
#show()
def apply_habitat_loss(self, type=HABITAT_LOSS_TYPE):
cells_to_loose = floor((ROWS*COLUMNS)*LOST_HABITAT)
lost_habitat = 0
if type==1:
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
while not self.world[x_coord][y_coord].habitat in self.occupied_habitats:
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
self.world[x_coord][y_coord].habitat = lost_habitat
self.world[x_coord][y_coord].inhabitant = None
self.world[x_coord][y_coord].visitor = None
cells_lost = 1
x_count = 1
y_count = 0
x_next = 1
y_next = 1
x_offset = -1
y_offset = 1
while cells_lost < cells_to_loose:
if x_count > 0:
x_coord = (x_coord+x_offset)%ROWS
x_count -= 1
if x_count == 0:
x_next += 1
if x_offset == 1:
x_offset = -1
elif x_offset == -1:
x_offset = 1
y_count = y_next
elif y_count > 0:
y_coord = (y_coord+y_offset)%COLUMNS
y_count -= 1
if y_count == 0:
y_next += 1
if y_offset == 1:
y_offset = -1
elif y_offset == -1:
y_offset = 1
x_count = x_next
self.world[x_coord][y_coord].habitat = lost_habitat
self.world[x_coord][y_coord].inhabitant = None
self.world[x_coord][y_coord].visitor = None
cells_lost += 1
if type==2:
cells_lost = 0
#cells_deleted = []
while cells_lost < cells_to_loose:
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
while not self.world[x_coord][y_coord].habitat in self.occupied_habitats or self.world[x_coord][y_coord].habitat==lost_habitat:#(x_coord,y_coord) in cells_deleted:
x_coord = self.rnd.randint(0,ROWS-1)
y_coord = self.rnd.randint(0,COLUMNS-1)
self.world[x_coord][y_coord].habitat = lost_habitat
self.world[x_coord][y_coord].inhabitant = None
self.world[x_coord][y_coord].visitor = None
cells_lost += 1
#cells_deleted.append((x_coord,y_coord))
#the following piece of codes displays a figure showing what happens to the ecosystem
#habitats after the habitat loss event implement using the algorithm above
# Z = []
# for i in range(ROWS):
# row = []
# for j in range(COLUMNS):
# if self.world[i][j].habitat == None:
# print 'This cell does not have habitat', i, j
# row.append(self.world[i][j].habitat)
# Z.append(array(row))
#
# z = array(Z)
#
#
# new_fig = plt.figure()
# new_plot = new_fig.add_subplot(111)
# new_plot.pcolor(z, edgecolors='k', linewidths=1)
# plt.draw()
# #show()
#def draw_species_distribution(self):
# draw_thread = threading.Thread(target=self.threaded_drawing_sp_dist, args=(self.net, self.sp_dist_plot, self.world, self.species_scl))
# draw_thread.start()
#draw_thread.join()
# draw_thread2 = threading.Thread(target=self.threaded_drawing_sp_dist, args=(self.net, self.sp_dist_plot_v, self.world, self.species_scl, True))
# draw_thread2.start()
# self.fig.canvas.draw()
# self.fig_v.canvas.draw()
#def threaded_drawing_sp_dist(self, net, plot, world, scl_rank, visitor=False):
#Z = []
#for i in range(ROWS):
# row = []
# for j in range(COLUMNS):
# if visitor:
# if world[i][j].habitat == 0:
# row.append(-2)
# elif world[i][j].visitor == None:
# row.append(-1)
# else:
# if net.node[world[i][j].visitor.species_id].has_key('invader') and net.node[world[i][j].visitor.species_id]['invader']:
# row.append(max(scl_rank.values()) + 1)
# elif world[i][j].visitor.species_id in self.mutualists:
# row.append(max(scl_rank.values()) + 1)
# else:
# row.append(scl_rank[world[i][j].visitor.species_id])
# else:
# if world[i][j].habitat == 0:
# row.append(-2)
# elif world[i][j].inhabitant == None:
# row.append(-1)
# else:
# if net.node[world[i][j].inhabitant.species_id].has_key('invader') and net.node[world[i][j].inhabitant.species_id]['invader']:
# row.append(max(scl_rank.values()) + 1)
# elif world[i][j].inhabitant.species_id in self.mutualists:
# row.append(max(scl_rank.values()) + 1)
# elif world[i][j].inhabitant.species_id in self.mutualistic_producers:
# row.append(max(scl_rank.values()) + 2)
# else:
# row.append(scl_rank[world[i][j].inhabitant.species_id])
# Z.append(array(row))
#z = array(Z)
#z[1][1] = -2
#z[1][2] = -1
#z[1][3] = 0
#z[1][4] = 1
#z[1][5] = 2
#z[1][6] = 3
#z[1][7] = 4
#z[1][8] = 5
#plot.set_array(z.ravel())
#plot.autoscale()
def _init_empty_cells(self):
self.world = []
for i in range(ROWS):
row = []
for j in range(COLUMNS):
new_cell = Cell()
row.append(new_cell)
self.world.append(row)
def inmigration(self, cell):
inmigrant_sp = self.rnd.choice(self.species)
while inmigrant_sp in self.species_removed:
inmigrant_sp = self.rnd.choice(self.species)
sp_habitats = self.net.node[inmigrant_sp]['habitats']
#if the habitat available in the cell is not one of the species' do nothing
if not cell.habitat in sp_habitats:
return False
inmigrant = Individual(inmigrant_sp)
if inmigrant_sp in self.mutualists:
inmigrant.become_mutualist()
elif inmigrant_sp in self.mutualistic_producers:
inmigrant.become_mutualistic_producer()
if cell.inhabitant == None:
cell.inhabitant = inmigrant
self.new_inds_inmigration[inmigrant_sp] += 1
return True
else:
if self.In_degrees[inmigrant_sp] == 0:
return False
current_indiv = cell.inhabitant
if current_indiv.species_id == inmigrant_sp:
return False
if (current_indiv.species_id, inmigrant_sp) in self.Edges:
if self.In_degrees[current_indiv.species_id] == 0:
if cell.visitor == None:
if self.species_scl[inmigrant_sp] > 1:
inmigrant.eat(current_indiv, herbivorous=True, omnivore=True)
else:
inmigrant.eat(current_indiv, herbivorous=True)
cell.visitor = inmigrant
self._update_realised_network(current_indiv, inmigrant)
if inmigrant.mutualist:
inmigrant.set_mutualistic_partner(current_indiv)
self.new_inds_inmigration[inmigrant_sp] += 1
return True
else:
if self.rnd.random() < CAPTURE_PROB:
inmigrant.eat(current_indiv)
cell.inhabitant = inmigrant
self._update_realised_network(current_indiv, inmigrant)
self.dead_individuals[current_indiv.species_id] += 1
self.new_inds_inmigration[inmigrant_sp] += 1
return True
# elif (current_indiv.species_id, second_indiv.species_id) in self.Edges:
# if self.rnd.random() < CAPTURE_PROB:
# second_indiv.eat(current_indiv)
# self._update_realised_network(current_indiv, second_indiv)
# else:
# return
if self.In_degrees[inmigrant_sp] != 0:
if cell.visitor == None:
cell.visitor = inmigrant
self.new_inds_inmigration[inmigrant_sp] += 1
return True
else:
current_indiv = cell.visitor
if current_indiv.species_id == inmigrant_sp:
return False
if (current_indiv.species_id, inmigrant_sp) in self.Edges and self.rnd.random() < CAPTURE_PROB:
inmigrant.eat(current_indiv)
cell.visitor = inmigrant
self._update_realised_network(current_indiv, inmigrant)
self.dead_individuals[current_indiv.species_id] += 1
self.new_inds_inmigration[inmigrant_sp] += 1
return True
def update_world(self):
idx_col = self.rnd.randint(0,COLUMNS-1)
init_idx_col = idx_col
idx_row = self.rnd.randint(0,ROWS-1)
init_idx_row = idx_row
self.new_inds_reproduction = dict.fromkeys(self.species, 0)
self.new_inds_inmigration = dict.fromkeys(self.species, 0)
self.dead_individuals = dict.fromkeys(self.species, 0)
row_count = 0
for i in range(idx_row, ROWS):
if row_count > 0:
idx_col = 0
for j in range(idx_col, COLUMNS):
current_cell = self.world[i][j]
if self.rnd.random() < INMIGRATION:
self.inmigration(current_cell)
if current_cell.inhabitant == None and current_cell.visitor == None:
continue
else:
if current_cell.visitor != None:
if current_cell.inhabitant == None:
current_cell.inhabitant = current_cell.visitor
current_cell.visitor = None
else:
self._move_individual(i, j, True)
self._move_individual(i, j)
row_count += 1
row_count = 0
end_col = COLUMNS
for i in range(0, idx_row+1):
if row_count == init_idx_row:
end_col = init_idx_col
for j in range(0, end_col):
current_cell = self.world[i][j]
if self.rnd.random() < INMIGRATION:
self.inmigration(current_cell)
if current_cell.inhabitant == None and current_cell.visitor == None:
continue
else:
if current_cell.visitor != None:
if current_cell.inhabitant == None:
current_cell.inhabitant = current_cell.visitor
current_cell.visitor = None
else:
self._move_individual(i, j, True)
self._move_individual(i, j)
row_count += 1
def _move_individual(self, i, j, visitor=False):
current_cell = self.world[i][j]
if visitor:
current_indiv = current_cell.visitor
else:
current_indiv = current_cell.inhabitant
producer = False
if self.In_degrees[current_indiv.species_id] == 0:
if visitor:
print 'there is a producer in a visitor spot'
producer = True
if current_indiv.live(producer) == False:
self.dead_individuals[current_indiv.species_id] += 1
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
if current_cell.visitor != None:
current_cell.inhabitant = current_cell.visitor
current_cell.visitor = None
return
#if the individual is a mutualist cool off its efficiency
if current_indiv.mutualist and current_indiv.current_host != None:
current_indiv.mutualistic_cool_off()
#... and if it is in a cell with an empty space for producers... reproduce is mutualistic host
if not visitor and current_cell.visitor == None and self.rnd.random() < current_indiv.mut_efficiency and current_indiv.current_host != None:
current_cell.visitor = current_indiv
current_cell.inhabitant = Individual(current_indiv.current_host)
self.new_inds_reproduction[current_indiv.current_host] += 1
current_cell.inhabitant.become_mutualistic_producer()
current_indiv.reset_mutualistic_state()
return
#this is to state whether the current individual is a plant that can auto reproduce
auto_reproductive = False
#if the individual is a primary producer it cannot move, so, continue...
if producer:
current_indiv.synthesis() #... but it must feed
if not current_indiv.mutualistic_producer:
auto_reproductive = True
else:
return
else:
#here animals can reproduce. If the current individual do reproduces, then returns (it doesn't do anything else)
if self.sexual_reproduction(current_indiv, i, j):
# if visitor:
# print 'visitor reproducing', current_indiv.species_id
return
if current_indiv.mutualist:
new_idx_x = self.rnd.randint(-MOVE_RADIUS_MUTUALISTS, MOVE_RADIUS_MUTUALISTS)
new_idx_y = self.rnd.randint(-MOVE_RADIUS_MUTUALISTS, MOVE_RADIUS_MUTUALISTS)
else:
new_idx_x = self.rnd.randint(-MOVE_RADIUS, MOVE_RADIUS)
new_idx_y = self.rnd.randint(-MOVE_RADIUS, MOVE_RADIUS)
new_cell_x = (i+new_idx_x)%ROWS
new_cell_y = (j+new_idx_y)%COLUMNS
#if the cell is the same do nothing (stay)
if new_cell_x == i and new_cell_y == j:
return
new_cell = self.world[new_cell_x][new_cell_y]
sp_habitats = self.net.node[current_indiv.species_id]['habitats']
#if the habitat available in the cell is not one of the individuals' do nothing
if not new_cell.habitat in sp_habitats:
return
if new_cell.inhabitant == None and new_cell.visitor != None:
new_cell.inhabitant = new_cell.visitor
new_cell.visitor = None
#this is where the reproduction of primary producers (plants) occur
#if the current individual is a plant that can auto reproduce (wind dispersal) then...
if auto_reproductive:
if self.rnd.random() < REPRODUCTION_RATE:
if new_cell.inhabitant == None:
if current_indiv.mutualist:
print 'I am a mutualist auto reproducing'
new_cell.inhabitant = Individual(current_indiv.species_id)
self.new_inds_reproduction[current_indiv.species_id] += 1
elif new_cell.visitor == None and self.species_scl[new_cell.inhabitant.species_id] > 0:
new_cell.visitor = new_cell.inhabitant
new_cell.inhabitant = Individual(current_indiv.species_id)
self.new_inds_reproduction[current_indiv.species_id] += 1
return
if new_cell.inhabitant == None:
#if the current individual is a mutualist moving to an empty cell it can (depending on its
#mutualistic efficiency and the availability of space) facilitate the creation of a new
#individual of its previous host
if new_cell.visitor == None and current_indiv.mutualist and current_indiv.current_host != None and new_cell.habitat in self.net.node[current_indiv.current_host]['habitats'] and self.rnd.random() < current_indiv.mut_efficiency:
new_cell.inhabitant = Individual(current_indiv.current_host)
self.new_inds_reproduction[current_indiv.current_host] += 1
new_cell.inhabitant.become_mutualistic_producer()
current_indiv.reset_mutualistic_state()
new_cell.visitor = current_indiv
else:
new_cell.inhabitant = current_indiv
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
else:
if new_cell.visitor != None:
#no interactions involving plants are possible in the following case
second_indiv = new_cell.visitor
if (current_indiv.species_id, second_indiv.species_id) in self.Edges:
if self.rnd.random() < CAPTURE_PROB:
#print 'this is a carnivorous link between prey', current_indiv.species_id, 'and predator', second_indiv.species_id, 'new cell visitor not empty'
second_indiv.eat(current_indiv)
self._update_realised_network(current_indiv, second_indiv)
self.dead_individuals[current_indiv.species_id] += 1
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
elif (second_indiv.species_id, current_indiv.species_id) in self.Edges:
if self.rnd.random() < CAPTURE_PROB:
#print 'this is a carnivorous link between prey', second_indiv.species_id, 'and predator', current_indiv.species_id, 'the inhabitant eats the newcomer'
current_indiv.eat(second_indiv)
new_cell.visitor = None
new_cell.visitor = current_indiv
self._update_realised_network(second_indiv, current_indiv)
self.dead_individuals[second_indiv.species_id] += 1
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
else:
second_indiv = new_cell.inhabitant
#if the individuals belong to the same species they can either mate or,
#if they share a connection, one can eat the other
if second_indiv.species_id == current_indiv.species_id:
if (second_indiv.species_id, current_indiv.species_id) in self.Edges:
if self.rnd.random() < CAPTURE_PROB:
#print 'this is a cannibalistic link and hence a predator-prey interaction between', current_indiv.species_id
if self.rnd.random() < 0.5:
current_indiv.eat(second_indiv)
new_cell.inhabitant = current_indiv
self._update_realised_network(second_indiv, current_indiv)
self.dead_individuals[second_indiv.species_id] += 1
else:
second_indiv.eat(current_indiv)
self._update_realised_network(current_indiv, second_indiv)
self.dead_individuals[current_indiv.species_id] += 1
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
elif (second_indiv.species_id, current_indiv.species_id) in self.Edges:
#this is the only case in which the second individual may be a primary producer
#if the second individual is a primary producer it remains alive, although losing some resource
#and if the current individual is a mutualist it will record the second individual information
if self.In_degrees[second_indiv.species_id] == 0:
#print 'this is an herbivorous link between producer', second_indiv.species_id, 'and herbivore', current_indiv.species_id
if new_cell.visitor == None:
if self.species_scl[current_indiv.species_id] > 1:
current_indiv.eat(second_indiv, herbivorous=True, omnivore=True)
else:
current_indiv.eat(second_indiv, herbivorous=True)
new_cell.visitor = current_indiv
self._update_realised_network(second_indiv, current_indiv)
if current_indiv.mutualist:
current_indiv.set_mutualistic_partner(second_indiv)
else:
return
else:
#print 'this is a carnivorous link between prey', second_indiv.species_id, 'and predator', current_indiv.species_id, '(the visitor is the predator)'
if self.rnd.random() < CAPTURE_PROB:
current_indiv.eat(second_indiv)
new_cell.inhabitant = current_indiv
self._update_realised_network(second_indiv, current_indiv)
self.dead_individuals[second_indiv.species_id] += 1
else:
return
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
elif (current_indiv.species_id, second_indiv.species_id) in self.Edges:
if self.In_degrees[current_indiv.species_id] == 0 and self.species_scl[second_indiv.species_id] > 1:
print 'omnivore predator eating without paying omnivore penalty'
if self.rnd.random() < CAPTURE_PROB:
#print 'this is a carnivorous link between prey', current_indiv.species_id, 'and predator', second_indiv.species_id, 'the host is the predator'
second_indiv.eat(current_indiv)
self._update_realised_network(current_indiv, second_indiv)
self.dead_individuals[current_indiv.species_id] += 1
else:
return
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
else:
if new_cell.visitor == None and self.species_scl[current_indiv.species_id] != 0:
new_cell.visitor = current_indiv
if visitor:
current_cell.visitor = None
else:
current_cell.inhabitant = None
def sexual_reproduction(self, individual, i, j):
if not individual.ready_to_mate():
return False
x = (i-MATING_SPATIAL_RATIO)%ROWS
start_y = (j-MATING_SPATIAL_RATIO)%COLUMNS
mating_cell = None
partner = None
for x_offset in range(MATING_SPATIAL_RATIO*2):
x = (x+1)%ROWS
y = start_y
for y_offset in range(MATING_SPATIAL_RATIO*2):
y = (y+1)%COLUMNS
if x == i and y == j:
continue
temp_cell = self.world[x][y]
if mating_cell == None and (temp_cell.inhabitant == None or temp_cell.visitor == None): # and temp_cell.habitat in self.net.node[individual.species_id]['habitats']:
mating_cell = temp_cell
if partner == None:
if temp_cell.inhabitant != None and temp_cell.inhabitant.species_id == individual.species_id and temp_cell.inhabitant.ready_to_mate():
partner = temp_cell.inhabitant
elif temp_cell.visitor != None and temp_cell.visitor.species_id == individual.species_id and temp_cell.visitor.ready_to_mate():
partner = temp_cell.visitor
# print 'visitor chosen for reproduction', partner.species_id
if mating_cell != None and partner != None:
break
if mating_cell != None and partner != None:
newborn = Individual(individual.species_id)
self.new_inds_reproduction[individual.species_id] += 1
if individual.species_id in self.mutualists:
newborn.become_mutualist()
newborn.resource = (individual.reproduce() + partner.reproduce())*2
if mating_cell.inhabitant == None:
mating_cell.inhabitant = newborn
else:
mating_cell.visitor = newborn
return True
else:
return False
def _create_habitats_distribution(self):
largest_r = None
smallest_r = None
for n, atts in self.net.nodes(data=True):
if largest_r == None or atts['r'] > largest_r:
largest_r = atts['r']
if smallest_r == None or atts['r'] < smallest_r:
smallest_r = atts['r']
self.habitats_dist = []
self.habitats_dist.append(smallest_r)
for i in range(1,MAX_HABITATS):
self.habitats_dist.append( self.habitats_dist[i-1] + ((largest_r-self.habitats_dist[i-1])/2) )
self.habitats_dist.append(largest_r)
def _assign_species_habitats(self, type=1):
self._create_habitats_distribution()
if type == 1:
for n in self.net.nodes():
current_r = self.net.node[n]['r']
habitats_no = 1
for i in range(len(self.habitats_dist)):
if current_r >= self.habitats_dist[i] and current_r <= self.habitats_dist[i+1]:
break
habitats_no += 1
self.rnd.shuffle(self.habitats)
self.net.node[n]['habitats'] = set()
for i in range(habitats_no):
self.net.node[n]['habitats'].add(self.habitats[i])
elif type == 2:
producers = set()
for n in self.net.nodes():
if self.In_degrees[n] == 0:
current_r = self.net.node[n]['r']
habitats_no = 1
for i in range(len(self.habitats_dist)):
if current_r >= self.habitats_dist[i] and current_r <= self.habitats_dist[i+1]:
break
habitats_no += 1
self.net.node[n]['habitats'] = set()
if habitats_no == 1:
self.net.node[n]['habitats'].add(self.rnd.choice(self.habitats))
else:
self.rnd.shuffle(self.habitats)
for i in range(habitats_no):
self.net.node[n]['habitats'].add(self.habitats[i])
producers.add(n)
nodes = set(self.net.nodes())
nodes -= producers
nodes_sorted = sorted(nodes, self.compare_nodes_niches)
for n in nodes_sorted:
if not self.net.node[n].has_key('habitats'):
self._assign_node_habitats(n)
def _assign_node_habitats(self, n):
self.net.node[n]['habitats'] = set()
predecessors = sorted(self.net.predecessors(n), self.compare_nodes_niches)
for pre in predecessors:
if n == pre:
continue
if not self.net.node[pre].has_key('habitats'):
self._assign_node_habitats(pre)
self.net.node[n]['habitats'] |= self.net.node[pre]['habitats']
def _update_realised_network(self, prey, predator):
x=0
if not prey.species_id in self.realised_net.nodes():
node_data = self.net.node[prey.species_id]
self.realised_net.add_node(prey.species_id, attr_dict=node_data)
if not predator.species_id in self.realised_net.nodes():
node_data = self.net.node[predator.species_id]
self.realised_net.add_node(predator.species_id, attr_dict=node_data)
if not (prey.species_id, predator.species_id) in self.realised_net.edges():
self.realised_net.add_edge(prey.species_id, predator.species_id)
self.realised_net[prey.species_id][predator.species_id]['is'] = 1