-
Notifications
You must be signed in to change notification settings - Fork 0
/
first_model.f90
3239 lines (2338 loc) · 115 KB
/
first_model.f90
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
! This is the main code file for Hanif Kawousi's Msc-project.
! >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
! NOTE: This is the 2Gene Model WITH BACKGROUND MORTALITY AND RISK SIGNALLING
! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
!------------------------------------
!--------PARAMETER MODULE------------
!------------------------------------
module params
implicit none
! NON-OBJECT: change these to access or avoid data that will affect compilation.
logical, public, parameter :: IS_DEBUG_SCREEN = .FALSE.
logical, public, parameter :: IS_DEBUG_ARRAY_READ = .FALSE.
logical, public, parameter :: IS_SAVE_POPULATION = .TRUE.
logical, public, parameter :: IS_SAVE_POPULATION_GENES = .FALSE. !remember: IS_ZIP_DATA and IS_DEBUG_DATA must be .TRUE.
!Both must be the same: .TRUE. or .FALSE., otherwise error-message
logical, public, parameter :: IS_ZIP_DATA = .FALSE. ! compress large data before it takes a lot of space
logical, public, parameter :: IS_DEBUG_DATA= .FALSE. !Run all recording of a value at each timestep: weight, emotion_state, food_availability, food_eaten
character(*), public, parameter :: ZIP_PROG = 'gzip' !program can be changed in the future.
! Numerical code for missing value
real, parameter, public :: MISSING = -9999.0
integer, parameter, public :: UNDEFINED = -9999
! ============= BIRD ====================
integer, parameter, public :: HUNGER_MIN = 0, HUNGER_MAX = 10
integer, parameter, public :: FEAR_MIN = 0, FEAR_MAX = 10
real, parameter, public :: BIRD_INITIAL_WEIGHT = 10.0 !20 grams
real, parameter, public :: BIRD_MAXIMUM_WEIGHT_MULTIPLICATOR = 4 !The number we multiply initial weight with. This defines birds maximum weight.
real, parameter, public :: BIRD_MINIMUM_WEIGHT_MULTIPLICATOR = 0.4 !The number we multiply initial weight with. This defines birds minimum weight.
real, parameter, public :: WEIGHT_REDUCTION_CONSTANT = 0.0015 !Only for when the bird encounters predator, but escapes. The added stress of escape will manifest in excess weight reduction.
real, parameter, public :: METABOLIC_COST_CONSTANT = 0.0001 ! The cost of life to be multiplied with birds weight.
real, parameter, public :: FEAR_DECAY_RATE = 0.02 ! Adjust this value as needed
real, parameter, public :: FEAR_INCREMENT_AFTER_ATTACK = 0.3 !This is the increased fear of the bird in attack situations.
real, parameter, public :: HUNGER_PLASTICITY = 1 ! Param for variation in hunger between birds.
real, parameter, public :: FEAR_PLASTICITY = 1
real, parameter, public :: EXPLORATION_PROBABILITY = 0.001 !Should be between 0.0 and 1.0 (most likely below 0.1)
!params for fraction in fuction bird_eat_fraction_when_fear
real, parameter, public :: FRAC_S1_FEAR = 1 !max value
real, parameter, public :: FRAC_S2_FEAR = 0.3 !min val
real, parameter, public :: SIGM_K_FEAR= 1.75
!params for fraction in fuction bird_eat_fraction_when_hunger
real, parameter, public :: FRAC_S1_HUNGER = .95 !max value
real, parameter, public :: FRAC_S2_HUNGER = 0 !min val
real, parameter, public :: SIGM_K_HUNGER = 1.25
!bird limit_food_intake params:
real, parameter, public :: SIGMOID_STEEPNESS = 1
real, parameter, public :: SIGMOID_MIDPOINT = 0.5
real, parameter, public :: VIGILANCE_FACTOR = 0.015
! ========================================
! =========== PREDATOR ====================
real, parameter, public :: FREQUENCY_OF_PREDATOR_MIN = 0.01
real, parameter, public :: FREQUENCY_OF_PREDATOR_MAX = 0.15
! For signal generations only:
real, parameter, public :: FEAR_SIGNAL_MULTIPLIER = 6 ! if 1 then we are in evolutionary gens.
!parameter for predation_risk, risk of the bird to meet predator in a particular environment.
! if the bird sees the predator, the predator sees the bird.
!Is_Evolutionary_Gens == .TRUE. then:
! real, parameter, public :: ATTACK_RATE = 0.15!risk of bird being eaten by predator if attacked. 0.1 if Is_Evolutionary_Gens
!Is_Evolutionary_Gens == .FALSE. then:
real, parameter, public :: ATTACK_RATE = 0 !ecological experiment: predator attack switched off!
! ========================================
! =========== ENVIRONMENT ====================
integer, parameter, public :: ENVIRONMENT_SIZE = 100 !size of envornment, nr of cells = 100
real, parameter, public :: FOOD_AVAILABILITY_MEAN = 5, FOOD_AVAILABILITY_VARIANCE = 2 !parameter for food, measured in weight grams added to the birds mass
real, parameter, public :: FOOD_AVAILABILITY_MIN = 4, &
FOOD_AVAILABILITY_MAX = FOOD_AVAILABILITY_MEAN + FOOD_AVAILABILITY_VARIANCE
! ===========================================
!! =========== OUTPUT ====================
! File name that keeps all output data from all generations of the model
character(len=*), parameter, public :: MODEL_OUTPUT_FILE = "my_model_output_2G.csv"
character(len=*), parameter, public :: FOOD_PRED_DISTRIBUTION_FILE = "food_pred_distribution_2G.csv"
! =========================================
!!=== CREATING DIRECTORIES FOR OUTPUT FILES =====
character(*), parameter, public :: GENERATION_SUBFOLDER = "generations/"
character(*), parameter, public :: FACTOR_EXPERIMENT_SUBFOLDER = "factor_experiment/"
character(*), parameter, public :: WEIGHT_HISTORY_SUBFOLDER = "weight_history_2G/"
character(*), parameter, public :: EMOTION_STATE_SUBFOLDER = "emotion_history_2G/"
character(*), parameter, public :: EMOTION_GENE_SUBFOLDER = "gene_history_2G/"
!================================================
!======= READ "FACTOR" FILE FOR EXPERIMENT =======
character(len=*), parameter, public :: FACTOR_FILE = "signal_values.csv"
!=================================================
!=================== GA ===================
!Population size
integer, parameter, public :: GENERATIONS = 300
! 30 for testing, 300 for sim.
integer, parameter, public :: SIGNAL_ONLY_GENERATIONS = 10 !10 for testing fear only,
!5 for theoretical experiment with factor from file and no mutation.
!Generations for when attack_rate is turned off and only signal remains
integer, parameter, public :: EASY_GENERATIONS = 20 !10 for testing, 20 for sim
integer, parameter, public :: POP_SIZE = 10000
real, parameter, public :: GA_REPRODUCE_THRESHOLD = 0.75 !minimum fitness for reproduction
!Proportion of the best reproducing birds of selection
real, parameter :: GA_REPRODUCE_PR = 0.7
!exact number of birds reproducing
integer, parameter, public :: GA_REPRODUCE_N = int(POP_SIZE * GA_REPRODUCE_PR)
real, parameter, public :: GA_PROB_REPR_MAX = 0.85
real, parameter, public :: GA_PROB_REPR_MIN = 0.0
! integer, parameter, public :: NUM_EGGS_RANGE_MAX = 9
! integer, parameter, public :: NUM_EGGS_RANGE_MIN = 1
integer, parameter, public :: SELECTION_MULTIPLICATOR = 1
integer, parameter, public :: TOTAL_TIME_STEP = 365
real, parameter, public :: MUTATION_PROBABILITY = 0.01 !0.02 for evo, 0.0 when Is_Evolutionary_Generations is .not. and/or Is_Factor_Experiments = .TRUE.
real, parameter, public :: BACKGROUND_MORTALITY = 0.001 !if Is_Evolutionary_Generations = True
!Background mortality is a common word birds killed by events as disease, hostile weather-conditions, parasitism, etc...
!==========================================
!==================== Global Variables ===========================
integer, public :: Current_Generation
logical, public :: Is_Evolutionary_Generations
logical, public :: Is_Factor_Experiments = .FALSE. ! TRUE IF EXPERIMENT WITH FACTOR FROM EXTERNAL CSV FILE
character(len=:), allocatable, public :: Genome_File_Name
real, public :: Full_Pop_Factor
real, public :: Last_Full_Pop_Factor
! the real value one must multiply
! with survivors in order to return to POP_SIZE
! or size of the population at it's full.
! ================================================================
contains
!-----------------------------------------------------------------------------
!> Force a value within the range set by the vmin and vmax dummy parameter
!! values. If the value is within the range, it does not change, if it
!! falls outside, the output force value is obtained as
!! min( max( value, FORCE_MIN ), FORCE_MAX )
!! @param[in] value_in Input value for forcing transformation.
!! @param[in] vmin minimum value of the force-to range (lower limit), if
!! not present, a lower limit of 0.0 is used.
!! @param[in] vmax maximum value of the force-to range (upper limit)
!! @returns an input value forced to the range.
!! @note Note that this is the **real** precision version of the
!! generic `within` function.
elemental function within(value_in, vmin, vmax) result (value_out)
real, intent(in) :: value_in
real, optional, intent(in) :: vmin
real, intent(in) :: vmax
real :: value_out
! Local copies of optionals.
real :: vmin_here
! Check optional minimum value, if absent, set to a default value 0.0.
if (present(vmin)) then
vmin_here = vmin
else
vmin_here = 0.0
end if
value_out = min( max( value_in, vmin_here ), vmax )
end function within
!-----------------------------------------------------------------------------
!> @brief Rescale a real variable with the range A:B to have the new
!! range A1:B1.
!! @details Linear transformation of the input value `value_in` such
!! `k * value_in + beta`, where the `k` and `beta` coefficients
!! are found by solving a simple linear system:
!! @f$ \left\{\begin{matrix}
!! A_{1}= k \cdot A + \beta; \\
!! B_{1}= k \cdot B + \beta
!! \end{matrix}\right. @f$. It has this solution:
!! @f$ k=\frac{A_{1}-B_{1}}{A-B},
!! \beta=-\frac{A_{1} \cdot B-A \cdot B_{1}}{A-B} @f$
!! @warning The function does not check if `value_in` lies within [A:B].
!! @note Code for wxMaxima equation solve:
!! @code
!! solve( [A1=A*k+b, B1=B*k+b] ,[k,b] );
!! @endcode
elemental function rescale(value_in, A, B, A1, B1) result(rescaled)
real, intent(in) :: value_in
real, intent(in) :: A, B, A1, B1
real :: rescaled
! Local variables
real :: ck, cb
!> ### Implementation details ###
!> First, find the linear coefficients `ck` and `cb`
!! from the simple linear system.
ck = (A1-B1) / (A-B)
cb = -1.0 * ((A1*B - A*B1) / (A-B))
!> Second, do the actual linear rescale of the input value.
rescaled = value_in*ck + cb
end function rescale
!-----------------------------------------------------------------------------
!> Calculate an average value of a real array, excluding MISSING values.
!! @param vector_in The input data vector
!! @param missing_code Optional parameter setting the missing data code,
!! to be excluded from the calculation of the mean.
!! @param undef_ret_null Optional parameter, if TRUE, the function returns
!! zero rather than undefined if the sample size is zero.
!! @returns The mean value of the vector.
!! @note This is a real array version.
pure function average (array_in, missing_code, undef_ret_null) &
result (mean_val)
! @param vector_in The input data vector
real, dimension(:), intent(in) :: array_in
! @param missing_code Optional parameter setting the missing data code,
! to be excluded from the calculation of the mean.
real, optional, intent(in) :: missing_code
! @param undef_ret_null Optional parameter, if TRUE, the function returns
! zero rather than undefined if the sample size is zero.
logical, optional, intent(in) :: undef_ret_null
! @returns The mean value of the vector.
real :: mean_val
! Local missing code.
real :: missing_code_here
! Local sample size, N of valid values.
integer :: count_valid
! Define high precision kind for very big value
integer, parameter :: HRP = selected_real_kind(33, 4931)
! Big arrays can result in huge sum values, to accommodate them,
! use commondata::hrp and commondata::long types
real(HRP) :: bigsum, bigmean
!> ### Implementation details ###
!> Check if missing data code is provided from dummy input.
!! If not, use global parameter.
if (present(missing_code)) then
missing_code_here = missing_code
else
missing_code_here = MISSING
end if
!> Fist, count how many valid values are there in the array.
count_valid = count(array_in /= missing_code_here)
!> If there are no valid values in the array, mean is undefined.
if (count_valid==0) then
if (present(undef_ret_null)) then
if (undef_ret_null) then
mean_val = 0.0 !> still return zero if undef_ret_null is TRUE.
else
mean_val = MISSING
end if
else
mean_val = MISSING
end if
return
end if
bigsum = sum( real(array_in, HRP), array_in /= missing_code_here )
bigmean = bigsum / count_valid
mean_val = real(bigmean)
end function average
! pure function update_pop_regain_size_factor(pop_survived, pop_full) result(Full_Pop_Factor)
! integer, dimension(:), intent(in) :: pop_survived
! real, dimension(:), intent(out) :: pop_full ! Assuming pop_full is meant to be returned as well
! real :: Full_Pop_Factor
!> Calculates the factor to regain the full population size from the survived population.
!!
!! This function takes the number of individuals that survived and the full population size,
!! and calculates the factor that can be used to scale up the survived population to the
!! full population size.
!!
!! @param pop_survived The number of individuals that survived.
!! @param pop_full The full population size.
!! @return The factor to scale up the survived population to the full population size.
pure function update_pop_regain_size_factor(pop_survived, pop_full) result(factor)
integer, intent(in) :: pop_survived
integer, intent(in) :: pop_full ! Assuming pop_full is meant to be returned as well
real :: factor
factor = real(pop_full) / real(pop_survived)
end function update_pop_regain_size_factor
!For finding probability of reproduction
!> Calculates the probability of reproduction for an individual based on its current
!! mass (m) and the mass thresholds for reproduction (m_0 and m_max).
!!
!! This function uses a linear interpolation between the minimum and maximum
!! probabilities of reproduction (GA_PROB_REPR_MIN and GA_PROB_REPR_MAX) to determine the probability of reproduction for the given mass.
!!
!! @param m The current mass of the individual.
!! @param m_0 The minimum mass threshold for reproduction.
!! @param m_max The maximum mass threshold for reproduction.
!! @return The probability of reproduction for the individual.
function prob_repr(m, m_0, m_max) result(prob)
real, intent(in) :: m, m_0, m_max
real :: prob
real :: k, b
real, parameter :: P = GA_PROB_REPR_MAX
real, parameter :: P_0 = GA_PROB_REPR_MIN
call solve_linear( k, b, m_0, P_0, m_max, P )
prob = k * m + b
prob = within(prob, P_0, P)
end function prob_repr
! General solver for linear equation
!
! Given the x_min, x_max and y_min y_max,
! determine the coefficients for the linear
! equation k and b
! y_max + *
! | * . y = k x + b
! | * . ? ?
! | * .
! y_min +-------+
! x_min x_max
!> Solves for the coefficients k and b of a linear equation y = kx + b,
!! given the minimum and maximum values of x and y.
!!
!! This subroutine takes the minimum and maximum values of x and y,
!! and calculates the coefficients k and b for the linear equation y = kx + b
!! that passes through those points.
!!
!! @param k The slope of the linear equation.
!! @param b The y-intercept of the linear equation.
!! @param x_min The minimum value of x.
!! @param y_min The minimum value of y.
!! @param x_max The maximum value of x.
!! @param y_max The maximum value of y.
pure subroutine solve_linear(k, b, x_min, y_min, x_max, y_max)
real, intent(out) :: k,b
real, intent(in) :: x_min, y_min, x_max, y_max
k = (y_min - y_max) / (x_min-x_max)
b = -1 * (x_max*y_min - x_min*y_max) / ( x_min - x_max )
end subroutine solve_linear
!function and subsequent subroutine for calculating median value.
! https://rosettacode.org/wiki/Averages/Median#Fortran
function median (array_in) result(median_value)
implicit none
real, dimension(:), intent(in) :: array_in
real, dimension(:), allocatable :: sorted_array
real :: median_value
integer :: i, n, mid
integer :: n_valid, index_valid
! make a smaller array from the input array that excludes missing values:
! Make size of sorted array to
!Copy array to avoid modifying original data
n_valid = 0
do i=1, size(array_in)
if (array_in(i) /= MISSING) n_valid = n_valid + 1
end do
allocate(sorted_array(n_valid))
index_valid = 0
do i=1, size(array_in)
if (array_in(i) /= MISSING) then
index_valid = index_valid + 1
sorted_array(index_valid) = array_in(i)
end if
end do
n = size(sorted_array)
call sort(sorted_array)
!Calculate the median
if (mod(n, 2) == 0) then
mid = n / 2
median_value = (sorted_array(mid) + sorted_array(mid + 1)) / 2.0
else
mid = (n + 1) / 2
median_value = sorted_array(mid)
end if
end function median
subroutine sort(array)
implicit none
real, intent(inout) :: array(:)
integer :: n
integer :: i, j
real :: temp
n = size(array)
! Making a bubble sort algorithm:
! Bubble sort algorithm, also known as sinking sort,
! is the simplest sorting algorithm that runs through the list repeatedly,
! compares adjacent elements, and swaps them if they are out of order.
! Code inspired by https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Fortran
!
do i = 1, n - 1
do j = i + 1, n
if (array(i) > array(j)) then
temp = array(i)
array(i) = array(j)
array(j) = temp
end if
end do
end do
end subroutine sort
!-----------------------------------------------------------------------------
!> Calculate standard deviation using trivial formula:
!! @f[ \sigma=\sqrt{\frac{\sum (x-\overline{x})^{2}}{N-1}} . @f]
!! @note This is a real array version.
function std_dev(array_in, missing_code, undef_ret_null) result (stddev)
!> @param vector_in The input data vector
real, dimension(:), intent(in) :: array_in
!> @param missing_code Optional parameter setting the missing data code,
!! to be excluded from the calculation of the mean.
real, optional, intent(in) :: missing_code
!> @param undef_ret_null Optional parameter, if TRUE, the function returns
!! zero rather than undefined if the sample size is zero.
logical, optional, intent(in) :: undef_ret_null
!> @returns The standard deviation of the data vector.
real :: stddev
! Local missing code.
real :: missing_code_here
! Local sample size, N of valid values.
integer :: count_valid
! Minimum sample size resulting in real calculation, everythin less
! than this returns invalid.
integer, parameter :: MIN_N = 4
! An array of squared deviations
real, dimension(size(array_in)) :: dev2
! Mean value
real :: sample_mean
!> Check if missing data code is provided from dummy input.
!! If not, use global parameter.
if (present(missing_code)) then
missing_code_here = missing_code
else
missing_code_here = MISSING
end if
count_valid = count(array_in /= missing_code_here)
!> If there are no valid values in the array, std. dev. is undefined.
if (count_valid < MIN_N) then
if (present(undef_ret_null)) then
if (undef_ret_null) then
stddev = 0.0 !> still return zero if undef_ret_null is TRUE.
else
stddev = MISSING
end if
else
stddev = MISSING
end if
return
end if
sample_mean = average ( array_in, missing_code_here )
where ( array_in /= missing_code_here )
dev2 = ( array_in - sample_mean ) ** 2
elsewhere
dev2 = missing_code_here
end where
stddev = sqrt( sum( dev2, dev2 /= missing_code_here ) / (count_valid - 1) )
end function std_dev
!-----------------------------------------------------------------------------
!> Converts logical to standard (kind SRP) real, .FALSE. => 0, .TRUE. => 1
!! @note Note that this function is required to place logical data
!! like the survival status (alive) into the reshape array that is
!! saved as the CSV data file.
!! **Example: **
!! @code
!! call CSV_MATRIX_WRITE ( reshape( &
!! [ habitat_safe%food%food%x, &
!! habitat_safe%food%food%y, &
!! habitat_safe%food%food%depth, &
!! conv_l2r(habitat_safe%food%food%eaten), &
!! habitat_safe%food%food%size], &
!! [habitat_safe%food%number_food_items, 5]), &
!! "zzz_food_s" // MODEL_NAME // "_" // MMDD // &
!! "_gen_" // TOSTR(generat, GENERATIONS) // csv, &
!! ["X ","Y ", "D ", "EATN", "SIZE"] &
!! ) @endcode
elemental function l2r(flag, code_false, code_true) result (num_out)
logical, intent(in) :: flag
real, optional, intent(in) :: code_false
real, optional, intent(in) :: code_true
real :: num_out
! Local copies of optionals.
real :: code_false_loc, code_true_loc
! Local real parameters for the default FALSE and TRUE.
real, parameter :: FALSE_DEF=0.0, TRUE_DEF=1.0
!> First, check optional parameters.
if (present(code_false)) then
code_false_loc = code_false
else
code_false_loc = FALSE_DEF
end if
if (present(code_true)) then
code_true_loc = code_true
else
code_true_loc = TRUE_DEF
end if
! Second, do the actual conversion.
if (flag .eqv. .TRUE.) then
num_out = code_true_loc
else
num_out = code_false_loc
end if
end function l2r
! Function for calculating linear increase in predation to ensure soft pressure from the environment in the initial 20 generations.
function approx_easy(generation, min_y, max_y) result (y_approx)
real :: y_approx
integer, intent(in) :: generation
real, intent(in) :: min_y, max_y
!when M is at it's highest value, the attack_rate is also at it's highest,
!when M is lower than it's highest value, the attack rate is somewhere along
!the linear slope that goes from minimum attack rate (min_y) to maximum attack rate
!(max_y).
real :: k, b ! parameters of the linear equation
integer, parameter :: M = EASY_GENERATIONS !Parameter for the generations where the environment is less harsh and allows for an individual's mistakes.
k = -1 * (min_y - max_y) / (M - 1)
b = (M*min_y - max_y) / (M - 1)
if (generation < M) then !if the generation nr is less than M(=20)
y_approx = k * real(generation) + b !y_approx, the environments predation is k * (real)generation.
else !"Real" due to temporal continuity within and between generation (slope of the linear eq)
y_approx = max_y !if generation is 20 or above, continue with universal parameters.
end if
end function approx_easy
subroutine get_global_runtime_params()
! Purpose
! The subroutine get_global_runtime_params is designed to retrieve and
! process command-line arguments passed to the program. It sets global
! parameters based on the presence and values of these arguments.
! Description:
! This subroutine fetches the number of command-line arguments
! and stores them in an allocatable array. It then processes the
! first argument, if available, to set the values of two global
! parameters: Genome_File_Name and Is_Evolutionary_Generations.
! Usage:
! This subroutine does not take any input arguments nor return any output.
! It relies on command-line arguments passed when the Fortran program is executed.
! Example, in terminal, if we run gfortran -o example example.f90:
!./example
! expected output should be: Is_Evolutionary_Generations: T
!if we run ./example my_genome_file.txt
! expected output: Is_Evolutionary_Generations: F
integer :: i, n_args
character(100), dimension(:), allocatable :: cmd_args
! Get the number of command-line arguments
n_args = command_argument_count()
! Allocate array to hold command-line arguments
allocate(cmd_args(n_args))
! Retrieve each command-line argument and store it in cmd_args
do i = 1, n_args
call get_command_argument(number = i, value = cmd_args(i))
end do
! Process the command-line arguments to set global parameters
if (n_args > 0) then
Genome_File_Name = trim(cmd_args(1))
Is_Evolutionary_Generations = .FALSE.
else
Genome_File_Name = " "
Is_Evolutionary_Generations = .TRUE.
end if
end subroutine get_global_runtime_params
end module params
!------------------------------------
!------ENVIRONMENT MODULE------------
!------------------------------------
module environment
use params
use BASE_RANDOM
implicit none
! Spatial location at one cell, in the initial model it is
! just a single cell, integer number
! Note: defining an elementary spatial unit makes it easy to
! extend the model to 2d or 3d
type, public :: location
integer :: x
contains
procedure, public :: put_random => location_place_random
procedure, public :: place => location_place_object_location !for bird and predator
procedure, public :: walk => location_random_walk !only for bird
end type location
! Each spatial cell has additional data characteristics:
! - food availability
! - predation risk
type, extends(location) :: env_cell
real :: food_availability
real :: predator_frequency
contains
procedure, public :: init => cell_init
end type env_cell
! The whole environment is a collection of cells
! Note: note that the size of the environment is an allocatable (dynamic)
! array.
type whole_environ
type(env_cell), allocatable, dimension(:) :: point
contains
procedure, public :: init => env_init
procedure, public :: save => environemnt_save_csv
procedure, public :: load_env_csv => load_environment_from_csv
end type whole_environ
contains
! This subroutine places the basic spatial object (location class) to a
! random place.
subroutine location_place_random(this, min_pos, max_pos)
use BASE_RANDOM
class(location), intent(inout) :: this
! Optional parameters defining a range of positions to place the spatial
! object, but by default the position is from 1 to ENVIRONMENT_SIZE
integer, optional, intent(in) :: min_pos, max_pos
integer :: min_loc, max_loc
if (present(min_pos)) then
min_loc = min_pos
else
min_loc = 1
end if
if (present(max_pos)) then
max_loc = max_pos
else
max_loc = ENVIRONMENT_SIZE
end if
this%x = RAND(min_loc, max_loc)
end subroutine location_place_random
! Place a spatial object to a specific location (cell) within the environment
subroutine location_place_object_location(this, where)
class(location), intent(inout) :: this
integer, intent(in) :: where
this%x = where
end subroutine location_place_object_location
subroutine location_random_walk(this, min_pos, max_pos)
use BASE_RANDOM
class(location), intent(inout) :: this
integer, optional, intent(in) :: min_pos, max_pos
!deside if left or right-movement
logical :: is_going_left
integer :: min_loc, max_loc
! Process optional parameters using the min_pos and max_pos from
! the subroutine call or default values
if (present(min_pos)) then
min_loc = min_pos
else
min_loc = 1
end if
if (present(max_pos)) then
max_loc = max_pos
else
max_loc = ENVIRONMENT_SIZE
end if
if ( RAND() > 0.5 ) then
is_going_left = .TRUE.
else
is_going_left = .FALSE.
end if
if ( is_going_left .and. this%x == min_loc ) then
is_going_left = .FALSE.
elseif ( .NOT. is_going_left .and. this%x == max_loc) then
is_going_left = .TRUE.
end if
if (is_going_left) then
this%x = this%x - 1
else
this%x = this%x + 1
end if
end subroutine location_random_walk
! Initialize a single cell within the environment
subroutine cell_init(this, x, env)
use BASE_RANDOM
class(env_cell), intent(out) :: this
integer, intent(in) :: x
type(whole_environ), optional, intent(inout) :: env
this%x = x ! set location
this%food_availability = within(RNORM(FOOD_AVAILABILITY_MEAN, FOOD_AVAILABILITY_VARIANCE), &
FOOD_AVAILABILITY_MIN, FOOD_AVAILABILITY_MAX)
if (Is_Evolutionary_Generations) then
this%predator_frequency = RAND(FREQUENCY_OF_PREDATOR_MIN, FREQUENCY_OF_PREDATOR_MAX)
else
! if (present(env)) then
! call env%load_env_csv()
! this%predator_frequency = env%point(x)%predator_frequency
! else
this%predator_frequency = RAND(FREQUENCY_OF_PREDATOR_MIN * FEAR_SIGNAL_MULTIPLIER, &
FREQUENCY_OF_PREDATOR_MAX * FEAR_SIGNAL_MULTIPLIER)
! end if
! this%predator_frequency = this%predator_frequency * FEAR_SIGNAL_MULTIPLIER
! end if
end if
end subroutine cell_init
! Initialize the whole environment
subroutine env_init(this, max_size) !max size of the environ, but optional. Made for testing with shorter arrays.
class(whole_environ), intent(inout) :: this
integer, intent(in), optional :: max_size
integer :: i, max_size_loc
! process optional parameter defining the maximum size of the environment
if (present(max_size)) then
max_size_loc = max_size
else
max_size_loc = ENVIRONMENT_SIZE
end if
! First, allocate the dynamic environment array with its size
! Note that we test if the array has already been allocated to guard against
! possible error, e.g. if init is called more than once
if (.not. allocated(this%point) ) then
allocate (this%point(max_size_loc))
else
! Repeated initialization of the environment
! would be strange so we report this
write(*,*) "WARNING: repeated initialization of the environment detected"
deallocate (this%point)
allocate (this%point(max_size_loc))
end if
do i=1, size(this%point)
call this%point(i)%init(i, this) ! we initialize the food and predation data
end do
end subroutine env_init
!Subroutine for saving info on food-distribution across the one-dimensional
!matrix that is our birds array of habitats.
!Subroutine logic:
!Using only CSV_ARRAY_WRITE from CSV_IO, an array is created. This array
!makes an output array(output_array) which is basically a one dimensional
!array of cells that correspond the habitats our bird walks in. This array
!consist of however many cells we want ("this"). When we loop over it from
!i = 1 until total array size, for each loop the food that is within each
!cell is recorded. This only needs to be done once, since the food in cells
!are a non-changing value. This is then saved to output_array, that gets sent
!to FOOD_PRED_DISTRIBUTION_FILE
subroutine environemnt_save_csv(this)
use CSV_IO, only : CSV_MATRIX_WRITE
class(whole_environ), intent(in) :: this
integer :: i
real, allocatable, dimension(:,:) :: output_array
allocate(output_array(size(this%point), 2))
do i=1, size(this%point)
output_array(i,1) = this%point(i)%food_availability
output_array(i,2) = this%point(i)%predator_frequency
end do
call CSV_MATRIX_WRITE(output_array, FOOD_PRED_DISTRIBUTION_FILE, colnames = ["FOOD_AVAILABILITY", "RISK_PREDATION "])
end subroutine environemnt_save_csv
!> Loads the environment data from a CSV file and initializes the environment cells.
!>
!> If the CSV file is successfully opened, the function reads the food availability
! and predator frequency for each cell in the environment and stores them in the
! corresponding `this%point` elements. If the file does not contain data for all cells,
! the remaining cells are initialized using the `cell_init` subroutine.
!>
!> If the CSV file cannot be opened, the function generates a new environment
! by initializing all cells using the `cell_init` subroutine.
!>
!> @param this The `whole_environ` object representing the environment.
subroutine load_environment_from_csv(this)
class(whole_environ), intent(inout) :: this
integer :: i, io_status
character(len=100) :: line
open(unit=10, file=FOOD_PRED_DISTRIBUTION_FILE, status='old', action='read', iostat=io_status)
if (io_status == 0) then
read(10, *, iostat=io_status) ! Skip header line
do i = 1, size(this%point)
read(10, *, iostat=io_status) this%point(i)%food_availability !, this%point(i)%predator_frequency
if (io_status /= 0) exit
this%point(i)%x = i
end do
close(10)
if (i <= size(this%point)) then
print*, "Warning: Not all environment data loaded. Generating remaining cells."
do i = i, size(this%point)
call cell_init(this%point(i), i)
end do
end if
else
print*, "Error opening CSV file. Generating new environment."
do i = 1, size(this%point)
call cell_init(this%point(i), i)
end do
end if
end subroutine load_environment_from_csv
end module environment
!--------------------------------------
!-------GENOME MODULE------------------
!--------------------------------------
module organism
use params
use environment
use BASE_RANDOM
implicit none
!describe how we define genes
!make an integer range that describes fear vs hunger
!--------------------------------
!-----------LOCATION/GENE--------
!--------------------------------
type, extends(location), public :: GENOME
integer :: gene_fear !the higher the gene_fear the lower the gene, opposite proportional
integer :: gene_hunger !DOCUMENT ME!
contains
procedure, public :: init_genome => genome_init_all
procedure, public :: mutate => gene_mutate
end type GENOME
!--------------------------------
!-------------BIRD/GENOME----------
!--------------------------------
type, extends(GENOME), public :: BIRD
real :: weight
!In this model set by the params BIRD_INITAL_WEIGHT and BIRD_MAXIMUM_WEIGHT_MULTIPLICATOR/BIRD_MINIMUM_WEIGHT_MULTIPLICATOR
real, dimension(TOTAL_TIME_STEP) :: weight_history
!recording weight in matrix by timestep and generation
real, dimension(TOTAL_TIME_STEP) :: fear_history
! recording emotion in matrix by timestep and generation - previously emotion_history
real, dimension(TOTAL_TIME_STEP) :: hunger_history
! recording genes in matrix by timestep and generation
real, dimension(TOTAL_TIME_STEP) :: hunger_gene_history
real, dimension(TOTAL_TIME_STEP) :: fear_gene_history
real :: state_fear !values between 0 and 10
real :: state_hunger !values between 0 and 10
logical :: is_alive
logical :: is_killed_by_predator
integer :: bird_meets_predator_counter