-
Notifications
You must be signed in to change notification settings - Fork 0
/
m_genome.f90
1897 lines (1664 loc) · 88.3 KB
/
m_genome.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
!> @file m_genome.f90
!! The Genome objects of the AHA Model.
!! @author Sergey Budaev <sergey.budaev@uib.no>
!! @author Jarl Giske <jarl.giske@uib.no>
!! @date 2016-2017
!-------------------------------------------------------------------------------
! $Id$
!-------------------------------------------------------------------------------
!-------------------------------------------------------------------------------
!> @brief Definition the genetic architecture of the agent
!> @section the_genome_module THE_GENOME module
!> This module defines the genetic architecture objects of the agent. See
!! @ref aha_buildblocks_genome "The genome structure" for an overview.
module THE_GENOME
use COMMONDATA !> @note We need Global Data in every module!
!> @note We don't need all environmental objects definitions here!
!! But the individual genome `INDIVIDUAL_GENOME` is an extension
!! of `SPATIAL_MOVING`.
use THE_ENVIRONMENT, only : SPATIAL_MOVING
implicit none
character (len=*), parameter, private :: MODNAME = "(THE_GENOME)"
!-----------------------------------------------------------------------------
!> @brief This describes an individual gene object. See
!! @ref aha_buildblocks_genome "the genome structure" for as general
!! description and @ref aha_buildblocks_genome_gene "gene" for
!! details.
type, public :: GENE
!> sets a descriptive label of the allele, e.g its role and purpose
character(len=LABEL_LENGTH) :: allele_label
!> @brief Sets the value of the allele that is stored and evolved.
!! @note In the new version allele values are *INTEGER*
!! rather than *REAL*. Integer genome is not affected by the CPU
!! precision and does not suffer from FPU rounding errors. This is
!! what is expected from the genome: genes should be atomic, fixed,
!! and never subject to any uncontrollable fluctuations and drift.
!! Otherwise no "inheritance" is guaranteed. Only controlled
!! mutations are allowed. Integer calculations will also have higher
!! calculation speed and may hopefully avoid IEEE float point errors
!! (overflow/underflow). Also, we may in future use more realistic
!! limited-range allele functions to mimic real DNA structure.
!! If we have sufficiently large range of possible allele values,
!! e.g. 1:10000 and integer-to-real conversion function for
!! converting these true integer allele values to real values
!! within 0.:1. in the gamma neural response function, this would
!! not have a much different effect compared with the old
!! real-value gene implementation.
integer, dimension(ADDITIVE_COMPS) :: allele_value
!> sets if the allele is dominant
logical :: dominant
!> sets the multiplicative dominance weight
real(SRP) :: dominance_weight
!> rank_id of the gene, needed for sorting alleles within the chromosome
integer :: rank_id
contains
!> init alleles with random values, labels not set here,
!! use this function for startup initialisations of random agents
!! See `the_genome::allele_init_random()`
procedure, public :: init_allele => allele_init_random
!> create empty zero allele object, should be used for offspring inits
!! as we do not need to init them with random values, they will get
!! them from the parents using inherit function set
!! See `the_genome::allele_create_zero()`
procedure, public :: create_allele => allele_create_zero
!> init label alleles random
!! See `the_genome::allele_label_init_random()`
procedure, public :: label_random => allele_label_init_random
!> set labels for the allele
!! See `the_genome::allele_label_set()`
procedure, public :: labels => allele_label_set
!> get the allele label
!! See `the_genome::allele_label_get()`
procedure, public :: label_get => allele_label_get
!> set individual value of allele
!! See `the_genome::allele_value_set()`
procedure, public :: set => allele_value_set
!> set the vector of additive allele components
!! See `the_genome::alleles_value_vector_set()`
procedure, public :: set_vector => alleles_value_vector_set
!> get the value of the allele
!! See `the_genome::allele_value_get()`
procedure, public :: get => allele_value_get
!> get the vector of additive allele components
!! See `the_genome::allele_values_vector_get()`
procedure, public :: get_vector => allele_values_vector_get
!> set rank_id for the allele
!! See `the_genome::allele_rank_id_set()`
procedure, public :: rank => allele_rank_id_set
!> Introduce a random point mutation to one (random) of the alleles
!! See `the_genome::allele_mutate_random()`
procedure, public :: mutate_point => allele_mutate_random
!> Introduce random mutations to the whole allele components set
!! See `the_genome::allele_mutate_random_batch()`
procedure, public :: mutate_set => allele_mutate_random_batch
end type GENE
!-----------------------------------------------------------------------------
!> This type describes the chromosome object.
!! Chromosome consists of an array of alleles and a descriptive
!! string label. See
!! @ref aha_buildblocks_genome "\"the genome structure\"" for as general
!! description and @ref aha_buildblocks_genome_chromosome
!! "\"chromosome\"" for details.
type, public :: CHROMOSOME
!> chromosome label
character(len=LABEL_LENGTH) :: chromosome_label
!> chromosome length, i.e. N of alleles here
integer :: clength
!> array of alleles of the size `clength`
type(GENE), allocatable, dimension(:) :: allele
contains
!> This subroutine initialises the chromosome with, and allocates, random
!! alleles, sets one of them randomly dominant and optionally defines the
!! chromosome label.
!! See `the_genome::chromosome_init_allocate_random()`
procedure, public :: init_chromosome => chromosome_init_allocate_random
!> Init a new chromosome, zero, non-random.
!! See `the_genome::chromosome_create_allocate_zero()`
procedure, public :: create_chromosome => chromosome_create_allocate_zero
!> This subroutine recalculates rank_id indices for consecutive gene objects
!! within the chromosome. This may be necessary after reordering by random
!! relocation mutation.
!! See `the_genome::chromosome_recalculate_rank_ids()`
procedure, public :: recalc_rank_id => chromosome_recalculate_rank_ids
!> mutate within the same chromosome, relocate a gene (unit of alleles) to a
!! different random position within the same chromosome, the misplaced gene
!! moves to the relocated gene position, so they are just swap.
!! See `the_genome::chromosome_mutate_relocate_swap_random()`
procedure, public :: mutate_swap => chromosome_mutate_relocate_swap_random
!> Mutate within the same chromosome, relocate a gene (unit of alleles) to a
!! different random position within the same chromosome, shifting all other
!! genes within the chromosome down one position. This works as
!! follows: first, we randomly determine the gene to relocate, assign it
!! a new random rank_id. Then re-sort the chromosome according to the new
!! ranks with `qsort` with the `qs_partition_rank_id` backend.
!! See `the_genome::chromosome_mutate_relocate_shift_random()`
procedure, public :: mutate_shift => chromosome_mutate_relocate_shift_random
!> Sort GENE objects within the CHROMOSOME by their rank_id
!! The two subroutines below are a variant of the recursive quick-sort
!! algorithm adapted for sorting integer components of the the `CHROMOSOME`
!! object.
!! See `the_genome::chromosome_sort_rank_id()`
procedure, public :: sort_rank_id => chromosome_sort_rank_id
end type CHROMOSOME
!-----------------------------------------------------------------------------
!> This type describes parameters of the individual agent's genome
!! The genome is an array of allocatable the_genome::chromosome objects,
!! different kinds of agents may have different genomes with
!! different number of chromosomes. See
!! @ref aha_buildblocks_genome "\"the genome structure\"" for as general
!! description and @ref aha_buildblocks_genome_genome "\"genome\"" for
!! details.
type, public, extends(SPATIAL_MOVING) :: INDIVIDUAL_GENOME
!> label for the genome
character(len=LABEL_LENGTH) :: genome_label
!> the size of the genome, i.e. N of chromosomes = N_CHROMOSOMES
!! in this version it is constant, can implement variable genomes later.
integer :: genome_size = N_CHROMOSOMES
!> array of chromosome objects, the two dimensions refer to
!! (1) chromosome number in the genome and (2) the number of homologs
!! (1:2 for diploid), so chromosome is a 2D array.
type(CHROMOSOME), allocatable, dimension(:,:) :: chromosome
!> The sex of the individual: is male = TRUE or female = FALSE
!! this is the main sex identifier. The sex_label defined below
!! should only be used for outputs and similar purposes.
logical :: sex_is_male
!> Verbal label for sex ("male" or "female").
character(len=LABEL_LENGTH) :: sex_label
!> Flag the agent is alive (TRUE) or dead (False).
logical :: alive
contains
!> Initialise the genome at random, and set sex as determined by the sex
!! determination locus.
!! See `the_genome::genome_init_random()`
procedure, public :: init_genome => genome_init_random
!> Create a new empty genome, and set sex as determined by the sex
!! determination locus. Genome values are from parents using inherit
!! functions.
!! See `the_genome::genome_create_zero()`
procedure, public :: create_genome => genome_create_zero
!> Label genome. If label is not provided, make a random string.
!! @note TMP NOTE: label setting removed from the create function
!! as it will now override create for `SPATIAL_MOVING`.
!! See `the_genome::genome_label_set()`
procedure, public :: label => genome_label_set
!> Accessor function to get the genome label. The label is a kind of a
!! (random) text string name of the genome and the individual agent.
!! @note We especially need this accessor function because the genome (and
!! individual) name is used in other modules for file names ids etc.
!! See `the_genome::genome_label_get()`
procedure, public :: individ_label => genome_label_get
!> Sex has a separate status from all other genetically determined traits.
!! It is initialised here, at the genotype level of the class hierarchy.
!! See `the_genome::genome_sex_determine_init()`
procedure, public :: sex_init => genome_sex_determine_init ! init sex
!> Get the logical sex ID of the genome object component.
!! See `the_genome::genome_get_sex_is_male()`
procedure, public :: is_male => genome_get_sex_is_male
!> Get the logical sex ID of the genome object component.
!! See `the_genome::genome_get_sex_is_female()`
procedure, public :: is_female => genome_get_sex_is_female
!> Get the descriptive sex label: male or female.
!! See `the_genome::genome_get_sex_label()`
procedure, public :: label_sex => genome_get_sex_label
!> Init a trait from the genotype, trait can be any object in any of
!! the up level class hierarchy that is determined from the boolean
!! genotype x phenotype matrix.
!! See `the_genome::trait_init_genotype_gamma2gene()`
procedure, public :: trait_init => trait_init_genotype_gamma2gene
!> Set an **individual trait** of the agent that depends on the
!! genotype. This can be any trait upwards in the class hierarchy.
!! See `the_genome::trait_set_genotype_gamma2gene()`
procedure, public :: trait_set => trait_set_genotype_gamma2gene
!> Generic interface to the neuronal response function.
!! See `the_genome::trait_init_genotype_gamma2gene()` and
!! `the_genome::trait_set_genotype_gamma2gene()`.
generic, public :: neuro_resp => trait_init, trait_set
!> Init a trait from the genotype, trait can be any object in any of
!! the up level class hierarchy that is determined from the boolean
!! genotype x phenotype matrix. Note that this method is based on
!! simple linear rescale rather than neuronal response.
!! See `the_genome::trait_init_linear_sum_additive_comps_2genes_r()`
procedure, public :: trait_init_linear => &
trait_init_linear_sum_additive_comps_2genes_r
!> Set an **individual trait** of the agent that depends on the
!! genotype. This can be any trait upwards in the class hierarchy.
!! Note that this method is based on simple linear rescale rather than
!! neuronal response.
!! See `the_genome::trait_set_linear_sum_additive_comps_2genes_r()`
procedure, public :: trait_set_linear => &
trait_set_linear_sum_additive_comps_2genes_r
!> Generic interface to the simple linear genotype to phenotype
!! transformation functions. See
!! `the_genome::trait_init_linear_sum_additive_comps_2genes_r()` and
!! `the_genome::trait_set_linear_sum_additive_comps_2genes_r()`.
generic, public :: linear_g2p => trait_init_linear, trait_set_linear
!> Set the individual to be alive, normally this function is used after
!! init or birth.
!! See `the_genome::genome_individual_set_alive()`
procedure, public :: lives => genome_individual_set_alive
!> Set the individual to be **dead**. Note that this function does not
!! deallocate the individual agent object, this may be a separate
!! destructor function.
!! The `dies` method is implemented at the following levels
!! of the agent object hierarchy (upper overrides the lower level):
!! - the_genome::individual_genome::dies();
!! - the_neurobio::appraisal::dies();
!! - the_neurobio::gos_global::dies();
!! - the_individual::individual_agent::dies().
!! .
!! See `the_genome::genome_individual_set_dead()`
procedure, public :: dies => genome_individual_set_dead
!> Set the individual to be **dead**. Note that in this class this method
!! implementation points to the same procedure as
!! `the_genome::individual_genome::dies(). However the `dies` method is
!! overriden upwards in the class hierarchy to also nullify
!! neurobiological and behavioural objects. So this method should be
!! only called in procedures that specifically implemented override of
!! the `dies` method:
!! - the_neurobio::gos_global::dies()
!! - the_individual::individual_agent::dies()
!! .
!! See `the_genome::genome_individual_set_dead()`
procedure, public :: set_dead => genome_individual_set_dead
!> Check if the individual is alive.
!! See `the_genome::genome_individual_check_alive()`
procedure, public :: is_alive => genome_individual_check_alive
!> Check if the individual is dead (the opposite of `is_alive`).
!! See `the_genome::genome_individual_check_dead()`
procedure, public :: is_dead => genome_individual_check_dead
!> Internal **genetic recombination backend**, exchange individual alleles
!! between homologous chromosomes in mother and father genomes to form
!! the `this` (offspring) genome. Fully random recombination. See
!! `the_genome::genome_individual_recombine_homol_full_rand_alleles()`.
procedure, public :: recombine_random => &
genome_individual_recombine_homol_full_rand_alleles
!> Internal genetic recombination backend, exchange individual alleles
!! between homologous chromosomes in mother and father genomes to form
!! the `this` (offspring) genome. Partially random recombination. See
!! `the_genome::genome_individual_recombine_homol_part_rand_alleles()`.
procedure, public :: recombine_partial => &
genome_individual_recombine_homol_part_rand_alleles
!> Internal **fixed genetic crossover** backend, exchange blocks of
!! alleles between homologous chromosomes in mother and father genomes
!! to form the `this` (offspring) genome.
!! See `the_genome::genome_individual_crossover_homol_fix()`.
procedure, public :: crossover => &
genome_individual_crossover_homol_fix
!> Perform a probabilistic random mutation(s) on the individual genome.
!! This is a high level wrapper to build mutations from various
!! components. See `the_genome::genome_mutate_wrapper()`.
procedure, public :: mutate => genome_mutate_wrapper
end type INDIVIDUAL_GENOME
! qsort and partition are only for sorting genetic objects within this
! module, so they are private. We also don't use real procedure names, refer
! them by their intarface names (left of =>).
! private :: genome_init_random
contains ! ........ implementation of procedures for this level ................
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
! General sorting functions for THE_GENOME module objects
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!> Sort GENE objects within the CHROMOSOME by their `rank_id`.
!! The two subroutines `qsort` and `qs_partition_rank_id` are a variant of
!! the recursive quick-sort algorithm adapted for sorting integer components
!! of the the `CHROMOSOME` object.
elemental subroutine chromosome_sort_rank_id(this)
class(CHROMOSOME), intent(inout) :: this
call qsort(this%allele) ! This is the array component we sort.
contains
!...........................................................................
!> `qsort` and `qs_partition_` are the two parts of the recursive sort
!! algorithm `qsort` is the recursive frontend. Sorts genes within the
!! chromosome by components of the array of `allele`s.
recursive pure subroutine qsort(A)
!> @param[inout] input array to be sorted. It has the same type as
!! the individual component objects of the array-object
!! that we are going to sort.
type(GENE), intent(in out), dimension(:) :: A
integer :: iq
if(size(A) > 1) then
call qs_partition_rank_id(A, iq)
call qsort(A(:iq-1))
call qsort(A(iq:))
endif
end subroutine qsort
!...........................................................................
!> `qsort` and `qs_partition_` are the two parts of the recursive sort
!! algorithm `qs_partition_rank_id` is a pivot backend, here it sorts
!! genes within the chromosome object by integer `rank_id` components of
!! the genes.
pure subroutine qs_partition_rank_id(A, marker)
!> @param[inout] input array to be sorted.
type(GENE), intent(in out), dimension(:) :: A
!> @param[out] internal pivot marker.
integer, intent(out) :: marker
integer :: i, j
type(GENE) :: temp
!> @note Pivot point `x`, has the same type **as
!! the sorted object component**.
integer :: x
! We sort GENE objects within the CHROMOSOME by their `rank_id`
! components (hardwired).
x = A(1)%rank_id
i= 0
j= size(A) + 1
do
j = j-1
do
if (A(j)%rank_id <= x) exit
j = j-1
end do
i = i+1
do
if (A(i)%rank_id >= x) exit
i = i+1
end do
if (i < j) then
! exchange A(i) and A(j)
temp = A(i)
A(i) = A(j)
A(j) = temp
elseif (i == j) then
marker = i+1
return
else
marker = i
return
endif
end do
end subroutine qs_partition_rank_id
end subroutine chromosome_sort_rank_id
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
! Functions linked with the object GENE
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!-----------------------------------------------------------------------------
!> Initialises allele with a random integer. Note that we do **not** set
!! the labels for the alleles here during the random initialisation.
subroutine allele_init_random(this)
class(GENE), intent(inout) :: this
!> The allele components are initialised by a random integers within
!! the range `ALLELERANGE_MIN` and `ALLELERANGE_MAX` parameetr values.
call RAND_ARRAY(this%allele_value, ALLELERANGE_MIN, ALLELERANGE_MAX)
! create random labels for the allele initially (disabled)
! call this%label_random()
end subroutine allele_init_random
!-----------------------------------------------------------------------------
!> Create allele with zero value. We don't set labels for alleles here
elemental subroutine allele_create_zero(this)
class(GENE), intent(inout) :: this
!> @note Note that there is no need to allocate `allele_value` array
!! as it has fixed shape.
this%allele_value = 0
end subroutine allele_create_zero
!-----------------------------------------------------------------------------
!> The (pair of) alleles here are assigned random string labels
!! Not sure if that is necessary for any application though
subroutine allele_label_init_random(this)
class(GENE), intent(inout) :: this
this%allele_label = RAND_STRING(LABEL_LENGTH,LABEL_CST,LABEL_CEN)
end subroutine allele_label_init_random
!-----------------------------------------------------------------------------
!> Set labels for the alleles. The subroutine parameter is array of labels
elemental subroutine allele_label_set(this, label)
class(GENE), intent(inout) :: this
!> @param[in] label, provides an array of labels to set for the allele.
character(len=*), intent(in) :: label
this%allele_label = label
end subroutine allele_label_set
!-----------------------------------------------------------------------------
!> Get the i-th allele label.
elemental function allele_label_get(this) result(label)
class(GENE), intent(in) :: this
!> @returns Returns the label of the allele.
character(len=LABEL_LENGTH) :: label
label = this%allele_label
end function allele_label_get
!-----------------------------------------------------------------------------
!> Set a single value of the allele additive component.
elemental subroutine allele_value_set(this, set_value, nr)
class(GENE), intent(inout) :: this
!> @param[in] value, provides the value to set for the allele and the
!! allele number.
integer, intent(in) :: set_value
!> @param[in] number, provides the number of the allele component to set.
integer, intent(in) :: nr
this%allele_value(nr) = set_value
end subroutine allele_value_set
!-----------------------------------------------------------------------------
!> Set values of the alleles as a vector, i.e. sets the whole gene values.
pure subroutine alleles_value_vector_set(this, values)
class(GENE), intent(inout) :: this
!> @param[in] values, provides vector of values to set for the alleles.
integer, dimension(ADDITIVE_COMPS), intent(in) :: values
this%allele_value = values
end subroutine alleles_value_vector_set
!-----------------------------------------------------------------------------
!> Get the value of the allele
elemental function allele_value_get(this, nr) result(avalue)
class(GENE), intent(in) :: this
!> @param[in] number, provides the number of the allele component to set.
integer, intent(in) :: nr
!> @returns Returns the value of the `nr`'s allele.
integer :: avalue
avalue = this%allele_value(nr)
end function allele_value_get
!-----------------------------------------------------------------------------
!> Get the vector of all values of the alleles, i.e. gets the gene values.
pure subroutine allele_values_vector_get(this, values)
class(GENE), intent(in) :: this
!> @param[out] values, Gets the vector of the values for the alleles.
integer, dimension(ADDITIVE_COMPS), intent(out) :: values
values = this%allele_value
end subroutine allele_values_vector_get
!-----------------------------------------------------------------------------
elemental subroutine allele_rank_id_set(this, value_id)
class(GENE), intent(inout) :: this
!> @param rank_id, set this value to the allele `rank_id`.
integer, intent(in) :: value_id
this%rank_id = value_id
end subroutine allele_rank_id_set
!-----------------------------------------------------------------------------
!> Introduce a random point mutation to a random allele component.
subroutine allele_mutate_random(this, prob)
class(GENE), intent(inout) :: this
!> @param[in] prob optional probability of mutation, if absent, the default
!! value commondata::mutationrate_point is used.
real(SRP), optional, intent(in) :: prob
! Local copies of optionals.
real(SRP) :: prob_mut
integer :: this_allele_mutates
! Check optional probability of mutation.
if (present(prob)) then
prob_mut = prob
else
prob_mut = MUTATIONRATE_POINT
end if
!> ### Implementation details ###
!> Do mutate if a random value is smaller than the commondata::mutationrate
!! parameter constant.
if (RAND_R4() < prob_mut) then
!> First, determine which of the alleles components gets mutation.
this_allele_mutates = RAND_I(1, ADDITIVE_COMPS)
!> Second, change the value of this allele component to an random integer.
call this%set(RAND_I(ALLELERANGE_MIN,ALLELERANGE_MAX),this_allele_mutates)
end if
end subroutine allele_mutate_random
!-----------------------------------------------------------------------------
!> Introduce a random mutation of the whole set of additive allele components.
subroutine allele_mutate_random_batch(this, prob)
class(GENE), intent(inout) :: this
!> @param[in] prob optional probability of mutation, if absent, the default
!! value commondata::mutationrate_batch is used.
real(SRP), optional, intent(in) :: prob
! Local copies of optionals.
real(SRP) :: prob_mut
! Check optional probability of mutation.
if (present(prob)) then
prob_mut = prob
else
prob_mut = MUTATIONRATE_BATCH
end if
if (RAND_R4() < prob_mut) then
!> ### Implementation details ###
!> This mutation just re-init the whole allele set as random.
call this%init_allele()
end if
end subroutine allele_mutate_random_batch
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
! Functions linked with the object CHROMOSOME
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!-----------------------------------------------------------------------------
!> This subroutine initialises the chromosome with, and allocates, random
!! alleles, sets one of them randomly dominant and optionally defines the
!! chromosome label.
!! @param[in] length, sets the length of the chromosome object, N of alleles.
!! @param[in] label, sets the label for the chromosome object, optional.
subroutine chromosome_init_allocate_random(this, length, label)
class(CHROMOSOME), intent(inout) :: this
! @param[in] length, sets the length of the chromosome object, N of alleles.
integer, intent(in) :: length
! @param[in] label, sets the label for the chromosome object, optional.
character(len=*), optional, intent(in) :: label
! local cycle counters
integer :: i
!> ### Implementation details ###
!> We set the chromosome label if such a parameter is provided, or
!! a random string if not.
if (present(label)) then
this%chromosome_label = label
else
! label chromosome with a random string here
this%chromosome_label = RAND_STRING(LABEL_LENGTH,LABEL_CST,LABEL_CEN)
end if
!> First, set the chromosome length using the procedure parameter `length`.
this%clength = length
!> Then, allocate the array of the allele objects with this length.
if (.not. allocated(this%allele)) allocate(this%allele(length))
!> Initialise all the alleles within this chromosome.
do i=1, length
!> Specifically, initialise the allele.
call this%allele(i)%init_allele()
!> Set initial rank_id ID of the allele.
call this%allele(i)%rank(i)
!> Finally, set the label for the alleles within this chromosome.
!! Labels can be set random using this function (disabled):
!! @code
!! call this%allele(i)%label_random()
!! @endcode
!! But in this implementation we construct the label for the allele from
!! the *chromosome label* and the *allele number*;
call this%allele(i)%labels( label( 1:len_trim(label)- &
max(0, len_trim(label)+ &
len(TOSTR(length))-LABEL_LENGTH)-1 &
) // "_" // TOSTR(i,length) &
)
!> Long chromosome labels are trimmed at right to fit the allele number.
end do
end subroutine chromosome_init_allocate_random
!-----------------------------------------------------------------------------
!> Init a new chromosome, zero, non-random.
subroutine chromosome_create_allocate_zero(this, length, label)
class(CHROMOSOME), intent(inout) :: this
! @param[in] length, sets the length of the chromosome object,N of alleles.
integer, intent(in) :: length
! @param[in] label, sets the label for the chromosome object, optional.
character(len=*), optional, intent(in) :: label
! local cycle counters
integer :: i
!> ### Implementation details ###
!> Set the chromosome label if provided as parameter, or random string
!! if not.
if (present(label)) then
this%chromosome_label = label
else
! label chromosome with a random string here
this%chromosome_label = RAND_STRING(LABEL_LENGTH,LABEL_CST,LABEL_CEN)
end if
!> First, set the chromosome length using the procedure parameter `length`.
this%clength = length
!> Then, we allocate the array of the allele objects with this length.
if (.not. allocated(this%allele)) allocate(this%allele(length))
!> Initialise all the alleles within this chromosome.
!! @note Parallel `do concurrent` construct is used here.
! @warning The `do concurrent` construct is F2008 and can not (yet) be
! implemented in all compilers. Use normal `do` in such a case.
do concurrent ( i=1:length )
! initialise the allele with zeros
call this%allele(i)%create_allele()
! set initial rank_id ID of the allele
this%allele(i)%rank_id = i
! make labels for the alleles within this chromosome.
! 1. we can set random labels for the alleles using this
! function below:
!call this%allele(i)%label_random()
! 2. or construct the vector of labels for the alleles from the chromosome
! label and allele number:
call this%allele(i)%labels( trim(label) // TOSTR(i,length) )
end do
end subroutine chromosome_create_allocate_zero
!-----------------------------------------------------------------------------
!> This subroutine recalculates rank_id indices for consecutive gene objects
!! within the chromosome. This may be necessary after reordering by random
!! relocation mutation.
elemental subroutine chromosome_recalculate_rank_ids(this)
class(CHROMOSOME), intent(inout) :: this
integer :: i
! @warning The `do concurrent` construct is F2008 and can not (yet) be
! implemented in all compilers. Use normal `do` in such a case.
do concurrent ( i = 1:this%clength )
! Reset rank_id ID of each.
this%allele(i)%rank_id = i
end do
end subroutine chromosome_recalculate_rank_ids
!-----------------------------------------------------------------------------
!> Mutate within the same chromosome, relocate a gene (unit of alleles) to a
!! different random position within the same chromosome, the misplaced gene
!! moves to the relocated gene position, so they are just **swap**.
subroutine chromosome_mutate_relocate_swap_random(this, prob)
class(CHROMOSOME), intent(inout) :: this
!> @param[in] prob optional probability of mutation, if absent, the default
!! value commondata::relocation_swap_rate is used.
real(SRP), optional, intent(in) :: prob
! Local copies of optionals.
real(SRP) :: prob_mut
type(GENE) :: temp_shift
integer :: gene_move, gene_swap
! Check optional probability of mutation.
if (present(prob)) then
prob_mut = prob
else
prob_mut = RELOCATION_SWAP_RATE
end if
!> ### Implementation details ###
!> Do mutate if a random value is smaller than the
!! commondata::relocation_swap_rate parameter constant value.
if (RAND_R4() < prob_mut) then
!> If yes, randomly determine the gene (`gene_move`) that initiates
!! the mutation move within the chromosome.
gene_move = RAND_I(1,this%clength)
!> Randomly determine the gene that will be swapped with the `gene_move`.
gene_swap = RAND_I(1,this%clength)
!> Then, cycle through the alleles and select new random allele if
!! it happens to coincide with `gene_move`.
do while (gene_swap == gene_move)
gene_swap = RAND_I(1,this%clength)
end do
!> After this, do the gene swap, and gene rank_id ID swap.
temp_shift = this%allele(gene_move)
! swap objects
this%allele(gene_move) = this%allele(gene_swap)
this%allele(gene_swap) = temp_shift
! and swap their rank_id's
this%allele(gene_move)%rank_id = gene_move
this%allele(gene_swap)%rank_id = gene_swap
end if
end subroutine chromosome_mutate_relocate_swap_random
!-----------------------------------------------------------------------------
!> Mutate within the same chromosome, relocate a gene (unit of alleles) to a
!! different random position within the same chromosome, **shifting** all
!! other genes within the chromosome down one position. This works as
!! follows: first, we randomly determine the gene to relocate, assign it
!! a new random rank_id. Then re-sort the chromosome according to the new
!! ranks with `qsort` with the `qs_partition_rank_id` backend.
subroutine chromosome_mutate_relocate_shift_random(this, prob)
class(CHROMOSOME), intent(inout) :: this
!> @param[in] prob optional probability of mutation, if absent, the default
!! value commondata::relocation_shift_rate is used.
real(SRP), optional, intent(in) :: prob
! Local copies of optionals.
real(SRP) :: prob_mut
integer :: gene_move, gene_moveto
! Check optional probability of mutation.
if (present(prob)) then
prob_mut = prob
else
prob_mut = RELOCATION_SHIFT_RATE
end if
!> ### Implementation details ###
!> Do mutate if a random value is smaller than the
!! commondata::relocation_shift_rate parameter constant value.
if (RAND_R4() < prob_mut) then
!> If yes, randomly determine the gene that initiates move within
!! the chromosome.
gene_move = RAND_I(1,this%clength)
!> Randomly determine the new position of this gene.
gene_moveto = RAND_I(1,this%clength)
!> Then, cycle through alleles and select new random allele if
!! it happens to coincide with `gene_move`.
do while (gene_moveto == gene_move)
gene_moveto = RAND_I(1,this%clength)
end do
!> After the cycle, adjust rank_id's of the alleles.
this%allele(gene_move)%rank_id = gene_moveto
!> Then re-sort the allele objects by their updated rank_id's.
call this%sort_rank_id()
!> Finally, recalculate rank_id's so they are again ordered.
call this%recalc_rank_id()
end if
end subroutine chromosome_mutate_relocate_shift_random
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
! Functions linked with the object INDIVIDUAL_GENOME
!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
!-----------------------------------------------------------------------------
!> Initialise the genome at random, and set sex as determined by the sex
!! determination locus.
subroutine genome_init_random(this, label)
class(INDIVIDUAL_GENOME), intent(inout) :: this
!! @param[in] label, set an optional label of the genome, if unset,
!! generate random string.
character(len=*), optional, intent(in) :: label
! Local variables
integer :: i,j
!> ### Implementation details ###
!> First, create spatial moving object component of the individual genome.
!! But we do not yet position the genome object.
call this%create()
!> Allocate the genome object, it must have `genome_size` chromosomes and
!! `CHROMOSOME_PLOIDY` homologs.
if (.not. allocated(this%chromosome)) &
allocate(this%chromosome(this%genome_size,CHROMOSOME_PLOIDY))
!> Now cycle over all the chromosomes and homologs and initialise each
!! of them.
do j=1, CHROMOSOME_PLOIDY
do i=1, this%genome_size
call this%chromosome(i,j)%init_chromosome( LEN_CHROMOSOMES(i), &
LAB_CHROMOSOMES(i) )
end do
end do
!> On exit from the cycle, set the genome label if provided, or random
!! string if not.
if (present(label)) then
call this%label( label )
else
! label the genome with a random string here
call this%label ()
end if
!> Then, determine the sex of the genome by the genome sex
!! determination locus taking into account the sex ratio.
call this%sex_init()
end subroutine genome_init_random
!-----------------------------------------------------------------------------
!> Create a new empty genome, and set sex as determined by the sex
!! determination locus. Genome values are from parents using inherit
!! functions.
subroutine genome_create_zero(this)
class(INDIVIDUAL_GENOME), intent(inout) :: this
! Local variables
integer :: i,j
!> ### Implementation details ###
!> First of all, Create spatial moving object component of the
!! individual genome.
call this%create()
!> Allocate the genome object, it must have `genome_size` chromosomes and
!! `CHROMOSOME_PLOIDY` homologs
if (.not. allocated(this%chromosome)) &
allocate(this%chromosome(this%genome_size,CHROMOSOME_PLOIDY))
!> Now cycle over all the chromosomes and homologs and initialise each
!! of them with empty genes (zero).
do j=1, CHROMOSOME_PLOIDY
do i=1, this%genome_size
call this%chromosome(i,j)%create_chromosome( LEN_CHROMOSOMES(i), &
LAB_CHROMOSOMES(i) )
end do
end do
!> Initialise the label the genome with a random string.
call this%label()
!> Determine the sex of the genome by the genome sex determination locus
!! taking into account the sex ratio.
call this%sex_init()
end subroutine genome_create_zero
!-----------------------------------------------------------------------------
!> Label genome. If label is not provided, make a random string.
! @note TMP NOTE: label setting removed from the create function
! as it will now override create for `SPATIAL_MOVING`.
subroutine genome_label_set(this, label)
class(INDIVIDUAL_GENOME), intent(inout) :: this
!! @param[in] label, set an optional label of the genome, if unset,
!! generate random string.
character(len=*), optional, intent(in) :: label
!> ### Implementation details ###
!> Set the genome label if provided, or random string if not.
if (present(label)) then
this%genome_label = label
else
! label the genome with a random string here
this%genome_label = RAND_STRING(LABEL_LENGTH,LABEL_CST,LABEL_CEN)
end if
end subroutine genome_label_set
!-----------------------------------------------------------------------------
!> Accessor function to get the genome label. The label is a kind of a
!! (random) text string name of the genome and the individual agent.
!! @note We especially need this accessor function because the genome (and
!! individual) name is used in other modules for file names ids etc.
!! @returns String label.
elemental function genome_label_get(this) result (label_str)
class(INDIVIDUAL_GENOME), intent(in) :: this
! @warning Intel Fortran 17 does not allow setting allocatable attribute
! for an elemental function. GNU gfortran allows.
! @warning Use intrinsic `trim` function to avoid blanks, especially when
! building file names. For example:
! `MMDD // "_a_"// trim(this%individ_label()) `
character(len=LABEL_LENGTH) :: label_str
label_str = this%genome_label
end function genome_label_get
!-----------------------------------------------------------------------------
!> @brief Sex determination initialisation subroutine.
!! @details Determine the genome's sex, sex is set by a logical identifier,
!! `sex_is_male` TRUE is **male**. Sex is calculated from the genome
!! and based on the average values of the sex determination alleles
!! in homologous chromosomes, rescaled to 0:1. This rescaled
!! value is then compared with the sex ratio parameter.
subroutine genome_sex_determine_init(this)
class(INDIVIDUAL_GENOME), intent(inout) :: this
integer :: i, j, k
integer :: sex_locus_sum ! average_sex_locus
integer :: sex_locus_num ! counter
integer, dimension(ADDITIVE_COMPS) :: values_from_allele
!---------------------------------------------------------------------------
!> ### Implementation details ###
!> The implementation is based on **genotype** x **phenotype** matrix
!! (logical type): commondata::sex_genotype_phenotype.
!!
!> First, initialise the average sex locus sum across the homologous
!! chromosomes.
sex_locus_sum = 0; sex_locus_num = 0
!> #### Loops ####
!> Then loop across **homologs**, **chromosomes** and **alleles** until
!! the value of `SEX_GENOTYPE_PHENOTYPE` gets TRUE. This means it is the
!! *sex locus*.
CHOMOLOGS: do k=1,CHROMOSOME_PLOIDY
CCHROMOS: do i=1,this%genome_size
CALLALES: do j=1, this%chromosome(i,k)%clength
if ( SEX_GENOTYPE_PHENOTYPE(j,i) ) then
!> - If this condition is met, set label to the sex locus allele
!! ("SEX_LOCUS").
call this%chromosome(i,k)%allele(j)%labels(SEXLOCUS_LABEL)
!> - Sex is determined by an average of the sex loci of the
!! homologous chromosomes.
!! Therefore, first get the vector of additive allele components.
call this%chromosome(i,k)%allele(j)%get_vector(values_from_allele)
!> - And sum it up to finally get the total sum for all chromosomes.
sex_locus_sum = sex_locus_sum + sum(values_from_allele)
!> - Finally, also update the counter of the totals.
!! .
sex_locus_num = sex_locus_num + ADDITIVE_COMPS
end if
end do CALLALES
end do CCHROMOS
end do CHOMOLOGS
!! -------------------------------------------------------------------------
!> Upon exit from the loop, check if the average sex locus across all
!! homologous chromosomes and additive allele components, scaled to 0:1
!! is less than the `SEX_RATIO`, the subject becomes the **male** genotype.
if ( ((real(sex_locus_sum,SRP)/real(sex_locus_num,SRP)) / &