-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathspecies_eidos.cpp
4338 lines (3509 loc) · 225 KB
/
species_eidos.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
//
// species_eidos.cpp
// SLiM
//
// Created by Ben Haller on 7/11/20.
// Copyright (c) 2020-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 "species.h"
#include "community.h"
#include "haplosome.h"
#include "individual.h"
#include "subpopulation.h"
#include "polymorphism.h"
#include "interaction_type.h"
#include "log_file.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <utility>
#include <algorithm>
#include <vector>
#include <cmath>
#include <ctime>
#include <unordered_map>
//
// Eidos support
//
#pragma mark -
#pragma mark Eidos support
#pragma mark -
// Note that the functions below are dispatched out by Community::ContextDefinedFunctionDispatch()
// ********************* (integer$)initializeAncestralNucleotides(is sequence)
//
EidosValue_SP Species::ExecuteContextFunction_initializeAncestralNucleotides(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
EidosValue *sequence_value = p_arguments[0].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
if (num_ancseq_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): initializeAncestralNucleotides() may be called only once." << EidosTerminate();
if (!nucleotide_based_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): initializeAncestralNucleotides() may be only be called in nucleotide-based models." << EidosTerminate();
EidosValueType sequence_value_type = sequence_value->Type();
int sequence_value_count = sequence_value->Count();
if (sequence_value_count == 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): initializeAncestralNucleotides() requires a sequence of length >= 1." << EidosTerminate();
// This function triggers the creation of an implicit chromosome if a chromosome has not already been set up
if ((num_chromosome_inits_ == 0) && !has_implicit_chromosome_)
MakeImplicitChromosome(ChromosomeType::kA_DiploidAutosome);
Chromosome *chromosome = CurrentlyInitializingChromosome();
if (sequence_value_type == EidosValueType::kValueInt)
{
// A vector of integers has been provided, where ACGT == 0123
const int64_t *int_data = sequence_value->IntData();
chromosome->ancestral_seq_buffer_ = new NucleotideArray(sequence_value_count, int_data);
}
else if (sequence_value_type == EidosValueType::kValueString)
{
if (sequence_value_count != 1)
{
// A vector of characters has been provided, which must all be "A" / "C" / "G" / "T"
const std::string *string_data = sequence_value->StringData();
chromosome->ancestral_seq_buffer_ = new NucleotideArray(sequence_value_count, string_data);
}
else // sequence_value_count == 1
{
const std::string &sequence_string = sequence_value->StringData()[0];
bool contains_only_nuc = true;
// OK, we do a weird thing here. We want to try to construct a NucleotideArray
// from sequence_string, which throws with EIDOS_TERMINATION if it fails, but
// we want to actually catch that exception even if we're running at the
// command line, where EIDOS_TERMINATION normally calls exit(). So we actually
// play around with the error-handling state to make it do what we want it to do.
// This is very naughty and should be redesigned, but right now I'm not seeing
// the right redesign strategy, so... hacking it for now. Parallel code is at
// Chromosome::ExecuteMethod_setAncestralNucleotides()
bool save_gEidosTerminateThrows = gEidosTerminateThrows;
gEidosTerminateThrows = true;
try {
chromosome->ancestral_seq_buffer_ = new NucleotideArray(sequence_string.length(), sequence_string.c_str());
} catch (...) {
contains_only_nuc = false;
// clean up the error state since we don't want this throw to be reported
gEidosTermination.clear();
gEidosTermination.str("");
}
gEidosTerminateThrows = save_gEidosTerminateThrows;
if (!contains_only_nuc)
{
// A singleton string has been provided that contains characters other than ACGT; we will interpret it as a filesystem path for a FASTA file
std::string file_path = Eidos_ResolvedPath(sequence_string);
std::ifstream file_stream(file_path.c_str());
if (!file_stream.is_open())
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): the file at path " << sequence_string << " could not be opened or does not exist." << EidosTerminate();
bool started_sequence = false;
std::string line, fasta_sequence;
while (getline(file_stream, line))
{
// skippable lines are blank or start with a '>' or ';'
// we skip over them if they're at the start of the file; once we start a sequence, they terminate the sequence
bool skippable = ((line.length() == 0) || (line[0] == '>') || (line[0] == ';'));
if (!started_sequence && skippable)
continue;
if (skippable)
break;
// otherwise, append the nucleotides from this line, removing a \r if one is present at the end of the line
if (line.back() == '\r')
line.pop_back();
fasta_sequence.append(line);
started_sequence = true;
}
if (file_stream.bad())
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): a filesystem error occurred while reading the file at path " << sequence_string << "." << EidosTerminate();
if (fasta_sequence.length() == 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): no FASTA sequence found in " << sequence_string << "." << EidosTerminate();
chromosome->ancestral_seq_buffer_ = new NucleotideArray(fasta_sequence.length(), fasta_sequence.c_str());
}
}
}
if (chromosome->extent_immutable_)
{
if (chromosome->ancestral_seq_buffer_->size() != (std::size_t)(chromosome->last_position_ + 1))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeAncestralNucleotides): the length of the provided ancestral sequence does not match the length of the chromosome." << EidosTerminate();
}
// debugging
//std::cout << "ancestral sequence set: " << *chromosome_->ancestral_seq_buffer_ << std::endl;
if (SLiM_verbosity_level >= 1)
{
output_stream << "initializeAncestralNucleotides(\"";
// output up to 20 nucleotides, followed by an ellipsis if necessary
for (std::size_t i = 0; (i < 20) && (i < chromosome->ancestral_seq_buffer_->size()); ++i)
output_stream << "ACGT"[chromosome->ancestral_seq_buffer_->NucleotideAtIndex(i)];
if (chromosome->ancestral_seq_buffer_->size() > 20)
output_stream << gEidosStr_ELLIPSIS;
output_stream << "\");" << std::endl;
}
num_ancseq_inits_++;
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Int(chromosome->ancestral_seq_buffer_->size()));
}
// ********************* (object<Chromosome>$)initializeChromosome(integer$ id, [Ni$ length = NULL], [string$ type = "A"], [Ns$ symbol = NULL], [Ns$ name = NULL], [integer$ mutationRuns = 0])
//
EidosValue_SP Species::ExecuteContextFunction_initializeChromosome(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
// We are starting the definition of a new explicitly defined chromosome. We zero out counts for all
// chromosome-specific initialization functions; this is a blank slate. An implicit chromosome is
// not allowed to have already been defined.
if (has_implicit_chromosome_)
{
if (num_mutrate_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeMutationRate() was called. To fix this error, call initializeChromosome() first and then call initializeMutationRate(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
if (num_recrate_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeRecombinationRate() was called. To fix this error, call initializeChromosome() first and then call initializeRecombinationRate(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
if (num_genomic_element_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeGenomicElement() was called. To fix this error, call initializeChromosome() first and then call initializeGenomicElement(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
if (num_gene_conv_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeGeneConversion() was called. To fix this error, call initializeChromosome() first and then call initializeGeneConversion(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
if (num_ancseq_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeAncestralNucleotides() was called. To fix this error, call initializeChromosome() first and then call initializeAncestralNucleotides(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
if (num_hotmap_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot be called to explicitly create a chromosome, because the chromosome has already been implicitly defined. This occurred because initializeHotspotMap() was called. To fix this error, call initializeChromosome() first and then call initializeHotspotMap(), or don't call initializeChromosome() at all if you do not need an explicitly defined chromosome." << EidosTerminate();
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): (internal error) initializeChromosome() was called with an implicitly defined chromosome. However, the cause of this cannot be diagnosed, indicating an internal logic error." << EidosTerminate();
}
if (chromosomes_.size() >= SLIM_MAX_CHROMOSOMES)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() cannot make a new chromosome because the maximum number of chromosomes allowed per species (" << SLIM_MAX_CHROMOSOMES << ") has already been reached. If you want to model a large number of unlinked loci, using a recombination rate of 0.5, rather than multiple chromosomes, is recommended." << EidosTerminate();
if (num_chromosome_inits_ > 0)
{
// A previous explicitly defined chromosome terminates its definition here,
// so we do some checking of that previous chromosome's integrity.
EndCurrentChromosome(/* starting_new_chromosome */ true);
}
num_mutrate_inits_ = 0;
num_recrate_inits_ = 0;
num_genomic_element_inits_ = 0;
num_gene_conv_inits_ = 0;
num_ancseq_inits_ = 0;
num_hotmap_inits_ = 0;
// Get parameters and bounds-check
EidosValue *id_value = p_arguments[0].get();
EidosValue *length_value = p_arguments[1].get();
EidosValue *type_value = p_arguments[2].get();
EidosValue *symbol_value = p_arguments[3].get();
EidosValue *name_value = p_arguments[4].get();
EidosValue *mutationRuns_value = p_arguments[5].get();
int64_t id = id_value->IntAtIndex_NOCAST(0, nullptr);
if (id < 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires id to be non-negative." << EidosTerminate();
if (ChromosomeFromID(id))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires id to be unique within the species; two chromosomes in the same species may not have the same id." << EidosTerminate();
// -1 represents a length of NULL, indicating the length is mutable and will be assessed later
slim_position_t length = -1;
if (length_value->Type() == EidosValueType::kValueInt)
{
length = SLiMCastToPositionTypeOrRaise(length_value->IntAtIndex_NOCAST(0, nullptr));
if (length - 1 > SLIM_MAX_BASE_POSITION)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires the last base position (length-1) to be <= 1e15." << EidosTerminate();
}
std::string type_string = type_value->StringAtIndex_NOCAST(0, nullptr);
ChromosomeType chromosome_type = ChromosomeTypeForString(type_string);
if (!sex_enabled_ &&
((chromosome_type == ChromosomeType::kX_XSexChromosome) ||
(chromosome_type == ChromosomeType::kY_YSexChromosome) ||
(chromosome_type == ChromosomeType::kZ_ZSexChromosome) ||
(chromosome_type == ChromosomeType::kW_WSexChromosome) ||
(chromosome_type == ChromosomeType::kHF_HaploidFemaleInherited) ||
(chromosome_type == ChromosomeType::kFL_HaploidFemaleLine) ||
(chromosome_type == ChromosomeType::kHM_HaploidMaleInherited) ||
(chromosome_type == ChromosomeType::kML_HaploidMaleLine) ||
(chromosome_type == ChromosomeType::kNullY_YSexChromosomeWithNull)))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): chromosome type '" << chromosome_type << "' is only allowed in sexual models; call initializeSex() to enable sex first." << EidosTerminate();
std::string symbol;
if (symbol_value->Type() == EidosValueType::kValueString)
symbol = symbol_value->StringAtIndex_NOCAST(0, nullptr);
else
symbol = std::to_string(id);
if ((symbol.length() == 0) || (symbol.length() > 5))
{
if (symbol_value->Type() == EidosValueType::kValueString)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires symbol to be a string with a length of 1-3 characters." << EidosTerminate();
else
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires symbol to be a string with a length of 1-3 characters; since the id given to the chromosome (" << id << ") is more than three digits, a symbol must be supplied explicitly to satisfy this requirement." << EidosTerminate();
}
// these checks for symbol try to ensure that it can be used in a filename, as in tree-seq recording, without causing problems
for (char c : symbol) {
if (!std::isprint(static_cast<unsigned char>(c))) {
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires symbol to consist only of printable ASCII characters." << EidosTerminate();
}
}
if (symbol.find_first_of(" \\/:$*?<>|._-\"") != std::string::npos)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() does not allow symbol to contain the characters [space], \\, /, :, $, *, ?, <, >, |, ., _, -, or \"." << EidosTerminate();
if (ChromosomeFromSymbol(symbol))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires symbol to be unique within the species; two chromosomes in the same species may not have the same symbol." << EidosTerminate();
std::string name;
if (name_value->Type() == EidosValueType::kValueString)
name = name_value->StringAtIndex_NOCAST(0, nullptr);
int64_t mutrun_count = mutationRuns_value->IntAtIndex_NOCAST(0, nullptr);
if (mutrun_count != 0)
{
if ((mutrun_count < 1) || (mutrun_count > 10000))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeChromosome): initializeChromosome() requires mutationRuns to be between 1 and 10000, inclusive." << EidosTerminate();
}
// Set up the new chromosome object; it gets a retain count on it from EidosDictionaryRetained::EidosDictionaryRetained()
Chromosome *chromosome = new Chromosome(*this, chromosome_type, id, symbol, /* p_index */ (uint8_t)num_chromosome_inits_, (int)mutrun_count);
EidosValue_SP result_SP = EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(chromosome, gSLiM_Chromosome_Class));
chromosome->SetName(name);
if (length == -1)
{
// the length is NULL, so it is mutable until Chromosome::InitializeDraws() is called
chromosome->last_position_ = 0;
chromosome->extent_immutable_ = false;
}
else
{
// the length has been specified explicitly, so it is immutable
chromosome->last_position_ = length - 1;
chromosome->extent_immutable_ = true;
}
// Add it to our registry; AddChromosome() takes its retain count
AddChromosome(chromosome);
num_chromosome_inits_++;
has_currently_initializing_chromosome_ = true;
if (SLiM_verbosity_level >= 1)
{
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
output_stream << "initializeChromosome(" << id << ", " << length << ", '" << type_string << "'";
if (symbol_value->Type() == EidosValueType::kValueString)
output_stream << ", symbol='" << symbol << "'";
if (name.length())
output_stream << ", name='" << name << "'";
if (mutrun_count != 0)
output_stream << ", mutationRuns=" << mutrun_count;
output_stream << ");" << std::endl;
}
return result_SP;
}
// ********************* (object<GenomicElement>)initializeGenomicElement(io<GenomicElementType> genomicElementType, [Ni start = NULL], [Ni end = NULL])
//
EidosValue_SP Species::ExecuteContextFunction_initializeGenomicElement(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
EidosValue *genomicElementType_value = p_arguments[0].get();
EidosValue *start_value = p_arguments[1].get();
EidosValue *end_value = p_arguments[2].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
// BEWARE: Before we do anything else, we need to handle the start == end == NULL case,
// which modifies start_value and end_value. Be careful not to break this ugly hack!
bool start_is_NULL = (start_value->Type() == EidosValueType::kValueNULL);
bool end_is_NULL = (end_value->Type() == EidosValueType::kValueNULL);
EidosValue_Int_SP start_value_mocked, end_value_mocked;
if (start_is_NULL && end_is_NULL)
{
if ((num_chromosome_inits_ == 0) || has_implicit_chromosome_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() only allows NULL for start and end with a chromosome that is explicitly defined with initializeChromosome(), so that the length of the chromosome is known." << EidosTerminate();
Chromosome *chromosome = CurrentlyInitializingChromosome();
if (!chromosome->extent_immutable_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() only allows NULL for start and end with a chromosome that has an explicitly defined length." << EidosTerminate();
slim_position_t last_position = chromosome->last_position_;
// Here is the ugly hack! We want start_value and end_value to have specific values based upon the
// focal chromosome. The simplest way to achieve that is to substitute new EidosValues in for them.
// To do that, we have two EidosValue_Int_SPs defined above, for RAII. We'll make the mocked values,
// and substitute them in for use by the remaining code. They will be freed on exit from this method.
start_value_mocked = EidosValue_Int_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Int(0));
end_value_mocked = EidosValue_Int_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Int(last_position));
start_value = start_value_mocked.get();
end_value = end_value_mocked.get();
}
else if (start_is_NULL || end_is_NULL)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() only allows a start or end value of NULL if _both_ start and end are NULL; they cannot be NULL separately." << EidosTerminate();
// ------ end of ugly hack; from here on, start_value and end_value are guaranteed to be type integer -------
// Now check counts and such
if (start_value->Count() != end_value->Count())
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() requires start and end to be the same length." << EidosTerminate();
if ((genomicElementType_value->Count() != 1) && (genomicElementType_value->Count() != start_value->Count()))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() requires genomicElementType to be a singleton, or to match the length of start and end." << EidosTerminate();
int element_count = start_value->Count();
int type_count = genomicElementType_value->Count();
if (element_count == 0)
return gStaticEidosValueVOID;
// This function triggers the creation of an implicit chromosome if a chromosome has not already been set up
if ((num_chromosome_inits_ == 0) && !has_implicit_chromosome_)
MakeImplicitChromosome(ChromosomeType::kA_DiploidAutosome);
Chromosome *chromosome = CurrentlyInitializingChromosome();
GenomicElementType *genomic_element_type_ptr_0 = ((type_count == 1) ? SLiM_ExtractGenomicElementTypeFromEidosValue_io(genomicElementType_value, 0, &community_, this, "initializeGenomicElement()") : nullptr); // SPECIES CONSISTENCY CHECK
GenomicElementType *genomic_element_type_ptr = nullptr;
slim_position_t start_position = 0, end_position = 0;
EidosValue_Object *result_vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Object(gSLiM_GenomicElement_Class))->resize_no_initialize(element_count);
for (int element_index = 0; element_index < element_count; ++element_index)
{
genomic_element_type_ptr = ((type_count == 1) ? genomic_element_type_ptr_0 : SLiM_ExtractGenomicElementTypeFromEidosValue_io(genomicElementType_value, element_index, &community_, this, "initializeGenomicElement()")); // SPECIES CONSISTENCY CHECK
start_position = SLiMCastToPositionTypeOrRaise(start_value->IntAtIndex_NOCAST(element_index, nullptr));
end_position = SLiMCastToPositionTypeOrRaise(end_value->IntAtIndex_NOCAST(element_index, nullptr));
if (end_position < start_position)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() end position " << end_position << " is less than start position " << start_position << "." << EidosTerminate();
if (chromosome->extent_immutable_)
{
if ((start_position < 0) || (end_position > chromosome->last_position_))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() genomic element extent lies outside of the extent of the chromosome." << EidosTerminate();
}
// Check that the new element will not overlap any existing element; if end_position > last_genomic_element_position we are safe.
// Otherwise, we have to check all previously defined elements. The use of last_genomic_element_position is an optimization to
// avoid an O(N) scan with each added element; as long as elements are added in sorted order there is no need to scan.
if (start_position <= last_genomic_element_position_)
{
for (GenomicElement *element : chromosome->GenomicElements())
{
if ((element->start_position_ <= end_position) && (element->end_position_ >= start_position))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElement): initializeGenomicElement() genomic element from start position " << start_position << " to end position " << end_position << " overlaps existing genomic element." << EidosTerminate();
}
}
if (end_position > last_genomic_element_position_)
last_genomic_element_position_ = end_position;
// Create and add the new element
GenomicElement *new_genomic_element = new GenomicElement(genomic_element_type_ptr, start_position, end_position);
chromosome->GenomicElements().emplace_back(new_genomic_element);
result_vec->set_object_element_no_check_NORR(new_genomic_element, element_index);
community_.chromosome_changed_ = true;
num_genomic_element_inits_++;
}
if (SLiM_verbosity_level >= 1)
{
if (start_is_NULL && end_is_NULL)
{
output_stream << "initializeGenomicElement(g" << genomic_element_type_ptr->genomic_element_type_id_ << ");" << std::endl;
}
else if (ABBREVIATE_DEBUG_INPUT && (num_genomic_element_inits_ > 20) && (num_genomic_element_inits_ != element_count))
{
if ((num_genomic_element_inits_ - element_count) <= 20)
output_stream << "(...initializeGenomicElement() calls omitted...)" << std::endl;
}
else if (element_count == 1)
{
output_stream << "initializeGenomicElement(g" << genomic_element_type_ptr->genomic_element_type_id_ << ", " << start_position << ", " << end_position << ");" << std::endl;
}
else
{
output_stream << "initializeGenomicElement(...);" << std::endl;
}
}
return EidosValue_SP(result_vec);
}
// ********************* (object<GenomicElementType>$)initializeGenomicElementType(is$ id, io<MutationType> mutationTypes, numeric proportions, [Nf mutationMatrix = NULL])
//
EidosValue_SP Species::ExecuteContextFunction_initializeGenomicElementType(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
EidosValue *id_value = p_arguments[0].get();
EidosValue *mutationTypes_value = p_arguments[1].get();
EidosValue *proportions_value = p_arguments[2].get();
EidosValue *mutationMatrix_value = p_arguments[3].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
slim_objectid_t map_identifier = SLiM_ExtractObjectIDFromEidosValue_is(id_value, 0, 'g');
if (community_.GenomicElementTypeWithID(map_identifier))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() genomic element type g" << map_identifier << " already defined." << EidosTerminate();
int mut_type_id_count = mutationTypes_value->Count();
int proportion_count = proportions_value->Count();
if (mut_type_id_count != proportion_count)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() requires the sizes of mutationTypes and proportions to be equal." << EidosTerminate();
std::vector<MutationType*> mutation_types;
std::vector<double> mutation_fractions;
for (int mut_type_index = 0; mut_type_index < mut_type_id_count; ++mut_type_index)
{
MutationType *mutation_type_ptr = SLiM_ExtractMutationTypeFromEidosValue_io(mutationTypes_value, mut_type_index, &community_, this, "initializeGenomicElementType()"); // SPECIES CONSISTENCY CHECK
double proportion = proportions_value->NumericAtIndex_NOCAST(mut_type_index, nullptr);
if ((proportion < 0) || !std::isfinite(proportion)) // == 0 is allowed but must be fixed before the simulation executes; see InitializeDraws()
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() proportions must be greater than or equal to zero (" << EidosStringForFloat(proportion) << " supplied)." << EidosTerminate();
if (std::find(mutation_types.begin(), mutation_types.end(), mutation_type_ptr) != mutation_types.end())
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() mutation type m" << mutation_type_ptr->mutation_type_id_ << " used more than once." << EidosTerminate();
if (nucleotide_based_ && !mutation_type_ptr->nucleotide_based_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): in nucleotide-based models, initializeGenomicElementType() requires all mutation types for the genomic element type to be nucleotide-based. Non-nucleotide-based mutation types may be used in nucleotide-based models, but they cannot be autogenerated by SLiM, and therefore cannot be referenced by a genomic element type." << EidosTerminate();
mutation_types.emplace_back(mutation_type_ptr);
mutation_fractions.emplace_back(proportion);
// check whether we are using a mutation type that is non-neutral; check and set pure_neutral_
if ((mutation_type_ptr->dfe_type_ != DFEType::kFixed) || (mutation_type_ptr->dfe_parameters_[0] != 0.0))
{
pure_neutral_ = false;
// the mutation type's all_pure_neutral_DFE_ flag is presumably already set
}
}
EidosValueType mm_type = mutationMatrix_value->Type();
if (!nucleotide_based_ && (mm_type != EidosValueType::kValueNULL))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() requires mutationMatrix to be NULL in non-nucleotide-based models." << EidosTerminate();
if (nucleotide_based_ && (mm_type == EidosValueType::kValueNULL))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() requires mutationMatrix to be non-NULL in nucleotide-based models." << EidosTerminate();
GenomicElementType *new_genomic_element_type = new GenomicElementType(*this, map_identifier, mutation_types, mutation_fractions);
if (nucleotide_based_)
new_genomic_element_type->SetNucleotideMutationMatrix(EidosValue_Float_SP((EidosValue_Float *)(mutationMatrix_value)));
genomic_element_types_.emplace(map_identifier, new_genomic_element_type);
community_.genomic_element_types_changed_ = true;
// define a new Eidos variable to refer to the new genomic element type
EidosSymbolTableEntry &symbol_entry = new_genomic_element_type->SymbolTableEntry();
if (p_interpreter.SymbolTable().ContainsSymbol(symbol_entry.first))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGenomicElementType): initializeGenomicElementType() symbol " << EidosStringRegistry::StringForGlobalStringID(symbol_entry.first) << " was already defined prior to its definition here." << EidosTerminate();
community_.SymbolTable().InitializeConstantSymbolEntry(symbol_entry);
if (SLiM_verbosity_level >= 1)
{
if (ABBREVIATE_DEBUG_INPUT && (num_ge_type_inits_ > 99))
{
if (num_ge_type_inits_ == 100)
output_stream << "(...more initializeGenomicElementType() calls omitted...)" << std::endl;
}
else
{
output_stream << "initializeGenomicElementType(" << map_identifier;
output_stream << ((mut_type_id_count > 1) ? ", c(" : ", ");
for (int mut_type_index = 0; mut_type_index < mut_type_id_count; ++mut_type_index)
output_stream << (mut_type_index > 0 ? ", m" : "m") << mutation_types[mut_type_index]->mutation_type_id_;
output_stream << ((mut_type_id_count > 1) ? ")" : "");
output_stream << ((mut_type_id_count > 1) ? ", c(" : ", ");
for (int mut_type_index = 0; mut_type_index < mut_type_id_count; ++mut_type_index)
output_stream << (mut_type_index > 0 ? ", " : "") << proportions_value->NumericAtIndex_NOCAST(mut_type_index, nullptr);
output_stream << ((mut_type_id_count > 1) ? ")" : "");
output_stream << ");" << std::endl;
}
}
num_ge_type_inits_++;
return symbol_entry.second;
}
// ********************* (object<MutationType>$)initializeMutationType(is$ id, numeric$ dominanceCoeff, string$ distributionType, ...)
// ********************* (object<MutationType>$)initializeMutationTypeNuc(is$ id, numeric$ dominanceCoeff, string$ distributionType, ...)
//
EidosValue_SP Species::ExecuteContextFunction_initializeMutationType(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
// Figure out whether the mutation type is nucleotide-based
bool nucleotide_based = (p_function_name == "initializeMutationTypeNuc");
if (nucleotide_based && !nucleotide_based_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeMutationType): initializeMutationTypeNuc() may be only be called in nucleotide-based models." << EidosTerminate();
EidosValue *id_value = p_arguments[0].get();
EidosValue *dominanceCoeff_value = p_arguments[1].get();
EidosValue *distributionType_value = p_arguments[2].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
slim_objectid_t map_identifier = SLiM_ExtractObjectIDFromEidosValue_is(id_value, 0, 'm');
double dominance_coeff = dominanceCoeff_value->NumericAtIndex_NOCAST(0, nullptr);
std::string dfe_type_string = distributionType_value->StringAtIndex_NOCAST(0, nullptr);
if (community_.MutationTypeWithID(map_identifier))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeMutationType): " << p_function_name << "() mutation type m" << map_identifier << " already defined." << EidosTerminate();
// Parse the DFE type and parameters, and do various sanity checks
DFEType dfe_type;
std::vector<double> dfe_parameters;
std::vector<std::string> dfe_strings;
MutationType::ParseDFEParameters(dfe_type_string, p_arguments.data() + 3, (int)p_arguments.size() - 3, &dfe_type, &dfe_parameters, &dfe_strings);
#ifdef SLIMGUI
// each new mutation type gets a unique zero-based index, used by SLiMgui to categorize mutations
MutationType *new_mutation_type = new MutationType(*this, map_identifier, dominance_coeff, nucleotide_based, dfe_type, dfe_parameters, dfe_strings, num_mutation_type_inits_);
#else
MutationType *new_mutation_type = new MutationType(*this, map_identifier, dominance_coeff, nucleotide_based, dfe_type, dfe_parameters, dfe_strings);
#endif
mutation_types_.emplace(map_identifier, new_mutation_type);
community_.mutation_types_changed_ = true;
// keep track of whether we have ever seen a type 's' (scripted) DFE; if so, we switch to a slower case when evolving
if (dfe_type == DFEType::kScript)
type_s_dfes_present_ = true;
// define a new Eidos variable to refer to the new mutation type
EidosSymbolTableEntry &symbol_entry = new_mutation_type->SymbolTableEntry();
if (p_interpreter.SymbolTable().ContainsSymbol(symbol_entry.first))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeMutationType): " << p_function_name << "() symbol " << EidosStringRegistry::StringForGlobalStringID(symbol_entry.first) << " was already defined prior to its definition here." << EidosTerminate();
community_.SymbolTable().InitializeConstantSymbolEntry(symbol_entry);
if (SLiM_verbosity_level >= 1)
{
if (ABBREVIATE_DEBUG_INPUT && (num_mutation_type_inits_ > 99))
{
if (num_mutation_type_inits_ == 100)
output_stream << "(...more " << p_function_name << "() calls omitted...)" << std::endl;
}
else
{
output_stream << p_function_name << "(" << map_identifier << ", " << dominance_coeff << ", \"" << dfe_type << "\"";
if (dfe_parameters.size() > 0)
{
for (double dfe_param : dfe_parameters)
output_stream << ", " << dfe_param;
}
else
{
for (const std::string &dfe_param : dfe_strings)
output_stream << ", \"" << dfe_param << "\"";
}
output_stream << ");" << std::endl;
}
}
num_mutation_type_inits_++;
return symbol_entry.second;
}
// ********************* (void)initializeRecombinationRate(numeric rates, [Ni ends = NULL], [string$ sex = "*"])
//
EidosValue_SP Species::ExecuteContextFunction_initializeRecombinationRate(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
EidosValue *rates_value = p_arguments[0].get();
EidosValue *ends_value = p_arguments[1].get();
EidosValue *sex_value = p_arguments[2].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
int rate_count = rates_value->Count();
// Figure out what sex we are being given a map for
IndividualSex requested_sex;
std::string sex_string = sex_value->StringAtIndex_NOCAST(0, nullptr);
if (sex_string.compare("M") == 0)
requested_sex = IndividualSex::kMale;
else if (sex_string.compare("F") == 0)
requested_sex = IndividualSex::kFemale;
else if (sex_string.compare("*") == 0)
requested_sex = IndividualSex::kUnspecified;
else
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requested sex '" << sex_string << "' unsupported." << EidosTerminate();
if ((requested_sex != IndividualSex::kUnspecified) && !sex_enabled_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() sex-specific recombination map supplied in non-sexual simulation." << EidosTerminate();
// This function triggers the creation of an implicit chromosome if a chromosome has not already been set up
if ((num_chromosome_inits_ == 0) && !has_implicit_chromosome_)
MakeImplicitChromosome(ChromosomeType::kA_DiploidAutosome);
Chromosome *chromosome = CurrentlyInitializingChromosome();
// Make sure specifying a map for that sex is legal, given our current state. Since single_recombination_map_ has not been set
// yet, we just look to see whether the chromosome's policy has already been determined or not.
if (((requested_sex == IndividualSex::kUnspecified) && ((chromosome->recombination_rates_M_.size() != 0) || (chromosome->recombination_rates_F_.size() != 0))) ||
((requested_sex != IndividualSex::kUnspecified) && (chromosome->recombination_rates_H_.size() != 0)))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() cannot change the chromosome between using a single map versus separate maps for the sexes; the original configuration must be preserved." << EidosTerminate();
if (((requested_sex == IndividualSex::kUnspecified) && (num_recrate_inits_ > 0)) || ((requested_sex != IndividualSex::kUnspecified) && (num_recrate_inits_ > 1)))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() may be called only once (or once per sex, with sex-specific recombination maps). The multiple recombination regions of a recombination map must be set up in a single call to initializeRecombinationRate()." << EidosTerminate();
// Set up to replace the requested map
std::vector<slim_position_t> &positions = ((requested_sex == IndividualSex::kUnspecified) ? chromosome->recombination_end_positions_H_ :
((requested_sex == IndividualSex::kMale) ? chromosome->recombination_end_positions_M_ : chromosome->recombination_end_positions_F_));
std::vector<double> &rates = ((requested_sex == IndividualSex::kUnspecified) ? chromosome->recombination_rates_H_ :
((requested_sex == IndividualSex::kMale) ? chromosome->recombination_rates_M_ : chromosome->recombination_rates_F_));
if (ends_value->Type() == EidosValueType::kValueNULL)
{
if (rate_count != 1)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires rates to be a singleton if ends is not supplied." << EidosTerminate();
double recombination_rate = rates_value->NumericAtIndex_NOCAST(0, nullptr);
// check values; I thought about requiring a rate of 0.0 for all haploid chromosome types, but maybe
// the user wants to recombine them sometimes with addRecombinant(), no need to prevent them
if ((recombination_rate < 0.0) || (recombination_rate > 0.5) || std::isnan(recombination_rate))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires rates to be in [0.0, 0.5] (" << EidosStringForFloat(recombination_rate) << " supplied)." << EidosTerminate();
// then adopt them
rates.clear();
positions.clear();
rates.emplace_back(recombination_rate);
//positions.emplace_back(?); // deferred; patched in Chromosome::InitializeDraws().
}
else
{
int end_count = ends_value->Count();
if ((end_count != rate_count) || (end_count == 0))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires ends and rates to be of equal and nonzero size." << EidosTerminate();
// check values
for (int value_index = 0; value_index < end_count; ++value_index)
{
double recombination_rate = rates_value->NumericAtIndex_NOCAST(value_index, nullptr);
slim_position_t recombination_end_position = SLiMCastToPositionTypeOrRaise(ends_value->IntAtIndex_NOCAST(value_index, nullptr));
if (value_index > 0)
if (recombination_end_position <= ends_value->IntAtIndex_NOCAST(value_index - 1, nullptr))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires ends to be in strictly ascending order." << EidosTerminate();
if ((recombination_rate < 0.0) || (recombination_rate > 0.5) || std::isnan(recombination_rate))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires rates to be in [0.0, 0.5] (" << EidosStringForFloat(recombination_rate) << " supplied)." << EidosTerminate();
if (chromosome->extent_immutable_)
{
if ((recombination_end_position <= 0) || (recombination_end_position > chromosome->last_position_))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeRecombinationRate): initializeRecombinationRate() requires all end positions to be within the extent of the chromosome." << EidosTerminate();
}
}
// then adopt them
rates.clear();
positions.clear();
for (int interval_index = 0; interval_index < end_count; ++interval_index)
{
double recombination_rate = rates_value->NumericAtIndex_NOCAST(interval_index, nullptr);
slim_position_t recombination_end_position = SLiMCastToPositionTypeOrRaise(ends_value->IntAtIndex_NOCAST(interval_index, nullptr));
rates.emplace_back(recombination_rate);
positions.emplace_back(recombination_end_position);
}
}
community_.chromosome_changed_ = true;
if (SLiM_verbosity_level >= 1)
{
int ratesSize = (int)rates.size();
int endsSize = (int)positions.size();
output_stream << "initializeRecombinationRate(";
if (ratesSize > 1)
output_stream << "c(";
for (int interval_index = 0; interval_index < ratesSize; ++interval_index)
{
if (interval_index >= 50)
{
output_stream << ", ...";
break;
}
output_stream << (interval_index == 0 ? "" : ", ") << rates[interval_index];
}
if (ratesSize > 1)
output_stream << ")";
if (endsSize > 0)
{
output_stream << ", ";
if (endsSize > 1)
output_stream << "c(";
for (int interval_index = 0; interval_index < endsSize; ++interval_index)
{
if (interval_index >= 50)
{
output_stream << ", ...";
break;
}
output_stream << (interval_index == 0 ? "" : ", ") << positions[interval_index];
}
if (endsSize > 1)
output_stream << ")";
}
output_stream << ");" << std::endl;
}
num_recrate_inits_++;
return gStaticEidosValueVOID;
}
// ********************* (void)initializeGeneConversion(numeric$ nonCrossoverFraction, numeric$ meanLength, numeric$ simpleConversionFraction, [numeric$ bias = 0], [logical$ redrawLengthsOnFailure = F])
//
EidosValue_SP Species::ExecuteContextFunction_initializeGeneConversion(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
EidosValue *nonCrossoverFraction_value = p_arguments[0].get();
EidosValue *meanLength_value = p_arguments[1].get();
EidosValue *simpleConversionFraction_value = p_arguments[2].get();
EidosValue *bias_value = p_arguments[3].get();
EidosValue *redrawLengthsOnFailure_value = p_arguments[4].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
if (num_gene_conv_inits_ > 0)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() may be called only once." << EidosTerminate();
double non_crossover_fraction = nonCrossoverFraction_value->NumericAtIndex_NOCAST(0, nullptr);
double gene_conversion_avg_length = meanLength_value->NumericAtIndex_NOCAST(0, nullptr);
double simple_conversion_fraction = simpleConversionFraction_value->NumericAtIndex_NOCAST(0, nullptr);
double bias = bias_value->NumericAtIndex_NOCAST(0, nullptr);
bool redraw_lengths_on_failure = redrawLengthsOnFailure_value->LogicalAtIndex_NOCAST(0, nullptr);
if ((non_crossover_fraction < 0.0) || (non_crossover_fraction > 1.0) || std::isnan(non_crossover_fraction))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() nonCrossoverFraction must be between 0.0 and 1.0 inclusive (" << EidosStringForFloat(non_crossover_fraction) << " supplied)." << EidosTerminate();
if ((gene_conversion_avg_length < 0.0) || std::isnan(gene_conversion_avg_length)) // intentionally no upper bound
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() meanLength must be >= 0.0 (" << EidosStringForFloat(gene_conversion_avg_length) << " supplied)." << EidosTerminate();
if ((simple_conversion_fraction < 0.0) || (simple_conversion_fraction > 1.0) || std::isnan(simple_conversion_fraction))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() simpleConversionFraction must be between 0.0 and 1.0 inclusive (" << EidosStringForFloat(simple_conversion_fraction) << " supplied)." << EidosTerminate();
if ((bias < -1.0) || (bias > 1.0) || std::isnan(bias))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() bias must be between -1.0 and 1.0 inclusive (" << EidosStringForFloat(bias) << " supplied)." << EidosTerminate();
if ((bias != 0.0) && !nucleotide_based_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeGeneConversion): initializeGeneConversion() bias must be 0.0 in non-nucleotide-based models." << EidosTerminate();
// This function triggers the creation of an implicit chromosome if a chromosome has not already been set up
if ((num_chromosome_inits_ == 0) && !has_implicit_chromosome_)
MakeImplicitChromosome(ChromosomeType::kA_DiploidAutosome);
Chromosome *chromosome = CurrentlyInitializingChromosome();
chromosome->using_DSB_model_ = true;
chromosome->non_crossover_fraction_ = non_crossover_fraction;
chromosome->gene_conversion_avg_length_ = gene_conversion_avg_length;
chromosome->gene_conversion_inv_half_length_ = 1.0 / (gene_conversion_avg_length / 2.0);
chromosome->simple_conversion_fraction_ = simple_conversion_fraction;
chromosome->mismatch_repair_bias_ = bias;
chromosome->redraw_lengths_on_failure_ = redraw_lengths_on_failure;
if (SLiM_verbosity_level >= 1)
{
output_stream << "initializeGeneConversion(" << non_crossover_fraction << ", " << gene_conversion_avg_length << ", " << simple_conversion_fraction << ", " << bias;
if (redraw_lengths_on_failure)
output_stream << ", T";
output_stream << ");" << std::endl;
}
num_gene_conv_inits_++;
return gStaticEidosValueVOID;
}
// ********************* (void)initializeHotspotMap(numeric multipliers, [Ni ends = NULL], [string$ sex = "*"])
//
EidosValue_SP Species::ExecuteContextFunction_initializeHotspotMap(const std::string &p_function_name, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_function_name, p_arguments, p_interpreter)
if (!nucleotide_based_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() may only be called in nucleotide-based models (use initializeMutationRate() to vary the mutation rate along the chromosome)." << EidosTerminate();
EidosValue *multipliers_value = p_arguments[0].get();
EidosValue *ends_value = p_arguments[1].get();
EidosValue *sex_value = p_arguments[2].get();
std::ostream &output_stream = p_interpreter.ExecutionOutputStream();
int multipliers_count = multipliers_value->Count();
// Figure out what sex we are being given a map for
IndividualSex requested_sex;
std::string sex_string = sex_value->StringAtIndex_NOCAST(0, nullptr);
if (sex_string.compare("M") == 0)
requested_sex = IndividualSex::kMale;
else if (sex_string.compare("F") == 0)
requested_sex = IndividualSex::kFemale;
else if (sex_string.compare("*") == 0)
requested_sex = IndividualSex::kUnspecified;
else
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requested sex '" << sex_string << "' unsupported." << EidosTerminate();
if ((requested_sex != IndividualSex::kUnspecified) && !sex_enabled_)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() sex-specific hotspot map supplied in non-sexual simulation." << EidosTerminate();
// This function triggers the creation of an implicit chromosome if a chromosome has not already been set up
if ((num_chromosome_inits_ == 0) && !has_implicit_chromosome_)
MakeImplicitChromosome(ChromosomeType::kA_DiploidAutosome);
Chromosome *chromosome = CurrentlyInitializingChromosome();
// Make sure specifying a map for that sex is legal, given our current state
if (((requested_sex == IndividualSex::kUnspecified) && ((chromosome->hotspot_multipliers_M_.size() != 0) || (chromosome->hotspot_multipliers_F_.size() != 0))) ||
((requested_sex != IndividualSex::kUnspecified) && (chromosome->hotspot_multipliers_H_.size() != 0)))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() cannot change the chromosome between using a single map versus separate maps for the sexes; the original configuration must be preserved." << EidosTerminate();
if (((requested_sex == IndividualSex::kUnspecified) && (num_hotmap_inits_ > 0)) || ((requested_sex != IndividualSex::kUnspecified) && (num_hotmap_inits_ > 1)))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() may be called only once (or once per sex, with sex-specific hotspot maps). The multiple hotspot regions of a hotspot map must be set up in a single call to initializeHotspotMap()." << EidosTerminate();
// Set up to replace the requested map
std::vector<slim_position_t> &positions = ((requested_sex == IndividualSex::kUnspecified) ? chromosome->hotspot_end_positions_H_ :
((requested_sex == IndividualSex::kMale) ? chromosome->hotspot_end_positions_M_ : chromosome->hotspot_end_positions_F_));
std::vector<double> &multipliers = ((requested_sex == IndividualSex::kUnspecified) ? chromosome->hotspot_multipliers_H_ :
((requested_sex == IndividualSex::kMale) ? chromosome->hotspot_multipliers_M_ : chromosome->hotspot_multipliers_F_));
if (ends_value->Type() == EidosValueType::kValueNULL)
{
if (multipliers_count != 1)
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires multipliers to be a singleton if ends is not supplied." << EidosTerminate();
double multiplier = multipliers_value->NumericAtIndex_NOCAST(0, nullptr);
// check values
if ((multiplier < 0.0) || !std::isfinite(multiplier)) // intentionally no upper bound
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires multipliers to be >= 0 (" << EidosStringForFloat(multiplier) << " supplied)." << EidosTerminate();
// then adopt them
multipliers.clear();
positions.clear();
multipliers.emplace_back(multiplier);
//positions.emplace_back(?); // deferred; patched in Chromosome::InitializeDraws().
}
else
{
int end_count = ends_value->Count();
if ((end_count != multipliers_count) || (end_count == 0))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires ends and multipliers to be of equal and nonzero size." << EidosTerminate();
// check values
for (int value_index = 0; value_index < end_count; ++value_index)
{
double multiplier = multipliers_value->NumericAtIndex_NOCAST(value_index, nullptr);
slim_position_t multiplier_end_position = SLiMCastToPositionTypeOrRaise(ends_value->IntAtIndex_NOCAST(value_index, nullptr));
if (value_index > 0)
if (multiplier_end_position <= ends_value->IntAtIndex_NOCAST(value_index - 1, nullptr))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires ends to be in strictly ascending order." << EidosTerminate();
if ((multiplier < 0.0) || !std::isfinite(multiplier)) // intentionally no upper bound
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires multipliers to be >= 0 (" << EidosStringForFloat(multiplier) << " supplied)." << EidosTerminate();
if (chromosome->extent_immutable_)
{
if ((multiplier_end_position <= 0) || (multiplier_end_position > chromosome->last_position_))
EIDOS_TERMINATION << "ERROR (Species::ExecuteContextFunction_initializeHotspotMap): initializeHotspotMap() requires all end positions to be within the extent of the chromosome." << EidosTerminate();
}
}
// then adopt them
multipliers.clear();
positions.clear();
for (int interval_index = 0; interval_index < end_count; ++interval_index)
{
double multiplier = multipliers_value->NumericAtIndex_NOCAST(interval_index, nullptr);
slim_position_t multiplier_end_position = SLiMCastToPositionTypeOrRaise(ends_value->IntAtIndex_NOCAST(interval_index, nullptr));
multipliers.emplace_back(multiplier);
positions.emplace_back(multiplier_end_position);
}