-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathindividual.cpp
5204 lines (4286 loc) · 219 KB
/
individual.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
//
// individual.cpp
// SLiM
//
// Created by Ben Haller on 6/10/16.
// Copyright (c) 2016-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 "individual.h"
#include "subpopulation.h"
#include "species.h"
#include "community.h"
#include "eidos_property_signature.h"
#include "eidos_call_signature.h"
#include "polymorphism.h"
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <fstream>
#include <utility>
#pragma mark -
#pragma mark Individual
#pragma mark -
// A global counter used to assign all Individual objects a unique ID
slim_pedigreeid_t gSLiM_next_pedigree_id = 0;
// Static member bools that track whether any individual has ever sustained a particular type of change
bool Individual::s_any_individual_color_set_ = false;
bool Individual::s_any_individual_dictionary_set_ = false;
bool Individual::s_any_individual_tag_set_ = false;
bool Individual::s_any_individual_tagF_set_ = false;
bool Individual::s_any_individual_tagL_set_ = false;
bool Individual::s_any_haplosome_tag_set_ = false;
bool Individual::s_any_individual_fitness_scaling_set_ = false;
// individual first, haplosomes later; this is the new multichrom paradigm
// BCH 10/12/2024: Note that this will rarely be called after simulation startup; see NewSubpopIndividual()
Individual::Individual(Subpopulation *p_subpopulation, slim_popsize_t p_individual_index, IndividualSex p_sex, slim_age_t p_age, double p_fitness, float p_mean_parent_age) :
#ifdef SLIMGUI
color_set_(false),
#endif
mean_parent_age_(p_mean_parent_age), pedigree_id_(-1), pedigree_p1_(-1), pedigree_p2_(-1),
pedigree_g1_(-1), pedigree_g2_(-1), pedigree_g3_(-1), pedigree_g4_(-1), reproductive_output_(0),
sex_(p_sex), migrant_(false), killed_(false), cached_fitness_UNSAFE_(p_fitness),
#ifdef SLIMGUI
cached_unscaled_fitness_(p_fitness),
#endif
age_(p_age), index_(p_individual_index), subpopulation_(p_subpopulation)
{
// Set up our haplosomes with nullptr values initially. If we have 0/1/2 haplosomes total, we use our
// internal buffer for speed; avoid malloc/free entirely, and even more important, get the memory
// locality of having the haplosome pointers right inside the individual itself. Otherwise, we alloc
// an external buffer, which entails fetching a new cache line to go through the indirection.
int haplosome_count_per_individual = subpopulation_->HaplosomeCountPerIndividual();
if (haplosome_count_per_individual <= 2)
{
hapbuffer_[0] = nullptr;
hapbuffer_[1] = nullptr;
haplosomes_ = hapbuffer_;
}
else
{
haplosomes_ = (Haplosome **)calloc(haplosome_count_per_individual, sizeof(Haplosome *));
}
// Initialize tag values to the "unset" value
tag_value_ = SLIM_TAG_UNSET_VALUE;
tagF_value_ = SLIM_TAGF_UNSET_VALUE;
tagL0_set_ = false;
tagL1_set_ = false;
tagL2_set_ = false;
tagL3_set_ = false;
tagL4_set_ = false;
// Initialize x/y/z to 0.0, only when leak-checking (they show up as used before initialized in Valgrind)
#if SLIM_LEAK_CHECKING
spatial_x_ = 0.0;
spatial_y_ = 0.0;
spatial_z_ = 0.0;
#endif
}
Individual::~Individual(void)
{
// BCH 10/6/2024: Individual now owns the haplosomes inside it (a policy change for multichrom)
// BCH 10/12/2024: Note that this might no longer be called except at simulation end; see FreeSubpopIndividual()
Subpopulation *subpop = subpopulation_;
// The subpopulation_ pointer is set to nullptr when an individual is placed in individuals_junkyard_;
// in that case, its haplosomes have already been freed, so this loop does not need to run.
if (subpopulation_)
{
const std::vector<Chromosome *> &chromosome_for_haplosome_index = subpopulation_->species_.ChromosomesForHaplosomeIndices();
int haplosome_count_per_individual = subpop->HaplosomeCountPerIndividual();
Haplosome **haplosomes = haplosomes_;
for (int haplosome_index = 0; haplosome_index < haplosome_count_per_individual; ++haplosome_index)
{
Haplosome *haplosome = haplosomes[haplosome_index];
// haplosome pointers can be nullptr, if an individual has already freed its haplosome objects;
// this happens when an individual is placed in individuals_junkyard_, in particular
if (haplosome)
{
Chromosome *chromosome = chromosome_for_haplosome_index[haplosome_index];
chromosome->FreeHaplosome(haplosome);
}
}
}
if (haplosomes_ != hapbuffer_)
free(haplosomes_);
#if DEBUG
haplosomes_ = nullptr;
#endif
}
#if DEBUG
void Individual::AddHaplosomeAtIndex(Haplosome *p_haplosome, int p_index)
{
int haplosome_count_per_individual = subpopulation_->HaplosomeCountPerIndividual();
if ((p_index < 0) || (p_index >= haplosome_count_per_individual))
EIDOS_TERMINATION << "ERROR (Individual::AddHaplosomeAtIndex): (internal error) haplosome index " << p_index << " out of range." << EidosTerminate();
// in DEBUG haplosomes_ should be zero-filled; when not in DEBUG, it may not be!
if (haplosomes_[p_index])
EIDOS_TERMINATION << "ERROR (Individual::AddHaplosomeAtIndex): (internal error) haplosome index " << p_index << " already filled." << EidosTerminate();
// the haplosome should already know that it belongs to the individual; this method just makes the individual aware of that
if (p_haplosome->individual_ != this)
EIDOS_TERMINATION << "ERROR (Individual::AddHaplosomeAtIndex): (internal error) haplosome individual_ pointer not set up." << EidosTerminate();
haplosomes_[p_index] = p_haplosome;
}
#endif
void Individual::AppendHaplosomesForChromosomes(EidosValue_Object *vec, std::vector<slim_chromosome_index_t> &chromosome_indices, int64_t index, bool includeNulls)
{
Species &species = subpopulation_->species_;
for (slim_chromosome_index_t chromosome_index : chromosome_indices)
{
Chromosome *chromosome = species.Chromosomes()[chromosome_index];
int first_haplosome_index = species.FirstHaplosomeIndices()[chromosome_index];
switch (chromosome->Type())
{
// diploid chromosome types, where we will use index if supplied
case ChromosomeType::kA_DiploidAutosome:
case ChromosomeType::kX_XSexChromosome:
case ChromosomeType::kZ_ZSexChromosome:
{
if ((index == -1) || (index == 0))
{
Haplosome *haplosome = haplosomes_[first_haplosome_index];
if (includeNulls || !haplosome->IsNull())
vec->push_object_element_NORR(haplosome);
}
if ((index == -1) || (index == 1))
{
Haplosome *haplosome = haplosomes_[first_haplosome_index+1];
if (includeNulls || !haplosome->IsNull())
vec->push_object_element_NORR(haplosome);
}
break;
}
// haploid chromosome types, where index is ignored
case ChromosomeType::kH_HaploidAutosome:
case ChromosomeType::kY_YSexChromosome:
case ChromosomeType::kW_WSexChromosome:
case ChromosomeType::kHF_HaploidFemaleInherited:
case ChromosomeType::kFL_HaploidFemaleLine:
case ChromosomeType::kHM_HaploidMaleInherited:
case ChromosomeType::kML_HaploidMaleLine:
case ChromosomeType::kHNull_HaploidAutosomeWithNull: // the null is just ignored by this code
{
Haplosome *haplosome = haplosomes_[first_haplosome_index];
if (includeNulls || !haplosome->IsNull())
vec->push_object_element_NORR(haplosome);
break;
}
// haploid chromosome types with a null haplosome first; index is ignored
case ChromosomeType::kNullY_YSexChromosomeWithNull:
{
Haplosome *haplosome = haplosomes_[first_haplosome_index+1]; // the (possibly) non-null haplosome
if (includeNulls || !haplosome->IsNull())
vec->push_object_element_NORR(haplosome);
break;
}
}
}
}
static inline bool _InPedigree(slim_pedigreeid_t A, slim_pedigreeid_t A_P1, slim_pedigreeid_t A_P2, slim_pedigreeid_t A_G1, slim_pedigreeid_t A_G2, slim_pedigreeid_t A_G3, slim_pedigreeid_t A_G4, slim_pedigreeid_t B)
{
if (B == -1)
return false;
if ((A == B) || (A_P1 == B) || (A_P2 == B) || (A_G1 == B) || (A_G2 == B) || (A_G3 == B) || (A_G4 == B))
return true;
return false;
}
static double _Relatedness(slim_pedigreeid_t A, slim_pedigreeid_t A_P1, slim_pedigreeid_t A_P2, slim_pedigreeid_t A_G1, slim_pedigreeid_t A_G2, slim_pedigreeid_t A_G3, slim_pedigreeid_t A_G4,
slim_pedigreeid_t B, slim_pedigreeid_t B_P1, slim_pedigreeid_t B_P2, slim_pedigreeid_t B_G1, slim_pedigreeid_t B_G2, slim_pedigreeid_t B_G3, slim_pedigreeid_t B_G4)
{
if ((A == -1) || (B == -1))
{
// Unknown pedigree IDs do not match anybody
return 0.0;
}
else if (A == B)
{
// An individual matches itself with relatedness 1.0
return 1.0;
}
else {
double out = 0.0;
if (_InPedigree(B, B_P1, B_P2, B_G1, B_G2, B_G3, B_G4, A)) // if A is in B...
{
out += _Relatedness(A, A_P1, A_P2, A_G1, A_G2, A_G3, A_G4, B_P1, B_G1, B_G2, -1, -1, -1, -1) / 2.0;
out += _Relatedness(A, A_P1, A_P2, A_G1, A_G2, A_G3, A_G4, B_P2, B_G3, B_G4, -1, -1, -1, -1) / 2.0;
}
else
{
out += _Relatedness(A_P1, A_G1, A_G2, -1, -1, -1, -1, B, B_P1, B_P2, B_G1, B_G2, B_G3, B_G4) / 2.0;
out += _Relatedness(A_P2, A_G3, A_G4, -1, -1, -1, -1, B, B_P1, B_P2, B_G1, B_G2, B_G3, B_G4) / 2.0;
}
return out;
}
}
double Individual::_Relatedness(slim_pedigreeid_t A, slim_pedigreeid_t A_P1, slim_pedigreeid_t A_P2, slim_pedigreeid_t A_G1, slim_pedigreeid_t A_G2, slim_pedigreeid_t A_G3, slim_pedigreeid_t A_G4,
slim_pedigreeid_t B, slim_pedigreeid_t B_P1, slim_pedigreeid_t B_P2, slim_pedigreeid_t B_G1, slim_pedigreeid_t B_G2, slim_pedigreeid_t B_G3, slim_pedigreeid_t B_G4,
IndividualSex A_sex, IndividualSex B_sex, ChromosomeType p_chromosome_type)
{
// This version of _Relatedness() corrects for the sex chromosome case. It should be regarded as the top-level internal API here.
// This is separate from RelatednessToIndividual(), and implemented as a static member function, for unit testing; we want an
// API that unit tests can call without needing to actually have a constructed Individual object.
// Correct for sex-chromosome simulations; the only individuals that count are those that pass on the sex chromosome to the
// child. We can do that here since we know that the first parent of a given individual is female and the second is male.
// If individuals are cloning, then both parents will be the same sex as the offspring, in fact, but we still want to
// treat it the same I think (?). For example, a male offspring from biparental mating inherits an X from its female
// parent only; a male offspring from cloning still inherits only one sex chromosome from its parent, so the same correction
// seems appropriate still.
#if DEBUG
if ((p_chromosome_type != ChromosomeType::kA_DiploidAutosome) && ((A_sex == IndividualSex::kHermaphrodite) || (B_sex == IndividualSex::kHermaphrodite)))
EIDOS_TERMINATION << "ERROR (Individual::_Relatedness): (internal error) hermaphrodites cannot exist when modeling a sex chromosome" << EidosTerminate();
if (((A_sex == IndividualSex::kHermaphrodite) && (B_sex != IndividualSex::kHermaphrodite)) || ((A_sex != IndividualSex::kHermaphrodite) && (B_sex == IndividualSex::kHermaphrodite)))
EIDOS_TERMINATION << "ERROR (Individual::_Relatedness): (internal error) hermaphrodites cannot coexist with males and females" << EidosTerminate();
if (((A_sex == IndividualSex::kMale) && (B_P1 == A) && (B_P1 != B_P2)) ||
((B_sex == IndividualSex::kMale) && (A_P1 == B) && (A_P1 != A_P2)) ||
((A_sex == IndividualSex::kFemale) && (B_P2 == A) && (B_P2 != B_P1)) ||
((B_sex == IndividualSex::kFemale) && (A_P2 == B) && (A_P2 != A_P1)))
EIDOS_TERMINATION << "ERROR (Individual::_Relatedness): (internal error) a male was indicated as a first parent, or a female as second parent, without clonality" << EidosTerminate();
#endif
switch (p_chromosome_type)
{
case ChromosomeType::kA_DiploidAutosome:
case ChromosomeType::kH_HaploidAutosome:
{
// No intervention needed (we assume that inheritance was normal, without null haplosomes)
// For "H", recombination is possible if there are two parents, so this is the same as "A"
break;
}
case ChromosomeType::kHNull_HaploidAutosomeWithNull:
{
// For "H-", the second parent should always match the first (by cloning), but we make sure of it
B_P1 = A_P1;
B_P2 = A_P2;
B_G1 = A_G1;
B_G2 = A_G2;
B_G3 = A_G3;
B_G4 = A_G4;
break;
}
case ChromosomeType::kX_XSexChromosome:
{
// Whichever sex A is, its second parent (A_P2) is male and so its male parent (A_G4) gave A_P2 a Y, not an X
A_G4 = A_G3;
if (A_sex == IndividualSex::kMale)
{
// If A is male, its second parent (male) gave it a Y, not an X
A_P2 = A_P1;
A_G3 = A_G1;
A_G4 = A_G2;
}
// Whichever sex B is, its second parent (B_P2) is male and so its male parent (B_G4) gave B_P2 a Y, not an X
B_G4 = B_G3;
if (B_sex == IndividualSex::kMale)
{
// If B is male, its second parent (male) gave it a Y, not an X
B_P2 = B_P1;
B_G3 = B_G1;
B_G4 = B_G2;
}
break;
}
case ChromosomeType::kY_YSexChromosome:
case ChromosomeType::kNullY_YSexChromosomeWithNull:
case ChromosomeType::kML_HaploidMaleLine:
{
// When modeling the Y, females have no relatedness to anybody else except themselves, defined as 1.0 for consistency
if ((A_sex == IndividualSex::kFemale) || (B_sex == IndividualSex::kFemale))
{
if (A == B)
return 1.0;
return 0.0;
}
// The female parents (A_P1 and B_P1) and their parents, and female grandparents (A_G3 and B_G3), do not contribute
A_G3 = A_G4;
A_P1 = A_P2;
A_G1 = A_G3;
A_G2 = A_G4;
B_G3 = B_G4;
B_P1 = B_P2;
B_G1 = B_G3;
B_G2 = B_G4;
break;
}
case ChromosomeType::kHM_HaploidMaleInherited:
{
// inherited from the male parent, so only the male (second) parents count
A_G3 = A_G4;
A_P1 = A_P2;
A_G1 = A_G3;
A_G2 = A_G4;
B_G3 = B_G4;
B_P1 = B_P2;
B_G1 = B_G3;
B_G2 = B_G4;
break;
}
case ChromosomeType::kZ_ZSexChromosome:
{
// Whichever sex A is, its first parent (A_P1) is female and so its female parent (A_G1) gave A_P1 a W, not a Z
A_G1 = A_G2;
if (A_sex == IndividualSex::kFemale)
{
// If A is female, its first parent (female) gave it a W, not a Z
A_P1 = A_P2;
A_G1 = A_G3;
A_G2 = A_G4;
}
// Whichever sex B is, its first parent (B_P1) is female and so its female parent (B_G1) gave B_P1 a W, not a Z
B_G1 = B_G2;
if (B_sex == IndividualSex::kFemale)
{
// If B is female, its first parent (female) gave it a W, not a Z
B_P1 = B_P2;
B_G1 = B_G3;
B_G2 = B_G4;
}
break;
}
case ChromosomeType::kW_WSexChromosome:
case ChromosomeType::kFL_HaploidFemaleLine:
{
// When modeling the W, males have no relatedness to anybody else except themselves, defined as 1.0 for consistency
if ((A_sex == IndividualSex::kMale) || (B_sex == IndividualSex::kMale))
{
if (A == B)
return 1.0;
return 0.0;
}
// The male parents (A_P2 and B_P2) and their parents, and male grandparents (A_G2 and B_G2), do not contribute
A_G2 = A_G1;
A_P2 = A_P1;
A_G3 = A_G1;
A_G4 = A_G2;
B_G2 = B_G1;
B_P2 = B_P1;
B_G3 = B_G1;
B_G4 = B_G2;
break;
}
case ChromosomeType::kHF_HaploidFemaleInherited:
{
// inherited from the female parent, so only the female (first) parents count
A_G2 = A_G1;
A_P2 = A_P1;
A_G3 = A_G1;
A_G4 = A_G2;
B_G2 = B_G1;
B_P2 = B_P1;
B_G3 = B_G1;
B_G4 = B_G2;
break;
}
}
return ::_Relatedness(A, A_P1, A_P2, A_G1, A_G2, A_G3, A_G4, B, B_P1, B_P2, B_G1, B_G2, B_G3, B_G4);
}
double Individual::RelatednessToIndividual(Individual &p_ind, ChromosomeType p_chromosome_type)
{
// So, the goal is to calculate A and B's relatedness, given pedigree IDs for themselves and (perhaps) for their parents and
// grandparents. Note that a pedigree ID of -1 means "no information"; for a given cycle, information should either be
// available for everybody, or for nobody (the latter occurs when that cycle is prior to the start of forward simulation).
// So we have these ancestry trees:
//
// G1 G2 G3 G4 G5 G6 G7 G8
// \ / \ / \ / \ /
// P1 P2 P3 P4
// \ / \ /
// \ / \ /
// \ / \ /
// A B
//
// If A and B are same individual, the relatedness is 1.0. Otherwise, we need to determine the amount of consanguinity between
// A and B. If A is a parent of B (P3 or P4), their relatedness is 0.5; if A is a grandparent of B (G5/G6/G7/G8), then their
// relatedness is 0.25. A could also appear in B's tree more than once, but A cannot be its own parent. So if A==P3, then A
// cannot also be G5 or G6, and indeed, we do not need to look at G5 or G6 at all; the fact that A==P3 tells us everything we
// we need to know about that half of B's tree, with a contribution of 0.5. But it could *additionally* be true that A==P4,
// giving another 0.5 for 1.0 total; or that A==G7, for 0.25; or that A==G8, for 0.25; for that A==G7 *and* A==G8, for 0.5,
// making 1.0 total. Basically, whenever you see A at a given position you do not need to look further upward from that node,
// but you must still look at other nodes. To do this properly, recursion is the simplest approach; this algorithm is thanks
// to Peter Ralph.
//
Individual &indA = *this, &indB = p_ind;
slim_pedigreeid_t A = indA.pedigree_id_;
slim_pedigreeid_t A_P1 = indA.pedigree_p1_;
slim_pedigreeid_t A_P2 = indA.pedigree_p2_;
slim_pedigreeid_t A_G1 = indA.pedigree_g1_;
slim_pedigreeid_t A_G2 = indA.pedigree_g2_;
slim_pedigreeid_t A_G3 = indA.pedigree_g3_;
slim_pedigreeid_t A_G4 = indA.pedigree_g4_;
slim_pedigreeid_t B = indB.pedigree_id_;
slim_pedigreeid_t B_P1 = indB.pedigree_p1_;
slim_pedigreeid_t B_P2 = indB.pedigree_p2_;
slim_pedigreeid_t B_G1 = indB.pedigree_g1_;
slim_pedigreeid_t B_G2 = indB.pedigree_g2_;
slim_pedigreeid_t B_G3 = indB.pedigree_g3_;
slim_pedigreeid_t B_G4 = indB.pedigree_g4_;
return _Relatedness(A, A_P1, A_P2, A_G1, A_G2, A_G3, A_G4, B, B_P1, B_P2, B_G1, B_G2, B_G3, B_G4, indA.sex_, indB.sex_, p_chromosome_type);
}
int Individual::_SharedParentCount(slim_pedigreeid_t X_P1, slim_pedigreeid_t X_P2, slim_pedigreeid_t Y_P1, slim_pedigreeid_t Y_P2)
{
// This is the top-level internal API here. It is separate from RelatednessToIndividual(), and
// implemented as a static member function, for unit testing; we want an
// API that unit tests can call without needing to actually have a constructed Individual object.
// If one individual is missing parent information, return 0
if ((X_P1 == -1) || (X_P2 == -1) || (Y_P1 == -1) || (Y_P2 == -1))
return 0;
// If both parents match, in one way or another, then they must be full siblings
if ((X_P1 == Y_P1) && (X_P2 == Y_P2))
return 2;
if ((X_P1 == Y_P2) && (X_P2 == Y_P1))
return 2;
// Otherwise, if one parent matches, they must be half siblings
if ((X_P1 == Y_P1) || (X_P1 == Y_P2) || (X_P2 == Y_P1) || (X_P2 == Y_P2))
return 1;
// Otherwise, they are not siblings
return 0;
}
int Individual::SharedParentCountWithIndividual(Individual &p_ind)
{
// This is much simpler than Individual::RelatednessToIndividual(); we just want the shared parent count. That is
// defined, for two individuals X and Y with parents in {A, B, C, D}, as:
//
// AB CD -> 0 (no shared parents)
// AB CC -> 0 (no shared parents)
// AB AC -> 1 (half siblings)
// AB AA -> 1 (half siblings)
// AA AB -> 1 (half siblings)
// AB AB -> 2 (full siblings)
// AB BA -> 2 (full siblings)
// AA AA -> 2 (full siblings)
//
// If X is itself a parent of Y, or vice versa, that is irrelevant for this method; we are not measuring
// consanguinity here.
//
Individual &indX = *this, &indY = p_ind;
slim_pedigreeid_t X_P1 = indX.pedigree_p1_;
slim_pedigreeid_t X_P2 = indX.pedigree_p2_;
slim_pedigreeid_t Y_P1 = indY.pedigree_p1_;
slim_pedigreeid_t Y_P2 = indY.pedigree_p2_;
return _SharedParentCount(X_P1, X_P2, Y_P1, Y_P2);
}
// print a vector of individuals, with all mutations and all haplosomes, to a stream
// this takes a focal chromosome; if nullptr, data from all chromosomes is printed
void Individual::PrintIndividuals_SLiM(std::ostream &p_out, const Individual **p_individuals, int64_t p_individuals_count, Species &species, bool p_output_spatial_positions, bool p_output_ages, bool p_output_ancestral_nucs, bool p_output_pedigree_ids, bool p_output_object_tags, bool p_output_substitutions, Chromosome *p_focal_chromosome)
{
Population &population = species.population_;
Community &community = species.community_;
if (population.child_generation_valid_)
EIDOS_TERMINATION << "ERROR (Individual::PrintIndividuals_SLiM): (internal error) called with child generation active!." << EidosTerminate();
#if DO_MEMORY_CHECKS
// This method can burn a huge amount of memory and get us killed, if we have a maximum memory usage. It's nice to
// try to check for that and terminate with a proper error message, to help the user diagnose the problem.
int mem_check_counter = 0, mem_check_mod = 100;
if (eidos_do_memory_checks)
Eidos_CheckRSSAgainstMax("Individual::PrintIndividuals_SLiM", "(The memory usage was already out of bounds on entry.)");
#endif
// this method now handles outputFull() as well as outputIndividuals()
bool output_full_population = (p_individuals == nullptr);
if (output_full_population)
{
// We need to set up an individuals vector that contains all individuals, so we can share code below
int64_t total_population_size = 0;
for (const std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : population.subpops_)
{
Subpopulation *subpop = subpop_pair.second;
slim_popsize_t subpop_size = subpop->parent_subpop_size_;
total_population_size += subpop_size;
}
p_individuals = (const Individual **)malloc(total_population_size * sizeof(Individual *));
p_individuals_count = total_population_size;
const Individual **ind_buffer_ptr = p_individuals;
for (const std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : population.subpops_)
{
Subpopulation *subpop = subpop_pair.second;
slim_popsize_t subpop_size = subpop->parent_subpop_size_;
for (slim_popsize_t i = 0; i < subpop_size; i++) // go through all children
*(ind_buffer_ptr++) = subpop->parent_individuals_[i];
}
}
// write the #OUT line
p_out << "#OUT: " << community.Tick() << " " << species.Cycle() << (output_full_population ? " A" : " IS") << std::endl;
// Figure out spatial position output. If it was not requested, then we don't do it, and that's fine. If it
// was requested, then we output the number of spatial dimensions we're configured for (which might be zero).
int spatial_output_count = (p_output_spatial_positions ? species.SpatialDimensionality() : 0);
// Figure out age output. If it was not requested, don't do it; if it was requested, do it if we use a nonWF model.
int age_output_count = (p_output_ages && (species.model_type_ == SLiMModelType::kModelTypeNonWF)) ? 1 : 0;
// Starting in SLiM 2.3, we output a version indicator at the top of the file so we can decode different
// versions, etc. Starting in SLiM 5, the version number is again synced with PrintAllBinary() (skipping
// over 7 directly to 8), and the crazy four-way version number scheme that encoded flags is gone. See
// PrintAllBinary() for the version history; but with version 8 we break backward compatibility anyway.
p_out << "Version: 8" << std::endl;
// Starting with version 8 (SLiM 5.0), we write out some flags; this information used to be incorporated into
// the version number, which was gross. Now we write out flags for all optional output that is enabled.
// Reading code can assume that if a flag is not present, that output is not present.
bool has_nucleotides = species.IsNucleotideBased();
bool output_ancestral_nucs = has_nucleotides && p_output_ancestral_nucs;
p_out << "Flags:";
if (spatial_output_count) p_out << " SPACE=" << spatial_output_count;
if (age_output_count) p_out << " AGES";
if (p_output_pedigree_ids) p_out << " PEDIGREES";
if (has_nucleotides) p_out << " NUC";
if (output_ancestral_nucs) p_out << " ANC_SEQ";
if (p_output_object_tags) p_out << " OBJECT_TAGS";
if (p_output_substitutions) p_out << " SUBSTITUTIONS";
p_out << std::endl;
// Output populations first, for outputFull() only
if (output_full_population)
{
p_out << "Populations:" << std::endl;
for (const std::pair<const slim_objectid_t,Subpopulation*> &subpop_pair : population.subpops_)
{
Subpopulation *subpop = subpop_pair.second;
slim_popsize_t subpop_size = subpop->parent_subpop_size_;
double subpop_sex_ratio;
if (species.model_type_ == SLiMModelType::kModelTypeWF)
{
subpop_sex_ratio = subpop->parent_sex_ratio_;
}
else
{
// We want to output empty (but not removed) subpops, so we use a sex ratio of 0.0 to prevent div by 0
if (subpop->parent_subpop_size_ == 0)
subpop_sex_ratio = 0.0;
else
subpop_sex_ratio = 1.0 - (subpop->parent_first_male_index_ / (double)subpop->parent_subpop_size_);
}
p_out << "p" << subpop_pair.first << " " << subpop_size;
// SEX ONLY
if (subpop->sex_enabled_)
p_out << " S " << subpop_sex_ratio;
else
p_out << " H";
if (p_output_object_tags)
{
if (subpop->tag_value_ == SLIM_TAG_UNSET_VALUE)
p_out << " ?";
else
p_out << ' ' << subpop->tag_value_;
}
p_out << std::endl;
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Individual::PrintIndividuals_SLiM", "(Out of memory while outputting population list.)");
}
#endif
}
}
// print all individuals; this used to come after the Mutations: section, but now mutations are per-chromosome,
// whereas the list of individuals is invariant across all of the chromosomes printed, and so must come before
p_out << "Individuals:" << std::endl;
THREAD_SAFETY_IN_ACTIVE_PARALLEL("Individual::PrintIndividuals_SLiM(): usage of statics");
static char double_buf[40];
for (int64_t individual_index = 0; individual_index < p_individuals_count; ++individual_index)
{
const Individual &individual = *(p_individuals[individual_index]);
Subpopulation *subpop = individual.subpopulation_;
slim_popsize_t index_in_subpop = individual.index_;
if (!subpop || (index_in_subpop == -1))
{
if (output_full_population)
free(p_individuals);
EIDOS_TERMINATION << "ERROR (Individual::PrintIndividuals_SLiM): target individuals must be visible in a subpopulation (i.e., may not be new juveniles)." << EidosTerminate();
}
p_out << "p" << subpop->subpopulation_id_ << ":i" << index_in_subpop; // individual identifier
// BCH 9/13/2020: adding individual pedigree IDs, for SLiM 3.5, format version 5/6
if (p_output_pedigree_ids)
p_out << " " << individual.PedigreeID();
p_out << ' ' << individual.sex_;
// BCH 2/5/2025: Before version 8, we emitted haplosome identifiers here, like "p1:16" and
// "p1:17", but now that we have multiple chromosomes that really isn't helpful; removing
// them. In the Haplosomes section we will now just identify the individual; that suffices.
// output spatial position if requested; BCH 22 March 2019 switch to full precision for this, for accurate reloading
if (spatial_output_count)
{
if (spatial_output_count >= 1)
{
snprintf(double_buf, 40, "%.*g", EIDOS_DBL_DIGS, individual.spatial_x_); // necessary precision for non-lossiness
p_out << " " << double_buf;
}
if (spatial_output_count >= 2)
{
snprintf(double_buf, 40, "%.*g", EIDOS_DBL_DIGS, individual.spatial_y_); // necessary precision for non-lossiness
p_out << " " << double_buf;
}
if (spatial_output_count >= 3)
{
snprintf(double_buf, 40, "%.*g", EIDOS_DBL_DIGS, individual.spatial_z_); // necessary precision for non-lossiness
p_out << " " << double_buf;
}
}
// output ages if requested
if (age_output_count)
p_out << " " << individual.age_;
// output individual tags if requested
if (p_output_object_tags)
{
if (individual.tag_value_ == SLIM_TAG_UNSET_VALUE)
p_out << " ?";
else
p_out << ' ' << individual.tag_value_;
if (individual.tagF_value_ == SLIM_TAGF_UNSET_VALUE)
p_out << " ?";
else
{
snprintf(double_buf, 40, "%.*g", EIDOS_DBL_DIGS, individual.tagF_value_); // necessary precision for non-lossiness
p_out << " " << double_buf;
}
if (individual.tagL0_set_)
p_out << ' ' << (individual.tagL0_value_ ? 'T' : 'F');
else
p_out << " ?";
if (individual.tagL1_set_)
p_out << ' ' << (individual.tagL1_value_ ? 'T' : 'F');
else
p_out << " ?";
if (individual.tagL2_set_)
p_out << ' ' << (individual.tagL2_value_ ? 'T' : 'F');
else
p_out << " ?";
if (individual.tagL3_set_)
p_out << ' ' << (individual.tagL3_value_ ? 'T' : 'F');
else
p_out << " ?";
if (individual.tagL4_set_)
p_out << ' ' << (individual.tagL4_value_ ? 'T' : 'F');
else
p_out << " ?";
}
p_out << std::endl;
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Population::PrintAll", "(Out of memory while printing individuals.)");
}
#endif
}
// Loop over chromosomes and output data for each
const std::vector<Chromosome *> &chromosomes = species.Chromosomes();
for (Chromosome *chromosome : chromosomes)
{
// if we have a focal chromosome, skip all the other chromosomes
if (p_focal_chromosome && (chromosome != p_focal_chromosome))
continue;
// write information about the chromosome; note that we write the chromosome symbol, but PrintAllBinary() does not
slim_chromosome_index_t chromosome_index = chromosome->Index();
p_out << "Chromosome: " << (uint32_t)chromosome_index << " " << chromosome->Type() << " " << chromosome->ID() << " " << chromosome->last_position_ << " \"" << chromosome->Symbol() << "\"";
if (p_output_object_tags)
{
if (chromosome->tag_value_ == SLIM_TAG_UNSET_VALUE)
p_out << " ?";
else
p_out << ' ' << chromosome->tag_value_;
}
p_out << std::endl;
int first_haplosome_index = species.FirstHaplosomeIndices()[chromosome_index];
int last_haplosome_index = species.LastHaplosomeIndices()[chromosome_index];
PolymorphismMap polymorphisms;
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
// add all polymorphisms for this chromosome
for (int64_t individual_index = 0; individual_index < p_individuals_count; ++individual_index)
{
const Individual *ind = p_individuals[individual_index];
Haplosome **haplosomes = ind->haplosomes_;
for (int haplosome_index = first_haplosome_index; haplosome_index <= last_haplosome_index; haplosome_index++)
{
Haplosome *haplosome = haplosomes[haplosome_index];
int mutrun_count = haplosome->mutrun_count_;
for (int run_index = 0; run_index < mutrun_count; ++run_index)
{
const MutationRun *mutrun = haplosome->mutruns_[run_index];
int mut_count = mutrun->size();
const MutationIndex *mut_ptr = mutrun->begin_pointer_const();
for (int mut_index = 0; mut_index < mut_count; ++mut_index)
AddMutationToPolymorphismMap(&polymorphisms, mut_block_ptr + mut_ptr[mut_index]);
}
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Population::PrintAll", "(Out of memory while assembling polymorphisms.)");
}
#endif
}
}
// print all polymorphisms
p_out << "Mutations:" << std::endl;
for (const PolymorphismPair &polymorphism_pair : polymorphisms)
{
// NOTE this added mutation_id_, BCH 11 June 2016
// NOTE the output format changed due to the addition of the nucleotide, BCH 2 March 2019
if (p_output_object_tags)
polymorphism_pair.second.Print_ID_Tag(p_out);
else
polymorphism_pair.second.Print_ID(p_out);
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Population::PrintAll", "(Out of memory while printing polymorphisms.)");
}
#endif
}
// print all haplosomes
p_out << "Haplosomes:" << std::endl;
for (int64_t individual_index = 0; individual_index < p_individuals_count; ++individual_index)
{
const Individual *ind = p_individuals[individual_index];
Haplosome **haplosomes = ind->haplosomes_;
for (int haplosome_index = first_haplosome_index; haplosome_index <= last_haplosome_index; haplosome_index++)
{
Haplosome *haplosome = haplosomes[haplosome_index];
// i used to be the haplosome index, now it is the individual index; we will have one or
// two lines with this individual index, depending on the intrinsic ploidy of the chromosome
// since we changed from a haplosome index to an individual index, we now emit an "i",
// just follow the same convention as the Individuals section
p_out << "p" << ind->subpopulation_->subpopulation_id_ << ":i" << ind->index_;
if (p_output_object_tags)
{
if (haplosome->tag_value_ == SLIM_TAG_UNSET_VALUE)
p_out << " ?";
else
p_out << ' ' << haplosome->tag_value_;
}
if (haplosome->IsNull())
{
p_out << " <null>";
}
else
{
int mutrun_count = haplosome->mutrun_count_;
for (int run_index = 0; run_index < mutrun_count; ++run_index)
{
const MutationRun *mutrun = haplosome->mutruns_[run_index];
int mut_count = mutrun->size();
const MutationIndex *mut_ptr = mutrun->begin_pointer_const();
for (int mut_index = 0; mut_index < mut_count; ++mut_index)
{
slim_polymorphismid_t polymorphism_id = FindMutationInPolymorphismMap(polymorphisms, mut_block_ptr + mut_ptr[mut_index]);
if (polymorphism_id == -1)
EIDOS_TERMINATION << "ERROR (Population::PrintAll): (internal error) polymorphism not found." << EidosTerminate();
p_out << " " << polymorphism_id;
}
}
}
p_out << std::endl;
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Population::PrintAll", "(Out of memory while printing haplosomes.)");
}
#endif
}
}
// print ancestral sequence
if (output_ancestral_nucs)
{
p_out << "Ancestral sequence:" << std::endl;
p_out << *(chromosome->AncestralSequence());
// operator<< above ends with a newline; here we add another, which the read code
// can use to recognize that the nucleotide sequence has ended, even without an EOF
p_out << std::endl;
}
}
// Output substitutions at the end if requested; see Species::ExecuteMethod_outputFixedMutations()
if (output_full_population && p_output_substitutions)
{
p_out << "Substitutions:" << std::endl;
std::vector<Substitution*> &subs = population.substitutions_;
for (unsigned int i = 0; i < subs.size(); i++)
{
p_out << i << " ";
if (p_output_object_tags)
subs[i]->PrintForSLiMOutput_Tag(p_out);
else
subs[i]->PrintForSLiMOutput(p_out);
#if DO_MEMORY_CHECKS
if (eidos_do_memory_checks)
{
mem_check_counter++;
if (mem_check_counter % mem_check_mod == 0)
Eidos_CheckRSSAgainstMax("Species::ExecuteMethod_outputFixedMutations", "(outputFixedMutations(): Out of memory while outputting substitution objects.)");
}
#endif
}
}
// if we malloced a buffer of individuals above, free it now
if (output_full_population)
free(p_individuals);
}
void Individual::PrintIndividuals_VCF(std::ostream &p_out, const Individual **p_individuals, int64_t p_individuals_count, Species &p_species, bool p_output_multiallelics, bool p_simplify_nucs, bool p_output_nonnucs, Chromosome *p_focal_chromosome)
{
const std::vector<Chromosome *> &chromosomes = p_species.Chromosomes();
bool nucleotide_based = p_species.IsNucleotideBased();
bool pedigrees_enabled = p_species.PedigreesEnabledByUser();
// print the VCF header
p_out << "##fileformat=VCFv4.2" << std::endl;
{
time_t rawtime;
struct tm timeinfo;
char buffer[25]; // should never be more than 10, in fact, plus a null
time(&rawtime);
localtime_r(&rawtime, &timeinfo);
strftime(buffer, 25, "%Y%m%d", &timeinfo);