-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualization_manager.py
More file actions
844 lines (710 loc) · 35.2 KB
/
Copy pathvisualization_manager.py
File metadata and controls
844 lines (710 loc) · 35.2 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
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
"""
This module works a helping module for the BioSim interface by providing necessary visualization
codes.
"""
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
import os
import subprocess
import warnings
__author__ = 'Mahrin Tasfe'
__email__ = 'mahrin.tasfe@nmbu.no'
_FFMPEG_BINARY = 'ffmpeg'
_MAGICK_BINARY = 'magick'
# update this to the directory and file-name beginning
# for the graphics files
_DEFAULT_GRAPHICS_NAME = 'bio_sim'
_DEFAULT_IMG_FORMAT = 'png'
_DEFAULT_MOVIE_FORMAT = 'mp4' # alternatives: mp4, gif
class Visualization:
""" Class for holding all the methods related to visualization."""
def __init__(self, island_obj, hist_specs, ymax_animals, cmax_animals,
img_dir, img_fmt, img_base=None):
"""
Constructor of the Visualization class. It gets its parameter values from the BioSim class.
Parameters
----------
island_obj : Island Object
It holds all the cells and information related to the island.
hist_specs : dict
hist_specs` is a dictionary with one entry per property for which a histogram
shall be shown. For each property, a dictionary providing the maximum value
and the bin width must be given.
ymax_animals : int
Number specifying y-axis limit for graph showing animal numbers.
cmax_animals : dict
Color-scale limits for animal densities.
img_dir : str
Path to directory for figures.
img_base : str
Beginning of file name for figures.
img_fmt : str
File type for figures, e.g. 'png' or 'pdf'.
"""
# Variables related to image save and update
self.img_base = img_base
if img_base is None:
self.img_name = _DEFAULT_GRAPHICS_NAME
else:
self.img_name = self.img_base
self.img_dir = img_dir
if img_dir is not None:
if '.' in self.img_dir:
self.img_base = os.getcwd() # Getting the current folder location
else:
path_for_making_directory = os.path.join('..', self.img_dir)
# Create a directory--if directory already exists, it does not overwrite
path = Path(path_for_making_directory)
if not path.exists():
path.mkdir()
self.img_base = path_for_making_directory
else:
self.img_base = None
self.img_fmt = img_fmt if img_fmt is not None else _DEFAULT_IMG_FORMAT
self.img_ctr = 0
self.img_step = 1
self.img_complete_path = None
# Setting up island object and island map size
self.island_obj = island_obj
# The following will be initialized by setup_graphics
self.fig = None
# Size of the island
# no_of_rows=y_axis=height of map
# no_of_cols=x_axis=width of map
self.x_axis = self.island_obj.island_size['col']
self.y_axis = self.island_obj.island_size['row']
# Variables for holding the island map and info bar
self.plot_island_map = None
self.plot_island_info_bar = None
# Suppress the warning related to set_ylim
warnings.filterwarnings("ignore", category=UserWarning)
# Limit of y-axis for the animal count plot
self.ymax_animals = ymax_animals
self.ymax_animals_offset = 0.09
# Variables for holding the line plot (animal count)
self.plot_animal_count = None
# Variables for holding the current year, herbivore count and carnivore count
self.plot_stat = None
# Variables for holding the density plots
self.plot_pop_density_herbivore = None
self.plot_pop_density_carnivore = None
self.img_axis_pop_density_Herbivore = None
self.img_axis_pop_density_Carnivore = None
self.carn_bar_flag = False
self.herb_bar_flag = False
# variable for color scale of heat map
self.cmax_animals = cmax_animals
# Variables for holding the plots of histograms
self.plot_hist_age = None
self.plot_hist_weight = None
self.plot_hist_fitness = None
# Variables related to the histogram
self.default_hist_specs = {'fitness': {'max': 1.0, 'delta': 0.05},
'weight': {'max': 80, 'delta': 2},
'age': {'max': 80, 'delta': 2}}
# By default, setting the hist specs to our chosen default_hist_specs
self.hist_specs = self.default_hist_specs
# If hist_specs is given, then going by each element of the given hist_specs
# and updating the self.hist_specs with the given hist values in place of the default one.
if hist_specs is not None:
for hist_type, hist_spec_vals_dict in hist_specs.items():
self.hist_specs[hist_type] = hist_spec_vals_dict
self.bin_max_fitness = self.hist_specs['fitness']['max']
self.bin_width_fitness = self.hist_specs['fitness']['delta']
self.bin_max_weight = self.hist_specs['weight']['max']
self.bin_width_weight = self.hist_specs['weight']['delta']
self.bin_max_age = self.hist_specs['age']['max']
self.bin_width_age = self.hist_specs['age']['delta']
self.bin_edges_age = None
self.bin_edges_weight = None
self.bin_edges_fitness = None
self.hist_step_weight_carn = None
self.hist_step_weight_herb = None
self.hist_step_fitness_carn = None
self.hist_step_fitness_herb = None
self.hist_step_patch_age_carn = None
self.hist_step_patch_age_herb = None
def plot_island_map_with_side_bar(self):
""" Plots the island with its landscape types."""
if self.plot_island_map is None:
self.plot_island_map = self.fig.add_subplot(3, 3, 1)
self.plot_island_info_bar = self.fig.add_subplot(3, 3, 2)
self.plot_island_info_bar.axis('off')
# Plotting the island map
# R G B
rgb_value = {'W': (0.0, 0.0, 1.0), # blue
'L': (0.0, 0.6, 0.0), # dark green
'H': (0.5, 1.0, 0.5), # light green
'D': (1.0, 1.0, 0.5)} # light yellow
island_map = self.island_obj.island_map_string
map_rgb = [[rgb_value[column] for column in row]
for row in island_map.splitlines()]
self.plot_island_map.imshow(map_rgb)
self.plot_island_map.set_xticks(range(0, self.x_axis, 5))
self.plot_island_map.set_xticklabels(range(0, self.x_axis, 5))
self.plot_island_map.set_yticks(range(0, self.y_axis, 5))
self.plot_island_map.set_yticklabels(range(0, self.y_axis, 5))
self.plot_island_map.set_title('Island', fontsize=10)
self.plot_island_map.set_xlabel('X-axis')
self.plot_island_map.set_ylabel('Y-axis')
# Plotting the info bar of map
self.plot_island_info_bar.text(x=0.5,
y=0.88,
s="Landscape Types",
ha='center',
va='center',
fontsize=10)
for ix, name in enumerate(('Water', 'Lowland',
'Highland', 'Desert')):
self.plot_island_info_bar.add_patch(plt.Rectangle(xy=(0., ix * 0.2),
width=0.3,
height=0.1,
edgecolor='none',
facecolor=rgb_value[name[0]]))
self.plot_island_info_bar.text(x=0.35,
y=ix * 0.2,
s=name,
transform=self.plot_island_info_bar.transAxes)
def plot_animal_count_line_plot(self, last_simulated_year, updated_pop_log):
"""
Setting the animal count line plot.
Parameters
----------
updated_pop_log : dataframe
Holds the population information of each year.
last_simulated_year: int
The year when the simulation will end.
"""
if self.plot_animal_count is None:
self.plot_animal_count = self.fig.add_subplot(3, 3, 3)
self.plot_animal_count.set_title('Animals Count', fontsize=10)
self.plot_animal_count.set_xlabel('Year')
self.plot_animal_count.set_ylabel('Population')
# Setting the ymax_animals
# If ymax_animals is not given, setting it with the max value
# of the current year's population
if self.ymax_animals is None:
self.ymax_animals = np.amax(updated_pop_log[-1:].values) + \
np.amax(updated_pop_log[-1:].values) * self.ymax_animals_offset
else:
self.ymax_animals = self.ymax_animals
self.plot_animal_count.set_ylim(0, self.ymax_animals)
# Setting up x-label animal count plot
self.plot_animal_count.set_xlim(0, last_simulated_year + 1)
# Plotting the line-plots
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Total'],
color='green')
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Herbivore'],
color='blue')
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Carnivore'],
color='red')
def update_animal_count(self, updated_pop_log):
"""
Updates the line-plots of herbivores and carnivores.
Parameters
----------
updated_pop_log : dataframe
Holds the population information of each year.
"""
# Setting the ymax_animals
# If the current year population max is greater than the previous one, then update
if np.amax(updated_pop_log[-1:].values) > self.ymax_animals:
self.ymax_animals = np.amax(updated_pop_log[-1:].values) + \
np.amax(updated_pop_log[-1:].values) * self.ymax_animals_offset
self.plot_animal_count.set_ylim(0, self.ymax_animals)
# Plotting the line-plots
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Total'],
color='green')
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Herbivore'],
color='blue', label='Herbivore')
self.plot_animal_count.plot(updated_pop_log['Year'], updated_pop_log['Carnivore'],
color='red', label='Carnivore')
plt.pause(0.03)
def plot_year_statistics(self):
"""
Setting the year population statistics plot.
"""
if self.plot_stat is None:
self.plot_stat = self.fig.add_subplot(3, 3, 6)
self.plot_stat.axis('off')
def update_year_statistics(self, current_year, herb_count, carn_count):
"""
Updates the year population statistics.
Parameters
----------
current_year : int
The current year of the simulation.
herb_count : int
Herbivore count of the current year.
carn_count : int
Carnivore count of the current year.
"""
# Clear previous text
self.plot_stat.cla()
self.plot_stat.axis('off')
# Setting the texts
self.plot_stat.text(x=0.2,
y=0.8,
s="Population statistics",
ha='left',
fontweight='bold',
va='center',
fontsize=10)
self.plot_stat.text(x=0.2,
y=0.6,
s="Year: " + str(current_year),
ha='left',
va='center',
fontsize=10)
total_pop = herb_count + carn_count
self.plot_stat.text(x=0.2, y=0.5,
s="Total population: " + str(total_pop),
ha='left',
va='center',
fontsize=10)
self.plot_stat.text(x=0.2, y=0.4,
s="Herbivore number: " + str(herb_count),
ha='left',
va='center',
fontsize=10)
self.plot_stat.text(x=0.2, y=0.3,
s="Carnivore number: " + str(carn_count),
ha='left',
va='center',
fontsize=10)
# Setting the patches for each text
self.plot_stat.add_patch(plt.Rectangle(xy=(0.08, 0.5),
width=0.1,
height=0.02,
edgecolor='none',
facecolor='green'))
self.plot_stat.add_patch(plt.Rectangle(xy=(0.08, 0.4),
width=0.1,
height=0.02,
edgecolor='none',
facecolor='blue'))
self.plot_stat.add_patch(plt.Rectangle(xy=(0.08, 0.3),
width=0.1,
height=0.02,
edgecolor='none',
facecolor='red'))
plt.pause(0.03)
def plot_animal_density_heat_map(self):
"""
Setting the animal density plots.
Notes
-----
- For writing this code, we used the reference: https://shorturl.at/gntRS
"""
if self.plot_pop_density_herbivore is None:
self.plot_pop_density_herbivore = self.fig.add_subplot(3, 3, 4)
self.plot_pop_density_herbivore.set_title('Herbivore Distribution', fontsize=10)
self.plot_pop_density_herbivore.set_xlabel('X-axis')
self.plot_pop_density_herbivore.set_ylabel('Y-axis')
self.plot_pop_density_herbivore.set_xticks(range(0, self.x_axis, 5))
self.plot_pop_density_herbivore.set_xticklabels(range(0, self.x_axis, 5))
self.plot_pop_density_herbivore.set_yticks(range(0, self.y_axis, 5))
self.plot_pop_density_herbivore.set_yticklabels(range(0, self.y_axis, 5))
self.img_axis_pop_density_Herbivore = None
if self.plot_pop_density_carnivore is None:
self.plot_pop_density_carnivore = self.fig.add_subplot(3, 3, 5)
self.plot_pop_density_carnivore.set_title('Carnivore Distribution', fontsize=10)
self.plot_pop_density_carnivore.set_xlabel('X-axis')
self.plot_pop_density_carnivore.set_ylabel('Y-axis')
self.img_axis_pop_density_Carnivore = None
self.plot_pop_density_carnivore.set_xticks(range(0, self.x_axis, 5))
self.plot_pop_density_carnivore.set_xticklabels(range(0, self.x_axis, 5))
self.plot_pop_density_carnivore.set_yticks(range(0, self.y_axis, 5))
self.plot_pop_density_carnivore.set_yticklabels(range(0, self.y_axis, 5))
def update_pop_density_herbivore(self, pop_density):
"""
Updates Herbivore density heat map.
Notes
-----
- For writing this code, we used the reference: https://shorturl.at/gntRS
Parameters
----------
pop_density : numpy
2D numpy array holds the number of Herbivores present in each cell of the island.
"""
# For putting in the heatmap color range.
# if cmax_animals given, using the even one,
# otherwise getting the values from density matrix.
if self.cmax_animals is not None:
v_max = self.cmax_animals['Herbivore']
v_min = 0
else:
v_max = np.amax(pop_density, axis=None)
v_min = 0
# Creating the heat map
self.img_axis_pop_density_Herbivore = self.plot_pop_density_herbivore.imshow(
pop_density, interpolation='nearest', vmin=v_min, vmax=v_max)
# Setting the color-bar only once and not updating it during entire simulation.
if v_max > 0 and not self.herb_bar_flag:
cbar = plt.colorbar(mappable=self.img_axis_pop_density_Herbivore,
ax=self.plot_pop_density_herbivore,
ticks=[0, v_max], orientation='vertical')
cbar.set_ticklabels(['min', 'max'])
self.herb_bar_flag = True
plt.pause(0.03)
def update_pop_density_carnivore(self, pop_density):
"""
Updates Carnivore density heat map.
Notes
-----
- For writing this code, we used the reference: https://shorturl.at/gntRS
Parameters
----------
pop_density : numpy
2D numpy array holds the number of Carnivores present in each cell of the island.
"""
# For putting in the heatmap color range.
# if cmax_animals given, using the even one,
# otherwise getting the values from density matrix.
if self.cmax_animals is not None:
v_max = self.cmax_animals['Carnivore']
v_min = 0
else:
v_max = np.amax(pop_density, axis=None)
v_min = 0
# Creating the heat map
self.img_axis_pop_density_Carnivore = self.plot_pop_density_carnivore.imshow(
pop_density,
interpolation='nearest',
vmin=v_min,
vmax=v_max)
# Setting the color-bar only once and not updating it during entire simulation.
if v_max > 0 and not self.carn_bar_flag:
cbar = plt.colorbar(mappable=self.img_axis_pop_density_Carnivore,
ax=self.plot_pop_density_carnivore,
ticks=[0, v_max],
orientation='vertical')
cbar.set_ticklabels(['min', 'max'])
self.carn_bar_flag = True
plt.pause(0.03)
def plot_histogram_fitness_func(self):
"""
Setting the histogram for showing the frequency of animals' fitnesses.
"""
if self.plot_hist_fitness is None:
# Creating plot
self.plot_hist_fitness = self.fig.add_subplot(3, 3, 7)
self.plot_hist_fitness.set_title('Fitness', fontsize=10)
self.plot_hist_fitness.set_xlabel('X-axis-fitness value')
self.plot_hist_fitness.set_ylabel('Y-axis-fitness frequency')
# Getting the current year's data
herb_fitnesses_island, carn_fitnesses_island = \
self.island_obj.get_animal_fitnesses_island()
# Calculating edges
self.bin_edges_fitness = np.arange(0,
self.bin_max_fitness + self.bin_width_fitness / 2,
self.bin_width_fitness)
# Creating blank place for array for storing data
# During each cycle, it will be updated with new data
hist_counts = np.zeros_like(self.bin_edges_fitness[:-1], dtype=float)
# Getting the StepPatch's using the stairs
self.hist_step_fitness_herb = self.plot_hist_fitness.stairs(
hist_counts,
edges=self.bin_edges_fitness,
color='b',
lw=2,
label='Herbivore')
self.hist_step_fitness_carn = self.plot_hist_fitness.stairs(
hist_counts,
edges=self.bin_edges_fitness,
color='r',
lw=2,
label='Carnivore')
# Getting the initial y_max (frequency height) from the data
hist_freq_herb, _ = np.histogram(herb_fitnesses_island,
bins=self.bin_edges_fitness)
hist_freq_carn, _ = np.histogram(carn_fitnesses_island,
bins=self.bin_edges_fitness)
# Setting the xlim and ylim
self.plot_hist_fitness.set_xlim([0, self.bin_max_fitness])
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_fitness.set_ylim([0, y_max])
self.plot_hist_fitness.legend()
def update_fitness_hist(self, herb_fitnesses_island, carn_fitnesses_island):
"""
Updates the histogram of fitness with the updated fitness values of the animals
present on the island in the current year.
Parameters
----------
herb_fitnesses_island : list
Hold the fitness information of all the herbivores present on the island.
carn_fitnesses_island : list
Hold the fitness information of all the Carnivores present on the island.
"""
# Getting the frequencies
hist_freq_herb, _ = np.histogram(herb_fitnesses_island, self.bin_edges_fitness)
hist_freq_carn, _ = np.histogram(carn_fitnesses_island, self.bin_edges_fitness)
# Setting the new data
self.hist_step_fitness_herb.set_data(hist_freq_herb)
self.hist_step_fitness_carn.set_data(hist_freq_carn)
# Updating the xlim, ylim according to the new data
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_fitness.set_ylim([0, y_max])
self.plot_hist_fitness.set_xlim([0, self.bin_max_fitness])
self.plot_hist_fitness.legend()
plt.pause(0.03)
def plot_histogram_age_func(self):
"""
Setting the histogram for showing the frequency of animal ages.
"""
# Creating plot
if self.plot_hist_age is None:
self.plot_hist_age = self.fig.add_subplot(3, 3, 8)
self.plot_hist_age.set_title('Age', fontsize=10)
self.plot_hist_age.set_xlabel('X-axis-age value')
self.plot_hist_age.set_ylabel('Y-axis-age frequency')
# Getting the current year's data
herb_ages_island, carn_ages_island = self.island_obj.get_animal_ages_island()
# Calculating edges
self.bin_edges_age = np.arange(0, self.bin_max_age + self.bin_width_age / 2,
self.bin_width_age)
# Creating blank place for array for storing data
# During each cycle, it will be updated with new data
hist_counts = np.zeros_like(self.bin_edges_age[:-1], dtype=float)
# Getting the StepPatch's using the stairs
self.hist_step_patch_age_herb = self.plot_hist_age.stairs(hist_counts,
edges=self.bin_edges_age,
color='b',
lw=2,
label='Herbivore')
self.hist_step_patch_age_carn = self.plot_hist_age.stairs(hist_counts,
edges=self.bin_edges_age,
color='r',
lw=2,
label='Carnivore')
# Getting the initial y_max (frequency height) from the data
hist_freq_herb, _ = np.histogram(herb_ages_island,
bins=self.bin_edges_age)
hist_freq_carn, _ = np.histogram(carn_ages_island,
bins=self.bin_edges_age)
# Setting the xlim and ylim
self.plot_hist_age.set_xlim([0, self.bin_max_age])
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_age.set_ylim([0, y_max])
self.plot_hist_age.legend()
def update_age_hist(self, herb_ages_island, carn_ages_island):
"""
Updates the histogram of age with the updated age values of the animals
present on the island in the current year.
Parameters
----------
herb_ages_island : list
Hold the age information of all the herbivores present on the island.
carn_ages_island: list
Hold the age information of all the Carnivores present on the island.
"""
# Getting the frequencies
hist_freq_herb, _ = np.histogram(herb_ages_island, self.bin_edges_age)
hist_freq_carn, _ = np.histogram(carn_ages_island, self.bin_edges_age)
# Setting the new data
self.hist_step_patch_age_herb.set_data(hist_freq_herb)
self.hist_step_patch_age_carn.set_data(hist_freq_carn)
# Updating the xlim, ylim according to the new data
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_age.set_ylim([0, y_max])
self.plot_hist_age.set_xlim([0, self.bin_max_age])
self.plot_hist_age.legend()
plt.pause(0.03)
def plot_histogram_weight_func(self):
"""
Setting the histogram for showing the frequency of animals' weights.
"""
if self.plot_hist_weight is None:
# Creating plot
self.plot_hist_weight = self.fig.add_subplot(3, 3, 9)
self.plot_hist_weight.set_title('Weight', fontsize=10)
self.plot_hist_weight.set_xlabel('X-axis-weight value')
self.plot_hist_weight.set_ylabel('Y-axis-weight frequency')
# Getting the current year's data
herb_weights_island, carn_weights_island = \
self.island_obj.get_animal_weights_island()
# Calculating edges
self.bin_edges_weight = np.arange(0,
self.bin_max_weight + self.bin_width_weight / 2,
self.bin_width_weight)
# Creating blank place for array for storing data
# During each cycle, it will be updated with new data
hist_counts = np.zeros_like(self.bin_edges_weight[:-1], dtype=float)
# Getting the StepPatch's using the stairs
self.hist_step_weight_herb = self.plot_hist_weight.stairs(
hist_counts,
edges=self.bin_edges_weight,
color='b',
lw=2,
label='Herbivore')
self.hist_step_weight_carn = self.plot_hist_weight.stairs(
hist_counts,
edges=self.bin_edges_weight,
color='r',
lw=2,
label='Carnivore')
# Getting the initial y_max (frequency height) from the data
hist_freq_herb, _ = np.histogram(herb_weights_island,
bins=self.bin_edges_weight)
hist_freq_carn, _ = np.histogram(carn_weights_island,
bins=self.bin_edges_weight)
# Setting the xlim and ylim
self.plot_hist_weight.set_xlim([0, self.bin_max_weight])
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_weight.set_ylim([0, y_max])
self.plot_hist_weight.legend()
def update_weight_hist(self, herb_weights_island, carn_weights_island):
"""
Updates the histogram of fitness with the updated fitness values of the animals
present on the island in the current year.
Parameters
----------
herb_weights_island : list
Hold the weight information of all the herbivores present on the island.
carn_weights_island : list
Hold the weight information of all the Carnivores present on the island.
"""
# Getting the frequencies
hist_freq_herb, _ = np.histogram(herb_weights_island, self.bin_edges_weight)
hist_freq_carn, _ = np.histogram(carn_weights_island, self.bin_edges_weight)
# Setting the new data
self.hist_step_weight_herb.set_data(hist_freq_herb)
self.hist_step_weight_carn.set_data(hist_freq_carn)
# Updating the xlim, ylim according to the new data
y_max = max(hist_freq_herb + hist_freq_carn) * 1.2
self.plot_hist_weight.set_ylim([0, y_max])
self.plot_hist_weight.set_xlim([0, self.bin_max_weight])
self.plot_hist_weight.legend()
plt.pause(0.03)
def make_movie(self, movie_fmt=None):
"""
Creates MPEG4 movie from visualization images saved.
.. :note:
Requires ffmpeg for MP4 and magick for GIF
The movie is stored as img_base + movie_fmt
"""
if self.img_base is None:
raise RuntimeError("No filename defined.")
if movie_fmt is None:
movie_fmt = _DEFAULT_MOVIE_FORMAT
path_video = os.path.join(self.img_base, self.img_name)
# print("location of finding image", path_video)
if movie_fmt == 'mp4':
try:
# Parameters chosen according to http://trac.ffmpeg.org/wiki/Encode/H.264,
# section "Compatibility"
subprocess.check_call([_FFMPEG_BINARY,
'-i', '{}_%05d.png'.format(path_video),
'-y',
'-profile:v', 'baseline',
'-level', '3.0',
'-pix_fmt', 'yuv420p',
'{}.{}'.format(path_video, movie_fmt)])
except subprocess.CalledProcessError as err:
raise RuntimeError('ERROR: ffmpeg failed with: {}'.format(err))
elif movie_fmt == 'gif':
try:
subprocess.check_call([_MAGICK_BINARY,
'-delay', '1',
'-loop', '0',
'{}_*.png'.format(path_video),
'{}.{}'.format(path_video, movie_fmt)])
except subprocess.CalledProcessError as err:
raise RuntimeError('ERROR: convert failed with: {}'.format(err))
else:
raise ValueError('Unknown movie format: ' + movie_fmt)
def save_graphics(self, current_year):
"""
Saves graphics to file if img_dir is given.
For writing to the file, both the img_dir and the img_base must be string.
If both are none, this method do not further execute.
Parameters
----------
current_year : int
The current year of the simulation.
Returns
-------
None
if img_dir or the img_base is None.
"""
if self.img_base is None or current_year % self.img_step != 0:
return
image_name_format = '{base}_{num:05d}.{type}'.format(base=self.img_name,
num=self.img_ctr,
type=self.img_fmt)
complete_path_with_name_fmt = os.path.join(self.img_base, image_name_format)
plt.savefig(complete_path_with_name_fmt)
self.img_ctr += 1
def setup_graphics(self, last_simulated_year, updated_pop_log):
"""
Creates subplots and the initial structure of individual plots with the
initial data.
Parameters
----------
updated_pop_log : dataframe
Holds the population information of each year.
last_simulated_year: int
The year when the simulation will end.
"""
# Without this, if simulation() is called several times, initial structure will be lost
if self.fig is None:
self.fig = plt.figure(figsize=(14, 7)) # Width=14, height=7
# Setting the initial structure of each subplot
self.plot_island_map_with_side_bar()
self.plot_animal_count_line_plot(last_simulated_year=last_simulated_year,
updated_pop_log=updated_pop_log)
self.plot_year_statistics()
self.plot_animal_density_heat_map()
self.plot_histogram_fitness_func()
self.plot_histogram_weight_func()
self.plot_histogram_age_func()
# Automatically adjusting the positions of subplots and other elements within a
# figure to eliminate overlapping or excessive whitespace
self.fig.tight_layout()
def update_graphics(self, current_year, updated_pop_log, herb_density_matrix,
carn_density_matrix):
"""
Updates graphics with current data.
Parameters
----------
current_year : int
The current year of the simulation.
updated_pop_log : dataframe
Holds the population information of each year.
herb_density_matrix : numpy
2D numpy array holds the number of Herbivores present in each cell of the island.
carn_density_matrix : numpy
2D numpy array holds the number of Carnivores present in each cell of the island.
"""
# Getting the current year's population data
# herb_count = int(updated_pop_log[-1:]['Herbivore'])
# carn_count = int(updated_pop_log[-1:]['Carnivore'])
herb_count = int(updated_pop_log.iloc[-1]['Herbivore'])
carn_count = int(updated_pop_log.iloc[-1]['Carnivore'])
# Updating the animal count plot
self.update_animal_count(updated_pop_log=updated_pop_log)
# Updating the pop_statistics
self.update_year_statistics(
current_year=current_year,
herb_count=herb_count,
carn_count=carn_count)
# Updating the density plots
self.update_pop_density_herbivore(herb_density_matrix)
self.update_pop_density_carnivore(carn_density_matrix)
# Updating the histograms plots
herb_ages_island_current_year, \
carn_ages_island_current_year = self.island_obj.get_animal_ages_island()
self.update_age_hist(herb_ages_island_current_year,
carn_ages_island_current_year)
herb_weights_island_current_year, \
carn_weights_island_current_year = self.island_obj.get_animal_weights_island()
self.update_weight_hist(herb_weights_island_current_year,
carn_weights_island_current_year)
herb_fitnesses_island_current_year, \
carn_fitnesses_island_current_year = self.island_obj.get_animal_fitnesses_island()
self.update_fitness_hist(herb_fitnesses_island_current_year,
carn_fitnesses_island_current_year)
# Flushing all the events for viewing the image
self.fig.canvas.flush_events() # ensure every thing is drawn
plt.pause(0.03) # pause required to pass control to GUI