-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathpopulation.cpp
8523 lines (7044 loc) · 366 KB
/
population.cpp
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
//
// population.cpp
// SLiM
//
// Created by Ben Haller on 12/13/14.
// Copyright (c) 2014-2025 Philipp Messer. All rights reserved.
// A product of the Messer Lab, http://messerlab.org/slim/
//
// This file is part of SLiM.
//
// SLiM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// SLiM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with SLiM. If not, see <http://www.gnu.org/licenses/>.
#include "population.h"
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <utility>
#include <unordered_map>
#include <ctime>
#include "community.h"
#include "species.h"
#include "slim_globals.h"
#include "eidos_script.h"
#include "eidos_interpreter.h"
#include "eidos_symbol_table.h"
#include "polymorphism.h"
#include "subpopulation.h"
#include "interaction_type.h"
#include "eidos_globals.h"
#if EIDOS_ROBIN_HOOD_HASHING
#include "robin_hood.h"
#elif STD_UNORDERED_MAP_HASHING
#include <unordered_map>
#endif
// the initial capacities for the haplosome and individual pools here are just guesses at balancing low default memory usage, maximizing locality, and minimization of additional allocs
Population::Population(Species &p_species) : model_type_(p_species.model_type_), community_(p_species.community_), species_(p_species), species_haplosome_pool_(p_species.species_haplosome_pool_), species_individual_pool_(p_species.species_individual_pool_)
{
}
Population::~Population(void)
{
RemoveAllSubpopulationInfo();
#ifdef SLIMGUI
// release malloced storage for SLiMgui statistics collection
for (auto history_record_iter : fitness_histories_)
{
FitnessHistory &history_record = history_record_iter.second;
if (history_record.history_)
{
free(history_record.history_);
history_record.history_ = nullptr;
history_record.history_length_ = 0;
}
}
for (auto history_record_iter : subpop_size_histories_)
{
SubpopSizeHistory &history_record = history_record_iter.second;
if (history_record.history_)
{
free(history_record.history_);
history_record.history_ = nullptr;
history_record.history_length_ = 0;
}
}
#endif
// dispose of any freed subpops
PurgeRemovedSubpopulations();
// dispose of individuals within our junkyard
for (Individual *individual : species_individuals_junkyard_)
{
individual->~Individual();
species_individual_pool_.DisposeChunk(const_cast<Individual *>(individual));
}
species_individuals_junkyard_.clear();
}
void Population::RemoveAllSubpopulationInfo(void)
{
// BEWARE: do not access sim_ in this method! This is called from
// Population::~Population(), at which point sim_ no longer exists!
// Free all subpopulations and then clear out our subpopulation list
for (auto subpopulation : subpops_)
delete subpopulation.second;
subpops_.clear();
// Free all substitutions and clear out the substitution vector
for (auto substitution : substitutions_)
substitution->Release();
substitutions_.resize(0);
treeseq_substitutions_map_.clear();
// The malloced storage of the mutation registry will be freed when it is destroyed, but it
// does not know that the Mutation pointers inside it are owned, so we need to release them.
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
int registry_size;
const MutationIndex *registry_iter = MutationRegistry(®istry_size);
const MutationIndex *registry_iter_end = registry_iter + registry_size;
for (; registry_iter != registry_iter_end; ++registry_iter)
(mut_block_ptr + *registry_iter)->Release();
mutation_registry_.clear();
#ifdef SLIM_KEEP_MUTTYPE_REGISTRIES
// If we're keeping any separate registries inside mutation types, clear those now as well
// NOTE: The access of sim_ here is permissible because it will not happen after sim_ has been
// destructed, due to the clearing of keeping_muttype_registries_ at the end of this block.
// This block will execute when this method is called directly by Species::~Species(), and
// then it will not execute again when this method is called by Population::~Population().
// This design could probably stand to get cleaned up. FIXME
if (keeping_muttype_registries_)
{
for (auto muttype_iter : species_.MutationTypes())
{
MutationType *muttype = muttype_iter.second;
if (muttype->keeping_muttype_registry_)
{
muttype->muttype_registry_.clear();
muttype->keeping_muttype_registry_ = false;
}
}
keeping_muttype_registries_ = false;
}
#endif
#ifdef SLIMGUI
// release malloced storage for SLiMgui statistics collection
if (mutation_loss_times_)
{
free(mutation_loss_times_);
mutation_loss_times_ = nullptr;
mutation_loss_tick_slots_ = 0;
}
if (mutation_fixation_times_)
{
free(mutation_fixation_times_);
mutation_fixation_times_ = nullptr;
mutation_fixation_tick_slots_ = 0;
}
// Don't throw away the fitness history; it is perfectly valid even if the population has just been changed completely. It happened.
// If the read is followed by setting the cycle backward, individual fitness history entries will be invalidated in response.
// if (fitness_history_)
// {
// free(fitness_history_);
// fitness_history_ = nullptr;
// fitness_history_length_ = 0;
// }
#endif
}
// add new empty subpopulation p_subpop_id of size p_subpop_size
Subpopulation *Population::AddSubpopulation(slim_objectid_t p_subpop_id, slim_popsize_t p_subpop_size, double p_initial_sex_ratio, bool p_haploid)
{
if (community_.SubpopulationIDInUse(p_subpop_id))
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulation): subpopulation p" << p_subpop_id << " has been used already, and cannot be used again (to prevent conflicts)." << EidosTerminate();
if ((p_subpop_size < 1) && (model_type_ == SLiMModelType::kModelTypeWF)) // allowed in nonWF models
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulation): subpopulation p" << p_subpop_id << " empty." << EidosTerminate();
if (child_generation_valid_)
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulation): (internal error) called with child generation active!." << EidosTerminate();
// make and add the new subpopulation
Subpopulation *new_subpop = nullptr;
if (species_.SexEnabled())
new_subpop = new Subpopulation(*this, p_subpop_id, p_subpop_size, true, p_initial_sex_ratio, p_haploid); // SEX ONLY
else
new_subpop = new Subpopulation(*this, p_subpop_id, p_subpop_size, true, p_haploid);
#ifdef SLIMGUI
// When running under SLiMgui, we need to decide whether this subpopulation comes in selected or not. We can't defer that
// to SLiMgui's next update, because then mutation tallies are not kept properly up to date, resulting in a bad GUI refresh.
// The rule is: if all currently existing subpops are selected, then the new subpop comes in selected as well.
bool gui_all_selected = true;
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
if (!subpop_pair.second->gui_selected_)
{
gui_all_selected = false;
break;
}
new_subpop->gui_selected_ = gui_all_selected;
#endif
subpops_.emplace(p_subpop_id, new_subpop);
species_.used_subpop_ids_.emplace(p_subpop_id, new_subpop->name_);
// cached mutation counts/frequencies are no longer accurate; mark the cache as invalid
InvalidateMutationReferencesCache();
return new_subpop;
}
// WF only:
// add new subpopulation p_subpop_id of size p_subpop_size individuals drawn from source subpopulation p_source_subpop_id
Subpopulation *Population::AddSubpopulationSplit(slim_objectid_t p_subpop_id, Subpopulation &p_source_subpop, slim_popsize_t p_subpop_size, double p_initial_sex_ratio)
{
if (community_.SubpopulationIDInUse(p_subpop_id))
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulationSplit): subpopulation p" << p_subpop_id << " has been used already, and cannot be used again (to prevent conflicts)." << EidosTerminate();
if (p_subpop_size < 1)
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulationSplit): subpopulation p" << p_subpop_id << " empty." << EidosTerminate();
if (child_generation_valid_)
EIDOS_TERMINATION << "ERROR (Population::AddSubpopulationSplit): (internal error) called with child generation active!." << EidosTerminate();
// make and add the new subpopulation; note that we tell Subpopulation::Subpopulation() not to record tree-seq information
Subpopulation *new_subpop = nullptr;
if (species_.SexEnabled())
new_subpop = new Subpopulation(*this, p_subpop_id, p_subpop_size, false, p_initial_sex_ratio, false); // SEX ONLY
else
new_subpop = new Subpopulation(*this, p_subpop_id, p_subpop_size, false, false);
#ifdef SLIMGUI
// When running under SLiMgui, we need to decide whether this subpopulation comes in selected or not. We can't defer that
// to SLiMgui's next update, because then mutation tallies are not kept properly up to date, resulting in a bad GUI refresh.
// The rule is: if all currently existing subpops are selected, then the new subpop comes in selected as well.
bool gui_all_selected = true;
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
if (!subpop_pair.second->gui_selected_)
{
gui_all_selected = false;
break;
}
new_subpop->gui_selected_ = gui_all_selected;
#endif
subpops_.emplace(p_subpop_id, new_subpop);
species_.used_subpop_ids_.emplace(p_subpop_id, new_subpop->name_);
// then draw parents from the source population according to fitness, obeying the new subpop's sex ratio
Subpopulation &subpop = *new_subpop;
bool recording_tree_sequence = species_.RecordingTreeSequence();
// TREE SEQUENCE RECORDING
if (recording_tree_sequence)
{
// OK, so, this is gross. The user can call addSubpopSplit(), and the new individuals created as a side effect need to
// arrive in the tree-seq tables stamped with a later time than their parents, but as far as SLiM is concerned they
// were created at the same time as the parents; they exist at the same point in time, and it's WF, therefore they
// were created at the same time, Q.E.D. So to get the tree-seq code not to object, we add a small offset to the
// tick counter. Since addSubpopSplit() could be called multiple times in sequence, splitting a new subpop off
// from each previous one in a linear fashion, each call to addSubpopSplit() needs to increase this offset slightly.
// The offset is reset to zero each time the tree sequence's tick counter advances. This is similar to the timing
// problem that made us create tree_seq_tick_ in the first place, due to children arriving in the same SLiM tick as
// their parents, but at least that only happens once per tick in a predictable fashion.
species_.AboutToSplitSubpop();
}
gsl_rng *rng = EIDOS_GSL_RNG(omp_get_thread_num());
for (slim_popsize_t parent_index = 0; parent_index < subpop.parent_subpop_size_; parent_index++)
{
// draw individual from p_source_subpop and assign to be a parent in subpop
// BCH 4/25/2018: we have to tree-seq record the new individuals and haplosomes here, with the correct parent information
// Peter observes that biologically, it might make sense for each new haplosome in the split subpop to actually be a
// clone of the original haplosome in the sense that it has the same parent as the original haplosomes, with the same
// recombination breakpoints, etc. But that would be quite hard to implement, especially since the parent in question
// might have been simplified away already, and that script could have modified the original, and so forth. Having
// the new haplosome just inherit exactly from the original seems reasonable enough; for practical purposes it shouldn't
// matter.
slim_popsize_t migrant_index;
if (species_.SexEnabled())
{
if (parent_index < subpop.parent_first_male_index_)
migrant_index = p_source_subpop.DrawFemaleParentUsingFitness(rng);
else
migrant_index = p_source_subpop.DrawMaleParentUsingFitness(rng);
}
else
{
migrant_index = p_source_subpop.DrawParentUsingFitness(rng);
}
// TREE SEQUENCE RECORDING
if (recording_tree_sequence)
species_.SetCurrentNewIndividual(subpop.parent_individuals_[parent_index]);
Haplosome **source_individual_haplosomes = p_source_subpop.parent_individuals_[migrant_index]->haplosomes_;
Haplosome **dest_individual_haplosomes = subpop.parent_individuals_[parent_index]->haplosomes_;
int haplosome_count_per_individual = species_.HaplosomeCountPerIndividual();
for (int haplosome_index = 0; haplosome_index < haplosome_count_per_individual; haplosome_index++)
{
Haplosome *source_haplosome = source_individual_haplosomes[haplosome_index];
Haplosome *dest_haplosome = dest_individual_haplosomes[haplosome_index];
dest_haplosome->copy_from_haplosome(*source_haplosome); // transmogrifies to null if needed
// TREE SEQUENCE RECORDING
if (recording_tree_sequence)
{
if (source_haplosome->IsNull())
species_.RecordNewHaplosome_NULL(dest_haplosome);
else
species_.RecordNewHaplosome(nullptr, 0, dest_haplosome, source_haplosome, nullptr);
}
}
}
// cached mutation counts/frequencies are no longer accurate; mark the cache as invalid
InvalidateMutationReferencesCache();
// UpdateFitness() is not called here - all fitnesses are kept as equal. This is because the parents were drawn from the source subpopulation according
// to their fitness already; fitness has already been applied. If UpdateFitness() were called, fitness would be double-applied in this cycle.
return new_subpop;
}
// WF only:
// set size of subpopulation p_subpop_id to p_subpop_size
void Population::SetSize(Subpopulation &p_subpop, slim_popsize_t p_subpop_size)
{
// SetSize() can only be called when the child generation has not yet been generated. It sets the size on the child generation,
// and then that size takes effect when the children are generated from the parents in EvolveSubpopulation().
if (child_generation_valid_)
EIDOS_TERMINATION << "ERROR (Population::SetSize): called when the child generation was valid." << EidosTerminate();
if (p_subpop_size == 0) // remove subpopulation p_subpop_id
{
slim_objectid_t subpop_id = p_subpop.subpopulation_id_;
// only remove if we have not already removed
if (subpops_.count(subpop_id))
{
// Note that we don't free the subpopulation here, because there may be live references to it; instead we keep it to the end of the cycle and then free it
// First we remove the symbol for the subpop
community_.SymbolTable().RemoveConstantForSymbol(p_subpop.SymbolTableEntry().first);
// Then we immediately remove the subpop from our list of subpops
subpops_.erase(subpop_id);
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
subpop_pair.second->migrant_fractions_.erase(subpop_id);
// remember the subpop for later disposal
removed_subpops_.emplace_back(&p_subpop);
// cached mutation counts/frequencies are no longer accurate; mark the cache as invalid
InvalidateMutationReferencesCache();
}
}
else
{
// After we change the subpop size, we need to generate new children haplosomes to fit the new requirements
p_subpop.child_subpop_size_ = p_subpop_size;
p_subpop.GenerateChildrenToFitWF();
}
}
// nonWF only:
// remove subpopulation p_subpop_id from the model entirely
void Population::RemoveSubpopulation(Subpopulation &p_subpop)
{
slim_objectid_t subpop_id = p_subpop.subpopulation_id_;
// only remove if we have not already removed
if (subpops_.count(subpop_id))
{
// Note that we don't free the subpopulation here, because there may be live references to it; instead we keep it to the end of the cycle and then free it
community_.InvalidateInteractionsForSubpopulation(&p_subpop);
// First we remove the symbol for the subpop
community_.SymbolTable().RemoveConstantForSymbol(p_subpop.SymbolTableEntry().first);
// Then we immediately remove the subpop from our list of subpops
subpops_.erase(subpop_id);
// remember the subpop for later disposal
removed_subpops_.emplace_back(&p_subpop);
// and let it know that it is invalid
p_subpop.has_been_removed_ = true;
// cached mutation counts/frequencies are no longer accurate; mark the cache as invalid
InvalidateMutationReferencesCache();
}
}
// nonWF only:
// move individuals as requested by survival() callbacks
void Population::ResolveSurvivalPhaseMovement(void)
{
// So, we have a survival() callback that has requested that some individuals move during the viability/survival phase.
// We want to handle this as efficiently as we can; we could have many individuals moving between subpops in arbitrary
// ways. We will remove all moving individuals from their current subpops in a single pass, and then add them to their
// new subpops in a single pass. If just one individual is moving, this will be inefficient since the algorithm is O(N)
// in the number of individuals, but I think it makes sense to optimize for the many-moving case for now.
bool sex_enabled = species_.SexEnabled();
// mark all individuals in all subpops as not-moving
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
for (Individual *individual : (subpop_pair.second)->parent_individuals_)
individual->scratch_ = 0;
// mark moving individuals in all subpops as moving
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
for (Individual *individual : (subpop_pair.second)->nonWF_survival_moved_individuals_)
individual->scratch_ = 1;
// loop through subpops and remove all individuals that are leaving, compacting downwards; similar to Subpopulation::ViabilitySurvival()
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
{
Subpopulation *subpop = subpop_pair.second;
Individual **individual_data = subpop->parent_individuals_.data();
int remaining_individual_index = 0;
int females_leaving = 0;
bool individuals_leaving = false;
for (int individual_index = 0; individual_index < subpop->parent_subpop_size_; ++individual_index)
{
Individual *individual = individual_data[individual_index];
bool remaining = (individual->scratch_ == 0);
if (remaining)
{
// individuals that remain get copied down to the next available slot
if (remaining_individual_index != individual_index)
{
individual_data[remaining_individual_index] = individual;
// fix the individual's index_
individual_data[remaining_individual_index]->index_ = remaining_individual_index;
}
remaining_individual_index++;
}
else
{
// individuals that do not remain get tallied and removed at the end
if (sex_enabled && (individual->sex_ == IndividualSex::kFemale))
females_leaving++;
individuals_leaving = true;
}
}
// Then fix our bookkeeping for the first male index, subpop size, caches, etc.
if (individuals_leaving)
{
subpop->parent_subpop_size_ = remaining_individual_index;
if (sex_enabled)
subpop->parent_first_male_index_ -= females_leaving;
subpop->parent_individuals_.resize(subpop->parent_subpop_size_);
subpop->cached_parent_individuals_value_.reset();
}
}
// loop through subpops and append individuals that are arriving; we do this using Subpopulation::MergeReproductionOffspring()
for (std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : subpops_)
{
Subpopulation *subpop = subpop_pair.second;
subpop->nonWF_offspring_individuals_.swap(subpop->nonWF_survival_moved_individuals_);
for (Individual *individual : subpop->nonWF_offspring_individuals_)
{
#if defined(SLIMGUI)
// tally this as an incoming migrant for SLiMgui
++subpop->gui_migrants_[individual->subpopulation_->subpopulation_id_];
#endif
individual->subpopulation_ = subpop;
individual->migrant_ = true;
}
subpop->MergeReproductionOffspring();
}
// Invalidate interactions; we just do this for all subpops, for now, rather than trying to
// selectively invalidate only the subpops involved in the migrations that occurred
community_.InvalidateInteractionsForSpecies(&species_);
}
void Population::PurgeRemovedSubpopulations(void)
{
if (removed_subpops_.size())
{
for (auto removed_subpop : removed_subpops_)
delete removed_subpop;
removed_subpops_.resize(0);
}
}
#if DEFER_BROKEN
// The "defer" flag is simply disregarded at the moment; its design has rotted away,
// and needs to be remade anew once things have settled down.
void Population::CheckForDeferralInHaplosomesVector(Haplosome **p_haplosomes, size_t p_elements_size, const std::string &p_caller)
{
if (HasDeferredHaplosomes())
{
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Haplosome *haplosome = p_haplosomes[element_index];
if (haplosome->IsDeferred())
EIDOS_TERMINATION << "ERROR (" << p_caller << "): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
}
}
}
void Population::CheckForDeferralInHaplosomes(EidosValue_Object *p_haplosomes, const std::string &p_caller)
{
if (HasDeferredHaplosomes())
{
int element_count = p_haplosomes->Count();
EidosObject * const *haplosomes_data = p_haplosomes->ObjectData();
for (int element_index = 0; element_index < element_count; ++element_index)
{
Haplosome *haplosome = (Haplosome *)haplosomes_data[element_index];
if (haplosome->IsDeferred())
EIDOS_TERMINATION << "ERROR (" << p_caller << "): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
}
}
}
void Population::CheckForDeferralInIndividualsVector(Individual * const *p_individuals, size_t p_elements_size, const std::string &p_caller)
{
if (HasDeferredHaplosomes())
{
int haplosome_count_per_individual = species_.HaplosomeCountPerIndividual();
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Individual *ind = p_individuals[element_index];
Haplosome **haplosomes = ind->haplosomes_;
for (int haplosome_index = 0; haplosome_index < haplosome_count_per_individual; haplosome_index++)
{
Haplosome *haplosome = haplosomes[haplosome_index];
if (haplosome->IsDeferred())
EIDOS_TERMINATION << "ERROR (" << p_caller << "): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
}
}
}
}
#endif
// nonWF only:
#if DEFER_BROKEN
// The "defer" flag is simply disregarded at the moment; its design has rotted away,
// and needs to be remade anew once things have settled down.
// This method uses the old reproduction methods, which have been removed from the code base; it needs a complete rework
void Population::DoDeferredReproduction(void)
{
size_t deferred_count_nonrecombinant = deferred_reproduction_nonrecombinant_.size();
size_t deferred_count_recombinant = deferred_reproduction_recombinant_.size();
size_t deferred_count_total = deferred_count_nonrecombinant + deferred_count_recombinant;
if (deferred_count_total == 0)
return;
// before going parallel, we need to ensure that we have enough capacity in the
// mutation block; we can't expand it while parallel, due to race conditions
// see Population::EvolveSubpopulation() for the equivalent WF code
#ifdef _OPENMP
do {
int registry_size;
MutationRegistry(®istry_size);
size_t est_mutation_block_slots_remaining_PRE = gSLiM_Mutation_Block_Capacity - registry_size;
double overall_mutation_rate = std::max(species_.chromosome_->overall_mutation_rate_F_, species_.chromosome_->overall_mutation_rate_M_); // already multiplied by L
size_t est_slots_needed = (size_t)ceil(2 * deferred_count_total * overall_mutation_rate); // 2 because diploid, in the worst case
size_t ten_times_demand = 10 * est_slots_needed;
if (est_mutation_block_slots_remaining_PRE <= ten_times_demand)
{
SLiM_IncreaseMutationBlockCapacity();
est_mutation_block_slots_remaining_PRE = gSLiM_Mutation_Block_Capacity - registry_size;
//std::cerr << "Tick " << community_.Tick() << ": DOUBLED CAPACITY ***********************************" << std::endl;
}
else
break;
} while (true);
#endif
// now generate the haplosomes of the deferred offspring in parallel
EIDOS_BENCHMARK_START(EidosBenchmarkType::k_DEFERRED_REPRO);
EIDOS_THREAD_COUNT(gEidos_OMP_threads_DEFERRED_REPRO);
#pragma omp parallel for schedule(dynamic, 1) default(none) shared(deferred_count_nonrecombinant) if(deferred_count_nonrecombinant >= EIDOS_OMPMIN_DEFERRED_REPRO) num_threads(thread_count)
for (size_t deferred_index = 0; deferred_index < deferred_count_nonrecombinant; ++deferred_index)
{
SLiM_DeferredReproduction_NonRecombinant &deferred_rec = deferred_reproduction_nonrecombinant_[deferred_index];
if ((deferred_rec.type_ == SLiM_DeferredReproductionType::kCrossoverMutation) || (deferred_rec.type_ == SLiM_DeferredReproductionType::kSelfed))
{
DoCrossoverMutation(deferred_rec.parent1_->subpopulation_, *deferred_rec.child_haplosome_1_, deferred_rec.parent1_->index_, deferred_rec.child_sex_, deferred_rec.parent1_->sex_, nullptr, nullptr);
DoCrossoverMutation(deferred_rec.parent2_->subpopulation_, *deferred_rec.child_haplosome_2_, deferred_rec.parent2_->index_, deferred_rec.child_sex_, deferred_rec.parent2_->sex_, nullptr, nullptr);
}
else if (deferred_rec.type_ == SLiM_DeferredReproductionType::kClonal)
{
#warning the use of haplosomes_[0] and haplosomes_[1] here needs to be updated for multichrom
DoClonalMutation(deferred_rec.parent1_->subpopulation_, *deferred_rec.child_haplosome_1_, *deferred_rec.parent1_->haplosomes_[0], deferred_rec.child_sex_, nullptr);
DoClonalMutation(deferred_rec.parent1_->subpopulation_, *deferred_rec.child_haplosome_2_, *deferred_rec.parent1_->haplosomes_[1], deferred_rec.child_sex_, nullptr);
}
}
//EIDOS_THREAD_COUNT(gEidos_OMP_threads_DEFERRED_REPRO); // this loop shares the same key
#pragma omp parallel for schedule(dynamic, 1) default(none) shared(deferred_count_recombinant) if(deferred_count_recombinant >= EIDOS_OMPMIN_DEFERRED_REPRO) num_threads(thread_count)
for (size_t deferred_index = 0; deferred_index < deferred_count_recombinant; ++deferred_index)
{
SLiM_DeferredReproduction_Recombinant &deferred_rec = deferred_reproduction_recombinant_[deferred_index];
if (deferred_rec.strand2_ == nullptr)
{
DoClonalMutation(deferred_rec.mutorigin_subpop_, *deferred_rec.child_haplosome_, *deferred_rec.strand1_, deferred_rec.sex_, nullptr);
}
else if (deferred_rec.type_ == SLiM_DeferredReproductionType::kRecombinant)
{
DoRecombinantMutation(deferred_rec.mutorigin_subpop_, *deferred_rec.child_haplosome_, deferred_rec.strand1_, deferred_rec.strand2_, deferred_rec.sex_, deferred_rec.break_vec_, nullptr);
}
}
EIDOS_BENCHMARK_END(EidosBenchmarkType::k_DEFERRED_REPRO);
// Clear the deferred reproduction queue
deferred_reproduction_nonrecombinant_.resize(0);
deferred_reproduction_recombinant_.resize(0);
}
#endif
// WF only:
// set fraction p_migrant_fraction of p_subpop_id that originates as migrants from p_source_subpop_id per cycle
void Population::SetMigration(Subpopulation &p_subpop, slim_objectid_t p_source_subpop_id, double p_migrant_fraction)
{
if (subpops_.count(p_source_subpop_id) == 0)
EIDOS_TERMINATION << "ERROR (Population::SetMigration): no subpopulation p" << p_source_subpop_id << "." << EidosTerminate();
if ((p_migrant_fraction < 0.0) || (p_migrant_fraction > 1.0) || std::isnan(p_migrant_fraction))
EIDOS_TERMINATION << "ERROR (Population::SetMigration): migration fraction has to be within [0,1] (" << EidosStringForFloat(p_migrant_fraction) << " supplied)." << EidosTerminate();
if (p_subpop.migrant_fractions_.count(p_source_subpop_id) != 0)
p_subpop.migrant_fractions_.erase(p_source_subpop_id);
if (p_migrant_fraction > 0.0) // BCH 4 March 2015: Added this if so we don't put a 0.0 migration rate into the table; harmless but looks bad in SLiMgui...
p_subpop.migrant_fractions_.emplace(p_source_subpop_id, p_migrant_fraction);
}
// WF only:
// apply mateChoice() callbacks to a mating event with a chosen first parent; the return is the second parent index, or -1 to force a redraw
slim_popsize_t Population::ApplyMateChoiceCallbacks(slim_popsize_t p_parent1_index, Subpopulation *p_subpop, Subpopulation *p_source_subpop, std::vector<SLiMEidosBlock*> &p_mate_choice_callbacks)
{
THREAD_SAFETY_IN_ANY_PARALLEL("Population::ApplyMateChoiceCallbacks(): running Eidos callback");
#if (SLIMPROFILING == 1)
// PROFILING
SLIM_PROFILE_BLOCK_START();
#endif
SLiMEidosBlockType old_executing_block_type = community_.executing_block_type_;
community_.executing_block_type_ = SLiMEidosBlockType::SLiMEidosMateChoiceCallback;
// We start out using standard weights taken from the source subpopulation. If, when we are done handling callbacks, we are still
// using those standard weights, then we can do a draw using our fast lookup tables. Otherwise, we will do a draw the hard way.
bool sex_enabled = p_subpop->sex_enabled_;
double *standard_weights = (sex_enabled ? p_source_subpop->cached_male_fitness_ : p_source_subpop->cached_parental_fitness_);
double *current_weights = standard_weights;
slim_popsize_t weights_length = p_source_subpop->cached_fitness_size_;
bool weights_modified = false;
Individual *chosen_mate = nullptr; // callbacks can return an Individual instead of a weights vector, held here
bool weights_reflect_chosen_mate = false; // if T, a weights vector has been created with a 1 for the chosen mate, to pass to the next callback
SLiMEidosBlock *last_interventionist_mate_choice_callback = nullptr;
for (SLiMEidosBlock *mate_choice_callback : p_mate_choice_callbacks)
{
if (mate_choice_callback->block_active_)
{
#if DEBUG_POINTS_ENABLED
// SLiMgui debugging point
EidosDebugPointIndent indenter;
{
EidosInterpreterDebugPointsSet *debug_points = community_.DebugPoints();
EidosToken *decl_token = mate_choice_callback->root_node_->token_;
if (debug_points && debug_points->set.size() && (decl_token->token_line_ != -1) &&
(debug_points->set.find(decl_token->token_line_) != debug_points->set.end()))
{
SLIM_ERRSTREAM << EidosDebugPointIndent::Indent() << "#DEBUG mateChoice(";
if (mate_choice_callback->subpopulation_id_ != -1)
SLIM_ERRSTREAM << "p" << mate_choice_callback->subpopulation_id_;
SLIM_ERRSTREAM << ")";
if (mate_choice_callback->block_id_ != -1)
SLIM_ERRSTREAM << " s" << mate_choice_callback->block_id_;
SLIM_ERRSTREAM << " (line " << (decl_token->token_line_ + 1) << community_.DebugPointInfo() << ")" << std::endl;
indenter.indent();
}
}
#endif
// local variables for the callback parameters that we might need to allocate here, and thus need to free below
EidosValue_SP local_weights_ptr;
bool redraw_mating = false;
if (chosen_mate && !weights_reflect_chosen_mate && mate_choice_callback->contains_weights_)
{
// A previous callback said it wanted a specific individual to be the mate. We now need to make a weights vector
// to represent that, since we have another callback that wants an incoming weights vector.
if (!weights_modified)
{
current_weights = (double *)malloc(sizeof(double) * weights_length); // allocate a new weights vector
if (!current_weights)
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): allocation failed; you may need to raise the memory limit for SLiM." << EidosTerminate(nullptr);
weights_modified = true;
}
EIDOS_BZERO(current_weights, sizeof(double) * weights_length);
current_weights[chosen_mate->index_] = 1.0;
weights_reflect_chosen_mate = true;
}
// The callback is active, so we need to execute it; we start a block here to manage the lifetime of the symbol table
{
EidosSymbolTable callback_symbols(EidosSymbolTableType::kContextConstantsTable, &community_.SymbolTable());
EidosSymbolTable client_symbols(EidosSymbolTableType::kLocalVariablesTable, &callback_symbols);
EidosFunctionMap &function_map = community_.FunctionMap();
EidosInterpreter interpreter(mate_choice_callback->compound_statement_node_, client_symbols, function_map, &community_, SLIM_OUTSTREAM, SLIM_ERRSTREAM);
if (mate_choice_callback->contains_self_)
callback_symbols.InitializeConstantSymbolEntry(mate_choice_callback->SelfSymbolTableEntry()); // define "self"
// Set all of the callback's parameters; note we use InitializeConstantSymbolEntry() for speed.
// We can use that method because we know the lifetime of the symbol table is shorter than that of
// the value objects, and we know that the values we are setting here will not change (the objects
// referred to by the values may change, but the values themselves will not change).
if (mate_choice_callback->contains_individual_)
{
Individual *parent1 = p_source_subpop->parent_individuals_[p_parent1_index];
callback_symbols.InitializeConstantSymbolEntry(gID_individual, parent1->CachedEidosValue());
}
if (mate_choice_callback->contains_subpop_)
callback_symbols.InitializeConstantSymbolEntry(gID_subpop, p_subpop->SymbolTableEntry().second);
if (mate_choice_callback->contains_sourceSubpop_)
callback_symbols.InitializeConstantSymbolEntry(gID_sourceSubpop, p_source_subpop->SymbolTableEntry().second);
if (mate_choice_callback->contains_weights_)
{
local_weights_ptr = EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Float(current_weights, weights_length));
callback_symbols.InitializeConstantSymbolEntry(gEidosID_weights, local_weights_ptr);
}
try
{
// Interpret the script; the result from the interpretation can be one of several things, so this is a bit complicated
EidosValue_SP result_SP = interpreter.EvaluateInternalBlock(mate_choice_callback->script_);
EidosValue *result = result_SP.get();
EidosValueType result_type = result->Type();
if (result_type == EidosValueType::kValueVOID)
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): mateChoice() callbacks must explicitly return a value." << EidosTerminate(mate_choice_callback->identifier_token_);
else if (result_type == EidosValueType::kValueNULL)
{
// NULL indicates that the mateChoice() callback did not wish to alter the weights, so we do nothing
}
else if (result_type == EidosValueType::kValueObject)
{
// A singleton vector of type Individual may be returned to choose a specific mate
if ((result->Count() == 1) && (((EidosValue_Object *)result)->Class() == gSLiM_Individual_Class))
{
#if DEBUG
// this checks the value type at runtime
chosen_mate = (Individual *)result->ObjectData()[0];
#else
// unsafe cast for speed
chosen_mate = (Individual *)((EidosValue_Object *)result)->data()[0];
#endif
weights_reflect_chosen_mate = false;
// remember this callback for error attribution below
last_interventionist_mate_choice_callback = mate_choice_callback;
}
else
{
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): invalid return value for mateChoice() callback." << EidosTerminate(mate_choice_callback->identifier_token_);
}
}
else if (result_type == EidosValueType::kValueFloat)
{
int result_count = result->Count();
if (result_count == 0)
{
// a return of float(0) indicates that there is no acceptable mate for the first parent; the first parent must be redrawn
redraw_mating = true;
}
else if (result_count == weights_length)
{
// if we used to have a specific chosen mate, we don't any more
chosen_mate = nullptr;
weights_reflect_chosen_mate = false;
// a non-zero float vector must match the size of the source subpop, and provides a new set of weights for us to use
if (!weights_modified)
{
current_weights = (double *)malloc(sizeof(double) * weights_length); // allocate a new weights vector
if (!current_weights)
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): allocation failed; you may need to raise the memory limit for SLiM." << EidosTerminate(nullptr);
weights_modified = true;
}
// use FloatData() to get the values, copy them with memcpy()
memcpy(current_weights, result->FloatData(), sizeof(double) * weights_length);
// remember this callback for error attribution below
last_interventionist_mate_choice_callback = mate_choice_callback;
}
else
{
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): invalid return value for mateChoice() callback." << EidosTerminate(mate_choice_callback->identifier_token_);
}
}
else
{
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): invalid return value for mateChoice() callback." << EidosTerminate(mate_choice_callback->identifier_token_);
}
}
catch (...)
{
throw;
}
}
// If this callback told us not to generate the child, we do not call the rest of the callback chain; we're done
if (redraw_mating)
{
if (weights_modified)
free(current_weights);
community_.executing_block_type_ = old_executing_block_type;
#if (SLIMPROFILING == 1)
// PROFILING
SLIM_PROFILE_BLOCK_END(community_.profile_callback_totals_[(int)(SLiMEidosBlockType::SLiMEidosMateChoiceCallback)]);
#endif
return -1;
}
}
}
// If we have a specific chosen mate, then we don't need to draw, but we do need to check the sex of the proposed mate
if (chosen_mate)
{
slim_popsize_t drawn_parent = chosen_mate->index_;
if (weights_modified)
free(current_weights);
if (sex_enabled)
{
if (drawn_parent < p_source_subpop->parent_first_male_index_)
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): second parent chosen by mateChoice() callback is female." << EidosTerminate(last_interventionist_mate_choice_callback->identifier_token_);
}
community_.executing_block_type_ = old_executing_block_type;
#if (SLIMPROFILING == 1)
// PROFILING
SLIM_PROFILE_BLOCK_END(community_.profile_callback_totals_[(int)(SLiMEidosBlockType::SLiMEidosMateChoiceCallback)]);
#endif
return drawn_parent;
}
// If a callback supplied a different set of weights, we need to use those weights to draw a male parent
if (weights_modified)
{
slim_popsize_t drawn_parent = -1;
double weights_sum = 0;
int positive_count = 0;
// first we assess the weights vector: get its sum, bounds-check it, etc.
for (slim_popsize_t weight_index = 0; weight_index < weights_length; ++weight_index)
{
double x = current_weights[weight_index];
if (!std::isfinite(x))
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): weight returned by mateChoice() callback is not finite." << EidosTerminate(last_interventionist_mate_choice_callback->identifier_token_);
if (x > 0.0)
{
positive_count++;
weights_sum += x;
continue;
}
if (x < 0.0)
EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): weight returned by mateChoice() callback is less than 0.0." << EidosTerminate(last_interventionist_mate_choice_callback->identifier_token_);
}
if (weights_sum <= 0.0)
{
// We used to consider this an error; now we consider it to represent the first parent having no acceptable choice, so we
// re-draw. Returning float(0) is essentially equivalent, except that it short-circuits the whole mateChoice() callback
// chain, whereas returning a vector of 0 values can be modified by a downstream mateChoice() callback. Usually that is
// not an important distinction. Returning float(0) is faster in principle, but if one is already constructing a vector
// of weights that can simply end up being all zero, then this path is much easier. BCH 5 March 2017
//EIDOS_TERMINATION << "ERROR (Population::ApplyMateChoiceCallbacks): weights returned by mateChoice() callback sum to 0.0 or less." << EidosTerminate(last_interventionist_mate_choice_callback->identifier_token_);
free(current_weights);
community_.executing_block_type_ = old_executing_block_type;
#if (SLIMPROFILING == 1)
// PROFILING
SLIM_PROFILE_BLOCK_END(community_.profile_callback_totals_[(int)(SLiMEidosBlockType::SLiMEidosMateChoiceCallback)]);
#endif
return -1;
}
// then we draw from the weights vector
if (positive_count == 1)
{
// there is only a single positive value, so the callback has chosen a parent for us; we just need to locate it
// we could have noted it above, but I don't want to slow down that loop, since many positive weights is the likely case
for (slim_popsize_t weight_index = 0; weight_index < weights_length; ++weight_index)
if (current_weights[weight_index] > 0.0)
{
drawn_parent = weight_index;
break;
}
}
else if (positive_count <= weights_length / 4) // the threshold here is a guess
{
// there are just a few positive values, so try to be faster about scanning for them by checking for zero first
gsl_rng *rng = EIDOS_GSL_RNG(omp_get_thread_num());
double the_rose_in_the_teeth = Eidos_rng_uniform_pos(rng) * weights_sum;
double bachelor_sum = 0.0;
for (slim_popsize_t weight_index = 0; weight_index < weights_length; ++weight_index)
{
double weight = current_weights[weight_index];
if (weight > 0.0)
{
bachelor_sum += weight;
if (the_rose_in_the_teeth <= bachelor_sum)
{
drawn_parent = weight_index;
break;
}
}
}
}
else
{
// there are many positive values, so we need to do a uniform draw and see who gets the rose
gsl_rng *rng = EIDOS_GSL_RNG(omp_get_thread_num());
double the_rose_in_the_teeth = Eidos_rng_uniform_pos(rng) * weights_sum;
double bachelor_sum = 0.0;
for (slim_popsize_t weight_index = 0; weight_index < weights_length; ++weight_index)
{
bachelor_sum += current_weights[weight_index];
if (the_rose_in_the_teeth <= bachelor_sum)
{