-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathhaplosome.cpp
4847 lines (3860 loc) · 215 KB
/
haplosome.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
//
// haplosome.cpp
// SLiM
//
// Created by Ben Haller on 12/13/14.
// Copyright (c) 2014-2025 Philipp Messer. All rights reserved.
// A product of the Messer Lab, http://messerlab.org/slim/
//
// This file is part of SLiM.
//
// SLiM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//
// SLiM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with SLiM. If not, see <http://www.gnu.org/licenses/>.
#include "haplosome.h"
#include "slim_globals.h"
#include "eidos_call_signature.h"
#include "eidos_property_signature.h"
#include "community.h"
#include "species.h"
#include "polymorphism.h"
#include "subpopulation.h"
#include "eidos_sorting.h"
#include <algorithm>
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <utility>
#pragma mark -
#pragma mark Haplosome
#pragma mark -
// Static class variables in support of Haplosome's bulk operation optimization; see Haplosome::WillModifyRunForBulkOperation()
int64_t Haplosome::s_bulk_operation_id_ = 0;
slim_mutrun_index_t Haplosome::s_bulk_operation_mutrun_index_ = -1;
SLiMBulkOperationHashTable Haplosome::s_bulk_operation_runs_;
Haplosome::~Haplosome(void)
{
if (mutruns_ != run_buffer_)
free(mutruns_);
mutruns_ = nullptr;
mutrun_count_ = 0;
}
Chromosome *Haplosome::AssociatedChromosome(void) const
{
return individual_->subpopulation_->species_.Chromosomes()[chromosome_index_];
}
// prints an error message, a stacktrace, and exits; called only for DEBUG
void Haplosome::NullHaplosomeAccessError(void) const
{
EIDOS_TERMINATION << "ERROR (Haplosome::NullHaplosomeAccessError): (internal error) a null haplosome was accessed." << EidosTerminate();
}
MutationRun *Haplosome::WillModifyRun(slim_mutrun_index_t p_run_index, MutationRunContext &p_mutrun_context)
{
#if DEBUG
if (p_run_index >= mutrun_count_)
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRun): (internal error) attempt to modify an out-of-index run." << EidosTerminate();
#endif
// This method used to support in-place modification for mutruns with a use count of 1,
// saving the new mutation run allocation; this is now done only in WillModifyRun_UNSHARED().
// See the header comment for more information.
const MutationRun *original_run = mutruns_[p_run_index];
MutationRun *new_run = MutationRun::NewMutationRun(p_mutrun_context); // take from shared pool of used objects
new_run->copy_from_run(*original_run);
mutruns_[p_run_index] = new_run;
// We return a non-const pointer to the caller, giving them permission to modify this new run
return new_run;
}
MutationRun *Haplosome::WillModifyRun_UNSHARED(slim_mutrun_index_t p_run_index, MutationRunContext &p_mutrun_context)
{
#if DEBUG
if (p_run_index >= mutrun_count_)
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRun_UNSHARED): (internal error) attempt to modify an out-of-index run." << EidosTerminate();
#endif
// This method avoids the new mutation run allocation, unless the mutation run is empty.
// This is based on a guarantee from the caller that the run is unshared (unless it is empty).
// See the header comment for more information.
const MutationRun *original_run = mutruns_[p_run_index];
if (original_run->size() == 0)
{
MutationRun *new_run = MutationRun::NewMutationRun(p_mutrun_context); // take from shared pool of used objects
new_run->copy_from_run(*original_run);
mutruns_[p_run_index] = new_run;
// We return a non-const pointer to the caller, giving them permission to modify this new run
return new_run;
}
else
{
// We have been guaranteed by the caller that this mutation run is unshared, so we can cast away the const
MutationRun *unlocked_run = const_cast<MutationRun *>(original_run);
unlocked_run->will_modify_run(); // in-place modification of runs requires notification, for cache invalidation
// We return a non-const pointer to the caller, giving them permission to modify this run
return unlocked_run;
}
}
void Haplosome::BulkOperationStart(int64_t p_operation_id, slim_mutrun_index_t p_mutrun_index)
{
THREAD_SAFETY_IN_ACTIVE_PARALLEL("Haplosome::BulkOperationStart(): s_bulk_operation_id_");
if (s_bulk_operation_id_ != 0)
{
//EIDOS_TERMINATION << "ERROR (Haplosome::BulkOperationStart): (internal error) unmatched bulk operation start." << EidosTerminate();
// It would be nice to be able to throw an exception here, but in the present design, the
// bulk operation info can get messed up if the bulk operation throws an exception that
// blows through the call to Haplosome::BulkOperationEnd().
// Note this warning is not suppressed by gEidosSuppressWarnings; that is deliberate
std::cout << "WARNING (Haplosome::BulkOperationStart): (internal error) unmatched bulk operation start." << std::endl;
// For now, we assume that the end call got blown through, and we close out the old operation.
Haplosome::BulkOperationEnd(s_bulk_operation_id_, s_bulk_operation_mutrun_index_);
}
s_bulk_operation_id_ = p_operation_id;
s_bulk_operation_mutrun_index_ = p_mutrun_index;
}
MutationRun *Haplosome::WillModifyRunForBulkOperation(int64_t p_operation_id, slim_mutrun_index_t p_mutrun_index, MutationRunContext &p_mutrun_context)
{
THREAD_SAFETY_IN_ACTIVE_PARALLEL("Haplosome::WillModifyRunForBulkOperation(): s_bulk_operation_id_");
if (p_mutrun_index != s_bulk_operation_mutrun_index_)
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRunForBulkOperation): (internal error) incorrect run index during bulk operation." << EidosTerminate();
if (p_mutrun_index >= mutrun_count_)
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRunForBulkOperation): (internal error) attempt to modify an out-of-index run." << EidosTerminate();
#if 0
#warning Haplosome::WillModifyRunForBulkOperation disabled...
// The trivial version of this function just calls WillModifyRun(),
// requesting that the caller perform the operation
return WillModifyRun(p_run_index);
#else
// The interesting version remembers the operation in progress, using the ID, and
// tracks original/final MutationRun pointers, returning nullptr if an original is matched.
const MutationRun *original_run = mutruns_[p_mutrun_index];
if (p_operation_id != s_bulk_operation_id_)
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRunForBulkOperation): (internal error) missing bulk operation start." << EidosTerminate();
auto found_run_pair = s_bulk_operation_runs_.find(original_run);
if (found_run_pair == s_bulk_operation_runs_.end())
{
// This MutationRun is not in the map, so we need to set up a new entry
MutationRun *product_run = MutationRun::NewMutationRun(p_mutrun_context);
product_run->copy_from_run(*original_run);
mutruns_[p_mutrun_index] = product_run;
try {
s_bulk_operation_runs_.emplace(original_run, product_run);
} catch (...) {
EIDOS_TERMINATION << "ERROR (Haplosome::WillModifyRunForBulkOperation): (internal error) SLiM encountered a raise from an internal hash table; please report this." << EidosTerminate(nullptr);
}
//std::cout << "WillModifyRunForBulkOperation() created product for " << original_run << std::endl;
return product_run;
}
else
{
// This MutationRun is in the map, so we can just reuse it to redo the operation
mutruns_[p_mutrun_index] = found_run_pair->second;
//std::cout << " WillModifyRunForBulkOperation() substituted known product for " << original_run << std::endl;
return nullptr;
}
#endif
}
void Haplosome::BulkOperationEnd(int64_t p_operation_id, slim_mutrun_index_t p_mutrun_index)
{
THREAD_SAFETY_IN_ACTIVE_PARALLEL("Haplosome::BulkOperationEnd(): s_bulk_operation_id_");
if ((p_operation_id == s_bulk_operation_id_) && (p_mutrun_index == s_bulk_operation_mutrun_index_))
{
s_bulk_operation_runs_.clear();
s_bulk_operation_id_ = 0;
s_bulk_operation_mutrun_index_ = -1;
}
else
{
EIDOS_TERMINATION << "ERROR (Haplosome::BulkOperationEnd): (internal error) unmatched bulk operation end." << EidosTerminate();
}
}
void Haplosome::TallyHaplosomeReferences_Checkback(slim_refcount_t *p_mutrun_ref_tally, slim_refcount_t *p_mutrun_tally, int64_t p_operation_id)
{
#if DEBUG
if (mutrun_count_ == 0)
NullHaplosomeAccessError();
#endif
for (int run_index = 0; run_index < mutrun_count_; ++run_index)
{
if (mutruns_[run_index]->operation_id_ != p_operation_id)
{
(*p_mutrun_ref_tally) += mutruns_[run_index]->use_count();
(*p_mutrun_tally)++;
mutruns_[run_index]->operation_id_ = p_operation_id;
}
}
}
void Haplosome::MakeNull(void)
{
if (mutrun_count_)
{
if (mutruns_ != run_buffer_)
free(mutruns_);
mutruns_ = nullptr;
mutrun_count_ = 0;
mutrun_length_ = 0;
}
}
void Haplosome::ReinitializeHaplosomeToNull(Individual *individual)
{
// Transmogrify a haplosome (which might be null or non-null) into a null haplosome
individual_ = individual;
if (mutrun_count_)
{
// was a non-null haplosome, needs to become null
if (mutruns_ != run_buffer_)
free(mutruns_);
mutruns_ = nullptr;
// chromosome_index_ remains untouched; we still belong to the same chromosome
mutrun_count_ = 0;
mutrun_length_ = 0;
}
}
void Haplosome::ReinitializeHaplosomeToNonNull(Individual *individual, Chromosome *p_chromosome)
{
// Transmogrify a haplosome (which might be null or non-null) into a non-null haplosome with a specific configuration
individual_ = individual;
#if DEBUG
// We should always be reinitializing a haplosome that already belongs to the chromosome;
// the only reason the chromosome is passed in is that it knows the mutrun configuration.
if (chromosome_index_ != p_chromosome->Index())
EIDOS_TERMINATION << "ERROR (Haplosome::ReinitializeHaplosomeToNonNull): (internal error) incorrect chromosome index." << EidosTerminate();
#endif
if (mutrun_count_ == 0)
{
// was a null haplosome, needs to become not null
mutrun_count_ = p_chromosome->mutrun_count_;
mutrun_length_ = p_chromosome->mutrun_length_;
if (mutrun_count_ <= SLIM_HAPLOSOME_MUTRUN_BUFSIZE)
{
mutruns_ = run_buffer_;
#if SLIM_CLEAR_HAPLOSOMES
EIDOS_BZERO(run_buffer_, SLIM_HAPLOSOME_MUTRUN_BUFSIZE * sizeof(const MutationRun *));
#endif
}
else
{
#if SLIM_CLEAR_HAPLOSOMES
mutruns_ = (const MutationRun **)calloc(mutrun_count_, sizeof(const MutationRun *));
#else
mutruns_ = (const MutationRun **)malloc(mutrun_count_ * sizeof(const MutationRun *));
#endif
}
}
else if (mutrun_count_ != p_chromosome->mutrun_count_)
{
// the number of mutruns has changed; need to reallocate
if (mutruns_ != run_buffer_)
free(mutruns_);
mutrun_count_ = p_chromosome->mutrun_count_;
mutrun_length_ = p_chromosome->mutrun_length_;
if (mutrun_count_ <= SLIM_HAPLOSOME_MUTRUN_BUFSIZE)
{
mutruns_ = run_buffer_;
#if SLIM_CLEAR_HAPLOSOMES
EIDOS_BZERO(run_buffer_, SLIM_HAPLOSOME_MUTRUN_BUFSIZE * sizeof(const MutationRun *));
#endif
}
else
{
#if SLIM_CLEAR_HAPLOSOMES
mutruns_ = (const MutationRun **)calloc(mutrun_count_, sizeof(const MutationRun *));
#else
mutruns_ = (const MutationRun **)malloc(mutrun_count_ * sizeof(const MutationRun *));
#endif
}
}
else
{
#if SLIM_CLEAR_HAPLOSOMES
// the number of mutruns has not changed; need to zero out
EIDOS_BZERO(mutruns_, mutrun_count_ * sizeof(const MutationRun *));
#endif
}
}
void Haplosome::record_derived_states(Species *p_species) const
{
// This is called by Species::RecordAllDerivedStatesFromSLiM() to record all the derived states present
// in a given haplosome that was just created by readFromPopulationFile() or some similar situation. It should
// make calls to record the derived state at each position in the haplosome that has any mutation.
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
THREAD_SAFETY_IN_ACTIVE_PARALLEL("Haplosome::record_derived_states(): usage of statics");
static std::vector<Mutation *> record_vec;
for (int run_index = 0; run_index < mutrun_count_; ++run_index)
{
const MutationRun *mutrun = mutruns_[run_index];
int mutrun_size = mutrun->size();
slim_position_t last_pos = -1;
//record_vec.resize(0); // should always be left clear by the code below
for (int mut_index = 0; mut_index < mutrun_size; ++mut_index)
{
MutationIndex mutation_index = (*mutrun)[mut_index];
Mutation *mutation = mut_block_ptr + mutation_index;
slim_position_t mutation_pos = mutation->position_;
if (mutation_pos != last_pos)
{
// New position, so we finish the previous derived-state block...
if (last_pos != -1)
{
p_species->RecordNewDerivedState(this, last_pos, record_vec);
record_vec.resize(0);
}
// ...and start a new derived-state block
last_pos = mutation_pos;
}
record_vec.emplace_back(mutation);
}
// record the last derived block, if any
if (last_pos != -1)
{
p_species->RecordNewDerivedState(this, last_pos, record_vec);
record_vec.resize(0);
}
}
}
//
// Eidos support
//
#pragma mark -
#pragma mark Eidos support
#pragma mark -
void Haplosome::GenerateCachedEidosValue(void)
{
// Note that this cache cannot be invalidated as long as a symbol table might exist that this value has been placed into
self_value_ = EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(this, gSLiM_Haplosome_Class));
}
const EidosClass *Haplosome::Class(void) const
{
return gSLiM_Haplosome_Class;
}
void Haplosome::Print(std::ostream &p_ostream) const
{
p_ostream << Class()->ClassNameForDisplay() << "<";
p_ostream << AssociatedChromosome()->Type();
if (mutrun_count_ == 0)
p_ostream << ":null>";
else
p_ostream << ":" << mutation_count() << ">";
}
EidosValue_SP Haplosome::GetProperty(EidosGlobalStringID p_property_id)
{
// All of our strings are in the global registry, so we can require a successful lookup
switch (p_property_id)
{
// constants
case gID_chromosome:
{
// We reach our chromosome through our individual; note this prevents standalone haplosome objects
Chromosome *chromosome = AssociatedChromosome();
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(chromosome, gSLiM_Chromosome_Class));
}
case gID_haplosomePedigreeID: // ACCELERATED
{
if (!individual_->subpopulation_->species_.PedigreesEnabledByUser())
EIDOS_TERMINATION << "ERROR (Haplosome::GetProperty): property haplosomePedigreeID is not available because pedigree recording has not been enabled." << EidosTerminate();
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Int(haplosome_id_));
}
case gID_individual:
{
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(individual_, gSLiM_Individual_Class));
}
case gID_isNullHaplosome: // ACCELERATED
return ((mutrun_count_ == 0) ? gStaticEidosValue_LogicalT : gStaticEidosValue_LogicalF);
case gID_mutations:
{
if (IsDeferred())
EIDOS_TERMINATION << "ERROR (Haplosome::GetProperty): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
int mut_count = mutation_count();
EidosValue_Object *vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Object(gSLiM_Mutation_Class))->resize_no_initialize_RR(mut_count);
EidosValue_SP result_SP = EidosValue_SP(vec);
int set_index = 0;
for (int run_index = 0; run_index < mutrun_count_; ++run_index)
{
const MutationRun *mutrun = mutruns_[run_index];
const MutationIndex *mut_start_ptr = mutrun->begin_pointer_const();
const MutationIndex *mut_end_ptr = mutrun->end_pointer_const();
for (const MutationIndex *mut_ptr = mut_start_ptr; mut_ptr < mut_end_ptr; ++mut_ptr)
vec->set_object_element_no_check_no_previous_RR(mut_block_ptr + *mut_ptr, set_index++);
}
return result_SP;
}
// variables
case gID_tag: // ACCELERATED
{
slim_usertag_t tag_value = tag_value_;
if (tag_value == SLIM_TAG_UNSET_VALUE)
EIDOS_TERMINATION << "ERROR (Haplosome::GetProperty): property tag accessed on haplosome before being set." << EidosTerminate();
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Int(tag_value));
}
// all others, including gID_none
default:
return super::GetProperty(p_property_id);
}
}
EidosValue *Haplosome::GetProperty_Accelerated_haplosomePedigreeID(EidosObject **p_values, size_t p_values_size)
{
EidosValue_Int *int_result = (new (gEidosValuePool->AllocateChunk()) EidosValue_Int())->resize_no_initialize(p_values_size);
size_t value_index = 0;
// check that pedigrees are enabled, once
if (value_index < p_values_size)
{
Haplosome *value = (Haplosome *)(p_values[value_index]);
if (!value->individual_->subpopulation_->species_.PedigreesEnabledByUser())
EIDOS_TERMINATION << "ERROR (Haplosome::GetProperty): property haplosomePedigreeID is not available because pedigree recording has not been enabled." << EidosTerminate();
int_result->set_int_no_check(value->haplosome_id_, value_index);
++value_index;
}
for ( ; value_index < p_values_size; ++value_index)
{
Haplosome *value = (Haplosome *)(p_values[value_index]);
int_result->set_int_no_check(value->haplosome_id_, value_index);
}
return int_result;
}
EidosValue *Haplosome::GetProperty_Accelerated_isNullHaplosome(EidosObject **p_values, size_t p_values_size)
{
EidosValue_Logical *logical_result = (new (gEidosValuePool->AllocateChunk()) EidosValue_Logical())->resize_no_initialize(p_values_size);
for (size_t value_index = 0; value_index < p_values_size; ++value_index)
{
Haplosome *value = (Haplosome *)(p_values[value_index]);
logical_result->set_logical_no_check(value->mutrun_count_ == 0, value_index);
}
return logical_result;
}
EidosValue *Haplosome::GetProperty_Accelerated_tag(EidosObject **p_values, size_t p_values_size)
{
EidosValue_Int *int_result = (new (gEidosValuePool->AllocateChunk()) EidosValue_Int())->resize_no_initialize(p_values_size);
for (size_t value_index = 0; value_index < p_values_size; ++value_index)
{
Haplosome *value = (Haplosome *)(p_values[value_index]);
slim_usertag_t tag_value = value->tag_value_;
if (tag_value == SLIM_TAG_UNSET_VALUE)
EIDOS_TERMINATION << "ERROR (Haplosome::GetProperty): property tag accessed on haplosome before being set." << EidosTerminate();
int_result->set_int_no_check(tag_value, value_index);
}
return int_result;
}
void Haplosome::SetProperty(EidosGlobalStringID p_property_id, const EidosValue &p_value)
{
switch (p_property_id)
{
case gID_tag: // ACCELERATED
{
slim_usertag_t value = SLiMCastToUsertagTypeOrRaise(p_value.IntAtIndex_NOCAST(0, nullptr));
tag_value_ = value;
Individual::s_any_haplosome_tag_set_ = true;
return;
}
default:
{
return super::SetProperty(p_property_id, p_value);
}
}
}
void Haplosome::SetProperty_Accelerated_tag(EidosObject **p_values, size_t p_values_size, const EidosValue &p_source, size_t p_source_size)
{
Individual::s_any_haplosome_tag_set_ = true;
// SLiMCastToUsertagTypeOrRaise() is a no-op at present
if (p_source_size == 1)
{
int64_t source_value = p_source.IntAtIndex_NOCAST(0, nullptr);
for (size_t value_index = 0; value_index < p_values_size; ++value_index)
((Haplosome *)(p_values[value_index]))->tag_value_ = source_value;
}
else
{
const int64_t *source_data = p_source.IntData();
for (size_t value_index = 0; value_index < p_values_size; ++value_index)
((Haplosome *)(p_values[value_index]))->tag_value_ = source_data[value_index];
}
}
EidosValue_SP Haplosome::ExecuteInstanceMethod(EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
switch (p_method_id)
{
//case gID_containsMarkerMutation: return ExecuteMethod_Accelerated_containsMarkerMutation(p_method_id, p_arguments, p_interpreter);
//case gID_containsMutations: return ExecuteMethod_Accelerated_containsMutations(p_method_id, p_arguments, p_interpreter);
//case gID_countOfMutationsOfType: return ExecuteMethod_Accelerated_countOfMutationsOfType(p_method_id, p_arguments, p_interpreter);
case gID_mutationsOfType: return ExecuteMethod_mutationsOfType(p_method_id, p_arguments, p_interpreter);
case gID_nucleotides: return ExecuteMethod_nucleotides(p_method_id, p_arguments, p_interpreter);
case gID_positionsOfMutationsOfType: return ExecuteMethod_positionsOfMutationsOfType(p_method_id, p_arguments, p_interpreter);
case gID_sumOfMutationsOfType: return ExecuteMethod_sumOfMutationsOfType(p_method_id, p_arguments, p_interpreter);
default: return super::ExecuteInstanceMethod(p_method_id, p_arguments, p_interpreter);
}
}
// ********************* - (Nlo<Mutation>$)containsMarkerMutation(io<MutationType>$ mutType, integer$ position, [returnMutation$ = F])
//
EidosValue_SP Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation(EidosObject **p_elements, size_t p_elements_size, EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_method_id, p_arguments, p_interpreter)
EidosValue *mutType_value = p_arguments[0].get();
EidosValue *position_value = p_arguments[1].get();
EidosValue *returnMutation_value = p_arguments[2].get();
if (p_elements_size)
{
// SPECIES CONSISTENCY CHECK
Species *haplosomes_species = Community::SpeciesForHaplosomesVector((Haplosome **)p_elements, (int)p_elements_size);
if (!haplosomes_species)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation): containsMarkerMutation() requires that all target haplosomes belong to the same species." << EidosTerminate();
haplosomes_species->population_.CheckForDeferralInHaplosomesVector((Haplosome **)p_elements, p_elements_size, "Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation");
Species &species = *haplosomes_species;
MutationType *mutation_type_ptr = SLiM_ExtractMutationTypeFromEidosValue_io(mutType_value, 0, &species.community_, &species, "containsMarkerMutation()"); // SPECIES CONSISTENCY CHECK
slim_position_t marker_position = SLiMCastToPositionTypeOrRaise(position_value->IntAtIndex_NOCAST(0, nullptr));
eidos_logical_t returnMutation = returnMutation_value->LogicalAtIndex_NOCAST(0, nullptr);
if (p_elements_size == 1)
{
// separate singleton case to return gStaticEidosValue_LogicalT / gStaticEidosValue_LogicalF
Haplosome *element = (Haplosome *)(p_elements[0]);
if (!element->IsNull())
{
Chromosome *chromosome = element->AssociatedChromosome();
slim_position_t last_position = chromosome->last_position_;
if (marker_position > last_position)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation): containsMarkerMutation() position " << marker_position << " is past the end of the chromosome for the haplosome." << EidosTerminate();
Mutation *mut = element->mutation_with_type_and_position(mutation_type_ptr, marker_position, last_position);
if (returnMutation == false)
return (mut ? gStaticEidosValue_LogicalT : gStaticEidosValue_LogicalF);
else
return (mut ? EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(mut, gSLiM_Mutation_Class)) : (EidosValue_SP)gStaticEidosValueNULL);
}
}
else if (returnMutation == false)
{
// We will return a logical vector, T/F for each target haplosome; parallelized
EidosValue_Logical *result_logical_vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Logical())->resize_no_initialize(p_elements_size);
bool null_haplosome_seen = false;
EIDOS_THREAD_COUNT(gEidos_OMP_threads_CONTAINS_MARKER_MUT);
#pragma omp parallel for schedule(dynamic, 16) default(none) shared(p_elements_size) firstprivate(p_elements, mutation_type_ptr, marker_position, last_position, result_logical_vec) reduction(||: null_haplosome_seen) if(p_elements_size >= EIDOS_OMPMIN_CONTAINS_MARKER_MUT) num_threads(thread_count)
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Haplosome *element = (Haplosome *)(p_elements[element_index]);
if (element->IsNull())
{
null_haplosome_seen = true;
continue;
}
Chromosome *chromosome = element->AssociatedChromosome();
slim_position_t last_position = chromosome->last_position_;
if (marker_position > last_position)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation): containsMarkerMutation() position " << marker_position << " is past the end of the chromosome for the haplosome." << EidosTerminate();
Mutation *mut = element->mutation_with_type_and_position(mutation_type_ptr, marker_position, last_position);
result_logical_vec->set_logical_no_check(mut != nullptr, element_index);
}
if (!null_haplosome_seen)
return EidosValue_SP(result_logical_vec);
}
else // (returnMutation == true)
{
// We will return an object<Mutation> vector, one Mutation (or NULL) for each target haplosome; not parallelized, for now
EidosValue_Object *result_obj_vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Object(gSLiM_Mutation_Class))->reserve(p_elements_size);
bool null_haplosome_seen = false;
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Haplosome *element = (Haplosome *)(p_elements[element_index]);
if (element->IsNull())
{
null_haplosome_seen = true;
continue;
}
Chromosome *chromosome = element->AssociatedChromosome();
slim_position_t last_position = chromosome->last_position_;
if (marker_position > last_position)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation): containsMarkerMutation() position " << marker_position << " is past the end of the chromosome for the haplosome." << EidosTerminate();
Mutation *mut = element->mutation_with_type_and_position(mutation_type_ptr, marker_position, last_position);
if (mut)
result_obj_vec->push_object_element_RR(mut);
}
if (!null_haplosome_seen)
return EidosValue_SP(result_obj_vec);
}
// we drop through to here when a null haplosome is encountered
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMarkerMutation): containsMarkerMutation() cannot be called on a null haplosome." << EidosTerminate();
}
else
{
return gStaticEidosValue_Logical_ZeroVec;
}
}
// ********************* - (logical)containsMutations(object<Mutation> mutations)
//
EidosValue_SP Haplosome::ExecuteMethod_Accelerated_containsMutations(EidosObject **p_elements, size_t p_elements_size, EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_method_id, p_arguments, p_interpreter)
if (p_elements_size)
{
// SPECIES CONSISTENCY CHECK
Species *haplosomes_species = Community::SpeciesForHaplosomesVector((Haplosome **)p_elements, (int)p_elements_size);
if (!haplosomes_species)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() requires that all target haplosomes belong to the same species." << EidosTerminate();
haplosomes_species->population_.CheckForDeferralInHaplosomesVector((Haplosome **)p_elements, p_elements_size, "Haplosome::ExecuteMethod_Accelerated_containsMutations");
EidosValue *mutations_value = p_arguments[0].get();
int mutations_count = mutations_value->Count();
if (mutations_count > 0)
{
Species *mutations_species = Community::SpeciesForMutations(mutations_value);
if (mutations_species != haplosomes_species)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() requires that all mutations belong to the same species as the target haplosomes." << EidosTerminate();
}
if ((mutations_count == 1) && (p_elements_size == 1))
{
// We want to be smart enough to return gStaticEidosValue_LogicalT or gStaticEidosValue_LogicalF in the singleton/singleton case
Mutation *mut = (Mutation *)(mutations_value->ObjectElementAtIndex_NOCAST(0, nullptr));
Haplosome *element = (Haplosome *)(p_elements[0]);
if (element->IsNull())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() cannot be called on a null haplosome." << EidosTerminate();
// BCH 11/24/2024: I've gone back and forth on whether it should be an error to ask whether a mutation
// associated with chromosome A is in a haplosome associated with chromosome B. For now I'm going to
// say it is an error, and that can be relaxed later if it becomes clear that it is too strict. It
// does seem like it is a question that indicates a fundamental logic flaw, like asking whether a
// mutation that belongs to species A is in a haplosome that belongs to species B.
if (mut->chromosome_index_ != element->chromosome_index_)
{
//return gStaticEidosValue_LogicalF;
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() requires that all mutations are associated with the same chromosome as the target haplosomes. (If this requirement makes life difficult, it could be relaxed if necessary; but it seems useful for catching logic errors. Note that the containsMutations() method of Individual does not have this restriction.)" << EidosTerminate();
}
bool contained = element->contains_mutation(mut);
return (contained ? gStaticEidosValue_LogicalT : gStaticEidosValue_LogicalF);
}
else
{
EidosValue_Logical *logical_result = (new (gEidosValuePool->AllocateChunk()) EidosValue_Logical())->resize_no_initialize(p_elements_size * mutations_count);
EidosValue_SP result(logical_result);
int64_t result_index = 0;
EidosObject * const *mutations_data = mutations_value->ObjectData();
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Haplosome *element = (Haplosome *)(p_elements[element_index]);
if (element->IsNull())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() cannot be called on a null haplosome." << EidosTerminate();
for (int value_index = 0; value_index < mutations_count; ++value_index)
{
Mutation *mut = (Mutation *)mutations_data[value_index];
// BCH 11/24/2024: I've gone back and forth on whether it should be an error to ask whether a mutation
// associated with chromosome A is in a haplosome associated with chromosome B. For now I'm going to
// say it is an error, and that can be relaxed later if it becomes clear that it is too strict. It
// does seem like it is a question that indicates a fundamental logic flaw, like asking whether a
// mutation that belongs to species A is in a haplosome that belongs to species B.
if (mut->chromosome_index_ != element->chromosome_index_)
{
//logical_result->set_logical_no_check(false, result_index++);
//continue;
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_containsMutations): containsMutations() requires that all mutations are associated with the same chromosome as the target haplosomes. (If this requirement makes life difficult, it could be relaxed if necessary; but it seems useful for catching logic errors. Note that the containsMutations() method of Individual does not have this restriction.)" << EidosTerminate();
}
bool contained = element->contains_mutation(mut);
logical_result->set_logical_no_check(contained, result_index++);
}
}
return result;
}
}
else
{
return gStaticEidosValue_Logical_ZeroVec;
}
}
// ********************* - (integer$)countOfMutationsOfType(io<MutationType>$ mutType)
//
EidosValue_SP Haplosome::ExecuteMethod_Accelerated_countOfMutationsOfType(EidosObject **p_elements, size_t p_elements_size, EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_method_id, p_arguments, p_interpreter)
if (p_elements_size == 0)
return gStaticEidosValue_Integer_ZeroVec;
// SPECIES CONSISTENCY CHECK
Species *species = Community::SpeciesForHaplosomesVector((Haplosome **)p_elements, (int)p_elements_size);
if (species == nullptr)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_countOfMutationsOfType): countOfMutationsOfType() requires that mutType belongs to the same species as the target individual." << EidosTerminate();
species->population_.CheckForDeferralInHaplosomesVector((Haplosome **)p_elements, p_elements_size, "Haplosome::ExecuteMethod_Accelerated_countOfMutationsOfType");
EidosValue *mutType_value = p_arguments[0].get();
MutationType *mutation_type_ptr = SLiM_ExtractMutationTypeFromEidosValue_io(mutType_value, 0, &species->community_, species, "countOfMutationsOfType()"); // SPECIES CONSISTENCY CHECK
// Count the number of mutations of the given type
const int32_t mutrun_count = ((Haplosome *)(p_elements[0]))->mutrun_count_;
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
EidosValue_Int *integer_result = (new (gEidosValuePool->AllocateChunk()) EidosValue_Int())->resize_no_initialize(p_elements_size);
bool saw_error = false;
EIDOS_THREAD_COUNT(gEidos_OMP_threads_G_COUNT_OF_MUTS_OF_TYPE);
#pragma omp parallel for schedule(dynamic, 1) default(none) shared(p_elements_size) firstprivate(p_elements, mut_block_ptr, mutation_type_ptr, integer_result, mutrun_count) reduction(||: saw_error) if(p_elements_size >= EIDOS_OMPMIN_G_COUNT_OF_MUTS_OF_TYPE) num_threads(thread_count)
for (size_t element_index = 0; element_index < p_elements_size; ++element_index)
{
Haplosome *element = (Haplosome *)(p_elements[element_index]);
if (element->IsNull())
{
saw_error = true;
continue;
}
int match_count = 0;
for (int run_index = 0; run_index < mutrun_count; ++run_index)
{
const MutationRun *mutrun = element->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)
if ((mut_block_ptr + mut_ptr[mut_index])->mutation_type_ptr_ == mutation_type_ptr)
++match_count;
}
integer_result->set_int_no_check(match_count, element_index);
}
if (saw_error)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_Accelerated_countOfMutationsOfType): countOfMutationsOfType() cannot be called on a null haplosome." << EidosTerminate();
return EidosValue_SP(integer_result);
}
// ********************* - (object<Mutation>)mutationsOfType(io<MutationType>$ mutType)
//
EidosValue_SP Haplosome::ExecuteMethod_mutationsOfType(EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_method_id, p_arguments, p_interpreter)
EidosValue *mutType_value = p_arguments[0].get();
if (IsDeferred())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_mutationsOfType): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
if (IsNull())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_mutationsOfType): mutationsOfType() cannot be called on a null haplosome." << EidosTerminate();
Species &species = individual_->subpopulation_->species_;
MutationType *mutation_type_ptr = SLiM_ExtractMutationTypeFromEidosValue_io(mutType_value, 0, &species.community_, &species, "mutationsOfType()"); // SPECIES CONSISTENCY CHECK
// We want to return a singleton if we can, but we also want to avoid scanning through all our mutations twice.
// We do this by not creating a vector until we see the second match; with one match, we make a singleton.
Mutation *mut_block_ptr = gSLiM_Mutation_Block;
Mutation *first_match = nullptr;
EidosValue_Object *vec = nullptr;
EidosValue_SP result_SP;
int run_index;
for (run_index = 0; run_index < mutrun_count_; ++run_index)
{
const MutationRun *mutrun = 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)
{
Mutation *mut = (mut_block_ptr + mut_ptr[mut_index]);
if (mut->mutation_type_ptr_ == mutation_type_ptr)
{
if (!vec)
{
if (!first_match)
first_match = mut;
else
{
vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Object(gSLiM_Mutation_Class));
result_SP = EidosValue_SP(vec);
vec->push_object_element_RR(first_match);
vec->push_object_element_RR(mut);
first_match = nullptr;
}
}
else
{
vec->push_object_element_RR(mut);
}
}
}
}
// Now return the appropriate return value
if (first_match)
{
return EidosValue_SP(new (gEidosValuePool->AllocateChunk()) EidosValue_Object(first_match, gSLiM_Mutation_Class));
}
else
{
if (!vec)
{
vec = (new (gEidosValuePool->AllocateChunk()) EidosValue_Object(gSLiM_Mutation_Class));
result_SP = EidosValue_SP(vec);
}
return result_SP;
}
}
// ********************* – (is)nucleotides([Ni$ start = NULL], [Ni$ end = NULL], [s$ format = "string"])
//
EidosValue_SP Haplosome::ExecuteMethod_nucleotides(EidosGlobalStringID p_method_id, const std::vector<EidosValue_SP> &p_arguments, EidosInterpreter &p_interpreter)
{
#pragma unused (p_method_id, p_arguments, p_interpreter)
if (IsDeferred())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_nucleotides): the mutations of deferred haplosomes cannot be accessed." << EidosTerminate();
Species *species = &individual_->subpopulation_->species_;
Chromosome *chromosome = AssociatedChromosome();
slim_position_t last_position = chromosome->last_position_;
if (!species->IsNucleotideBased())
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_nucleotides): nucleotides() may only be called in nucleotide-based models." << EidosTerminate();
NucleotideArray *sequence = chromosome->AncestralSequence();
EidosValue *start_value = p_arguments[0].get();
EidosValue *end_value = p_arguments[1].get();
int64_t start = (start_value->Type() == EidosValueType::kValueNULL) ? 0 : start_value->IntAtIndex_NOCAST(0, nullptr);
int64_t end = (end_value->Type() == EidosValueType::kValueNULL) ? last_position : end_value->IntAtIndex_NOCAST(0, nullptr);
if ((start < 0) || (end < 0) || (start > last_position) || (end > last_position) || (start > end))
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_nucleotides): start and end must be within the chromosome's extent, and start must be <= end." << EidosTerminate();
if (((std::size_t)start >= sequence->size()) || ((std::size_t)end >= sequence->size()))
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_nucleotides): (internal error) start and end must be within the ancestral sequence's length." << EidosTerminate();
int64_t length = end - start + 1;
if (length > INT_MAX)
EIDOS_TERMINATION << "ERROR (Haplosome::ExecuteMethod_nucleotides): the returned vector would exceed the maximum vector length in Eidos." << EidosTerminate();
EidosValue_String *format_value = (EidosValue_String *)p_arguments[2].get();
const std::string &format = format_value->StringRefAtIndex_NOCAST(0, nullptr);
if (format == "codon")
{
EidosValue_SP codon_value = sequence->NucleotidesAsCodonVector(start, end, /* p_force_vector */ true);
// patch the sequence with nucleotide mutations
// no singleton case; we force a vector return from NucleotidesAsCodonVector() for simplicity
int64_t *int_vec = ((EidosValue_Int *)(codon_value.get()))->data_mutable();
HaplosomeWalker walker(this);
walker.MoveToPosition(start);
while (!walker.Finished())
{
Mutation *mut = walker.CurrentMutation();
slim_position_t pos = mut->position_;
// pos >= start is guaranteed by MoveToPosition()
if (pos > end)
break;
int8_t nuc = mut->nucleotide_;