-
Notifications
You must be signed in to change notification settings - Fork 2
/
cnF2freq.cpp
8199 lines (7055 loc) · 222 KB
/
cnF2freq.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
// cnF2freq, (c) Carl Nettelblad, Department of Information Technology, Uppsala University
// 2008-2019
//
// PlantImpute 1.5, with support for forward-backward and old "true" tree-style cnF2freq
// algorithm. This reduces mamoery requirements and speeds up imputation. A lot. Still
// som e kinks to work out. Please contact the author regarding proper references.
//
//
// This code is allowed to be freely used for any commercial or research purpose. If the code is
// used or integrated into another project largely unchanged, attribution to the original author
// should be included. No warranties are given.
#define NDEBUG
#define BOOST_NO_EXCEPTIONS
#undef __cpp_exceptions
#define __cpp_exceptions 0
#include <exception>
#include <cstdlib>
namespace boost
{
void throw_exception( std::exception const & e )
{std::abort();}
}
#include <vector>
#include <string.h>
#include <stdio.h>
#include <omp.h>
#include <limits>
const int ANALYZE_FLAG_FORWARD = 0;
const int ANALYZE_FLAG_BACKWARD = 16;
const int ANALYZE_FLAG_STORE = 32;
float templgeno[8] = { -1, -0.5,
0, 0.5,
0, 0.5,
1, -0.5 };
const int NO_EQUIVALENCE = -1;
const int ZERO_PROPAGATE = 1;
const long long WEIGHT_DISCRETIZER = 1000000;
#include <array>
#include <ranges>
#include <boost/math/distributions/binomial.hpp>
#include <boost/static_assert.hpp>
#include <boost/random/linear_congruential.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
/*#include <boost/mpi/environment.hpp>
#include <boost/mpi/communicator.hpp>
#include <boost/mpi.hpp>*/
#include <memory>
#include <string>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/static_vector.hpp>
#include <boost/program_options.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/container/vector/vector_fwd.hpp>
#include <boost/fusion/include/vector_fwd.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/fusion/include/at_c.hpp>
//#include <boost/numeric/odeint.hpp>
#include <boost/math/quadrature/gauss_kronrod.hpp>
#include <iostream>
#include <fstream>
#if LIBSTATGEN
#include <VcfRecordGenotype.h>
#include <VcfFileReader.h>
#include <VcfFileWriter.h>
#endif
#include <vector>
using namespace boost::iostreams;
using namespace boost::spirit;
namespace po = boost::program_options;
//namespace ode = boost::numeric::odeint;
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include <unordered_set>
#include <set>
#include <algorithm>
#include <math.h>
#include <type_traits>
#include <map>
#include <float.h>
#include <numeric>
#include <type_traits>
#include <spawn.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std; // use functions that are part of the standard library
//using namespace boost::mpi;
using namespace boost::random;
using boost::container::static_vector;
using boost::container::small_vector;
using boost::container::flat_map;
using boost::container::flat_set;
#define none cnF2freqNONE
#ifndef _MSC_VER
#define _isnan isnan
#define _finite isfinite
#endif
#include "settings.h"
#if XSTDBITSET
#include <xstd/bit_set.hpp>
#endif
#define __assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)
#define restrict __restrict__
EXTERNFORGCC boost::random::mt19937 rng;
#pragma omp threadprivate(rng)
#ifdef DOEXTERNFORGCC
boost::random::mt19937 rng;
#endif
struct spectype
{
};
spectype globspec;
int myrand(int max)
{
boost::uniform_int<> orig(0, max - 1);
return orig(rng);
}
struct negtrue
{
const int value;
negtrue(bool neg, int value) : value(neg ? -1 : (value >= 0 ? value : 0))
{
}
operator bool() const
{
return value < 0;
}
};
struct MarkerValueType {};
constexpr MarkerValueType MarkerValue;
struct MarkerVal
{
private:
int val;
public:
constexpr explicit MarkerVal(int val) : val(val) {}
constexpr MarkerVal() : val(0) {}
constexpr int value() const
{
return val;
}
constexpr bool operator == (const MarkerVal& rhs) const
{
return val == rhs.val;
}
constexpr bool operator != (const MarkerVal& rhs) const
{
return val != rhs.val;
}
constexpr bool operator < (const MarkerVal& rhs) const
{
return val < rhs.val;
}
};
constexpr const MarkerVal operator* (const int& val, const MarkerValueType& rhs)
{
return MarkerVal(val);
}
typedef pair<MarkerVal, MarkerVal> MarkerValPair;
const MarkerVal UnknownMarkerVal = (MarkerVal)0;
const MarkerVal sexmarkerval = 9 * MarkerValue;
const float maxdiff = 0.000005;
bool early = false;
vector<double> markerposes;;
vector<double> actrec[2];
map<string, int> markernames;
//int selfgen = 0;
double genrec[3];
vector<unsigned int> chromstarts;
vector<int> markertranslation;
typedef vector<array<double, 5 > > MWTYPE;
template<class T> class vectorplus;
template<> class vectorplus<MWTYPE >
{
public:
MWTYPE operator () (const MWTYPE& l, const MWTYPE& r)
{
MWTYPE result;
result.resize(l.size());
for (size_t i = 0; i < l.size(); i++)
{
for (int j = 0; j < 5; j++)
{
result[i][j] = l[i][j] + r[i][j];
}
}
return result;
}
};
template<class T> class vectorplus<vector<T> >
{
public:
vector<T> operator () (const vector<T>& l, const vector<T>& r)
{
vector<T> result;
result.resize(l.size());
for (size_t i = 0; i < l.size(); i++)
{
result[i] = l[i] + r[i];
}
return result;
}
};
/*namespace boost { namespace mpi {
template<class T>
struct is_commutative<vectorplus<vector<T> >, vector<T> >
: mpl::true_ { };
} }*/
MWTYPE markerweight;
MWTYPE markerweight2;
double discstep = 0.1;
double baserec[2];
int sexc = 1;
// Is a specific marker value a admissible as a match to marker b
// The logic we use currently represents "0" as unknown, anything else as a known
// marker value.
// NOTE, VALUE CHANGED FOR ZEROS!
template<int zeropropagate> bool markermiss(MarkerVal& a, const MarkerVal b)
{
// This is the real logic; we do not bind anything at all when zeropropagate is true
if (zeropropagate == ZERO_PROPAGATE) return false;
if (a == UnknownMarkerVal)
{
if (!zeropropagate) a = b;
return false;
}
if (b == UnknownMarkerVal && a != sexmarkerval) return false;
return a != b;
}
// Move a tree-based binary flag up a generation. The structure of bit flags might look like
// (1)(3)(3), where each group of (3) is in itself (1)(2), where (2) is of course (1)(1).
int upflagit(int flag, int parnum, unsigned int genwidth)
{
if (flag < 0) return flag;
flag >>= parnum * (genwidth - 1);
flag &= ((1 << (genwidth - 1)) - 1);
return flag;
}
struct individ;
std::string tmppath{ "." };
int generation = 1;
int shiftflagmode;
int lockpos[NUMSHIFTS];
int quickmark[NUMSHIFTS];
int quickgen[NUMSHIFTS];
template<class T2> class PerStateArray
{
public:
typedef array<T2, NUMTYPES> T;
};
template<class T2> class StateToStateMatrix
{
public:
typedef typename PerStateArray<
typename PerStateArray<T2>::T >
::T T;
};
#if !DOFB
// The quick prefixes are caches that retain the last invocation.
// Only used fully when we stop at marker positions exactly, i.e. not a general grid search.
double quickfactor[NUMSHIFTS];
PerStateArray<int>::T quickendmarker[NUMSHIFTS];
PerStateArray<double>::T quickendfactor[NUMSHIFTS];
StateToStateMatrix<double>::T quickendprobs[NUMSHIFTS];
PerStateArray<double>::T quickmem[NUMSHIFTS];
#endif
small_vector<std::pair<MarkerVal, double>, 5> testlista;
template<class K, class T, int N = 2> using small_map = flat_map<K, T, less<K>, small_vector<std::pair<K, T>, N>>;
// A hashed store of inheritance pathway branches that are known to be impossible.
// Since we can track the two branches that make up the state in the F_2 individual independently,
// this optimization can reduce part of the cost by sqrt(number of states).
typedef array<array<array<array<array<array<array<int, 4>, HALFNUMSHIFTS>, HALFNUMPATHS + 1>, HALFNUMTYPES>, 2>, 2>, 2> IAT;
EXTERNFORGCC IAT impossible;
// A memory structure storing haplo information for later update.
// By keeping essentially thread-independent copies, no critical sections have to
// be acquired during the updates.
EXTERNFORGCC array<array<double, 2>, INDCOUNT> haplos;
EXTERNFORGCC array<array<small_map<MarkerVal, double>, 2>, INDCOUNT> infprobs;
#if !DOFB
// done, factors and cacheprobs all keep track of the same data
// done indicates that a specific index (in the binary tree of blocks of multi-step transitions) is done
// with a "generation id" that's semi-unique, meaning no active clearing of the data structure is performed
EXTERNFORGCC vector<int> done[NUMSHIFTS];
// factors contain the mantissas of the extended floating-point representation
EXTERNFORGCC vector<PerStateArray<double>::T > factors[NUMSHIFTS];
// cacheprobs contain actual transitions from every possible state to every possible other state
EXTERNFORGCC vector<StateToStateMatrix<double>::T > cacheprobs[NUMSHIFTS];
#else
EXTERNFORGCC vector<array<PerStateArray<double>::T, 3> > fwbw[NUMSHIFTS];
EXTERNFORGCC vector<array<double, 3> > fwbwfactors[NUMSHIFTS];
int fwbwdone[NUMSHIFTS];
#endif
EXTERNFORGCC vector<individ*> reltree;
EXTERNFORGCC vector<individ*> reltreeordered;
EXTERNFORGCC flat_map<individ*, int> relmap;
EXTERNFORGCC flat_map<individ*, int> relmapshift;
//#pragma omp threadprivate(realdone, realfactors, realcacheprobs)
#pragma omp threadprivate(generation, shiftflagmode, impossible, haplos, lockpos, reltree, reltreeordered, relmap, relmapshift, infprobs)
#if !DOFB
#pragma omp threadprivate(quickmark, quickgen, quickmem, quickfactor, quickendfactor, quickendprobs, done, factors, cacheprobs)
#else
#pragma omp threadprivate(fwbw,fwbwfactors,fwbwdone)
#endif
#ifdef DOEXTERNFORGCC
IAT impossible;
array<array<double, 2>, INDCOUNT> haplos;
vector<PerStateArray<double>::T > factors[NUMSHIFTS];
vector<individ*> reltree;
vector<individ*> reltreeordered;
flat_map<individ*, int> relmap; //containing flag2 indices
flat_map<individ*, int> relmapshift; //containing flag2 indices
std::array<std::array<small_map<MarkerVal, double>, 2>, INDCOUNT> infprobs;
#if !DOFB
vector<int> done[NUMSHIFTS];
vector<StateToStateMatrix<double>::T > cacheprobs[NUMSHIFTS];
#else
vector<std::array<PerStateArray<double>::T, 3> > fwbw[NUMSHIFTS];
vector<std::array<double, 3> > fwbwfactors[NUMSHIFTS];
#endif
#endif
// We put all thread-local structures in our own separate struct. This is because many compilers implementing OpenMP
// use a relatively expensive call for determining thread-local global data, which is not cached over function calls.
// The simple pointer-arithmetic for a lookup within a struct is cheaper.
struct threadblock
{
int* const generation;
int* const shiftflagmode;
#if !DOFB
int* const quickmark;
int* const quickgen;
#endif
int* const lockpos;
#if !DOFB
double* const quickfactor;
PerStateArray<double>::T* const quickmem;
PerStateArray<int>::T* const quickendmarker;
#endif
IAT* const impossible;
std::array<std::array<double, 2>, INDCOUNT>* const haplos;
std::array<std::array<small_map<MarkerVal, double>, 2>, INDCOUNT>* infprobs;
#if !DOFB
vector<int>* const done;
vector<PerStateArray<double>::T >* const factors;
vector<StateToStateMatrix<double>::T >* const cacheprobs;
PerStateArray<double>::T* const quickendfactor;
StateToStateMatrix<double>::T* const quickendprobs;
#else
vector<std::array<PerStateArray<double>::T, 3> >* fwbw;
vector<std::array<double, 3> >* fwbwfactors;
int* fwbwdone;
#endif
threadblock() : generation(&::generation), shiftflagmode(&::shiftflagmode), impossible(&::impossible),
haplos(&::haplos), lockpos(::lockpos), infprobs(&::infprobs),
#if !DOFB
done(::done), factors(::factors), cacheprobs(::cacheprobs),
quickmark(::quickmark), quickgen(::quickgen), quickmem(::quickmem),
quickfactor(::quickfactor), quickendfactor(::quickendfactor), quickendprobs(::quickendprobs),
quickendmarker(::quickendmarker),
#else
fwbw(::fwbw), fwbwfactors(::fwbwfactors), fwbwdone(::fwbwdone)
#endif
{
};
};
// Turners are used as mix-ins when probabilities are filtered at the "fixed" marker
// (the one we are actually probing).
// This functionality is used to invert the state in different manner, to test for the
// possibility that the complete haplotype assignment from an arbitrary point until the end
// has been mixed up. This can easily happen as the assignment of haplotype numbers is
// basically arbitrary, so the only thing keeping it in place is the linkage to the original
// defining locus.
class noneturner
{
public:
void operator() (const PerStateArray<double>::T& probs) const
{
};
bool canquickend() const
{
return true;
}
} none;
class aroundturner
{
int turn;
int flagmodeshift;
public:
aroundturner(int turn)
{
if (NUMGEN == 3)
{
this->turn = turn & 54;
flagmodeshift = (turn >> TYPEBITS) | ((turn & 1) ? 2 : 0) |
((turn & 8) ? 4 : 0);
// Mis-guided (?) attempt to correct for relskews
if (RELSKEWSTATES && false)
{
this->turn |= (flagmodeshift & 1) << BITS_W_SELF;
}
}
else
{
this->turn = turn & 3;
flagmodeshift = (turn >> TYPEBITS);
}
}
bool canquickend() const
{
return false;
}
void operator() (PerStateArray<double>::T& probs) const
{
PerStateArray<double>::T probs2;
for (int i = 0; i < NUMTYPES; i++)
{
int newval = i ^ turn;
if (flagmodeshift)
{
// Emulating actually switching parental genotypes around
// newval = ((newval & 1) << 1) | ((newval & 2) >> 1);
}
probs2[newval] = probs[i];
}
for (int i = 0; i < NUMTYPES; i++)
{
probs[i] = probs2[i];
}
// Not *tb out of laziness, the number of calls is limited
shiftflagmode ^= flagmodeshift;
// Hacky, tacky
};
};
// A struct containing some auxiliary arguments to the trackpossible family of functions.
// These parameters are not known at compile-time, hence not template arguments, but they do not
// change over the series of recursive calls.
const struct trackpossibleparams
{
const double updateval;
int* const gstr;
trackpossibleparams() : updateval(0.0), gstr(0)
{
}
trackpossibleparams(double updateval, int* gstr, MarkerVal markerval = UnknownMarkerVal) : updateval(updateval), gstr(gstr)
{
}
} tpdefault;
struct classicstop
{
int lockpos;
int genotype;
classicstop(int lockpos, int genotype) : lockpos(lockpos), genotype(genotype)
{}
explicit operator int() const
{
return lockpos;
}
const int getgenotype(int startmark) const
{
return genotype;
}
negtrue okstep(const int startmark, const int endmark) const
{
bool found = (lockpos <= -1000 - startmark && lockpos > -1000 - endmark) ||
(lockpos >= markerposes[startmark] && lockpos <= markerposes[endmark]);
return negtrue(!found, genotype);
}
bool fixtofind(int& genotype, double& startpos, double& endpos, int j) const
{
bool tofind = (lockpos >= startpos && lockpos <= endpos);
if (tofind)
{
endpos = lockpos;
}
if (lockpos == -1000 - j + 1)
{
tofind = true;
endpos = startpos;
}
if (tofind)
{
genotype = this->genotype;
}
return tofind;
}
};
struct smnonecommon
{
const int getgenotype(int startmark) const
{
return -1;
}
};
struct nonestop : smnonecommon
{
operator int() const
{
assert(false);
return -1;
}
negtrue okstep(const int startmark, const int endmark) const
{
return negtrue(true, 0);
}
bool fixtofind(int& genotype, double& startpos, double& endpos, int j) const
{
return false;
}
} NONESTOP;
struct tssmcommon
{
int lockpos;
int genotype[2];
operator int() const
{
return lockpos;
}
negtrue okstep(const int startmark, const int endmark) const
{
// twicestop is only used for markers
bool found = (lockpos <= -1000 - startmark + 1 && lockpos > -1000 - endmark);
if (found)
{
int index = -lockpos - startmark - 1000;
if (index == 0 || index == 1) return negtrue(!found, genotype[index]);
}
return negtrue(!found, 0);
}
bool fixtofind(int& genotype, double& startpos, double& endpos, int j) const
{
bool two = lockpos == -1000 - j + 2;
if (lockpos == -1000 - j + 1 || two)
{
endpos = startpos;
genotype = this->genotype[two];
return true;
}
return false;
}
protected: tssmcommon(int lockpos) : lockpos(lockpos)
{
}
};
struct twicestop : tssmcommon
{
twicestop(int lockpos, int* genotype) : tssmcommon(lockpos)
{
this->genotype[0] = genotype[0];
this->genotype[1] = genotype[1];
}
twicestop(int lockpos, int g1, int g2) : tssmcommon(lockpos)
{
this->genotype[0] = g1;
this->genotype[1] = g2;
}
const int getgenotype(int startmark) const
{
return genotype[-1000 - startmark != lockpos];
}
};
struct stopmodpair : tssmcommon, smnonecommon
{
typedef std::array<std::array<float, 2>, 2> miniactrecT;
miniactrecT actrec;
stopmodpair(int lockpos, miniactrecT actrec) : tssmcommon(lockpos), actrec(actrec)
{
genotype[0] = -1;
genotype[1] = -1;
}
};
template<class G> const bool canquickend(int startmark, const G& stopdata)
{
return false;
}
/*template<> const bool canquickend<smnonecommon>(int startmark, const smnonecommon &stopdata)
{
return false;
}*/
template<> const bool canquickend<classicstop>(int startmark, const classicstop& stopdata)
{
return stopdata.lockpos <= -1000 && stopdata.genotype >= 0;
}
template<> const bool canquickend<twicestop>(int startmark, const twicestop& stopdata)
{
return stopdata.lockpos == -1000 - startmark + 1;
}
// Should only be called for markers where locking is really done
template<class G> bool firstlockmatch(int lockpos, const G& stopdata)
{
return stopdata.lockpos == lockpos;
}
template<> bool firstlockmatch<nonestop>(const int lockpos, const nonestop& stopdata)
{
return false;
}
#ifdef PERMARKERACTREC
template<class G> double getactrec(const G& stopdata, double startpos, double endpos, int k, int j, int gen)
{
return actrec[k][j];
}
#else
template<class G> double getactrec(const G& stopdata, double startpos, double endpos, int k, int j, int gen)
{
return genrec[gen];
}
#endif
template<> double getactrec<stopmodpair>(const stopmodpair& stopdata, double startpos, double endpos, int k, int j, int gen)
{
int index = j - 1 + stopdata.lockpos + 1000;
if (index == 0 || index == 1) return stopdata.actrec[k][index];
return actrec[k][j];
}
const int HAPLOS = 1;
const int GENOS = 2;
const int HOMOZYGOUS = 4;
const int GENOSPROBE = 8;
struct clause
{
long long weight;
static_vector<int, 8> cinds;
//vector<individ*> individuals;
string toString() const {
string s = boost::lexical_cast<std::string>(weight);
//std::stringstream ints;
//std::copy(cInds.begin(), cInds.end(), std::ostream_iterator<int>(ints, " "));
for (size_t i = 0; i < cinds.size(); i++) {
if (cinds[i]) {
s = s + " " + boost::lexical_cast<std::string>(cinds[i]);
}
}
//s = s + " " + ints.str();
return s;// note each line ends in a space
}
stringstream& clausetostringstream() const {
static thread_local stringstream s;
s.str("");
s.clear();
for (size_t i = 0; i < cinds.size(); i++) {
if (cinds[i]) {
s << " " << std::to_string(cinds[i]);
}
}
return s;
}
string weighttostring() const {
return std::to_string(weight);
}
};
template<int skipper, int update, int zeropropagate>
struct vectortrackpossible
{
const threadblock& tb;
MarkerVal inmarkerval[TURNBITS][NUMPATHS / skipper];
double secondval[TURNBITS][NUMPATHS / skipper];
int geno[TURNBITS][NUMPATHS / skipper]; // Used to be flag
int flag2[TURNBITS][NUMPATHS / skipper]; // Used to be flag99 and flag2 everywhere else
int localshift[TURNBITS][NUMPATHS / skipper];
double result[NUMPATHS / skipper];
const trackpossibleparams& extparams;
const unsigned int marker;
int meid;
int menow;
vectortrackpossible(unsigned int marker, const trackpossibleparams& extparams, int flag2);
};
// A structure containing most of the information on an individual
struct individ
{
// The individual #.
int n;
string name;
// Generation number. Convenient, while not strictly needed.
int gen;
// Number of children.
int children;
int descendants;
// Am I explicitly created to not contain genotypes?
bool empty;
// Do I lack (relevant) parents?
bool founder;
// Parents.
individ* pars[2];
//
vector<individ*> kids;
// Sex.
bool sex;
// Line or strain of origin, should only exist in founders.
int strain;
// Marker data as a list of pairs. No specific ordering assumed.
vector<MarkerValPair> markerdata;
vector<double> variances;
vector<pair<double, double>> markersure;
vector<MarkerValPair> priormarkerdata;
vector<pair<double, double>> priormarkersure;
vector<array<double, 3>> priorgenotypes;
// Temporary storage of all possible marker values, used in fixparents.
vector<small_map<MarkerVal, pair<int, double> > > markervals;
// The haplotype weight, or skewness. Introducing an actual ordering of the value in markerdata.
vector<double> haploweight;
// Relative skewness, i.e. shifts between adjacent markers.
vector<double> relhaplo;
// The cost-benefit value of inverting the haplotype assignment from an arbitrary marker point on.
vector<double> negshift;
vector<int> lastinved;
vector<unsigned int> lockstart;
vector<array<small_map<MarkerVal, double>, 2> > infprobs;
vector<array<double, 2>> homozyg;
vector<int> genotypegrid;
// Accumulators for haplotype skewness updates.
vector<double> haplobase;
vector<double> haplocount;
individ()
{
pars[0] = 0;
pars[1] = 0;
strain = 0;
sex = false;
empty = false;
// False is the safe option, other code will be take shortcuts if founder is true.
founder = false;
descendants = 0;
}
bool arerelated(individ* b, vector<individ*> stack = vector<individ*>(), int gens = 0)
{
if (gens > 2) return false;
if (!this) abort();
if (b == this) return true;
if (find(stack.begin(), stack.end(), this) != stack.end())
{
return false;
}
stack.push_back(this);
if (stack.size() == 1)
{
if (b && b->arerelated(this, stack, gens + 1)) return true;
}
if (pars[0] && pars[0]->arerelated(b, stack, gens + 1)) return true;
if (pars[1] && pars[1]->arerelated(b, stack, gens + 1)) return true;
for (individ* i : kids)
{
for (individ* j : b->kids)
{
if (i == j) return true;
}
}
//stack.pop_back();
return false;
}
// A wrapper for calling trackpossible. Additional logic introduced to do lookup in the "impossible" tables of branches
// not allowed at the current point. This will generally mean most branches and reduces the number of states visited considerably
// in typical cases.
//
// The double overload means that the class can be treated as a conventional function call, returning a double, when the pre-lookup
// is not needed. In the "real" trackpossible method, one instance is called in that way, while the other one is pre-looked up.
template<int update, int zeropropagate, class extra=const spectype, int templgenwidth = -2, int templflag2 = -2> struct recursetrackpossible
{
individ* mother;
int upflagr;
int upflag2r;
int upshiftr;
double secondval;
const trackpossibleparams& extparams;
const unsigned int genwidth;
const MarkerVal markerval;
const int marker;
const threadblock& tb;
int firstpar;
int* impossibleref;
int impossibleval;
bool prelok;
extra& data;
recursetrackpossible(individ* mother, const threadblock& tb, MarkerVal markerval, double secondval, int marker, int upflag, int upflag2, int upshift, unsigned int genwidth, int f2n, int firstpar, int numrealpar, const trackpossibleparams& extparams, extra& data) noexcept :
genwidth(genwidth), extparams(extparams), markerval(markerval), marker(marker), tb(tb), firstpar(firstpar), mother(mother), secondval(secondval), data(data)
{
if constexpr (templgenwidth >= 0) __assume(genwidth == templgenwidth);
if constexpr (templflag2 > -2)
{
if constexpr (templflag2 == -1) __assume(upflag2 == -1);
else
__assume(upflag2 > -1);
}
upflagr = upflagit(upflag, firstpar, genwidth);
upflag2r = upflagit(upflag2, firstpar, genwidth >> (NUMGEN - NUMFLAG2GEN));
upshiftr = upflagit(upshift, firstpar, genwidth >> (NUMGEN - NUMSHIFTGEN));
prelok = true;
if constexpr (DOIMPOSSIBLE)
{
if (zeropropagate != ZERO_PROPAGATE && genwidth == (1 << (NUMGEN - 1)))
{
if (DOIMPOSSIBLE)
{
impossibleref = &(*tb.impossible)[*(tb.shiftflagmode) & 1][firstpar][f2n][upflagr][upflag2r + 1][upshiftr][marker & 3];
impossibleval = (*tb.generation) * markerposes.size() + marker;
}
else
{