Debian Codegraph @

plink2_ld.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "include/plink2_stats.h"
19 #include "plink2_compress_stream.h"
20 #include "plink2_filter.h"
21 #include "plink2_ld.h"
22 #include "plink2_set.h"
23
24 #include <unistd.h> // unlink()
25
26 #ifdef __cplusplus
27 # include <functional> // std::greater
28 #endif
29
30 #ifdef __cplusplus
31 namespace plink2 {
32 #endif
33
34 void InitLd(LdInfo* ldip) {
35 ldip->prune_flags = kfLdPrune0;
36 ldip->prune_window_size = 0;
37 ldip->prune_window_incr = 0;
38 ldip->prune_last_param = 0.0;
39 ldip->ld_console_flags = kfLdConsole0;
40 ldip->ld_console_varids[0] = nullptr;
41 ldip->ld_console_varids[1] = nullptr;
42 }
43
44 void CleanupLd(LdInfo* ldip) {
45 free_cond(ldip->ld_console_varids[0]);
46 free_cond(ldip->ld_console_varids[1]);
47 }
48
49 void InitClump(ClumpInfo* clump_ip) {
50 clump_ip->fnames_flattened = nullptr;
51 clump_ip->range_fname = nullptr;
52 clump_ip->test_name = nullptr;
53 clump_ip->id_field = nullptr;
54 clump_ip->a1_field = nullptr;
55 clump_ip->test_field = nullptr;
56 clump_ip->p_field = nullptr;
57 clump_ip->ln_bin_boundaries = nullptr;
58 clump_ip->ln_p1 = kLn10 * -4.0 * (1.0 - kSmallEpsilon);
59 clump_ip->ln_p2 = kLn10 * -2.0 * (1.0 - kSmallEpsilon);
60 clump_ip->r2 = 0.5 * (1.0 + kSmallEpsilon);
61 clump_ip->bin_bound_ct = 0;
62 clump_ip->bp_radius = 249999;
63 clump_ip->range_border = 0;
64 clump_ip->flags = kfClump0;
65 }
66
67 void CleanupClump(ClumpInfo* clump_ip) {
68 free_cond(clump_ip->fnames_flattened);
69 free_cond(clump_ip->range_fname);
70 free_cond(clump_ip->test_name);
71 free_cond(clump_ip->id_field);
72 free_cond(clump_ip->a1_field);
73 free_cond(clump_ip->test_field);
74 free_cond(clump_ip->p_field);
75 free_cond(clump_ip->ln_bin_boundaries);
76 }
77
78 void InitVcor(VcorInfo* vcip) {
79 vcip->ld_snp_list_fname = nullptr;
80 InitRangeList(&(vcip->ld_snp_range_list));
81 // We want to error out during command-line parsing when the user specifies
82 // matrix output with one of these filters, or inter-chr output with one of
83 // the radius filters.
84 // Unfortunately, --ld-window... flags are parsed before --r[2]-[un]phased,
85 // so directly initializing bp_radius and min_r2 to default values doesn't
86 // work out cleanly. Instead, we initialize them to out-of-range values, and
87 // fill in defaults during --r[2]-[un]phased parsing.
88 vcip->var_ct_radius = 0x7fffffff; // avoids overflows UINT32_MAX would have
89 vcip->bp_radius = UINT32_MAX;
90 vcip->cm_radius = -1.0;
91 vcip->min_r2 = 2.0;
92 vcip->flags = kfVcor0;
93 }
94
95 void CleanupVcor(VcorInfo* vcip) {
96 free_cond(vcip->ld_snp_list_fname);
97 CleanupRangeList(&(vcip->ld_snp_range_list));
98 }
99
100 void StripUnplacedNoCount(const ChrInfo* cip, uintptr_t* variant_include) {
101 if (IsSet(cip->chr_mask, 0)) {
102 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[0];
103 const uint32_t start_uidx = cip->chr_fo_vidx_start[chr_fo_idx];
104 ClearBitsNz(start_uidx, cip->chr_fo_vidx_start[chr_fo_idx + 1], variant_include);
105 }
106 if (cip->zero_extra_chrs) {
107 const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
108 for (uint32_t chr_idx = cip->max_code + 1; chr_idx != chr_code_end; ++chr_idx) {
109 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_idx];
110 const uint32_t start_uidx = cip->chr_fo_vidx_start[chr_fo_idx];
111 ClearBitsNz(start_uidx, cip->chr_fo_vidx_start[chr_fo_idx + 1], variant_include);
112 }
113 }
114 }
115
116 // Move to plink2_common if any users outside plink2_ld.
117 BoolErr StripUnplaced(const uintptr_t* orig_variant_include, const ChrInfo* cip, uint32_t raw_variant_ct, uint32_t* skipped_variant_ctp, uintptr_t** new_variant_includep) {
118 uint32_t skipped_variant_ct = 0;
119 if (IsSet(cip->chr_mask, 0)) {
120 skipped_variant_ct = CountChrVariantsUnsafe(orig_variant_include, cip, 0);
121 }
122 const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
123 if (cip->zero_extra_chrs) {
124 for (uint32_t chr_idx = cip->max_code + 1; chr_idx != chr_code_end; ++chr_idx) {
125 if (IsSet(cip->chr_mask, chr_idx)) {
126 skipped_variant_ct += CountChrVariantsUnsafe(orig_variant_include, cip, cip->chr_idx_to_foidx[chr_idx]);
127 }
128 }
129 }
130 *skipped_variant_ctp = skipped_variant_ct;
131 if (!skipped_variant_ct) {
132 *new_variant_includep = nullptr;
133 return 0;
134 }
135 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
136 if (unlikely(bigstack_alloc_w(raw_variant_ctl, new_variant_includep))) {
137 return 1;
138 }
139 uintptr_t* new_variant_include = *new_variant_includep;
140 memcpy(new_variant_include, orig_variant_include, raw_variant_ctl * sizeof(intptr_t));
141 StripUnplacedNoCount(cip, new_variant_include);
142 return 0;
143 }
144
145 static inline const uintptr_t* StripUnplacedK(const uintptr_t* orig_variant_include, const ChrInfo* cip, uint32_t raw_variant_ct, uint32_t* skipped_variant_ctp) {
146 uintptr_t* new_variant_include;
147 if (unlikely(StripUnplaced(orig_variant_include, cip, raw_variant_ct, skipped_variant_ctp, &new_variant_include))) {
148 return nullptr;
149 }
150 return new_variant_include? new_variant_include : orig_variant_include;
151 }
152
153 // Returns number of skipped variants.
154 uint32_t StripUnplacedMut(const ChrInfo* cip, uintptr_t* variant_include) {
155 uint32_t skipped_variant_ct = 0;
156 if (IsSet(cip->chr_mask, 0)) {
157 skipped_variant_ct = CountChrVariantsUnsafe(variant_include, cip, 0);
158 }
159 const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct;
160 if (cip->zero_extra_chrs) {
161 for (uint32_t chr_idx = cip->max_code + 1; chr_idx != chr_code_end; ++chr_idx) {
162 if (IsSet(cip->chr_mask, chr_idx)) {
163 // bugfix (15 Jan 2025): passed wrong last parameter
164 skipped_variant_ct += CountChrVariantsUnsafe(variant_include, cip, chr_idx);
165 }
166 }
167 }
168 if (!skipped_variant_ct) {
169 return 0;
170 }
171 StripUnplacedNoCount(cip, variant_include);
172 return skipped_variant_ct;
173 }
174
175
176 #ifdef USE_AVX2
177 // todo: see if either approach in avx_jaccard_index.c in
178 // github.com/CountOnes/hamming_weight helps here.
179
180 static inline int32_t DotprodAvx2(const VecW* __restrict hom1_iter, const VecW* __restrict ref2het1_iter, const VecW* __restrict hom2_iter, const VecW* __restrict ref2het2_iter, uintptr_t vec_ct) {
181 // popcount(hom1 & hom2) - 2 * popcount(hom1 & hom2 & (ref2het1 ^ ref2het2))
182 // ct must be a multiple of 4.
183 VecW cnt = vecw_setzero();
184 VecW ones_both = vecw_setzero();
185 VecW ones_neg = vecw_setzero();
186 VecW twos_both = vecw_setzero();
187 VecW twos_neg = vecw_setzero();
188 for (uintptr_t vec_idx = 0; vec_idx < vec_ct; vec_idx += 4) {
189 VecW count1_both = hom1_iter[vec_idx] & hom2_iter[vec_idx];
190 VecW cur_xor = ref2het1_iter[vec_idx] ^ ref2het2_iter[vec_idx];
191 VecW count1_neg = count1_both & cur_xor;
192
193 VecW count2_both = hom1_iter[vec_idx + 1] & hom2_iter[vec_idx + 1];
194 cur_xor = ref2het1_iter[vec_idx + 1] ^ ref2het2_iter[vec_idx + 1];
195 VecW count2_neg = count2_both & cur_xor;
196 const VecW twos_both_a = Csa256(count1_both, count2_both, &ones_both);
197 const VecW twos_neg_a = Csa256(count1_neg, count2_neg, &ones_neg);
198
199 count1_both = hom1_iter[vec_idx + 2] & hom2_iter[vec_idx + 2];
200 cur_xor = ref2het1_iter[vec_idx + 2] ^ ref2het2_iter[vec_idx + 2];
201 count1_neg = count1_both & cur_xor;
202
203 count2_both = hom1_iter[vec_idx + 3] & hom2_iter[vec_idx + 3];
204 cur_xor = ref2het1_iter[vec_idx + 3] ^ ref2het2_iter[vec_idx + 3];
205 count2_neg = count2_both & cur_xor;
206 const VecW twos_both_b = Csa256(count1_both, count2_both, &ones_both);
207 const VecW twos_neg_b = Csa256(count1_neg, count2_neg, &ones_neg);
208 const VecW fours_both = Csa256(twos_both_a, twos_both_b, &twos_both);
209 const VecW fours_neg = Csa256(twos_neg_a, twos_neg_b, &twos_neg);
210 // tried continuing to eights, not worth it
211 // deliberate unsigned-int64 overflow here
212 cnt = cnt + PopcountVecAvx2(fours_both) - vecw_slli(PopcountVecAvx2(fours_neg), 1);
213 }
214 cnt = cnt - PopcountVecAvx2(twos_neg);
215 cnt = vecw_slli(cnt, 2);
216 const VecW twos_sum = PopcountVecAvx2(twos_both) - PopcountVecAvx2(ones_neg);
217 cnt = cnt + vecw_slli(twos_sum, 1);
218 cnt = cnt + PopcountVecAvx2(ones_both);
219 return HsumW(cnt);
220 }
221
222 int32_t DotprodWords(const uintptr_t* __restrict hom1, const uintptr_t* __restrict ref2het1, const uintptr_t* __restrict hom2, const uintptr_t* __restrict ref2het2, uintptr_t word_ct) {
223 int32_t tot_both = 0;
224 uint32_t widx = 0;
225 if (word_ct >= 16) { // this already pays off with a single block
226 const uintptr_t block_ct = word_ct / (kWordsPerVec * 4);
227 tot_both = DotprodAvx2(R_CAST(const VecW*, hom1), R_CAST(const VecW*, ref2het1), R_CAST(const VecW*, hom2), R_CAST(const VecW*, ref2het2), block_ct * 4);
228 widx = block_ct * (4 * kWordsPerVec);
229 }
230 uint32_t tot_neg = 0;
231 for (; widx != word_ct; ++widx) {
232 const uintptr_t hom_word = hom1[widx] & hom2[widx];
233 const uintptr_t xor_word = ref2het1[widx] ^ ref2het2[widx];
234 tot_both += PopcountWord(hom_word);
235 tot_neg += PopcountWord(hom_word & xor_word);
236 }
237 return tot_both - 2 * tot_neg;
238 }
239
240 static inline void SumSsqAvx2(const VecW* __restrict hom1_iter, const VecW* __restrict ref2het1_iter, const VecW* __restrict hom2_iter, const VecW* __restrict ref2het2_iter, uintptr_t vec_ct, uint32_t* __restrict ssq2_ptr, uint32_t* __restrict plus2_ptr) {
241 // popcounts (nm1 & hom2) and (nm1 & hom2 & ref2het2). ct is multiple of 8.
242 VecW cnt_ssq = vecw_setzero();
243 VecW cnt_plus = vecw_setzero();
244 VecW ones_ssq = vecw_setzero();
245 VecW ones_plus = vecw_setzero();
246 VecW twos_ssq = vecw_setzero();
247 VecW twos_plus = vecw_setzero();
248 VecW fours_ssq = vecw_setzero();
249 VecW fours_plus = vecw_setzero();
250 for (uintptr_t vec_idx = 0; vec_idx < vec_ct; vec_idx += 8) {
251 VecW count1_ssq = (hom1_iter[vec_idx] | ref2het1_iter[vec_idx]) & hom2_iter[vec_idx];
252 VecW count1_plus = count1_ssq & ref2het2_iter[vec_idx];
253
254 VecW count2_ssq = (hom1_iter[vec_idx + 1] | ref2het1_iter[vec_idx + 1]) & hom2_iter[vec_idx + 1];
255 VecW count2_plus = count2_ssq & ref2het2_iter[vec_idx + 1];
256 VecW twos_ssq_a = Csa256(count1_ssq, count2_ssq, &ones_ssq);
257 VecW twos_plus_a = Csa256(count1_plus, count2_plus, &ones_plus);
258
259 count1_ssq = (hom1_iter[vec_idx + 2] | ref2het1_iter[vec_idx + 2]) & hom2_iter[vec_idx + 2];
260 count1_plus = count1_ssq & ref2het2_iter[vec_idx + 2];
261
262 count2_ssq = (hom1_iter[vec_idx + 3] | ref2het1_iter[vec_idx + 3]) & hom2_iter[vec_idx + 3];
263 count2_plus = count2_ssq & ref2het2_iter[vec_idx + 3];
264 VecW twos_ssq_b = Csa256(count1_ssq, count2_ssq, &ones_ssq);
265 VecW twos_plus_b = Csa256(count1_plus, count2_plus, &ones_plus);
266 const VecW fours_ssq_a = Csa256(twos_ssq_a, twos_ssq_b, &twos_ssq);
267 const VecW fours_plus_a = Csa256(twos_plus_a, twos_plus_b, &twos_plus);
268
269 count1_ssq = (hom1_iter[vec_idx + 4] | ref2het1_iter[vec_idx + 4]) & hom2_iter[vec_idx + 4];
270 count1_plus = count1_ssq & ref2het2_iter[vec_idx + 4];
271
272 count2_ssq = (hom1_iter[vec_idx + 5] | ref2het1_iter[vec_idx + 5]) & hom2_iter[vec_idx + 5];
273 count2_plus = count2_ssq & ref2het2_iter[vec_idx + 5];
274 twos_ssq_a = Csa256(count1_ssq, count2_ssq, &ones_ssq);
275 twos_plus_a = Csa256(count1_plus, count2_plus, &ones_plus);
276
277 count1_ssq = (hom1_iter[vec_idx + 6] | ref2het1_iter[vec_idx + 6]) & hom2_iter[vec_idx + 6];
278 count1_plus = count1_ssq & ref2het2_iter[vec_idx + 6];
279
280 count2_ssq = (hom1_iter[vec_idx + 7] | ref2het1_iter[vec_idx + 7]) & hom2_iter[vec_idx + 7];
281 count2_plus = count2_ssq & ref2het2_iter[vec_idx + 7];
282 twos_ssq_b = Csa256(count1_ssq, count2_ssq, &ones_ssq);
283 twos_plus_b = Csa256(count1_plus, count2_plus, &ones_plus);
284 const VecW fours_ssq_b = Csa256(twos_ssq_a, twos_ssq_b, &twos_ssq);
285 const VecW fours_plus_b = Csa256(twos_plus_a, twos_plus_b, &twos_plus);
286 const VecW eights_ssq = Csa256(fours_ssq_a, fours_ssq_b, &fours_ssq);
287 const VecW eights_plus = Csa256(fours_plus_a, fours_plus_b, &fours_plus);
288 // negligible benefit from going to sixteens here
289 cnt_ssq = cnt_ssq + PopcountVecAvx2(eights_ssq);
290 cnt_plus = cnt_plus + PopcountVecAvx2(eights_plus);
291 }
292 cnt_ssq = vecw_slli(cnt_ssq, 3);
293 cnt_plus = vecw_slli(cnt_plus, 3);
294 cnt_ssq = cnt_ssq + vecw_slli(PopcountVecAvx2(fours_ssq), 2);
295 cnt_plus = cnt_plus + vecw_slli(PopcountVecAvx2(fours_plus), 2);
296 cnt_ssq = cnt_ssq + vecw_slli(PopcountVecAvx2(twos_ssq), 1);
297 cnt_plus = cnt_plus + vecw_slli(PopcountVecAvx2(twos_plus), 1);
298 cnt_ssq = cnt_ssq + PopcountVecAvx2(ones_ssq);
299 cnt_plus = cnt_plus + PopcountVecAvx2(ones_plus);
300 *ssq2_ptr = HsumW(cnt_ssq);
301 *plus2_ptr = HsumW(cnt_plus);
302 }
303
304 void SumSsqWords(const uintptr_t* hom1, const uintptr_t* ref2het1, const uintptr_t* hom2, const uintptr_t* ref2het2, uint32_t word_ct, int32_t* sum2_ptr, uint32_t* ssq2_ptr) {
305 uint32_t ssq2 = 0;
306 uint32_t plus2 = 0;
307 uint32_t widx = 0;
308 // this has high constant overhead at the end; may want to require more than
309 // one block?
310 if (word_ct >= 32) {
311 const uintptr_t block_ct = word_ct / (8 * kWordsPerVec);
312 SumSsqAvx2(R_CAST(const VecW*, hom1), R_CAST(const VecW*, ref2het1), R_CAST(const VecW*, hom2), R_CAST(const VecW*, ref2het2), block_ct * 8, &ssq2, &plus2);
313 widx = block_ct * (8 * kWordsPerVec);
314 }
315 for (; widx != word_ct; ++widx) {
316 const uintptr_t ssq2_word = (hom1[widx] | ref2het1[widx]) & hom2[widx];
317 ssq2 += PopcountWord(ssq2_word);
318 plus2 += PopcountWord(ssq2_word & ref2het2[widx]);
319 }
320 *sum2_ptr = S_CAST(int32_t, 2 * plus2 - ssq2); // deliberate overflow
321 *ssq2_ptr = ssq2;
322 }
323 #else // !USE_AVX2
324 static inline int32_t DotprodVecsNm(const VecW* __restrict hom1_iter, const VecW* __restrict ref2het1_iter, const VecW* __restrict hom2_iter, const VecW* __restrict ref2het2_iter, uintptr_t vec_ct) {
325 // popcount(hom1 & hom2) - 2 * popcount(hom1 & hom2 & (ref2het1 ^ ref2het2))
326 // ct must be a multiple of 3.
327 assert(!(vec_ct % 3));
328 const VecW m1 = VCONST_W(kMask5555);
329 const VecW m2 = VCONST_W(kMask3333);
330 const VecW m4 = VCONST_W(kMask0F0F);
331 VecW acc_both = vecw_setzero();
332 VecW acc_neg = vecw_setzero();
333 uintptr_t cur_incr = 30;
334 for (; ; vec_ct -= cur_incr) {
335 if (vec_ct < 30) {
336 if (!vec_ct) {
337 return HsumW(acc_both) - 2 * HsumW(acc_neg);
338 }
339 cur_incr = vec_ct;
340 }
341 VecW inner_acc_both = vecw_setzero();
342 VecW inner_acc_neg = vecw_setzero();
343 const VecW* hom1_stop = &(hom1_iter[cur_incr]);
344 do {
345 VecW count1_both = (*hom1_iter++) & (*hom2_iter++);
346 VecW cur_xor = (*ref2het1_iter++) ^ (*ref2het2_iter++);
347 VecW count1_neg = count1_both & cur_xor;
348
349 VecW count2_both = (*hom1_iter++) & (*hom2_iter++);
350 cur_xor = (*ref2het1_iter++) ^ (*ref2het2_iter++);
351 VecW count2_neg = count2_both & cur_xor;
352
353 VecW cur_hom = (*hom1_iter++) & (*hom2_iter++);
354 cur_xor = (*ref2het1_iter++) ^ (*ref2het2_iter++);
355 VecW half1_neg = cur_hom & cur_xor;
356 const VecW half2_both = vecw_srli(cur_hom, 1) & m1;
357 const VecW half2_neg = vecw_srli(half1_neg, 1) & m1;
358 const VecW half1_both = cur_hom & m1;
359 half1_neg = half1_neg & m1;
360 count1_both = count1_both - (vecw_srli(count1_both, 1) & m1);
361 count1_neg = count1_neg - (vecw_srli(count1_neg, 1) & m1);
362 count2_both = count2_both - (vecw_srli(count2_both, 1) & m1);
363 count2_neg = count2_neg - (vecw_srli(count2_neg, 1) & m1);
364 count1_both = count1_both + half1_both;
365 count1_neg = count1_neg + half1_neg;
366 count2_both = count2_both + half2_both;
367 count2_neg = count2_neg + half2_neg;
368 count1_both = (count1_both & m2) + (vecw_srli(count1_both, 2) & m2);
369 count1_neg = (count1_neg & m2) + (vecw_srli(count1_neg, 2) & m2);
370 count1_both = count1_both + (count2_both & m2) + (vecw_srli(count2_both, 2) & m2);
371 count1_neg = count1_neg + (count2_neg & m2) + (vecw_srli(count2_neg, 2) & m2);
372 inner_acc_both = inner_acc_both + (count1_both & m4) + (vecw_srli(count1_both, 4) & m4);
373 inner_acc_neg = inner_acc_neg + (count1_neg & m4) + (vecw_srli(count1_neg, 4) & m4);
374 } while (hom1_iter < hom1_stop);
375 const VecW m0 = vecw_setzero();
376 acc_both = acc_both + vecw_bytesum(inner_acc_both, m0);
377 acc_neg = acc_neg + vecw_bytesum(inner_acc_neg, m0);
378 }
379 }
380
381 int32_t DotprodWords(const uintptr_t* __restrict hom1, const uintptr_t* __restrict ref2het1, const uintptr_t* __restrict hom2, const uintptr_t* __restrict ref2het2, uintptr_t word_ct) {
382 int32_t tot_both = 0;
383 uint32_t widx = 0;
384 if (word_ct >= kWordsPerVec * 3) {
385 const uintptr_t block_ct = word_ct / (kWordsPerVec * 3);
386 tot_both = DotprodVecsNm(R_CAST(const VecW*, hom1), R_CAST(const VecW*, ref2het1), R_CAST(const VecW*, hom2), R_CAST(const VecW*, ref2het2), block_ct * 3);
387 widx = block_ct * (3 * kWordsPerVec);
388 }
389 uint32_t tot_neg = 0;
390 for (; widx != word_ct; ++widx) {
391 const uintptr_t hom_word = hom1[widx] & hom2[widx];
392 const uintptr_t xor_word = ref2het1[widx] ^ ref2het2[widx];
393 tot_both += PopcountWord(hom_word);
394 tot_neg += PopcountWord(hom_word & xor_word);
395 }
396 return tot_both - 2 * tot_neg;
397 }
398
399 #ifndef USE_SSE42
400 static inline void SumSsqVecs(const VecW* __restrict hom1_iter, const VecW* __restrict ref2het1_iter, const VecW* __restrict hom2_iter, const VecW* __restrict ref2het2_iter, uintptr_t vec_ct, uint32_t* __restrict ssq2_ptr, uint32_t* __restrict plus2_ptr) {
401 // popcounts (nm1 & hom2) and (nm1 & hom2 & ref2het2). ct is multiple of 3.
402 assert(!(vec_ct % 3));
403 const VecW m1 = VCONST_W(kMask5555);
404 const VecW m2 = VCONST_W(kMask3333);
405 const VecW m4 = VCONST_W(kMask0F0F);
406 VecW acc_ssq2 = vecw_setzero();
407 VecW acc_plus2 = vecw_setzero();
408 uint32_t cur_incr = 30;
409 for (; ; vec_ct -= cur_incr) {
410 if (vec_ct < 30) {
411 if (!vec_ct) {
412 *ssq2_ptr = HsumW(acc_ssq2);
413 *plus2_ptr = HsumW(acc_plus2);
414 return;
415 }
416 cur_incr = vec_ct;
417 }
418 VecW inner_acc_ssq = vecw_setzero();
419 VecW inner_acc_plus = vecw_setzero();
420 for (uint32_t vec_idx = 0; vec_idx < cur_incr; vec_idx += 3) {
421 VecW count1_ssq = (hom1_iter[vec_idx] | ref2het1_iter[vec_idx]) & hom2_iter[vec_idx];
422 VecW count1_plus = count1_ssq & ref2het2_iter[vec_idx];
423
424 VecW count2_ssq = (hom1_iter[vec_idx + 1] | ref2het1_iter[vec_idx + 1]) & hom2_iter[vec_idx + 1];
425 VecW count2_plus = count2_ssq & ref2het2_iter[vec_idx + 1];
426
427 VecW half1_ssq = (hom1_iter[vec_idx + 2] | ref2het1_iter[vec_idx + 2]) & hom2_iter[vec_idx + 2];
428 VecW half1_plus = half1_ssq & ref2het2_iter[vec_idx + 2];
429 VecW half2_ssq = vecw_srli(half1_ssq, 1) & m1;
430 VecW half2_plus = vecw_srli(half1_plus, 1) & m1;
431 half1_ssq = half1_ssq & m1;
432 half1_plus = half1_plus & m1;
433 count1_ssq = count1_ssq - (vecw_srli(count1_ssq, 1) & m1);
434 count1_plus = count1_plus - (vecw_srli(count1_plus, 1) & m1);
435 count2_ssq = count2_ssq - (vecw_srli(count2_ssq, 1) & m1);
436 count2_plus = count2_plus - (vecw_srli(count2_plus, 1) & m1);
437 count1_ssq = count1_ssq + half1_ssq;
438 count1_plus = count1_plus + half1_plus;
439 count2_ssq = count2_ssq + half2_ssq;
440 count2_plus = count2_plus + half2_plus;
441 count1_ssq = (count1_ssq & m2) + (vecw_srli(count1_ssq, 2) & m2);
442 count1_plus = (count1_plus & m2) + (vecw_srli(count1_plus, 2) & m2);
443 count1_ssq = count1_ssq + (count2_ssq & m2) + (vecw_srli(count2_ssq, 2) & m2);
444 count1_plus = count1_plus + (count2_plus & m2) + (vecw_srli(count2_plus, 2) & m2);
445 inner_acc_ssq = inner_acc_ssq + (count1_ssq & m4) + (vecw_srli(count1_ssq, 4) & m4);
446 inner_acc_plus = inner_acc_plus + (count1_plus & m4) + (vecw_srli(count1_plus, 4) & m4);
447 }
448 hom1_iter = &(hom1_iter[cur_incr]);
449 ref2het1_iter = &(ref2het1_iter[cur_incr]);
450 hom2_iter = &(hom2_iter[cur_incr]);
451 ref2het2_iter = &(ref2het2_iter[cur_incr]);
452 const VecW m0 = vecw_setzero();
453 acc_ssq2 = acc_ssq2 + vecw_bytesum(inner_acc_ssq, m0);
454 acc_plus2 = acc_plus2 + vecw_bytesum(inner_acc_plus, m0);
455 }
456 }
457 #endif
458
459 void SumSsqWords(const uintptr_t* hom1, const uintptr_t* ref2het1, const uintptr_t* hom2, const uintptr_t* ref2het2, uint32_t word_ct, int32_t* sum2_ptr, uint32_t* ssq2_ptr) {
460 uint32_t ssq2 = 0;
461 uint32_t plus2 = 0;
462 uint32_t widx = 0;
463 #ifndef USE_SSE42
464 if (word_ct >= kWordsPerVec * 3) {
465 const uintptr_t block_ct = word_ct / (kWordsPerVec * 3);
466 SumSsqVecs(R_CAST(const VecW*, hom1), R_CAST(const VecW*, ref2het1), R_CAST(const VecW*, hom2), R_CAST(const VecW*, ref2het2), block_ct * 3, &ssq2, &plus2);
467 widx = block_ct * (3 * kWordsPerVec);
468 }
469 #endif
470 for (; widx != word_ct; ++widx) {
471 const uintptr_t ssq2_word = (hom1[widx] | ref2het1[widx]) & hom2[widx];
472 ssq2 += PopcountWord(ssq2_word);
473 plus2 += PopcountWord(ssq2_word & ref2het2[widx]);
474 }
475 *sum2_ptr = S_CAST(int32_t, 2 * plus2 - ssq2); // deliberate overflow
476 *ssq2_ptr = ssq2;
477 }
478 #endif // !USE_AVX2
479
480 #if defined(USE_AVX2) || !defined(USE_SSE42)
481 static inline void SumSsqNmVecs(const VecW* __restrict hom1_iter, const VecW* __restrict ref2het1_iter, const VecW* __restrict hom2_iter, const VecW* __restrict ref2het2_iter, uintptr_t vec_ct, uint32_t* __restrict nm_ptr, uint32_t* __restrict ssq2_ptr, uint32_t* __restrict plus2_ptr) {
482 // vec_ct must be a multiple of 3.
483 assert(!(vec_ct % 3));
484 const VecW m1 = VCONST_W(kMask5555);
485 const VecW m2 = VCONST_W(kMask3333);
486 const VecW m4 = VCONST_W(kMask0F0F);
487 VecW acc_nm = vecw_setzero();
488 VecW acc_ssq2 = vecw_setzero();
489 VecW acc_plus2 = vecw_setzero();
490 uint32_t cur_incr = 30;
491 for (; ; vec_ct -= cur_incr) {
492 if (vec_ct < 30) {
493 if (!vec_ct) {
494 *nm_ptr = HsumW(acc_nm);
495 *ssq2_ptr = HsumW(acc_ssq2);
496 *plus2_ptr = HsumW(acc_plus2);
497 return;
498 }
499 cur_incr = vec_ct;
500 }
501 VecW inner_acc_nm = vecw_setzero();
502 VecW inner_acc_ssq = vecw_setzero();
503 VecW inner_acc_plus = vecw_setzero();
504 for (uint32_t vec_idx = 0; vec_idx < cur_incr; vec_idx += 3) {
505 VecW nm1 = hom1_iter[vec_idx] | ref2het1_iter[vec_idx];
506 VecW hom2 = hom2_iter[vec_idx];
507 VecW ref2het2 = ref2het2_iter[vec_idx];
508 VecW count1_ssq = nm1 & hom2;
509 VecW count1_nm = nm1 & (hom2 | ref2het2);
510 VecW count1_plus = count1_ssq & ref2het2;
511
512 nm1 = hom1_iter[vec_idx + 1] | ref2het1_iter[vec_idx + 1];
513 hom2 = hom2_iter[vec_idx + 1];
514 ref2het2 = ref2het2_iter[vec_idx + 1];
515 VecW count2_ssq = nm1 & hom2;
516 VecW count2_nm = nm1 & (hom2 | ref2het2);
517 VecW count2_plus = count2_ssq & ref2het2;
518
519 nm1 = hom1_iter[vec_idx + 2] | ref2het1_iter[vec_idx + 2];
520 hom2 = hom2_iter[vec_idx + 2];
521 ref2het2 = ref2het2_iter[vec_idx + 2];
522 VecW half_a_ssq = nm1 & hom2;
523 VecW half_a_nm = nm1 & (hom2 | ref2het2);
524 VecW half_a_plus = half_a_ssq & ref2het2;
525 const VecW half_b_ssq = vecw_srli(half_a_ssq, 1) & m1;
526 const VecW half_b_nm = vecw_srli(half_a_nm, 1) & m1;
527 const VecW half_b_plus = vecw_srli(half_a_plus, 1) & m1;
528 half_a_ssq = half_a_ssq & m1;
529 half_a_nm = half_a_nm & m1;
530 half_a_plus = half_a_plus & m1;
531 count1_ssq = count1_ssq - (vecw_srli(count1_ssq, 1) & m1);
532 count1_nm = count1_nm - (vecw_srli(count1_nm, 1) & m1);
533 count1_plus = count1_plus - (vecw_srli(count1_plus, 1) & m1);
534 count2_ssq = count2_ssq - (vecw_srli(count2_ssq, 1) & m1);
535 count2_nm = count2_nm - (vecw_srli(count2_nm, 1) & m1);
536 count2_plus = count2_plus - (vecw_srli(count2_plus, 1) & m1);
537 count1_ssq = count1_ssq + half_a_ssq;
538 count1_nm = count1_nm + half_a_nm;
539 count1_plus = count1_plus + half_a_plus;
540 count2_ssq = count2_ssq + half_b_ssq;
541 count2_nm = count2_nm + half_b_nm;
542 count2_plus = count2_plus + half_b_plus;
543 count1_ssq = (count1_ssq & m2) + (vecw_srli(count1_ssq, 2) & m2);
544 count1_nm = (count1_nm & m2) + (vecw_srli(count1_nm, 2) & m2);
545 count1_plus = (count1_plus & m2) + (vecw_srli(count1_plus, 2) & m2);
546 count1_ssq = count1_ssq + (count2_ssq & m2) + (vecw_srli(count2_ssq, 2) & m2);
547 count1_nm = count1_nm + (count2_nm & m2) + (vecw_srli(count2_nm, 2) & m2);
548 count1_plus = count1_plus + (count2_plus & m2) + (vecw_srli(count2_plus, 2) & m2);
549 inner_acc_nm = inner_acc_nm + (count1_nm & m4) + (vecw_srli(count1_nm, 4) & m4);
550 inner_acc_ssq = inner_acc_ssq + (count1_ssq & m4) + (vecw_srli(count1_ssq, 4) & m4);
551 inner_acc_plus = inner_acc_plus + (count1_plus & m4) + (vecw_srli(count1_plus, 4) & m4);
552 }
553 hom1_iter = &(hom1_iter[cur_incr]);
554 ref2het1_iter = &(ref2het1_iter[cur_incr]);
555 hom2_iter = &(hom2_iter[cur_incr]);
556 ref2het2_iter = &(ref2het2_iter[cur_incr]);
557 const VecW m0 = vecw_setzero();
558 acc_nm = acc_nm + vecw_bytesum(inner_acc_nm, m0);
559 acc_ssq2 = acc_ssq2 + vecw_bytesum(inner_acc_ssq, m0);
560 acc_plus2 = acc_plus2 + vecw_bytesum(inner_acc_plus, m0);
561 }
562 }
563 #endif // __LP64__
564
565 void SumSsqNmWords(const uintptr_t* hom1, const uintptr_t* ref2het1, const uintptr_t* hom2, const uintptr_t* ref2het2, uint32_t word_ct, uint32_t* __restrict nm_ptr, int32_t* sum2_ptr, uint32_t* __restrict ssq2_ptr) {
566 uint32_t nm = 0;
567 uint32_t ssq2 = 0;
568 uint32_t plus2 = 0;
569 uint32_t widx = 0;
570 #if defined(USE_AVX2) || !defined(USE_SSE42)
571 if (word_ct >= 3 * kWordsPerVec) {
572 const uintptr_t block_ct = word_ct / (3 * kWordsPerVec);
573 SumSsqNmVecs(R_CAST(const VecW*, hom1), R_CAST(const VecW*, ref2het1), R_CAST(const VecW*, hom2), R_CAST(const VecW*, ref2het2), block_ct * 3, &nm, &ssq2, &plus2);
574 widx = block_ct * (3 * kWordsPerVec);
575 }
576 #endif
577 for (; widx != word_ct; ++widx) {
578 const uintptr_t nm1_word = hom1[widx] | ref2het1[widx];
579 const uintptr_t hom2_word = hom2[widx];
580 const uintptr_t ref2het2_word = ref2het2[widx];
581 nm += PopcountWord(nm1_word & (hom2_word | ref2het2_word));
582 const uintptr_t ssq2_word = nm1_word & hom2_word;
583 ssq2 += PopcountWord(ssq2_word);
584 plus2 += PopcountWord(ssq2_word & ref2het2_word);
585 }
586 *nm_ptr = nm;
587 *sum2_ptr = S_CAST(int32_t, 2 * plus2 - ssq2); // deliberate overflow
588 *ssq2_ptr = ssq2;
589 }
590
591 // er, subcontig_info probably deserves its own type...
592 void LdPruneNextSubcontig(const uintptr_t* variant_include, const uint32_t* variant_bps, const uint32_t* subcontig_info, const uint32_t* subcontig_thread_assignments, uint32_t prune_window_size, uint32_t thread_idx, uint32_t* subcontig_idx_ptr, uint32_t* subcontig_end_tvidx_ptr, uint32_t* next_window_end_tvidx_ptr, uint32_t* variant_uidx_winstart_ptr, uint32_t* variant_uidx_winend_ptr) {
593 uint32_t subcontig_idx = *subcontig_idx_ptr;
594 do {
595 ++subcontig_idx;
596 } while (subcontig_thread_assignments[subcontig_idx] != thread_idx);
597 *subcontig_idx_ptr = subcontig_idx;
598 const uint32_t subcontig_first_tvidx = *subcontig_end_tvidx_ptr;
599 const uint32_t subcontig_len = subcontig_info[3 * subcontig_idx];
600 const uint32_t variant_uidx_winstart = subcontig_info[3 * subcontig_idx + 2];
601 const uint32_t subcontig_end_tvidx = subcontig_first_tvidx + subcontig_len;
602 *subcontig_end_tvidx_ptr = subcontig_end_tvidx;
603 if (variant_bps) {
604 const uint32_t variant_bp_thresh = variant_bps[variant_uidx_winstart] + prune_window_size;
605 uintptr_t variant_uidx_winend_base;
606 uintptr_t cur_bits;
607 BitIter1Start(variant_include, variant_uidx_winstart + 1, &variant_uidx_winend_base, &cur_bits);
608 uint32_t first_window_len = 1;
609 uint32_t variant_uidx_winend;
610 do {
611 variant_uidx_winend = BitIter1(variant_include, &variant_uidx_winend_base, &cur_bits);
612 } while ((variant_bps[variant_uidx_winend] <= variant_bp_thresh) && (++first_window_len < subcontig_len));
613 *next_window_end_tvidx_ptr = subcontig_first_tvidx + first_window_len;
614 *variant_uidx_winend_ptr = variant_uidx_winend;
615 } else {
616 *next_window_end_tvidx_ptr = subcontig_first_tvidx + MINV(subcontig_len, prune_window_size);
617 }
618
619 *variant_uidx_winstart_ptr = variant_uidx_winstart;
620 }
621
622 void LdPruneNextWindow(const uintptr_t* __restrict variant_include, const uint32_t* __restrict variant_bps, const uint32_t* __restrict tvidxs, const uintptr_t* __restrict cur_window_removed, uint32_t prune_window_size, uint32_t window_incr, uint32_t window_maxl, uint32_t subcontig_end_tvidx, uint32_t* cur_window_size_ptr, uint32_t* __restrict window_start_tvidx_ptr, uint32_t* __restrict variant_uidx_winstart_ptr, uint32_t* __restrict next_window_end_tvidx_ptr, uint32_t* __restrict variant_uidx_winend_ptr, uintptr_t* __restrict occupied_window_slots, uint32_t* winpos_to_slot_idx) {
623 uint32_t next_window_end_tvidx = *next_window_end_tvidx_ptr;
624 if (next_window_end_tvidx == subcontig_end_tvidx) {
625 // just completed last window in subcontig
626 *cur_window_size_ptr = 0;
627 *window_start_tvidx_ptr = subcontig_end_tvidx;
628 ZeroWArr(window_maxl, occupied_window_slots);
629 return;
630 }
631 uint32_t next_window_start_tvidx = *window_start_tvidx_ptr;
632 if (variant_bps) {
633 // this is guaranteed to be nonnegative
634 uintptr_t variant_uidx_base;
635 uintptr_t cur_bits;
636 BitIter1Start(variant_include, *variant_uidx_winstart_ptr + 1, &variant_uidx_base, &cur_bits);
637 uint32_t variant_uidx_winend = *variant_uidx_winend_ptr;
638 const uint32_t window_start_min_bp = variant_bps[variant_uidx_winend] - prune_window_size;
639 uint32_t window_start_bp;
640 uint32_t variant_uidx_winstart;
641 do {
642 // advance window start by as much as necessary to make end advance by at
643 // least 1
644 ++next_window_start_tvidx;
645 variant_uidx_winstart = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
646 window_start_bp = variant_bps[variant_uidx_winstart];
647 } while (window_start_bp < window_start_min_bp);
648 // now advance window end as appropriate
649 const uint32_t window_end_thresh = window_start_bp + prune_window_size;
650 BitIter1Start(variant_include, variant_uidx_winend + 1, &variant_uidx_base, &cur_bits);
651 do {
652 if (++next_window_end_tvidx == subcontig_end_tvidx) {
653 break;
654 }
655 variant_uidx_winend = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
656 } while (variant_bps[variant_uidx_winend] <= window_end_thresh);
657 *variant_uidx_winstart_ptr = variant_uidx_winstart;
658 *variant_uidx_winend_ptr = variant_uidx_winend;
659 } else {
660 next_window_start_tvidx += window_incr;
661 next_window_end_tvidx = MINV(next_window_start_tvidx + prune_window_size, subcontig_end_tvidx);
662 }
663 const uint32_t cur_window_size = *cur_window_size_ptr;
664 uint32_t winpos_write = 0;
665 for (uint32_t winpos_read = 0; winpos_read != cur_window_size; ++winpos_read) {
666 const uint32_t slot_idx = winpos_to_slot_idx[winpos_read];
667 if (IsSet(cur_window_removed, winpos_read) || (tvidxs[slot_idx] < next_window_start_tvidx)) {
668 ClearBit(slot_idx, occupied_window_slots);
669 } else {
670 winpos_to_slot_idx[winpos_write++] = slot_idx;
671 }
672 }
673 *cur_window_size_ptr = winpos_write;
674 *window_start_tvidx_ptr = next_window_start_tvidx;
675 *next_window_end_tvidx_ptr = next_window_end_tvidx;
676 }
677
678 typedef struct VariantAggsStruct {
679 uint32_t nm_ct;
680 int32_t sum;
681 uint32_t ssq;
682 } VariantAggs;
683
684 // On entry, {cur_nm_ct, cur_first_sum, cur_first_ssq} must be initialized to
685 // first_vaggs values.
686 void ComputeIndepPairwiseR2Components(const uintptr_t* __restrict first_genobufs, const uintptr_t* __restrict second_genobufs, const VariantAggs* second_vaggs, uint32_t founder_ct, uint32_t* cur_nm_ct_ptr, int32_t* cur_first_sum_ptr, uint32_t* cur_first_ssq_ptr, int32_t* second_sum_ptr, uint32_t* second_ssq_ptr, int32_t* cur_dotprod_ptr) {
687 const uint32_t founder_ctaw = BitCtToAlignedWordCt(founder_ct);
688 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
689 // Three cases:
690 // 1. Just need dot product.
691 // 2. Also need {first_sum, first_ssq} xor {second_sum, second_ssq}.
692 // 3. Need all six variables.
693 *cur_dotprod_ptr = DotprodWords(first_genobufs, &(first_genobufs[founder_ctaw]), second_genobufs, &(second_genobufs[founder_ctaw]), founder_ctl);
694 if (*cur_nm_ct_ptr != founder_ct) {
695 SumSsqWords(first_genobufs, &(first_genobufs[founder_ctaw]), second_genobufs, &(second_genobufs[founder_ctaw]), founder_ctl, second_sum_ptr, second_ssq_ptr);
696 } else {
697 *second_sum_ptr = second_vaggs->sum;
698 *second_ssq_ptr = second_vaggs->ssq;
699 }
700 const uint32_t second_nm_ct = second_vaggs->nm_ct;
701 if (second_nm_ct == founder_ct) {
702 return;
703 }
704 if (*cur_nm_ct_ptr != founder_ct) {
705 SumSsqNmWords(second_genobufs, &(second_genobufs[founder_ctaw]), first_genobufs, &(first_genobufs[founder_ctaw]), founder_ctl, cur_nm_ct_ptr, cur_first_sum_ptr, cur_first_ssq_ptr);
706 } else {
707 SumSsqWords(second_genobufs, &(second_genobufs[founder_ctaw]), first_genobufs, &(first_genobufs[founder_ctaw]), founder_ctl, cur_first_sum_ptr, cur_first_ssq_ptr);
708 *cur_nm_ct_ptr = second_nm_ct;
709 }
710 }
711
712 void FillVaggs(const uintptr_t* hom_vec, const uintptr_t* ref2het_vec, uintptr_t word_ct, VariantAggs* vaggs, uint32_t* nm_ct_ptr, uint32_t* plusone_ct_ptr, uint32_t* minusone_ct_ptr) {
713 uint32_t hom_ct;
714 uint32_t ref2het_ct;
715 uint32_t ref2_ct;
716 PopcountWordsIntersect3val(hom_vec, ref2het_vec, word_ct, &hom_ct, &ref2het_ct, &ref2_ct);
717 const uint32_t alt2_ct = hom_ct - ref2_ct;
718 const uint32_t nm_ct = alt2_ct + ref2het_ct;
719 vaggs->nm_ct = nm_ct;
720 vaggs->sum = S_CAST(int32_t, ref2_ct - alt2_ct); // deliberate overflow
721 vaggs->ssq = hom_ct;
722 *nm_ct_ptr = nm_ct;
723 *plusone_ct_ptr = ref2_ct;
724 *minusone_ct_ptr = alt2_ct;
725 }
726
727 void IndepPairwiseUpdateSubcontig(uint32_t variant_uidx_winstart, uint32_t x_start, uint32_t x_len, uint32_t y_start, uint32_t y_len, uint32_t founder_ct, uint32_t founder_male_ct, uint32_t founder_nonfemale_ct, uint32_t* is_x_ptr, uint32_t* is_y_ptr, uint32_t* cur_founder_ct_ptr, uint32_t* cur_founder_ctaw_ptr, uint32_t* cur_founder_ctl_ptr, uintptr_t* entire_variant_buf_word_ct_ptr) {
728 // _len is better than _end here since we can exploit unsignedness
729 const uint32_t is_x = ((variant_uidx_winstart - x_start) < x_len);
730 const uint32_t is_y = ((variant_uidx_winstart - y_start) < y_len);
731 if ((is_x != (*is_x_ptr)) || (is_y != (*is_y_ptr))) {
732 *is_x_ptr = is_x;
733 *is_y_ptr = is_y;
734 uint32_t cur_founder_ct = founder_ct;
735 if (is_x) {
736 cur_founder_ct = founder_male_ct;
737 } else if (is_y) {
738 cur_founder_ct = founder_nonfemale_ct;
739 }
740 const uint32_t cur_founder_ctaw = BitCtToAlignedWordCt(cur_founder_ct);
741 *cur_founder_ct_ptr = cur_founder_ct;
742 *cur_founder_ctaw_ptr = cur_founder_ctaw;
743 *cur_founder_ctl_ptr = BitCtToWordCt(cur_founder_ct);
744 *entire_variant_buf_word_ct_ptr = 2 * cur_founder_ctaw;
745 if (is_x) {
746 *entire_variant_buf_word_ct_ptr += 2 * BitCtToAlignedWordCt(founder_ct - founder_male_ct);
747 }
748 }
749 }
750
751 typedef struct IndepPairwiseCtxStruct {
752 const uint32_t* subcontig_info;
753 const uint32_t* subcontig_thread_assignments;
754 const uintptr_t* variant_include;
755 const uintptr_t* allele_idx_offsets;
756 const AlleleCode* maj_alleles;
757 const double* all_allele_freqs;
758 const uint32_t* variant_bps;
759 const uintptr_t* preferred_variants;
760 uint32_t* tvidx_end;
761 uint32_t x_start;
762 uint32_t x_len;
763 uint32_t y_start;
764 uint32_t y_len;
765 uint32_t founder_ct;
766 uint32_t founder_male_ct;
767 uint32_t founder_nonfemale_ct;
768 uint32_t prune_window_size;
769 uint32_t window_maxl;
770 double prune_ld_thresh;
771 uint32_t window_incr;
772 uint32_t cur_batch_size;
773
774 uintptr_t** genobufs;
775 uintptr_t** occupied_window_slots;
776 uintptr_t** cur_window_removed;
777 double** cur_maj_freqs;
778 uintptr_t** removed_variants_write;
779 VariantAggs** vaggs;
780 VariantAggs** nonmale_vaggs;
781 uint32_t** winpos_to_slot_idx;
782 uint32_t** tvidxs;
783 uint32_t** first_unchecked_tvidx;
784 // 't' stands for thread here
785 uintptr_t** raw_tgenovecs[2];
786 } IndepPairwiseCtx;
787
788 THREAD_FUNC_DECL IndepPairwiseThread(void* raw_arg) {
789 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
790 const uintptr_t tidx = arg->tidx;
791 IndepPairwiseCtx* ctx = S_CAST(IndepPairwiseCtx*, arg->sharedp->context);
792
793 const uint32_t* subcontig_info = ctx->subcontig_info;
794 const uint32_t* subcontig_thread_assignments = ctx->subcontig_thread_assignments;
795 const uintptr_t* variant_include = ctx->variant_include;
796 const uintptr_t* preferred_variants = ctx->preferred_variants;
797 const uint32_t x_start = ctx->x_start;
798 const uint32_t x_len = ctx->x_len;
799 const uint32_t y_start = ctx->y_start;
800 const uint32_t y_len = ctx->y_len;
801 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
802 const AlleleCode* maj_alleles = ctx->maj_alleles;
803 const double* all_allele_freqs = ctx->all_allele_freqs;
804 const uint32_t* variant_bps = ctx->variant_bps;
805 const uint32_t founder_ct = ctx->founder_ct;
806 const uint32_t founder_male_ct = ctx->founder_male_ct;
807 const uint32_t founder_male_ctl2 = NypCtToWordCt(founder_male_ct);
808 const uint32_t founder_nonfemale_ct = ctx->founder_nonfemale_ct;
809 const uint32_t nonmale_ct = founder_ct - founder_male_ct;
810 const uint32_t nonmale_ctaw = BitCtToAlignedWordCt(nonmale_ct);
811 const uint32_t nonmale_ctl = BitCtToWordCt(nonmale_ct);
812 const uintptr_t raw_tgenovec_single_variant_word_ct = RoundUpPow2(NypCtToWordCt(nonmale_ct) + founder_male_ctl2, kWordsPerVec);
813 const uint32_t prune_window_size = ctx->prune_window_size;
814 const uint32_t window_maxl = ctx->window_maxl;
815 const double prune_ld_thresh = ctx->prune_ld_thresh;
816 const uint32_t window_incr = ctx->window_incr;
817 const uint32_t tvidx_end = ctx->tvidx_end[tidx];
818 uintptr_t* genobufs = ctx->genobufs[tidx];
819 uintptr_t* occupied_window_slots = ctx->occupied_window_slots[tidx];
820 uintptr_t* cur_window_removed = ctx->cur_window_removed[tidx];
821 uintptr_t* removed_variants_write = ctx->removed_variants_write[tidx];
822 double* cur_maj_freqs = ctx->cur_maj_freqs[tidx];
823 VariantAggs* vaggs = ctx->vaggs[tidx];
824 VariantAggs* nonmale_vaggs = ctx->nonmale_vaggs[tidx];
825 uint32_t* winpos_to_slot_idx = ctx->winpos_to_slot_idx[tidx];
826 uint32_t* tvidxs = ctx->tvidxs[tidx];
827 uint32_t* first_unchecked_tvidx = ctx->first_unchecked_tvidx? ctx->first_unchecked_tvidx[tidx] : nullptr;
828
829 uint32_t subcontig_end_tvidx = 0;
830 uint32_t subcontig_idx = UINT32_MAX; // deliberate overflow
831 uint32_t window_start_tvidx = 0;
832 uint32_t next_window_end_tvidx = 0;
833 uint32_t write_slot_idx = 0;
834 uint32_t is_x = 0;
835 uint32_t is_y = 0;
836 uint32_t cur_window_size = 0;
837 uint32_t winpos_split = 0;
838 uint32_t tvidx_start = 0;
839 uint32_t cur_founder_ct = founder_ct;
840 uint32_t cur_founder_ctaw = BitCtToAlignedWordCt(founder_ct);
841 uint32_t cur_founder_ctl = BitCtToWordCt(founder_ct);
842 uintptr_t variant_uidx_base = 0;
843 uintptr_t variant_include_bits = variant_include[0];
844 uint32_t variant_uidx_winstart = 0;
845 uint32_t variant_uidx_winend = 0;
846 uintptr_t entire_variant_buf_word_ct = 2 * cur_founder_ctaw;
847 uint32_t cur_allele_ct = 2;
848 uint32_t parity = 0;
849 do {
850 const uint32_t cur_batch_size = ctx->cur_batch_size;
851 const uint32_t tvidx_stop = MINV(tvidx_start + cur_batch_size, tvidx_end);
852 // main loop has to be variant-, not window-, based due to how datasets too
853 // large to fit in memory are handled: we may have to halt in the middle of
854 // unpacking data for a window, waiting until the current I/O pass is
855 // complete before proceeding
856 const uintptr_t* raw_tgenovecs = ctx->raw_tgenovecs[parity][tidx];
857 for (uint32_t cur_tvidx = tvidx_start; cur_tvidx < tvidx_stop; ) {
858 if (cur_tvidx == subcontig_end_tvidx) {
859 LdPruneNextSubcontig(variant_include, variant_bps, subcontig_info, subcontig_thread_assignments, prune_window_size, tidx, &subcontig_idx, &subcontig_end_tvidx, &next_window_end_tvidx, &variant_uidx_winstart, &variant_uidx_winend);
860 IndepPairwiseUpdateSubcontig(variant_uidx_winstart, x_start, x_len, y_start, y_len, founder_ct, founder_male_ct, founder_nonfemale_ct, &is_x, &is_y, &cur_founder_ct, &cur_founder_ctaw, &cur_founder_ctl, &entire_variant_buf_word_ct);
861 BitIter1Start(variant_include, variant_uidx_winstart, &variant_uidx_base, &variant_include_bits);
862 winpos_split = 0;
863 }
864 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
865 write_slot_idx = AdvTo0Bit(occupied_window_slots, write_slot_idx);
866 uintptr_t tvidx_offset = cur_tvidx - tvidx_start;
867 const uintptr_t* cur_raw_tgenovecs = &(raw_tgenovecs[tvidx_offset * raw_tgenovec_single_variant_word_ct]);
868 uintptr_t* cur_genobuf = &(genobufs[write_slot_idx * entire_variant_buf_word_ct]);
869 uintptr_t* cur_genobuf_ref2het = &(cur_genobuf[cur_founder_ctaw]);
870 // need local genobuf anyway due to halts, so may as well perform split
871 // here.
872 SplitHomRef2het(cur_raw_tgenovecs, cur_founder_ct, cur_genobuf, cur_genobuf_ref2het);
873 uint32_t nm_ct;
874 uint32_t plusone_ct;
875 uint32_t minusone_ct;
876 FillVaggs(cur_genobuf, cur_genobuf_ref2het, cur_founder_ctl, &(vaggs[write_slot_idx]), &nm_ct, &plusone_ct, &minusone_ct);
877 if (is_x) {
878 cur_genobuf = &(cur_genobuf[2 * cur_founder_ctaw]);
879 cur_genobuf_ref2het = &(cur_genobuf[nonmale_ctaw]);
880 SplitHomRef2het(&(cur_raw_tgenovecs[founder_male_ctl2]), nonmale_ct, cur_genobuf, cur_genobuf_ref2het);
881 uint32_t x_nonmale_nm_ct;
882 uint32_t x_nonmale_plusone_ct;
883 uint32_t x_nonmale_minusone_ct;
884 FillVaggs(cur_genobuf, cur_genobuf_ref2het, nonmale_ctl, &(nonmale_vaggs[write_slot_idx]), &x_nonmale_nm_ct, &x_nonmale_plusone_ct, &x_nonmale_minusone_ct);
885 nm_ct += 2 * x_nonmale_nm_ct;
886 plusone_ct += 2 * x_nonmale_plusone_ct;
887 minusone_ct += 2 * x_nonmale_minusone_ct;
888 }
889 if (((!plusone_ct) && (!minusone_ct)) || (plusone_ct == nm_ct) || (minusone_ct == nm_ct)) {
890 SetBit(cur_window_size, cur_window_removed);
891 SetBit(cur_tvidx, removed_variants_write);
892 } else {
893 tvidxs[write_slot_idx] = cur_tvidx;
894 uintptr_t allele_idx_base;
895 if (!allele_idx_offsets) {
896 allele_idx_base = variant_uidx;
897 } else {
898 allele_idx_base = allele_idx_offsets[variant_uidx];
899 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_base;
900 allele_idx_base -= variant_uidx;
901 }
902 cur_maj_freqs[write_slot_idx] = GetAlleleFreq(&(all_allele_freqs[allele_idx_base]), maj_alleles[variant_uidx], cur_allele_ct);
903 if (preferred_variants && IsSet(preferred_variants, variant_uidx)) {
904 cur_maj_freqs[write_slot_idx] -= 1.0;
905 }
906 if (first_unchecked_tvidx) {
907 first_unchecked_tvidx[write_slot_idx] = cur_tvidx + 1;
908 }
909 }
910 SetBit(write_slot_idx, occupied_window_slots);
911 winpos_to_slot_idx[cur_window_size++] = write_slot_idx;
912 ++cur_tvidx;
913 // are we at the end of a window? if not, load more variant(s) before
914 // proceeding.
915 if (cur_tvidx != next_window_end_tvidx) {
916 continue;
917 }
918 if (first_unchecked_tvidx) {
919 // PLINK 1.x pruning order
920
921 // possible for cur_window_size == 1, if all variants at the end of the
922 // previous window were pruned
923 uint32_t cur_removed_ct = PopcountWords(cur_window_removed, BitCtToWordCt(cur_window_size));
924 uint32_t prev_removed_ct;
925 do {
926 prev_removed_ct = cur_removed_ct;
927 // const uint32_t debug_print = (!IsSet(cur_window_removed, 0)) && (tvidxs[winpos_to_slot_idx[0]] == 0);
928 for (uint32_t first_winpos = 0; ; ++first_winpos) {
929 // can't use BitIter0 since we care about changes in this loop to
930 // cur_window_removed
931 first_winpos = AdvTo0Bit(cur_window_removed, first_winpos);
932 // can assume empty trailing bit for cur_window_removed
933 if (first_winpos == cur_window_size) {
934 break;
935 }
936 const uint32_t first_slot_idx = winpos_to_slot_idx[first_winpos];
937 const uint32_t cur_first_unchecked_tvidx = first_unchecked_tvidx[first_slot_idx];
938 if (cur_first_unchecked_tvidx == cur_tvidx) {
939 continue;
940 }
941 // safe to use BitIter0 for second_winpos, though
942 uintptr_t second_winpos_base;
943 uintptr_t cur_window_removed_inv_bits;
944 BitIter0Start(cur_window_removed, first_winpos + 1, &second_winpos_base, &cur_window_removed_inv_bits);
945 {
946 uint32_t second_winpos;
947 uint32_t second_slot_idx;
948 do {
949 second_winpos = BitIter0(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
950 if (second_winpos == cur_window_size) {
951 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
952 goto IndepPairwiseThread_next_first;
953 }
954 second_slot_idx = winpos_to_slot_idx[second_winpos];
955 } while (tvidxs[second_slot_idx] < cur_first_unchecked_tvidx);
956 const uintptr_t* first_genobufs = &(genobufs[first_slot_idx * entire_variant_buf_word_ct]);
957 const uint32_t first_nm_ct = vaggs[first_slot_idx].nm_ct;
958 const int32_t first_sum = vaggs[first_slot_idx].sum;
959 const uint32_t first_ssq = vaggs[first_slot_idx].ssq;
960 while (1) {
961 const uintptr_t* second_genobufs = &(genobufs[second_slot_idx * entire_variant_buf_word_ct]);
962 uint32_t cur_nm_ct = first_nm_ct;
963 int32_t cur_first_sum = first_sum;
964 uint32_t cur_first_ssq = first_ssq;
965 int32_t second_sum;
966 uint32_t second_ssq;
967 int32_t cur_dotprod;
968 ComputeIndepPairwiseR2Components(first_genobufs, second_genobufs, &(vaggs[second_slot_idx]), cur_founder_ct, &cur_nm_ct, &cur_first_sum, &cur_first_ssq, &second_sum, &second_ssq, &cur_dotprod);
969 if (is_x) {
970 uint32_t nonmale_nm_ct = nonmale_vaggs[first_slot_idx].nm_ct;
971 int32_t nonmale_first_sum = nonmale_vaggs[first_slot_idx].sum;
972 uint32_t nonmale_first_ssq = nonmale_vaggs[first_slot_idx].ssq;
973 int32_t nonmale_dotprod;
974 int32_t nonmale_second_sum;
975 uint32_t nonmale_second_ssq;
976 ComputeIndepPairwiseR2Components(&(first_genobufs[2 * cur_founder_ctaw]), &(second_genobufs[2 * cur_founder_ctaw]), &(nonmale_vaggs[second_slot_idx]), nonmale_ct, &nonmale_nm_ct, &nonmale_first_sum, &nonmale_first_ssq, &nonmale_second_sum, &nonmale_second_ssq, &nonmale_dotprod);
977 // only --ld-xchr 3 for now
978 // assumes founder_ct < 2^30
979 cur_nm_ct += 2 * nonmale_nm_ct;
980 cur_first_sum += 2 * nonmale_first_sum;
981 cur_first_ssq += 2 * nonmale_first_ssq;
982 second_sum += 2 * nonmale_second_sum;
983 second_ssq += 2 * nonmale_second_ssq;
984 cur_dotprod += 2 * nonmale_dotprod;
985 }
986 // these three values are actually cur_nm_ct times their
987 // true values, but that cancels out
988 const double cov12 = S_CAST(double, cur_dotprod * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, cur_first_sum) * second_sum);
989 const double variance1 = S_CAST(double, cur_first_ssq * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, cur_first_sum) * cur_first_sum);
990 const double variance2 = S_CAST(double, second_ssq * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, second_sum) * second_sum);
991 // > instead of >=, so we don't prune from a pair of
992 // variants with zero common observations
993 if (cov12 * cov12 > prune_ld_thresh * variance1 * variance2) {
994 // this has a surprisingly large ~3% speed penalty on my
995 // main test scenario, but that's an acceptable price to
996 // pay for reproducibility.
997 if (cur_maj_freqs[first_slot_idx] > cur_maj_freqs[second_slot_idx] * (1 + kSmallEpsilon)) {
998 SetBit(first_winpos, cur_window_removed);
999 SetBit(tvidxs[first_slot_idx], removed_variants_write);
1000 } else {
1001 SetBit(second_winpos, cur_window_removed);
1002 SetBit(tvidxs[second_slot_idx], removed_variants_write);
1003 const uint32_t next_start_winpos = BitIter0NoAdv(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
1004 if (next_start_winpos < cur_window_size) {
1005 first_unchecked_tvidx[first_slot_idx] = tvidxs[winpos_to_slot_idx[next_start_winpos]];
1006 } else {
1007 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
1008 }
1009 }
1010 break;
1011 }
1012 second_winpos = BitIter0(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
1013 if (second_winpos == cur_window_size) {
1014 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
1015 break;
1016 }
1017 second_slot_idx = winpos_to_slot_idx[second_winpos];
1018 } // while (1)
1019 }
1020 IndepPairwiseThread_next_first:
1021 ;
1022 }
1023 cur_removed_ct = PopcountWords(cur_window_removed, BitCtToWordCt(cur_window_size));
1024 } while (cur_removed_ct > prev_removed_ct);
1025 } else {
1026 // Within each window, scan in reverse order. This way, we tend to
1027 // check the nearest new pairs first, and this should allow us to exit
1028 // early more often.
1029 const uint32_t second_winpos_stop = winpos_split? winpos_split : 1;
1030 for (uint32_t second_winpos = cur_window_size; second_winpos != second_winpos_stop; ) {
1031 --second_winpos;
1032 const uint32_t second_slot_idx = winpos_to_slot_idx[second_winpos];
1033 const uintptr_t* second_genobufs = &(genobufs[second_slot_idx * entire_variant_buf_word_ct]);
1034 const uint32_t second_nm_ct = vaggs[second_slot_idx].nm_ct;
1035 const int32_t second_sum = vaggs[second_slot_idx].sum;
1036 const uint32_t second_ssq = vaggs[second_slot_idx].ssq;
1037 for (uint32_t first_winpos = second_winpos; first_winpos; ) {
1038 --first_winpos;
1039 // possible todo: faster unset-bit reverse-iterator. but probably
1040 // doesn't pay off here.
1041 if (IsSet(cur_window_removed, first_winpos)) {
1042 continue;
1043 }
1044 const uint32_t first_slot_idx = winpos_to_slot_idx[first_winpos];
1045 const uintptr_t* first_genobufs = &(genobufs[first_slot_idx * entire_variant_buf_word_ct]);
1046 uint32_t cur_nm_ct = second_nm_ct;
1047 int32_t cur_second_sum = second_sum;
1048 uint32_t cur_second_ssq = second_ssq;
1049 int32_t first_sum;
1050 uint32_t first_ssq;
1051 int32_t cur_dotprod;
1052 ComputeIndepPairwiseR2Components(second_genobufs, first_genobufs, &(vaggs[first_slot_idx]), cur_founder_ct, &cur_nm_ct, &cur_second_sum, &cur_second_ssq, &first_sum, &first_ssq, &cur_dotprod);
1053 if (is_x) {
1054 uint32_t nonmale_nm_ct = nonmale_vaggs[second_slot_idx].nm_ct;
1055 int32_t nonmale_second_sum = nonmale_vaggs[second_slot_idx].sum;
1056 uint32_t nonmale_second_ssq = nonmale_vaggs[second_slot_idx].ssq;
1057 int32_t nonmale_dotprod;
1058 int32_t nonmale_first_sum;
1059 uint32_t nonmale_first_ssq;
1060 ComputeIndepPairwiseR2Components(&(second_genobufs[2 * cur_founder_ctaw]), &(first_genobufs[2 * cur_founder_ctaw]), &(nonmale_vaggs[first_slot_idx]), nonmale_ct, &nonmale_nm_ct, &nonmale_second_sum, &nonmale_second_ssq, &nonmale_first_sum, &nonmale_first_ssq, &nonmale_dotprod);
1061 // only --ld-xchr 3 for now
1062 // assumes founder_ct < 2^30
1063 cur_nm_ct += 2 * nonmale_nm_ct;
1064 first_sum += 2 * nonmale_first_sum;
1065 first_ssq += 2 * nonmale_first_ssq;
1066 cur_second_sum += 2 * nonmale_second_sum;
1067 cur_second_ssq += 2 * nonmale_second_ssq;
1068 cur_dotprod += 2 * nonmale_dotprod;
1069 }
1070 // these three values are actually cur_nm_ct times their
1071 // true values, but that cancels out
1072 const double cov12 = S_CAST(double, cur_dotprod * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, first_sum) * cur_second_sum);
1073 const double variance1 = S_CAST(double, first_ssq * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, first_sum) * first_sum);
1074 const double variance2 = S_CAST(double, cur_second_ssq * S_CAST(int64_t, cur_nm_ct) - S_CAST(int64_t, cur_second_sum) * cur_second_sum);
1075 // > instead of >=, so we don't prune from a pair of
1076 // variants with zero common observations
1077 if (cov12 * cov12 > prune_ld_thresh * variance1 * variance2) {
1078 if (cur_maj_freqs[first_slot_idx] <= cur_maj_freqs[second_slot_idx] * (1 + kSmallEpsilon)) {
1079 SetBit(second_winpos, cur_window_removed);
1080 SetBit(tvidxs[second_slot_idx], removed_variants_write);
1081 break;
1082 }
1083 SetBit(first_winpos, cur_window_removed);
1084 SetBit(tvidxs[first_slot_idx], removed_variants_write);
1085 }
1086 } // while (1)
1087 }
1088 }
1089 const uint32_t prev_window_size = cur_window_size;
1090 LdPruneNextWindow(variant_include, variant_bps, tvidxs, cur_window_removed, prune_window_size, window_incr, window_maxl, subcontig_end_tvidx, &cur_window_size, &window_start_tvidx, &variant_uidx_winstart, &next_window_end_tvidx, &variant_uidx_winend, occupied_window_slots, winpos_to_slot_idx);
1091 winpos_split = cur_window_size;
1092 // clear bits here since we set cur_window_removed bits during loading
1093 // process in monomorphic case
1094 ZeroWArr(BitCtToWordCt(prev_window_size), cur_window_removed);
1095 write_slot_idx = 0;
1096 }
1097 parity = 1 - parity;
1098 tvidx_start = tvidx_stop;
1099 } while (!THREAD_BLOCK_FINISH(arg));
1100 THREAD_RETURN;
1101 }
1102
1103 PglErr IndepPairwise(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const AlleleCode* maj_alleles, const double* allele_freqs, const uintptr_t* founder_info, const uint32_t* founder_info_cumulative_popcounts, const uintptr_t* founder_nonmale, const uintptr_t* founder_male, const uintptr_t* founder_nonfemale, const LdInfo* ldip, const uintptr_t* preferred_variants, const uint32_t* subcontig_info, const uint32_t* subcontig_thread_assignments, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t founder_male_ct, uint32_t founder_nonfemale_ct, uint32_t subcontig_ct, uintptr_t window_max, uint32_t calc_thread_ct, uint32_t max_load, PgenReader* simple_pgrp, uintptr_t* removed_variants_collapsed) {
1104 ThreadGroup tg;
1105 PreinitThreads(&tg);
1106 PglErr reterr = kPglRetSuccess;
1107 {
1108 const uint32_t founder_nonmale_ct = founder_ct - founder_male_ct;
1109 if (unlikely(founder_nonmale_ct * 2 + founder_male_ct > 0x7fffffffU)) {
1110 // may as well document this
1111 logerrputs("Error: --indep-pairwise does not support >= 2^30 founders.\n");
1112 goto IndepPairwise_ret_NOT_YET_SUPPORTED;
1113 }
1114 const uint32_t founder_nonmale_ctaw = BitCtToAlignedWordCt(founder_nonmale_ct);
1115 const uint32_t founder_male_ctaw = BitCtToAlignedWordCt(founder_male_ct);
1116 // Per-thread allocations:
1117 // - tvidx_batch_size * raw_tgenovec_single_variant_word_ct *
1118 // sizeof(intptr_t) for raw genotype data (raw_tgenovecs)
1119 // - tvidx_batch_size * sizeof(double) for cur_maj_freqs
1120 // - if pos-based window, tvidx_batch_size * sizeof(int32_t)
1121 // - All of the above again, to allow loader thread to operate
1122 // independently
1123 // - window_max * 2 * (founder_nonmale_ctaw + founder_male_ctaw) *
1124 // kBytesPerVec for split genotype data
1125 // - max_loadl * sizeof(intptr_t) for removed-variant bitarray
1126 // - window_max * 3 * sizeof(int32_t) for main missing_ct, sum(x_i),
1127 // sum(x_i^2) array
1128 // - window_max * 3 * sizeof(int32_t) for chrX founder_male missing_ct,
1129 // sum(x_i), sum(x_i^2) array
1130 // - window_max * sizeof(int32_t) for indexes into genotype data bitarrays
1131 // (for now, anyway)
1132 // - window_max * sizeof(int32_t) for live_indices (variant_idxs?)
1133 // - window_max * sizeof(int32_t) for start_arr (first uncompared
1134 // variant_idx)
1135 IndepPairwiseCtx ctx;
1136 uintptr_t* tmp_genovec;
1137 uint32_t* thread_last_subcontig;
1138 uint32_t* thread_subcontig_start_tvidx;
1139 uint32_t* thread_last_tvidx;
1140 uint32_t* thread_last_uidx;
1141 if (unlikely(bigstack_alloc_w(NypCtToWordCt(raw_sample_ct), &tmp_genovec) ||
1142 bigstack_calloc_u32(calc_thread_ct, &ctx.tvidx_end) ||
1143 bigstack_calloc_u32(calc_thread_ct, &thread_last_subcontig) ||
1144 bigstack_calloc_u32(calc_thread_ct, &thread_subcontig_start_tvidx) ||
1145 bigstack_calloc_u32(calc_thread_ct, &thread_last_tvidx) ||
1146 bigstack_calloc_u32(calc_thread_ct, &thread_last_uidx) ||
1147 bigstack_alloc_wp(calc_thread_ct, &ctx.genobufs) ||
1148 bigstack_alloc_wp(calc_thread_ct, &ctx.occupied_window_slots) ||
1149 bigstack_alloc_wp(calc_thread_ct, &ctx.cur_window_removed) ||
1150 bigstack_alloc_dp(calc_thread_ct, &ctx.cur_maj_freqs) ||
1151 bigstack_alloc_wp(calc_thread_ct, &ctx.removed_variants_write) ||
1152 BIGSTACK_ALLOC_X(VariantAggs*, calc_thread_ct, &ctx.vaggs) ||
1153 BIGSTACK_ALLOC_X(VariantAggs*, calc_thread_ct, &ctx.nonmale_vaggs) ||
1154 bigstack_alloc_u32p(calc_thread_ct, &ctx.winpos_to_slot_idx) ||
1155 bigstack_alloc_u32p(calc_thread_ct, &ctx.tvidxs) ||
1156 bigstack_alloc_wp(calc_thread_ct, &(ctx.raw_tgenovecs[0])) ||
1157 bigstack_alloc_wp(calc_thread_ct, &(ctx.raw_tgenovecs[1])))) {
1158 goto IndepPairwise_ret_NOMEM;
1159 }
1160 const uint32_t plink1_order = (ldip->prune_flags / kfLdPrunePlink1Order) & 1;
1161 if (plink1_order) {
1162 if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.first_unchecked_tvidx))) {
1163 goto IndepPairwise_ret_NOMEM;
1164 }
1165 } else {
1166 ctx.first_unchecked_tvidx = nullptr;
1167 }
1168 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
1169 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
1170 ctx.tvidx_end[cur_thread_idx] += subcontig_info[3 * subcontig_idx];
1171 }
1172 const uintptr_t entire_variant_buf_word_ct = 2 * (founder_nonmale_ctaw + founder_male_ctaw);
1173 const uint32_t window_maxl = BitCtToWordCt(window_max);
1174 const uint32_t max_loadl = BitCtToWordCt(max_load);
1175 const uintptr_t genobuf_alloc = RoundUpPow2(window_max * entire_variant_buf_word_ct * sizeof(intptr_t), kCacheline);
1176 const uintptr_t occupied_window_slots_alloc = RoundUpPow2(window_maxl * sizeof(intptr_t), kCacheline);
1177 const uintptr_t cur_window_removed_alloc = RoundUpPow2((1 + window_max / kBitsPerWord) * sizeof(intptr_t), kCacheline);
1178 const uintptr_t cur_maj_freqs_alloc = RoundUpPow2(window_max * sizeof(double), kCacheline);
1179 const uintptr_t removed_variants_write_alloc = RoundUpPow2(max_loadl * sizeof(intptr_t), kCacheline);
1180
1181 // two of these
1182 const uintptr_t vaggs_alloc = RoundUpPow2(window_max * sizeof(VariantAggs), kCacheline);
1183
1184 // (2 + plink1_order) of these
1185 const uintptr_t window_int32_alloc = RoundUpPow2(window_max * sizeof(int32_t), kCacheline);
1186
1187 const uintptr_t thread_alloc_base = genobuf_alloc + occupied_window_slots_alloc + cur_window_removed_alloc + cur_maj_freqs_alloc + removed_variants_write_alloc + 2 * vaggs_alloc + (2 + plink1_order) * window_int32_alloc;
1188
1189 const uint32_t founder_ctl2 = NypCtToWordCt(founder_ct);
1190 const uint32_t founder_male_ctl2 = NypCtToWordCt(founder_male_ct);
1191 const uint32_t founder_nonmale_ctl2 = NypCtToWordCt(founder_nonmale_ct);
1192 const uint32_t founder_nonfemale_ctl2 = NypCtToWordCt(founder_nonfemale_ct);
1193 const uintptr_t raw_tgenovec_single_variant_word_ct = RoundUpPow2(founder_nonmale_ctl2 + founder_male_ctl2, kWordsPerVec);
1194 // round down
1195 uintptr_t bigstack_avail_per_thread = RoundDownPow2(bigstack_left() / calc_thread_ct, kCacheline);
1196 // may as well require capacity for >= 256 variants per thread per pass
1197 if (unlikely(bigstack_avail_per_thread <= thread_alloc_base + 2 * 256 * raw_tgenovec_single_variant_word_ct * sizeof(intptr_t))) {
1198 goto IndepPairwise_ret_NOMEM;
1199 }
1200 bigstack_avail_per_thread -= thread_alloc_base;
1201 uint32_t tvidx_batch_size = DivUp(max_load, 2);
1202 // tried a bunch of powers of two, this seems to be a good value
1203 if (tvidx_batch_size > 65536) {
1204 tvidx_batch_size = 65536;
1205 }
1206 // tvidx_batch_size = max_load; // temporary debugging
1207 if (2 * tvidx_batch_size * raw_tgenovec_single_variant_word_ct * sizeof(intptr_t) > bigstack_avail_per_thread) {
1208 tvidx_batch_size = bigstack_avail_per_thread / RoundUpPow2(raw_tgenovec_single_variant_word_ct * 2 * sizeof(intptr_t), kCacheline);
1209 }
1210 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1211 ctx.genobufs[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(genobuf_alloc));
1212 ctx.occupied_window_slots[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(occupied_window_slots_alloc));
1213 ZeroWArr(window_maxl, ctx.occupied_window_slots[tidx]);
1214 ctx.cur_window_removed[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(cur_window_removed_alloc));
1215 ZeroWArr(1 + window_max / kBitsPerWord, ctx.cur_window_removed[tidx]);
1216 ctx.cur_maj_freqs[tidx] = S_CAST(double*, bigstack_alloc_raw(cur_maj_freqs_alloc));
1217 ctx.removed_variants_write[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(removed_variants_write_alloc));
1218 ZeroWArr(max_loadl, ctx.removed_variants_write[tidx]);
1219 ctx.vaggs[tidx] = S_CAST(VariantAggs*, bigstack_alloc_raw(vaggs_alloc));
1220 ctx.nonmale_vaggs[tidx] = S_CAST(VariantAggs*, bigstack_alloc_raw(vaggs_alloc));
1221 ctx.winpos_to_slot_idx[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1222 ctx.tvidxs[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1223 if (ctx.first_unchecked_tvidx) {
1224 ctx.first_unchecked_tvidx[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1225 }
1226 ctx.raw_tgenovecs[0][tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(tvidx_batch_size * raw_tgenovec_single_variant_word_ct * sizeof(intptr_t)));
1227 ctx.raw_tgenovecs[1][tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(tvidx_batch_size * raw_tgenovec_single_variant_word_ct * sizeof(intptr_t)));
1228 }
1229 ctx.subcontig_info = subcontig_info;
1230 ctx.subcontig_thread_assignments = subcontig_thread_assignments;
1231 ctx.variant_include = variant_include;
1232 ctx.allele_idx_offsets = allele_idx_offsets;
1233 ctx.maj_alleles = maj_alleles;
1234 ctx.all_allele_freqs = allele_freqs;
1235 ctx.variant_bps = variant_bps;
1236 ctx.preferred_variants = preferred_variants;
1237 ctx.founder_ct = founder_ct;
1238 ctx.founder_male_ct = founder_male_ct;
1239 ctx.founder_nonfemale_ct = founder_nonfemale_ct;
1240 ctx.prune_window_size = ldip->prune_window_size;
1241 ctx.window_maxl = window_maxl;
1242 ctx.prune_ld_thresh = ldip->prune_last_param * (1 + kSmallEpsilon);
1243 ctx.window_incr = ldip->prune_window_incr;
1244 ctx.cur_batch_size = tvidx_batch_size;
1245 const uint32_t all_haploid = IsSet(cip->haploid_mask, 0);
1246 uint32_t x_start = 0;
1247 uint32_t x_end = 0;
1248 uint32_t y_start = 0;
1249 uint32_t y_end = 0;
1250 GetXymtStartAndEnd(cip, kChrOffsetX, &x_start, &x_end);
1251 GetXymtStartAndEnd(cip, kChrOffsetY, &y_start, &y_end);
1252 const uint32_t x_len = x_end - x_start;
1253 const uint32_t y_len = y_end - y_start;
1254 ctx.x_start = x_start;
1255 ctx.x_len = x_len;
1256 ctx.y_start = y_start;
1257 ctx.y_len = y_len;
1258 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
1259 goto IndepPairwise_ret_NOMEM;
1260 }
1261 SetThreadFuncAndData(IndepPairwiseThread, &ctx, &tg);
1262
1263 // Main workflow:
1264 // 1. Set n=0, load batch 0
1265
1266 // 2. Spawn threads processing batch n
1267 // 3. Increment n by 1
1268 // 4. Load batch n unless eof
1269 // 5. Join threads
1270 // 6. Goto step 2 unless eof
1271 //
1272 // 7. Assemble final results with CopyBitarrRange()
1273 uint32_t parity = 0;
1274 uint32_t pct = 0;
1275 uint32_t next_print_tvidx_start = max_load / 100;
1276 logprintf("--indep-pairwise (%u compute thread%s): ", calc_thread_ct, (calc_thread_ct == 1)? "" : "s");
1277 fputs("0%", stdout);
1278 fflush(stdout);
1279 for (uint32_t cur_tvidx_start = 0; ; cur_tvidx_start += tvidx_batch_size) {
1280 if (!IsLastBlock(&tg)) {
1281 PgrSampleSubsetIndex pssi;
1282 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
1283 uintptr_t** cur_raw_tgenovecs = ctx.raw_tgenovecs[parity];
1284 const uint32_t cur_tvidx_end = cur_tvidx_start + tvidx_batch_size;
1285 uint32_t is_x_or_y = 0;
1286 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
1287 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
1288 if (thread_last_subcontig[cur_thread_idx] > subcontig_idx) {
1289 continue;
1290 }
1291 uint32_t cur_tvidx = thread_last_tvidx[cur_thread_idx];
1292 if (cur_tvidx == cur_tvidx_end) {
1293 continue;
1294 }
1295 uint32_t subcontig_start_tvidx = thread_subcontig_start_tvidx[cur_thread_idx];
1296 uint32_t tvidx_end = subcontig_start_tvidx + subcontig_info[3 * subcontig_idx];
1297 if (tvidx_end > cur_tvidx_end) {
1298 tvidx_end = cur_tvidx_end;
1299 thread_last_subcontig[cur_thread_idx] = subcontig_idx;
1300 } else {
1301 thread_subcontig_start_tvidx[cur_thread_idx] = tvidx_end;
1302 thread_last_subcontig[cur_thread_idx] = subcontig_idx + 1;
1303 }
1304 uintptr_t tvidx_offset_end = tvidx_end - cur_tvidx_start;
1305 uint32_t variant_uidx;
1306 if (subcontig_start_tvidx == cur_tvidx) {
1307 variant_uidx = subcontig_info[3 * subcontig_idx + 2];
1308 } else {
1309 variant_uidx = thread_last_uidx[cur_thread_idx];
1310 }
1311 const uint32_t is_haploid = IsSet(cip->haploid_mask, GetVariantChr(cip, variant_uidx));
1312 uint32_t is_x = ((variant_uidx - x_start) < x_len);
1313 const uint32_t new_is_x_or_y = is_x || ((variant_uidx - y_start) < y_len);
1314
1315 // due to nonempty subset requirement (removed?)
1316 is_x = is_x && founder_nonmale_ct;
1317 if (is_x_or_y != new_is_x_or_y) {
1318 is_x_or_y = new_is_x_or_y;
1319 if (is_x_or_y) {
1320 PgrClearSampleSubsetIndex(simple_pgrp, &pssi);
1321 } else {
1322 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
1323 }
1324 }
1325 uintptr_t* cur_thread_raw_tgenovec = cur_raw_tgenovecs[cur_thread_idx];
1326 uintptr_t variant_uidx_base;
1327 uintptr_t cur_bits;
1328 BitIter1Start(variant_include, variant_uidx, &variant_uidx_base, &cur_bits);
1329 --variant_uidx;
1330 // todo: document whether tvidx_offset is guaranteed to be <=
1331 // tvidx_offset_end if this code is revisited.
1332 for (uintptr_t tvidx_offset = cur_tvidx - cur_tvidx_start; tvidx_offset < tvidx_offset_end; ++tvidx_offset) {
1333 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
1334 uintptr_t* cur_raw_tgenovec = &(cur_thread_raw_tgenovec[tvidx_offset * raw_tgenovec_single_variant_word_ct]);
1335 // There is no generalization of Pearson r^2 to multiallelic
1336 // variants with real traction, and after looking at the existing
1337 // options I don't see a reason for this to change anytime soon.
1338 // So we always load major allele counts.
1339 // probable todo: switch to PgrGetDifflistOrGenovec() and have a
1340 // fast path for low-MAF variants. Though this isn't *that*
1341 // important because knowledgeable users will have already filtered
1342 // out the lowest-MAF variants before starting the LD-prune job.
1343 if (!is_x_or_y) {
1344 reterr = PgrGetInv1(founder_info, pssi, founder_ct, variant_uidx, maj_alleles[variant_uidx], simple_pgrp, cur_raw_tgenovec);
1345 if (unlikely(reterr)) {
1346 PgenErrPrintNV(reterr, variant_uidx);
1347 goto IndepPairwise_ret_1;
1348 }
1349 if (is_haploid) {
1350 SetHetMissing(founder_ctl2, cur_raw_tgenovec);
1351 }
1352 } else {
1353 reterr = PgrGetInv1(nullptr, pssi, raw_sample_ct, variant_uidx, maj_alleles[variant_uidx], simple_pgrp, tmp_genovec);
1354 if (unlikely(reterr)) {
1355 PgenErrPrintNV(reterr, variant_uidx);
1356 goto IndepPairwise_ret_1;
1357 }
1358 if (is_x) {
1359 if (founder_male_ct) {
1360 CopyNyparrNonemptySubset(tmp_genovec, founder_male, raw_sample_ct, founder_male_ct, cur_raw_tgenovec);
1361 SetHetMissing(founder_male_ctl2, cur_raw_tgenovec);
1362 }
1363 CopyNyparrNonemptySubset(tmp_genovec, founder_nonmale, raw_sample_ct, founder_nonmale_ct, &(cur_raw_tgenovec[founder_male_ctl2]));
1364 if (all_haploid) {
1365 // don't just treat chrX identically to autosomes, since for
1366 // doubled haploids we still want to give females 2x the
1367 // weight of males. I think.
1368 SetHetMissing(founder_nonmale_ctl2, &(cur_raw_tgenovec[founder_male_ctl2]));
1369 }
1370 } else {
1371 if (founder_nonfemale_ct) {
1372 CopyNyparrNonemptySubset(tmp_genovec, founder_nonfemale, raw_sample_ct, founder_nonfemale_ct, cur_raw_tgenovec);
1373 SetHetMissing(founder_nonfemale_ctl2, cur_raw_tgenovec);
1374 }
1375 }
1376 }
1377 }
1378 thread_last_tvidx[cur_thread_idx] = tvidx_end;
1379 thread_last_uidx[cur_thread_idx] = variant_uidx + 1;
1380 }
1381 }
1382 if (cur_tvidx_start) {
1383 JoinThreads(&tg);
1384 if (IsLastBlock(&tg)) {
1385 break;
1386 }
1387 if (cur_tvidx_start >= next_print_tvidx_start) {
1388 if (pct > 10) {
1389 putc_unlocked('\b', stdout);
1390 }
1391 pct = (cur_tvidx_start * 100LLU) / max_load;
1392 printf("\b\b%u%%", pct++);
1393 fflush(stdout);
1394 next_print_tvidx_start = (pct * S_CAST(uint64_t, max_load)) / 100;
1395 }
1396 }
1397 if (cur_tvidx_start + tvidx_batch_size >= max_load) {
1398 DeclareLastThreadBlock(&tg);
1399 }
1400 if (unlikely(SpawnThreads(&tg))) {
1401 goto IndepPairwise_ret_THREAD_CREATE_FAIL;
1402 }
1403 parity = 1 - parity;
1404 }
1405 ZeroU32Arr(calc_thread_ct, thread_subcontig_start_tvidx);
1406 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
1407 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
1408 const uintptr_t* cur_removed_variants = ctx.removed_variants_write[cur_thread_idx];
1409 const uint32_t subcontig_len = subcontig_info[3 * subcontig_idx];
1410 const uint32_t subcontig_idx_start = subcontig_info[3 * subcontig_idx + 1];
1411 CopyBitarrRange(cur_removed_variants, thread_subcontig_start_tvidx[cur_thread_idx], subcontig_idx_start, subcontig_len, removed_variants_collapsed);
1412 thread_subcontig_start_tvidx[cur_thread_idx] += subcontig_len;
1413 }
1414 if (pct > 10) {
1415 putc_unlocked('\b', stdout);
1416 }
1417 fputs("\b\b", stdout);
1418 }
1419 while (0) {
1420 IndepPairwise_ret_NOMEM:
1421 reterr = kPglRetNomem;
1422 break;
1423 IndepPairwise_ret_THREAD_CREATE_FAIL:
1424 reterr = kPglRetThreadCreateFail;
1425 break;
1426 IndepPairwise_ret_NOT_YET_SUPPORTED:
1427 reterr = kPglRetNotYetSupported;
1428 break;
1429 }
1430 IndepPairwise_ret_1:
1431 CleanupThreads(&tg);
1432 // caller will free memory
1433 return reterr;
1434 }
1435
1436 typedef struct VariantHapAggsStruct {
1437 uint32_t nm_ct;
1438 uint32_t sum;
1439 } VariantHapAggs;
1440
1441 // On entry, {cur_nm_ct, cur_first_sum} must be initialized to first_vhaggs
1442 // values.
1443 void ComputeIndepPairphaseR2Components(const uintptr_t* __restrict first_hap_vec, const uintptr_t* __restrict second_hap_vec, const VariantHapAggs* second_vhaggs, uint32_t nm_vec_woffset, uint32_t cur_hap_ct, uint32_t* cur_nm_ct_ptr, uint32_t* cur_first_sum_ptr, uint32_t* second_sum_ptr, uint32_t* cur_dotprod_ptr) {
1444 const uint32_t cur_hap_ctl = BitCtToWordCt(cur_hap_ct);
1445 // Three cases:
1446 // 1. Just need dot product.
1447 // 2. Also need first_sum xor second_sum.
1448 // 3. Need all four variables.
1449 *cur_dotprod_ptr = PopcountWordsIntersect(first_hap_vec, second_hap_vec, cur_hap_ctl);
1450 const uintptr_t* first_nm_vec = &(first_hap_vec[nm_vec_woffset]);
1451 if (*cur_nm_ct_ptr != cur_hap_ct) {
1452 *second_sum_ptr = PopcountWordsIntersect(first_nm_vec, second_hap_vec, cur_hap_ctl);
1453 } else {
1454 *second_sum_ptr = second_vhaggs->sum;
1455 }
1456 const uint32_t second_nm_ct = second_vhaggs->nm_ct;
1457 if (second_nm_ct == cur_hap_ct) {
1458 return;
1459 }
1460 const uintptr_t* second_nm_vec = &(second_hap_vec[nm_vec_woffset]);
1461 *cur_first_sum_ptr = PopcountWordsIntersect(first_hap_vec, second_nm_vec, cur_hap_ctl);
1462 if (*cur_nm_ct_ptr != cur_hap_ct) {
1463 *cur_nm_ct_ptr = PopcountWordsIntersect(first_nm_vec, second_nm_vec, cur_hap_ctl);
1464 } else {
1465 *cur_nm_ct_ptr = second_nm_ct;
1466 }
1467 }
1468
1469 // Returns 1 if monomorphic, 0 otherwise.
1470 uint32_t FillVhaggs(const uintptr_t* hap_vec, const uintptr_t* nm_vec, uintptr_t word_ct, VariantHapAggs* vhaggs) {
1471 const uint32_t nm_ct = PopcountWords(nm_vec, word_ct);
1472 const uint32_t sum = PopcountWords(hap_vec, word_ct);
1473 vhaggs->nm_ct = nm_ct;
1474 vhaggs->sum = sum;
1475 return (!sum) || (sum == nm_ct);
1476 }
1477
1478 void IndepPairphaseUpdateSubcontig(const ChrInfo* cip, uint32_t variant_uidx_winstart, uint32_t x_start, uint32_t x_len, uint32_t y_start, uint32_t y_len, uint32_t founder_ct, uint32_t founder_male_ct, uint32_t founder_nonfemale_ct, uint32_t* is_x_ptr, uint32_t* is_y_ptr, uint32_t* is_haploid_ptr, uint32_t* cur_hap_ct_ptr, uint32_t* cur_hap_ctl_ptr) {
1479 // _len is better than _end here since we can exploit unsignedness
1480 const uint32_t is_x = ((variant_uidx_winstart - x_start) < x_len);
1481 const uint32_t is_y = ((variant_uidx_winstart - y_start) < y_len);
1482 const uint32_t is_haploid = IsSet(cip->haploid_mask, GetVariantChr(cip, variant_uidx_winstart));
1483 if ((is_x != (*is_x_ptr)) || (is_y != (*is_y_ptr)) || (is_haploid != (*is_haploid_ptr))) {
1484 *is_x_ptr = is_x;
1485 *is_y_ptr = is_y;
1486 *is_haploid_ptr = is_haploid;
1487 uint32_t cur_hap_ct;
1488 if (is_x) {
1489 cur_hap_ct = 2 * founder_ct - founder_male_ct;
1490 } else if (is_y) {
1491 cur_hap_ct = founder_nonfemale_ct;
1492 } else {
1493 cur_hap_ct = founder_ct * (2 - is_haploid);
1494 }
1495 *cur_hap_ct_ptr = cur_hap_ct;
1496 *cur_hap_ctl_ptr = BitCtToWordCt(cur_hap_ct);
1497 }
1498 }
1499
1500 typedef struct IndepPairphaseCtxStruct {
1501 const ChrInfo* cip;
1502 const uint32_t* subcontig_info;
1503 const uint32_t* subcontig_thread_assignments;
1504 const uintptr_t* variant_include;
1505 const uintptr_t* allele_idx_offsets;
1506 const AlleleCode* maj_alleles;
1507 const double* all_allele_freqs;
1508 const uint32_t* variant_bps;
1509 const uintptr_t* preferred_variants;
1510 uint32_t* tvidx_end;
1511 uint32_t x_start;
1512 uint32_t x_len;
1513 uint32_t y_start;
1514 uint32_t y_len;
1515 uint32_t founder_ct;
1516 uint32_t founder_male_ct;
1517 uint32_t founder_nonfemale_ct;
1518 uint32_t prune_window_size;
1519 uint32_t window_maxl;
1520 double prune_ld_thresh;
1521 uint32_t window_incr;
1522 uint32_t cur_batch_size;
1523
1524 uintptr_t** hap_then_nm_vecs;
1525 uintptr_t** occupied_window_slots;
1526 uintptr_t** cur_window_removed;
1527 double** cur_maj_freqs;
1528 uintptr_t** removed_variants_write;
1529 VariantHapAggs** vhaggs;
1530 uint32_t** winpos_to_slot_idx;
1531 uint32_t** tvidxs;
1532 uint32_t** first_unchecked_tvidx;
1533 uintptr_t** loader_hap_then_nm_vecs[2];
1534 } IndepPairphaseCtx;
1535
1536 THREAD_FUNC_DECL IndepPairphaseThread(void* raw_arg) {
1537 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
1538 const uintptr_t tidx = arg->tidx;
1539 IndepPairphaseCtx* ctx = S_CAST(IndepPairphaseCtx*, arg->sharedp->context);
1540
1541 const ChrInfo* cip = ctx->cip;
1542 const uint32_t* subcontig_info = ctx->subcontig_info;
1543 const uint32_t* subcontig_thread_assignments = ctx->subcontig_thread_assignments;
1544 const uintptr_t* variant_include = ctx->variant_include;
1545 const uintptr_t* preferred_variants = ctx->preferred_variants;
1546 const uint32_t x_start = ctx->x_start;
1547 const uint32_t x_len = ctx->x_len;
1548 const uint32_t y_start = ctx->y_start;
1549 const uint32_t y_len = ctx->y_len;
1550 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
1551 const AlleleCode* maj_alleles = ctx->maj_alleles;
1552 const double* all_allele_freqs = ctx->all_allele_freqs;
1553 const uint32_t* variant_bps = ctx->variant_bps;
1554 const uint32_t founder_ct = ctx->founder_ct;
1555 const uint32_t founder_male_ct = ctx->founder_male_ct;
1556 const uint32_t founder_nonfemale_ct = ctx->founder_nonfemale_ct;
1557 const uint32_t max_hap_ctaw = BitCtToAlignedWordCt(founder_ct * 2);
1558 const uintptr_t max_hap_ctaw_x2 = max_hap_ctaw * 2;
1559 const uint32_t prune_window_size = ctx->prune_window_size;
1560 const uint32_t window_maxl = ctx->window_maxl;
1561 const double prune_ld_thresh = ctx->prune_ld_thresh;
1562 const uint32_t window_incr = ctx->window_incr;
1563 const uint32_t tvidx_end = ctx->tvidx_end[tidx];
1564 uintptr_t* hap_then_nm_vecs = ctx->hap_then_nm_vecs[tidx];
1565 uintptr_t* occupied_window_slots = ctx->occupied_window_slots[tidx];
1566 uintptr_t* cur_window_removed = ctx->cur_window_removed[tidx];
1567 uintptr_t* removed_variants_write = ctx->removed_variants_write[tidx];
1568 double* cur_maj_freqs = ctx->cur_maj_freqs[tidx];
1569 VariantHapAggs* vhaggs = ctx->vhaggs[tidx];
1570 uint32_t* winpos_to_slot_idx = ctx->winpos_to_slot_idx[tidx];
1571 uint32_t* tvidxs = ctx->tvidxs[tidx];
1572 uint32_t* first_unchecked_tvidx = ctx->first_unchecked_tvidx? ctx->first_unchecked_tvidx[tidx] : nullptr;
1573
1574 uint32_t subcontig_end_tvidx = 0;
1575 uint32_t subcontig_idx = UINT32_MAX; // deliberate overflow
1576 uint32_t window_start_tvidx = 0;
1577 uint32_t next_window_end_tvidx = 0;
1578 uint32_t write_slot_idx = 0;
1579 uint32_t is_x = 0;
1580 uint32_t is_y = 0;
1581 uint32_t is_haploid = IsSet(cip->haploid_mask, 0);
1582 uint32_t cur_window_size = 0;
1583 uint32_t winpos_split = 0;
1584 uint32_t tvidx_start = 0;
1585 uint32_t cur_hap_ct = founder_ct * (2 - is_haploid);
1586 uint32_t cur_hap_ctl = BitCtToWordCt(cur_hap_ct);
1587 uintptr_t variant_uidx_base = 0;
1588 uintptr_t variant_include_bits = variant_include[0];
1589 uint32_t variant_uidx_winstart = 0;
1590 uint32_t variant_uidx_winend = 0;
1591 uint32_t cur_allele_ct = 2;
1592 uint32_t parity = 0;
1593 do {
1594 const uint32_t cur_batch_size = ctx->cur_batch_size;
1595 const uint32_t tvidx_stop = MINV(tvidx_start + cur_batch_size, tvidx_end);
1596 // main loop has to be variant-, not window-, based due to how datasets too
1597 // large to fit in memory are handled: we may have to halt in the middle of
1598 // unpacking data for a window, waiting until the current I/O pass is
1599 // complete before proceeding
1600 const uintptr_t* loader_hap_then_nm_vecs = ctx->loader_hap_then_nm_vecs[parity][tidx];
1601 for (uint32_t cur_tvidx = tvidx_start; cur_tvidx < tvidx_stop; ) {
1602 if (cur_tvidx == subcontig_end_tvidx) {
1603 LdPruneNextSubcontig(variant_include, variant_bps, subcontig_info, subcontig_thread_assignments, prune_window_size, tidx, &subcontig_idx, &subcontig_end_tvidx, &next_window_end_tvidx, &variant_uidx_winstart, &variant_uidx_winend);
1604 IndepPairphaseUpdateSubcontig(cip, variant_uidx_winstart, x_start, x_len, y_start, y_len, founder_ct, founder_male_ct, founder_nonfemale_ct, &is_x, &is_y, &is_haploid, &cur_hap_ct, &cur_hap_ctl);
1605 BitIter1Start(variant_include, variant_uidx_winstart, &variant_uidx_base, &variant_include_bits);
1606 winpos_split = 0;
1607 }
1608 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
1609 write_slot_idx = AdvTo0Bit(occupied_window_slots, write_slot_idx);
1610 uintptr_t tvidx_offset = cur_tvidx - tvidx_start;
1611 {
1612 const uintptr_t* cur_loader_hap_then_nm_vecs = &(loader_hap_then_nm_vecs[tvidx_offset * max_hap_ctaw_x2]);
1613 uintptr_t* cur_hap_vec = &(hap_then_nm_vecs[write_slot_idx * max_hap_ctaw_x2]);
1614 memcpy(cur_hap_vec, cur_loader_hap_then_nm_vecs, max_hap_ctaw_x2 * sizeof(intptr_t));
1615 uintptr_t* cur_nm_vec = &(cur_hap_vec[max_hap_ctaw]);
1616 if (FillVhaggs(cur_hap_vec, cur_nm_vec, cur_hap_ctl, &(vhaggs[write_slot_idx]))) {
1617 SetBit(cur_window_size, cur_window_removed);
1618 SetBit(cur_tvidx, removed_variants_write);
1619 } else {
1620 tvidxs[write_slot_idx] = cur_tvidx;
1621 uintptr_t allele_idx_base;
1622 if (!allele_idx_offsets) {
1623 allele_idx_base = variant_uidx;
1624 } else {
1625 allele_idx_base = allele_idx_offsets[variant_uidx];
1626 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_base;
1627 allele_idx_base -= variant_uidx;
1628 }
1629 cur_maj_freqs[write_slot_idx] = GetAlleleFreq(&(all_allele_freqs[allele_idx_base]), maj_alleles[variant_uidx], cur_allele_ct);
1630 if (preferred_variants && IsSet(preferred_variants, variant_uidx)) {
1631 cur_maj_freqs[write_slot_idx] -= 1.0;
1632 }
1633 if (first_unchecked_tvidx) {
1634 first_unchecked_tvidx[write_slot_idx] = cur_tvidx + 1;
1635 }
1636 }
1637 }
1638 SetBit(write_slot_idx, occupied_window_slots);
1639 winpos_to_slot_idx[cur_window_size++] = write_slot_idx;
1640 ++cur_tvidx;
1641 // are we at the end of a window? if not, load more variant(s) before
1642 // proceeding.
1643 if (cur_tvidx != next_window_end_tvidx) {
1644 continue;
1645 }
1646 if (first_unchecked_tvidx) {
1647 // PLINK 1.x pruning order
1648
1649 // possible for cur_window_size == 1, if all variants at the end of the
1650 // previous window were pruned
1651 uint32_t cur_removed_ct = PopcountWords(cur_window_removed, BitCtToWordCt(cur_window_size));
1652 uint32_t prev_removed_ct;
1653 do {
1654 prev_removed_ct = cur_removed_ct;
1655 for (uint32_t first_winpos = 0; ; ++first_winpos) {
1656 // can't use BitIter0 since we care about changes in this loop to
1657 // cur_window_removed
1658 first_winpos = AdvTo0Bit(cur_window_removed, first_winpos);
1659 // can assume empty trailing bit for cur_window_removed
1660 if (first_winpos == cur_window_size) {
1661 break;
1662 }
1663 const uint32_t first_slot_idx = winpos_to_slot_idx[first_winpos];
1664 const uint32_t cur_first_unchecked_tvidx = first_unchecked_tvidx[first_slot_idx];
1665 if (cur_first_unchecked_tvidx == cur_tvidx) {
1666 continue;
1667 }
1668 // safe to use BitIter0 for second_winpos, though
1669 uintptr_t second_winpos_base;
1670 uintptr_t cur_window_removed_inv_bits;
1671 BitIter0Start(cur_window_removed, first_winpos + 1, &second_winpos_base, &cur_window_removed_inv_bits);
1672 {
1673 uint32_t second_winpos;
1674 uint32_t second_slot_idx;
1675 do {
1676 second_winpos = BitIter0(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
1677 if (second_winpos == cur_window_size) {
1678 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
1679 goto IndepPairphaseThread_next_first;
1680 }
1681 second_slot_idx = winpos_to_slot_idx[second_winpos];
1682 } while (tvidxs[second_slot_idx] < cur_first_unchecked_tvidx);
1683 const uintptr_t* first_hap_vec = &(hap_then_nm_vecs[first_slot_idx * max_hap_ctaw_x2]);
1684 const uint32_t first_nm_ct = vhaggs[first_slot_idx].nm_ct;
1685 const uint32_t first_sum = vhaggs[first_slot_idx].sum;
1686 while (1) {
1687 const uintptr_t* second_hap_vec = &(hap_then_nm_vecs[second_slot_idx * max_hap_ctaw_x2]);
1688 uint32_t cur_nm_ct = first_nm_ct;
1689 uint32_t cur_first_sum = first_sum;
1690 uint32_t second_sum;
1691 uint32_t cur_dotprod;
1692 ComputeIndepPairphaseR2Components(first_hap_vec, second_hap_vec, &(vhaggs[second_slot_idx]), max_hap_ctaw, cur_hap_ct, &cur_nm_ct, &cur_first_sum, &second_sum, &cur_dotprod);
1693 // these three values are actually cur_nm_ct times their
1694 // true values, but that cancels out
1695 const double cov12 = S_CAST(double, S_CAST(int64_t, cur_dotprod * S_CAST(uint64_t, cur_nm_ct) - S_CAST(uint64_t, cur_first_sum) * second_sum));
1696 const double variance1 = S_CAST(double, cur_first_sum * S_CAST(int64_t, cur_nm_ct - cur_first_sum));
1697 const double variance2 = S_CAST(double, second_sum * S_CAST(int64_t, cur_nm_ct - second_sum));
1698 // > instead of >=, so we don't prune from a pair of
1699 // variants with zero common observations
1700 if (cov12 * cov12 > prune_ld_thresh * variance1 * variance2) {
1701 if (cur_maj_freqs[first_slot_idx] > cur_maj_freqs[second_slot_idx] * (1 + kSmallEpsilon)) {
1702 SetBit(first_winpos, cur_window_removed);
1703 SetBit(tvidxs[first_slot_idx], removed_variants_write);
1704 } else {
1705 SetBit(second_winpos, cur_window_removed);
1706 SetBit(tvidxs[second_slot_idx], removed_variants_write);
1707 const uint32_t next_start_winpos = BitIter0NoAdv(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
1708 if (next_start_winpos < cur_window_size) {
1709 first_unchecked_tvidx[first_slot_idx] = tvidxs[winpos_to_slot_idx[next_start_winpos]];
1710 } else {
1711 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
1712 }
1713 }
1714 break;
1715 }
1716 second_winpos = BitIter0(cur_window_removed, &second_winpos_base, &cur_window_removed_inv_bits);
1717 if (second_winpos == cur_window_size) {
1718 first_unchecked_tvidx[first_slot_idx] = cur_tvidx;
1719 break;
1720 }
1721 second_slot_idx = winpos_to_slot_idx[second_winpos];
1722 } // while (1)
1723 }
1724 IndepPairphaseThread_next_first:
1725 ;
1726 }
1727 cur_removed_ct = PopcountWords(cur_window_removed, BitCtToWordCt(cur_window_size));
1728 } while (cur_removed_ct > prev_removed_ct);
1729 } else {
1730 // Within each window, scan in reverse order. This way, we tend to
1731 // check the nearest new pairs first, and this should allow us to exit
1732 // early more often.
1733 const uint32_t second_winpos_stop = winpos_split? winpos_split : 1;
1734 for (uint32_t second_winpos = cur_window_size; second_winpos != second_winpos_stop; ) {
1735 --second_winpos;
1736 const uint32_t second_slot_idx = winpos_to_slot_idx[second_winpos];
1737 const uintptr_t* second_hap_vec = &(hap_then_nm_vecs[second_slot_idx * max_hap_ctaw_x2]);
1738 const uint32_t second_nm_ct = vhaggs[second_slot_idx].nm_ct;
1739 const int32_t second_sum = vhaggs[second_slot_idx].sum;
1740 for (uint32_t first_winpos = second_winpos; first_winpos; ) {
1741 --first_winpos;
1742 // possible todo: faster unset-bit reverse-iterator. but probably
1743 // doesn't pay off here.
1744 if (IsSet(cur_window_removed, first_winpos)) {
1745 continue;
1746 }
1747 const uint32_t first_slot_idx = winpos_to_slot_idx[first_winpos];
1748 const uintptr_t* first_hap_vec = &(hap_then_nm_vecs[first_slot_idx * max_hap_ctaw_x2]);
1749 uint32_t cur_nm_ct = second_nm_ct;
1750 uint32_t cur_second_sum = second_sum;
1751 uint32_t first_sum;
1752 uint32_t cur_dotprod;
1753 ComputeIndepPairphaseR2Components(second_hap_vec, first_hap_vec, &(vhaggs[first_slot_idx]), max_hap_ctaw, cur_hap_ct, &cur_nm_ct, &cur_second_sum, &first_sum, &cur_dotprod);
1754 // these three values are actually cur_nm_ct times their
1755 // true values, but that cancels out
1756 const double cov12 = S_CAST(double, S_CAST(int64_t, cur_dotprod * S_CAST(uint64_t, cur_nm_ct) - S_CAST(uint64_t, first_sum) * cur_second_sum));
1757 const double variance1 = S_CAST(double, first_sum * S_CAST(int64_t, cur_nm_ct - first_sum));
1758 const double variance2 = S_CAST(double, cur_second_sum * S_CAST(int64_t, cur_nm_ct - cur_second_sum));
1759 // > instead of >=, so we don't prune from a pair of
1760 // variants with zero common observations
1761 // printf("cur_dotprod: %u cur_nm_ct: %u first_sum: %u cur_second_sum: %u\n", cur_dotprod, cur_nm_ct, first_sum, cur_second_sum);
1762 // printf("vidx1: %u vidx2: %u r^2: %g\n", tvidxs[first_slot_idx], tvidxs[second_slot_idx], cov12 * cov12 / (variance1 * variance2));
1763 if (cov12 * cov12 > prune_ld_thresh * variance1 * variance2) {
1764 if (cur_maj_freqs[first_slot_idx] <= cur_maj_freqs[second_slot_idx] * (1 + kSmallEpsilon)) {
1765 SetBit(second_winpos, cur_window_removed);
1766 SetBit(tvidxs[second_slot_idx], removed_variants_write);
1767 break;
1768 }
1769 SetBit(first_winpos, cur_window_removed);
1770 SetBit(tvidxs[first_slot_idx], removed_variants_write);
1771 }
1772 } // while (1)
1773 }
1774 }
1775 const uint32_t prev_window_size = cur_window_size;
1776 LdPruneNextWindow(variant_include, variant_bps, tvidxs, cur_window_removed, prune_window_size, window_incr, window_maxl, subcontig_end_tvidx, &cur_window_size, &window_start_tvidx, &variant_uidx_winstart, &next_window_end_tvidx, &variant_uidx_winend, occupied_window_slots, winpos_to_slot_idx);
1777 winpos_split = cur_window_size;
1778 // clear bits here since we set cur_window_removed bits during loading
1779 // process in monomorphic case
1780 ZeroWArr(BitCtToWordCt(prev_window_size), cur_window_removed);
1781 write_slot_idx = 0;
1782 }
1783 parity = 1 - parity;
1784 tvidx_start = tvidx_stop;
1785 } while (!THREAD_BLOCK_FINISH(arg));
1786 THREAD_RETURN;
1787 }
1788
1789 PglErr IndepPairphase(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const AlleleCode* maj_alleles, const double* allele_freqs, const uintptr_t* founder_info, const uint32_t* founder_info_cumulative_popcounts, const uintptr_t* founder_nonmale, const uintptr_t* founder_male, const uintptr_t* founder_nonfemale, const LdInfo* ldip, const uintptr_t* preferred_variants, const uint32_t* subcontig_info, const uint32_t* subcontig_thread_assignments, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t founder_male_ct, uint32_t founder_nonfemale_ct, uint32_t subcontig_ct, uintptr_t window_max, uint32_t calc_thread_ct, uint32_t max_load, PgenReader* simple_pgrp, uintptr_t* removed_variants_collapsed) {
1790 ThreadGroup tg;
1791 PreinitThreads(&tg);
1792 PglErr reterr = kPglRetSuccess;
1793 {
1794 const uint32_t max_hap_ct = founder_ct * 2;
1795 const uint32_t hap_ctaw = BitCtToAlignedWordCt(max_hap_ct);
1796 const uintptr_t hap_ctaw_x2 = hap_ctaw * 2;
1797
1798 // Per-thread allocations:
1799 // - tvidx_batch_size * hap_ctaw_x2 * sizeof(intptr_t) for loaded haplotype
1800 // data (hap_then_nm_vecs)
1801 // - tvidx_batch_size * sizeof(double) for cur_maj_freqs
1802 // - if pos-based window, tvidx_batch_size * sizeof(int32_t)
1803 // - All of the above again, to allow loader thread to operate
1804 // independently
1805 // - window_max * hap_ctaw_x2 * kBytesPerVec for current-window haplotype
1806 // data
1807 // - max_loadl * sizeof(intptr_t) for removed-variant bitarray
1808 // - window_max * 2 * sizeof(int32_t) for main missing_ct, sum(x_i) array
1809 // - window_max * sizeof(int32_t) for indexes into genotype data bitarrays
1810 // (for now, anyway)
1811 // - window_max * sizeof(int32_t) for live_indices (variant_idxs?)
1812 // - window_max * sizeof(int32_t) for start_arr (first uncompared
1813 // variant_idx)
1814 const uint32_t founder_ctl2 = NypCtToWordCt(founder_ct);
1815 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
1816 const uint32_t raw_sample_ctl2 = NypCtToWordCt(raw_sample_ct);
1817 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1818 IndepPairphaseCtx ctx;
1819 uintptr_t* genovec;
1820 uintptr_t* phasepresent = nullptr; // spurious g++ 4.8 warning
1821 uintptr_t* phaseinfo = nullptr;
1822 uintptr_t* raw_genovec = nullptr;
1823 uintptr_t* raw_phasepresent = nullptr;
1824 uintptr_t* raw_phaseinfo = nullptr;
1825 uint32_t* thread_last_subcontig;
1826 uint32_t* thread_subcontig_start_tvidx;
1827 uint32_t* thread_last_tvidx;
1828 uint32_t* thread_last_uidx;
1829 if (unlikely(bigstack_alloc_w(founder_ctl2, &genovec) ||
1830 bigstack_alloc_w(founder_ctl, &phasepresent) ||
1831 bigstack_alloc_w(founder_ctl, &phaseinfo) ||
1832 bigstack_alloc_w(raw_sample_ctl2, &raw_genovec) ||
1833 bigstack_alloc_w(raw_sample_ctl, &raw_phasepresent) ||
1834 bigstack_alloc_w(raw_sample_ctl, &raw_phaseinfo) ||
1835 bigstack_calloc_u32(calc_thread_ct, &ctx.tvidx_end) ||
1836 bigstack_calloc_u32(calc_thread_ct, &thread_last_subcontig) ||
1837 bigstack_calloc_u32(calc_thread_ct, &thread_subcontig_start_tvidx) ||
1838 bigstack_calloc_u32(calc_thread_ct, &thread_last_tvidx) ||
1839 bigstack_calloc_u32(calc_thread_ct, &thread_last_uidx) ||
1840 bigstack_alloc_wp(calc_thread_ct, &ctx.hap_then_nm_vecs) ||
1841 bigstack_alloc_wp(calc_thread_ct, &ctx.occupied_window_slots) ||
1842 bigstack_alloc_wp(calc_thread_ct, &ctx.cur_window_removed) ||
1843 bigstack_alloc_dp(calc_thread_ct, &ctx.cur_maj_freqs) ||
1844 bigstack_alloc_wp(calc_thread_ct, &ctx.removed_variants_write) ||
1845 BIGSTACK_ALLOC_X(VariantHapAggs*, calc_thread_ct, &ctx.vhaggs) ||
1846 bigstack_alloc_u32p(calc_thread_ct, &ctx.winpos_to_slot_idx) ||
1847 bigstack_alloc_u32p(calc_thread_ct, &ctx.tvidxs) ||
1848 bigstack_alloc_wp(calc_thread_ct, &(ctx.loader_hap_then_nm_vecs[0])) ||
1849 bigstack_alloc_wp(calc_thread_ct, &(ctx.loader_hap_then_nm_vecs[1])))) {
1850 goto IndepPairphase_ret_NOMEM;
1851 }
1852 const uint32_t plink1_order = (ldip->prune_flags / kfLdPrunePlink1Order) & 1;
1853 if (plink1_order) {
1854 if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.first_unchecked_tvidx))) {
1855 goto IndepPairphase_ret_NOMEM;
1856 }
1857 } else {
1858 ctx.first_unchecked_tvidx = nullptr;
1859 }
1860 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
1861 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
1862 ctx.tvidx_end[cur_thread_idx] += subcontig_info[3 * subcontig_idx];
1863 }
1864 const uint32_t window_maxl = BitCtToWordCt(window_max);
1865 const uint32_t max_loadl = BitCtToWordCt(max_load);
1866 const uintptr_t variant_vec_alloc = RoundUpPow2(window_max * hap_ctaw_x2 * sizeof(intptr_t), kCacheline);
1867
1868 const uintptr_t occupied_window_slots_alloc = RoundUpPow2(window_maxl * sizeof(intptr_t), kCacheline);
1869 const uintptr_t cur_window_removed_alloc = RoundUpPow2((1 + window_max / kBitsPerWord) * sizeof(intptr_t), kCacheline);
1870 const uintptr_t cur_maj_freqs_alloc = RoundUpPow2(window_max * sizeof(double), kCacheline);
1871 const uintptr_t removed_variants_write_alloc = RoundUpPow2(max_loadl * sizeof(intptr_t), kCacheline);
1872 const uintptr_t vhaggs_alloc = RoundUpPow2(window_max * sizeof(VariantHapAggs), kCacheline);
1873
1874 // (2 + plink1_order) of these
1875 const uintptr_t window_int32_alloc = RoundUpPow2(window_max * sizeof(int32_t), kCacheline);
1876
1877 const uintptr_t thread_alloc_base = variant_vec_alloc + occupied_window_slots_alloc + cur_window_removed_alloc + cur_maj_freqs_alloc + removed_variants_write_alloc + vhaggs_alloc + (2 + plink1_order) * window_int32_alloc;
1878
1879 // round down
1880 uintptr_t bigstack_avail_per_thread = RoundDownPow2(bigstack_left() / calc_thread_ct, kCacheline);
1881 const uintptr_t loader_single_variant_byte_ct = 2 * (hap_ctaw_x2 * sizeof(intptr_t));
1882 // may as well require capacity for >= 256 variants per thread per pass
1883 if (unlikely(bigstack_avail_per_thread <= thread_alloc_base + 256 * loader_single_variant_byte_ct)) {
1884 goto IndepPairphase_ret_NOMEM;
1885 }
1886 bigstack_avail_per_thread -= thread_alloc_base;
1887 uint32_t tvidx_batch_size = DivUp(max_load, 2);
1888 // tried a bunch of powers of two, this seems to be a good value
1889 if (tvidx_batch_size > 65536) {
1890 tvidx_batch_size = 65536;
1891 }
1892 // tvidx_batch_size = max_load; // temporary debugging
1893 if (tvidx_batch_size * loader_single_variant_byte_ct > bigstack_avail_per_thread) {
1894 tvidx_batch_size = bigstack_avail_per_thread / loader_single_variant_byte_ct;
1895 }
1896 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1897 ctx.hap_then_nm_vecs[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(variant_vec_alloc));
1898 ctx.occupied_window_slots[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(occupied_window_slots_alloc));
1899 ZeroWArr(window_maxl, ctx.occupied_window_slots[tidx]);
1900 ctx.cur_window_removed[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(cur_window_removed_alloc));
1901 ZeroWArr(1 + window_max / kBitsPerWord, ctx.cur_window_removed[tidx]);
1902 ctx.cur_maj_freqs[tidx] = S_CAST(double*, bigstack_alloc_raw(cur_maj_freqs_alloc));
1903 ctx.removed_variants_write[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(removed_variants_write_alloc));
1904 ZeroWArr(max_loadl, ctx.removed_variants_write[tidx]);
1905 ctx.vhaggs[tidx] = S_CAST(VariantHapAggs*, bigstack_alloc_raw(vhaggs_alloc));
1906 ctx.winpos_to_slot_idx[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1907 ctx.tvidxs[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1908 if (ctx.first_unchecked_tvidx) {
1909 ctx.first_unchecked_tvidx[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(window_int32_alloc));
1910 }
1911 ctx.loader_hap_then_nm_vecs[0][tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(tvidx_batch_size * hap_ctaw_x2 * sizeof(intptr_t)));
1912 ctx.loader_hap_then_nm_vecs[1][tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(tvidx_batch_size * hap_ctaw_x2 * sizeof(intptr_t)));
1913 }
1914 ctx.cip = cip;
1915 ctx.subcontig_info = subcontig_info;
1916 ctx.subcontig_thread_assignments = subcontig_thread_assignments;
1917 ctx.variant_include = variant_include;
1918 ctx.allele_idx_offsets = allele_idx_offsets;
1919 ctx.maj_alleles = maj_alleles;
1920 ctx.all_allele_freqs = allele_freqs;
1921 ctx.variant_bps = variant_bps;
1922 ctx.preferred_variants = preferred_variants;
1923 ctx.founder_ct = founder_ct;
1924 ctx.founder_male_ct = founder_male_ct;
1925 ctx.founder_nonfemale_ct = founder_nonfemale_ct;
1926 ctx.prune_window_size = ldip->prune_window_size;
1927 ctx.window_maxl = window_maxl;
1928 ctx.prune_ld_thresh = ldip->prune_last_param * (1 + kSmallEpsilon);
1929 ctx.window_incr = ldip->prune_window_incr;
1930 ctx.cur_batch_size = tvidx_batch_size;
1931 const uint32_t all_haploid = IsSet(cip->haploid_mask, 0);
1932 uint32_t x_start = 0;
1933 uint32_t x_end = 0;
1934 uint32_t y_start = 0;
1935 uint32_t y_end = 0;
1936 GetXymtStartAndEnd(cip, kChrOffsetX, &x_start, &x_end);
1937 GetXymtStartAndEnd(cip, kChrOffsetY, &y_start, &y_end);
1938 const uint32_t x_len = x_end - x_start;
1939 const uint32_t y_len = y_end - y_start;
1940 ctx.x_start = x_start;
1941 ctx.x_len = x_len;
1942 ctx.y_start = y_start;
1943 ctx.y_len = y_len;
1944 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
1945 goto IndepPairphase_ret_NOMEM;
1946 }
1947 SetThreadFuncAndData(IndepPairphaseThread, &ctx, &tg);
1948
1949 const uint32_t founder_nonmale_ct = founder_ct - founder_male_ct;
1950 const uint32_t founder_nonmale_ctl = BitCtToWordCt(founder_nonmale_ct);
1951 uintptr_t hap_vec_overflow = 0;
1952 uintptr_t nm_vec_overflow = 0;
1953 // Main workflow:
1954 // 1. Set n=0, load batch 0
1955
1956 // 2. Spawn threads processing batch n
1957 // 3. Increment n by 1
1958 // 4. Load batch n unless eof
1959 // 5. Join threads
1960 // 6. Goto step 2 unless eof
1961 //
1962 // 7. Assemble final results with CopyBitarrRange()
1963 uint32_t parity = 0;
1964 uint32_t pct = 0;
1965 uint32_t next_print_tvidx_start = max_load / 100;
1966 logprintf("--indep-pairphase (%u compute thread%s): ", calc_thread_ct, (calc_thread_ct == 1)? "" : "s");
1967 fputs("0%", stdout);
1968 fflush(stdout);
1969 for (uint32_t cur_tvidx_start = 0; ; cur_tvidx_start += tvidx_batch_size) {
1970 if (!IsLastBlock(&tg)) {
1971 PgrSampleSubsetIndex pssi;
1972 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
1973 uintptr_t** cur_loader_hap_then_nm_vecs = ctx.loader_hap_then_nm_vecs[parity];
1974 const uint32_t cur_tvidx_end = cur_tvidx_start + tvidx_batch_size;
1975 uint32_t is_x_or_y = 0;
1976 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
1977 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
1978 if (thread_last_subcontig[cur_thread_idx] > subcontig_idx) {
1979 continue;
1980 }
1981 uint32_t cur_tvidx = thread_last_tvidx[cur_thread_idx];
1982 if (cur_tvidx == cur_tvidx_end) {
1983 continue;
1984 }
1985 uint32_t subcontig_start_tvidx = thread_subcontig_start_tvidx[cur_thread_idx];
1986 uint32_t tvidx_end = subcontig_start_tvidx + subcontig_info[3 * subcontig_idx];
1987 if (tvidx_end > cur_tvidx_end) {
1988 tvidx_end = cur_tvidx_end;
1989 thread_last_subcontig[cur_thread_idx] = subcontig_idx;
1990 } else {
1991 thread_subcontig_start_tvidx[cur_thread_idx] = tvidx_end;
1992 thread_last_subcontig[cur_thread_idx] = subcontig_idx + 1;
1993 }
1994 uintptr_t tvidx_offset_end = tvidx_end - cur_tvidx_start;
1995 uint32_t variant_uidx;
1996 if (subcontig_start_tvidx == cur_tvidx) {
1997 variant_uidx = subcontig_info[3 * subcontig_idx + 2];
1998 } else {
1999 variant_uidx = thread_last_uidx[cur_thread_idx];
2000 }
2001 const uint32_t is_haploid = IsSet(cip->haploid_mask, GetVariantChr(cip, variant_uidx));
2002 uint32_t is_x = ((variant_uidx - x_start) < x_len);
2003 const uint32_t new_is_x_or_y = is_x || ((variant_uidx - y_start) < y_len);
2004
2005 // due to nonempty subset requirement (removed?)
2006 is_x = is_x && founder_nonmale_ct;
2007 if (is_x_or_y != new_is_x_or_y) {
2008 is_x_or_y = new_is_x_or_y;
2009 if (is_x_or_y) {
2010 PgrClearSampleSubsetIndex(simple_pgrp, &pssi);
2011 } else {
2012 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
2013 }
2014 }
2015 uintptr_t* cur_thread_loader_hap_then_nm_vecs = cur_loader_hap_then_nm_vecs[cur_thread_idx];
2016 uintptr_t variant_uidx_base;
2017 uintptr_t cur_bits;
2018 BitIter1Start(variant_include, variant_uidx, &variant_uidx_base, &cur_bits);
2019 --variant_uidx;
2020 for (uintptr_t tvidx_offset = cur_tvidx - cur_tvidx_start; tvidx_offset < tvidx_offset_end; ++tvidx_offset) {
2021 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2022 uintptr_t* cur_loader_hap_vec = &(cur_thread_loader_hap_then_nm_vecs[tvidx_offset * hap_ctaw_x2]);
2023 uintptr_t* cur_loader_nm_vec = &(cur_loader_hap_vec[hap_ctaw]);
2024 if (!is_x_or_y) {
2025 uint32_t phasepresent_ct;
2026 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, variant_uidx, maj_alleles[variant_uidx], simple_pgrp, genovec, phasepresent, phaseinfo, &phasepresent_ct);
2027 if (unlikely(reterr)) {
2028 PgenErrPrintNV(reterr, variant_uidx);
2029 goto IndepPairphase_ret_1;
2030 }
2031 if (!is_haploid) {
2032 if (unlikely(HapsplitMustPhased(genovec, phasepresent, phaseinfo, founder_ct, phasepresent_ct, cur_loader_hap_vec, cur_loader_nm_vec))) {
2033 logputs("\n");
2034 logerrprintf("Error: --indep-pairphase: 0-based variant #%u is not fully phased.\n", variant_uidx);
2035 goto IndepPairphase_ret_INCONSISTENT_INPUT;
2036 }
2037 } else {
2038 HapsplitHaploid(genovec, founder_ct, cur_loader_hap_vec, cur_loader_nm_vec);
2039 }
2040 } else {
2041 uint32_t phase_exists;
2042 reterr = PgrGetInv1P(nullptr, pssi, raw_sample_ct, variant_uidx, maj_alleles[variant_uidx], simple_pgrp, raw_genovec, raw_phasepresent, raw_phaseinfo, &phase_exists);
2043 if (unlikely(reterr)) {
2044 PgenErrPrintNV(reterr, variant_uidx);
2045 goto IndepPairphase_ret_1;
2046 }
2047 if (is_x) {
2048 if (founder_male_ct) {
2049 CopyNyparrNonemptySubset(raw_genovec, founder_male, raw_sample_ct, founder_male_ct, genovec);
2050 // quasi-bugfix (17 Oct 2023): forgot to remove benchmarking
2051 // loop
2052 HapsplitHaploid(genovec, founder_male_ct, cur_loader_hap_vec, cur_loader_nm_vec);
2053 }
2054 CopyNyparrNonemptySubset(raw_genovec, founder_nonmale, raw_sample_ct, founder_nonmale_ct, genovec);
2055 if (all_haploid) {
2056 SetHetMissing(NypCtToWordCt(founder_nonmale_ct), genovec);
2057 }
2058 if (phase_exists) {
2059 CopyBitarrSubset(raw_phasepresent, founder_nonmale, founder_nonmale_ct, phasepresent);
2060 CopyBitarrSubset(raw_phaseinfo, founder_nonmale, founder_nonmale_ct, phaseinfo);
2061 phase_exists = !AllWordsAreZero(phasepresent, founder_nonmale_ctl);
2062 }
2063 const uint32_t founder_male_fullword_ct = founder_male_ct / kBitsPerWord;
2064 const uint32_t founder_male_ct_rem = founder_male_ct % kBitsPerWord;
2065 if (founder_male_ct_rem) {
2066 hap_vec_overflow = cur_loader_hap_vec[founder_male_fullword_ct];
2067 nm_vec_overflow = cur_loader_nm_vec[founder_male_fullword_ct];
2068 }
2069 if (unlikely(HapsplitMustPhased(genovec, phasepresent, phaseinfo, founder_nonmale_ct, phase_exists, &(cur_loader_hap_vec[founder_male_fullword_ct]), &(cur_loader_nm_vec[founder_male_fullword_ct])))) {
2070 logputs("\n");
2071 logerrprintf("Error: --indep-pairphase: 0-based variant #%u is not fully phased.\n", variant_uidx);
2072 goto IndepPairphase_ret_INCONSISTENT_INPUT;
2073 }
2074 if (founder_male_ct_rem) {
2075 const uint32_t word_idx = founder_male_fullword_ct + ((founder_nonmale_ct * 2) / kBitsPerWord);
2076 const uint32_t lshift_ct = (founder_nonmale_ct * 2) % kBitsPerWord;
2077 cur_loader_hap_vec[word_idx] |= hap_vec_overflow << lshift_ct;
2078 cur_loader_nm_vec[word_idx] |= nm_vec_overflow << lshift_ct;
2079 if (lshift_ct + founder_male_ct_rem > kBitsPerWord) {
2080 const uint32_t rshift_ct = kBitsPerWord - lshift_ct;
2081 cur_loader_hap_vec[word_idx + 1] = hap_vec_overflow >> rshift_ct;
2082 cur_loader_nm_vec[word_idx + 1] = nm_vec_overflow >> rshift_ct;
2083 }
2084 }
2085 } else {
2086 // chrY
2087 if (founder_nonfemale_ct) {
2088 CopyNyparrNonemptySubset(raw_genovec, founder_nonfemale, raw_sample_ct, founder_nonfemale_ct, genovec);
2089 HapsplitHaploid(genovec, founder_nonfemale_ct, cur_loader_hap_vec, cur_loader_nm_vec);
2090 }
2091 }
2092 }
2093 }
2094 thread_last_tvidx[cur_thread_idx] = tvidx_end;
2095 thread_last_uidx[cur_thread_idx] = variant_uidx + 1;
2096 }
2097 }
2098 if (cur_tvidx_start) {
2099 JoinThreads(&tg);
2100 if (IsLastBlock(&tg)) {
2101 break;
2102 }
2103 if (cur_tvidx_start >= next_print_tvidx_start) {
2104 if (pct > 10) {
2105 putc_unlocked('\b', stdout);
2106 }
2107 pct = (cur_tvidx_start * 100LLU) / max_load;
2108 printf("\b\b%u%%", pct++);
2109 fflush(stdout);
2110 next_print_tvidx_start = (pct * S_CAST(uint64_t, max_load)) / 100;
2111 }
2112 }
2113 if (cur_tvidx_start + tvidx_batch_size >= max_load) {
2114 DeclareLastThreadBlock(&tg);
2115 }
2116 if (unlikely(SpawnThreads(&tg))) {
2117 goto IndepPairphase_ret_THREAD_CREATE_FAIL;
2118 }
2119 parity = 1 - parity;
2120 }
2121 ZeroU32Arr(calc_thread_ct, thread_subcontig_start_tvidx);
2122 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
2123 const uint32_t cur_thread_idx = subcontig_thread_assignments[subcontig_idx];
2124 const uintptr_t* cur_removed_variants = ctx.removed_variants_write[cur_thread_idx];
2125 const uint32_t subcontig_len = subcontig_info[3 * subcontig_idx];
2126 const uint32_t subcontig_idx_start = subcontig_info[3 * subcontig_idx + 1];
2127 CopyBitarrRange(cur_removed_variants, thread_subcontig_start_tvidx[cur_thread_idx], subcontig_idx_start, subcontig_len, removed_variants_collapsed);
2128 thread_subcontig_start_tvidx[cur_thread_idx] += subcontig_len;
2129 }
2130 if (pct > 10) {
2131 putc_unlocked('\b', stdout);
2132 }
2133 fputs("\b\b", stdout);
2134 }
2135 while (0) {
2136 IndepPairphase_ret_NOMEM:
2137 reterr = kPglRetNomem;
2138 break;
2139 IndepPairphase_ret_INCONSISTENT_INPUT:
2140 reterr = kPglRetInconsistentInput;
2141 break;
2142 IndepPairphase_ret_THREAD_CREATE_FAIL:
2143 reterr = kPglRetThreadCreateFail;
2144 break;
2145 }
2146 IndepPairphase_ret_1:
2147 CleanupThreads(&tg);
2148 // caller will free memory
2149 return reterr;
2150 }
2151
2152 PglErr LdPruneSubcontigSplitAll(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, uint32_t prune_window_size, uint32_t* window_max_ptr, uint32_t** subcontig_info_ptr, uint32_t* subcontig_ct_ptr) {
2153 // variant_bps must be nullptr if window size is not bp-based
2154 // chr0 assumed to already be removed from variant_include.
2155 // this will skip over chromosomes/contigs with only 1 variant.
2156 const uint32_t chr_ct = cip->chr_ct;
2157 uint32_t* subcontig_info = R_CAST(uint32_t*, g_bigstack_base);
2158 uint32_t* subcontig_info_iter = subcontig_info;
2159 uint32_t* subcontig_info_limit = &(R_CAST(uint32_t*, g_bigstack_end)[-3]);
2160 uint32_t window_max = 0;
2161 uint32_t variant_idx = 0;
2162 if (variant_bps) {
2163 window_max = 1;
2164 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
2165 const uint32_t chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2166 const uint32_t initial_variant_uidx = AdvBoundedTo1Bit(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], chr_end);
2167 const uint32_t chr_variant_ct = PopcountBitRange(variant_include, initial_variant_uidx, chr_end);
2168 const uint32_t variant_idx_end = variant_idx + chr_variant_ct;
2169 if (chr_variant_ct > 1) {
2170 uintptr_t variant_uidx_base;
2171 uintptr_t variant_include_bits;
2172 BitIter1Start(variant_include, initial_variant_uidx + 1, &variant_uidx_base, &variant_include_bits);
2173 uint32_t subcontig_uidx_first = initial_variant_uidx;
2174 uint32_t subcontig_idx_first = variant_idx;
2175 uint32_t window_idx_first = variant_idx;
2176 uint32_t window_uidx_first = initial_variant_uidx;
2177 uint32_t window_pos_first = variant_bps[initial_variant_uidx];
2178 uint32_t prev_pos = window_pos_first;
2179 ++variant_idx;
2180 do {
2181 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
2182 uint32_t variant_bp_thresh = variant_bps[variant_uidx];
2183 if (variant_bp_thresh < prune_window_size) {
2184 prev_pos = variant_bp_thresh;
2185 variant_bp_thresh = 0;
2186 } else {
2187 if (variant_bp_thresh - prune_window_size > prev_pos) {
2188 if (variant_idx > subcontig_idx_first + 1) {
2189 if (subcontig_info_iter > subcontig_info_limit) {
2190 return kPglRetNomem;
2191 }
2192 *subcontig_info_iter++ = variant_idx - subcontig_idx_first;
2193 *subcontig_info_iter++ = subcontig_idx_first;
2194 *subcontig_info_iter++ = subcontig_uidx_first;
2195 }
2196 subcontig_uidx_first = variant_uidx;
2197 subcontig_idx_first = variant_idx;
2198 }
2199 prev_pos = variant_bp_thresh;
2200 variant_bp_thresh -= prune_window_size;
2201 }
2202 if (variant_bp_thresh > window_pos_first) {
2203 uintptr_t window_uidx_first_base;
2204 uintptr_t cur_bits;
2205 BitIter1Start(variant_include, window_uidx_first + 1, &window_uidx_first_base, &cur_bits);
2206 do {
2207 window_uidx_first = BitIter1(variant_include, &window_uidx_first_base, &cur_bits);
2208 window_pos_first = variant_bps[window_uidx_first];
2209 ++window_idx_first;
2210 } while (variant_bp_thresh > window_pos_first);
2211 } else if (variant_idx - window_idx_first == window_max) {
2212 ++window_max;
2213 }
2214 } while (++variant_idx < variant_idx_end);
2215 if (variant_idx > subcontig_idx_first + 1) {
2216 if (subcontig_info_iter > subcontig_info_limit) {
2217 return kPglRetNomem;
2218 }
2219 *subcontig_info_iter++ = variant_idx - subcontig_idx_first;
2220 *subcontig_info_iter++ = subcontig_idx_first;
2221 *subcontig_info_iter++ = subcontig_uidx_first;
2222 }
2223 }
2224 variant_idx = variant_idx_end;
2225 }
2226 } else {
2227 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
2228 const uint32_t chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2229 const uint32_t first_variant_uidx = AdvBoundedTo1Bit(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], chr_end);
2230 const uint32_t chr_variant_ct = PopcountBitRange(variant_include, first_variant_uidx, chr_end);
2231 if (chr_variant_ct > 1) {
2232 if (subcontig_info_iter > subcontig_info_limit) {
2233 return kPglRetNomem;
2234 }
2235 *subcontig_info_iter++ = chr_variant_ct;
2236 *subcontig_info_iter++ = variant_idx;
2237 *subcontig_info_iter++ = first_variant_uidx;
2238 if (window_max < prune_window_size) {
2239 if (chr_variant_ct > window_max) {
2240 window_max = chr_variant_ct;
2241 }
2242 }
2243 }
2244 variant_idx += chr_variant_ct;
2245 }
2246 if (window_max > prune_window_size) {
2247 window_max = prune_window_size;
2248 }
2249 }
2250 *subcontig_ct_ptr = S_CAST(uintptr_t, subcontig_info_iter - subcontig_info) / 3;
2251 *subcontig_info_ptr = subcontig_info;
2252 BigstackFinalizeU32(subcontig_info, (*subcontig_ct_ptr) * 3);
2253 *window_max_ptr = window_max;
2254 return kPglRetSuccess;
2255 }
2256
2257 // next several functions (including load_balance()) will probably move to
2258 // plink2_common
2259 void Minheap64ReplaceRoot(uint32_t heap_size, uint64_t new_root, uint64_t* minheap64_preroot) {
2260 uint32_t cur_pos = 1;
2261 while (1) {
2262 uint32_t child_pos = cur_pos * 2;
2263 if (child_pos >= heap_size) {
2264 if (child_pos == heap_size) {
2265 // special case: one child at end of heap
2266 const uint64_t child_val = minheap64_preroot[child_pos];
2267 if (new_root > child_val) {
2268 minheap64_preroot[cur_pos] = child_val;
2269 cur_pos = child_pos;
2270 }
2271 }
2272 break;
2273 }
2274 uint64_t min_child_val = minheap64_preroot[child_pos];
2275 const uint64_t child_val2 = minheap64_preroot[child_pos + 1];
2276 if (child_val2 < min_child_val) {
2277 min_child_val = child_val2;
2278 ++child_pos;
2279 }
2280 if (new_root <= min_child_val) {
2281 break;
2282 }
2283 minheap64_preroot[cur_pos] = min_child_val;
2284 cur_pos = child_pos;
2285 }
2286 minheap64_preroot[cur_pos] = new_root;
2287 }
2288
2289 /*
2290 void Minheap64DeleteRoot(uint64_t* minheap64_preroot, uint32_t* heap_size_ptr) {
2291 uint32_t heap_size = *heap_size_ptr;
2292 const uint64_t new_root = minheap64_preroot[heap_size];
2293 Minheap64ReplaceRoot(--heap_size, new_root, minheap64_preroot);
2294 *heap_size_ptr = heap_size;
2295 }
2296 */
2297
2298 void Minheap64Insert(uint64_t new_entry, uint64_t* minheap64_preroot, uint32_t* heap_size_ptr) {
2299 // assumes minheap64_preroot[0] == 0
2300 const uint32_t heap_size = 1 + (*heap_size_ptr);
2301 *heap_size_ptr = heap_size;
2302 uint32_t cur_pos = heap_size;
2303 while (1) {
2304 const uint32_t parent_pos = cur_pos / 2;
2305 const uint64_t parent_val = minheap64_preroot[parent_pos];
2306 if (new_entry >= parent_val) {
2307 minheap64_preroot[cur_pos] = new_entry;
2308 return;
2309 }
2310 minheap64_preroot[cur_pos] = parent_val;
2311 cur_pos = parent_pos;
2312 }
2313 }
2314
2315 // This is intended to split a relatively small number of contig-like regions
2316 // between threads, but it shouldn't totally fall apart if there are millions
2317 // of regions and hundreds of threads.
2318 // Based on the Longest Processing Time algorithm, but with a few adjustments:
2319 // * max(largest_weight, round_up(total_weight / thread_ct)) is noted, and the
2320 // first 8 * thread_ct thread assignments are based on best-fit to that
2321 // capacity. The constant 8 is chosen to be enough to beat basic LPT's
2322 // 4/3 - 1/{3m} approximation factor by a relevant margin, while keeping
2323 // runtime under control. (In the event that there is no fit, the capacity
2324 // is increased.)
2325 // * If any task assignments remain, we use LPT, but attempt to use a lower
2326 // number of threads; we only add another thread if we would otherwise have
2327 // to increase max_load.
2328 PglErr LoadBalance(const uint32_t* task_weights, uint32_t task_ct, uint32_t* thread_ct_ptr, uint32_t* thread_assignments, uint32_t* max_load_ptr) {
2329 // max_load assumed to be initialized to zero
2330 assert(task_ct);
2331 const uint32_t orig_thread_ct = *thread_ct_ptr;
2332 if (orig_thread_ct == 1) {
2333 ZeroU32Arr(task_ct, thread_assignments);
2334 // replace this with an acc_uint32 call?
2335 uint32_t max_load = task_weights[0];
2336 for (uint32_t task_idx = 1; task_idx != task_ct; ++task_idx) {
2337 max_load += task_weights[task_idx];
2338 }
2339 *max_load_ptr = max_load;
2340 return kPglRetSuccess;
2341 }
2342 assert(task_ct >= orig_thread_ct);
2343 uint64_t* sorted_tagged_weights;
2344 uint64_t* minheap64_preroot;
2345 if (bigstack_alloc_u64(task_ct, &sorted_tagged_weights) ||
2346 bigstack_alloc_u64(orig_thread_ct + 2, &minheap64_preroot)) {
2347 return kPglRetNomem;
2348 }
2349 minheap64_preroot[0] = 0;
2350 uint64_t* minheap64 = &(minheap64_preroot[1]);
2351 uint32_t total_weight = 0;
2352 for (uintptr_t task_idx = 0; task_idx != task_ct; ++task_idx) {
2353 const uintptr_t cur_weight = task_weights[task_idx];
2354 total_weight += cur_weight;
2355 sorted_tagged_weights[task_idx] = (S_CAST(uint64_t, cur_weight) << 32) + task_idx;
2356 }
2357 uint64_t* sorted_tagged_weights_end = &(sorted_tagged_weights[task_ct]);
2358 // could try std::nth_element if this is ever a bottleneck
2359 #ifdef __cplusplus
2360 std::sort(sorted_tagged_weights, sorted_tagged_weights_end, std::greater<uint64_t>());
2361 #else
2362 qsort(sorted_tagged_weights, task_ct, sizeof(int64_t), u64cmp_decr);
2363 #endif
2364 const uint64_t largest_tagged_weight = sorted_tagged_weights[0];
2365 uint32_t initial_max_load = largest_tagged_weight >> 32;
2366 uint32_t thread_ct = 1 + (total_weight - 1) / initial_max_load;
2367 if (thread_ct > orig_thread_ct) {
2368 thread_ct = orig_thread_ct;
2369 initial_max_load = 1 + (total_weight - 1) / orig_thread_ct;
2370 }
2371
2372 for (uintptr_t thread_idx = 1; thread_idx != thread_ct; ++thread_idx) {
2373 minheap64[thread_idx - 1] = thread_ct - thread_idx;
2374 }
2375 minheap64[thread_ct - 1] = largest_tagged_weight & 0xffffffff00000000LLU;
2376 for (uint32_t thread_idx = thread_ct; thread_idx <= orig_thread_ct; ++thread_idx) {
2377 minheap64[thread_idx] = 0xffffffffffffffffLLU;
2378 }
2379 thread_assignments[S_CAST(uint32_t, largest_tagged_weight)] = 0;
2380 uint64_t max_load_shifted = (S_CAST(uint64_t, initial_max_load) << 32) | 0xffffffffLLU;
2381 uint64_t* best_fit_end = sorted_tagged_weights_end;
2382 if (task_ct > 8 * orig_thread_ct) {
2383 // stop best-fit here
2384 best_fit_end = &(sorted_tagged_weights[8 * orig_thread_ct]);
2385 }
2386 uint64_t* sorted_tagged_weights_iter = &(sorted_tagged_weights[1]);
2387 while (sorted_tagged_weights_iter != best_fit_end) {
2388 // maintain minheap64 as fully sorted list
2389 uint64_t cur_tagged_weight = *sorted_tagged_weights_iter++;
2390 const uint32_t task_idx = S_CAST(uint32_t, cur_tagged_weight);
2391 cur_tagged_weight &= 0xffffffff00000000LLU;
2392 const uintptr_t idxp1 = LowerBoundNonemptyU64(minheap64, thread_ct, max_load_shifted - cur_tagged_weight);
2393 if (idxp1) {
2394 uintptr_t idx = idxp1 - 1;
2395 const uint64_t new_entry = minheap64[idx] + cur_tagged_weight;
2396 for (; ; ++idx) {
2397 const uint64_t next_entry = minheap64[idx + 1];
2398 if (new_entry < next_entry) {
2399 break;
2400 }
2401 minheap64[idx] = next_entry;
2402 }
2403 thread_assignments[task_idx] = S_CAST(uint32_t, new_entry);
2404 minheap64[idx] = new_entry;
2405 } else if (thread_ct < orig_thread_ct) {
2406 const uint64_t new_entry = cur_tagged_weight + thread_ct;
2407 const uintptr_t insert_pt = LowerBoundNonemptyU64(minheap64, thread_ct, new_entry);
2408 for (uintptr_t thread_idx = thread_ct; thread_idx != insert_pt; --thread_idx) {
2409 minheap64[thread_idx] = minheap64[thread_idx - 1];
2410 }
2411 minheap64[insert_pt] = new_entry;
2412 thread_assignments[task_idx] = thread_ct++;
2413 } else {
2414 // move lowest entry to end of list, shift everything else down
2415 const uint64_t new_entry = minheap64[0] + cur_tagged_weight;
2416 for (uint32_t thread_idx = 1; thread_idx != thread_ct; ++thread_idx) {
2417 minheap64[thread_idx - 1] = minheap64[thread_idx];
2418 }
2419 minheap64[thread_ct - 1] = new_entry;
2420 max_load_shifted = new_entry | 0xffffffffLLU;
2421 thread_assignments[task_idx] = S_CAST(uint32_t, new_entry);
2422 }
2423 }
2424 if (best_fit_end != sorted_tagged_weights_end) {
2425 do {
2426 const uint64_t cur_heaproot = minheap64[0];
2427 uint64_t cur_tagged_weight = *sorted_tagged_weights_iter++;
2428 const uint32_t task_idx = S_CAST(uint32_t, cur_tagged_weight);
2429 uint32_t cur_thread = S_CAST(uint32_t, cur_heaproot);
2430 cur_tagged_weight &= 0xffffffff00000000LLU;
2431 uint64_t new_entry = cur_heaproot + cur_tagged_weight;
2432 if (new_entry > max_load_shifted) {
2433 if (thread_ct < orig_thread_ct) {
2434 thread_assignments[task_idx] = thread_ct;
2435 Minheap64Insert(cur_tagged_weight + thread_ct, minheap64_preroot, &thread_ct);
2436 continue;
2437 } else {
2438 max_load_shifted = new_entry | 0xffffffffLLU;
2439 }
2440 }
2441 thread_assignments[task_idx] = cur_thread;
2442 Minheap64ReplaceRoot(thread_ct, new_entry, minheap64_preroot);
2443 } while (sorted_tagged_weights_iter != sorted_tagged_weights_end);
2444 }
2445 BigstackReset(sorted_tagged_weights);
2446 *thread_ct_ptr = thread_ct;
2447 *max_load_ptr = max_load_shifted >> 32;
2448 return kPglRetSuccess;
2449 }
2450
2451 PglErr LdPruneWrite(const uintptr_t* variant_include, const uintptr_t* removed_variants_collapsed, const char* const* variant_ids, uint32_t variant_ct, char* outname, char* outname_end) {
2452 FILE* outfile = nullptr;
2453 PglErr reterr = kPglRetSuccess;
2454 {
2455 fputs("Writing...", stdout);
2456 fflush(stdout);
2457 snprintf(outname_end, kMaxOutfnameExtBlen, ".prune.in");
2458 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
2459 goto LdPruneWrite_ret_OPEN_FAIL;
2460 }
2461 char* write_iter = g_textbuf;
2462 char* textbuf_flush = &(write_iter[kMaxMediumLine]);
2463 uintptr_t variant_uidx_base = 0;
2464 uintptr_t cur_bits = variant_include[0];
2465 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
2466 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2467 if (IsSet(removed_variants_collapsed, variant_idx)) {
2468 continue;
2469 }
2470 write_iter = strcpya(write_iter, variant_ids[variant_uidx]);
2471 AppendBinaryEoln(&write_iter);
2472 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
2473 goto LdPruneWrite_ret_WRITE_FAIL;
2474 }
2475 }
2476 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
2477 goto LdPruneWrite_ret_WRITE_FAIL;
2478 }
2479
2480 snprintf(&(outname_end[7]), kMaxOutfnameExtBlen - 7, "out");
2481 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
2482 goto LdPruneWrite_ret_OPEN_FAIL;
2483 }
2484 write_iter = g_textbuf;
2485 variant_uidx_base = 0;
2486 cur_bits = variant_include[0];
2487 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
2488 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2489 if (!IsSet(removed_variants_collapsed, variant_idx)) {
2490 continue;
2491 }
2492 write_iter = strcpya(write_iter, variant_ids[variant_uidx]);
2493 AppendBinaryEoln(&write_iter);
2494 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
2495 goto LdPruneWrite_ret_WRITE_FAIL;
2496 }
2497 }
2498 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
2499 goto LdPruneWrite_ret_WRITE_FAIL;
2500 }
2501 *outname_end = '\0';
2502 putc_unlocked('\r', stdout);
2503 logprintfww("Variant lists written to %s.prune.in and %s.prune.out .\n", outname, outname);
2504 }
2505 while (0) {
2506 LdPruneWrite_ret_OPEN_FAIL:
2507 reterr = kPglRetOpenFail;
2508 break;
2509 LdPruneWrite_ret_WRITE_FAIL:
2510 reterr = kPglRetWriteFail;
2511 break;
2512 }
2513 fclose_cond(outfile);
2514 return reterr;
2515 }
2516
2517 PglErr LdPrune(const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const AlleleCode* maj_alleles, const double* allele_freqs, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const LdInfo* ldip, const char* indep_preferred_fname, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t nosex_ct, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
2518 // common initialization between --indep-pairwise and --indep-pairphase
2519 unsigned char* bigstack_mark = g_bigstack_base;
2520 unsigned char* bigstack_end_mark = g_bigstack_end;
2521 PglErr reterr = kPglRetSuccess;
2522 {
2523 const uint32_t is_pairphase = (ldip->prune_flags / kfLdPrunePairphase) & 1;
2524 if (founder_ct < 2) {
2525 logerrprintfww("Error: --indep-pair%s requires at least two founders. (--make-founders may come in handy here.)\n", is_pairphase? "phase" : "wise");
2526 goto LdPrune_ret_INCONSISTENT_INPUT;
2527 }
2528 uint32_t skipped_variant_ct;
2529 const uintptr_t* variant_include = StripUnplacedK(orig_variant_include, cip, raw_variant_ct, &skipped_variant_ct);
2530 if (unlikely(variant_include == nullptr)) {
2531 goto LdPrune_ret_NOMEM;
2532 }
2533 if (skipped_variant_ct) {
2534 logprintf("--indep-pair%s: Ignoring %u chromosome 0 variant%s.\n", is_pairphase? "phase" : "wise", skipped_variant_ct, (skipped_variant_ct == 1)? "" : "s");
2535 variant_ct -= skipped_variant_ct;
2536 }
2537
2538 if (!(ldip->prune_flags & kfLdPruneWindowBp)) {
2539 variant_bps = nullptr;
2540 }
2541 const uint32_t prune_window_size = ldip->prune_window_size;
2542 uint32_t* subcontig_info;
2543 uint32_t window_max;
2544 uint32_t subcontig_ct;
2545 if (LdPruneSubcontigSplitAll(variant_include, cip, variant_bps, prune_window_size, &window_max, &subcontig_info, &subcontig_ct)) {
2546 goto LdPrune_ret_NOMEM;
2547 }
2548 if (!subcontig_ct) {
2549 logerrprintf("Warning: Skipping --indep-pair%s since there are no pairs of variants to\nprocess.\n", is_pairphase? "phase" : "wise");
2550 goto LdPrune_ret_1;
2551 }
2552
2553 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
2554 uintptr_t* preferred_variants = nullptr;
2555 uint32_t dup_found;
2556 if (!indep_preferred_fname) {
2557 reterr = CheckIdUniqueness(g_bigstack_base, g_bigstack_end, variant_include, variant_ids, variant_ct, max_thread_ct, &dup_found);
2558 if (unlikely(reterr)) {
2559 goto LdPrune_ret_1;
2560 }
2561 } else {
2562 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &preferred_variants))) {
2563 goto LdPrune_ret_NOMEM;
2564 }
2565 memcpy(preferred_variants, variant_include, raw_variant_ctl * sizeof(intptr_t));
2566 reterr = NondupIdLoad(g_bigstack_base, g_bigstack_end, variant_ids, indep_preferred_fname, raw_variant_ct, variant_ct, max_thread_ct, preferred_variants, &dup_found, g_logbuf);
2567 if (unlikely(reterr)) {
2568 if (g_logbuf[0]) {
2569 logerrputsb();
2570 }
2571 goto LdPrune_ret_1;
2572 }
2573 }
2574 if (unlikely(dup_found)) {
2575 logerrprintfww("Error: --indep-pair%s requires unique variant IDs. (--set-all-var-ids and/or --rm-dup may help.)\n", is_pairphase? "phase" : "wise");
2576 goto LdPrune_ret_INCONSISTENT_INPUT;
2577 }
2578 if (preferred_variants) {
2579 const uint32_t preferred_variant_ct = PopcountWords(preferred_variants, raw_variant_ctl);
2580 logprintf("--indep-preferred: %u variant%s loaded.\n", preferred_variant_ct, (preferred_variant_ct == 1)? "" : "s");
2581 }
2582
2583 if (max_thread_ct > 2) {
2584 --max_thread_ct;
2585 }
2586 if (max_thread_ct > subcontig_ct) {
2587 max_thread_ct = subcontig_ct;
2588 }
2589 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
2590 const uint32_t variant_ctl = BitCtToWordCt(variant_ct);
2591 uint32_t* founder_info_cumulative_popcounts;
2592 // bugfix (25 Mar 2023, 25 Aug 2023): founder_nonmale/founder_male are NOT
2593 // supposed to be "collapsed".
2594 uintptr_t* founder_nonmale;
2595 uintptr_t* founder_male;
2596 uintptr_t* removed_variants_collapsed;
2597 uint32_t* subcontig_thread_assignments;
2598 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &founder_info_cumulative_popcounts) ||
2599 bigstack_alloc_w(raw_sample_ctl, &founder_nonmale) ||
2600 bigstack_alloc_w(raw_sample_ctl, &founder_male) ||
2601 bigstack_calloc_w(variant_ctl, &removed_variants_collapsed) ||
2602 bigstack_alloc_u32(subcontig_ct, &subcontig_thread_assignments))) {
2603 goto LdPrune_ret_NOMEM;
2604 }
2605 FillCumulativePopcounts(founder_info, raw_sample_ctl, founder_info_cumulative_popcounts);
2606 BitvecAndCopy(founder_info, sex_male, raw_sample_ctl, founder_male);
2607 BitvecInvmaskCopy(founder_info, sex_male, raw_sample_ctl, founder_nonmale);
2608 const uint32_t founder_male_ct = PopcountWords(founder_male, raw_sample_ctl);
2609 uintptr_t* founder_nonfemale = founder_male;
2610 uint32_t founder_nonfemale_ct = founder_male_ct;
2611 if (nosex_ct) {
2612 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &founder_nonfemale))) {
2613 goto LdPrune_ret_NOMEM;
2614 }
2615 AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, founder_nonfemale);
2616 BitvecAnd(founder_info, raw_sample_ctl, founder_nonfemale);
2617 founder_nonfemale_ct = PopcountWords(founder_nonfemale, raw_sample_ctl);
2618 }
2619 uint32_t* subcontig_weights;
2620 if (unlikely(bigstack_end_alloc_u32(subcontig_ct, &subcontig_weights))) {
2621 goto LdPrune_ret_NOMEM;
2622 }
2623
2624 // initial window_max-based memory requirement estimate
2625 const uint32_t plink1_order = (ldip->prune_flags / kfLdPrunePlink1Order) & 1;
2626 if (is_pairphase) {
2627 const uint32_t max_hap_ct = founder_ct * 2;
2628 const uintptr_t hap_ctaw_x2 = 2 * BitCtToAlignedWordCt(max_hap_ct);
2629 // reserve ~1/2 of space for main variant data buffer,
2630 // removed_variant_write
2631 // everything else:
2632 // hap_vecs + nm_vecs: thread_ct * window_max * hap_ctaw_x2 * word
2633 // occupied_window_slots: thread_ct * window_maxl * word
2634 // cur_window_removed: thread_ct * (1 + window_max / kBitsPerWord) *
2635 // word
2636 // (ignore removed_variant_write)
2637 // maj_freqs: thread_ct * window_max * 8
2638 // vhaggs: thread_ct * window_max * VariantHapAggs
2639 // winpos_to_slot_idx, tvidxs: window_max * 2 * int32
2640 // first_unchecked_tvidx: window_max * int32 if plink1_order
2641 uintptr_t per_thread_alloc = RoundUpPow2(window_max * hap_ctaw_x2 * sizeof(intptr_t), kCacheline) + 2 * RoundUpPow2((1 + window_max / kBitsPerWord) * sizeof(intptr_t), kCacheline) + RoundUpPow2(window_max * sizeof(double), kCacheline) + RoundUpPow2(window_max * sizeof(VariantHapAggs), kCacheline) + (2 + plink1_order) * RoundUpPow2(window_max * sizeof(int32_t), kCacheline);
2642 uintptr_t bigstack_left2 = bigstack_left();
2643 if (per_thread_alloc * max_thread_ct > bigstack_left2) {
2644 if (unlikely(per_thread_alloc > bigstack_left2)) {
2645 goto LdPrune_ret_NOMEM;
2646 }
2647 max_thread_ct = bigstack_left2 / per_thread_alloc;
2648 }
2649 } else {
2650 const uintptr_t entire_variant_buf_word_ct = 2 * (BitCtToAlignedWordCt(founder_ct - founder_male_ct) + BitCtToAlignedWordCt(founder_male_ct));
2651 // reserve ~1/2 of space for main variant data buffer,
2652 // removed_variant_write
2653 // everything else:
2654 // genobufs: thread_ct * window_max * entire_variant_buf_word_ct * word
2655 // occupied_window_slots: thread_ct * window_maxl * word
2656 // cur_window_removed: thread_ct * (1 + window_max / kBitsPerWord) *
2657 // word
2658 // (ignore removed_variant_write)
2659 // maj_freqs: thread_ct * window_max * 8
2660 // vaggs, nonmale_vaggs: thread_ct * window_max * VariantAggs
2661 // winpos_to_slot_idx, tvidxs: window_max * 2 * int32
2662 // first_unchecked_tvidx: window_max * int32 if plink1_order
2663 uintptr_t per_thread_alloc = RoundUpPow2(window_max * entire_variant_buf_word_ct * sizeof(intptr_t), kCacheline) + 2 * RoundUpPow2((1 + window_max / kBitsPerWord) * sizeof(intptr_t), kCacheline) + RoundUpPow2(window_max * sizeof(double), kCacheline) + 2 * RoundUpPow2(window_max * sizeof(VariantAggs), kCacheline) + (2 + plink1_order) * RoundUpPow2(window_max * sizeof(int32_t), kCacheline);
2664 uintptr_t bigstack_left2 = bigstack_left();
2665 if (per_thread_alloc * max_thread_ct > bigstack_left2) {
2666 if (unlikely(per_thread_alloc > bigstack_left2)) {
2667 goto LdPrune_ret_NOMEM;
2668 }
2669 max_thread_ct = bigstack_left2 / per_thread_alloc;
2670 }
2671 }
2672
2673
2674 for (uint32_t subcontig_idx = 0; subcontig_idx != subcontig_ct; ++subcontig_idx) {
2675 // todo: adjust chrX weights upward, and chrY downward
2676 subcontig_weights[subcontig_idx] = subcontig_info[3 * subcontig_idx];
2677 // printf("%u %u %u\n", subcontig_info[3 * subcontig_idx], subcontig_info[3 * subcontig_idx + 1], subcontig_info[3 * subcontig_idx + 2]);
2678 }
2679 uint32_t max_load = 0;
2680 if (unlikely(LoadBalance(subcontig_weights, subcontig_ct, &max_thread_ct, subcontig_thread_assignments, &max_load))) {
2681 goto LdPrune_ret_NOMEM;
2682 }
2683 BigstackEndReset(bigstack_end_mark);
2684
2685 if (is_pairphase) {
2686 reterr = IndepPairphase(variant_include, cip, variant_bps, allele_idx_offsets, maj_alleles, allele_freqs, founder_info, founder_info_cumulative_popcounts, founder_nonmale, founder_male, founder_nonfemale, ldip, preferred_variants, subcontig_info, subcontig_thread_assignments, raw_sample_ct, founder_ct, founder_male_ct, founder_nonfemale_ct, subcontig_ct, window_max, max_thread_ct, max_load, simple_pgrp, removed_variants_collapsed);
2687 } else {
2688 reterr = IndepPairwise(variant_include, cip, variant_bps, allele_idx_offsets, maj_alleles, allele_freqs, founder_info, founder_info_cumulative_popcounts, founder_nonmale, founder_male, founder_nonfemale, ldip, preferred_variants, subcontig_info, subcontig_thread_assignments, raw_sample_ct, founder_ct, founder_male_ct, founder_nonfemale_ct, subcontig_ct, window_max, max_thread_ct, max_load, simple_pgrp, removed_variants_collapsed);
2689 }
2690 if (unlikely(reterr)) {
2691 goto LdPrune_ret_1;
2692 }
2693 const uint32_t removed_ct = PopcountWords(removed_variants_collapsed, variant_ctl);
2694 logprintf("%u/%u variants removed.\n", removed_ct, variant_ct);
2695 reterr = LdPruneWrite(variant_include, removed_variants_collapsed, variant_ids, variant_ct, outname, outname_end);
2696 // if (unlikely(reterr)) {
2697 // goto LdPrune_ret_1;
2698 // }
2699 }
2700 while (0) {
2701 LdPrune_ret_NOMEM:
2702 reterr = kPglRetNomem;
2703 break;
2704 LdPrune_ret_INCONSISTENT_INPUT:
2705 reterr = kPglRetInconsistentInput;
2706 break;
2707 }
2708 LdPrune_ret_1:
2709 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
2710 return reterr;
2711 }
2712
2713
2714 // todo: see if this can also be usefully condensed into two bitarrays
2715 #if defined(USE_SSE2) && !defined(USE_AVX2)
2716 void GenoarrSplit12Nm(const uintptr_t* __restrict genoarr, uint32_t sample_ct, uintptr_t* __restrict one_bitarr, uintptr_t* __restrict two_bitarr, uintptr_t* __restrict nm_bitarr) {
2717 // ok if trailing bits of genoarr are not zeroed out
2718 // trailing bits of {one,two,nm}_bitarr are zeroed out
2719 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
2720 const uint32_t out_fullvec_ct = sample_ctl2 / (kWordsPerVec * 2);
2721 const VecW m1 = VCONST_W(kMask5555);
2722 # ifdef USE_SHUFFLE8
2723 const VecW swap12 = vecw_setr8(
2724 0, 1, 4, 5, 2, 3, 6, 7,
2725 8, 9, 12, 13, 10, 11, 14, 15);
2726 # else
2727 const VecW m2 = VCONST_W(kMask3333);
2728 # endif
2729 const VecW m4 = VCONST_W(kMask0F0F);
2730 const VecW m8 = VCONST_W(kMask00FF);
2731 for (uintptr_t vidx = 0; vidx != out_fullvec_ct; ++vidx) {
2732 const VecW vec_lo = vecw_loadu(&(genoarr[2 * kWordsPerVec * vidx]));
2733 const VecW vec_hi = vecw_loadu(&(genoarr[2 * kWordsPerVec * vidx + kWordsPerVec]));
2734 VecW inv0_lo = vecw_and_notfirst(vec_lo, m1);
2735 VecW inv0_hi = vecw_and_notfirst(vec_hi, m1);
2736 VecW inv1_lo = vecw_and_notfirst(vecw_srli(vec_lo, 1), m1);
2737 VecW inv1_hi = vecw_and_notfirst(vecw_srli(vec_hi, 1), m1);
2738 # ifdef USE_SHUFFLE8
2739 inv0_lo = (inv0_lo | vecw_srli(inv0_lo, 3)) & m4;
2740 inv0_hi = (inv0_hi | vecw_srli(inv0_hi, 3)) & m4;
2741 inv1_lo = (inv1_lo | vecw_srli(inv1_lo, 3)) & m4;
2742 inv1_hi = (inv1_hi | vecw_srli(inv1_hi, 3)) & m4;
2743 inv0_lo = vecw_shuffle8(swap12, inv0_lo);
2744 inv0_hi = vecw_shuffle8(swap12, inv0_hi);
2745 inv1_lo = vecw_shuffle8(swap12, inv1_lo);
2746 inv1_hi = vecw_shuffle8(swap12, inv1_hi);
2747 # else
2748 inv0_lo = (inv0_lo | vecw_srli(inv0_lo, 1)) & m2;
2749 inv0_hi = (inv0_hi | vecw_srli(inv0_hi, 1)) & m2;
2750 inv1_lo = (inv1_lo | vecw_srli(inv1_lo, 1)) & m2;
2751 inv1_hi = (inv1_hi | vecw_srli(inv1_hi, 1)) & m2;
2752 inv0_lo = (inv0_lo | vecw_srli(inv0_lo, 2)) & m4;
2753 inv0_hi = (inv0_hi | vecw_srli(inv0_hi, 2)) & m4;
2754 inv1_lo = (inv1_lo | vecw_srli(inv1_lo, 2)) & m4;
2755 inv1_hi = (inv1_hi | vecw_srli(inv1_hi, 2)) & m4;
2756 # endif
2757 inv0_lo = inv0_lo | vecw_srli(inv0_lo, 4);
2758 inv0_hi = inv0_hi | vecw_srli(inv0_hi, 4);
2759 inv1_lo = inv1_lo | vecw_srli(inv1_lo, 4);
2760 inv1_hi = inv1_hi | vecw_srli(inv1_hi, 4);
2761 const VecW inv0_packed = vecw_gather_even(inv0_lo, inv0_hi, m8);
2762 const VecW inv1_packed = vecw_gather_even(inv1_lo, inv1_hi, m8);
2763 const VecW one_packed = vecw_and_notfirst(inv0_packed, inv1_packed);
2764 const VecW two_packed = vecw_and_notfirst(inv1_packed, inv0_packed);
2765 const VecW nm_packed = inv0_packed | inv1_packed;
2766 vecw_storeu(&(one_bitarr[kWordsPerVec * vidx]), one_packed);
2767 vecw_storeu(&(two_bitarr[kWordsPerVec * vidx]), two_packed);
2768 vecw_storeu(&(nm_bitarr[kWordsPerVec * vidx]), nm_packed);
2769 }
2770 Halfword* one_bitarr_alias = R_CAST(Halfword*, one_bitarr);
2771 Halfword* two_bitarr_alias = R_CAST(Halfword*, two_bitarr);
2772 Halfword* nm_bitarr_alias = R_CAST(Halfword*, nm_bitarr);
2773 for (uint32_t widx = RoundDownPow2(sample_ctl2, kWordsPerVec * 2); widx != sample_ctl2; ++widx) {
2774 const uintptr_t cur_geno_word = genoarr[widx];
2775 const uint32_t low_halfword = PackWordToHalfwordMask5555(cur_geno_word);
2776 const uint32_t high_halfword = PackWordToHalfwordMaskAAAA(cur_geno_word);
2777 one_bitarr_alias[widx] = low_halfword & (~high_halfword);
2778 two_bitarr_alias[widx] = high_halfword & (~low_halfword);
2779 nm_bitarr_alias[widx] = ~(low_halfword & high_halfword);
2780 }
2781 const uint32_t sample_ct_rem = sample_ct % kBitsPerWord;
2782 if (sample_ct_rem) {
2783 const uint32_t last_widx = sample_ct / kBitsPerWord;
2784 const uintptr_t trailing_mask = (k1LU << sample_ct_rem) - 1;
2785 uintptr_t* __attribute__((may_alias)) one_bitarr_last = &(one_bitarr[last_widx]);
2786 uintptr_t* __attribute__((may_alias)) two_bitarr_last = &(two_bitarr[last_widx]);
2787 uintptr_t* __attribute__((may_alias)) nm_bitarr_last = &(nm_bitarr[last_widx]);
2788 *one_bitarr_last &= trailing_mask;
2789 *two_bitarr_last &= trailing_mask;
2790 *nm_bitarr_last &= trailing_mask;
2791 }
2792 }
2793 #else
2794 void GenoarrSplit12Nm(const uintptr_t* __restrict genoarr, uint32_t sample_ct, uintptr_t* __restrict one_bitarr, uintptr_t* __restrict two_bitarr, uintptr_t* __restrict nm_bitarr) {
2795 // ok if trailing bits of genoarr are not zeroed out
2796 // trailing bits of {one,two,nm}_bitarr are zeroed out
2797 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
2798 Halfword* one_bitarr_alias = R_CAST(Halfword*, one_bitarr);
2799 Halfword* two_bitarr_alias = R_CAST(Halfword*, two_bitarr);
2800 Halfword* nm_bitarr_alias = R_CAST(Halfword*, nm_bitarr);
2801 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
2802 const uintptr_t cur_geno_word = genoarr[widx];
2803 const uint32_t low_halfword = PackWordToHalfwordMask5555(cur_geno_word);
2804 const uint32_t high_halfword = PackWordToHalfwordMaskAAAA(cur_geno_word);
2805 one_bitarr_alias[widx] = low_halfword & (~high_halfword);
2806 two_bitarr_alias[widx] = high_halfword & (~low_halfword);
2807 nm_bitarr_alias[widx] = ~(low_halfword & high_halfword);
2808 }
2809
2810 const uint32_t sample_ct_rem = sample_ct % kBitsPerWord;
2811 if (sample_ct_rem) {
2812 const uint32_t last_widx = sample_ct / kBitsPerWord;
2813 const uintptr_t trailing_mask = (k1LU << sample_ct_rem) - 1;
2814 uintptr_t* __attribute__((may_alias)) one_bitarr_last = &(one_bitarr[last_widx]);
2815 uintptr_t* __attribute__((may_alias)) two_bitarr_last = &(two_bitarr[last_widx]);
2816 uintptr_t* __attribute__((may_alias)) nm_bitarr_last = &(nm_bitarr[last_widx]);
2817 *one_bitarr_last &= trailing_mask;
2818 *two_bitarr_last &= trailing_mask;
2819 *nm_bitarr_last &= trailing_mask;
2820 }
2821 }
2822 #endif
2823
2824 uint32_t GenoBitvecSumMain(const VecW* one_vvec, const VecW* two_vvec, uint32_t vec_ct) {
2825 // Analog of popcount_vecs.
2826 const VecW m0 = vecw_setzero(); // bugfix (15 Aug 2018)
2827 const VecW m1 = VCONST_W(kMask5555);
2828 const VecW m2 = VCONST_W(kMask3333);
2829 const VecW m4 = VCONST_W(kMask0F0F);
2830 const VecW* one_vvec_iter = one_vvec;
2831 const VecW* two_vvec_iter = two_vvec;
2832 VecW prev_sad_result = vecw_setzero();
2833 VecW acc = vecw_setzero();
2834 uint32_t cur_incr = 15;
2835 for (; ; vec_ct -= cur_incr) {
2836 if (vec_ct < 15) {
2837 if (!vec_ct) {
2838 acc = acc + prev_sad_result;
2839 return HsumW(acc);
2840 }
2841 cur_incr = vec_ct;
2842 }
2843 VecW inner_acc = vecw_setzero();
2844 const VecW* one_vvec_stop = &(one_vvec_iter[cur_incr]);
2845 do {
2846 VecW one_count = *one_vvec_iter++;
2847 VecW two_count = *two_vvec_iter++;
2848 one_count = one_count - (vecw_srli(one_count, 1) & m1);
2849 two_count = two_count - (vecw_srli(two_count, 1) & m1);
2850 one_count = (one_count & m2) + (vecw_srli(one_count, 2) & m2);
2851 two_count = (two_count & m2) + (vecw_srli(two_count, 2) & m2);
2852 // one_count and two_count now contain 4-bit partial bitcounts, each in
2853 // the range 0..4. finally enough room to compute
2854 // 2 * two_count + one_count
2855 // in parallel and add it to the accumulator.
2856 one_count = vecw_slli(two_count, 1) + one_count;
2857 inner_acc = inner_acc + (one_count & m4) + (vecw_srli(one_count, 4) & m4);
2858 } while (one_vvec_iter < one_vvec_stop);
2859 acc = acc + prev_sad_result;
2860 prev_sad_result = vecw_bytesum(inner_acc, m0);
2861 }
2862 }
2863
2864 uint32_t GenoBitvecSum(const uintptr_t* one_bitvec, const uintptr_t* two_bitvec, uint32_t word_ct) {
2865 // popcount(one_bitvec) + 2 * popcount(two_bitvec)
2866 uint32_t tot = 0;
2867 #ifdef __LP64__
2868 if (word_ct >= kWordsPerVec) {
2869 #endif
2870 const uint32_t remainder = word_ct % kWordsPerVec;
2871 const uint32_t main_block_word_ct = word_ct - remainder;
2872 word_ct = remainder;
2873 tot = GenoBitvecSumMain(R_CAST(const VecW*, one_bitvec), R_CAST(const VecW*, two_bitvec), main_block_word_ct / kWordsPerVec);
2874 #ifdef __LP64__
2875 one_bitvec = &(one_bitvec[main_block_word_ct]);
2876 two_bitvec = &(two_bitvec[main_block_word_ct]);
2877 }
2878 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
2879 tot += PopcountWord(one_bitvec[trailing_word_idx]) + 2 * PopcountWord(two_bitvec[trailing_word_idx]);
2880 }
2881 #endif
2882 return tot;
2883 }
2884
2885 uint32_t GenoBitvecSumSubsetMain(const VecW* subset_vvec, const VecW* one_vvec, const VecW* two_vvec, uint32_t vec_ct) {
2886 // Same as GenoBitvecSumMain(), just with an additional mask.
2887 const VecW m0 = vecw_setzero();
2888 const VecW m1 = VCONST_W(kMask5555);
2889 const VecW m2 = VCONST_W(kMask3333);
2890 const VecW m4 = VCONST_W(kMask0F0F);
2891 const VecW* subset_vvec_iter = subset_vvec;
2892 const VecW* one_vvec_iter = one_vvec;
2893 const VecW* two_vvec_iter = two_vvec;
2894 VecW prev_sad_result = vecw_setzero();
2895 VecW acc = vecw_setzero();
2896 uint32_t cur_incr = 15;
2897 for (; ; vec_ct -= cur_incr) {
2898 if (vec_ct < 15) {
2899 if (!vec_ct) {
2900 acc = acc + prev_sad_result;
2901 return HsumW(acc);
2902 }
2903 cur_incr = vec_ct;
2904 }
2905 VecW inner_acc = vecw_setzero();
2906 const VecW* subset_vvec_stop = &(subset_vvec_iter[cur_incr]);
2907 do {
2908 VecW maskv = *subset_vvec_iter++;
2909 VecW one_count = (*one_vvec_iter++) & maskv;
2910 VecW two_count = (*two_vvec_iter++) & maskv;
2911 one_count = one_count - (vecw_srli(one_count, 1) & m1);
2912 two_count = two_count - (vecw_srli(two_count, 1) & m1);
2913 one_count = (one_count & m2) + (vecw_srli(one_count, 2) & m2);
2914 two_count = (two_count & m2) + (vecw_srli(two_count, 2) & m2);
2915 one_count = vecw_slli(two_count, 1) + one_count;
2916 inner_acc = inner_acc + (one_count & m4) + (vecw_srli(one_count, 4) & m4);
2917 } while (subset_vvec_iter < subset_vvec_stop);
2918 acc = acc + prev_sad_result;
2919 prev_sad_result = vecw_bytesum(inner_acc, m0);
2920 }
2921 }
2922
2923 uint32_t GenoBitvecSumSubset(const uintptr_t* subset_mask, const uintptr_t* one_bitvec, const uintptr_t* two_bitvec, uint32_t word_ct) {
2924 // popcount(subset_mask & one_bitvec)
2925 // + 2 * popcount(subset_mask & two_bitvec)
2926 uint32_t tot = 0;
2927 #ifdef __LP64__
2928 if (word_ct >= kWordsPerVec) {
2929 #endif
2930 const uint32_t remainder = word_ct % kWordsPerVec;
2931 const uint32_t main_block_word_ct = word_ct - remainder;
2932 word_ct = remainder;
2933 tot = GenoBitvecSumSubsetMain(R_CAST(const VecW*, subset_mask), R_CAST(const VecW*, one_bitvec), R_CAST(const VecW*, two_bitvec), main_block_word_ct / kWordsPerVec);
2934 #ifdef __LP64__
2935 subset_mask = &(subset_mask[main_block_word_ct]);
2936 one_bitvec = &(one_bitvec[main_block_word_ct]);
2937 two_bitvec = &(two_bitvec[main_block_word_ct]);
2938 }
2939 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
2940 const uintptr_t subset_word = subset_mask[trailing_word_idx];
2941 tot += PopcountWord(subset_word & one_bitvec[trailing_word_idx]) + 2 * PopcountWord(subset_word & two_bitvec[trailing_word_idx]);
2942 }
2943 #endif
2944 return tot;
2945 }
2946
2947 // phased-hardcall r^2 computation:
2948 // definitely-known part of dot product is
2949 // popcount((one_bitvec0 & two_bitvec1) | (two_bitvec0 & one_bitvec1))
2950 // + popcount(two_bitvec0 & two_bitvec1) * 2
2951 // + possible phased-het-het term
2952 // possibly-unknown part is
2953 // popcount(one_bitvec0 & one_bitvec1) - phased-het-het count
2954 // when nm_bitvec0 isn't all-ones, also necessary to compute
2955 // popcount(nm_bitvec0 & one_bitvec1)
2956 // + popcount(nm_bitvec0 & two_bitvec1) * 2
2957 // analogous statement is true for nm_bitvec1
2958 // if both are incomplete, also need popcount of intersection (compute this
2959 // first and skip rest of computation when zero).
2960 //
2961 // for possibly-unknown part, --ld reports all solutions when multiple
2962 // solutions exist, everything else uses EM solution
2963
2964 void GenoBitvecPhasedDotprodMain(const VecW* one_vvec0, const VecW* two_vvec0, const VecW* one_vvec1, const VecW* two_vvec1, uint32_t vec_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict hethet_ct_ptr) {
2965 const VecW m1 = VCONST_W(kMask5555);
2966 const VecW m2 = VCONST_W(kMask3333);
2967 const VecW m4 = VCONST_W(kMask0F0F);
2968 const VecW* one_vvec0_iter = one_vvec0;
2969 const VecW* two_vvec0_iter = two_vvec0;
2970 const VecW* one_vvec1_iter = one_vvec1;
2971 const VecW* two_vvec1_iter = two_vvec1;
2972 VecW acc_dotprod = vecw_setzero();
2973 VecW acc_hethet = vecw_setzero();
2974 uint32_t cur_incr = 15;
2975 for (; ; vec_ct -= cur_incr) {
2976 if (vec_ct < 15) {
2977 if (!vec_ct) {
2978 *known_dotprod_ptr = HsumW(acc_dotprod);
2979 *hethet_ct_ptr = HsumW(acc_hethet);
2980 return;
2981 }
2982 cur_incr = vec_ct;
2983 }
2984 VecW inner_acc_dotprod = vecw_setzero();
2985 VecW inner_acc_hethet = vecw_setzero();
2986 const VecW* one_vvec0_stop = &(one_vvec0_iter[cur_incr]);
2987 do {
2988 VecW one_vword0 = *one_vvec0_iter++;
2989 VecW two_vword0 = *two_vvec0_iter++;
2990 VecW one_vword1 = *one_vvec1_iter++;
2991 VecW two_vword1 = *two_vvec1_iter++;
2992
2993 VecW dotprod_1x_bits = (one_vword0 & two_vword1) | (one_vword1 & two_vword0);
2994 VecW dotprod_2x_bits = two_vword0 & two_vword1;
2995 VecW hethet_bits = one_vword0 & one_vword1;
2996 dotprod_1x_bits = dotprod_1x_bits - (vecw_srli(dotprod_1x_bits, 1) & m1);
2997 dotprod_2x_bits = dotprod_2x_bits - (vecw_srli(dotprod_2x_bits, 1) & m1);
2998 hethet_bits = hethet_bits - (vecw_srli(hethet_bits, 1) & m1);
2999 dotprod_1x_bits = (dotprod_1x_bits & m2) + (vecw_srli(dotprod_1x_bits, 2) & m2);
3000 dotprod_2x_bits = (dotprod_2x_bits & m2) + (vecw_srli(dotprod_2x_bits, 2) & m2);
3001 hethet_bits = (hethet_bits & m2) + (vecw_srli(hethet_bits, 2) & m2);
3002
3003 // we now have 4-bit partial bitcounts in the range 0..4. finally have
3004 // enough room to compute 2 * dotprod_2x_bits + dotprod_1x_bits.
3005 dotprod_1x_bits = vecw_slli(dotprod_2x_bits, 1) + dotprod_1x_bits;
3006 inner_acc_hethet = inner_acc_hethet + ((hethet_bits + vecw_srli(hethet_bits, 4)) & m4);
3007 inner_acc_dotprod = inner_acc_dotprod + (dotprod_1x_bits & m4) + (vecw_srli(dotprod_1x_bits, 4) & m4);
3008 } while (one_vvec0_iter < one_vvec0_stop);
3009 const VecW m0 = vecw_setzero();
3010 acc_hethet = acc_hethet + vecw_bytesum(inner_acc_hethet, m0);
3011 acc_dotprod = acc_dotprod + vecw_bytesum(inner_acc_dotprod, m0);
3012 }
3013 }
3014
3015 void GenoBitvecPhasedDotprod(const uintptr_t* one_bitvec0, const uintptr_t* two_bitvec0, const uintptr_t* one_bitvec1, const uintptr_t* two_bitvec1, uint32_t word_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict hethet_ct_ptr) {
3016 // known_dotprod := popcount((one_bitvec0 & two_bitvec1) |
3017 // (two_bitvec0 & one_bitvec1)) +
3018 // 2 * popcount(two_bitvec0 & two_bitvec1)
3019 // hethet_ct := popcount(one_bitvec0 & one_bitvec1)
3020 uint32_t known_dotprod = 0;
3021 uint32_t hethet_ct = 0;
3022 #ifdef __LP64__
3023 if (word_ct >= kWordsPerVec) {
3024 #endif
3025 const uint32_t remainder = word_ct % kWordsPerVec;
3026 const uint32_t main_block_word_ct = word_ct - remainder;
3027 word_ct = remainder;
3028 GenoBitvecPhasedDotprodMain(R_CAST(const VecW*, one_bitvec0), R_CAST(const VecW*, two_bitvec0), R_CAST(const VecW*, one_bitvec1), R_CAST(const VecW*, two_bitvec1), main_block_word_ct / kWordsPerVec, &known_dotprod, &hethet_ct);
3029 #ifdef __LP64__
3030 one_bitvec0 = &(one_bitvec0[main_block_word_ct]);
3031 two_bitvec0 = &(two_bitvec0[main_block_word_ct]);
3032 one_bitvec1 = &(one_bitvec1[main_block_word_ct]);
3033 two_bitvec1 = &(two_bitvec1[main_block_word_ct]);
3034 }
3035 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
3036 const uintptr_t one_word0 = one_bitvec0[trailing_word_idx];
3037 const uintptr_t two_word0 = two_bitvec0[trailing_word_idx];
3038 const uintptr_t one_word1 = one_bitvec1[trailing_word_idx];
3039 const uintptr_t two_word1 = two_bitvec1[trailing_word_idx];
3040 known_dotprod += PopcountWord((one_word0 & two_word1) | (one_word1 & two_word0)) + 2 * PopcountWord(two_word0 & two_word1);
3041 hethet_ct += PopcountWord(one_word0 & one_word1);
3042 }
3043 #endif
3044 *known_dotprod_ptr = known_dotprod;
3045 *hethet_ct_ptr = hethet_ct;
3046 }
3047
3048 void GenoBitvecPhasedDotprodSubsetMain(const VecW* subset_vvec, const VecW* one_vvec0, const VecW* two_vvec0, const VecW* one_vvec1, const VecW* two_vvec1, uint32_t vec_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict hethet_ct_ptr) {
3049 const VecW m1 = VCONST_W(kMask5555);
3050 const VecW m2 = VCONST_W(kMask3333);
3051 const VecW m4 = VCONST_W(kMask0F0F);
3052 const VecW* subset_vvec_iter = subset_vvec;
3053 const VecW* one_vvec0_iter = one_vvec0;
3054 const VecW* two_vvec0_iter = two_vvec0;
3055 const VecW* one_vvec1_iter = one_vvec1;
3056 const VecW* two_vvec1_iter = two_vvec1;
3057 VecW acc_dotprod = vecw_setzero();
3058 VecW acc_hethet = vecw_setzero();
3059 uint32_t cur_incr = 15;
3060 for (; ; vec_ct -= cur_incr) {
3061 if (vec_ct < 15) {
3062 if (!vec_ct) {
3063 *known_dotprod_ptr = HsumW(acc_dotprod);
3064 *hethet_ct_ptr = HsumW(acc_hethet);
3065 return;
3066 }
3067 cur_incr = vec_ct;
3068 }
3069 VecW inner_acc_dotprod = vecw_setzero();
3070 VecW inner_acc_hethet = vecw_setzero();
3071 const VecW* one_vvec0_stop = &(one_vvec0_iter[cur_incr]);
3072 do {
3073 VecW subset_vword = *subset_vvec_iter++;
3074 VecW one_vword0 = (*one_vvec0_iter++) & subset_vword;
3075 VecW two_vword0 = (*two_vvec0_iter++) & subset_vword;
3076 VecW one_vword1 = *one_vvec1_iter++;
3077 VecW two_vword1 = *two_vvec1_iter++;
3078
3079 VecW dotprod_1x_bits = (one_vword0 & two_vword1) | (one_vword1 & two_vword0);
3080 VecW dotprod_2x_bits = two_vword0 & two_vword1;
3081 VecW hethet_bits = one_vword0 & one_vword1;
3082 dotprod_1x_bits = dotprod_1x_bits - (vecw_srli(dotprod_1x_bits, 1) & m1);
3083 dotprod_2x_bits = dotprod_2x_bits - (vecw_srli(dotprod_2x_bits, 1) & m1);
3084 hethet_bits = hethet_bits - (vecw_srli(hethet_bits, 1) & m1);
3085 dotprod_1x_bits = (dotprod_1x_bits & m2) + (vecw_srli(dotprod_1x_bits, 2) & m2);
3086 dotprod_2x_bits = (dotprod_2x_bits & m2) + (vecw_srli(dotprod_2x_bits, 2) & m2);
3087 hethet_bits = (hethet_bits & m2) + (vecw_srli(hethet_bits, 2) & m2);
3088
3089 // we now have 4-bit partial bitcounts in the range 0..4. finally have
3090 // enough room to compute 2 * dotprod_2x_bits + dotprod_1x_bits.
3091 dotprod_1x_bits = vecw_slli(dotprod_2x_bits, 1) + dotprod_1x_bits;
3092 inner_acc_hethet = inner_acc_hethet + ((hethet_bits + vecw_srli(hethet_bits, 4)) & m4);
3093 inner_acc_dotprod = inner_acc_dotprod + (dotprod_1x_bits & m4) + (vecw_srli(dotprod_1x_bits, 4) & m4);
3094 } while (one_vvec0_iter < one_vvec0_stop);
3095 const VecW m0 = vecw_setzero();
3096 acc_hethet = acc_hethet + vecw_bytesum(inner_acc_hethet, m0);
3097 acc_dotprod = acc_dotprod + vecw_bytesum(inner_acc_dotprod, m0);
3098 }
3099 }
3100
3101 void GenoBitvecPhasedDotprodSubset(const uintptr_t* subset_mask, const uintptr_t* one_bitvec0, const uintptr_t* two_bitvec0, const uintptr_t* one_bitvec1, const uintptr_t* two_bitvec1, uint32_t word_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict hethet_ct_ptr) {
3102 uint32_t known_dotprod = 0;
3103 uint32_t hethet_ct = 0;
3104 #ifdef __LP64__
3105 if (word_ct >= kWordsPerVec) {
3106 #endif
3107 const uint32_t remainder = word_ct % kWordsPerVec;
3108 const uint32_t main_block_word_ct = word_ct - remainder;
3109 word_ct = remainder;
3110 GenoBitvecPhasedDotprodSubsetMain(R_CAST(const VecW*, subset_mask), R_CAST(const VecW*, one_bitvec0), R_CAST(const VecW*, two_bitvec0), R_CAST(const VecW*, one_bitvec1), R_CAST(const VecW*, two_bitvec1), main_block_word_ct / kWordsPerVec, &known_dotprod, &hethet_ct);
3111 #ifdef __LP64__
3112 subset_mask = &(subset_mask[main_block_word_ct]);
3113 one_bitvec0 = &(one_bitvec0[main_block_word_ct]);
3114 two_bitvec0 = &(two_bitvec0[main_block_word_ct]);
3115 one_bitvec1 = &(one_bitvec1[main_block_word_ct]);
3116 two_bitvec1 = &(two_bitvec1[main_block_word_ct]);
3117 }
3118 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
3119 const uintptr_t subset_word = subset_mask[trailing_word_idx];
3120 const uintptr_t one_word0 = one_bitvec0[trailing_word_idx] & subset_word;
3121 const uintptr_t two_word0 = two_bitvec0[trailing_word_idx] & subset_word;
3122 const uintptr_t one_word1 = one_bitvec1[trailing_word_idx];
3123 const uintptr_t two_word1 = two_bitvec1[trailing_word_idx];
3124 known_dotprod += PopcountWord((one_word0 & two_word1) | (one_word1 & two_word0)) + 2 * PopcountWord(two_word0 & two_word1);
3125 hethet_ct += PopcountWord(one_word0 & one_word1);
3126 }
3127 #endif
3128 *known_dotprod_ptr = known_dotprod;
3129 *hethet_ct_ptr = hethet_ct;
3130 }
3131
3132 // nmaj_cts[] must be initialized to correct values for
3133 // no-missing-values-in-other-variant case.
3134 uint32_t HardcallPhasedR2Stats(const uintptr_t* one_bitvec0, const uintptr_t* two_bitvec0, const uintptr_t* nm_bitvec0, const uintptr_t* one_bitvec1, const uintptr_t* two_bitvec1, const uintptr_t* nm_bitvec1, uint32_t sample_ct, uint32_t nm_ct0, uint32_t nm_ct1, uint32_t* __restrict nmaj_cts, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict hethet_ct_ptr) {
3135 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
3136 uint32_t nm_intersection_ct;
3137 if ((nm_ct0 != sample_ct) && (nm_ct1 != sample_ct)) {
3138 nm_intersection_ct = PopcountWordsIntersect(nm_bitvec0, nm_bitvec1, sample_ctl);
3139 if (!nm_intersection_ct) {
3140 nmaj_cts[0] = 0;
3141 nmaj_cts[1] = 0;
3142 *known_dotprod_ptr = 0;
3143 *hethet_ct_ptr = 0;
3144 return 0;
3145 }
3146 } else {
3147 nm_intersection_ct = MINV(nm_ct0, nm_ct1);
3148 }
3149 if (nm_ct0 != nm_intersection_ct) {
3150 nmaj_cts[0] = GenoBitvecSumSubset(nm_bitvec1, one_bitvec0, two_bitvec0, sample_ctl);
3151 }
3152 if (nm_ct1 != nm_intersection_ct) {
3153 nmaj_cts[1] = GenoBitvecSumSubset(nm_bitvec0, one_bitvec1, two_bitvec1, sample_ctl);
3154 }
3155 GenoBitvecPhasedDotprod(one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, sample_ctl, known_dotprod_ptr, hethet_ct_ptr);
3156 return nm_intersection_ct;
3157 }
3158
3159 void HardcallPhasedR2RefineMain(const VecW* phasepresent0_vvec, const VecW* phaseinfo0_vvec, const VecW* phasepresent1_vvec, const VecW* phaseinfo1_vvec, uint32_t vec_ct, uint32_t* __restrict hethet_decr_ptr, uint32_t* __restrict not_dotprod_ptr) {
3160 // vec_ct must be a multiple of 3
3161 const VecW m1 = VCONST_W(kMask5555);
3162 const VecW m2 = VCONST_W(kMask3333);
3163 const VecW m4 = VCONST_W(kMask0F0F);
3164 const VecW* phasepresent0_vvec_iter = phasepresent0_vvec;
3165 const VecW* phaseinfo0_vvec_iter = phaseinfo0_vvec;
3166 const VecW* phasepresent1_vvec_iter = phasepresent1_vvec;
3167 const VecW* phaseinfo1_vvec_iter = phaseinfo1_vvec;
3168 VecW acc_hethet_decr = vecw_setzero();
3169 VecW acc_not_dotprod = vecw_setzero(); // like not_hotdog, but more useful
3170 uint32_t cur_incr = 30;
3171 for (; ; vec_ct -= cur_incr) {
3172 if (vec_ct < 30) {
3173 if (!vec_ct) {
3174 *hethet_decr_ptr = HsumW(acc_hethet_decr);
3175 *not_dotprod_ptr = HsumW(acc_not_dotprod);
3176 return;
3177 }
3178 cur_incr = vec_ct;
3179 }
3180 VecW inner_acc_hethet_decr = vecw_setzero();
3181 VecW inner_acc_not_dotprod = vecw_setzero();
3182 const VecW* phasepresent0_vvec_stop = &(phasepresent0_vvec_iter[cur_incr]);
3183 do {
3184 // todo: benchmark against simpler one-vec-at-a-time loop
3185 VecW mask1 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++);
3186 VecW mask2 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++);
3187 VecW mask_half1 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++);
3188 VecW mask_half2 = vecw_srli(mask_half1, 1) & m1;
3189 mask_half1 = mask_half1 & m1;
3190
3191 VecW not_dotprod_count1 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3192 VecW not_dotprod_count2 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3193 VecW not_dotprod_half1 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3194 // bugfix (4 Nov 2017): incorrectly had mask_half1 here
3195 VecW not_dotprod_half2 = vecw_srli(not_dotprod_half1, 1) & mask_half2;
3196 not_dotprod_count1 = not_dotprod_count1 & mask1;
3197 not_dotprod_count2 = not_dotprod_count2 & mask2;
3198 not_dotprod_half1 = not_dotprod_half1 & mask_half1;
3199
3200 mask1 = mask1 - (vecw_srli(mask1, 1) & m1);
3201 mask2 = mask2 - (vecw_srli(mask2, 1) & m1);
3202 not_dotprod_count1 = not_dotprod_count1 - (vecw_srli(not_dotprod_count1, 1) & m1);
3203 not_dotprod_count2 = not_dotprod_count2 - (vecw_srli(not_dotprod_count2, 1) & m1);
3204 mask1 = mask1 + mask_half1;
3205 mask2 = mask2 + mask_half2;
3206 not_dotprod_count1 = not_dotprod_count1 + not_dotprod_half1;
3207 not_dotprod_count2 = not_dotprod_count2 + not_dotprod_half2;
3208
3209 mask1 = (mask1 & m2) + (vecw_srli(mask1, 2) & m2);
3210 not_dotprod_count1 = (not_dotprod_count1 & m2) + (vecw_srli(not_dotprod_count1, 2) & m2);
3211 mask1 = mask1 + (mask2 & m2) + (vecw_srli(mask2, 2) & m2);
3212 not_dotprod_count1 = not_dotprod_count1 + (not_dotprod_count2 & m2) + (vecw_srli(not_dotprod_count2, 2) & m2);
3213
3214 inner_acc_hethet_decr = inner_acc_hethet_decr + (mask1 & m4) + (vecw_srli(mask1, 4) & m4);
3215 inner_acc_not_dotprod = inner_acc_not_dotprod + (not_dotprod_count1 & m4) + (vecw_srli(not_dotprod_count1, 4) & m4);
3216 } while (phasepresent0_vvec_iter < phasepresent0_vvec_stop);
3217 const VecW m0 = vecw_setzero();
3218 acc_hethet_decr = acc_hethet_decr + vecw_bytesum(inner_acc_hethet_decr, m0);
3219 acc_not_dotprod = acc_not_dotprod + vecw_bytesum(inner_acc_not_dotprod, m0);
3220 }
3221 }
3222
3223 // only needs to be called when hethet_ct > 0, phasepresent0_ct > 0, and
3224 // phasepresent1_ct > 0.
3225 void HardcallPhasedR2Refine(const uintptr_t* phasepresent0, const uintptr_t* phaseinfo0, const uintptr_t* phasepresent1, const uintptr_t* phaseinfo1, uint32_t word_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict unknown_hethet_ct_ptr) {
3226 // unknown_hethet_ct -= popcount(phasepresent0 & phasepresent1)
3227 // known_dotprod_ptr += popcount(phasepresent0 & phasepresent1 &
3228 // (~(phaseinfo0 ^ phaseinfo1)))
3229 uint32_t hethet_decr = 0;
3230 uint32_t not_dotprod = 0;
3231 if (word_ct >= 3 * kWordsPerVec) {
3232 const uint32_t remainder = word_ct % (3 * kWordsPerVec);
3233 const uint32_t main_block_word_ct = word_ct - remainder;
3234 word_ct = remainder;
3235 HardcallPhasedR2RefineMain(R_CAST(const VecW*, phasepresent0), R_CAST(const VecW*, phaseinfo0), R_CAST(const VecW*, phasepresent1), R_CAST(const VecW*, phaseinfo1), main_block_word_ct / kWordsPerVec, &hethet_decr, &not_dotprod);
3236 phasepresent0 = &(phasepresent0[main_block_word_ct]);
3237 phaseinfo0 = &(phaseinfo0[main_block_word_ct]);
3238 phasepresent1 = &(phasepresent1[main_block_word_ct]);
3239 phaseinfo1 = &(phaseinfo1[main_block_word_ct]);
3240 }
3241 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
3242 const uintptr_t mask = phasepresent0[trailing_word_idx] & phasepresent1[trailing_word_idx];
3243 const uintptr_t xor_word = phaseinfo0[trailing_word_idx] ^ phaseinfo1[trailing_word_idx];
3244 hethet_decr += PopcountWord(mask);
3245 not_dotprod += PopcountWord(mask & xor_word);
3246 }
3247 *known_dotprod_ptr += hethet_decr - not_dotprod;
3248 *unknown_hethet_ct_ptr -= hethet_decr;
3249 }
3250
3251 void HardcallPhasedR2RefineSubsetMain(const VecW* subset_vvec, const VecW* phasepresent0_vvec, const VecW* phaseinfo0_vvec, const VecW* phasepresent1_vvec, const VecW* phaseinfo1_vvec, uint32_t vec_ct, uint32_t* __restrict hethet_decr_ptr, uint32_t* __restrict not_dotprod_ptr) {
3252 // vec_ct must be a multiple of 3
3253 const VecW m1 = VCONST_W(kMask5555);
3254 const VecW m2 = VCONST_W(kMask3333);
3255 const VecW m4 = VCONST_W(kMask0F0F);
3256 const VecW* subset_vvec_iter = subset_vvec;
3257 const VecW* phasepresent0_vvec_iter = phasepresent0_vvec;
3258 const VecW* phaseinfo0_vvec_iter = phaseinfo0_vvec;
3259 const VecW* phasepresent1_vvec_iter = phasepresent1_vvec;
3260 const VecW* phaseinfo1_vvec_iter = phaseinfo1_vvec;
3261 VecW acc_hethet_decr = vecw_setzero();
3262 VecW acc_not_dotprod = vecw_setzero();
3263 uint32_t cur_incr = 30;
3264 for (; ; vec_ct -= cur_incr) {
3265 if (vec_ct < 30) {
3266 if (!vec_ct) {
3267 *hethet_decr_ptr = HsumW(acc_hethet_decr);
3268 *not_dotprod_ptr = HsumW(acc_not_dotprod);
3269 return;
3270 }
3271 cur_incr = vec_ct;
3272 }
3273 VecW inner_acc_hethet_decr = vecw_setzero();
3274 VecW inner_acc_not_dotprod = vecw_setzero();
3275 const VecW* phasepresent0_vvec_stop = &(phasepresent0_vvec_iter[cur_incr]);
3276 do {
3277 VecW mask1 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++) & (*subset_vvec_iter++);
3278 VecW mask2 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++) & (*subset_vvec_iter++);
3279 VecW mask_half1 = (*phasepresent0_vvec_iter++) & (*phasepresent1_vvec_iter++) & (*subset_vvec_iter++);
3280 VecW mask_half2 = vecw_srli(mask_half1, 1) & m1;
3281 mask_half1 = mask_half1 & m1;
3282
3283 VecW not_dotprod_count1 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3284 VecW not_dotprod_count2 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3285 VecW not_dotprod_half1 = (*phaseinfo0_vvec_iter++) ^ (*phaseinfo1_vvec_iter++);
3286 VecW not_dotprod_half2 = vecw_srli(not_dotprod_half1, 1) & mask_half2;
3287 not_dotprod_count1 = not_dotprod_count1 & mask1;
3288 not_dotprod_count2 = not_dotprod_count2 & mask2;
3289 not_dotprod_half1 = not_dotprod_half1 & mask_half1;
3290
3291 mask1 = mask1 - (vecw_srli(mask1, 1) & m1);
3292 mask2 = mask2 - (vecw_srli(mask2, 1) & m1);
3293 not_dotprod_count1 = not_dotprod_count1 - (vecw_srli(not_dotprod_count1, 1) & m1);
3294 not_dotprod_count2 = not_dotprod_count2 - (vecw_srli(not_dotprod_count2, 1) & m1);
3295 mask1 = mask1 + mask_half1;
3296 mask2 = mask2 + mask_half2;
3297 not_dotprod_count1 = not_dotprod_count1 + not_dotprod_half1;
3298 not_dotprod_count2 = not_dotprod_count2 + not_dotprod_half2;
3299
3300 mask1 = (mask1 & m2) + (vecw_srli(mask1, 2) & m2);
3301 not_dotprod_count1 = (not_dotprod_count1 & m2) + (vecw_srli(not_dotprod_count1, 2) & m2);
3302 mask1 = mask1 + (mask2 & m2) + (vecw_srli(mask2, 2) & m2);
3303 not_dotprod_count1 = not_dotprod_count1 + (not_dotprod_count2 & m2) + (vecw_srli(not_dotprod_count2, 2) & m2);
3304
3305 inner_acc_hethet_decr = inner_acc_hethet_decr + (mask1 & m4) + (vecw_srli(mask1, 4) & m4);
3306 inner_acc_not_dotprod = inner_acc_not_dotprod + (not_dotprod_count1 & m4) + (vecw_srli(not_dotprod_count1, 4) & m4);
3307 } while (phasepresent0_vvec_iter < phasepresent0_vvec_stop);
3308 const VecW m0 = vecw_setzero();
3309 acc_hethet_decr = acc_hethet_decr + vecw_bytesum(inner_acc_hethet_decr, m0);
3310 acc_not_dotprod = acc_not_dotprod + vecw_bytesum(inner_acc_not_dotprod, m0);
3311 }
3312 }
3313
3314 void HardcallPhasedR2RefineSubset(const uintptr_t* subset_mask, const uintptr_t* phasepresent0, const uintptr_t* phaseinfo0, const uintptr_t* phasepresent1, const uintptr_t* phaseinfo1, uint32_t word_ct, uint32_t* __restrict known_dotprod_ptr, uint32_t* __restrict unknown_hethet_ct_ptr) {
3315 uint32_t hethet_decr = 0;
3316 uint32_t not_dotprod = 0;
3317 if (word_ct >= 3 * kWordsPerVec) {
3318 const uint32_t remainder = word_ct % (3 * kWordsPerVec);
3319 const uint32_t main_block_word_ct = word_ct - remainder;
3320 word_ct = remainder;
3321 HardcallPhasedR2RefineSubsetMain(R_CAST(const VecW*, subset_mask), R_CAST(const VecW*, phasepresent0), R_CAST(const VecW*, phaseinfo0), R_CAST(const VecW*, phasepresent1), R_CAST(const VecW*, phaseinfo1), main_block_word_ct / kWordsPerVec, &hethet_decr, &not_dotprod);
3322 subset_mask = &(subset_mask[main_block_word_ct]);
3323 phasepresent0 = &(phasepresent0[main_block_word_ct]);
3324 phaseinfo0 = &(phaseinfo0[main_block_word_ct]);
3325 phasepresent1 = &(phasepresent1[main_block_word_ct]);
3326 phaseinfo1 = &(phaseinfo1[main_block_word_ct]);
3327 }
3328 for (uint32_t trailing_word_idx = 0; trailing_word_idx != word_ct; ++trailing_word_idx) {
3329 const uintptr_t mask = phasepresent0[trailing_word_idx] & phasepresent1[trailing_word_idx] & subset_mask[trailing_word_idx];
3330 const uintptr_t xor_word = phaseinfo0[trailing_word_idx] ^ phaseinfo1[trailing_word_idx];
3331 hethet_decr += PopcountWord(mask);
3332 not_dotprod += PopcountWord(mask & xor_word);
3333 }
3334 *known_dotprod_ptr += hethet_decr - not_dotprod;
3335 *unknown_hethet_ct_ptr -= hethet_decr;
3336 }
3337
3338 // (Phased-)dosage r^2:
3339 // 1. This must be defined such that, as the phased-dosages approach integers,
3340 // r^2 converges to the corresponding phased-hardcall value.
3341 // 2. We also want r^2 between a variant and itself to be 1 (unless we have no
3342 // data at all). Unfortunately, the formula used before 26 Oct 2023 did not
3343 // have this property.
3344 //
3345 // Suppose one unphased sample has dosage(var0)=0.2 and dosage(var1)=0.2.
3346 // We treat this as P(var0=0/0)=0.8, P(var0=0/1)=0.2,
3347 // P(var1=0/0)=0.8, P(var1=0/1)=0.2.
3348 // Previously, we treated the two variants as independent, acting as if
3349 // P(var0=0/0, var1=0/1) = 0.8 * 0.2, etc.; but that is incompatible with (2),
3350 // and generally contrary to the whole point of a LD estimate.
3351 // Revised computation has unknown-hethet frequency equal to the
3352 // min(P(var0=0/1), P(var1=0/1)) upper bound, and known-dotprod equal to the
3353 // corresponding max(0, P(var0=1/1) + P(var1=1/1) - 1) lower bound.
3354
3355 static_assert(sizeof(Dosage) == 2, "plink2_ld dosage-handling routines must be updated.");
3356 #ifdef __LP64__
3357 # ifdef USE_AVX2
3358 void FillDosageHet(const Dosage* dosage_vec, uint32_t dosagev_ct, Dosage* dosage_het) {
3359 const __m256i* dosage_vvec_iter = R_CAST(const __m256i*, dosage_vec);
3360 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
3361 const __m256i all_n32768 = _mm256_set1_epi16(0x8000);
3362 const __m256i all_n16384 = _mm256_set1_epi16(0xc000);
3363 # else
3364 const __m256i all_n32768 = _mm256_set1_epi64x(-0x7fff7fff7fff8000LL);
3365 const __m256i all_n16384 = _mm256_set1_epi64x(-0x3fff3fff3fff4000LL);
3366 # endif
3367 const __m256i all0 = _mm256_setzero_si256();
3368 const __m256i all1 = _mm256_cmpeq_epi16(all0, all0);
3369 // 0-16384: leave unchanged
3370 // 16385-32768: subtract from 32768
3371 // 65535: set to 0
3372
3373 // subtract from 0, cmp_epi16 to produce mask, add 32768
3374 __m256i* dosage_het_iter = R_CAST(__m256i*, dosage_het);
3375 for (uint32_t vec_idx = 0; vec_idx != dosagev_ct; ++vec_idx) {
3376 __m256i dosagev = *dosage_vvec_iter++;
3377
3378 __m256i cur_mask = _mm256_cmpeq_epi16(dosagev, all1);
3379 dosagev = _mm256_andnot_si256(cur_mask, dosagev); // 65535 -> 0
3380
3381 // xor with -32768 is same as subtracting it
3382 __m256i dosagev_opp = _mm256_xor_si256(dosagev, all_n32768);
3383 // anything > -16384 after this subtraction was originally >16384.
3384 // calling the original value x, we want to flip the sign of (x - 32768)
3385 cur_mask = _mm256_cmpgt_epi16(dosagev_opp, all_n16384);
3386 dosagev_opp = _mm256_and_si256(cur_mask, dosagev_opp);
3387
3388 // has the <= 16384 values
3389 dosagev = _mm256_andnot_si256(cur_mask, dosagev);
3390
3391 dosagev_opp = _mm256_sub_epi16(all0, dosagev_opp);
3392 *dosage_het_iter++ = _mm256_add_epi16(dosagev, dosagev_opp);
3393 }
3394 }
3395
3396 uint64_t DenseDosageSum(const Dosage* dosage_vec, uint32_t vec_ct) {
3397 // end of dosage_vec assumed to be missing-padded (0-padded also ok)
3398 const __m256i* dosage_vvec_iter = R_CAST(const __m256i*, dosage_vec);
3399 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3400 const __m256i all1 = _mm256_cmpeq_epi16(m16, m16);
3401 uint64_t sum = 0;
3402 for (uint32_t vecs_left = vec_ct; ; ) {
3403 __m256i sumv = _mm256_setzero_si256();
3404 const __m256i* dosage_vvec_stop;
3405 // individual values in [0..32768]
3406 // 32768 * 8191 * 16 dosages per __m256i = just under 2^32
3407 if (vecs_left < 8191) {
3408 if (!vecs_left) {
3409 return sum;
3410 }
3411 dosage_vvec_stop = &(dosage_vvec_iter[vecs_left]);
3412 vecs_left = 0;
3413 } else {
3414 dosage_vvec_stop = &(dosage_vvec_iter[8191]);
3415 vecs_left -= 8191;
3416 }
3417 do {
3418 __m256i dosagev = *dosage_vvec_iter++;
3419 __m256i invmask = _mm256_cmpeq_epi16(dosagev, all1);
3420 dosagev = _mm256_andnot_si256(invmask, dosagev);
3421
3422 dosagev = _mm256_add_epi64(_mm256_and_si256(dosagev, m16), _mm256_and_si256(_mm256_srli_epi64(dosagev, 16), m16));
3423 sumv = _mm256_add_epi64(sumv, dosagev);
3424 } while (dosage_vvec_iter < dosage_vvec_stop);
3425 UniVec acc;
3426 acc.vw = R_CAST(VecW, sumv);
3427 sum += UniVecHsum32(acc);
3428 }
3429 }
3430
3431 uint64_t DenseDosageSumSubset(const Dosage* dosage_vec, const Dosage* dosage_mask_vec, uint32_t vec_ct) {
3432 // end of dosage_vec assumed to be missing-padded (0-padded also ok)
3433 const __m256i* dosage_vvec_iter = R_CAST(const __m256i*, dosage_vec);
3434 const __m256i* dosage_mask_vvec_iter = R_CAST(const __m256i*, dosage_mask_vec);
3435 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3436 const __m256i all1 = _mm256_cmpeq_epi16(m16, m16);
3437 uint64_t sum = 0;
3438 for (uint32_t vecs_left = vec_ct; ; ) {
3439 __m256i sumv = _mm256_setzero_si256();
3440 const __m256i* dosage_vvec_stop;
3441 if (vecs_left < 8191) {
3442 if (!vecs_left) {
3443 return sum;
3444 }
3445 dosage_vvec_stop = &(dosage_vvec_iter[vecs_left]);
3446 vecs_left = 0;
3447 } else {
3448 dosage_vvec_stop = &(dosage_vvec_iter[8191]);
3449 vecs_left -= 8191;
3450 }
3451 do {
3452 __m256i invmask = *dosage_mask_vvec_iter++;
3453 __m256i dosagev = *dosage_vvec_iter++;
3454 invmask = _mm256_cmpeq_epi16(invmask, all1);
3455 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosagev, all1));
3456 dosagev = _mm256_andnot_si256(invmask, dosagev);
3457
3458 dosagev = _mm256_add_epi64(_mm256_and_si256(dosagev, m16), _mm256_and_si256(_mm256_srli_epi64(dosagev, 16), m16));
3459 sumv = _mm256_add_epi64(sumv, dosagev);
3460 } while (dosage_vvec_iter < dosage_vvec_stop);
3461 UniVec acc;
3462 acc.vw = R_CAST(VecW, sumv);
3463 sum += UniVecHsum32(acc);
3464 }
3465 }
3466
3467 // 65535 treated as missing
3468 uint64_t DosageUnsignedDotprod(const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
3469 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3470 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3471 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3472 const __m256i all1 = _mm256_cmpeq_epi16(m16, m16);
3473 uint64_t dotprod = 0;
3474 for (uint32_t vecs_left = vec_ct; ; ) {
3475 __m256i dotprod_lo = _mm256_setzero_si256();
3476 __m256i dotprod_hi = _mm256_setzero_si256();
3477 const __m256i* dosage_vvec0_stop;
3478 // Products in [0..2^30]; dotprod_lo part is in 0..65535, dotprod_hi part
3479 // is in 0..16384.
3480 // 65535 * 4096 * 16 dosages per __m256i = just under 2^32
3481 if (vecs_left < 4096) {
3482 if (!vecs_left) {
3483 return dotprod;
3484 }
3485 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3486 vecs_left = 0;
3487 } else {
3488 dosage_vvec0_stop = &(dosage_vvec0_iter[4096]);
3489 vecs_left -= 4096;
3490 }
3491 do {
3492 __m256i dosage0 = *dosage_vvec0_iter++;
3493 __m256i dosage1 = *dosage_vvec1_iter++;
3494 __m256i invmask = _mm256_cmpeq_epi16(dosage0, all1);
3495 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage1, all1));
3496 dosage0 = _mm256_andnot_si256(invmask, dosage0);
3497 dosage1 = _mm256_andnot_si256(invmask, dosage1);
3498
3499 // todo: try rewriting this loop without 256-bit multiplication, to avoid
3500 // ~15% universal clock frequency slowdown (128-bit? sparse?)
3501 __m256i lo16 = _mm256_mullo_epi16(dosage0, dosage1);
3502 __m256i hi16 = _mm256_mulhi_epu16(dosage0, dosage1);
3503 lo16 = _mm256_add_epi64(_mm256_and_si256(lo16, m16), _mm256_and_si256(_mm256_srli_epi64(lo16, 16), m16));
3504 hi16 = _mm256_and_si256(_mm256_add_epi64(hi16, _mm256_srli_epi64(hi16, 16)), m16);
3505 dotprod_lo = _mm256_add_epi64(dotprod_lo, lo16);
3506 dotprod_hi = _mm256_add_epi64(dotprod_hi, hi16);
3507 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3508 UniVec acc_lo;
3509 UniVec acc_hi;
3510 acc_lo.vw = R_CAST(VecW, dotprod_lo);
3511 acc_hi.vw = R_CAST(VecW, dotprod_hi);
3512 dotprod += UniVecHsum32(acc_lo) + 65536 * UniVecHsum32(acc_hi);
3513 }
3514 }
3515
3516 uint64_t DosageUnsignedDotprodSubset(const Dosage* dosage_mask_vec, const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
3517 const __m256i* dosage_mask_iter = R_CAST(const __m256i*, dosage_mask_vec);
3518 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3519 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3520 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3521 const __m256i all1 = _mm256_cmpeq_epi16(m16, m16);
3522 uint64_t dotprod = 0;
3523 for (uint32_t vecs_left = vec_ct; ; ) {
3524 __m256i dotprod_lo = _mm256_setzero_si256();
3525 __m256i dotprod_hi = _mm256_setzero_si256();
3526 const __m256i* dosage_vvec0_stop;
3527 if (vecs_left < 4096) {
3528 if (!vecs_left) {
3529 return dotprod;
3530 }
3531 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3532 vecs_left = 0;
3533 } else {
3534 dosage_vvec0_stop = &(dosage_vvec0_iter[4096]);
3535 vecs_left -= 4096;
3536 }
3537 do {
3538 __m256i cur_mask = *dosage_mask_iter++;
3539 __m256i dosage0 = *dosage_vvec0_iter++;
3540 __m256i dosage1 = *dosage_vvec1_iter++;
3541 __m256i invmask = _mm256_cmpeq_epi16(dosage0, all1);
3542 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage1, all1));
3543 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(cur_mask, all1));
3544 dosage0 = _mm256_andnot_si256(invmask, dosage0);
3545 dosage1 = _mm256_andnot_si256(invmask, dosage1);
3546
3547 // todo: try rewriting this loop without 256-bit multiplication, to avoid
3548 // ~15% universal clock frequency slowdown (128-bit? sparse?)
3549 __m256i lo16 = _mm256_mullo_epi16(dosage0, dosage1);
3550 __m256i hi16 = _mm256_mulhi_epu16(dosage0, dosage1);
3551 lo16 = _mm256_add_epi64(_mm256_and_si256(lo16, m16), _mm256_and_si256(_mm256_srli_epi64(lo16, 16), m16));
3552 hi16 = _mm256_and_si256(_mm256_add_epi64(hi16, _mm256_srli_epi64(hi16, 16)), m16);
3553 dotprod_lo = _mm256_add_epi64(dotprod_lo, lo16);
3554 dotprod_hi = _mm256_add_epi64(dotprod_hi, hi16);
3555 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3556 UniVec acc_lo;
3557 UniVec acc_hi;
3558 acc_lo.vw = R_CAST(VecW, dotprod_lo);
3559 acc_hi.vw = R_CAST(VecW, dotprod_hi);
3560 dotprod += UniVecHsum32(acc_lo) + 65536 * UniVecHsum32(acc_hi);
3561 }
3562 }
3563
3564 void DosageUnphasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
3565 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3566 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3567 const __m256i* dosage_het0_iter = R_CAST(const __m256i*, dosage_het0);
3568 const __m256i* dosage_het1_iter = R_CAST(const __m256i*, dosage_het1);
3569 const __m256i all_32767 = _mm256_set1_epi16(0x7fff);
3570 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3571 const __m256i all0 = _mm256_setzero_si256();
3572 const __m256i all1 = _mm256_cmpeq_epi16(all0, all0);
3573 uint64_t uhethet_dosage = 0;
3574 uint64_t known_dotprod = 0;
3575 for (uint32_t vecs_left = vec_ct; ; ) {
3576 __m256i uhethet_sumv = _mm256_setzero_si256();
3577 __m256i dotprod_sumv = _mm256_setzero_si256();
3578 const __m256i* dosage_vvec0_stop;
3579 // individual dotprod_incr values in [0..32768]
3580 // 32768 * 8191 * 16 dosages per __m256i = just under 2^32
3581 if (vecs_left < 8191) {
3582 if (!vecs_left) {
3583 *known_dotprod_dosagep = known_dotprod * 2;
3584 *uhethet_dosagep = uhethet_dosage * 2;
3585 return;
3586 }
3587 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3588 vecs_left = 0;
3589 } else {
3590 dosage_vvec0_stop = &(dosage_vvec0_iter[8191]);
3591 vecs_left -= 8191;
3592 }
3593 do {
3594 // We wish to compute max(0, dosage0 + dosage1 - 32768), where dosage0
3595 // and dosage1 are uint16s in {0..32768, 65535}, where 65535 corresponds
3596 // to a missing value.
3597 // An annoying property of this computation is that
3598 // (dosage0 + dosage1 - 32768) ranges from -32768 to 32768, which just
3599 // barely exceeds the range of a (u)int16.
3600 // We work around this by observing that dosage0==0 can be treated as if
3601 // it were a missing value: it is impossible for dosage0 + dosage1 -
3602 // 32768 to exceed 0 if dosage0 is 0. With that case made ignorable,
3603 // (dosage0 + dosage1 - 32769) is then in the -32768..32767 int16 range,
3604 // so we compute 1 + max(-1, dosage0 + dosage1 - 32769) and then apply
3605 // our augmented mask.
3606 const __m256i dosage0_plus_32767 = _mm256_add_epi16(*dosage_vvec0_iter++, all_32767);
3607 const __m256i dosage1 = *dosage_vvec1_iter++;
3608 const __m256i het0 = *dosage_het0_iter++;
3609 const __m256i het1 = *dosage_het1_iter++;
3610 // Conveniently, dosage0 + 32767 > 0 in int16 space iff dosage0 is
3611 // missing or zero.
3612 const __m256i invmask = _mm256_or_si256(_mm256_cmpgt_epi16(dosage0_plus_32767, all0), _mm256_cmpeq_epi16(dosage1, all1));
3613 // No need to mask this, het0 or het1 is already equal to 0 when there's
3614 // a missing value.
3615 __m256i uhethet_incr = _mm256_min_epi16(het0, het1);
3616 // Adding 32767 and subtracting 32769 are equivalent in vector int16
3617 // space. (Though they're not equivalent when working with single
3618 // int16_ts!)
3619 const __m256i dosagesum_m32769 = _mm256_add_epi16(dosage0_plus_32767, dosage1);
3620 const __m256i unmasked_dotprod_incr = _mm256_sub_epi16(_mm256_max_epi16(dosagesum_m32769, all1), all1);
3621 __m256i dotprod_incr = _mm256_andnot_si256(invmask, unmasked_dotprod_incr);
3622
3623 uhethet_incr = _mm256_and_si256(_mm256_add_epi64(uhethet_incr, _mm256_srli_epi64(uhethet_incr, 16)), m16);
3624 dotprod_incr = _mm256_add_epi64(_mm256_and_si256(dotprod_incr, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incr, 16), m16));
3625 uhethet_sumv = _mm256_add_epi64(uhethet_sumv, uhethet_incr);
3626 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incr);
3627 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3628 UniVec uhethet_acc;
3629 UniVec dotprod_acc;
3630 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
3631 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
3632 uhethet_dosage += UniVecHsum32(uhethet_acc);
3633 known_dotprod += UniVecHsum32(dotprod_acc);
3634 }
3635 }
3636
3637 void DosageUnphasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
3638 const __m256i* invmask_iter = R_CAST(const __m256i*, subset_invmask);
3639 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3640 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3641 const __m256i* dosage_het0_iter = R_CAST(const __m256i*, dosage_het0);
3642 const __m256i* dosage_het1_iter = R_CAST(const __m256i*, dosage_het1);
3643 const __m256i all_32767 = _mm256_set1_epi16(0x7fff);
3644 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3645 const __m256i all0 = _mm256_setzero_si256();
3646 const __m256i all1 = _mm256_cmpeq_epi16(all0, all0);
3647 uint64_t uhethet_dosage = 0;
3648 uint64_t known_dotprod = 0;
3649 for (uint32_t vecs_left = vec_ct; ; ) {
3650 __m256i uhethet_sumv = _mm256_setzero_si256();
3651 __m256i dotprod_sumv = _mm256_setzero_si256();
3652 const __m256i* dosage_vvec0_stop;
3653 if (vecs_left < 8191) {
3654 if (!vecs_left) {
3655 *known_dotprod_dosagep = known_dotprod * 2;
3656 *uhethet_dosagep = uhethet_dosage * 2;
3657 return;
3658 }
3659 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3660 vecs_left = 0;
3661 } else {
3662 dosage_vvec0_stop = &(dosage_vvec0_iter[8191]);
3663 vecs_left -= 8191;
3664 }
3665 do {
3666 const __m256i raw_invmask = *invmask_iter++;
3667 const __m256i dosage0_plus_32767 = _mm256_add_epi16(*dosage_vvec0_iter++, all_32767);
3668 const __m256i dosage1 = *dosage_vvec1_iter++;
3669 const __m256i het0 = *dosage_het0_iter++;
3670 const __m256i het1 = *dosage_het1_iter++;
3671 __m256i uhethet_incr = _mm256_andnot_si256(raw_invmask, _mm256_min_epi16(het0, het1));
3672 __m256i invmask = _mm256_or_si256(raw_invmask, _mm256_cmpgt_epi16(dosage0_plus_32767, all0));
3673 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage1, all1));
3674 const __m256i dosagesum_m32769 = _mm256_add_epi16(dosage0_plus_32767, dosage1);
3675 const __m256i unmasked_dotprod_incr = _mm256_sub_epi16(_mm256_max_epi16(dosagesum_m32769, all1), all1);
3676 __m256i dotprod_incr = _mm256_andnot_si256(invmask, unmasked_dotprod_incr);
3677
3678 uhethet_incr = _mm256_and_si256(_mm256_add_epi64(uhethet_incr, _mm256_srli_epi64(uhethet_incr, 16)), m16);
3679 dotprod_incr = _mm256_add_epi64(_mm256_and_si256(dotprod_incr, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incr, 16), m16));
3680 uhethet_sumv = _mm256_add_epi64(uhethet_sumv, uhethet_incr);
3681 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incr);
3682 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3683 UniVec uhethet_acc;
3684 UniVec dotprod_acc;
3685 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
3686 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
3687 uhethet_dosage += UniVecHsum32(uhethet_acc);
3688 known_dotprod += UniVecHsum32(dotprod_acc);
3689 }
3690 }
3691
3692 void DosagePhasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
3693 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3694 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3695 const __m256i* dphase_delta0_iter = R_CAST(const __m256i*, dphase_delta0);
3696 const __m256i* dphase_delta1_iter = R_CAST(const __m256i*, dphase_delta1);
3697 const __m256i all_16384 = _mm256_set1_epi16(0x4000);
3698 const __m256i all_32767 = _mm256_set1_epi16(0x7fff);
3699 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
3700 const __m256i all_n32768 = _mm256_set1_epi16(0x8000);
3701 # else
3702 const __m256i all_n32768 = _mm256_set1_epi64x(-0x7fff7fff7fff8000LL);
3703 # endif
3704 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3705 const __m256i all0 = _mm256_setzero_si256();
3706 const __m256i all1 = _mm256_cmpeq_epi16(all0, all0);
3707 uint64_t uhethet_dosage = 0;
3708 uint64_t known_dotprod = 0;
3709 for (uint32_t vecs_left = vec_ct; ; ) {
3710 __m256i uhethet_sumv = _mm256_setzero_si256();
3711 __m256i dotprod_sumv = _mm256_setzero_si256();
3712 const __m256i* dosage_vvec0_stop;
3713 // dotprod_incrA and dotprod_incrB values in [0..32768]
3714 // 65536 * 4095 * 16 dosages per __m256i = just under 2^32
3715 if (vecs_left < 4095) {
3716 if (!vecs_left) {
3717 *known_dotprod_dosagep = known_dotprod;
3718 *uhethet_dosagep = uhethet_dosage;
3719 return;
3720 }
3721 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3722 vecs_left = 0;
3723 } else {
3724 dosage_vvec0_stop = &(dosage_vvec0_iter[4095]);
3725 vecs_left -= 4095;
3726 }
3727 do {
3728 const __m256i dosage0 = *dosage_vvec0_iter++;
3729 const __m256i dosage1 = *dosage_vvec1_iter++;
3730 const __m256i delta0 = *dphase_delta0_iter++;
3731 const __m256i delta1 = *dphase_delta1_iter++;
3732 const __m256i invmask = _mm256_or_si256(_mm256_cmpeq_epi16(dosage0, all1), _mm256_cmpeq_epi16(dosage1, all1));
3733 const __m256i dosage0A = _mm256_add_epi16(dosage0, delta0);
3734 const __m256i dosage1A = _mm256_add_epi16(dosage1, delta1);
3735 const __m256i dosage0B = _mm256_sub_epi16(dosage0, delta0);
3736 const __m256i dosage1B = _mm256_sub_epi16(dosage1, delta1);
3737 const __m256i dosageA_m32769 = _mm256_add_epi16(_mm256_add_epi16(dosage0A, dosage1A), all_32767);
3738 const __m256i dosageB_m32769 = _mm256_add_epi16(_mm256_add_epi16(dosage0B, dosage1B), all_32767);
3739 const __m256i invmaskA = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage0A, all0));
3740 const __m256i invmaskB = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage0B, all0));
3741 const __m256i unmasked_dotprod_incrA = _mm256_sub_epi16(_mm256_max_epi16(dosageA_m32769, all1), all1);
3742 const __m256i unmasked_dotprod_incrB = _mm256_sub_epi16(_mm256_max_epi16(dosageB_m32769, all1), all1);
3743 __m256i dotprod_incrA = _mm256_andnot_si256(invmaskA, unmasked_dotprod_incrA);
3744 __m256i dotprod_incrB = _mm256_andnot_si256(invmaskB, unmasked_dotprod_incrB);
3745 dotprod_incrA = _mm256_add_epi64(_mm256_and_si256(dotprod_incrA, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incrA, 16), m16));
3746 dotprod_incrB = _mm256_add_epi64(_mm256_and_si256(dotprod_incrB, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incrB, 16), m16));
3747 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incrA);
3748 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incrB);
3749
3750 const __m256i known0A = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage0A));
3751 const __m256i known1A = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage1A));
3752 const __m256i known0B = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage0B));
3753 const __m256i known1B = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage1B));
3754 const __m256i maxknownA = _mm256_max_epi16(known0A, known1A);
3755 const __m256i maxknownB = _mm256_max_epi16(known0B, known1B);
3756 __m256i uhethet_incr = _mm256_andnot_si256(invmask, _mm256_sub_epi16(all_n32768, _mm256_add_epi16(maxknownA, maxknownB)));
3757 uhethet_incr = _mm256_add_epi64(_mm256_and_si256(uhethet_incr, m16), _mm256_and_si256(_mm256_srli_epi64(uhethet_incr, 16), m16));
3758 uhethet_sumv = _mm256_add_epi64(uhethet_sumv, uhethet_incr);
3759 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3760 UniVec dotprod_acc;
3761 UniVec uhethet_acc;
3762 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
3763 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
3764 known_dotprod += UniVecHsum32(dotprod_acc);
3765 uhethet_dosage += UniVecHsum32(uhethet_acc);
3766 }
3767 }
3768
3769 void DosagePhasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
3770 const __m256i* invmask_iter = R_CAST(const __m256i*, subset_invmask);
3771 const __m256i* dosage_vvec0_iter = R_CAST(const __m256i*, dosage_vec0);
3772 const __m256i* dosage_vvec1_iter = R_CAST(const __m256i*, dosage_vec1);
3773 const __m256i* dphase_delta0_iter = R_CAST(const __m256i*, dphase_delta0);
3774 const __m256i* dphase_delta1_iter = R_CAST(const __m256i*, dphase_delta1);
3775 const __m256i all_16384 = _mm256_set1_epi16(0x4000);
3776 const __m256i all_32767 = _mm256_set1_epi16(0x7fff);
3777 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
3778 const __m256i all_n32768 = _mm256_set1_epi16(0x8000);
3779 # else
3780 const __m256i all_n32768 = _mm256_set1_epi64x(-0x7fff7fff7fff8000LL);
3781 # endif
3782 const __m256i m16 = _mm256_set1_epi64x(kMask0000FFFF);
3783 const __m256i all0 = _mm256_setzero_si256();
3784 const __m256i all1 = _mm256_cmpeq_epi16(all0, all0);
3785 uint64_t uhethet_dosage = 0;
3786 uint64_t known_dotprod = 0;
3787 for (uint32_t vecs_left = vec_ct; ; ) {
3788 __m256i uhethet_sumv = _mm256_setzero_si256();
3789 __m256i dotprod_sumv = _mm256_setzero_si256();
3790 const __m256i* dosage_vvec0_stop;
3791 if (vecs_left < 4095) {
3792 if (!vecs_left) {
3793 *known_dotprod_dosagep = known_dotprod;
3794 *uhethet_dosagep = uhethet_dosage;
3795 return;
3796 }
3797 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3798 vecs_left = 0;
3799 } else {
3800 dosage_vvec0_stop = &(dosage_vvec0_iter[4095]);
3801 vecs_left -= 4095;
3802 }
3803 do {
3804 __m256i invmask = *invmask_iter++;
3805 const __m256i dosage0 = *dosage_vvec0_iter++;
3806 const __m256i dosage1 = *dosage_vvec1_iter++;
3807 const __m256i delta0 = *dphase_delta0_iter++;
3808 const __m256i delta1 = *dphase_delta1_iter++;
3809 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage0, all1));
3810 invmask = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage1, all1));
3811 const __m256i dosage0A = _mm256_add_epi16(dosage0, delta0);
3812 const __m256i dosage1A = _mm256_add_epi16(dosage1, delta1);
3813 const __m256i dosage0B = _mm256_sub_epi16(dosage0, delta0);
3814 const __m256i dosage1B = _mm256_sub_epi16(dosage1, delta1);
3815 const __m256i dosageA_m32769 = _mm256_add_epi16(_mm256_add_epi16(dosage0A, dosage1A), all_32767);
3816 const __m256i dosageB_m32769 = _mm256_add_epi16(_mm256_add_epi16(dosage0B, dosage1B), all_32767);
3817 const __m256i invmaskA = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage0A, all0));
3818 const __m256i invmaskB = _mm256_or_si256(invmask, _mm256_cmpeq_epi16(dosage0B, all0));
3819 const __m256i unmasked_dotprod_incrA = _mm256_sub_epi16(_mm256_max_epi16(dosageA_m32769, all1), all1);
3820 const __m256i unmasked_dotprod_incrB = _mm256_sub_epi16(_mm256_max_epi16(dosageB_m32769, all1), all1);
3821 __m256i dotprod_incrA = _mm256_andnot_si256(invmaskA, unmasked_dotprod_incrA);
3822 __m256i dotprod_incrB = _mm256_andnot_si256(invmaskB, unmasked_dotprod_incrB);
3823 dotprod_incrA = _mm256_add_epi64(_mm256_and_si256(dotprod_incrA, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incrA, 16), m16));
3824 dotprod_incrB = _mm256_add_epi64(_mm256_and_si256(dotprod_incrB, m16), _mm256_and_si256(_mm256_srli_epi64(dotprod_incrB, 16), m16));
3825 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incrA);
3826 dotprod_sumv = _mm256_add_epi64(dotprod_sumv, dotprod_incrB);
3827
3828 const __m256i known0A = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage0A));
3829 const __m256i known1A = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage1A));
3830 const __m256i known0B = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage0B));
3831 const __m256i known1B = _mm256_abs_epi16(_mm256_sub_epi16(all_16384, dosage1B));
3832 const __m256i maxknownA = _mm256_max_epi16(known0A, known1A);
3833 const __m256i maxknownB = _mm256_max_epi16(known0B, known1B);
3834 __m256i uhethet_incr = _mm256_andnot_si256(invmask, _mm256_sub_epi16(all_n32768, _mm256_add_epi16(maxknownA, maxknownB)));
3835 uhethet_incr = _mm256_add_epi64(_mm256_and_si256(uhethet_incr, m16), _mm256_and_si256(_mm256_srli_epi64(uhethet_incr, 16), m16));
3836 uhethet_sumv = _mm256_add_epi64(uhethet_sumv, uhethet_incr);
3837 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3838 UniVec dotprod_acc;
3839 UniVec uhethet_acc;
3840 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
3841 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
3842 known_dotprod += UniVecHsum32(dotprod_acc);
3843 uhethet_dosage += UniVecHsum32(uhethet_acc);
3844 }
3845 }
3846 # else // !USE_AVX2
3847 void FillDosageHet(const Dosage* dosage_vec, uint32_t dosagev_ct, Dosage* dosage_het) {
3848 const __m128i* dosage_vvec_iter = R_CAST(const __m128i*, dosage_vec);
3849 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
3850 const __m128i all_n32768 = _mm_set1_epi16(0x8000);
3851 const __m128i all_n16384 = _mm_set1_epi16(0xc000);
3852 # else
3853 const __m128i all_n32768 = _mm_set1_epi64x(-0x7fff7fff7fff8000LL);
3854 const __m128i all_n16384 = _mm_set1_epi64x(-0x3fff3fff3fff4000LL);
3855 # endif
3856 const __m128i all0 = _mm_setzero_si128();
3857 const __m128i all1 = _mm_cmpeq_epi16(all0, all0);
3858 // 0-16384: leave unchanged
3859 // 16385-32768: subtract from 32768
3860 // 65535: set to 0
3861
3862 // subtract from 0, _mm_cmplt_epi16 to produce mask, add 32768
3863 __m128i* dosage_het_iter = R_CAST(__m128i*, dosage_het);
3864 for (uint32_t vec_idx = 0; vec_idx != dosagev_ct; ++vec_idx) {
3865 __m128i dosagev = *dosage_vvec_iter++;
3866
3867 __m128i cur_mask = _mm_cmpeq_epi16(dosagev, all1);
3868 dosagev = _mm_andnot_si128(cur_mask, dosagev); // 65535 -> 0
3869
3870 // xor with -32768 is same as subtracting it
3871 __m128i dosagev_opp = _mm_xor_si128(dosagev, all_n32768);
3872 // anything > -16384 after this subtraction was originally >16384.
3873 // calling the original value x, we want to flip the sign of (x - 32768)
3874 cur_mask = _mm_cmpgt_epi16(dosagev_opp, all_n16384);
3875 dosagev_opp = _mm_and_si128(cur_mask, dosagev_opp);
3876 dosagev = _mm_andnot_si128(cur_mask, dosagev); // has the <= 16384 values
3877 dosagev_opp = _mm_sub_epi16(all0, dosagev_opp);
3878 *dosage_het_iter++ = _mm_add_epi16(dosagev, dosagev_opp);
3879 }
3880 }
3881
3882 uint64_t DenseDosageSum(const Dosage* dosage_vec, uint32_t vec_ct) {
3883 // end of dosage_vec assumed to be missing-padded (0-padded also ok)
3884 const __m128i* dosage_vvec_iter = R_CAST(const __m128i*, dosage_vec);
3885 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
3886 const __m128i all1 = _mm_cmpeq_epi16(m16, m16);
3887 uint64_t sum = 0;
3888 for (uint32_t vecs_left = vec_ct; ; ) {
3889 __m128i sumv = _mm_setzero_si128();
3890 const __m128i* dosage_vvec_stop;
3891 // individual values in [0..32768]
3892 // 32768 * 16383 * 8 dosages per __m128i = just under 2^32
3893 if (vecs_left < 16383) {
3894 if (!vecs_left) {
3895 return sum;
3896 }
3897 dosage_vvec_stop = &(dosage_vvec_iter[vecs_left]);
3898 vecs_left = 0;
3899 } else {
3900 dosage_vvec_stop = &(dosage_vvec_iter[16383]);
3901 vecs_left -= 16383;
3902 }
3903 do {
3904 __m128i dosagev = *dosage_vvec_iter++;
3905 __m128i invmask = _mm_cmpeq_epi16(dosagev, all1);
3906 dosagev = _mm_andnot_si128(invmask, dosagev);
3907
3908 dosagev = _mm_add_epi64(_mm_and_si128(dosagev, m16), _mm_and_si128(_mm_srli_epi64(dosagev, 16), m16));
3909 sumv = _mm_add_epi64(sumv, dosagev);
3910 } while (dosage_vvec_iter < dosage_vvec_stop);
3911 UniVec acc;
3912 acc.vw = R_CAST(VecW, sumv);
3913 sum += UniVecHsum32(acc);
3914 }
3915 }
3916
3917 uint64_t DenseDosageSumSubset(const Dosage* dosage_vec, const Dosage* dosage_mask_vec, uint32_t vec_ct) {
3918 // end of dosage_vec assumed to be missing-padded (0-padded also ok)
3919 const __m128i* dosage_vvec_iter = R_CAST(const __m128i*, dosage_vec);
3920 const __m128i* dosage_mask_vvec_iter = R_CAST(const __m128i*, dosage_mask_vec);
3921 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
3922 const __m128i all1 = _mm_cmpeq_epi16(m16, m16);
3923 uint64_t sum = 0;
3924 for (uint32_t vecs_left = vec_ct; ; ) {
3925 __m128i sumv = _mm_setzero_si128();
3926 const __m128i* dosage_vvec_stop;
3927 if (vecs_left < 16383) {
3928 if (!vecs_left) {
3929 return sum;
3930 }
3931 dosage_vvec_stop = &(dosage_vvec_iter[vecs_left]);
3932 vecs_left = 0;
3933 } else {
3934 dosage_vvec_stop = &(dosage_vvec_iter[16383]);
3935 vecs_left -= 16383;
3936 }
3937 do {
3938 __m128i invmask = *dosage_mask_vvec_iter++;
3939 __m128i dosagev = *dosage_vvec_iter++;
3940 invmask = _mm_cmpeq_epi16(invmask, all1);
3941 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosagev, all1));
3942 dosagev = _mm_andnot_si128(invmask, dosagev);
3943
3944 dosagev = _mm_add_epi64(_mm_and_si128(dosagev, m16), _mm_and_si128(_mm_srli_epi64(dosagev, 16), m16));
3945 sumv = _mm_add_epi64(sumv, dosagev);
3946 } while (dosage_vvec_iter < dosage_vvec_stop);
3947 UniVec acc;
3948 acc.vw = R_CAST(VecW, sumv);
3949 sum += UniVecHsum32(acc);
3950 }
3951 }
3952
3953 // 65535 treated as missing
3954 uint64_t DosageUnsignedDotprod(const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
3955 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
3956 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
3957 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
3958 const __m128i all1 = _mm_cmpeq_epi16(m16, m16);
3959 uint64_t dotprod = 0;
3960 for (uint32_t vecs_left = vec_ct; ; ) {
3961 __m128i dotprod_lo = _mm_setzero_si128();
3962 __m128i dotprod_hi = _mm_setzero_si128();
3963 const __m128i* dosage_vvec0_stop;
3964 if (vecs_left < 8192) {
3965 if (!vecs_left) {
3966 return dotprod;
3967 }
3968 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
3969 vecs_left = 0;
3970 } else {
3971 dosage_vvec0_stop = &(dosage_vvec0_iter[8192]);
3972 vecs_left -= 8192;
3973 }
3974 do {
3975 __m128i dosage0 = *dosage_vvec0_iter++;
3976 __m128i dosage1 = *dosage_vvec1_iter++;
3977 __m128i invmask = _mm_cmpeq_epi16(dosage0, all1);
3978 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage1, all1));
3979 dosage0 = _mm_andnot_si128(invmask, dosage0);
3980 dosage1 = _mm_andnot_si128(invmask, dosage1);
3981
3982 __m128i lo16 = _mm_mullo_epi16(dosage0, dosage1);
3983 __m128i hi16 = _mm_mulhi_epu16(dosage0, dosage1);
3984 lo16 = _mm_add_epi64(_mm_and_si128(lo16, m16), _mm_and_si128(_mm_srli_epi64(lo16, 16), m16));
3985 hi16 = _mm_and_si128(_mm_add_epi64(hi16, _mm_srli_epi64(hi16, 16)), m16);
3986 dotprod_lo = _mm_add_epi64(dotprod_lo, lo16);
3987 dotprod_hi = _mm_add_epi64(dotprod_hi, hi16);
3988 } while (dosage_vvec0_iter < dosage_vvec0_stop);
3989 UniVec acc_lo;
3990 UniVec acc_hi;
3991 acc_lo.vw = R_CAST(VecW, dotprod_lo);
3992 acc_hi.vw = R_CAST(VecW, dotprod_hi);
3993 dotprod += UniVecHsum32(acc_lo) + 65536 * UniVecHsum32(acc_hi);
3994 }
3995 }
3996
3997 uint64_t DosageUnsignedDotprodSubset(const Dosage* dosage_mask_vec, const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
3998 const __m128i* dosage_mask_iter = R_CAST(const __m128i*, dosage_mask_vec);
3999 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
4000 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
4001 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
4002 const __m128i all1 = _mm_cmpeq_epi16(m16, m16);
4003 uint64_t dotprod = 0;
4004 for (uint32_t vecs_left = vec_ct; ; ) {
4005 __m128i dotprod_lo = _mm_setzero_si128();
4006 __m128i dotprod_hi = _mm_setzero_si128();
4007 const __m128i* dosage_vvec0_stop;
4008 if (vecs_left < 8192) {
4009 if (!vecs_left) {
4010 return dotprod;
4011 }
4012 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
4013 vecs_left = 0;
4014 } else {
4015 dosage_vvec0_stop = &(dosage_vvec0_iter[8192]);
4016 vecs_left -= 8192;
4017 }
4018 do {
4019 __m128i cur_mask = *dosage_mask_iter++;
4020 __m128i dosage0 = *dosage_vvec0_iter++;
4021 __m128i dosage1 = *dosage_vvec1_iter++;
4022 __m128i invmask = _mm_cmpeq_epi16(dosage0, all1);
4023 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage1, all1));
4024 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(cur_mask, all1));
4025 dosage0 = _mm_andnot_si128(invmask, dosage0);
4026 dosage1 = _mm_andnot_si128(invmask, dosage1);
4027
4028 __m128i lo16 = _mm_mullo_epi16(dosage0, dosage1);
4029 __m128i hi16 = _mm_mulhi_epu16(dosage0, dosage1);
4030 lo16 = _mm_add_epi64(_mm_and_si128(lo16, m16), _mm_and_si128(_mm_srli_epi64(lo16, 16), m16));
4031 hi16 = _mm_and_si128(_mm_add_epi64(hi16, _mm_srli_epi64(hi16, 16)), m16);
4032 dotprod_lo = _mm_add_epi64(dotprod_lo, lo16);
4033 dotprod_hi = _mm_add_epi64(dotprod_hi, hi16);
4034 } while (dosage_vvec0_iter < dosage_vvec0_stop);
4035 UniVec acc_lo;
4036 UniVec acc_hi;
4037 acc_lo.vw = R_CAST(VecW, dotprod_lo);
4038 acc_hi.vw = R_CAST(VecW, dotprod_hi);
4039 dotprod += UniVecHsum32(acc_lo) + 65536 * UniVecHsum32(acc_hi);
4040 }
4041 }
4042
4043 void DosageUnphasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4044 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
4045 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
4046 const __m128i* dosage_het0_iter = R_CAST(const __m128i*, dosage_het0);
4047 const __m128i* dosage_het1_iter = R_CAST(const __m128i*, dosage_het1);
4048 const __m128i all_32767 = _mm_set1_epi16(0x7fff);
4049 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
4050 const __m128i all0 = _mm_setzero_si128();
4051 const __m128i all1 = _mm_cmpeq_epi16(all0, all0);
4052 uint64_t uhethet_dosage = 0;
4053 uint64_t known_dotprod = 0;
4054 for (uint32_t vecs_left = vec_ct; ; ) {
4055 __m128i uhethet_sumv = _mm_setzero_si128();
4056 __m128i dotprod_sumv = _mm_setzero_si128();
4057 const __m128i* dosage_vvec0_stop;
4058 if (vecs_left < 16383) {
4059 if (!vecs_left) {
4060 *known_dotprod_dosagep = known_dotprod * 2;
4061 *uhethet_dosagep = uhethet_dosage * 2;
4062 return;
4063 }
4064 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
4065 vecs_left = 0;
4066 } else {
4067 dosage_vvec0_stop = &(dosage_vvec0_iter[16383]);
4068 vecs_left -= 16383;
4069 }
4070 do {
4071 const __m128i dosage0_plus_32767 = _mm_add_epi16(*dosage_vvec0_iter++, all_32767);
4072 const __m128i dosage1 = *dosage_vvec1_iter++;
4073 const __m128i het0 = *dosage_het0_iter++;
4074 const __m128i het1 = *dosage_het1_iter++;
4075 const __m128i invmask = _mm_or_si128(_mm_cmpgt_epi16(dosage0_plus_32767, all0), _mm_cmpeq_epi16(dosage1, all1));
4076 __m128i uhethet_incr = _mm_min_epi16(het0, het1);
4077 const __m128i dosagesum_m32769 = _mm_add_epi16(dosage0_plus_32767, dosage1);
4078 const __m128i unmasked_dotprod_incr = _mm_sub_epi16(_mm_max_epi16(dosagesum_m32769, all1), all1);
4079 __m128i dotprod_incr = _mm_andnot_si128(invmask, unmasked_dotprod_incr);
4080
4081 uhethet_incr = _mm_and_si128(_mm_add_epi64(uhethet_incr, _mm_srli_epi64(uhethet_incr, 16)), m16);
4082 dotprod_incr = _mm_add_epi64(_mm_and_si128(dotprod_incr, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incr, 16), m16));
4083 uhethet_sumv = _mm_add_epi64(uhethet_sumv, uhethet_incr);
4084 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incr);
4085 } while (dosage_vvec0_iter < dosage_vvec0_stop);
4086 UniVec uhethet_acc;
4087 UniVec dotprod_acc;
4088 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
4089 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
4090 uhethet_dosage += UniVecHsum32(uhethet_acc);
4091 known_dotprod += UniVecHsum32(dotprod_acc);
4092 }
4093 }
4094
4095 void DosageUnphasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4096 const __m128i* invmask_iter = R_CAST(const __m128i*, subset_invmask);
4097 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
4098 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
4099 const __m128i* dosage_het0_iter = R_CAST(const __m128i*, dosage_het0);
4100 const __m128i* dosage_het1_iter = R_CAST(const __m128i*, dosage_het1);
4101 const __m128i all_32767 = _mm_set1_epi16(0x7fff);
4102 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
4103 const __m128i all0 = _mm_setzero_si128();
4104 const __m128i all1 = _mm_cmpeq_epi16(all0, all0);
4105 uint64_t uhethet_dosage = 0;
4106 uint64_t known_dotprod = 0;
4107 for (uint32_t vecs_left = vec_ct; ; ) {
4108 __m128i uhethet_sumv = _mm_setzero_si128();
4109 __m128i dotprod_sumv = _mm_setzero_si128();
4110 const __m128i* dosage_vvec0_stop;
4111 if (vecs_left < 16383) {
4112 if (!vecs_left) {
4113 *known_dotprod_dosagep = known_dotprod * 2;
4114 *uhethet_dosagep = uhethet_dosage * 2;
4115 return;
4116 }
4117 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
4118 vecs_left = 0;
4119 } else {
4120 dosage_vvec0_stop = &(dosage_vvec0_iter[16383]);
4121 vecs_left -= 16383;
4122 }
4123 do {
4124 const __m128i raw_invmask = *invmask_iter++;
4125 const __m128i dosage0_plus_32767 = _mm_add_epi16(*dosage_vvec0_iter++, all_32767);
4126 const __m128i dosage1 = *dosage_vvec1_iter++;
4127 const __m128i het0 = *dosage_het0_iter++;
4128 const __m128i het1 = *dosage_het1_iter++;
4129 __m128i uhethet_incr = _mm_andnot_si128(raw_invmask, _mm_min_epi16(het0, het1));
4130 __m128i invmask = _mm_or_si128(raw_invmask, _mm_cmpgt_epi16(dosage0_plus_32767, all0));
4131 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage1, all1));
4132 const __m128i dosagesum_m32769 = _mm_add_epi16(dosage0_plus_32767, dosage1);
4133 const __m128i unmasked_dotprod_incr = _mm_sub_epi16(_mm_max_epi16(dosagesum_m32769, all1), all1);
4134 __m128i dotprod_incr = _mm_andnot_si128(invmask, unmasked_dotprod_incr);
4135
4136 uhethet_incr = _mm_and_si128(_mm_add_epi64(uhethet_incr, _mm_srli_epi64(uhethet_incr, 16)), m16);
4137 dotprod_incr = _mm_add_epi64(_mm_and_si128(dotprod_incr, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incr, 16), m16));
4138 uhethet_sumv = _mm_add_epi64(uhethet_sumv, uhethet_incr);
4139 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incr);
4140 } while (dosage_vvec0_iter < dosage_vvec0_stop);
4141 UniVec uhethet_acc;
4142 UniVec dotprod_acc;
4143 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
4144 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
4145 uhethet_dosage += UniVecHsum32(uhethet_acc);
4146 known_dotprod += UniVecHsum32(dotprod_acc);
4147 }
4148 }
4149
4150 void DosagePhasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4151 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
4152 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
4153 const __m128i* dphase_delta0_iter = R_CAST(const __m128i*, dphase_delta0);
4154 const __m128i* dphase_delta1_iter = R_CAST(const __m128i*, dphase_delta1);
4155 const __m128i all_16384 = _mm_set1_epi16(0x4000);
4156 const __m128i all_32767 = _mm_set1_epi16(0x7fff);
4157 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
4158 const __m128i all_n32768 = _mm_set1_epi16(0x8000);
4159 # else
4160 const __m128i all_n32768 = _mm_set1_epi64x(-0x7fff7fff7fff8000LL);
4161 # endif
4162 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
4163 const __m128i all0 = _mm_setzero_si128();
4164 const __m128i all1 = _mm_cmpeq_epi16(all0, all0);
4165 uint64_t known_dotprod = 0;
4166 uint64_t uhethet_dosage = 0;
4167 for (uint32_t vecs_left = vec_ct; ; ) {
4168 __m128i dotprod_sumv = _mm_setzero_si128();
4169 __m128i uhethet_sumv = _mm_setzero_si128();
4170 const __m128i* dosage_vvec0_stop;
4171 if (vecs_left < 8191) {
4172 if (!vecs_left) {
4173 *known_dotprod_dosagep = known_dotprod;
4174 *uhethet_dosagep = uhethet_dosage;
4175 return;
4176 }
4177 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
4178 vecs_left = 0;
4179 } else {
4180 dosage_vvec0_stop = &(dosage_vvec0_iter[8191]);
4181 vecs_left -= 8191;
4182 }
4183 do {
4184 const __m128i dosage0 = *dosage_vvec0_iter++;
4185 const __m128i dosage1 = *dosage_vvec1_iter++;
4186 const __m128i delta0 = *dphase_delta0_iter++;
4187 const __m128i delta1 = *dphase_delta1_iter++;
4188 const __m128i invmask = _mm_or_si128(_mm_cmpeq_epi16(dosage0, all1), _mm_cmpeq_epi16(dosage1, all1));
4189 const __m128i dosage0A = _mm_add_epi16(dosage0, delta0);
4190 const __m128i dosage1A = _mm_add_epi16(dosage1, delta1);
4191 const __m128i dosage0B = _mm_sub_epi16(dosage0, delta0);
4192 const __m128i dosage1B = _mm_sub_epi16(dosage1, delta1);
4193 const __m128i dosageA_m32769 = _mm_add_epi16(_mm_add_epi16(dosage0A, dosage1A), all_32767);
4194 const __m128i dosageB_m32769 = _mm_add_epi16(_mm_add_epi16(dosage0B, dosage1B), all_32767);
4195 const __m128i invmaskA = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage0A, all0));
4196 const __m128i invmaskB = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage0B, all0));
4197 const __m128i unmasked_dotprod_incrA = _mm_sub_epi16(_mm_max_epi16(dosageA_m32769, all1), all1);
4198 const __m128i unmasked_dotprod_incrB = _mm_sub_epi16(_mm_max_epi16(dosageB_m32769, all1), all1);
4199 __m128i dotprod_incrA = _mm_andnot_si128(invmaskA, unmasked_dotprod_incrA);
4200 __m128i dotprod_incrB = _mm_andnot_si128(invmaskB, unmasked_dotprod_incrB);
4201 dotprod_incrA = _mm_add_epi64(_mm_and_si128(dotprod_incrA, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incrA, 16), m16));
4202 dotprod_incrB = _mm_add_epi64(_mm_and_si128(dotprod_incrB, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incrB, 16), m16));
4203 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incrA);
4204 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incrB);
4205
4206 # ifdef USE_SSE42
4207 const __m128i known0A = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage0A));
4208 const __m128i known1A = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage1A));
4209 const __m128i known0B = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage0B));
4210 const __m128i known1B = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage1B));
4211 # else
4212 const __m128i pos0A = _mm_sub_epi16(all_16384, dosage0A);
4213 const __m128i neg0A = _mm_sub_epi16(dosage0A, all_16384);
4214 const __m128i pos1A = _mm_sub_epi16(all_16384, dosage1A);
4215 const __m128i neg1A = _mm_sub_epi16(dosage1A, all_16384);
4216 const __m128i pos0B = _mm_sub_epi16(all_16384, dosage0B);
4217 const __m128i neg0B = _mm_sub_epi16(dosage0B, all_16384);
4218 const __m128i pos1B = _mm_sub_epi16(all_16384, dosage1B);
4219 const __m128i neg1B = _mm_sub_epi16(dosage1B, all_16384);
4220 const __m128i known0A = _mm_max_epi16(pos0A, neg0A);
4221 const __m128i known1A = _mm_max_epi16(pos1A, neg1A);
4222 const __m128i known0B = _mm_max_epi16(pos0B, neg0B);
4223 const __m128i known1B = _mm_max_epi16(pos1B, neg1B);
4224 # endif
4225 const __m128i maxknownA = _mm_max_epi16(known0A, known1A);
4226 const __m128i maxknownB = _mm_max_epi16(known0B, known1B);
4227 __m128i uhethet_incr = _mm_andnot_si128(invmask, _mm_sub_epi16(all_n32768, _mm_add_epi16(maxknownA, maxknownB)));
4228 uhethet_incr = _mm_add_epi64(_mm_and_si128(uhethet_incr, m16), _mm_and_si128(_mm_srli_epi64(uhethet_incr, 16), m16));
4229 uhethet_sumv = _mm_add_epi64(uhethet_sumv, uhethet_incr);
4230 } while (dosage_vvec0_iter < dosage_vvec0_stop);
4231 UniVec dotprod_acc;
4232 UniVec uhethet_acc;
4233 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
4234 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
4235 known_dotprod += UniVecHsum32(dotprod_acc);
4236 uhethet_dosage += UniVecHsum32(uhethet_acc);
4237 }
4238 }
4239
4240 void DosagePhasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4241 const __m128i* invmask_iter = R_CAST(const __m128i*, subset_invmask);
4242 const __m128i* dosage_vvec0_iter = R_CAST(const __m128i*, dosage_vec0);
4243 const __m128i* dosage_vvec1_iter = R_CAST(const __m128i*, dosage_vec1);
4244 const __m128i* dphase_delta0_iter = R_CAST(const __m128i*, dphase_delta0);
4245 const __m128i* dphase_delta1_iter = R_CAST(const __m128i*, dphase_delta1);
4246 const __m128i all_16384 = _mm_set1_epi16(0x4000);
4247 const __m128i all_32767 = _mm_set1_epi16(0x7fff);
4248 # if defined(__APPLE__) && ((!defined(__cplusplus)) || (__cplusplus < 201103L))
4249 const __m128i all_n32768 = _mm_set1_epi16(0x8000);
4250 # else
4251 const __m128i all_n32768 = _mm_set1_epi64x(-0x7fff7fff7fff8000LL);
4252 # endif
4253 const __m128i m16 = _mm_set1_epi64x(kMask0000FFFF);
4254 const __m128i all0 = _mm_setzero_si128();
4255 const __m128i all1 = _mm_cmpeq_epi16(all0, all0);
4256 uint64_t known_dotprod = 0;
4257 uint64_t uhethet_dosage = 0;
4258 for (uint32_t vecs_left = vec_ct; ; ) {
4259 __m128i dotprod_sumv = _mm_setzero_si128();
4260 __m128i uhethet_sumv = _mm_setzero_si128();
4261 const __m128i* dosage_vvec0_stop;
4262 if (vecs_left < 8191) {
4263 if (!vecs_left) {
4264 *known_dotprod_dosagep = known_dotprod;
4265 *uhethet_dosagep = uhethet_dosage;
4266 return;
4267 }
4268 dosage_vvec0_stop = &(dosage_vvec0_iter[vecs_left]);
4269 vecs_left = 0;
4270 } else {
4271 dosage_vvec0_stop = &(dosage_vvec0_iter[8191]);
4272 vecs_left -= 8191;
4273 }
4274 do {
4275 __m128i invmask = *invmask_iter++;
4276 const __m128i dosage0 = *dosage_vvec0_iter++;
4277 const __m128i dosage1 = *dosage_vvec1_iter++;
4278 const __m128i delta0 = *dphase_delta0_iter++;
4279 const __m128i delta1 = *dphase_delta1_iter++;
4280 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage0, all1));
4281 invmask = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage1, all1));
4282 const __m128i dosage0A = _mm_add_epi16(dosage0, delta0);
4283 const __m128i dosage1A = _mm_add_epi16(dosage1, delta1);
4284 const __m128i dosage0B = _mm_sub_epi16(dosage0, delta0);
4285 const __m128i dosage1B = _mm_sub_epi16(dosage1, delta1);
4286 const __m128i dosageA_m32769 = _mm_add_epi16(_mm_add_epi16(dosage0A, dosage1A), all_32767);
4287 const __m128i dosageB_m32769 = _mm_add_epi16(_mm_add_epi16(dosage0B, dosage1B), all_32767);
4288 const __m128i invmaskA = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage0A, all0));
4289 const __m128i invmaskB = _mm_or_si128(invmask, _mm_cmpeq_epi16(dosage0B, all0));
4290 const __m128i unmasked_dotprod_incrA = _mm_sub_epi16(_mm_max_epi16(dosageA_m32769, all1), all1);
4291 const __m128i unmasked_dotprod_incrB = _mm_sub_epi16(_mm_max_epi16(dosageB_m32769, all1), all1);
4292 __m128i dotprod_incrA = _mm_andnot_si128(invmaskA, unmasked_dotprod_incrA);
4293 __m128i dotprod_incrB = _mm_andnot_si128(invmaskB, unmasked_dotprod_incrB);
4294 dotprod_incrA = _mm_add_epi64(_mm_and_si128(dotprod_incrA, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incrA, 16), m16));
4295 dotprod_incrB = _mm_add_epi64(_mm_and_si128(dotprod_incrB, m16), _mm_and_si128(_mm_srli_epi64(dotprod_incrB, 16), m16));
4296 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incrA);
4297 dotprod_sumv = _mm_add_epi64(dotprod_sumv, dotprod_incrB);
4298
4299 # ifdef USE_SSE42
4300 const __m128i known0A = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage0A));
4301 const __m128i known1A = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage1A));
4302 const __m128i known0B = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage0B));
4303 const __m128i known1B = _mm_abs_epi16(_mm_sub_epi16(all_16384, dosage1B));
4304 # else
4305 const __m128i pos0A = _mm_sub_epi16(all_16384, dosage0A);
4306 const __m128i neg0A = _mm_sub_epi16(dosage0A, all_16384);
4307 const __m128i pos1A = _mm_sub_epi16(all_16384, dosage1A);
4308 const __m128i neg1A = _mm_sub_epi16(dosage1A, all_16384);
4309 const __m128i pos0B = _mm_sub_epi16(all_16384, dosage0B);
4310 const __m128i neg0B = _mm_sub_epi16(dosage0B, all_16384);
4311 const __m128i pos1B = _mm_sub_epi16(all_16384, dosage1B);
4312 const __m128i neg1B = _mm_sub_epi16(dosage1B, all_16384);
4313 const __m128i known0A = _mm_max_epi16(pos0A, neg0A);
4314 const __m128i known1A = _mm_max_epi16(pos1A, neg1A);
4315 const __m128i known0B = _mm_max_epi16(pos0B, neg0B);
4316 const __m128i known1B = _mm_max_epi16(pos1B, neg1B);
4317 # endif
4318 const __m128i maxknownA = _mm_max_epi16(known0A, known1A);
4319 const __m128i maxknownB = _mm_max_epi16(known0B, known1B);
4320 __m128i uhethet_incr = _mm_andnot_si128(invmask, _mm_sub_epi16(all_n32768, _mm_add_epi16(maxknownA, maxknownB)));
4321 uhethet_incr = _mm_add_epi64(_mm_and_si128(uhethet_incr, m16), _mm_and_si128(_mm_srli_epi64(uhethet_incr, 16), m16));
4322 uhethet_sumv = _mm_add_epi64(uhethet_sumv, uhethet_incr);
4323 } while (dosage_vvec0_iter < dosage_vvec0_stop);
4324 UniVec dotprod_acc;
4325 UniVec uhethet_acc;
4326 dotprod_acc.vw = R_CAST(VecW, dotprod_sumv);
4327 uhethet_acc.vw = R_CAST(VecW, uhethet_sumv);
4328 known_dotprod += UniVecHsum32(dotprod_acc);
4329 uhethet_dosage += UniVecHsum32(uhethet_acc);
4330 }
4331 }
4332 # endif // !USE_AVX2
4333 #else // !__LP64__
4334 void FillDosageHet(const Dosage* dosage_vec, uint32_t dosagev_ct, Dosage* dosage_het) {
4335 const uint32_t sample_ctav = dosagev_ct * kDosagePerVec;
4336 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4337 const uint32_t cur_dosage = dosage_vec[sample_idx];
4338 uint32_t cur_hetval = cur_dosage;
4339 if (cur_hetval > 16384) {
4340 if (cur_hetval == kDosageMissing) {
4341 cur_hetval = 0;
4342 } else {
4343 cur_hetval = 32768 - cur_hetval;
4344 }
4345 }
4346 dosage_het[sample_idx] = cur_hetval;
4347 }
4348 }
4349
4350 uint64_t DenseDosageSum(const Dosage* dosage_vec, uint32_t vec_ct) {
4351 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4352 uint64_t sum = 0;
4353 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4354 const uint32_t cur_dosage = dosage_vec[sample_idx];
4355 if (cur_dosage != kDosageMissing) {
4356 sum += cur_dosage;
4357 }
4358 }
4359 return sum;
4360 }
4361
4362 uint64_t DenseDosageSumSubset(const Dosage* dosage_vec, const Dosage* dosage_mask_vec, uint32_t vec_ct) {
4363 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4364 uint64_t sum = 0;
4365 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4366 const uint32_t cur_dosage = dosage_vec[sample_idx];
4367 const uint32_t other_dosage = dosage_mask_vec[sample_idx];
4368 if ((cur_dosage != kDosageMissing) && (other_dosage != kDosageMissing)) {
4369 sum += cur_dosage;
4370 }
4371 }
4372 return sum;
4373 }
4374
4375 uint64_t DosageUnsignedDotprod(const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
4376 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4377 uint64_t dotprod = 0;
4378 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4379 const uint32_t cur_dosage0 = dosage_vec0[sample_idx];
4380 const uint32_t cur_dosage1 = dosage_vec1[sample_idx];
4381 if ((cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4382 dotprod += cur_dosage0 * cur_dosage1;
4383 }
4384 }
4385 return dotprod;
4386 }
4387
4388 uint64_t DosageUnsignedDotprodSubset(const Dosage* dosage_mask_vec, const Dosage* dosage_vec0, const Dosage* dosage_vec1, uint32_t vec_ct) {
4389 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4390 uint64_t dotprod = 0;
4391 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4392 const uint32_t cur_dosage_maskval = dosage_mask_vec[sample_idx];
4393 const uint32_t cur_dosage0 = dosage_vec0[sample_idx];
4394 const uint32_t cur_dosage1 = dosage_vec1[sample_idx];
4395 if ((cur_dosage_maskval != kDosageMissing) && (cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4396 dotprod += cur_dosage0 * cur_dosage1;
4397 }
4398 }
4399 return dotprod;
4400 }
4401
4402 void DosageUnphasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4403 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4404 // Multiply by 2 later so unphased and phased cases are on the same scale.
4405 // (Specifically, known_dotprod is in 1/kDosageMax increments and the logical
4406 // value ranges from 0..2n, where n is founder_ct; and unknown_hethet is in
4407 // 1/kDosageMax increments and ranges from 0..n.)
4408 uint64_t half_known_dotprod_dosage = 0;
4409 uint64_t half_uhethet_dosage = 0;
4410 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4411 const int32_t cur_dosage0 = dosage_vec0[sample_idx];
4412 const int32_t cur_dosage1 = dosage_vec1[sample_idx];
4413 if ((cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4414 half_known_dotprod_dosage += MAXV(0, cur_dosage0 + cur_dosage1 - S_CAST(int32_t, kDosageMax));
4415 half_uhethet_dosage += MINV(dosage_het0[sample_idx], dosage_het1[sample_idx]);
4416 }
4417 }
4418 *known_dotprod_dosagep = half_known_dotprod_dosage * 2;
4419 *uhethet_dosagep = half_uhethet_dosage * 2;
4420 }
4421
4422 // subset_invmask values required to be in {0, 65535}, for the sake of the
4423 // vectorized implementations
4424 void DosageUnphasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const Dosage* dosage_het0, const Dosage* dosage_het1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4425 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4426 // Multiply by 2 later so unphased and phased cases are on the same scale.
4427 // (Specifically, known_dotprod is in 1/kDosageMax increments and the logical
4428 // value ranges from 0..2n, where n is founder_ct; and unknown_hethet is in
4429 // 1/kDosageMax increments and ranges from 0..n.)
4430 uint64_t half_known_dotprod_dosage = 0;
4431 uint64_t half_uhethet_dosage = 0;
4432 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4433 const int32_t cur_dosage0 = dosage_vec0[sample_idx] | subset_invmask[sample_idx];
4434 const int32_t cur_dosage1 = dosage_vec1[sample_idx];
4435 if ((cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4436 half_known_dotprod_dosage += MAXV(0, cur_dosage0 + cur_dosage1 - S_CAST(int32_t, kDosageMax));
4437 half_uhethet_dosage += MINV(dosage_het0[sample_idx], dosage_het1[sample_idx]);
4438 }
4439 }
4440 *known_dotprod_dosagep = half_known_dotprod_dosage * 2;
4441 *uhethet_dosagep = half_uhethet_dosage * 2;
4442 }
4443
4444 void DosagePhasedDotprodComponents(const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4445 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4446 uint64_t known_dotprod_dosage = 0;
4447 uint64_t uhethet_dosage = 0;
4448 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4449 const uint32_t cur_dosage0 = dosage_vec0[sample_idx];
4450 const uint32_t cur_dosage1 = dosage_vec1[sample_idx];
4451 if ((cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4452 // dosage0 = a + b
4453 // delta0 = a - b
4454 // -> dosage + delta = 2a
4455 // dosage - delta = 2b
4456 const int32_t cur_delta0 = dphase_delta0[sample_idx];
4457 const int32_t cur_delta1 = dphase_delta1[sample_idx];
4458 const int32_t dosage0A_x2 = cur_dosage0 + cur_delta0;
4459 const int32_t dosage1A_x2 = cur_dosage1 + cur_delta1;
4460 const int32_t dosage0B_x2 = cur_dosage0 - cur_delta0;
4461 const int32_t dosage1B_x2 = cur_dosage1 - cur_delta1;
4462 known_dotprod_dosage += MAXV(0, dosage0A_x2 + dosage1A_x2 - S_CAST(int32_t, kDosageMax)) + MAXV(0, dosage0B_x2 + dosage1B_x2 - S_CAST(int32_t, kDosageMax));
4463 const uint32_t known0A = abs_i32(kDosageMid - dosage0A_x2);
4464 const uint32_t known1A = abs_i32(kDosageMid - dosage1A_x2);
4465 const uint32_t known0B = abs_i32(kDosageMid - dosage0B_x2);
4466 const uint32_t known1B = abs_i32(kDosageMid - dosage1B_x2);
4467 uhethet_dosage += kDosageMax - MAXV(known0A, known1A) - MAXV(known0B, known1B);
4468 }
4469 }
4470 *known_dotprod_dosagep = known_dotprod_dosage;
4471 *uhethet_dosagep = uhethet_dosage;
4472 }
4473
4474 void DosagePhasedDotprodComponentsSubset(const Dosage* subset_invmask, const Dosage* dosage_vec0, const Dosage* dosage_vec1, const SDosage* dphase_delta0, const SDosage* dphase_delta1, uint32_t vec_ct, uint64_t* known_dotprod_dosagep, uint64_t* uhethet_dosagep) {
4475 const uint32_t sample_ctav = vec_ct * kDosagePerVec;
4476 uint64_t known_dotprod_dosage = 0;
4477 uint64_t uhethet_dosage = 0;
4478 for (uint32_t sample_idx = 0; sample_idx != sample_ctav; ++sample_idx) {
4479 const uint32_t cur_dosage0 = dosage_vec0[sample_idx] | subset_invmask[sample_idx];
4480 const uint32_t cur_dosage1 = dosage_vec1[sample_idx];
4481 if ((cur_dosage0 != kDosageMissing) && (cur_dosage1 != kDosageMissing)) {
4482 // dosage0 = a + b
4483 // delta0 = a - b
4484 // -> dosage + delta = 2a
4485 // dosage - delta = 2b
4486 const int32_t cur_delta0 = dphase_delta0[sample_idx];
4487 const int32_t cur_delta1 = dphase_delta1[sample_idx];
4488 const int32_t dosage0A_x2 = cur_dosage0 + cur_delta0;
4489 const int32_t dosage1A_x2 = cur_dosage1 + cur_delta1;
4490 const int32_t dosage0B_x2 = cur_dosage0 - cur_delta0;
4491 const int32_t dosage1B_x2 = cur_dosage1 - cur_delta1;
4492 known_dotprod_dosage += MAXV(0, dosage0A_x2 + dosage1A_x2 - S_CAST(int32_t, kDosageMax)) + MAXV(0, dosage0B_x2 + dosage1B_x2 - S_CAST(int32_t, kDosageMax));
4493 const uint32_t known0A = abs_i32(kDosageMid - dosage0A_x2);
4494 const uint32_t known1A = abs_i32(kDosageMid - dosage1A_x2);
4495 const uint32_t known0B = abs_i32(kDosageMid - dosage0B_x2);
4496 const uint32_t known1B = abs_i32(kDosageMid - dosage1B_x2);
4497 uhethet_dosage += kDosageMax - MAXV(known0A, known1A) - MAXV(known0B, known1B);
4498 }
4499 }
4500 *known_dotprod_dosagep = known_dotprod_dosage;
4501 *uhethet_dosagep = uhethet_dosage;
4502 }
4503 #endif
4504
4505 // nmaj_dosages assumed to be initialized to whole-vector sums
4506 uint32_t DosageR2Freqs(const Dosage* dosage_vec0, const uintptr_t* nm_bitvec0, const Dosage* dosage_vec1, const uintptr_t* nm_bitvec1, uint32_t sample_ct, uint32_t nm_ct0, uint32_t nm_ct1, uint64_t* __restrict nmaj_dosages) {
4507 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
4508 uint32_t nm_intersection_ct;
4509 if ((nm_ct0 != sample_ct) && (nm_ct1 != sample_ct)) {
4510 nm_intersection_ct = PopcountWordsIntersect(nm_bitvec0, nm_bitvec1, sample_ctl);
4511 if (!nm_intersection_ct) {
4512 nmaj_dosages[0] = 0;
4513 nmaj_dosages[1] = 0;
4514 return 0;
4515 }
4516 } else {
4517 nm_intersection_ct = MINV(nm_ct0, nm_ct1);
4518 }
4519 const uint32_t vec_ct = DivUp(sample_ct, kDosagePerVec);
4520 if (nm_ct0 != nm_intersection_ct) {
4521 nmaj_dosages[0] = DenseDosageSumSubset(dosage_vec0, dosage_vec1, vec_ct);
4522 }
4523 if (nm_ct1 != nm_intersection_ct) {
4524 nmaj_dosages[1] = DenseDosageSumSubset(dosage_vec1, dosage_vec0, vec_ct);
4525 }
4526 return nm_intersection_ct;
4527 }
4528
4529 // nmaj_dosages assumed to be initialized to subsetted-vector sums.
4530 uint32_t DosageR2FreqsSubset(const Dosage* dosage_vec0, const uintptr_t* nm_bitvec0, const Dosage* dosage_vec1, const uintptr_t* nm_bitvec1, const uintptr_t* sample_include, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, uint64_t* __restrict nmaj_dosages, uintptr_t* cur_nm_buf, Dosage* invmask_buf) {
4531 // bugfix (29 Oct 2023): got raw_sample_ct / sample_ct mixed up
4532 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
4533 if (subsetted_nm_ct0 == sample_ct) {
4534 if (subsetted_nm_ct1 == sample_ct) {
4535 return sample_ct;
4536 }
4537 BitvecAndCopy(nm_bitvec1, sample_include, raw_sample_ctl, cur_nm_buf);
4538 } else {
4539 BitvecAndCopy(nm_bitvec0, sample_include, raw_sample_ctl, cur_nm_buf);
4540 if (subsetted_nm_ct1 != sample_ct) {
4541 BitvecAnd(nm_bitvec1, raw_sample_ctl, cur_nm_buf);
4542 }
4543 }
4544 const uint32_t nm_intersection_ct = PopcountWords(cur_nm_buf, raw_sample_ctl);
4545 if (!nm_intersection_ct) {
4546 nmaj_dosages[0] = 0;
4547 nmaj_dosages[1] = 0;
4548 return 0;
4549 }
4550 Expand1bitTo16(cur_nm_buf, RoundUpPow2(raw_sample_ct, kDosagePerVec), 0xffff, invmask_buf);
4551 const uint32_t vec_ct = DivUp(raw_sample_ct, kDosagePerVec);
4552 nmaj_dosages[0] = DenseDosageSumSubset(dosage_vec0, invmask_buf, vec_ct);
4553 nmaj_dosages[1] = DenseDosageSumSubset(dosage_vec1, invmask_buf, vec_ct);
4554 return nm_intersection_ct;
4555 }
4556
4557
4558 // "unscaled" because you need to multiply by allele count to get the proper
4559 // log-likelihood
4560 double EmPhaseUnscaledLnlike(double freq11, double freq12, double freq21, double freq22, double half_hethet_share, double freq11_incr) {
4561 // bugfix (11 Dec 2023): can't modify freq11, etc. in-place because then
4562 // they're no longer scaled with old calc_lnlike() known11, etc.
4563 const double adj_freq11 = freq11 + freq11_incr;
4564 const double adj_freq22 = freq22 + freq11_incr;
4565 const double adj_freq12 = freq12 + half_hethet_share - freq11_incr;
4566 const double adj_freq21 = freq21 + half_hethet_share - freq11_incr;
4567 const double cross_sum = adj_freq11 * adj_freq22 + adj_freq12 * adj_freq21;
4568 double lnlike = 0.0;
4569 if (cross_sum != 0.0) {
4570 lnlike = half_hethet_share * log(cross_sum);
4571 }
4572 if (adj_freq11 != 0.0) {
4573 lnlike += freq11 * log(adj_freq11);
4574 }
4575 if (adj_freq12 != 0.0) {
4576 lnlike += freq12 * log(adj_freq12);
4577 }
4578 if (adj_freq21 != 0.0) {
4579 lnlike += freq21 * log(adj_freq21);
4580 }
4581 if (adj_freq22 != 0.0) {
4582 lnlike += freq22 * log(adj_freq22);
4583 }
4584 return lnlike;
4585 }
4586
4587 ENUM_U31_DEF_START()
4588 kLDErrNone,
4589 kLDMonomorphic0,
4590 kLDMonomorphic1
4591 ENUM_U31_DEF_END(LDErr);
4592
4593 typedef struct PhasedLDExtraRetStruct {
4594 uint32_t sol_ct;
4595 uint32_t best_lnlike_mask;
4596 double freq_majmaj;
4597 double freq_majmin;
4598 double freq_minmaj;
4599 double freq_minmin;
4600 double half_unphased_hethet_share;
4601 double freq_majx;
4602 double freq_minx;
4603 double freq_xmaj;
4604 double freq_xmin;
4605 } PhasedLDExtraRet;
4606
4607 // If extra_retp is non-null, results contains relevant cubic_sols.
4608 // If extra_retp is nullptr, results[0] contains r2, and if
4609 // compute_d_and_dprime is true, results[1] = D and results[2] = D'.
4610 LDErr PhasedLD(const double* nmajsums_d, double known_dotprod_d, double unknown_hethet_d, double twice_tot_recip, uint32_t compute_d_and_dprime, PhasedLDExtraRet* extra_retp, double* results, uint32_t* is_neg_ptr) {
4611 // known-diplotype dosages (sum is 2 * (valid_obs_d - unknown_hethet_d)):
4612 // var0 var1
4613 // 0 - 0 : 2 * valid_obs_d - majsums[0] - majsums[1] + known_dotprod
4614 // 1 - 0 : majsums[0] - known_dotprod - unknown_hethet_d
4615 // 0 - 1 : majsums[1] - known_dotprod - unknown_hethet_d
4616 // 1 - 1 : known_dotprod
4617
4618 // bugfix (15 Sep 2023): otherwise possible for freq_majmaj to be slightly
4619 // less than zero, and this breaks EmPhaseUnscaledLnlike().
4620 const double freq_majmaj = MAXV(1.0 - (nmajsums_d[0] + nmajsums_d[1] - known_dotprod_d) * twice_tot_recip, 0.0);
4621 const double freq_majmin = (nmajsums_d[1] - known_dotprod_d - unknown_hethet_d) * twice_tot_recip;
4622 const double freq_minmaj = (nmajsums_d[0] - known_dotprod_d - unknown_hethet_d) * twice_tot_recip;
4623 const double freq_minmin = known_dotprod_d * twice_tot_recip;
4624 const double half_unphased_hethet_share = unknown_hethet_d * twice_tot_recip;
4625 const double freq_majx = freq_majmaj + freq_majmin + half_unphased_hethet_share;
4626 const double freq_minx = 1.0 - freq_majx;
4627 const double freq_xmaj = freq_majmaj + freq_minmaj + half_unphased_hethet_share;
4628 const double freq_xmin = 1.0 - freq_xmaj;
4629 // frequency of ~2^{-46} is actually possible with dosages and 2 billion
4630 // samples, so set this threshold at 2^{-47}
4631 if ((freq_majx < (kSmallEpsilon * 0.125)) || (freq_minx < (kSmallEpsilon * 0.125))) {
4632 return kLDMonomorphic0;
4633 }
4634 if ((freq_xmaj < (kSmallEpsilon * 0.125)) || (freq_xmin < (kSmallEpsilon * 0.125))) {
4635 return kLDMonomorphic1;
4636 }
4637 uint32_t cubic_sol_ct = 0;
4638 uint32_t first_relevant_sol_idx = 0;
4639 uint32_t best_lnlike_mask = 0;
4640 STD_ARRAY_DECL(double, 3, cubic_sols);
4641 if (half_unphased_hethet_share != 0.0) {
4642 // detect degenerate cases to avoid e-17 ugliness
4643 if ((freq_majmaj * freq_minmin != 0.0) || (freq_majmin * freq_minmaj != 0.0)) {
4644 // (f11 + x)(f22 + x)(K - x) = x(f12 + K - x)(f21 + K - x)
4645 // (x - K)(x + f11)(x + f22) + x(x - K - f12)(x - K - f21) = 0
4646 // x^3 + (f11 + f22 - K)x^2 + (f11*f22 - K*f11 - K*f22)x - K*f11*f22
4647 // + x^3 - (2K + f12 + f21)x^2 + (K + f12)(K + f21)x = 0
4648 cubic_sol_ct = CubicRealRoots(0.5 * (freq_majmaj + freq_minmin - freq_majmin - freq_minmaj - 3 * half_unphased_hethet_share), 0.5 * (freq_majmaj * freq_minmin + freq_majmin * freq_minmaj + half_unphased_hethet_share * (freq_majmin + freq_minmaj - freq_majmaj - freq_minmin + half_unphased_hethet_share)), -0.5 * half_unphased_hethet_share * freq_majmaj * freq_minmin, cubic_sols);
4649 if (cubic_sol_ct > 1) {
4650 // have encountered 7.9e-11 difference in testing, which is more than
4651 // twice kSmallishEpsilon.
4652 while (cubic_sols[cubic_sol_ct - 1] > half_unphased_hethet_share + 8 * kSmallishEpsilon) {
4653 --cubic_sol_ct;
4654 if (cubic_sol_ct == 1) {
4655 break;
4656 }
4657 }
4658 if (cubic_sols[cubic_sol_ct - 1] > half_unphased_hethet_share - 8 * kSmallishEpsilon) {
4659 cubic_sols[cubic_sol_ct - 1] = half_unphased_hethet_share;
4660 }
4661 while ((cubic_sols[first_relevant_sol_idx] < 8 * -kSmallishEpsilon) && (first_relevant_sol_idx + 1 < cubic_sol_ct)) {
4662 ++first_relevant_sol_idx;
4663 }
4664 }
4665 // bugfix (29 Jan 2025): Also need to clip up to 0 when there's only one
4666 // solution.
4667 if (cubic_sols[first_relevant_sol_idx] < 8 * kSmallishEpsilon) {
4668 cubic_sols[first_relevant_sol_idx] = 0.0;
4669 }
4670 } else {
4671 // At least one of {f11, f22} is zero, and one of {f12, f21} is zero.
4672 // Initially suppose that the zero-values are f11 and f12. Then the
4673 // equality becomes
4674 // x(f22 + x)(K - x) = x(K - x)(f21 + K - x)
4675 // x=0 and x=K are always solutions; the rest becomes
4676 // f22 + x = f21 + K - x
4677 // 2x = K + f21 - f22
4678 // x = (K + f21 - f22)/2; in-range iff (f21 - f22) in (-K, K).
4679 // So far so good. However, plink 1.9 incorrectly *always* checked
4680 // (f21 - f22) before 6 Oct 2017, when it needed to use all the nonzero
4681 // values.
4682 cubic_sols[0] = 0.0;
4683 const double nonzero_freq_xx = freq_majmaj + freq_minmin;
4684 const double nonzero_freq_xy = freq_majmin + freq_minmaj;
4685 // (current code still works if three or all four values are zero)
4686 if ((nonzero_freq_xx + kSmallishEpsilon < half_unphased_hethet_share + nonzero_freq_xy) && (nonzero_freq_xy + kSmallishEpsilon < half_unphased_hethet_share + nonzero_freq_xx)) {
4687 cubic_sol_ct = 3;
4688 cubic_sols[1] = (half_unphased_hethet_share + nonzero_freq_xy - nonzero_freq_xx) * 0.5;
4689 cubic_sols[2] = half_unphased_hethet_share;
4690 } else {
4691 cubic_sol_ct = 2;
4692 cubic_sols[1] = half_unphased_hethet_share;
4693 }
4694 }
4695 // cubic_sol_ct does not contain trailing too-large solutions
4696 if (cubic_sol_ct > first_relevant_sol_idx + 1) {
4697 double best_unscaled_lnlike = -DBL_MAX;
4698 for (uint32_t sol_idx = first_relevant_sol_idx; sol_idx < cubic_sol_ct; ++sol_idx) {
4699 const double cur_unscaled_lnlike = EmPhaseUnscaledLnlike(freq_majmaj, freq_majmin, freq_minmaj, freq_minmin, half_unphased_hethet_share, cubic_sols[sol_idx]);
4700 if (cur_unscaled_lnlike > best_unscaled_lnlike) {
4701 best_unscaled_lnlike = cur_unscaled_lnlike;
4702 best_lnlike_mask = 1 << sol_idx;
4703 } else if (cur_unscaled_lnlike == best_unscaled_lnlike) {
4704 best_lnlike_mask |= 1 << sol_idx;
4705 }
4706 }
4707 }
4708 } else {
4709 cubic_sol_ct = 1;
4710 cubic_sols[0] = 0.0;
4711 }
4712 if (!extra_retp) {
4713 uint32_t sol_idx = first_relevant_sol_idx;
4714 if (cubic_sol_ct - first_relevant_sol_idx > 1) {
4715 sol_idx = ctzu32(best_lnlike_mask);
4716 }
4717 const double cur_sol_xx = cubic_sols[sol_idx];
4718 double dd = freq_majmaj + cur_sol_xx - freq_majx * freq_xmaj;
4719 if (fabs(dd) < kSmallEpsilon) {
4720 dd = 0.0;
4721 }
4722 results[0] = dd * dd / (freq_majx * freq_xmaj * freq_minx * freq_xmin);
4723 *is_neg_ptr = (dd < 0.0);
4724 if (compute_d_and_dprime) {
4725 // maybe this should just always be computed since it's such a small
4726 // fraction of the total cost?
4727 results[1] = dd;
4728 if (dd >= 0.0) {
4729 results[2] = dd / MINV(freq_xmaj * freq_minx, freq_xmin * freq_majx);
4730 } else {
4731 // note that this preserves sign
4732 results[2] = dd / MINV(freq_xmaj * freq_majx, freq_xmin * freq_minx);
4733 }
4734 }
4735 } else {
4736 extra_retp->sol_ct = cubic_sol_ct - first_relevant_sol_idx;
4737 extra_retp->best_lnlike_mask = best_lnlike_mask >> first_relevant_sol_idx;
4738 extra_retp->freq_majmaj = freq_majmaj;
4739 extra_retp->freq_majmin = freq_majmin;
4740 extra_retp->freq_minmaj = freq_minmaj;
4741 extra_retp->freq_minmin = freq_minmin;
4742 extra_retp->half_unphased_hethet_share = half_unphased_hethet_share;
4743 extra_retp->freq_majx = freq_majx;
4744 extra_retp->freq_minx = freq_minx;
4745 extra_retp->freq_xmaj = freq_xmaj;
4746 extra_retp->freq_xmin = freq_xmin;
4747 for (uint32_t sol_idx = first_relevant_sol_idx; sol_idx != cubic_sol_ct; ++sol_idx) {
4748 results[sol_idx - first_relevant_sol_idx] = cubic_sols[sol_idx];
4749 }
4750 }
4751 return kLDErrNone;
4752 }
4753
4754 PglErr LdConsole(const uintptr_t* variant_include, const ChrInfo* cip, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const AlleleCode* maj_alleles, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const LdInfo* ldip, uint32_t variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, PgenReader* simple_pgrp) {
4755 unsigned char* bigstack_mark = g_bigstack_base;
4756 PglErr reterr = kPglRetSuccess;
4757 {
4758 if (unlikely(founder_ct < 2)) {
4759 logerrputs("Error: --ld requires at least two founders. (--make-founders may come in handy\nhere.)\n");
4760 goto LdConsole_ret_INCONSISTENT_INPUT;
4761 }
4762 STD_ARRAY_KREF(char*, 2) ld_console_varids = ldip->ld_console_varids;
4763 // ok to ignore chr_mask here
4764 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
4765 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
4766 // is_x:
4767 // * male het calls treated as missing hardcalls
4768 // * males only have half weight in all computations (or sqrt(0.5) if one
4769 // variant on chrX and one variant elsewhere)
4770 // * SNPHWEX used for HWE stats
4771 //
4772 // is_nonx_haploid:
4773 // * all het calls treated as missing hardcalls
4774 uint32_t var_uidxs[2];
4775 uint32_t chr_idxs[2];
4776 uint32_t is_xs[2];
4777 uint32_t is_haploids[2];
4778 uint32_t y_ct = 0;
4779 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
4780 const char* cur_varid = ld_console_varids[var_idx];
4781 int32_t ii = GetVariantUidxWithoutHtable(cur_varid, variant_ids, variant_include, variant_ct);
4782 if (unlikely(ii == -1)) {
4783 snprintf(g_logbuf, kLogbufSize, "Error: --ld variant '%s' does not appear in dataset.\n", cur_varid);
4784 goto LdConsole_ret_INCONSISTENT_INPUT_WW;
4785 } else if (unlikely(ii == -2)) {
4786 snprintf(g_logbuf, kLogbufSize, "Error: --ld variant '%s' appears multiple times in dataset.\n", cur_varid);
4787 goto LdConsole_ret_INCONSISTENT_INPUT_WW;
4788 }
4789 const uint32_t cur_var_uidx = ii;
4790 var_uidxs[var_idx] = cur_var_uidx;
4791 const uint32_t chr_idx = GetVariantChr(cip, cur_var_uidx);
4792 chr_idxs[var_idx] = chr_idx;
4793 const uint32_t is_x = (chr_idx == x_code);
4794 is_xs[var_idx] = is_x;
4795 uint32_t is_haploid = 0;
4796 if (IsSet(cip->haploid_mask, chr_idx)) {
4797 is_haploid = 1;
4798 y_ct += (chr_idx == y_code);
4799 }
4800 is_haploids[var_idx] = is_haploid;
4801 }
4802 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
4803 // if both unplaced, don't count as same-chromosome
4804 const uint32_t is_same_chr = chr_idxs[0] && (chr_idxs[0] == chr_idxs[1]);
4805 if (y_ct) {
4806 // only keep non-female founders
4807 // (relaxed on 12 Oct 2023 to be consistent with plink2 --set-hh-missing
4808 // behavior)
4809 uintptr_t* founder_info_tmp;
4810 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &founder_info_tmp))) {
4811 goto LdConsole_ret_NOMEM;
4812 }
4813 // female = sex_nm & (~sex_male)
4814
4815 // this leaves trailing bits set, but BitvecAnd with founder_info clears
4816 // them
4817 BitvecInvertCopy(sex_nm, raw_sample_ctl, founder_info_tmp);
4818 BitvecOr(sex_male, raw_sample_ctl, founder_info_tmp);
4819 BitvecAnd(founder_info, raw_sample_ctl, founder_info_tmp);
4820 founder_info = founder_info_tmp;
4821 founder_ct = PopcountWords(founder_info, raw_sample_ctl);
4822 if (unlikely(founder_ct < 2)) {
4823 logerrputs("Error: --ld requires at least two non-female founders when a chrY variant is\nspecified. (--make-founders may come in handy here.)\n");
4824 goto LdConsole_ret_INCONSISTENT_INPUT;
4825 }
4826 }
4827 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
4828 uint32_t* founder_info_cumulative_popcounts;
4829 PgenVariant pgvs[2];
4830 PreinitPgv(&(pgvs[0]));
4831 PreinitPgv(&(pgvs[1]));
4832 if (unlikely(bigstack_alloc_u32(founder_ctl, &founder_info_cumulative_popcounts) ||
4833 BigstackAllocPgv(founder_ct, 0, kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent, &(pgvs[0])) ||
4834 BigstackAllocPgv(founder_ct, 0, kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent, &(pgvs[1])))) {
4835 goto LdConsole_ret_NOMEM;
4836 }
4837
4838 const uint32_t x_present = (is_xs[0] || is_xs[1]);
4839 const uint32_t founder_ctv = BitCtToVecCt(founder_ct);
4840 const uint32_t founder_ctaw = founder_ctv * kWordsPerVec;
4841 uintptr_t* sex_male_collapsed = nullptr;
4842 uintptr_t* sex_male_collapsed_interleaved = nullptr;
4843 uint32_t x_male_ct = 0;
4844 if (x_present) {
4845 if (unlikely(bigstack_alloc_w(founder_ctaw, &sex_male_collapsed) ||
4846 bigstack_alloc_w(founder_ctaw, &sex_male_collapsed_interleaved))) {
4847 goto LdConsole_ret_NOMEM;
4848 }
4849 CopyBitarrSubset(sex_male, founder_info, founder_ct, sex_male_collapsed);
4850 ZeroTrailingWords(founder_ctl, sex_male_collapsed);
4851 FillInterleavedMaskVec(sex_male_collapsed, founder_ctv, sex_male_collapsed_interleaved);
4852 x_male_ct = PopcountWords(sex_male_collapsed, founder_ctaw);
4853 }
4854 FillCumulativePopcounts(founder_info, founder_ctl, founder_info_cumulative_popcounts);
4855
4856 PgrSampleSubsetIndex pssi;
4857 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
4858 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
4859 const uint32_t variant_uidx = var_uidxs[var_idx];
4860 // (unconditionally allocating phaseinfo/dosage_main and using the most
4861 // general-purpose loader makes sense when this loop only executes twice,
4862 // but --r2 will want to use different pgenlib loaders depending on
4863 // context.)
4864
4865 PgenVariant* pgvp = &(pgvs[var_idx]);
4866 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, variant_uidx, maj_alleles[variant_uidx], simple_pgrp, pgvp);
4867 if (unlikely(reterr)) {
4868 PgenErrPrintNV(reterr, variant_uidx);
4869 goto LdConsole_ret_1;
4870 }
4871 ZeroTrailingNyps(founder_ct, pgvp->genovec);
4872 if (is_haploids[var_idx]) {
4873 if (x_male_ct && is_xs[var_idx]) {
4874 if (pgvp->phasepresent_ct) {
4875 BitvecInvmask(sex_male_collapsed, founder_ctl, pgvp->phasepresent);
4876 pgvp->phasepresent_ct = PopcountWords(pgvp->phasepresent, founder_ctl);
4877 }
4878 if (pgvp->dphase_ct) {
4879 EraseMaleDphases(sex_male_collapsed, &(pgvp->dphase_ct), pgvp->dphase_present, pgvp->dphase_delta);
4880 }
4881 } else {
4882 pgvp->phasepresent_ct = 0;
4883 pgvp->dphase_ct = 0;
4884 }
4885 }
4886 }
4887 const uint32_t use_phase = is_same_chr && (pgvs[0].phasepresent_ct || pgvs[0].dphase_ct) && (pgvs[1].phasepresent_ct || pgvs[1].dphase_ct);
4888 // in haploid case, het -> 0.5
4889 const uint32_t use_dosage = pgvs[0].dosage_ct || pgvs[1].dosage_ct || is_haploids[0] || is_haploids[1];
4890
4891 // values of interest:
4892 // mutually-nonmissing observation count
4893 // (all other values computed over mutually-nonmissing set)
4894 // 4 known-diplotype dosages (0..2 for each sample, in unphased het-het)
4895 // (unphased het-het fractional count can be inferred)
4896 // dosage sum for each variant
4897 uint32_t valid_x_male_ct = 0;
4898 double nmajsums_d[2];
4899 double x_male_nmajsums_d[2];
4900 double known_dotprod_d;
4901 double unknown_hethet_d;
4902 uint32_t valid_obs_ct;
4903 uint32_t hethet_hc_found = 0;
4904 if (!use_dosage) {
4905 // While we could theoretically optimize around the fact that we only
4906 // need to make a single phased-r^2 computation, that's silly; it makes a
4907 // lot more sense to use this as a testing ground for algorithms and data
4908 // representations suitable for --r/--r2, etc.
4909 uintptr_t* one_bitvecs[2];
4910 uintptr_t* two_bitvecs[2];
4911 uintptr_t* nm_bitvecs[2];
4912 if (unlikely(bigstack_alloc_w(founder_ctaw, &one_bitvecs[0]) ||
4913 bigstack_alloc_w(founder_ctaw, &two_bitvecs[0]) ||
4914 bigstack_alloc_w(founder_ctaw, &nm_bitvecs[0]) ||
4915 bigstack_alloc_w(founder_ctaw, &one_bitvecs[1]) ||
4916 bigstack_alloc_w(founder_ctaw, &two_bitvecs[1]) ||
4917 bigstack_alloc_w(founder_ctaw, &nm_bitvecs[1]))) {
4918 goto LdConsole_ret_NOMEM;
4919 }
4920 uint32_t nmaj_cts[2];
4921 uint32_t nm_cts[2]; // ugh.
4922 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
4923 GenoarrSplit12Nm(pgvs[var_idx].genovec, founder_ct, one_bitvecs[var_idx], two_bitvecs[var_idx], nm_bitvecs[var_idx]);
4924 nmaj_cts[var_idx] = GenoBitvecSum(one_bitvecs[var_idx], two_bitvecs[var_idx], founder_ctl);
4925 nm_cts[var_idx] = PopcountWords(nm_bitvecs[var_idx], founder_ctl);
4926 }
4927 uint32_t known_dotprod;
4928 uint32_t unknown_hethet_ct;
4929 valid_obs_ct = HardcallPhasedR2Stats(one_bitvecs[0], two_bitvecs[0], nm_bitvecs[0], one_bitvecs[1], two_bitvecs[1], nm_bitvecs[1], founder_ct, nm_cts[0], nm_cts[1], nmaj_cts, &known_dotprod, &unknown_hethet_ct);
4930 if (unlikely(!valid_obs_ct)) {
4931 goto LdConsole_ret_NO_VALID_OBSERVATIONS;
4932 }
4933 hethet_hc_found = (unknown_hethet_ct != 0);
4934 if (use_phase && hethet_hc_found) {
4935 // all that's needed for the hardcall-phase correction is:
4936 // popcount(phasepresent0 & phasepresent1)
4937 // popcount(phasepresent0 & phasepresent1 &
4938 // (phaseinfo0 ^ phaseinfo1))
4939 HardcallPhasedR2Refine(pgvs[0].phasepresent, pgvs[0].phaseinfo, pgvs[1].phasepresent, pgvs[1].phaseinfo, founder_ctl, &known_dotprod, &unknown_hethet_ct);
4940 }
4941 nmajsums_d[0] = u31tod(nmaj_cts[0]);
4942 nmajsums_d[1] = u31tod(nmaj_cts[1]);
4943 known_dotprod_d = S_CAST(double, known_dotprod);
4944 unknown_hethet_d = u31tod(unknown_hethet_ct);
4945 } else {
4946 const uint32_t founder_dosagev_ct = DivUp(founder_ct, kDosagePerVec);
4947 Dosage* dosage_vecs[2];
4948 Dosage* dosage_hets[2];
4949 uintptr_t* nm_bitvecs[2];
4950 // founder_ct automatically rounded up as necessary
4951 if (unlikely(bigstack_alloc_dosage(founder_ct, &dosage_vecs[0]) ||
4952 bigstack_alloc_dosage(founder_ct, &dosage_vecs[1]) ||
4953 bigstack_alloc_dosage(founder_ct, &dosage_hets[0]) ||
4954 bigstack_alloc_dosage(founder_ct, &dosage_hets[1]) ||
4955 bigstack_alloc_w(founder_ctl, &nm_bitvecs[0]) ||
4956 bigstack_alloc_w(founder_ctl, &nm_bitvecs[1]))) {
4957 goto LdConsole_ret_NOMEM;
4958 }
4959 uint64_t nmaj_dosages[2];
4960 uint32_t nm_cts[2];
4961 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
4962 const uint32_t dosage_ct = pgvs[var_idx].dosage_ct;
4963 PopulateDenseDosage(pgvs[var_idx].genovec, pgvs[var_idx].dosage_present, pgvs[var_idx].dosage_main, founder_ct, dosage_ct, dosage_vecs[var_idx]);
4964 nmaj_dosages[var_idx] = DenseDosageSum(dosage_vecs[var_idx], founder_dosagev_ct);
4965 FillDosageHet(dosage_vecs[var_idx], founder_dosagev_ct, dosage_hets[var_idx]);
4966 GenoarrToNonmissing(pgvs[var_idx].genovec, founder_ct, nm_bitvecs[var_idx]);
4967 // bugfix (10 Dec 2023)
4968 if (dosage_ct) {
4969 BitvecOr(pgvs[var_idx].dosage_present, founder_ctl, nm_bitvecs[var_idx]);
4970 }
4971 nm_cts[var_idx] = PopcountWords(nm_bitvecs[var_idx], founder_ctl);
4972 }
4973 SDosage* main_dphase_deltas[2];
4974 main_dphase_deltas[0] = nullptr;
4975 main_dphase_deltas[1] = nullptr;
4976 if (use_phase) {
4977 if (unlikely(bigstack_alloc_dphase(founder_ct, &main_dphase_deltas[0]) ||
4978 bigstack_alloc_dphase(founder_ct, &main_dphase_deltas[1]))) {
4979 goto LdConsole_ret_NOMEM;
4980 }
4981 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
4982 PopulateDenseDphase(pgvs[var_idx].phasepresent, pgvs[var_idx].phaseinfo, pgvs[var_idx].dosage_present, dosage_vecs[var_idx], pgvs[var_idx].dphase_present, pgvs[var_idx].dphase_delta, founder_ct, pgvs[var_idx].phasepresent_ct, pgvs[var_idx].dosage_ct, pgvs[var_idx].dphase_ct, main_dphase_deltas[var_idx]);
4983 }
4984 }
4985 valid_obs_ct = DosageR2Freqs(dosage_vecs[0], nm_bitvecs[0], dosage_vecs[1], nm_bitvecs[1], founder_ct, nm_cts[0], nm_cts[1], nmaj_dosages);
4986 if (unlikely(!valid_obs_ct)) {
4987 goto LdConsole_ret_NO_VALID_OBSERVATIONS;
4988 }
4989 nmajsums_d[0] = u63tod(nmaj_dosages[0]) * kRecipDosageMid;
4990 nmajsums_d[1] = u63tod(nmaj_dosages[1]) * kRecipDosageMid;
4991 uint64_t known_dotprod_dosage;
4992 uint64_t uhethet_dosage;
4993 if (!x_male_ct) {
4994 if (!use_phase) {
4995 DosageUnphasedDotprodComponents(dosage_vecs[0], dosage_vecs[1], dosage_hets[0], dosage_hets[1], founder_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
4996 } else {
4997 DosagePhasedDotprodComponents(dosage_vecs[0], dosage_vecs[1], main_dphase_deltas[0], main_dphase_deltas[1], founder_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
4998 }
4999 known_dotprod_d = u63tod(known_dotprod_dosage) * kRecipDosageMax;
5000 unknown_hethet_d = u63tod(uhethet_dosage) * kRecipDosageMax;
5001 } else {
5002 Dosage* x_nonmale_dosage_invmask;
5003 Dosage* x_male_dosage_invmask;
5004 uintptr_t* sex_nonmale_collapsed;
5005 uintptr_t* nm_buf;
5006 Dosage* invmask_buf;
5007 if (unlikely(bigstack_alloc_dosage(founder_ct, &x_nonmale_dosage_invmask) ||
5008 bigstack_alloc_dosage(founder_ct, &x_male_dosage_invmask) ||
5009 bigstack_alloc_w(founder_ctl, &sex_nonmale_collapsed) ||
5010 bigstack_alloc_w(founder_ctl, &nm_buf) ||
5011 bigstack_alloc_dosage(founder_ct, &invmask_buf))) {
5012 goto LdConsole_ret_NOMEM;
5013 }
5014 BitvecInvertCopy(sex_male_collapsed, founder_ctl, sex_nonmale_collapsed);
5015 ZeroTrailingBits(founder_ct, sex_nonmale_collapsed);
5016 Expand1bitTo16(sex_nonmale_collapsed, RoundUpPow2(founder_ct, kDosagePerVec), 0xffff, x_nonmale_dosage_invmask);
5017 Expand1bitTo16(sex_male_collapsed, RoundUpPow2(founder_ct, kDosagePerVec), 0xffff, x_male_dosage_invmask);
5018 uint32_t x_male_nm_cts[2];
5019 x_male_nm_cts[0] = PopcountWordsIntersect(sex_male_collapsed, nm_bitvecs[0], founder_ctl);
5020 x_male_nm_cts[1] = PopcountWordsIntersect(sex_male_collapsed, nm_bitvecs[1], founder_ctl);
5021 uint64_t x_male_nmaj_dosages[2];
5022 x_male_nmaj_dosages[0] = DenseDosageSumSubset(dosage_vecs[0], x_male_dosage_invmask, founder_dosagev_ct);
5023 x_male_nmaj_dosages[1] = DenseDosageSumSubset(dosage_vecs[1], x_male_dosage_invmask, founder_dosagev_ct);
5024 valid_x_male_ct = DosageR2FreqsSubset(dosage_vecs[0], nm_bitvecs[0], dosage_vecs[1], nm_bitvecs[1], sex_male_collapsed, founder_ct, x_male_ct, x_male_nm_cts[0], x_male_nm_cts[1], x_male_nmaj_dosages, nm_buf, invmask_buf);
5025 if (!use_phase) {
5026 DosageUnphasedDotprodComponentsSubset(x_nonmale_dosage_invmask, dosage_vecs[0], dosage_vecs[1], dosage_hets[0], dosage_hets[1], founder_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
5027 } else {
5028 DosagePhasedDotprodComponentsSubset(x_nonmale_dosage_invmask, dosage_vecs[0], dosage_vecs[1], main_dphase_deltas[0], main_dphase_deltas[1], founder_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
5029 }
5030 uint64_t x_male_known_dotprod_dosage;
5031 uint64_t x_male_uhethet_dosage;
5032 DosageUnphasedDotprodComponentsSubset(x_male_dosage_invmask, dosage_vecs[0], dosage_vecs[1], dosage_hets[0], dosage_hets[1], founder_dosagev_ct, &x_male_known_dotprod_dosage, &x_male_uhethet_dosage);
5033
5034 // males have sqrt(0.5) weight if one variant is chrX, half-weight if
5035 // both are chrX
5036 const double male_mult = (is_xs[0] && is_xs[1])? 0.5 : (0.5 * kSqrt2);
5037 // unknown_hethet_d = u63tod(uhethet_dosage) * kRecipDosageMax;
5038 known_dotprod_d = (u63tod(known_dotprod_dosage) + male_mult * u63tod(x_male_known_dotprod_dosage)) * kRecipDosageMax;
5039 unknown_hethet_d = (u63tod(uhethet_dosage) + male_mult * u63tod(x_male_uhethet_dosage)) * kRecipDosageMax;
5040 x_male_nmajsums_d[0] = u63tod(x_male_nmaj_dosages[0]) * kRecipDosageMid;
5041 x_male_nmajsums_d[1] = u63tod(x_male_nmaj_dosages[1]) * kRecipDosageMid;
5042 }
5043 }
5044 double valid_obs_d = u31tod(valid_obs_ct);
5045 if (valid_x_male_ct) {
5046 const double male_decr = (is_xs[0] && is_xs[1])? 0.5 : (1.0 - 0.5 * kSqrt2);
5047 nmajsums_d[0] -= male_decr * x_male_nmajsums_d[0];
5048 nmajsums_d[1] -= male_decr * x_male_nmajsums_d[1];
5049 valid_obs_d -= male_decr * u31tod(valid_x_male_ct);
5050 }
5051
5052 const double twice_tot_recip = 0.5 / valid_obs_d;
5053 // in plink 1.9, "freq12" refers to first variant=1, second variant=2
5054 // this most closely corresponds to freq_majmin here
5055 PhasedLDExtraRet extra_ret;
5056 double cubic_sols[3];
5057 const LDErr ld_err = PhasedLD(nmajsums_d, known_dotprod_d, unknown_hethet_d, twice_tot_recip, 1, &extra_ret, cubic_sols, nullptr);
5058 if (ld_err) {
5059 logerrprintfww("Warning: Skipping --ld since %s is monomorphic across all valid observations.\n", ld_console_varids[ld_err - 1]);
5060 goto LdConsole_ret_1;
5061 }
5062 logputs("\n");
5063 logprintfww("--ld %s %s:\n", ld_console_varids[0], ld_console_varids[1]);
5064 logputs("\n");
5065
5066 char* write_poststop = &(g_logbuf[80]);
5067 uint32_t varid_slens[2];
5068 uint32_t cur_allele_ct = 2;
5069 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
5070 const uint32_t cur_variant_uidx = var_uidxs[var_idx];
5071 uintptr_t allele_idx_offset_base = cur_variant_uidx * 2;
5072 if (allele_idx_offsets) {
5073 allele_idx_offset_base = allele_idx_offsets[cur_variant_uidx];
5074 cur_allele_ct = allele_idx_offsets[cur_variant_uidx + 1] - allele_idx_offset_base;
5075 }
5076 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5077
5078 const char* cur_varid = ld_console_varids[var_idx];
5079 const uint32_t cur_varid_slen = strlen(ld_console_varids[var_idx]);
5080 varid_slens[var_idx] = cur_varid_slen;
5081 char* write_iter = memcpya(g_logbuf, cur_varid, cur_varid_slen);
5082 write_iter = strcpya_k(write_iter, " alleles:\n");
5083 *write_iter = '\0';
5084 WordWrapB(0);
5085 logputsb();
5086 write_iter = strcpya_k(g_logbuf, " MAJOR = ");
5087 const uint32_t maj_idx = maj_alleles[cur_variant_uidx];
5088 const char* maj_allele = cur_alleles[maj_idx];
5089 const uint32_t maj_slen = strlen(maj_allele);
5090 uint32_t slen_limit = 70;
5091 if (!maj_idx) {
5092 write_iter = strcpya_k(write_iter, "REF = ");
5093 slen_limit -= 6;
5094 }
5095 if (maj_slen < slen_limit) {
5096 write_iter = memcpyax(write_iter, maj_allele, maj_slen, '\n');
5097 } else {
5098 write_iter = memcpya(write_iter, maj_allele, slen_limit - 3);
5099 write_iter = strcpya_k(write_iter, "...\n");
5100 }
5101 *write_iter = '\0';
5102 logputsb();
5103 write_iter = strcpya_k(g_logbuf, " MINOR = ");
5104 uint32_t allele_idx = (maj_idx == 0)? 1 : 0;
5105 while (1) {
5106 const char* cur_allele = cur_alleles[allele_idx];
5107 const uint32_t cur_slen = strlen(cur_allele);
5108 if (S_CAST(uintptr_t, write_poststop - write_iter) <= cur_slen) {
5109 char* write_ellipsis_start = &(g_logbuf[76]);
5110 if (write_ellipsis_start > write_iter) {
5111 const uint32_t final_char_ct = S_CAST(uintptr_t, write_ellipsis_start - write_iter);
5112 memcpy(write_iter, cur_allele, final_char_ct);
5113 }
5114 write_iter = strcpya_k(write_ellipsis_start, "...");
5115 break;
5116 }
5117 write_iter = memcpya(write_iter, cur_allele, cur_slen);
5118 ++allele_idx;
5119 if (allele_idx == maj_idx) {
5120 ++allele_idx;
5121 }
5122 if (allele_idx == cur_allele_ct) {
5123 break;
5124 }
5125 *write_iter++ = ',';
5126 }
5127 *write_iter++ = '\n';
5128 *write_iter = '\0';
5129 logputsb();
5130 if (maj_idx) {
5131 write_iter = strcpya_k(g_logbuf, " (REF = ");
5132 const char* ref_allele = cur_alleles[0];
5133 const uint32_t ref_slen = strlen(ref_allele);
5134 if (ref_slen < 70) {
5135 write_iter = memcpya(write_iter, ref_allele, ref_slen);
5136 } else {
5137 write_iter = memcpya(write_iter, ref_allele, 67);
5138 write_iter = strcpya_k(write_iter, "...");
5139 }
5140 memcpy_k(write_iter, ")\n\0", 4);
5141 logputsb();
5142 }
5143 }
5144 logputs("\n");
5145 char* write_iter = u32toa(valid_obs_ct, g_logbuf);
5146 write_iter = strcpya_k(write_iter, " valid");
5147 if (y_ct) {
5148 write_iter = strcpya_k(write_iter, " non-female");
5149 }
5150 write_iter = strcpya_k(write_iter, " sample");
5151 if (valid_obs_ct != 1) {
5152 *write_iter++ = 's';
5153 }
5154 if (valid_x_male_ct && ((!y_ct) || (valid_x_male_ct < valid_obs_ct))) {
5155 write_iter = strcpya_k(write_iter, " (");
5156 write_iter = u32toa(valid_x_male_ct, write_iter);
5157 write_iter = strcpya_k(write_iter, " male)");
5158 }
5159 if (unknown_hethet_d == 0.0) {
5160 // not currently checking for (fractional) het pairs in dosage case.
5161 if (!use_dosage) {
5162 write_iter = strcpya_k(write_iter, "; ");
5163 if (hethet_hc_found) {
5164 write_iter = strcpya_k(write_iter, "all phased");
5165 } else {
5166 // not a literal "het pair" in the haploid case, but same concept, so
5167 // I'll just leave the language unchanged for now
5168 write_iter = strcpya_k(write_iter, "no het pairs present");
5169 }
5170 }
5171 } else {
5172 write_iter = strcpya_k(write_iter, "; ");
5173 // ddosagetoa() assumes kDosageMax rather than kDosageMid multiplier
5174 const uint64_t unknown_hethet_int_ddosage = S_CAST(int64_t, unknown_hethet_d * kDosageMax);
5175 char* write_iter2 = ddosagetoa(unknown_hethet_int_ddosage, write_iter);
5176 const uint32_t wrote_exactly_1 = (write_iter2 == &(write_iter[1])) && (write_iter[0] == '1');
5177 write_iter = strcpya_k(write_iter2, " het pair");
5178 if (!wrote_exactly_1) {
5179 *write_iter++ = 's';
5180 }
5181 write_iter = strcpya_k(write_iter, " statistically phased");
5182 }
5183 assert(write_iter - g_logbuf < 78);
5184 memcpy_k(write_iter, ".\n\0", 4);
5185 logputsb();
5186
5187 // sol_ct does not contain trailing too-large solutions
5188 const uint32_t sol_ct = extra_ret.sol_ct;
5189 if (sol_ct > 1) {
5190 logputs("Multiple phasing solutions; sample size, HWE, or random mating assumption may\nbe violated.\n\nHWE exact test p-values\n-----------------------\n");
5191 // (can't actually get here in nonx_haploid_or_mt case, impossible to
5192 // have a hethet)
5193
5194 const uint32_t hwe_midp = (ldip->ld_console_flags / kfLdConsoleHweMidp) & 1;
5195 uint32_t x_nosex_ct = 0; // usually shouldn't exist, but...
5196 uintptr_t* nosex_collapsed = nullptr;
5197 if (x_present) {
5198 x_nosex_ct = founder_ct - PopcountWordsIntersect(founder_info, sex_nm, raw_sample_ctl);
5199 if (x_nosex_ct) {
5200 if (unlikely(bigstack_alloc_w(founder_ctl, &nosex_collapsed))) {
5201 goto LdConsole_ret_NOMEM;
5202 }
5203 CopyBitarrSubset(sex_nm, founder_info, founder_ct, nosex_collapsed);
5204 // bugfix (17 Oct 2023): need to pass bit count, not word count
5205 AlignedBitarrInvert(founder_ct, nosex_collapsed);
5206 }
5207 }
5208 // Unlike plink 1.9, we don't restrict these HWE computations to the
5209 // nonmissing intersection.
5210 for (uint32_t var_idx = 0; var_idx != 2; ++var_idx) {
5211 const uintptr_t* cur_genovec = pgvs[var_idx].genovec;
5212 STD_ARRAY_DECL(uint32_t, 4, genocounts);
5213 GenoarrCountFreqsUnsafe(cur_genovec, founder_ct, genocounts);
5214 write_iter = strcpya_k(g_logbuf, " ");
5215 write_iter = strcpya(write_iter, ld_console_varids[var_idx]);
5216 write_iter = strcpya_k(write_iter, ": ");
5217 double hwe_ln_pval;
5218 if (!is_xs[var_idx]) {
5219 hwe_ln_pval = HweLnP(genocounts[1], genocounts[0], genocounts[2], hwe_midp);
5220 } else {
5221 STD_ARRAY_DECL(uint32_t, 4, male_genocounts);
5222 GenoarrCountSubsetFreqs(cur_genovec, sex_male_collapsed_interleaved, founder_ct, x_male_ct, male_genocounts);
5223 assert(!male_genocounts[1]);
5224 if (x_nosex_ct) {
5225 STD_ARRAY_DECL(uint32_t, 4, nosex_genocounts);
5226 GenoarrCountSubsetFreqs2(cur_genovec, nosex_collapsed, founder_ct, x_nosex_ct, nosex_genocounts);
5227 genocounts[0] -= nosex_genocounts[0];
5228 genocounts[1] -= nosex_genocounts[1];
5229 genocounts[2] -= nosex_genocounts[2];
5230 }
5231 hwe_ln_pval = HweXchrLnP(genocounts[1], genocounts[0] - male_genocounts[0], genocounts[2] - male_genocounts[2], male_genocounts[0], male_genocounts[2], hwe_midp);
5232 }
5233 write_iter = lntoa_g(hwe_ln_pval, write_iter);
5234 memcpy_k(write_iter, "\n", 2);
5235 logputsb();
5236 }
5237 }
5238 logputs("\n");
5239
5240 const uint32_t best_lnlike_mask = extra_ret.best_lnlike_mask;
5241 const double freq_majmaj = extra_ret.freq_majmaj;
5242 const double freq_majmin = extra_ret.freq_majmin;
5243 const double freq_minmaj = extra_ret.freq_minmaj;
5244 const double freq_minmin = extra_ret.freq_minmin;
5245 const double half_unphased_hethet_share = extra_ret.half_unphased_hethet_share;
5246 const double freq_majx = extra_ret.freq_majx;
5247 const double freq_minx = extra_ret.freq_minx;
5248 const double freq_xmaj = extra_ret.freq_xmaj;
5249 const double freq_xmin = extra_ret.freq_xmin;
5250 for (uint32_t sol_idx = 0; sol_idx < sol_ct; ++sol_idx) {
5251 if (sol_ct > 1) {
5252 write_iter = strcpya_k(g_logbuf, "Solution #");
5253 write_iter = u32toa(sol_idx + 1, write_iter);
5254 if ((best_lnlike_mask >> sol_idx) & 1) {
5255 write_iter = strcpya_k(write_iter, " (");
5256 if (best_lnlike_mask & ((1 << sol_idx) - 1)) {
5257 write_iter = strcpya_k(write_iter, "tied for ");
5258 }
5259 write_iter = strcpya_k(write_iter, "best likelihood)");
5260 }
5261 assert(write_iter - g_logbuf < 78);
5262 memcpy_k(write_iter, ":\n\0", 4);
5263 logputsb();
5264 }
5265 const double cur_sol_xx = cubic_sols[sol_idx];
5266 double dd = freq_majmaj + cur_sol_xx - freq_majx * freq_xmaj;
5267 if (fabs(dd) < kSmallEpsilon) {
5268 dd = 0.0;
5269 }
5270 write_iter = strcpya_k(g_logbuf, " r^2 = ");
5271 write_iter = dtoa_g(dd * dd / (freq_majx * freq_xmaj * freq_minx * freq_xmin), write_iter);
5272 write_iter = strcpya_k(write_iter, " |D'| = ");
5273 double d_prime;
5274 if (dd >= 0.0) {
5275 d_prime = dd / MINV(freq_xmaj * freq_minx, freq_xmin * freq_majx);
5276 } else {
5277 d_prime = -dd / MINV(freq_xmaj * freq_majx, freq_xmin * freq_minx);
5278 }
5279 write_iter = dtoa_g(d_prime, write_iter);
5280 assert(write_iter - g_logbuf < 79);
5281 strcpy_k(write_iter, "\n");
5282 logputsb();
5283
5284 logputs("\n");
5285
5286 // Default layout:
5287 // [8 spaces]Frequencies : [centered varID[1]]
5288 // (expectations under LE) MAJOR MINOR
5289 // ---------- ----------
5290 // MAJOR a.bcdefg a.bcdefg
5291 // (a.bcdefg) (a.bcdefg)
5292 // [r-justified varID[0]]
5293 // MINOR a.bcdefg a.bcdefg
5294 // (a.bcdefg) (a.bcdefg)
5295 //
5296 // (decimals are fixed-point, and trailing zeroes are erased iff there is
5297 // an exact match to ~13-digit precision; this is slightly more stringent
5298 // than plink 1.9's dtoa_f_w9p6_spaced() since there isn't much room here
5299 // for floating-point error to accumulate)
5300 // As for long variant IDs:
5301 // The default layout uses 55 columns, and stops working when
5302 // strlen(varID[0]) > 26. So the right half can be shifted up to 24
5303 // characters before things get ugly in terminal windows. Thus, once
5304 // string length > 50, we print only the first 47 characters of varID and
5305 // follow it with "...".
5306 // Similarly, when strlen(varID[1]) <= 51, centering is pretty
5307 // straightforward; beyond that, we print only the first 48 chars.
5308 uint32_t extra_initial_spaces = 0;
5309 const uint32_t varid_slen0 = varid_slens[0];
5310 if (varid_slen0 > 26) {
5311 // formatting fix (1 Feb 2018): cap this at 24, not 50
5312 extra_initial_spaces = MINV(varid_slen0 - 26, 24);
5313 }
5314 write_iter = strcpya_k(g_logbuf, " Frequencies : ");
5315 // default center column index is 43 + extra_initial_spaces; we're
5316 // currently at column 28
5317 // for length-1, we want to occupy just the center column index; for
5318 // length-2, both center and (center + 1), etc.
5319 // ((16 + extra_initial_spaces) * 2 - strlen(varID[1])) / 2
5320 const uint32_t varid_slen1 = varid_slens[1];
5321 if (varid_slen1 > 51) {
5322 write_iter = memcpya(write_iter, ld_console_varids[1], 48);
5323 write_iter = strcpya_k(write_iter, "...");
5324 } else {
5325 uint32_t offset_x2 = (16 + extra_initial_spaces) * 2;
5326 if (offset_x2 > varid_slen1) {
5327 uint32_t varid1_padding = (offset_x2 - varid_slen1) / 2;
5328 if (varid1_padding + varid_slen1 > 51) {
5329 varid1_padding = 51 - varid_slen1;
5330 }
5331 write_iter = memseta(write_iter, 32, varid1_padding);
5332 }
5333 write_iter = memcpya(write_iter, ld_console_varids[1], varid_slen1);
5334 }
5335 strcpy_k(write_iter, "\n");
5336 logputsb();
5337
5338 write_iter = strcpya_k(g_logbuf, " (expectations under LE)");
5339 write_iter = memseta(write_iter, 32, extra_initial_spaces + 10);
5340 snprintf(write_iter, 81 - 25 - 24 - 10, "MAJOR MINOR\n");
5341 logputsb();
5342
5343 write_iter = memseta(g_logbuf, 32, extra_initial_spaces + 33);
5344 snprintf(write_iter, 81 - 24 - 33, "---------- ----------\n");
5345 logputsb();
5346
5347 write_iter = strcpya_k(&(g_logbuf[27 + extra_initial_spaces]), "MAJOR ");
5348 write_iter = dtoa_f_probp6_spaced(freq_majmaj + cur_sol_xx, write_iter);
5349 write_iter = strcpya_k(write_iter, " ");
5350 const double cur_sol_xy = half_unphased_hethet_share - cur_sol_xx;
5351 write_iter = dtoa_f_probp6_clipped(freq_majmin + cur_sol_xy, write_iter);
5352 strcpy_k(write_iter, "\n");
5353 logputsb();
5354
5355 write_iter = strcpya_k(&(g_logbuf[27 + extra_initial_spaces]), " (");
5356 char* next_paren_open = &(write_iter[11]);
5357 write_iter = dtoa_f_probp6_clipped(freq_xmaj * freq_majx, write_iter);
5358 *write_iter++ = ')';
5359 memset(write_iter, ' ', next_paren_open - write_iter);
5360 *next_paren_open++ = '(';
5361 write_iter = dtoa_f_probp6_clipped(freq_xmin * freq_majx, next_paren_open);
5362 memcpy_k(write_iter, ")\n\0", 4);
5363 logputsb();
5364
5365 write_iter = g_logbuf;
5366 if (varid_slen0 < 26) {
5367 write_iter = &(write_iter[26 - varid_slen0]);
5368 }
5369 write_iter = memcpya(write_iter, ld_console_varids[0], varid_slen0);
5370 strcpy_k(write_iter, "\n");
5371 logputsb();
5372
5373 write_iter = memseta(g_logbuf, 32, 27 + extra_initial_spaces);
5374 write_iter = strcpya_k(write_iter, "MINOR ");
5375 write_iter = dtoa_f_probp6_spaced(freq_minmaj + cur_sol_xy, write_iter);
5376 write_iter = strcpya_k(write_iter, " ");
5377 write_iter = dtoa_f_probp6_clipped(freq_minmin + cur_sol_xx, write_iter);
5378 strcpy_k(write_iter, "\n");
5379 logputsb();
5380
5381 write_iter = strcpya_k(&(g_logbuf[27 + extra_initial_spaces]), " (");
5382 next_paren_open = &(write_iter[11]);
5383 write_iter = dtoa_f_probp6_clipped(freq_xmaj * freq_minx, write_iter);
5384 *write_iter++ = ')';
5385 memset(write_iter, ' ', next_paren_open - write_iter);
5386 *next_paren_open++ = '(';
5387 write_iter = dtoa_f_probp6_clipped(freq_xmin * freq_minx, next_paren_open);
5388 memcpy_k(write_iter, ")\n\0", 4);
5389 logputsb();
5390
5391 logputs("\n");
5392 if (dd > 0.0) {
5393 logputs(" Major alleles are in phase with each other.\n\n");
5394 } else if (dd < 0.0) {
5395 logputs(" Major alleles are out of phase with each other.\n\n");
5396 }
5397 }
5398 }
5399 while (0) {
5400 LdConsole_ret_NOMEM:
5401 reterr = kPglRetNomem;
5402 break;
5403 LdConsole_ret_INCONSISTENT_INPUT_WW:
5404 WordWrapB(0);
5405 logerrputsb();
5406 LdConsole_ret_INCONSISTENT_INPUT:
5407 reterr = kPglRetInconsistentInput;
5408 break;
5409 LdConsole_ret_NO_VALID_OBSERVATIONS:
5410 logerrputs("Error: No valid observations for --ld.\n");
5411 reterr = kPglRetDegenerateData;
5412 break;
5413 }
5414 LdConsole_ret_1:
5415 BigstackReset(bigstack_mark);
5416 return reterr;
5417 }
5418
5419 // distinguish fully-unphased r^2 computation from no-phased-calls subcase in
5420 // phased-r^2 computation
5421 ENUM_U31_DEF_START()
5422 kR2PhaseTypeUnphased,
5423 kR2PhaseTypeOmit,
5424 kR2PhaseTypePresent
5425 ENUM_U31_DEF_END(R2PhaseType);
5426
5427 static inline R2PhaseType R2PhaseOmit(R2PhaseType phase_type) {
5428 // convert kR2PhaseTypePresent to kR2PhaseTypeOmit, leave other values
5429 // unchanged
5430 return S_CAST(R2PhaseType, phase_type != kR2PhaseTypeUnphased);
5431 }
5432
5433 static inline R2PhaseType GetR2PhaseType(uint32_t phased_r2, uint32_t phase_present) {
5434 return S_CAST(R2PhaseType, phased_r2 * (1 + phase_present));
5435 }
5436
5437 // ***** --clump implementation starts here *****
5438 // We want to support --glm's handling of multiallelic variants, where we're
5439 // working in terms of (variant, allele) pairs rather than just variants.
5440 // So we maintain variant-based *and* allele-based bitvectors tracking the
5441 // pairs under consideration.
5442 //
5443 // Current multithreading strategies are restricted to a single index variant
5444 // at a time across all threads. Possible todo: implement a strategy similar
5445 // to --indep-pair{phase,wise}, where each thread works on its own island, and
5446 // benchmark on typical datasets against the existing implementation.
5447
5448 uint32_t GetNextIsland(const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* icandidate_vbitvec, const uintptr_t* observed_variants, uint32_t raw_variant_ct, uint32_t bp_radius, uint32_t* vidx_endp, uint32_t* chr_fo_idxp) {
5449 uint32_t vidx_start = *vidx_endp;
5450 uint32_t index_vidx = AdvBoundedTo1Bit(icandidate_vbitvec, vidx_start, raw_variant_ct);
5451 if (index_vidx == raw_variant_ct) {
5452 // ensure chr_fo_idx compares unequal
5453 *chr_fo_idxp = UINT32_MAX;
5454 return raw_variant_ct;
5455 }
5456 uint32_t chr_fo_idx = *chr_fo_idxp;
5457 uint32_t chr_end_vidx = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5458 if (index_vidx >= chr_end_vidx) {
5459 chr_fo_idx = GetVariantChrFoIdx(cip, index_vidx);
5460 *chr_fo_idxp = chr_fo_idx;
5461 chr_end_vidx = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5462 }
5463 uint32_t index_variant_bp = variant_bps[index_vidx];
5464 const uint32_t chr_start_vidx = cip->chr_fo_vidx_start[chr_fo_idx];
5465
5466 // Locate the left end of the island. This is straightforward since we
5467 // already have the leftmost index variant.
5468 uint32_t search_bp = (index_variant_bp < bp_radius)? 0 : (index_variant_bp - bp_radius);
5469 const uint32_t first_vidx_in_range = LowerBoundConstrainedNonemptyU32(variant_bps, chr_start_vidx, chr_end_vidx, search_bp);
5470 vidx_start = AdvTo1Bit(observed_variants, first_vidx_in_range);
5471
5472 // Now locate the right end of the island. This requires either
5473 // - identifying a pair of index variants that are more than bp_radius bp
5474 // apart from each other, which also don't share a non-index variant
5475 // candidate; or
5476 // - reaching the end of the chromosome without observing such a gap.
5477 uint32_t last_known_bp = index_variant_bp;
5478 for (uint32_t vidx_end = index_vidx + 1; ; ++vidx_end) {
5479 // Jump (bp_radius + 1) bp to the right, and identify the index variants
5480 // flanking that spot. (We know the end of the island cannot come before
5481 // this boundary.)
5482 vidx_end = ExpsearchU32(variant_bps, vidx_end, chr_end_vidx, last_known_bp + bp_radius + 1);
5483 const uint32_t last_index_vidx = FindLast1BitBefore(icandidate_vbitvec, vidx_end);
5484 const uint32_t last_index_bp = variant_bps[last_index_vidx];
5485 vidx_end = AdvBoundedTo1Bit(icandidate_vbitvec, vidx_end, chr_end_vidx);
5486 // Now vidx_end is either the first possibly-out-of-island index variant,
5487 // or equal to chr_end_vidx (which indicates end-of-chromosome).
5488 if (vidx_end < chr_end_vidx) {
5489 const uint32_t later_index_bp = variant_bps[vidx_end];
5490 const uint32_t delta = later_index_bp - last_index_bp;
5491 if (delta <= bp_radius) {
5492 // Obviously no gap here.
5493 last_known_bp = later_index_bp;
5494 continue;
5495 }
5496 }
5497 // Either the next index variant is separated by > bp_radius bp from the
5498 // last confirmed on-island index variant, or no such next index variant
5499 // exists at all.
5500 // In both cases, we want to locate the rightmost index-or-non-index
5501 // variant in range of the last confirmed on-island index variant.
5502 const uint32_t search_start_vidx = last_index_vidx + 1;
5503 const uint32_t first_out_of_range_vidx = ExpsearchU32(variant_bps, search_start_vidx, chr_end_vidx, last_index_bp + bp_radius + 1);
5504 const uint32_t last_in_range_vidx = FindLast1BitBefore(observed_variants, first_out_of_range_vidx);
5505 if ((vidx_end == chr_end_vidx) || (variant_bps[vidx_end] - variant_bps[last_in_range_vidx] <= bp_radius)) {
5506 *vidx_endp = last_in_range_vidx + 1;
5507 return vidx_start;
5508 }
5509 last_known_bp = variant_bps[vidx_end];
5510 }
5511 }
5512
5513 // allele_idx_first and _last, instead of _start and _end, because some
5514 // allele_idxs are skipped.
5515 uint32_t GetNextIslandIdxs(const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const uintptr_t* icandidate_vbitvec, const uintptr_t* observed_variants, const uintptr_t* observed_alleles, const uintptr_t* observed_alleles_cumulative_popcounts_w, uint32_t raw_variant_ct, uint32_t bp_radius, uintptr_t* oaidx_startp, uintptr_t* oaidx_endp, uint32_t* vidx_endp, uint32_t* chr_fo_idxp, uintptr_t* allele_idx_firstp, uintptr_t* allele_idx_lastp) {
5516 uint32_t vidx_start = GetNextIsland(cip, variant_bps, icandidate_vbitvec, observed_variants, raw_variant_ct, bp_radius, vidx_endp, chr_fo_idxp);
5517 if (vidx_start == raw_variant_ct) {
5518 return raw_variant_ct;
5519 }
5520 const uint32_t vidx_end = *vidx_endp;
5521 uintptr_t allele_idx_first;
5522 uintptr_t allele_idx_last;
5523 if (!allele_idx_offsets) {
5524 allele_idx_first = vidx_start * 2;
5525 allele_idx_last = vidx_end * 2;
5526 } else {
5527 allele_idx_first = allele_idx_offsets[vidx_start];
5528 allele_idx_last = allele_idx_offsets[vidx_end];
5529 }
5530 allele_idx_first = AdvTo1Bit(observed_alleles, allele_idx_first);
5531 allele_idx_last = FindLast1BitBefore(observed_alleles, allele_idx_last);
5532 *allele_idx_firstp = allele_idx_first;
5533 *allele_idx_lastp = allele_idx_last;
5534 if (oaidx_startp) {
5535 *oaidx_startp = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_idx_first);
5536 }
5537 *oaidx_endp = 1 + RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_idx_last);
5538 return vidx_start;
5539 }
5540
5541 void ScanPhaseDosage(const uintptr_t* observed_variants, PgenFileInfo* pgfip, uint32_t vidx_start, uint32_t vidx_end, uint32_t check_phase, uint32_t check_dosage, uint32_t* load_phasep, uint32_t* load_dosagep) {
5542 uint32_t vrtype_mask = 0;
5543 if (*load_phasep != check_phase) {
5544 vrtype_mask |= 0x90;
5545 }
5546 if (*load_dosagep != check_dosage) {
5547 vrtype_mask |= 0x60;
5548 }
5549 if (!vrtype_mask) {
5550 return;
5551 }
5552 // I suspect this is faster than calling AdvBoundedTo1Bit in the inner loop?
5553 // Todo: benchmark.
5554 const uint32_t vidx_ct = PopcountBitRange(observed_variants, vidx_start, vidx_end);
5555 uintptr_t variant_uidx_base;
5556 uintptr_t cur_bits;
5557 BitIter1Start(observed_variants, vidx_start, &variant_uidx_base, &cur_bits);
5558 for (uint32_t uii = 0; uii != vidx_ct; ++uii) {
5559 const uintptr_t variant_uidx = BitIter1(observed_variants, &variant_uidx_base, &cur_bits);
5560 const uint32_t vrtype = GetPgfiVrtype(pgfip, variant_uidx);
5561 const uint32_t vrtype_masked = vrtype & vrtype_mask;
5562 if (vrtype_masked) {
5563 if (vrtype_masked & 0x90) {
5564 *load_phasep = 1;
5565 vrtype_mask &= ~0x90;
5566 }
5567 if (vrtype_masked & 0x60) {
5568 *load_dosagep = 1;
5569 vrtype_mask &= ~0x60;
5570 }
5571 if (!vrtype_mask) {
5572 return;
5573 }
5574 }
5575 }
5576 }
5577
5578 typedef struct ClumpEntryStruct {
5579 struct ClumpEntryStruct* next;
5580 uint32_t pval_bin_x2; // low bit indicates >= --clump-p2 threshold
5581 uint32_t file_idx1_x2; // low bit indicates A1=ALT in force_a1 case
5582 } ClumpEntry;
5583
5584 typedef struct ClumpPvalStruct {
5585 double ln_pval;
5586 uintptr_t allele_idx;
5587 #ifdef __cplusplus
5588 bool operator<(const struct ClumpPvalStruct& rhs) const {
5589 if (ln_pval != rhs.ln_pval) {
5590 return (ln_pval < rhs.ln_pval);
5591 }
5592 return allele_idx < rhs.allele_idx;
5593 }
5594 #endif
5595 } ClumpPval;
5596
5597 #ifndef __cplusplus
5598 int32_t ClumpPvalCmp(const void* aa, const void* bb) {
5599 const ClumpPval* cp1 = S_CAST(const ClumpPval*, aa);
5600 const ClumpPval* cp2 = S_CAST(const ClumpPval*, bb);
5601 const double ln_pval1 = cp1->ln_pval;
5602 const double ln_pval2 = cp2->ln_pval;
5603 if (ln_pval1 != ln_pval2) {
5604 return (ln_pval1 < ln_pval2)? -1 : 1;
5605 }
5606 return (cp1->allele_idx < cp2->allele_idx)? -1 : 1;
5607 }
5608 #endif
5609
5610 ENUM_U31_DEF_START()
5611 kClumpJobNone,
5612 kClumpJobHighmemUnpack,
5613 kClumpJobHighmemR2,
5614 kClumpJobLowmemR2
5615 ENUM_U31_DEF_END(ClumpJobType);
5616
5617 // Unpacked representations:
5618 // 1. If not loading dosage:
5619 // a. If not loading phase:
5620 // uint32_t is_sparse, nm_ct, nmaj_ct, ssq:
5621 // RoundUpPow2(16, kBytesPerVec)
5622 // {one_bitvec, two_bitvec, nm_bitvec}: founder_ctaw words each, total
5623 // 3 * bitvec_byte_ct
5624 // uint32_t x_male_nm_ct, x_male_nmaj_ct, x_male_ssq: if chrX, another
5625 // RoundUpPow2(12, kBytesPerVec)
5626 // (sparse representation usually smaller, but need to compare if not
5627 // AVX2)
5628 // Male-specific values placed in the back so that the unpacker doesn't
5629 // need to distinguish between no-x-male-stats and
5630 // x-male-stats-not-needed.
5631 // b. If loading phase, also need phasepresent and phaseinfo, founder_ctaw
5632 // words each, for a total of 5 * bitvec_byte_ct +
5633 // RoundUpPow2(16, kBytesPerVec) + RoundUpPow2(0|12, kBytesPerVec)
5634 // 2. If loading dosage:
5635 // a. If not loading phase:
5636 // {dosage_vec, dosage_het}: founder_dosagev_ct vectors each; plus
5637 // nm_bitvec, i.e. 2 * dosagevec_byte_ct + bitvec_byte_ct
5638 // uint64_t nmaj_dosage, nmaj_dosage_ssq?, uint32_t nm_ct,
5639 // x_male_nm_ct?, uint64_t x_male_nmaj_dosage?,
5640 // x_male_nmaj_dosage_ssq?: RoundUpPow2({12|20|24|40}, kBytesPerVec)
5641 // b. If loading phase, also need main_dphase_deltas, for a total of
5642 // 3 * dosagevec_byte_ct + bitvec_byte_ct + RoundUpPow2({12|20|24|40},
5643 // kBytesPerVec)
5644 //
5645 // Possible todo: Unpack the index variant in a way that allows r^2 to be
5646 // computed efficiently against other variants *without* unpacking them.
5647
5648 // In the HighmemUnpack step, the main thread wants to prepare the next copy of
5649 // this while the worker threads are processing the current copy.
5650 typedef struct ClumpCtxAlternatingStruct {
5651 uintptr_t* oaidx_starts;
5652
5653 unsigned char padding[kCacheline];
5654 } ClumpCtxAlternating;
5655
5656 typedef struct ClumpCtxStruct {
5657 // Shared constants.
5658 const uintptr_t* observed_variants;
5659 const uintptr_t* allele_idx_offsets;
5660 const uintptr_t* variant_last_alidxs;
5661 const uint32_t* variant_last_alidxs_cumulative_popcounts;
5662 const uintptr_t* observed_alleles;
5663 const uintptr_t* observed_alleles_cumulative_popcounts_w;
5664 const uintptr_t* founder_info;
5665 const uint32_t* founder_info_cumulative_popcounts;
5666 const uintptr_t* founder_male_collapsed;
5667 const Dosage* male_dosage_invmask;
5668 const uintptr_t* founder_nonmale_collapsed;
5669 const Dosage* nonmale_dosage_invmask;
5670 const uintptr_t* founder_female_collapsed;
5671 const uintptr_t* founder_female_collapsed_interleaved;
5672 uint32_t founder_ct;
5673 uint32_t founder_male_ct;
5674 // Precomputed for convenience.
5675 uintptr_t pgv_byte_stride;
5676 uintptr_t bitvec_byte_ct;
5677 uintptr_t dosagevec_byte_ct;
5678 double r2_thresh;
5679 unsigned char allow_overlap;
5680
5681 // Remaining non-index variants.
5682 uintptr_t* candidate_oabitvec;
5683
5684 // In highmem mode, this is the base of (calc_thread_ct + 1) PgenVariant
5685 // buffer groups, offset by pgv_byte_stride bytes from each other. They are
5686 // used by worker-thread PgrGetDp() calls.
5687 // In lowmem mode, this is the base of at least cur_nonindex_ct PgenVariant
5688 // buffer groups, offset by pgv_byte_stride bytes from each other. They are
5689 // filled by main-thread PgrGetDp() calls, and interpreted by the worker
5690 // threads.
5691 PgenVariant pgv_base;
5692
5693 // In lowmem mode, these store additional PgenVariant fields.
5694 uint32_t* phasepresent_cts;
5695 uint32_t* dosage_cts;
5696 uint32_t* dphase_cts;
5697
5698 // Other per-thread resources.
5699
5700 // calc_thread_ct of these.
5701 PgenReader** pgr_ptrs;
5702 // Highmem: HighmemUnpack unpacks all current-island(-group) variants to this
5703 // memory region, then HighmemR2 reads from here. Could have
5704 // thousands, or even millions of variants here.
5705 // LowmemR2: each thread just needs workspace for one variant here. Index
5706 // variant is stored first.
5707 // Unpacked variant representation can vary based on phase_type and
5708 // load_dosage.
5709 unsigned char* unpacked_variants;
5710
5711 // In unphased case, one of these per thread to enable sparse-optimization.
5712 uintptr_t** raregeno_bufs;
5713 uint32_t** difflist_sample_id_bufs;
5714 // chrX workspaces
5715 // nm_buf: max(founder_nonmale_ct, founder_male_ct) bits
5716 // invmask_buf: max(founder_nonmale_ct, founder_male_ct) uint16s
5717 uintptr_t** chrx_workspaces;
5718 // Precomputed for convenience.
5719 uintptr_t unpacked_byte_stride;
5720
5721 // Current island-group.
5722 uintptr_t igroup_oaidx_start;
5723 uintptr_t allele_widx_start;
5724 uintptr_t allele_widx_end;
5725 unsigned char is_x;
5726 unsigned char is_y;
5727 unsigned char phase_type;
5728 unsigned char load_dosage;
5729 ClumpJobType job_type;
5730
5731 uintptr_t index_oaidx_offset;
5732 uintptr_t cur_nonindex_ct;
5733
5734 ClumpCtxAlternating a[2];
5735
5736 // Result buffers.
5737 // (calc_thread_ct + 1) of these, since main thread joins in
5738 uintptr_t** ld_idx_found;
5739
5740 uint64_t err_info;
5741 } ClumpCtx;
5742
5743 // phase_type and load_dosage are not read from ctx, since they can change as
5744 // we try to extend an island group along a single chromosome.
5745 uintptr_t UnpackedByteStride(const ClumpCtx* ctx, R2PhaseType phase_type, uint32_t x_exists, uint32_t load_dosage) {
5746 const uintptr_t bitvec_byte_ct = ctx->bitvec_byte_ct;
5747 if (!load_dosage) {
5748 uintptr_t stride = RoundUpPow2(16, kBytesPerVec) + (3 + 2 * (phase_type == kR2PhaseTypePresent)) * bitvec_byte_ct;
5749 #ifndef USE_AVX2
5750 const uint32_t founder_ct = ctx->founder_ct;
5751 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
5752 const uint32_t max_simple_difflist_len = founder_ct / 64;
5753 const uintptr_t sparse_req = RoundUpPow2((6 + max_simple_difflist_len) * sizeof(int32_t), kBytesPerVec) + NypCtToVecCt(max_simple_difflist_len) * kBytesPerVec + RoundUpPow2(founder_ctl * (kBytesPerWord + sizeof(int32_t)), kBytesPerVec);
5754 if (sparse_req > stride) {
5755 stride = sparse_req;
5756 }
5757 #endif
5758 if (x_exists) {
5759 stride += RoundUpPow2((2 + (phase_type == kR2PhaseTypeUnphased)) * sizeof(int32_t), kBytesPerVec);
5760 }
5761 return stride;
5762 }
5763 const uintptr_t trail_byte_ct = RoundUpPow2(((1 + (phase_type == kR2PhaseTypeUnphased)) * sizeof(int64_t) + sizeof(int32_t)) << x_exists, kBytesPerVec);
5764 return (1 + phase_type) * ctx->dosagevec_byte_ct + bitvec_byte_ct + trail_byte_ct;
5765 }
5766
5767 // does not check multiallelic fields
5768 void ClumpPgenVariantIncr(uintptr_t byte_ct, PgenVariant* pgvp) {
5769 const uintptr_t word_ct = byte_ct / kBytesPerWord;
5770 pgvp->genovec = &(pgvp->genovec[word_ct]);
5771 if (pgvp->phasepresent) {
5772 pgvp->phasepresent = &(pgvp->phasepresent[word_ct]);
5773 pgvp->phaseinfo = &(pgvp->phaseinfo[word_ct]);
5774 }
5775 if (pgvp->dosage_present) {
5776 const uintptr_t u16_ct = byte_ct / sizeof(int16_t);
5777 pgvp->dosage_present = &(pgvp->dosage_present[word_ct]);
5778 pgvp->dosage_main = &(pgvp->dosage_main[u16_ct]);
5779 if (pgvp->dphase_present) {
5780 pgvp->dphase_present = &(pgvp->dphase_present[word_ct]);
5781 pgvp->dphase_delta = &(pgvp->dphase_delta[u16_ct]);
5782 }
5783 }
5784 }
5785
5786 // x_male_nmaj_ct, x_male_ssq, and x_male_nm_ct only filled if
5787 // founder_male_collapsed is non-null.
5788 void LdUnpackNondosageDense(const PgenVariant* pgvp, const uintptr_t* founder_male_collapsed, uint32_t sample_ct, R2PhaseType phase_type, unsigned char* dst_iter) {
5789 const uintptr_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
5790 uint32_t* dst_u32 = R_CAST(uint32_t*, dst_iter);
5791 dst_u32[0] = 0; // is_sparse
5792 uintptr_t* dst_witer = R_CAST(uintptr_t*, &(dst_iter[RoundUpPow2(16, kBytesPerVec)]));
5793 uintptr_t* one_bitvec = dst_witer;
5794 dst_witer = &(dst_witer[sample_ctaw]);
5795 uintptr_t* two_bitvec = dst_witer;
5796 dst_witer = &(dst_witer[sample_ctaw]);
5797 uintptr_t* nm_bitvec = dst_witer;
5798 dst_witer = &(dst_witer[sample_ctaw]);
5799 uintptr_t* phasepresent = nullptr;
5800 uintptr_t* phaseinfo = nullptr;
5801 if (phase_type == kR2PhaseTypePresent) {
5802 phasepresent = dst_witer;
5803 dst_witer = &(dst_witer[sample_ctaw]);
5804 phaseinfo = dst_witer;
5805 dst_witer = &(dst_witer[sample_ctaw]);
5806 }
5807 GenoarrSplit12Nm(pgvp->genovec, sample_ct, one_bitvec, two_bitvec, nm_bitvec);
5808 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
5809 dst_u32[1] = PopcountWords(nm_bitvec, sample_ctl);
5810 dst_u32[2] = GenoBitvecSum(one_bitvec, two_bitvec, sample_ctl);
5811 dst_u32[3] = 0; // defensive
5812 if (phase_type == kR2PhaseTypePresent) {
5813 if (!pgvp->phasepresent_ct) {
5814 ZeroWArr(sample_ctl, phasepresent);
5815 } else {
5816 memcpy(phasepresent, pgvp->phasepresent, sample_ctl * sizeof(intptr_t));
5817 memcpy(phaseinfo, pgvp->phaseinfo, sample_ctl * sizeof(intptr_t));
5818 }
5819 } else if (phase_type == kR2PhaseTypeUnphased) {
5820 dst_u32[3] = dst_u32[2] + 2 * PopcountWords(two_bitvec, sample_ctl);
5821 }
5822 if (founder_male_collapsed) {
5823 uint32_t* dst_x_u32 = R_CAST(uint32_t*, dst_witer);
5824 // x_male_nm_ct
5825 dst_x_u32[0] = PopcountWordsIntersect(founder_male_collapsed, nm_bitvec, sample_ctl);
5826 dst_x_u32[1] = GenoBitvecSumSubset(founder_male_collapsed, one_bitvec, two_bitvec, sample_ctl);
5827 if (phase_type == kR2PhaseTypeUnphased) {
5828 // x_male_ssq
5829 dst_x_u32[2] = dst_x_u32[1] + 2 * PopcountWordsIntersect(founder_male_collapsed, two_bitvec, sample_ctl);
5830 }
5831 }
5832 }
5833
5834 // Ok if trailing bits of raregeno aren't clear.
5835 void LdUnpackNondosageSparse(const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, const uintptr_t* founder_male_collapsed, uint32_t sample_ct, uint32_t male_ct, uint32_t difflist_common_geno, uint32_t difflist_len, unsigned char* dst_iter) {
5836 uint32_t* dst_u32 = R_CAST(uint32_t*, dst_iter);
5837 dst_u32[0] = 1; // is_sparse
5838 dst_u32[4] = difflist_common_geno;
5839 dst_u32[5] = difflist_len;
5840 uint32_t nm_ct = sample_ct;
5841 uint32_t nmaj_ct = 0;
5842 uint32_t ssq = 0;
5843 if (difflist_common_geno) {
5844 if (difflist_common_geno == 3) {
5845 nm_ct = difflist_len;
5846 } else {
5847 const uint32_t two_ct = sample_ct - difflist_len;
5848 nmaj_ct = 2 * two_ct;
5849 ssq = 4 * two_ct;
5850 }
5851 }
5852 uintptr_t* raregeno_dst = R_CAST(uintptr_t*, &(dst_iter[RoundUpPow2((6 + difflist_len) * sizeof(int32_t), kBytesPerVec)]));
5853 const uint32_t raregeno_word_ct = NypCtToWordCt(difflist_len);
5854 uintptr_t* difflist_include_dst = &(raregeno_dst[RoundUpPow2(raregeno_word_ct, kWordsPerVec)]);
5855 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
5856 ZeroWArr(sample_ctl, difflist_include_dst);
5857 uint32_t* difflist_include_cumulative_popcounts_dst = R_CAST(uint32_t*, &(difflist_include_dst[sample_ctl]));
5858 if (difflist_len) {
5859 uint32_t* difflist_sample_ids_dst = &(dst_u32[6]);
5860 for (uint32_t uii = 0; uii != difflist_len; ++uii) {
5861 const uint32_t sample_idx = difflist_sample_ids[uii];
5862 difflist_sample_ids_dst[uii] = sample_idx;
5863 SetBit(sample_idx, difflist_include_dst);
5864 }
5865 FillCumulativePopcounts(difflist_include_dst, sample_ctl, difflist_include_cumulative_popcounts_dst);
5866 memcpy(raregeno_dst, raregeno, raregeno_word_ct * sizeof(intptr_t));
5867 ZeroTrailingNyps(difflist_len, raregeno_dst);
5868 STD_ARRAY_DECL(uint32_t, 4, genocounts);
5869 GenoarrCountFreqsUnsafe(raregeno_dst, difflist_len, genocounts);
5870 nm_ct -= genocounts[3];
5871 nmaj_ct += genocounts[1] + 2 * genocounts[2];
5872 ssq += genocounts[1] + 4 * genocounts[2];
5873 } else {
5874 ZeroU32Arr(sample_ctl, difflist_include_cumulative_popcounts_dst);
5875 }
5876 dst_u32[1] = nm_ct;
5877 dst_u32[2] = nmaj_ct;
5878 dst_u32[3] = ssq;
5879 if (founder_male_collapsed) {
5880 uint32_t x_male_nm_ct = male_ct;
5881 uint32_t x_male_nmaj_ct = 0;
5882 uint32_t x_male_ssq = 0;
5883 if (difflist_common_geno) {
5884 if (difflist_common_geno == 3) {
5885 x_male_nm_ct = 0;
5886 } else {
5887 x_male_nmaj_ct = male_ct * 2;
5888 x_male_ssq = male_ct * 4;
5889 }
5890 }
5891 if (difflist_len) {
5892 const uint32_t word_ct_m1 = raregeno_word_ct - 1;
5893 uint32_t genocounts[4];
5894 ZeroU32Arr(4, genocounts);
5895 uint32_t loop_len = kBitsPerWordD2;
5896 for (uint32_t widx = 0; ; ++widx) {
5897 if (widx >= word_ct_m1) {
5898 if (widx > word_ct_m1) {
5899 break;
5900 }
5901 loop_len = ModNz(difflist_len, kBitsPerWordD2);
5902 }
5903 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
5904 uintptr_t raregeno_word = raregeno[widx];
5905 for (uint32_t uii = 0; uii != loop_len; ++uii) {
5906 const uint32_t sample_idx = cur_difflist_sample_ids[uii];
5907 if (IsSet(founder_male_collapsed, sample_idx)) {
5908 const uintptr_t cur_geno = raregeno_word & 3;
5909 genocounts[cur_geno] += 1;
5910 }
5911 raregeno_word = raregeno_word >> 2;
5912 }
5913 }
5914 if (difflist_common_geno != 3) {
5915 x_male_nm_ct -= genocounts[3];
5916 } else {
5917 x_male_nm_ct = genocounts[0] + genocounts[1] + genocounts[2];
5918 }
5919 if (difflist_common_geno != 2) {
5920 x_male_nmaj_ct = genocounts[1] + 2 * genocounts[2];
5921 x_male_ssq = genocounts[1] + 4 * genocounts[2];
5922 } else {
5923 const uint32_t zero_or_missing_ct = genocounts[0] + genocounts[3];
5924 x_male_nmaj_ct -= genocounts[1] + 2 * zero_or_missing_ct;
5925 x_male_ssq -= 3 * genocounts[1] + 4 * zero_or_missing_ct;
5926 }
5927 }
5928 uint32_t* dst_x_u32 = &(difflist_include_cumulative_popcounts_dst[sample_ctl]);
5929 dst_x_u32[0] = x_male_nm_ct;
5930 dst_x_u32[1] = x_male_nmaj_ct;
5931 dst_x_u32[2] = x_male_ssq;
5932 }
5933 }
5934
5935 static inline uint32_t LdNondosageTrailAlignedByteCt(R2PhaseType phase_type, uint32_t x_exists) {
5936 return x_exists * RoundUpPow2((2 + (phase_type == kR2PhaseTypeUnphased)) * sizeof(int32_t), kBytesPerVec);
5937 }
5938
5939 static inline uint32_t LdDosageTrailAlignedByteCt(R2PhaseType phase_type, uint32_t x_exists) {
5940 return RoundUpPow2((sizeof(int64_t) + sizeof(int32_t) + sizeof(int64_t) * (phase_type == kR2PhaseTypeUnphased)) << x_exists, kBytesPerVec);
5941 }
5942
5943 void LdUnpackDosage(const PgenVariant* pgvp, const uintptr_t* founder_male_collapsed, const Dosage* male_dosage_invmask, uint32_t sample_ct, R2PhaseType phase_type, unsigned char* dst_iter) {
5944 const uintptr_t dosagev_ct = DivUp(sample_ct, kDosagePerVec);
5945 const uintptr_t dosagevec_byte_ct = dosagev_ct * kBytesPerVec;
5946 Dosage* dosage_vec = R_CAST(Dosage*, dst_iter);
5947 dst_iter = &(dst_iter[dosagevec_byte_ct]);
5948 Dosage* dosage_het = nullptr;
5949 if (phase_type != kR2PhaseTypeUnphased) {
5950 dosage_het = R_CAST(Dosage*, dst_iter);
5951 dst_iter = &(dst_iter[dosagevec_byte_ct]);
5952 }
5953 uintptr_t* nm_bitvec = R_CAST(uintptr_t*, dst_iter);
5954 const uintptr_t bitvec_byte_ct = BitCtToVecCt(sample_ct) * kBytesPerVec;
5955 dst_iter = &(dst_iter[bitvec_byte_ct]);
5956 SDosage* dense_dphase_delta = nullptr;
5957 if (phase_type == kR2PhaseTypePresent) {
5958 dense_dphase_delta = R_CAST(SDosage*, dst_iter);
5959 dst_iter = &(dst_iter[dosagevec_byte_ct]);
5960 }
5961 // In 32-bit build, no alignment guarantee for uint64s.
5962 unsigned char* nmaj_dosage_uc_ptr = dst_iter;
5963 dst_iter = &(dst_iter[sizeof(int64_t)]);
5964 unsigned char* nmaj_dosage_ssq_uc_ptr = nullptr;
5965 if (phase_type == kR2PhaseTypeUnphased) {
5966 nmaj_dosage_ssq_uc_ptr = dst_iter;
5967 dst_iter = &(dst_iter[sizeof(int64_t)]);
5968 }
5969 uint32_t* nm_ct_ptr = R_CAST(uint32_t*, dst_iter);
5970
5971 PopulateDenseDosage(pgvp->genovec, pgvp->dosage_present, pgvp->dosage_main, sample_ct, pgvp->dosage_ct, dosage_vec);
5972 const uint64_t nmaj_dosage = DenseDosageSum(dosage_vec, dosagev_ct);
5973 memcpy(nmaj_dosage_uc_ptr, &nmaj_dosage, sizeof(int64_t));
5974 GenoarrToNonmissing(pgvp->genovec, sample_ct, nm_bitvec);
5975 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
5976 BitvecOr(pgvp->dosage_present, sample_ctl, nm_bitvec);
5977 *nm_ct_ptr = PopcountWords(nm_bitvec, sample_ctl);
5978 if (phase_type == kR2PhaseTypeUnphased) {
5979 const uint64_t nmaj_dosage_ssq = DosageUnsignedDotprod(dosage_vec, dosage_vec, dosagev_ct);
5980 memcpy(nmaj_dosage_ssq_uc_ptr, &nmaj_dosage_ssq, sizeof(int64_t));
5981 } else {
5982 FillDosageHet(dosage_vec, dosagev_ct, dosage_het);
5983 if (phase_type == kR2PhaseTypePresent) {
5984 PopulateDenseDphase(pgvp->phasepresent, pgvp->phaseinfo, pgvp->dosage_present, dosage_vec, pgvp->dphase_present, pgvp->dphase_delta, sample_ct, pgvp->phasepresent_ct, pgvp->dosage_ct, pgvp->dphase_ct, dense_dphase_delta);
5985 }
5986 }
5987 if (founder_male_collapsed == nullptr) {
5988 return;
5989 }
5990 dst_iter = &(dst_iter[sizeof(int32_t)]);
5991 uint32_t* x_male_nm_ct_ptr = R_CAST(uint32_t*, dst_iter);
5992 *x_male_nm_ct_ptr = PopcountWordsIntersect(founder_male_collapsed, nm_bitvec, sample_ctl);
5993 dst_iter = &(dst_iter[sizeof(int32_t)]);
5994 const uint64_t x_male_nmaj_dosage = DenseDosageSumSubset(dosage_vec, male_dosage_invmask, dosagev_ct);
5995 memcpy(dst_iter, &x_male_nmaj_dosage, sizeof(int64_t));
5996 if (phase_type == kR2PhaseTypeUnphased) {
5997 dst_iter = &(dst_iter[sizeof(int64_t)]);
5998 const uint64_t x_male_nmaj_dosage_ssq = DosageUnsignedDotprodSubset(male_dosage_invmask, dosage_vec, dosage_vec, dosagev_ct);
5999 memcpy(dst_iter, &x_male_nmaj_dosage_ssq, sizeof(int64_t));
6000 }
6001 }
6002
6003 typedef struct R2NondosageDenseStruct {
6004 const uintptr_t* one_bitvec;
6005 const uintptr_t* two_bitvec;
6006 const uintptr_t* nm_bitvec;
6007 const uintptr_t* phasepresent; // may be uninitialized
6008 const uintptr_t* phaseinfo; // may be uninitialized
6009 } R2NondosageDense;
6010
6011 typedef struct R2NondosageSparseStruct {
6012 uint32_t difflist_common_geno;
6013 uint32_t difflist_len;
6014 const uint32_t* difflist_sample_ids;
6015 const uintptr_t* raregeno;
6016 const uintptr_t* difflist_include;
6017 const uint32_t* difflist_include_cumulative_popcounts;
6018 // probable todo: support phase
6019 } R2NondosageSparse;
6020
6021 typedef union {
6022 R2NondosageDense d;
6023 R2NondosageSparse s;
6024 } R2NondosagePayload;
6025
6026 typedef struct R2NondosageVariantStruct {
6027 uint32_t is_sparse;
6028 uint32_t nm_ct;
6029 uint32_t nmaj_ct;
6030 uint32_t ssq; // set to 0 unless unphased calc
6031 R2NondosagePayload p;
6032 uint32_t x_male_nm_ct; // may be uninitialized
6033 uint32_t x_male_nmaj_ct; // may be uninitialized
6034 uint32_t x_male_ssq; // may be uninitialized
6035 } R2NondosageVariant;
6036
6037 typedef struct R2DosageVariantStruct {
6038 const Dosage* dosage_vec;
6039 const Dosage* dosage_het; // may be uninitialized
6040 const uintptr_t* nm_bitvec;
6041 // probable todo: replace dense_dphase_delta with dosage_vec2 + dosage_het2.
6042 // takes ~33% more space, but I'd be shocked if it didn't result in a
6043 // noticeable phased-dosage r^2 speedup since computing the two het-sides
6044 // from scratch is so annoying. (and if that's how we're handling
6045 // dosage_het, we may as well handle dosage_vec the same way even though it
6046 // needs it less.)
6047 const SDosage* dense_dphase_delta; // may be uninitialized
6048 uint64_t nmaj_dosage;
6049 uint64_t nmaj_dosage_ssq; // may be uninitialized
6050 uint32_t nm_ct;
6051 uint32_t x_male_nm_ct; // may be uninitialized
6052 uint64_t x_male_nmaj_dosage; // may be uninitialized
6053 uint64_t x_male_nmaj_dosage_ssq; // may be uninitialized
6054 } R2DosageVariant;
6055
6056 typedef union {
6057 R2NondosageVariant nd;
6058 R2DosageVariant d;
6059 } R2Variant;
6060
6061 void FillR2Nondosage(const unsigned char* src_iter, uint32_t sample_ct, R2PhaseType phase_type, uint32_t is_x, R2NondosageVariant* ndp) {
6062 // See LdUnpackNondosage{Dense,Sparse}().
6063 const uint32_t* src_u32 = R_CAST(const uint32_t*, src_iter);
6064 const uint32_t is_sparse = src_u32[0];
6065 ndp->is_sparse = is_sparse;
6066 ndp->nm_ct = src_u32[1];
6067 ndp->nmaj_ct = src_u32[2];
6068 ndp->ssq = src_u32[3];
6069 if (is_sparse) {
6070 R2NondosageSparse* ndsp = &(ndp->p.s);
6071 ndsp->difflist_common_geno = src_u32[4];
6072 const uint32_t difflist_len = src_u32[5];
6073 ndsp->difflist_len = difflist_len;
6074 ndsp->difflist_sample_ids = &(src_u32[6]);
6075 const uintptr_t* raregeno = R_CAST(const uintptr_t*, &(src_iter[RoundUpPow2(sizeof(int32_t) * (6 + difflist_len), kBytesPerVec)]));
6076 ndsp->raregeno = raregeno;
6077 const uint32_t raregeno_word_ct = NypCtToWordCt(difflist_len);
6078 const uintptr_t* difflist_include = &(raregeno[RoundUpPow2(raregeno_word_ct, kWordsPerVec)]);
6079 ndsp->difflist_include = difflist_include;
6080 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6081 const uint32_t* difflist_include_cumulative_popcounts = R_CAST(const uint32_t*, &(difflist_include[sample_ctl]));
6082 ndsp->difflist_include_cumulative_popcounts = difflist_include_cumulative_popcounts;
6083 if (is_x) {
6084 const uint32_t* src_x_u32 = &(difflist_include_cumulative_popcounts[sample_ctl]);
6085 ndp->x_male_nm_ct = src_x_u32[0];
6086 ndp->x_male_nmaj_ct = src_x_u32[1];
6087 ndp->x_male_ssq = src_x_u32[2];
6088 }
6089 return;
6090 }
6091 const uintptr_t* src_witer = R_CAST(const uintptr_t*, &(src_iter[RoundUpPow2(16, kBytesPerVec)]));
6092 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
6093 R2NondosageDense* nddp = &(ndp->p.d);
6094 nddp->one_bitvec = src_witer;
6095 src_witer = &(src_witer[sample_ctaw]);
6096 nddp->two_bitvec = src_witer;
6097 src_witer = &(src_witer[sample_ctaw]);
6098 nddp->nm_bitvec = src_witer;
6099 src_witer = &(src_witer[sample_ctaw]);
6100 if (phase_type == kR2PhaseTypePresent) {
6101 nddp->phasepresent = src_witer;
6102 src_witer = &(src_witer[sample_ctaw]);
6103 nddp->phaseinfo = src_witer;
6104 src_witer = &(src_witer[sample_ctaw]);
6105 }
6106 if (is_x) {
6107 const uint32_t* src_x_u32 = R_CAST(const uint32_t*, src_witer);
6108 ndp->x_male_nm_ct = src_x_u32[0];
6109 ndp->x_male_nmaj_ct = src_x_u32[1];
6110 if (phase_type == kR2PhaseTypeUnphased) {
6111 ndp->x_male_ssq = src_x_u32[2];
6112 }
6113 }
6114 }
6115
6116 void FillR2Dosage(const unsigned char* src_iter, uint32_t sample_ct, R2PhaseType phase_type, uint32_t is_x, R2DosageVariant* dp) {
6117 // See LdUnpackDosage().
6118 const uintptr_t dosagev_ct = DivUp(sample_ct, kDosagePerVec);
6119 const uintptr_t dosagevec_byte_ct = dosagev_ct * kBytesPerVec;
6120 dp->dosage_vec = R_CAST(const Dosage*, src_iter);
6121 src_iter = &(src_iter[dosagevec_byte_ct]);
6122 if (phase_type != kR2PhaseTypeUnphased) {
6123 dp->dosage_het = R_CAST(const Dosage*, src_iter);
6124 src_iter = &(src_iter[dosagevec_byte_ct]);
6125 }
6126 dp->nm_bitvec = R_CAST(const uintptr_t*, src_iter);
6127 const uintptr_t bitvec_byte_ct = BitCtToVecCt(sample_ct) * kBytesPerVec;
6128 src_iter = &(src_iter[bitvec_byte_ct]);
6129 if (phase_type == kR2PhaseTypePresent) {
6130 dp->dense_dphase_delta = R_CAST(const SDosage*, src_iter);
6131 src_iter = &(src_iter[dosagevec_byte_ct]);
6132 }
6133 memcpy(&(dp->nmaj_dosage), src_iter, sizeof(int64_t));
6134 const unsigned char* trail_iter = &(src_iter[sizeof(int64_t)]);
6135 if (phase_type == kR2PhaseTypeUnphased) {
6136 memcpy(&(dp->nmaj_dosage_ssq), trail_iter, sizeof(int64_t));
6137 trail_iter = &(trail_iter[sizeof(int64_t)]);
6138 }
6139 memcpy(&(dp->nm_ct), trail_iter, sizeof(int32_t));
6140 if (!is_x) {
6141 return;
6142 }
6143 trail_iter = &(trail_iter[sizeof(int32_t)]);
6144 memcpy(&(dp->x_male_nm_ct), trail_iter, sizeof(int32_t));
6145 trail_iter = &(trail_iter[sizeof(int32_t)]);
6146 memcpy(&(dp->x_male_nmaj_dosage), trail_iter, sizeof(int64_t));
6147 if (phase_type == kR2PhaseTypeUnphased) {
6148 trail_iter = &(trail_iter[sizeof(int64_t)]);
6149 memcpy(&(dp->x_male_nmaj_dosage_ssq), trail_iter, sizeof(int64_t));
6150 }
6151 }
6152
6153 void FillR2V(const unsigned char* src_iter, uint32_t sample_ct, R2PhaseType phase_type, uint32_t is_x, uint32_t load_dosage, R2Variant* r2vp) {
6154 if (!load_dosage) {
6155 FillR2Nondosage(src_iter, sample_ct, phase_type, is_x, &(r2vp->nd));
6156 } else {
6157 FillR2Dosage(src_iter, sample_ct, phase_type, is_x, &(r2vp->d));
6158 }
6159 }
6160
6161 void ClumpHighmemUnpack(uintptr_t tidx, uint32_t parity, ClumpCtx* ctx) {
6162 // Unpack (variant, aidx)s to unpacked_variants.
6163 const uintptr_t oaidx_end = ctx->a[parity].oaidx_starts[tidx + 1];
6164 uintptr_t oaidx = ctx->a[parity].oaidx_starts[tidx];
6165 if (oaidx == oaidx_end) {
6166 return;
6167 }
6168 const uintptr_t* variant_last_alidxs = ctx->variant_last_alidxs;
6169 const uint32_t* variant_last_alidxs_cumulative_popcounts = ctx->variant_last_alidxs_cumulative_popcounts;
6170 const uintptr_t* observed_alleles = ctx->observed_alleles;
6171 const uintptr_t* observed_alleles_cumulative_popcounts_w = ctx->observed_alleles_cumulative_popcounts_w;
6172 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
6173 const uintptr_t pgv_byte_stride = ctx->pgv_byte_stride;
6174 PgenVariant pgv = ctx->pgv_base;
6175 ClumpPgenVariantIncr(pgv_byte_stride * tidx, &pgv);
6176 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
6177 const uintptr_t unpacked_byte_stride = ctx->unpacked_byte_stride;
6178 unsigned char* write_iter;
6179 {
6180 const uintptr_t igroup_oaidx_start = ctx->igroup_oaidx_start;
6181 write_iter = &(ctx->unpacked_variants[(oaidx - igroup_oaidx_start) * unpacked_byte_stride]);
6182 }
6183 const uintptr_t* founder_info = ctx->founder_info;
6184 const uint32_t* founder_info_cumulative_popcounts = ctx->founder_info_cumulative_popcounts;
6185 const uint32_t founder_male_ct = ctx->founder_male_ct;
6186 const uint32_t is_x = ctx->is_x;
6187 const uintptr_t* founder_male_collapsed = is_x? ctx->founder_male_collapsed : nullptr;
6188 const Dosage* male_dosage_invmask = is_x? ctx->male_dosage_invmask : nullptr;
6189 const uintptr_t* founder_female_collapsed = ctx->founder_female_collapsed;
6190 const uintptr_t* founder_female_collapsed_interleaved = ctx->founder_female_collapsed_interleaved;
6191 const uint32_t founder_ct = ctx->founder_ct;
6192 const uint32_t founder_ctv2 = NypCtToVecCt(founder_ct);
6193 const uint32_t is_y = ctx->is_y;
6194 PgrSampleSubsetIndex pssi;
6195 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, pgrp, &pssi);
6196 const R2PhaseType phase_type = S_CAST(R2PhaseType, ctx->phase_type);
6197 const uint32_t load_dosage = ctx->load_dosage;
6198 const uintptr_t allele_idx_start = IdxToUidxW(observed_alleles, observed_alleles_cumulative_popcounts_w, ctx->allele_widx_start, ctx->allele_widx_end, oaidx);
6199 const uint32_t max_simple_difflist_len = founder_ct / 64;
6200 uintptr_t* raregeno = nullptr;
6201 uint32_t* difflist_sample_ids = nullptr;
6202 if (phase_type == kR2PhaseTypeUnphased) {
6203 raregeno = ctx->raregeno_bufs[tidx];
6204 difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx];
6205 }
6206 uintptr_t allele_idx_base;
6207 uintptr_t cur_bits;
6208 BitIter1Start(observed_alleles, allele_idx_start, &allele_idx_base, &cur_bits);
6209 uintptr_t variant_uidx;
6210 PglErr reterr;
6211 for (; oaidx != oaidx_end; ++oaidx, write_iter = &(write_iter[unpacked_byte_stride])) {
6212 const uintptr_t allele_idx = BitIter1(observed_alleles, &allele_idx_base, &cur_bits);
6213 AlleleCode aidx;
6214 if (!allele_idx_offsets) {
6215 variant_uidx = allele_idx / 2;
6216 aidx = allele_idx % 2;
6217 } else {
6218 variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, allele_idx);
6219 aidx = allele_idx - allele_idx_offsets[variant_uidx];
6220 }
6221 if (load_dosage) {
6222 if (phase_type == kR2PhaseTypePresent) {
6223 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, variant_uidx, aidx, pgrp, &pgv);
6224 } else {
6225 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, variant_uidx, aidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
6226 }
6227 if (unlikely(reterr)) {
6228 goto ClumpHighmemUnpack_err;
6229 }
6230 if (is_y) {
6231 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
6232 }
6233 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, write_iter);
6234 } else {
6235 if ((phase_type == kR2PhaseTypeUnphased) && (!is_y)) {
6236 uint32_t difflist_common_geno;
6237 uint32_t difflist_len;
6238 reterr = PgrGetInv1DifflistOrGenovec(founder_info, pssi, founder_ct, max_simple_difflist_len, variant_uidx, aidx, pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
6239 if (unlikely(reterr)) {
6240 goto ClumpHighmemUnpack_err;
6241 }
6242 if (difflist_common_geno != UINT32_MAX) {
6243 if (difflist_len <= max_simple_difflist_len) {
6244 LdUnpackNondosageSparse(raregeno, difflist_sample_ids, founder_male_collapsed, founder_ct, founder_male_ct, difflist_common_geno, difflist_len, write_iter);
6245 continue;
6246 }
6247 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, founder_ct, difflist_len, pgv.genovec);
6248 }
6249 } else {
6250 if (phase_type == kR2PhaseTypePresent) {
6251 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, variant_uidx, aidx, pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
6252 } else {
6253 reterr = PgrGetInv1(founder_info, pssi, founder_ct, variant_uidx, aidx, pgrp, pgv.genovec);
6254 }
6255 if (unlikely(reterr)) {
6256 goto ClumpHighmemUnpack_err;
6257 }
6258 if (is_y) {
6259 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
6260 }
6261 }
6262 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, write_iter);
6263 }
6264 }
6265 return;
6266 ClumpHighmemUnpack_err:
6267 ;
6268 const uint64_t new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
6269 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
6270 }
6271
6272 // assumes sample_ct < 2^30.
6273 static inline uint32_t GenoBitvecUnphasedDotprod(const uintptr_t* one_bitvec0, const uintptr_t* two_bitvec0, const uintptr_t* one_bitvec1, const uintptr_t* two_bitvec1, uint32_t word_ct) {
6274 uint32_t half_hom_part;
6275 uint32_t hethet_ct;
6276 GenoBitvecPhasedDotprod(one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, word_ct, &half_hom_part, &hethet_ct);
6277 return 2 * half_hom_part + hethet_ct;
6278 }
6279
6280 static inline uint32_t GenoBitvecUnphasedDotprodSubset(const uintptr_t* subset_mask, const uintptr_t* one_bitvec0, const uintptr_t* two_bitvec0, const uintptr_t* one_bitvec1, const uintptr_t* two_bitvec1, uint32_t word_ct) {
6281 uint32_t half_hom_part;
6282 uint32_t hethet_ct;
6283 GenoBitvecPhasedDotprodSubset(subset_mask, one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, word_ct, &half_hom_part, &hethet_ct);
6284 return 2 * half_hom_part + hethet_ct;
6285 }
6286
6287 uint32_t ComputeR2NondosageUnphased1SparseStats(const R2NondosageVariant* densevp0, const R2NondosageVariant* sparsevp1, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr) {
6288 const uint32_t difflist_common_geno = sparsevp1->p.s.difflist_common_geno;
6289 const uint32_t difflist_len = sparsevp1->p.s.difflist_len;
6290 const uint32_t* difflist_sample_ids = sparsevp1->p.s.difflist_sample_ids;
6291 uint32_t nmaj_ct0 = 0;
6292 uint32_t nmaj_ct1 = 0;
6293 uint32_t ssq0 = 0;
6294 uint32_t ssq1 = 0;
6295 uint32_t dotprod = 0;
6296 uint32_t valid_obs_ct = 0;
6297 if (difflist_common_geno != 3) {
6298 nmaj_ct0 = densevp0->nmaj_ct;
6299 ssq0 = densevp0->ssq;
6300 dotprod = difflist_common_geno * nmaj_ct0;
6301 valid_obs_ct = densevp0->nm_ct;
6302 nmaj_ct1 = difflist_common_geno * valid_obs_ct;
6303 ssq1 = difflist_common_geno * nmaj_ct1;
6304 }
6305 if (difflist_len) {
6306 // genovec would be more convenient than this representation here, but that
6307 // shouldn't be a big deal.
6308 const uintptr_t* nm_bitvec0 = densevp0->p.d.nm_bitvec;
6309 const uintptr_t* one_bitvec0 = densevp0->p.d.one_bitvec;
6310 const uintptr_t* two_bitvec0 = densevp0->p.d.two_bitvec;
6311 const uintptr_t* raregeno = sparsevp1->p.s.raregeno;
6312 const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
6313 uint32_t joint_counts[16]; // low bits = dense geno, high bits = sparse
6314 ZeroU32Arr(16, joint_counts);
6315 uint32_t loop_len = kBitsPerWordD2;
6316 for (uint32_t widx = 0; ; ++widx) {
6317 if (widx >= word_ct_m1) {
6318 if (widx > word_ct_m1) {
6319 break;
6320 }
6321 loop_len = ModNz(difflist_len, kBitsPerWordD2);
6322 }
6323 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
6324 uintptr_t raregeno_word = raregeno[widx];
6325 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6326 const uintptr_t cur_sparse_geno = raregeno_word & 3;
6327 const uint32_t sample_idx = cur_difflist_sample_ids[uii];
6328 const uint32_t sample_widx = sample_idx / kBitsPerWord;
6329 const uint32_t sample_idx_lowbits = sample_idx % kBitsPerWord;
6330 const uintptr_t nm_bit = (nm_bitvec0[sample_widx] >> sample_idx_lowbits) & 1;
6331 const uintptr_t one_bit = (one_bitvec0[sample_widx] >> sample_idx_lowbits) & 1;
6332 // "& 3" takes care of this mask
6333 const uintptr_t two_bit_unmasked = two_bitvec0[sample_widx] >> sample_idx_lowbits;
6334 const uintptr_t cur_dense_geno = (nm_bit + one_bit + two_bit_unmasked * 2 - 1) & 3;
6335 joint_counts[cur_dense_geno + cur_sparse_geno * 4] += 1;
6336 raregeno_word = raregeno_word >> 2;
6337 }
6338 }
6339 if (difflist_common_geno != 3) {
6340 nmaj_ct0 -= joint_counts[13] + 2 * joint_counts[14];
6341 ssq0 -= joint_counts[13] + 4 * joint_counts[14];
6342 const uint32_t sparse_missing_dense_nm_ct = joint_counts[12] + joint_counts[13] + joint_counts[14];
6343 valid_obs_ct -= sparse_missing_dense_nm_ct;
6344 } else {
6345 const uint32_t dense_one_ct = joint_counts[1] + joint_counts[5] + joint_counts[9];
6346 const uint32_t dense_two_ct = joint_counts[2] + joint_counts[6] + joint_counts[10];
6347 nmaj_ct0 = dense_one_ct + 2 * dense_two_ct;
6348 ssq0 = dense_one_ct + 4 * dense_two_ct;
6349 const uint32_t dense_missing_sparse_nm_ct = joint_counts[3] + joint_counts[7] + joint_counts[11];
6350 valid_obs_ct = difflist_len - dense_missing_sparse_nm_ct;
6351 }
6352 const uint32_t sparse_one_ct = joint_counts[4] + joint_counts[5] + joint_counts[6];
6353 if (difflist_common_geno != 2) {
6354 const uint32_t sparse_two_ct = joint_counts[8] + joint_counts[9] + joint_counts[10];
6355 nmaj_ct1 = sparse_one_ct + 2 * sparse_two_ct;
6356 ssq1 = sparse_one_ct + 4 * sparse_two_ct;
6357 dotprod = joint_counts[5] + 2 * (joint_counts[6] + joint_counts[9]) + 4 * joint_counts[10];
6358 } else {
6359 const uint32_t sparse_zmiss_ct = joint_counts[0] + joint_counts[1] + joint_counts[2] + joint_counts[12] + joint_counts[13] + joint_counts[14];
6360 nmaj_ct1 -= sparse_one_ct + 2 * sparse_zmiss_ct;
6361 ssq1 -= 3 * sparse_one_ct + 4 * sparse_zmiss_ct;
6362 dotprod -= joint_counts[5] + 2 * (joint_counts[1] + joint_counts[6] + joint_counts[13]) + 4 * (joint_counts[2] + joint_counts[14]);
6363 }
6364 }
6365 *nmaj_ct0_ptr = nmaj_ct0;
6366 *nmaj_ct1_ptr = nmaj_ct1;
6367 *ssq0_ptr = ssq0;
6368 *ssq1_ptr = ssq1;
6369 *dotprod_ptr = dotprod;
6370 return valid_obs_ct;
6371 }
6372
6373 uint32_t ComputeR2NondosageUnphased2SparseStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr) {
6374 const R2NondosageVariant* longvp;
6375 const R2NondosageVariant* shortvp;
6376 uint32_t* nmaj_ctlong_ptr;
6377 uint32_t* nmaj_ctshort_ptr;
6378 uint32_t* ssqlong_ptr;
6379 uint32_t* ssqshort_ptr;
6380 if (ndp0->p.s.difflist_len <= ndp1->p.s.difflist_len) {
6381 longvp = ndp1;
6382 shortvp = ndp0;
6383 nmaj_ctlong_ptr = nmaj_ct1_ptr;
6384 nmaj_ctshort_ptr = nmaj_ct0_ptr;
6385 ssqlong_ptr = ssq1_ptr;
6386 ssqshort_ptr = ssq0_ptr;
6387 } else {
6388 longvp = ndp0;
6389 shortvp = ndp1;
6390 nmaj_ctlong_ptr = nmaj_ct0_ptr;
6391 nmaj_ctshort_ptr = nmaj_ct1_ptr;
6392 ssqlong_ptr = ssq0_ptr;
6393 ssqshort_ptr = ssq1_ptr;
6394 }
6395 const uint32_t difflist_common_geno_short = shortvp->p.s.difflist_common_geno;
6396 uint32_t nmaj_ctlong = 0;
6397 uint32_t nmaj_ctshort = 0;
6398 uint32_t ssqlong = 0;
6399 uint32_t ssqshort = 0;
6400 uint32_t dotprod = 0;
6401 uint32_t valid_obs_ct = 0;
6402 if (difflist_common_geno_short != 3) {
6403 nmaj_ctlong = longvp->nmaj_ct;
6404 ssqlong = longvp->ssq;
6405 dotprod = difflist_common_geno_short * nmaj_ctlong;
6406 valid_obs_ct = longvp->nm_ct;
6407 nmaj_ctshort = difflist_common_geno_short * valid_obs_ct;
6408 ssqshort = difflist_common_geno_short * nmaj_ctshort;
6409 }
6410 const uint32_t difflist_len_short = shortvp->p.s.difflist_len;
6411 if (difflist_len_short) {
6412 // tested genovec in place of {difflist_include,
6413 // difflist_include_cumulative_popcounts}; that benchmarked worse
6414 const uintptr_t* difflist_include_long = longvp->p.s.difflist_include;
6415 const uint32_t* difflist_include_long_cumulative_popcounts = longvp->p.s.difflist_include_cumulative_popcounts;
6416
6417 const uint32_t* difflist_sample_ids_short = shortvp->p.s.difflist_sample_ids;
6418 const uintptr_t* raregeno_long = longvp->p.s.raregeno;
6419 const uintptr_t* raregeno_short = shortvp->p.s.raregeno;
6420 const uint32_t difflist_common_geno_long = longvp->p.s.difflist_common_geno;
6421 uint32_t joint_counts[16]; // low bits = long, high bits = short
6422 ZeroU32Arr(16, joint_counts);
6423 const uint32_t word_ct_m1 = (difflist_len_short - 1) / kBitsPerWordD2;
6424 uint32_t loop_len = kBitsPerWordD2;
6425 for (uint32_t widx = 0; ; ++widx) {
6426 if (widx >= word_ct_m1) {
6427 if (widx > word_ct_m1) {
6428 break;
6429 }
6430 loop_len = ModNz(difflist_len_short, kBitsPerWordD2);
6431 }
6432 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids_short[widx * kBitsPerWordD2]);
6433 uintptr_t raregeno_word = raregeno_short[widx];
6434 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6435 const uint32_t sample_idx = cur_difflist_sample_ids[uii];
6436 const uintptr_t cur_geno_short = raregeno_word & 3;
6437 uintptr_t cur_geno_long = difflist_common_geno_long;
6438 if (IsSet(difflist_include_long, sample_idx)) {
6439 const uint32_t difflist_idx_long = RawToSubsettedPos(difflist_include_long, difflist_include_long_cumulative_popcounts, sample_idx);
6440 cur_geno_long = GetNyparrEntry(raregeno_long, difflist_idx_long);
6441 }
6442 joint_counts[cur_geno_long + 4 * cur_geno_short] += 1;
6443 raregeno_word = raregeno_word >> 2;
6444 }
6445 }
6446 if (difflist_common_geno_short != 3) {
6447 nmaj_ctlong -= joint_counts[13] + 2 * joint_counts[14];
6448 ssqlong -= joint_counts[13] + 4 * joint_counts[14];
6449 const uint32_t short_missing_long_nm_ct = joint_counts[12] + joint_counts[13] + joint_counts[14];
6450 valid_obs_ct -= short_missing_long_nm_ct;
6451 } else {
6452 const uint32_t long_one_ct = joint_counts[1] + joint_counts[5] + joint_counts[9];
6453 const uint32_t long_two_ct = joint_counts[2] + joint_counts[6] + joint_counts[10];
6454 nmaj_ctlong = long_one_ct + 2 * long_two_ct;
6455 ssqlong = long_one_ct + 4 * long_two_ct;
6456 const uint32_t long_missing_short_nm_ct = joint_counts[3] + joint_counts[7] + joint_counts[11];
6457 valid_obs_ct = difflist_len_short - long_missing_short_nm_ct;
6458 }
6459 const uint32_t short_one_ct = joint_counts[4] + joint_counts[5] + joint_counts[6];
6460 if (difflist_common_geno_short != 2) {
6461 const uint32_t short_two_ct = joint_counts[8] + joint_counts[9] + joint_counts[10];
6462 nmaj_ctshort = short_one_ct + 2 * short_two_ct;
6463 ssqshort = short_one_ct + 4 * short_two_ct;
6464 dotprod = joint_counts[5] + 2 * (joint_counts[6] + joint_counts[9]) + 4 * joint_counts[10];
6465 } else {
6466 const uint32_t short_zmiss_ct = joint_counts[0] + joint_counts[1] + joint_counts[2] + joint_counts[12] + joint_counts[13] + joint_counts[14];
6467 nmaj_ctshort -= short_one_ct + 2 * short_zmiss_ct;
6468 ssqshort -= 3 * short_one_ct + 4 * short_zmiss_ct;
6469 dotprod -= joint_counts[5] + 2 * (joint_counts[1] + joint_counts[6] + joint_counts[13]) + 4 * (joint_counts[2] + joint_counts[14]);
6470 }
6471 }
6472 *nmaj_ctlong_ptr = nmaj_ctlong;
6473 *nmaj_ctshort_ptr = nmaj_ctshort;
6474 *ssqlong_ptr = ssqlong;
6475 *ssqshort_ptr = ssqshort;
6476 *dotprod_ptr = dotprod;
6477 return valid_obs_ct;
6478 }
6479
6480 // Main return value is valid_obs_ct. On valid_obs_ct=0, other return values
6481 // may not be filled. (Same is true for the next three functions.)
6482 uint32_t ComputeR2NondosageUnphasedStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, uint32_t sample_ct, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr) {
6483 if (ndp0->is_sparse) {
6484 if (ndp1->is_sparse) {
6485 return ComputeR2NondosageUnphased2SparseStats(ndp0, ndp1, nmaj_ct0_ptr, nmaj_ct1_ptr, ssq0_ptr, ssq1_ptr, dotprod_ptr);
6486 } else {
6487 return ComputeR2NondosageUnphased1SparseStats(ndp1, ndp0, nmaj_ct1_ptr, nmaj_ct0_ptr, ssq1_ptr, ssq0_ptr, dotprod_ptr);
6488 }
6489 }
6490 if (ndp1->is_sparse) {
6491 return ComputeR2NondosageUnphased1SparseStats(ndp0, ndp1, nmaj_ct0_ptr, nmaj_ct1_ptr, ssq0_ptr, ssq1_ptr, dotprod_ptr);
6492 }
6493 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6494 const uintptr_t* nm_bitvec0 = ndp0->p.d.nm_bitvec;
6495 const uintptr_t* nm_bitvec1 = ndp1->p.d.nm_bitvec;
6496 const uint32_t nm_ct0 = ndp0->nm_ct;
6497 const uint32_t nm_ct1 = ndp1->nm_ct;
6498 uint32_t valid_obs_ct;
6499 if ((nm_ct0 != sample_ct) && (nm_ct1 != sample_ct)) {
6500 valid_obs_ct = PopcountWordsIntersect(nm_bitvec0, nm_bitvec1, sample_ctl);
6501 if (!valid_obs_ct) {
6502 return 0;
6503 }
6504 } else {
6505 valid_obs_ct = MINV(nm_ct0, nm_ct1);
6506 }
6507 const uintptr_t* one_bitvec0 = ndp0->p.d.one_bitvec;
6508 const uintptr_t* two_bitvec0 = ndp0->p.d.two_bitvec;
6509 if (nm_ct0 == valid_obs_ct) {
6510 *nmaj_ct0_ptr = ndp0->nmaj_ct;
6511 *ssq0_ptr = ndp0->ssq;
6512 } else {
6513 const uint32_t nmaj_ct0 = GenoBitvecSumSubset(nm_bitvec1, one_bitvec0, two_bitvec0, sample_ctl);
6514 *nmaj_ct0_ptr = nmaj_ct0;
6515 // 0, 1, 4 instead of 0, 1, 2
6516 *ssq0_ptr = nmaj_ct0 + 2 * PopcountWordsIntersect(nm_bitvec1, two_bitvec0, sample_ctl);
6517 }
6518 const uintptr_t* one_bitvec1 = ndp1->p.d.one_bitvec;
6519 const uintptr_t* two_bitvec1 = ndp1->p.d.two_bitvec;
6520 if (nm_ct1 == valid_obs_ct) {
6521 *nmaj_ct1_ptr = ndp1->nmaj_ct;
6522 *ssq1_ptr = ndp1->ssq;
6523 } else {
6524 const uint32_t nmaj_ct1 = GenoBitvecSumSubset(nm_bitvec0, one_bitvec1, two_bitvec1, sample_ctl);
6525 *nmaj_ct1_ptr = nmaj_ct1;
6526 *ssq1_ptr = nmaj_ct1 + 2 * PopcountWordsIntersect(nm_bitvec0, two_bitvec1, sample_ctl);
6527 }
6528 *dotprod_ptr = GenoBitvecUnphasedDotprod(one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, sample_ctl);
6529 return valid_obs_ct;
6530 }
6531
6532 uint32_t ComputeR2NondosagePhasedStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, uint32_t sample_ct, R2PhaseType phase_type, double* nmajsums_d, double* known_dotprod_d_ptr, double* unknown_hethet_d_ptr) {
6533 // See HardcallPhasedR2Stats(). Probable todo: make function names more
6534 // systematic.
6535 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
6536 const uintptr_t* nm_bitvec0 = ndp0->p.d.nm_bitvec;
6537 const uintptr_t* nm_bitvec1 = ndp1->p.d.nm_bitvec;
6538 const uint32_t nm_ct0 = ndp0->nm_ct;
6539 const uint32_t nm_ct1 = ndp1->nm_ct;
6540 uint32_t valid_obs_ct;
6541 if ((nm_ct0 != sample_ct) && (nm_ct1 != sample_ct)) {
6542 valid_obs_ct = PopcountWordsIntersect(nm_bitvec0, nm_bitvec1, sample_ctl);
6543 if (!valid_obs_ct) {
6544 return 0;
6545 }
6546 } else {
6547 valid_obs_ct = MINV(nm_ct0, nm_ct1);
6548 }
6549 const uintptr_t* one_bitvec0 = ndp0->p.d.one_bitvec;
6550 const uintptr_t* two_bitvec0 = ndp0->p.d.two_bitvec;
6551 uint32_t nmaj_ct0 = ndp0->nmaj_ct;
6552 if (nm_ct0 != valid_obs_ct) {
6553 nmaj_ct0 = GenoBitvecSumSubset(nm_bitvec1, one_bitvec0, two_bitvec0, sample_ctl);
6554 }
6555 const uintptr_t* one_bitvec1 = ndp1->p.d.one_bitvec;
6556 const uintptr_t* two_bitvec1 = ndp1->p.d.two_bitvec;
6557 uint32_t nmaj_ct1 = ndp1->nmaj_ct;
6558 if (nm_ct1 != valid_obs_ct) {
6559 nmaj_ct1 = GenoBitvecSumSubset(nm_bitvec0, one_bitvec1, two_bitvec1, sample_ctl);
6560 }
6561 uint32_t known_dotprod;
6562 uint32_t unknown_hethet_ct;
6563 GenoBitvecPhasedDotprod(one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, sample_ctl, &known_dotprod, &unknown_hethet_ct);
6564 if ((phase_type == kR2PhaseTypePresent) && (unknown_hethet_ct != 0)) {
6565 // don't bother with no-phase-here optimization for now
6566 HardcallPhasedR2Refine(ndp0->p.d.phasepresent, ndp0->p.d.phaseinfo, ndp1->p.d.phasepresent, ndp1->p.d.phaseinfo, sample_ctl, &known_dotprod, &unknown_hethet_ct);
6567 }
6568 nmajsums_d[0] = u31tod(nmaj_ct0);
6569 nmajsums_d[1] = u31tod(nmaj_ct1);
6570 // bugfix (26 Oct 2023): unknown_hethet treatment shouldn't actually change
6571 // in haploid case
6572 *known_dotprod_d_ptr = S_CAST(double, known_dotprod);
6573 *unknown_hethet_d_ptr = u31tod(unknown_hethet_ct);
6574 return valid_obs_ct;
6575 }
6576
6577 uint32_t ComputeR2DosageUnphasedStats(const R2DosageVariant* dp0, const R2DosageVariant* dp1, uint32_t sample_ct, uint64_t* nmaj_dosages, uint64_t* dosageprod_ptr, uint64_t* ssq0_ptr, uint64_t* ssq1_ptr) {
6578 const Dosage* dosage_vec0 = dp0->dosage_vec;
6579 const Dosage* dosage_vec1 = dp1->dosage_vec;
6580 const uintptr_t* nm_bitvec0 = dp0->nm_bitvec;
6581 const uintptr_t* nm_bitvec1 = dp1->nm_bitvec;
6582 const uint32_t nm_ct0 = dp0->nm_ct;
6583 const uint32_t nm_ct1 = dp1->nm_ct;
6584 nmaj_dosages[0] = dp0->nmaj_dosage;
6585 nmaj_dosages[1] = dp1->nmaj_dosage;
6586 const uint32_t valid_obs_ct = DosageR2Freqs(dosage_vec0, nm_bitvec0, dosage_vec1, nm_bitvec1, sample_ct, nm_ct0, nm_ct1, nmaj_dosages);
6587 if (!valid_obs_ct) {
6588 return 0;
6589 }
6590 const uint32_t sample_dosagev_ct = DivUp(sample_ct, kDosagePerVec);
6591 *dosageprod_ptr = DosageUnsignedDotprod(dosage_vec0, dosage_vec1, sample_dosagev_ct);
6592 if (nm_ct0 == valid_obs_ct) {
6593 *ssq0_ptr = dp0->nmaj_dosage_ssq;
6594 } else {
6595 // bugfix (24 Oct 2023): this needs to mask out opposite missing values
6596 *ssq0_ptr = DosageUnsignedDotprodSubset(dosage_vec1, dosage_vec0, dosage_vec0, sample_dosagev_ct);
6597 }
6598 if (nm_ct1 == valid_obs_ct) {
6599 *ssq1_ptr = dp1->nmaj_dosage_ssq;
6600 } else {
6601 *ssq1_ptr = DosageUnsignedDotprodSubset(dosage_vec0, dosage_vec1, dosage_vec1, sample_dosagev_ct);
6602 }
6603 return valid_obs_ct;
6604 }
6605
6606 uint32_t ComputeR2DosagePhasedStats(const R2DosageVariant* dp0, const R2DosageVariant* dp1, uint32_t sample_ct, R2PhaseType phase_type, double* nmajsums_d, double* known_dotprod_d_ptr, double* unknown_hethet_d_ptr) {
6607 const Dosage* dosage_vec0 = dp0->dosage_vec;
6608 const Dosage* dosage_vec1 = dp1->dosage_vec;
6609 const uintptr_t* nm_bitvec0 = dp0->nm_bitvec;
6610 const uintptr_t* nm_bitvec1 = dp1->nm_bitvec;
6611 const uint32_t nm_ct0 = dp0->nm_ct;
6612 const uint32_t nm_ct1 = dp1->nm_ct;
6613 uint64_t nmaj_dosages[2];
6614 nmaj_dosages[0] = dp0->nmaj_dosage;
6615 nmaj_dosages[1] = dp1->nmaj_dosage;
6616 const uint32_t valid_obs_ct = DosageR2Freqs(dosage_vec0, nm_bitvec0, dosage_vec1, nm_bitvec1, sample_ct, nm_ct0, nm_ct1, nmaj_dosages);
6617 if (!valid_obs_ct) {
6618 return 0;
6619 }
6620 const uint32_t sample_dosagev_ct = DivUp(sample_ct, kDosagePerVec);
6621 uint64_t known_dotprod_dosage;
6622 uint64_t uhethet_dosage;
6623 if (phase_type != kR2PhaseTypePresent) {
6624 const Dosage* dosage_het0 = dp0->dosage_het;
6625 const Dosage* dosage_het1 = dp1->dosage_het;
6626 DosageUnphasedDotprodComponents(dosage_vec0, dosage_vec1, dosage_het0, dosage_het1, sample_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
6627 } else {
6628 const SDosage* dphase_delta0 = dp0->dense_dphase_delta;
6629 const SDosage* dphase_delta1 = dp1->dense_dphase_delta;
6630 DosagePhasedDotprodComponents(dosage_vec0, dosage_vec1, dphase_delta0, dphase_delta1, sample_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
6631 }
6632 nmajsums_d[0] = u63tod(nmaj_dosages[0]) * kRecipDosageMid;
6633 nmajsums_d[1] = u63tod(nmaj_dosages[1]) * kRecipDosageMid;
6634 *known_dotprod_d_ptr = u63tod(known_dotprod_dosage) * kRecipDosageMax;
6635 *unknown_hethet_d_ptr = u63tod(uhethet_dosage) * kRecipDosageMax;
6636 return valid_obs_ct;
6637 }
6638
6639 // d_ptr and/or dprime_ptr can be nullptr. Neither are filled in unphased
6640 // case.
6641 double ComputeR2(const R2Variant* r2vp0, const R2Variant* r2vp1, uint32_t sample_ct, R2PhaseType phase_type, uint32_t load_dosage, double* d_ptr, double* dprime_ptr, uint32_t* is_neg_ptr) {
6642 double nmajsums_d[2];
6643 double known_dotprod_d;
6644 double unknown_hethet_d;
6645 uint32_t valid_obs_ct;
6646 if (!load_dosage) {
6647 const R2NondosageVariant* ndp0 = &(r2vp0->nd);
6648 const R2NondosageVariant* ndp1 = &(r2vp1->nd);
6649 if (phase_type == kR2PhaseTypeUnphased) {
6650 uint32_t nmaj_ct0;
6651 uint32_t nmaj_ct1;
6652 uint32_t ssq0;
6653 uint32_t ssq1;
6654 uint32_t dotprod;
6655 valid_obs_ct = ComputeR2NondosageUnphasedStats(ndp0, ndp1, sample_ct, &nmaj_ct0, &nmaj_ct1, &ssq0, &ssq1, &dotprod);
6656 if (!valid_obs_ct) {
6657 return -DBL_MAX;
6658 }
6659 // Previously implemented in e.g. IndepPairwiseThread.
6660 const int64_t variance0_i64 = ssq0 * S_CAST(int64_t, valid_obs_ct) - S_CAST(int64_t, nmaj_ct0) * nmaj_ct0;
6661 const int64_t variance1_i64 = ssq1 * S_CAST(int64_t, valid_obs_ct) - S_CAST(int64_t, nmaj_ct1) * nmaj_ct1;
6662 const double variance_prod = S_CAST(double, variance0_i64) * S_CAST(double, variance1_i64);
6663 if (variance_prod == 0.0) {
6664 return -DBL_MAX;
6665 }
6666 const double cov01 = S_CAST(double, dotprod * S_CAST(int64_t, valid_obs_ct) - S_CAST(int64_t, nmaj_ct0) * nmaj_ct1);
6667 *is_neg_ptr = (cov01 < 0.0);
6668 return cov01 * cov01 / variance_prod;
6669 }
6670 valid_obs_ct = ComputeR2NondosagePhasedStats(ndp0, ndp1, sample_ct, phase_type, nmajsums_d, &known_dotprod_d, &unknown_hethet_d);
6671 } else {
6672 const R2DosageVariant* dp0 = &(r2vp0->d);
6673 const R2DosageVariant* dp1 = &(r2vp1->d);
6674 if (phase_type == kR2PhaseTypeUnphased) {
6675 uint64_t nmaj_dosages[2];
6676 uint64_t dosageprod;
6677 uint64_t ssq0;
6678 uint64_t ssq1;
6679 valid_obs_ct = ComputeR2DosageUnphasedStats(dp0, dp1, sample_ct, nmaj_dosages, &dosageprod, &ssq0, &ssq1);
6680 if (!valid_obs_ct) {
6681 return -DBL_MAX;
6682 }
6683 const double variance0 = u127prod_diff_d(ssq0, valid_obs_ct, nmaj_dosages[0], nmaj_dosages[0]);
6684 const double variance1 = u127prod_diff_d(ssq1, valid_obs_ct, nmaj_dosages[1], nmaj_dosages[1]);
6685 const double variance_prod = variance0 * variance1;
6686 if (variance_prod == 0.0) {
6687 return -DBL_MAX;
6688 }
6689 const double cov01 = i127prod_diff_d(dosageprod, valid_obs_ct, nmaj_dosages[0], nmaj_dosages[1]);
6690 *is_neg_ptr = (cov01 < 0.0);
6691 return cov01 * cov01 / variance_prod;
6692 }
6693 valid_obs_ct = ComputeR2DosagePhasedStats(dp0, dp1, sample_ct, phase_type, nmajsums_d, &known_dotprod_d, &unknown_hethet_d);
6694 }
6695 if (!valid_obs_ct) {
6696 return -DBL_MAX;
6697 }
6698 const double twice_tot_recip = 0.5 / u31tod(valid_obs_ct);
6699 if ((d_ptr == nullptr) && (dprime_ptr == nullptr)) {
6700 double r2;
6701 const LDErr ld_err = PhasedLD(nmajsums_d, known_dotprod_d, unknown_hethet_d, twice_tot_recip, 0, nullptr, &r2, is_neg_ptr);
6702 return (ld_err == kLDErrNone)? r2 : -DBL_MAX;
6703 }
6704 double results[3];
6705 const LDErr ld_err = PhasedLD(nmajsums_d, known_dotprod_d, unknown_hethet_d, twice_tot_recip, 1, nullptr, results, is_neg_ptr);
6706 if (ld_err != kLDErrNone) {
6707 if (d_ptr) {
6708 *d_ptr = 0.0 / 0.0;
6709 }
6710 if (dprime_ptr) {
6711 *dprime_ptr = 0.0 / 0.0;
6712 }
6713 return -DBL_MAX;
6714 }
6715 if (d_ptr) {
6716 *d_ptr = results[1];
6717 }
6718 if (dprime_ptr) {
6719 *dprime_ptr = results[2];
6720 }
6721 return results[0];
6722 }
6723
6724 uint32_t ComputeR2NondosageUnphased1SparseSubsetStats(const R2NondosageVariant* densevp0, const R2NondosageVariant* sparsevp1, const uintptr_t* sample_include, uint32_t subsetted_nm_ct0, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr) {
6725 const uint32_t difflist_common_geno = sparsevp1->p.s.difflist_common_geno;
6726 const uint32_t difflist_len = sparsevp1->p.s.difflist_len;
6727 const uint32_t* difflist_sample_ids = sparsevp1->p.s.difflist_sample_ids;
6728 uint32_t nmaj_ct0 = 0;
6729 uint32_t nmaj_ct1 = 0;
6730 uint32_t ssq0 = 0;
6731 uint32_t ssq1 = 0;
6732 uint32_t dotprod = 0;
6733 uint32_t valid_obs_ct = 0;
6734 if (difflist_common_geno != 3) {
6735 nmaj_ct0 = *nmaj_ct0_ptr;
6736 ssq0 = *ssq0_ptr;
6737 dotprod = difflist_common_geno * nmaj_ct0;
6738 valid_obs_ct = subsetted_nm_ct0;
6739 nmaj_ct1 = difflist_common_geno * valid_obs_ct;
6740 ssq1 = difflist_common_geno * nmaj_ct1;
6741 }
6742 if (difflist_len) {
6743 const uintptr_t* nm_bitvec0 = densevp0->p.d.nm_bitvec;
6744 const uintptr_t* one_bitvec0 = densevp0->p.d.one_bitvec;
6745 const uintptr_t* two_bitvec0 = densevp0->p.d.two_bitvec;
6746 const uintptr_t* raregeno = sparsevp1->p.s.raregeno;
6747 const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
6748 uint32_t joint_counts[16]; // low bits = dense geno, high bits = sparse
6749 ZeroU32Arr(16, joint_counts);
6750 uint32_t loop_len = kBitsPerWordD2;
6751 for (uint32_t widx = 0; ; ++widx) {
6752 if (widx >= word_ct_m1) {
6753 if (widx > word_ct_m1) {
6754 break;
6755 }
6756 loop_len = ModNz(difflist_len, kBitsPerWordD2);
6757 }
6758 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
6759 uintptr_t raregeno_word = raregeno[widx];
6760 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6761 const uint32_t sample_idx = cur_difflist_sample_ids[uii];
6762 const uint32_t sample_widx = sample_idx / kBitsPerWord;
6763 const uint32_t sample_idx_lowbits = sample_idx % kBitsPerWord;
6764 if ((sample_include[sample_widx] >> sample_idx_lowbits) & 1) {
6765 const uintptr_t cur_sparse_geno = raregeno_word & 3;
6766 const uintptr_t nm_bit = (nm_bitvec0[sample_widx] >> sample_idx_lowbits) & 1;
6767 const uintptr_t one_bit = (one_bitvec0[sample_widx] >> sample_idx_lowbits) & 1;
6768 // "& 3" takes care of this mask
6769 const uintptr_t two_bit_unmasked = two_bitvec0[sample_widx] >> sample_idx_lowbits;
6770 const uintptr_t cur_dense_geno = (nm_bit + one_bit + two_bit_unmasked * 2 - 1) & 3;
6771 joint_counts[cur_dense_geno + cur_sparse_geno * 4] += 1;
6772 }
6773 raregeno_word = raregeno_word >> 2;
6774 }
6775 }
6776 if (difflist_common_geno != 3) {
6777 nmaj_ct0 -= joint_counts[13] + 2 * joint_counts[14];
6778 ssq0 -= joint_counts[13] + 4 * joint_counts[14];
6779 const uint32_t sparse_missing_dense_nm_ct = joint_counts[12] + joint_counts[13] + joint_counts[14];
6780 valid_obs_ct -= sparse_missing_dense_nm_ct;
6781 } else {
6782 const uint32_t dense_one_ct = joint_counts[1] + joint_counts[5] + joint_counts[9];
6783 const uint32_t dense_two_ct = joint_counts[2] + joint_counts[6] + joint_counts[10];
6784 nmaj_ct0 = dense_one_ct + 2 * dense_two_ct;
6785 ssq0 = dense_one_ct + 4 * dense_two_ct;
6786 const uint32_t dense_zero_ct = joint_counts[0] + joint_counts[4] + joint_counts[8];
6787 valid_obs_ct = dense_zero_ct + dense_one_ct + dense_two_ct;
6788 }
6789 const uint32_t sparse_one_ct = joint_counts[4] + joint_counts[5] + joint_counts[6];
6790 if (difflist_common_geno != 2) {
6791 const uint32_t sparse_two_ct = joint_counts[8] + joint_counts[9] + joint_counts[10];
6792 nmaj_ct1 = sparse_one_ct + 2 * sparse_two_ct;
6793 ssq1 = sparse_one_ct + 4 * sparse_two_ct;
6794 dotprod = joint_counts[5] + 2 * (joint_counts[6] + joint_counts[9]) + 4 * joint_counts[10];
6795 } else {
6796 const uint32_t sparse_zmiss_ct = joint_counts[0] + joint_counts[1] + joint_counts[2] + joint_counts[12] + joint_counts[13] + joint_counts[14];
6797 nmaj_ct1 -= sparse_one_ct + 2 * sparse_zmiss_ct;
6798 ssq1 -= 3 * sparse_one_ct + 4 * sparse_zmiss_ct;
6799 dotprod -= joint_counts[5] + 2 * (joint_counts[1] + joint_counts[6] + joint_counts[13]) + 4 * (joint_counts[2] + joint_counts[14]);
6800 }
6801 }
6802 *nmaj_ct0_ptr = nmaj_ct0;
6803 *nmaj_ct1_ptr = nmaj_ct1;
6804 *ssq0_ptr = ssq0;
6805 *ssq1_ptr = ssq1;
6806 *dotprod_ptr = dotprod;
6807 return valid_obs_ct;
6808 }
6809
6810 uint32_t ComputeR2NondosageUnphased2SparseSubsetStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, const uintptr_t* sample_include, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr) {
6811 const R2NondosageVariant* longvp;
6812 const R2NondosageVariant* shortvp;
6813 uint32_t* nmaj_ctlong_ptr;
6814 uint32_t* nmaj_ctshort_ptr;
6815 uint32_t* ssqlong_ptr;
6816 uint32_t* ssqshort_ptr;
6817 uint32_t long_nm_ct;
6818 if (ndp0->p.s.difflist_len <= ndp1->p.s.difflist_len) {
6819 longvp = ndp1;
6820 shortvp = ndp0;
6821 nmaj_ctlong_ptr = nmaj_ct1_ptr;
6822 nmaj_ctshort_ptr = nmaj_ct0_ptr;
6823 ssqlong_ptr = ssq1_ptr;
6824 ssqshort_ptr = ssq0_ptr;
6825 long_nm_ct = subsetted_nm_ct1;
6826 } else {
6827 longvp = ndp0;
6828 shortvp = ndp1;
6829 nmaj_ctlong_ptr = nmaj_ct0_ptr;
6830 nmaj_ctshort_ptr = nmaj_ct1_ptr;
6831 ssqlong_ptr = ssq0_ptr;
6832 ssqshort_ptr = ssq1_ptr;
6833 long_nm_ct = subsetted_nm_ct0;
6834 }
6835 const uint32_t difflist_common_geno_short = shortvp->p.s.difflist_common_geno;
6836 uint32_t nmaj_ctlong = 0;
6837 uint32_t nmaj_ctshort = 0;
6838 uint32_t ssqlong = 0;
6839 uint32_t ssqshort = 0;
6840 uint32_t dotprod = 0;
6841 uint32_t valid_obs_ct = 0;
6842 if (difflist_common_geno_short != 3) {
6843 nmaj_ctlong = *nmaj_ctlong_ptr;
6844 ssqlong = *ssqlong_ptr;
6845 dotprod = difflist_common_geno_short * nmaj_ctlong;
6846 valid_obs_ct = long_nm_ct;
6847 nmaj_ctshort = difflist_common_geno_short * valid_obs_ct;
6848 ssqshort = difflist_common_geno_short * nmaj_ctshort;
6849 }
6850 const uint32_t difflist_len_short = shortvp->p.s.difflist_len;
6851 if (difflist_len_short) {
6852 const uintptr_t* difflist_include_long = longvp->p.s.difflist_include;
6853 const uint32_t* difflist_include_long_cumulative_popcounts = longvp->p.s.difflist_include_cumulative_popcounts;
6854
6855 const uint32_t* difflist_sample_ids_short = shortvp->p.s.difflist_sample_ids;
6856 const uintptr_t* raregeno_long = longvp->p.s.raregeno;
6857 const uintptr_t* raregeno_short = shortvp->p.s.raregeno;
6858 const uint32_t difflist_common_geno_long = longvp->p.s.difflist_common_geno;
6859 uint32_t joint_counts[16]; // low bits = long, high bits = short
6860 ZeroU32Arr(16, joint_counts);
6861 const uint32_t word_ct_m1 = (difflist_len_short - 1) / kBitsPerWordD2;
6862 uint32_t loop_len = kBitsPerWordD2;
6863 for (uint32_t widx = 0; ; ++widx) {
6864 if (widx >= word_ct_m1) {
6865 if (widx > word_ct_m1) {
6866 break;
6867 }
6868 loop_len = ModNz(difflist_len_short, kBitsPerWordD2);
6869 }
6870 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids_short[widx * kBitsPerWordD2]);
6871 uintptr_t raregeno_word = raregeno_short[widx];
6872 for (uint32_t uii = 0; uii != loop_len; ++uii) {
6873 const uint32_t sample_idx = cur_difflist_sample_ids[uii];
6874 if (IsSet(sample_include, sample_idx)) {
6875 const uintptr_t cur_geno_short = raregeno_word & 3;
6876 uintptr_t cur_geno_long = difflist_common_geno_long;
6877 if (IsSet(difflist_include_long, sample_idx)) {
6878 const uint32_t difflist_idx_long = RawToSubsettedPos(difflist_include_long, difflist_include_long_cumulative_popcounts, sample_idx);
6879 cur_geno_long = GetNyparrEntry(raregeno_long, difflist_idx_long);
6880 }
6881 joint_counts[cur_geno_long + 4 * cur_geno_short] += 1;
6882 }
6883 raregeno_word = raregeno_word >> 2;
6884 }
6885 }
6886 if (difflist_common_geno_short != 3) {
6887 nmaj_ctlong -= joint_counts[13] + 2 * joint_counts[14];
6888 ssqlong -= joint_counts[13] + 4 * joint_counts[14];
6889 const uint32_t short_missing_long_nm_ct = joint_counts[12] + joint_counts[13] + joint_counts[14];
6890 valid_obs_ct -= short_missing_long_nm_ct;
6891 } else {
6892 const uint32_t long_one_ct = joint_counts[1] + joint_counts[5] + joint_counts[9];
6893 const uint32_t long_two_ct = joint_counts[2] + joint_counts[6] + joint_counts[10];
6894 nmaj_ctlong = long_one_ct + 2 * long_two_ct;
6895 ssqlong = long_one_ct + 4 * long_two_ct;
6896 const uint32_t long_zero_ct = joint_counts[0] + joint_counts[4] + joint_counts[8];
6897 valid_obs_ct = long_zero_ct + long_one_ct + long_two_ct;
6898 }
6899 const uint32_t short_one_ct = joint_counts[4] + joint_counts[5] + joint_counts[6];
6900 if (difflist_common_geno_short != 2) {
6901 const uint32_t short_two_ct = joint_counts[8] + joint_counts[9] + joint_counts[10];
6902 nmaj_ctshort = short_one_ct + 2 * short_two_ct;
6903 ssqshort = short_one_ct + 4 * short_two_ct;
6904 dotprod = joint_counts[5] + 2 * (joint_counts[6] + joint_counts[9]) + 4 * joint_counts[10];
6905 } else {
6906 const uint32_t short_zmiss_ct = joint_counts[0] + joint_counts[1] + joint_counts[2] + joint_counts[12] + joint_counts[13] + joint_counts[14];
6907 nmaj_ctshort -= short_one_ct + 2 * short_zmiss_ct;
6908 ssqshort -= 3 * short_one_ct + 4 * short_zmiss_ct;
6909 dotprod -= joint_counts[5] + 2 * (joint_counts[1] + joint_counts[6] + joint_counts[13]) + 4 * (joint_counts[2] + joint_counts[14]);
6910 }
6911 }
6912 *nmaj_ctlong_ptr = nmaj_ctlong;
6913 *nmaj_ctshort_ptr = nmaj_ctshort;
6914 *ssqlong_ptr = ssqlong;
6915 *ssqshort_ptr = ssqshort;
6916 *dotprod_ptr = dotprod;
6917 return valid_obs_ct;
6918 }
6919
6920 // nmaj_ct0, nmaj_ct1, ssq0, and ssq1 assumed to be initialized to precomputed
6921 // subsetted values.
6922 uint32_t ComputeR2NondosageUnphasedSubsetStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, const uintptr_t* sample_include, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, uint32_t* nmaj_ct0_ptr, uint32_t* nmaj_ct1_ptr, uint32_t* ssq0_ptr, uint32_t* ssq1_ptr, uint32_t* dotprod_ptr, uintptr_t* cur_nm_buf) {
6923 if (ndp0->is_sparse) {
6924 if (ndp1->is_sparse) {
6925 return ComputeR2NondosageUnphased2SparseSubsetStats(ndp0, ndp1, sample_include, subsetted_nm_ct0, subsetted_nm_ct1, nmaj_ct0_ptr, nmaj_ct1_ptr, ssq0_ptr, ssq1_ptr, dotprod_ptr);
6926 } else {
6927 return ComputeR2NondosageUnphased1SparseSubsetStats(ndp1, ndp0, sample_include, subsetted_nm_ct1, nmaj_ct1_ptr, nmaj_ct0_ptr, ssq1_ptr, ssq0_ptr, dotprod_ptr);
6928 }
6929 }
6930 if (ndp1->is_sparse) {
6931 return ComputeR2NondosageUnphased1SparseSubsetStats(ndp0, ndp1, sample_include, subsetted_nm_ct0, nmaj_ct0_ptr, nmaj_ct1_ptr, ssq0_ptr, ssq1_ptr, dotprod_ptr);
6932 }
6933 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
6934 const uintptr_t* nm_bitvec0 = ndp0->p.d.nm_bitvec;
6935 const uintptr_t* nm_bitvec1 = ndp1->p.d.nm_bitvec;
6936 const uintptr_t* cur_nm;
6937 uint32_t valid_obs_ct;
6938 if (subsetted_nm_ct0 == sample_ct) {
6939 valid_obs_ct = subsetted_nm_ct1;
6940 if (subsetted_nm_ct1 == sample_ct) {
6941 cur_nm = sample_include;
6942 } else {
6943 BitvecAndCopy(nm_bitvec1, sample_include, raw_sample_ctl, cur_nm_buf);
6944 cur_nm = cur_nm_buf;
6945 }
6946 } else {
6947 valid_obs_ct = subsetted_nm_ct0;
6948 BitvecAndCopy(nm_bitvec0, sample_include, raw_sample_ctl, cur_nm_buf);
6949 if (subsetted_nm_ct1 != sample_ct) {
6950 BitvecAnd(nm_bitvec1, raw_sample_ctl, cur_nm_buf);
6951 valid_obs_ct = PopcountWords(cur_nm_buf, raw_sample_ctl);
6952 if (!valid_obs_ct) {
6953 // bugfix (29 Oct 2023)
6954 *nmaj_ct0_ptr = 0;
6955 *nmaj_ct1_ptr = 0;
6956 *ssq0_ptr = 0;
6957 *ssq1_ptr = 0;
6958 *dotprod_ptr = 0;
6959 return 0;
6960 }
6961 }
6962 cur_nm = cur_nm_buf;
6963 }
6964 const uintptr_t* one_bitvec0 = ndp0->p.d.one_bitvec;
6965 const uintptr_t* two_bitvec0 = ndp0->p.d.two_bitvec;
6966 if (subsetted_nm_ct0 != valid_obs_ct) {
6967 const uint32_t nmaj_ct0 = GenoBitvecSumSubset(cur_nm, one_bitvec0, two_bitvec0, raw_sample_ctl);
6968 *nmaj_ct0_ptr = nmaj_ct0;
6969 // 0, 1, 4 instead of 0, 1, 2
6970 *ssq0_ptr = nmaj_ct0 + 2 * PopcountWordsIntersect(cur_nm, two_bitvec0, raw_sample_ctl);
6971 }
6972
6973 const uintptr_t* one_bitvec1 = ndp1->p.d.one_bitvec;
6974 const uintptr_t* two_bitvec1 = ndp1->p.d.two_bitvec;
6975 if (subsetted_nm_ct1 != valid_obs_ct) {
6976 const uint32_t nmaj_ct1 = GenoBitvecSumSubset(cur_nm, one_bitvec1, two_bitvec1, raw_sample_ctl);
6977 *nmaj_ct1_ptr = nmaj_ct1;
6978 *ssq1_ptr = nmaj_ct1 + 2 * PopcountWordsIntersect(cur_nm, two_bitvec1, raw_sample_ctl);
6979 }
6980 *dotprod_ptr = GenoBitvecUnphasedDotprodSubset(cur_nm, one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, raw_sample_ctl);
6981 return valid_obs_ct;
6982 }
6983
6984 uint32_t ComputeR2NondosagePhasedSubsetStats(const R2NondosageVariant* ndp0, const R2NondosageVariant* ndp1, const uintptr_t* sample_include, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, uint32_t subsetted_nmaj_ct0, uint32_t subsetted_nmaj_ct1, R2PhaseType phase_type, double* nmajsums_d, double* known_dotprod_d_ptr, double* unknown_hethet_d_ptr, uintptr_t* cur_nm_buf) {
6985 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
6986 const uintptr_t* nm_bitvec0 = ndp0->p.d.nm_bitvec;
6987 const uintptr_t* nm_bitvec1 = ndp1->p.d.nm_bitvec;
6988 const uintptr_t* cur_nm;
6989 uint32_t valid_obs_ct;
6990 if (subsetted_nm_ct0 == sample_ct) {
6991 valid_obs_ct = subsetted_nm_ct1;
6992 if (subsetted_nm_ct1 == sample_ct) {
6993 cur_nm = sample_include;
6994 } else {
6995 BitvecAndCopy(nm_bitvec1, sample_include, raw_sample_ctl, cur_nm_buf);
6996 cur_nm = cur_nm_buf;
6997 }
6998 } else {
6999 valid_obs_ct = subsetted_nm_ct0;
7000 BitvecAndCopy(nm_bitvec0, sample_include, raw_sample_ctl, cur_nm_buf);
7001 if (subsetted_nm_ct1 != sample_ct) {
7002 BitvecAnd(nm_bitvec1, raw_sample_ctl, cur_nm_buf);
7003 valid_obs_ct = PopcountWords(cur_nm_buf, raw_sample_ctl);
7004 if (!valid_obs_ct) {
7005 // bugfix (29 Oct 2023)
7006 nmajsums_d[0] = 0.0;
7007 nmajsums_d[1] = 0.0;
7008 *known_dotprod_d_ptr = 0;
7009 *unknown_hethet_d_ptr = 0;
7010 return 0;
7011 }
7012 }
7013 cur_nm = cur_nm_buf;
7014 }
7015 const uintptr_t* one_bitvec0 = ndp0->p.d.one_bitvec;
7016 const uintptr_t* two_bitvec0 = ndp0->p.d.two_bitvec;
7017 uint32_t nmaj_ct0 = subsetted_nmaj_ct0;
7018 if (subsetted_nm_ct0 != valid_obs_ct) {
7019 nmaj_ct0 = GenoBitvecSumSubset(cur_nm, one_bitvec0, two_bitvec0, raw_sample_ctl);
7020 }
7021
7022 const uintptr_t* one_bitvec1 = ndp1->p.d.one_bitvec;
7023 const uintptr_t* two_bitvec1 = ndp1->p.d.two_bitvec;
7024 uint32_t nmaj_ct1 = subsetted_nmaj_ct1;
7025 if (subsetted_nm_ct1 != valid_obs_ct) {
7026 nmaj_ct1 = GenoBitvecSumSubset(cur_nm, one_bitvec1, two_bitvec1, raw_sample_ctl);
7027 }
7028
7029 uint32_t known_dotprod;
7030 uint32_t unknown_hethet_ct;
7031 GenoBitvecPhasedDotprodSubset(cur_nm, one_bitvec0, two_bitvec0, one_bitvec1, two_bitvec1, raw_sample_ctl, &known_dotprod, &unknown_hethet_ct);
7032 if ((phase_type == kR2PhaseTypePresent) && (unknown_hethet_ct != 0)) {
7033 // don't bother with no-phase-here optimization for now
7034 HardcallPhasedR2RefineSubset(cur_nm, ndp0->p.d.phasepresent, ndp0->p.d.phaseinfo, ndp1->p.d.phasepresent, ndp1->p.d.phaseinfo, raw_sample_ctl, &known_dotprod, &unknown_hethet_ct);
7035 }
7036 nmajsums_d[0] = u31tod(nmaj_ct0);
7037 nmajsums_d[1] = u31tod(nmaj_ct1);
7038 *known_dotprod_d_ptr = S_CAST(double, known_dotprod);
7039 *unknown_hethet_d_ptr = u31tod(unknown_hethet_ct);
7040 return valid_obs_ct;
7041 }
7042
7043 // nmaj_dosages, ssq0, and ssq1 assumed to be initialized to subset values
7044 uint32_t ComputeR2DosageUnphasedSubsetStats(const R2DosageVariant* dp0, const R2DosageVariant* dp1, const uintptr_t* sample_include, const Dosage* dosage_subset_invmask, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, uint64_t* nmaj_dosages, uint64_t* ssq0_ptr, uint64_t* ssq1_ptr, uint64_t* dosageprod_ptr, uintptr_t* cur_nm_buf, Dosage* invmask_buf) {
7045 const Dosage* dosage_vec0 = dp0->dosage_vec;
7046 const Dosage* dosage_vec1 = dp1->dosage_vec;
7047 const uintptr_t* nm_bitvec0 = dp0->nm_bitvec;
7048 const uintptr_t* nm_bitvec1 = dp1->nm_bitvec;
7049 const uint32_t valid_obs_ct = DosageR2FreqsSubset(dosage_vec0, nm_bitvec0, dosage_vec1, nm_bitvec1, sample_include, raw_sample_ct, sample_ct, subsetted_nm_ct0, subsetted_nm_ct1, nmaj_dosages, cur_nm_buf, invmask_buf);
7050 if (!valid_obs_ct) {
7051 // bugfix (29 Oct 2023)
7052 *dosageprod_ptr = 0.0;
7053 *ssq0_ptr = 0.0;
7054 *ssq1_ptr = 0.0;
7055 return 0;
7056 }
7057 const Dosage* subset_invmask = (valid_obs_ct == sample_ct)? dosage_subset_invmask : invmask_buf;
7058 const uint32_t raw_sample_dosagev_ct = DivUp(raw_sample_ct, kDosagePerVec);
7059 *dosageprod_ptr = DosageUnsignedDotprodSubset(subset_invmask, dosage_vec0, dosage_vec1, raw_sample_dosagev_ct);
7060 if (subsetted_nm_ct0 != valid_obs_ct) {
7061 *ssq0_ptr = DosageUnsignedDotprodSubset(subset_invmask, dosage_vec0, dosage_vec0, raw_sample_dosagev_ct);
7062 }
7063 if (subsetted_nm_ct1 != valid_obs_ct) {
7064 *ssq1_ptr = DosageUnsignedDotprodSubset(subset_invmask, dosage_vec1, dosage_vec1, raw_sample_dosagev_ct);
7065 }
7066 return valid_obs_ct;
7067 }
7068
7069 // Caller is now responsible for setting nmajsums_d[k] =
7070 // u63tod(nmaj_dosages[k]) * kRecipDosageMid afterward.
7071 // bugfix (29 Oct 2023): caller still shouldn't be responsible for initializing
7072 // known_dotprod_d and unknown_hethet_d, so we need to zero them out on the
7073 // early-return.
7074 uint32_t ComputeR2DosagePhasedSubsetStats(const R2DosageVariant* dp0, const R2DosageVariant* dp1, const uintptr_t* sample_include, const Dosage* dosage_subset_invmask, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t subsetted_nm_ct0, uint32_t subsetted_nm_ct1, R2PhaseType phase_type, uint64_t* nmaj_dosages, double* known_dotprod_d_ptr, double* unknown_hethet_d_ptr, uintptr_t* cur_nm_buf, Dosage* invmask_buf) {
7075 const Dosage* dosage_vec0 = dp0->dosage_vec;
7076 const Dosage* dosage_vec1 = dp1->dosage_vec;
7077 const uintptr_t* nm_bitvec0 = dp0->nm_bitvec;
7078 const uintptr_t* nm_bitvec1 = dp1->nm_bitvec;
7079 const uint32_t valid_obs_ct = DosageR2FreqsSubset(dosage_vec0, nm_bitvec0, dosage_vec1, nm_bitvec1, sample_include, raw_sample_ct, sample_ct, subsetted_nm_ct0, subsetted_nm_ct1, nmaj_dosages, cur_nm_buf, invmask_buf);
7080 if (!valid_obs_ct) {
7081 *known_dotprod_d_ptr = 0;
7082 *unknown_hethet_d_ptr = 0;
7083 return 0;
7084 }
7085 const uint32_t raw_sample_dosagev_ct = DivUp(raw_sample_ct, kDosagePerVec);
7086 const Dosage* subset_invmask = (valid_obs_ct == sample_ct)? dosage_subset_invmask : invmask_buf;
7087 uint64_t known_dotprod_dosage;
7088 uint64_t uhethet_dosage;
7089 if (phase_type != kR2PhaseTypePresent) {
7090 const Dosage* dosage_het0 = dp0->dosage_het;
7091 const Dosage* dosage_het1 = dp1->dosage_het;
7092 DosageUnphasedDotprodComponentsSubset(subset_invmask, dosage_vec0, dosage_vec1, dosage_het0, dosage_het1, raw_sample_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
7093 } else {
7094 const SDosage* dphase_delta0 = dp0->dense_dphase_delta;
7095 const SDosage* dphase_delta1 = dp1->dense_dphase_delta;
7096 DosagePhasedDotprodComponentsSubset(subset_invmask, dosage_vec0, dosage_vec1, dphase_delta0, dphase_delta1, raw_sample_dosagev_ct, &known_dotprod_dosage, &uhethet_dosage);
7097 }
7098 *known_dotprod_d_ptr = u63tod(known_dotprod_dosage) * kRecipDosageMax;
7099 *unknown_hethet_d_ptr = u63tod(uhethet_dosage) * kRecipDosageMax;
7100 return valid_obs_ct;
7101 }
7102
7103 // There initially was a separate code path for the non-inter-chr case, where
7104 // the male and nonmale genotypes were pre-separated. It was useful as a
7105 // somewhat-independent implementation to test ComputeXR2() against. But it's
7106 // now deleted, despite being faster, since chrX-specific code is a defect
7107 // attractor and does not cover a large fraction of typical computational
7108 // loads.
7109 double ComputeXR2(const R2Variant* r2vp0, const R2Variant* r2vp1, const uintptr_t* founder_male_collapsed, const uintptr_t* founder_nonmale_collapsed, const Dosage* male_dosage_invmask, const Dosage* nonmale_dosage_invmask, uint32_t sample_ct, uint32_t male_ct, R2PhaseType phase_type, uint32_t load_dosage, uint32_t both_x, double* d_ptr, double* dprime_ptr, uint32_t* is_neg_ptr, uintptr_t* cur_nm_buf, Dosage* invmask_buf) {
7110 const double male_downwt = both_x? 0.5 : (1.0 - 0.5 * kSqrt2);
7111
7112 double male_nmajsums_d[2];
7113 double male_known_dotprod_d;
7114 double male_unknown_hethet_d;
7115 uint32_t male_obs_ct;
7116
7117 double nonmale_nmajsums_d[2];
7118 double nonmale_known_dotprod_d;
7119 double nonmale_unknown_hethet_d;
7120 uint32_t nonmale_obs_ct;
7121 if (!load_dosage) {
7122 const R2NondosageVariant* ndp0 = &(r2vp0->nd);
7123 const R2NondosageVariant* ndp1 = &(r2vp1->nd);
7124 if (phase_type == kR2PhaseTypeUnphased) {
7125 uint32_t nmaj_ct0;
7126 uint32_t nmaj_ct1;
7127 uint32_t ssq0;
7128 uint32_t ssq1;
7129 uint32_t dotprod;
7130 const uint32_t valid_obs_ct = ComputeR2NondosageUnphasedStats(ndp0, ndp1, sample_ct, &nmaj_ct0, &nmaj_ct1, &ssq0, &ssq1, &dotprod);
7131 if (!valid_obs_ct) {
7132 return -DBL_MAX;
7133 }
7134 /*
7135 printf("nmaj_ct0: %u\n", nmaj_ct0);
7136 printf("nmaj_ct1: %u\n", nmaj_ct1);
7137 printf("ssq0: %u\n", ssq0);
7138 printf("ssq1: %u\n", ssq1);
7139 printf("dotprod: %u\n", dotprod);
7140 printf("valid_obs_ct: %u\n", valid_obs_ct);
7141 */
7142 uint32_t male_nmaj_ct0 = ndp0->x_male_nmaj_ct;
7143 uint32_t male_nmaj_ct1 = ndp1->x_male_nmaj_ct;
7144 uint32_t male_ssq0 = ndp0->x_male_ssq;
7145 uint32_t male_ssq1 = ndp1->x_male_ssq;
7146 uint32_t male_dotprod;
7147 // printf("male_ssq1 before: %u\n", male_ssq1);
7148 male_obs_ct = ComputeR2NondosageUnphasedSubsetStats(ndp0, ndp1, founder_male_collapsed, sample_ct, male_ct, ndp0->x_male_nm_ct, ndp1->x_male_nm_ct, &male_nmaj_ct0, &male_nmaj_ct1, &male_ssq0, &male_ssq1, &male_dotprod, cur_nm_buf);
7149 /*
7150 printf("male_nmaj_ct0: %u\n", male_nmaj_ct0);
7151 printf("male_nmaj_ct1: %u\n", male_nmaj_ct1);
7152 printf("male_ssq0: %u\n", male_ssq0);
7153 printf("male_ssq1: %u\n", male_ssq1);
7154 printf("male_dotprod: %u\n", male_dotprod);
7155 printf("male_obs_ct: %u\n", male_obs_ct);
7156 */
7157
7158 const double weighted_obs_ct = u31tod(valid_obs_ct) - male_downwt * u31tod(male_obs_ct);
7159 const double weighted_nmaj_ct0 = u31tod(nmaj_ct0) - male_downwt * u31tod(male_nmaj_ct0);
7160 const double weighted_nmaj_ct1 = u31tod(nmaj_ct1) - male_downwt * u31tod(male_nmaj_ct1);
7161 const double weighted_ssq0 = u63tod(ssq0) - male_downwt * u63tod(male_ssq0);
7162 const double weighted_ssq1 = u63tod(ssq1) - male_downwt * u63tod(male_ssq1);
7163 const double weighted_dotprod = u63tod(dotprod) - male_downwt * u63tod(male_dotprod);
7164
7165 const double variance0 = weighted_ssq0 * weighted_obs_ct - weighted_nmaj_ct0 * weighted_nmaj_ct0;
7166 const double variance1 = weighted_ssq1 * weighted_obs_ct - weighted_nmaj_ct1 * weighted_nmaj_ct1;
7167 if ((variance0 <= 0.0) || (variance1 <= 0.0)) {
7168 return -DBL_MAX;
7169 }
7170 const double variance_prod = variance0 * variance1;
7171 const double cov01 = weighted_dotprod * weighted_obs_ct - weighted_nmaj_ct0 * weighted_nmaj_ct1;
7172 *is_neg_ptr = (cov01 < 0.0);
7173 return MINV(1.0, cov01 * cov01 / variance_prod);
7174 }
7175 const uint32_t x_male_nm_ct0 = ndp0->x_male_nm_ct;
7176 const uint32_t x_male_nm_ct1 = ndp1->x_male_nm_ct;
7177 const uint32_t x_male_nmaj_ct0 = ndp0->x_male_nmaj_ct;
7178 const uint32_t x_male_nmaj_ct1 = ndp1->x_male_nmaj_ct;
7179 male_obs_ct = ComputeR2NondosagePhasedSubsetStats(ndp0, ndp1, founder_male_collapsed, sample_ct, male_ct, x_male_nm_ct0, x_male_nm_ct1, x_male_nmaj_ct0, x_male_nmaj_ct1, R2PhaseOmit(phase_type), male_nmajsums_d, &male_known_dotprod_d, &male_unknown_hethet_d, cur_nm_buf);
7180 nonmale_obs_ct = ComputeR2NondosagePhasedSubsetStats(ndp0, ndp1, founder_nonmale_collapsed, sample_ct, sample_ct - male_ct, ndp0->nm_ct - x_male_nm_ct0, ndp1->nm_ct - x_male_nm_ct1, ndp0->nmaj_ct - x_male_nmaj_ct0, ndp1->nmaj_ct - x_male_nmaj_ct1, phase_type, nonmale_nmajsums_d, &nonmale_known_dotprod_d, &nonmale_unknown_hethet_d, cur_nm_buf);
7181 } else {
7182 const R2DosageVariant* dp0 = &(r2vp0->d);
7183 const R2DosageVariant* dp1 = &(r2vp1->d);
7184 uint64_t sex_nmaj_dosages[2];
7185 sex_nmaj_dosages[0] = dp0->x_male_nmaj_dosage;
7186 sex_nmaj_dosages[1] = dp1->x_male_nmaj_dosage;
7187 if (phase_type == kR2PhaseTypeUnphased) {
7188 uint64_t nmaj_dosages[2];
7189 uint64_t dosageprod;
7190 uint64_t ssq0;
7191 uint64_t ssq1;
7192 const uint32_t valid_obs_ct = ComputeR2DosageUnphasedStats(dp0, dp1, sample_ct, nmaj_dosages, &dosageprod, &ssq0, &ssq1);
7193 if (!valid_obs_ct) {
7194 return -DBL_MAX;
7195 }
7196 uint64_t male_ssq0 = dp0->x_male_nmaj_dosage_ssq;
7197 uint64_t male_ssq1 = dp1->x_male_nmaj_dosage_ssq;
7198 uint64_t male_dosageprod;
7199 male_obs_ct = ComputeR2DosageUnphasedSubsetStats(dp0, dp1, founder_male_collapsed, male_dosage_invmask, sample_ct, male_ct, dp0->x_male_nm_ct, dp1->x_male_nm_ct, sex_nmaj_dosages, &male_ssq0, &male_ssq1, &male_dosageprod, cur_nm_buf, invmask_buf);
7200
7201 const double weighted_obs_ct = u31tod(valid_obs_ct) - male_downwt * u31tod(male_obs_ct);
7202 const double weighted_nmaj0 = u63tod(nmaj_dosages[0]) - male_downwt * u63tod(sex_nmaj_dosages[0]);
7203 const double weighted_nmaj1 = u63tod(nmaj_dosages[1]) - male_downwt * u63tod(sex_nmaj_dosages[1]);
7204 const double weighted_dosageprod = u63tod(dosageprod) - male_downwt * u63tod(male_dosageprod);
7205 const double weighted_ssq0 = u63tod(ssq0) - male_downwt * u63tod(male_ssq0);
7206 const double weighted_ssq1 = u63tod(ssq1) - male_downwt * u63tod(male_ssq1);
7207
7208 const double variance0 = weighted_ssq0 * weighted_obs_ct - weighted_nmaj0 * weighted_nmaj0;
7209 const double variance1 = weighted_ssq1 * weighted_obs_ct - weighted_nmaj1 * weighted_nmaj1;
7210 if ((variance0 <= 0.0) || (variance1 <= 0.0)) {
7211 return -DBL_MAX;
7212 }
7213 const double variance_prod = variance0 * variance1;
7214 if (variance_prod == 0.0) {
7215 return -DBL_MAX;
7216 }
7217 const double cov01 = weighted_dosageprod * weighted_obs_ct - weighted_nmaj0 * weighted_nmaj1;
7218 *is_neg_ptr = (cov01 < 0.0);
7219 return MINV(1.0, cov01 * cov01 / variance_prod);
7220 }
7221 const uint32_t x_male_nm_ct0 = dp0->x_male_nm_ct;
7222 const uint32_t x_male_nm_ct1 = dp1->x_male_nm_ct;
7223 male_obs_ct = ComputeR2DosagePhasedSubsetStats(dp0, dp1, founder_male_collapsed, male_dosage_invmask, sample_ct, male_ct, x_male_nm_ct0, x_male_nm_ct1, R2PhaseOmit(phase_type), sex_nmaj_dosages, &male_known_dotprod_d, &male_unknown_hethet_d, cur_nm_buf, invmask_buf);
7224 male_nmajsums_d[0] = u63tod(sex_nmaj_dosages[0]) * kRecipDosageMid;
7225 male_nmajsums_d[1] = u63tod(sex_nmaj_dosages[1]) * kRecipDosageMid;
7226
7227 sex_nmaj_dosages[0] = dp0->nmaj_dosage - dp0->x_male_nmaj_dosage;
7228 sex_nmaj_dosages[1] = dp1->nmaj_dosage - dp1->x_male_nmaj_dosage;
7229 nonmale_obs_ct = ComputeR2DosagePhasedSubsetStats(dp0, dp1, founder_nonmale_collapsed, nonmale_dosage_invmask, sample_ct, sample_ct - male_ct, dp0->nm_ct - x_male_nm_ct0, dp1->nm_ct - x_male_nm_ct1, phase_type, sex_nmaj_dosages, &nonmale_known_dotprod_d, &nonmale_unknown_hethet_d, cur_nm_buf, invmask_buf);
7230 nonmale_nmajsums_d[0] = u63tod(sex_nmaj_dosages[0]) * kRecipDosageMid;
7231 nonmale_nmajsums_d[1] = u63tod(sex_nmaj_dosages[1]) * kRecipDosageMid;
7232 }
7233 if (male_obs_ct + nonmale_obs_ct == 0) {
7234 return -DBL_MAX;
7235 }
7236 const double male_wt = 1.0 - male_downwt;
7237 double nmajsums_d[2];
7238 nmajsums_d[0] = nonmale_nmajsums_d[0] + male_wt * male_nmajsums_d[0];
7239 nmajsums_d[1] = nonmale_nmajsums_d[1] + male_wt * male_nmajsums_d[1];
7240 const double known_dotprod_d = nonmale_known_dotprod_d + male_wt * male_known_dotprod_d;
7241 const double unknown_hethet_d = nonmale_unknown_hethet_d + male_wt * male_unknown_hethet_d;
7242 const double valid_obs_d = u31tod(nonmale_obs_ct) + male_wt * u31tod(male_obs_ct);
7243 const double twice_tot_recip = 0.5 / valid_obs_d;
7244 if ((d_ptr == nullptr) && (dprime_ptr == nullptr)) {
7245 double r2;
7246 const LDErr ld_err = PhasedLD(nmajsums_d, known_dotprod_d, unknown_hethet_d, twice_tot_recip, 0, nullptr, &r2, is_neg_ptr);
7247 return (ld_err == kLDErrNone)? r2 : -DBL_MAX;
7248 }
7249 double results[3];
7250 const LDErr ld_err = PhasedLD(nmajsums_d, known_dotprod_d, unknown_hethet_d, twice_tot_recip, 1, nullptr, results, is_neg_ptr);
7251 if (ld_err != kLDErrNone) {
7252 if (d_ptr) {
7253 *d_ptr = 0.0 / 0.0;
7254 }
7255 if (dprime_ptr) {
7256 *dprime_ptr = 0.0 / 0.0;
7257 }
7258 return -DBL_MAX;
7259 }
7260 if (d_ptr) {
7261 *d_ptr = results[1];
7262 }
7263 if (dprime_ptr) {
7264 *dprime_ptr = results[2];
7265 }
7266 return results[0];
7267 }
7268
7269 void ClumpHighmemR2(uintptr_t tidx, uint32_t thread_ct_p1, uint32_t parity, ClumpCtx* ctx) {
7270 // Compute r^2 of non-index (variant, aidx)s against the current index
7271 // variant, with everything already unpacked.
7272 const uint64_t cur_nonindex_ct = ctx->cur_nonindex_ct;
7273 const uintptr_t nonindex_start = (cur_nonindex_ct * tidx) / thread_ct_p1;
7274 const uintptr_t nonindex_end = (cur_nonindex_ct * (tidx + 1)) / thread_ct_p1;
7275 uintptr_t nonindex_rem = nonindex_end - nonindex_start;
7276 uintptr_t* write_iter = ctx->ld_idx_found[tidx];
7277 if (!nonindex_rem) {
7278 *write_iter = ~k0LU;
7279 return;
7280 }
7281 const uintptr_t igroup_oaidx_start = ctx->igroup_oaidx_start;
7282 const uintptr_t unpacked_byte_stride = ctx->unpacked_byte_stride;
7283 const uintptr_t* observed_alleles = ctx->observed_alleles;
7284 const uintptr_t* observed_alleles_cumulative_popcounts_w = ctx->observed_alleles_cumulative_popcounts_w;
7285 const unsigned char* unpacked_variants = ctx->unpacked_variants;
7286 const uintptr_t* candidate_oabitvec = ctx->candidate_oabitvec;
7287 uintptr_t allele_widx_start = ctx->allele_widx_start;
7288 const uintptr_t allele_widx_end = ctx->allele_widx_end;
7289 const uintptr_t oaidx_start = ctx->a[parity].oaidx_starts[tidx];
7290 const uint32_t founder_ct = ctx->founder_ct;
7291 const uint32_t founder_male_ct = ctx->founder_male_ct;
7292 const uint32_t allow_overlap = ctx->allow_overlap;
7293 const uint32_t is_x = ctx->is_x;
7294 const uintptr_t* founder_male_collapsed = nullptr;
7295 const uintptr_t* founder_nonmale_collapsed = nullptr;
7296 const Dosage* male_dosage_invmask = nullptr;
7297 const Dosage* nonmale_dosage_invmask = nullptr;
7298 uintptr_t* chrx_nm_buf = nullptr;
7299 Dosage* chrx_invmask_buf = nullptr;
7300 if (is_x) {
7301 founder_male_collapsed = ctx->founder_male_collapsed;
7302 male_dosage_invmask = ctx->male_dosage_invmask;
7303 founder_nonmale_collapsed = ctx->founder_nonmale_collapsed;
7304 nonmale_dosage_invmask = ctx->nonmale_dosage_invmask;
7305 chrx_nm_buf = ctx->chrx_workspaces[tidx];
7306 const uint32_t founder_ctaw = BitCtToAlignedWordCt(founder_ct);
7307 chrx_invmask_buf = R_CAST(Dosage*, &(chrx_nm_buf[founder_ctaw]));
7308 }
7309 const R2PhaseType phase_type = S_CAST(R2PhaseType, ctx->phase_type);
7310 const uint32_t load_dosage = ctx->load_dosage;
7311 const double r2_thresh = ctx->r2_thresh;
7312 const unsigned char* unpacked_index_variant = &(unpacked_variants[ctx->index_oaidx_offset * unpacked_byte_stride]);
7313 R2Variant index_r2v;
7314 FillR2V(unpacked_index_variant, founder_ct, phase_type, is_x, load_dosage, &index_r2v);
7315 uintptr_t oaidx_base;
7316 uintptr_t cur_oaidx_bits;
7317 BitIter1Start(candidate_oabitvec, oaidx_start, &oaidx_base, &cur_oaidx_bits);
7318 for (; nonindex_rem; --nonindex_rem) {
7319 const uintptr_t oaidx = BitIter1(candidate_oabitvec, &oaidx_base, &cur_oaidx_bits);
7320 const uintptr_t oaidx_offset = oaidx - igroup_oaidx_start;
7321 const unsigned char* unpacked_cur_variant = &(unpacked_variants[oaidx_offset * unpacked_byte_stride]);
7322 R2Variant cur_r2v;
7323 FillR2V(unpacked_cur_variant, founder_ct, phase_type, is_x, load_dosage, &cur_r2v);
7324 double cur_r2;
7325 if (!is_x) {
7326 uint32_t is_neg;
7327 cur_r2 = ComputeR2(&index_r2v, &cur_r2v, founder_ct, phase_type, load_dosage, nullptr, nullptr, &is_neg);
7328 } else {
7329 uint32_t is_neg;
7330 cur_r2 = ComputeXR2(&index_r2v, &cur_r2v, founder_male_collapsed, founder_nonmale_collapsed, male_dosage_invmask, nonmale_dosage_invmask, founder_ct, founder_male_ct, phase_type, load_dosage, 1, nullptr, nullptr, &is_neg, chrx_nm_buf, chrx_invmask_buf);
7331 }
7332 if (cur_r2 > r2_thresh) {
7333 if (!allow_overlap) {
7334 *write_iter = oaidx;
7335 } else {
7336 const uintptr_t allele_idx = ExpsearchIdxToUidxW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_widx_end, oaidx, &allele_widx_start);
7337 *write_iter = allele_idx;
7338 }
7339 ++write_iter;
7340 }
7341 }
7342 *write_iter = ~k0LU;
7343 }
7344
7345 void ClumpLowmemR2(uintptr_t tidx, uint32_t thread_ct_p1, uint32_t parity, ClumpCtx* ctx) {
7346 // Unpack a few non-index PgenVariants that were read by the main thread,
7347 // then compute r^2 between them and the index-(variant, aidx).
7348 const uint64_t cur_nonindex_ct = ctx->cur_nonindex_ct;
7349 // yeah, this variable name sucks
7350 uintptr_t nonindex_idx = (cur_nonindex_ct * tidx) / thread_ct_p1;
7351 const uintptr_t nonindex_end = (cur_nonindex_ct * (tidx + 1)) / thread_ct_p1;
7352 uintptr_t* write_iter = ctx->ld_idx_found[tidx];
7353 if (nonindex_idx == nonindex_end) {
7354 *write_iter = ~k0LU;
7355 return;
7356 }
7357 const uintptr_t* observed_alleles = ctx->observed_alleles;
7358 const uintptr_t* observed_alleles_cumulative_popcounts_w = ctx->observed_alleles_cumulative_popcounts_w;
7359 const uintptr_t pgv_byte_stride = ctx->pgv_byte_stride;
7360 PgenVariant pgv = ctx->pgv_base;
7361 ClumpPgenVariantIncr(pgv_byte_stride * nonindex_idx, &pgv);
7362 const uintptr_t* candidate_oabitvec = ctx->candidate_oabitvec;
7363 uintptr_t allele_widx_start = ctx->allele_widx_start;
7364 const uintptr_t allele_widx_end = ctx->allele_widx_end;
7365 const uintptr_t oaidx_start = ctx->a[parity].oaidx_starts[tidx];
7366 uint32_t founder_ct = ctx->founder_ct;
7367 const uint32_t founder_male_ct = ctx->founder_male_ct;
7368 const uint32_t allow_overlap = ctx->allow_overlap;
7369 const uint32_t is_x = ctx->is_x;
7370 const uintptr_t* founder_male_collapsed = nullptr;
7371 const uintptr_t* founder_nonmale_collapsed = nullptr;
7372 const Dosage* male_dosage_invmask = nullptr;
7373 const Dosage* nonmale_dosage_invmask = nullptr;
7374 uintptr_t* chrx_nm_buf = nullptr;
7375 Dosage* chrx_invmask_buf = nullptr;
7376 if (is_x) {
7377 founder_male_collapsed = ctx->founder_male_collapsed;
7378 founder_nonmale_collapsed = ctx->founder_nonmale_collapsed;
7379 male_dosage_invmask = ctx->male_dosage_invmask;
7380 nonmale_dosage_invmask = ctx->nonmale_dosage_invmask;
7381 chrx_nm_buf = ctx->chrx_workspaces[tidx];
7382 const uint32_t founder_ctaw = BitCtToAlignedWordCt(founder_ct);
7383 chrx_invmask_buf = R_CAST(Dosage*, &(chrx_nm_buf[founder_ctaw]));
7384 }
7385 const R2PhaseType phase_type = S_CAST(R2PhaseType, ctx->phase_type);
7386 const uint32_t load_dosage = ctx->load_dosage;
7387 const double r2_thresh = ctx->r2_thresh;
7388 unsigned char* unpacked_index_variant = ctx->unpacked_variants;
7389 R2Variant index_r2v;
7390 FillR2V(unpacked_index_variant, founder_ct, phase_type, is_x, load_dosage, &index_r2v);
7391 const uint32_t* phasepresent_cts = ctx->phasepresent_cts;
7392 const uint32_t* dosage_cts = ctx->dosage_cts;
7393 const uint32_t* dphase_cts = ctx->dphase_cts;
7394 const uintptr_t unpacked_byte_stride = ctx->unpacked_byte_stride;
7395 unsigned char* unpacked_cur_variant = &(unpacked_index_variant[(tidx + 1) * unpacked_byte_stride]);
7396 uintptr_t oaidx_base;
7397 uintptr_t cur_oaidx_bits;
7398 BitIter1Start(candidate_oabitvec, oaidx_start, &oaidx_base, &cur_oaidx_bits);
7399 for (; nonindex_idx != nonindex_end; ++nonindex_idx, ClumpPgenVariantIncr(pgv_byte_stride, &pgv)) {
7400 if (phasepresent_cts) {
7401 pgv.phasepresent_ct = phasepresent_cts[nonindex_idx];
7402 }
7403 if (dosage_cts) {
7404 pgv.dosage_ct = dosage_cts[nonindex_idx];
7405 if (dphase_cts) {
7406 pgv.dphase_ct = dphase_cts[nonindex_idx];
7407 }
7408 }
7409 const uintptr_t oaidx = BitIter1(candidate_oabitvec, &oaidx_base, &cur_oaidx_bits);
7410 if (load_dosage) {
7411 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, unpacked_cur_variant);
7412 } else {
7413 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, unpacked_cur_variant);
7414 }
7415 R2Variant cur_r2v;
7416 FillR2V(unpacked_cur_variant, founder_ct, phase_type, is_x, load_dosage, &cur_r2v);
7417 double cur_r2;
7418 if (!is_x) {
7419 uint32_t is_neg;
7420 cur_r2 = ComputeR2(&index_r2v, &cur_r2v, founder_ct, phase_type, load_dosage, nullptr, nullptr, &is_neg);
7421 } else {
7422 uint32_t is_neg;
7423 cur_r2 = ComputeXR2(&index_r2v, &cur_r2v, founder_male_collapsed, founder_nonmale_collapsed, male_dosage_invmask, nonmale_dosage_invmask, founder_ct, founder_male_ct, phase_type, load_dosage, 1, nullptr, nullptr, &is_neg, chrx_nm_buf, chrx_invmask_buf);
7424 }
7425 if (cur_r2 > r2_thresh) {
7426 if (!allow_overlap) {
7427 *write_iter = oaidx;
7428 } else {
7429 const uintptr_t allele_idx = ExpsearchIdxToUidxW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_widx_end, oaidx, &allele_widx_start);
7430 *write_iter = allele_idx;
7431 }
7432 ++write_iter;
7433 }
7434 }
7435 *write_iter = ~k0LU;
7436 }
7437
7438 THREAD_FUNC_DECL ClumpThread(void* raw_arg) {
7439 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
7440 const uintptr_t tidx = arg->tidx;
7441 const uint32_t calc_thread_ct_p1 = 1 + GetThreadCt(arg->sharedp);
7442 ClumpCtx* ctx = S_CAST(ClumpCtx*, arg->sharedp->context);
7443 uint32_t parity = 0;
7444 do {
7445 const ClumpJobType job_type = ctx->job_type;
7446 if (job_type == kClumpJobHighmemUnpack) {
7447 ClumpHighmemUnpack(tidx, parity, ctx);
7448 } else if (job_type == kClumpJobHighmemR2) {
7449 ClumpHighmemR2(tidx, calc_thread_ct_p1, parity, ctx);
7450 } else if (job_type == kClumpJobLowmemR2) {
7451 ClumpLowmemR2(tidx, calc_thread_ct_p1, parity, ctx);
7452 }
7453 parity = 1 - parity;
7454 } while (!THREAD_BLOCK_FINISH(arg));
7455 THREAD_RETURN;
7456 }
7457
7458 BoolErr ClumpSpillResults(const uintptr_t* observed_alleles, const uintptr_t* observed_alleles_cumulative_popcounts_w, uintptr_t* const* ld_idx_found, uint32_t cur_thread_ct, uintptr_t* prev_save_allele_idxp, uintptr_t* clump_sizep, uintptr_t* icandidate_oabitvec, FILE* clump_overlap_tmp) {
7459 uintptr_t prev_save_allele_idx = *prev_save_allele_idxp;
7460 uintptr_t clump_size = *clump_sizep;
7461 unsigned char buf[16];
7462 for (uint32_t tidx = 0; tidx != cur_thread_ct; ++tidx) {
7463 const uintptr_t* read_iter = ld_idx_found[tidx];
7464 for (; ; ++read_iter) {
7465 const uintptr_t save_allele_idx = *read_iter;
7466 if (save_allele_idx == ~k0LU) {
7467 break;
7468 }
7469 const uintptr_t oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, save_allele_idx);
7470 ClearBit(oaidx, icandidate_oabitvec);
7471 unsigned char* write_iter = Vint64Append(save_allele_idx - prev_save_allele_idx, buf);
7472 if (unlikely(!fwrite_unlocked(buf, 1, write_iter - buf, clump_overlap_tmp))) {
7473 return 1;
7474 }
7475 prev_save_allele_idx = save_allele_idx;
7476 ++clump_size;
7477 }
7478 }
7479 *prev_save_allele_idxp = prev_save_allele_idx;
7480 *clump_sizep = clump_size;
7481 return 0;
7482 }
7483
7484 // 0.0001, 0.001, 0.01, 0.05 with appropriate epsilons
7485 static const double kClumpDefaultLnBinBounds[4] = {
7486 -9.210340371976706,
7487 -6.907755278982529,
7488 -4.605170185988353,
7489 -2.995732273554161
7490 };
7491
7492 static_assert(kClumpMaxBinBounds * (kMaxLnGSlen + 1) + 256 <= kMaxLongLine, "ClumpReports() needs to be updated.");
7493 PglErr ClumpReports(const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const ClumpInfo* clump_ip, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t nosex_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, double output_min_ln, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
7494 unsigned char* bigstack_mark = g_bigstack_base;
7495 unsigned char* bigstack_end_mark = g_bigstack_end;
7496 char* fname_iter = clump_ip->fnames_flattened;
7497 uintptr_t line_idx = 0;
7498 FILE* clump_overlap_tmp = nullptr;
7499 char* cswritep = nullptr;
7500 PglErr reterr = kPglRetSuccess;
7501 ClumpCtx ctx;
7502 TextStream txs;
7503 CompressStreamState css;
7504 ThreadGroup tg;
7505 PreinitTextStream(&txs);
7506 PreinitCstream(&css);
7507 PreinitThreads(&tg);
7508 {
7509 if (unlikely(founder_ct < 2)) {
7510 logerrputs("Error: --clump requires at least two founders. (--make-founders may come in handy\nhere.)\n");
7511 goto ClumpReports_ret_INCONSISTENT_INPUT;
7512 } else if (founder_ct > 0x3fffffff) {
7513 logerrputs("Error: --clump does not support >= 2^30 founders.\n");
7514 goto ClumpReports_ret_NOT_YET_SUPPORTED;
7515 }
7516 uint32_t skipped_variant_ct;
7517 const uintptr_t* variant_include = StripUnplacedK(orig_variant_include, cip, raw_variant_ct, &skipped_variant_ct);
7518 if (unlikely(variant_include == nullptr)) {
7519 goto ClumpReports_ret_NOMEM;
7520 }
7521 const uint32_t variant_ct = orig_variant_ct - skipped_variant_ct;
7522 if (skipped_variant_ct) {
7523 logprintf("--clump: Ignoring %u chromosome 0 variant%s.\n", skipped_variant_ct, (skipped_variant_ct == 1)? "" : "s");
7524 }
7525 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
7526 const uintptr_t raw_allele_ct = allele_idx_offsets? allele_idx_offsets[raw_variant_ct] : (2 * raw_variant_ct);
7527 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
7528 const uintptr_t* variant_last_alidxs;
7529 const uint32_t* variant_last_alidxs_cumulative_popcounts;
7530 reterr = AllocAndFillVariantLastAlidxs(allele_idx_offsets, raw_variant_ct, max_thread_ct, &variant_last_alidxs, &variant_last_alidxs_cumulative_popcounts);
7531 if (unlikely(reterr)) {
7532 goto ClumpReports_ret_1;
7533 }
7534 uintptr_t* observed_variants;
7535 uintptr_t* observed_alleles;
7536 uintptr_t* observed_alleles_cumulative_popcounts_w;
7537 double* best_ln_pvals;
7538 // bugfix (29 Oct 2023): there are RawToSubsettedPosW(observed_alleles,
7539 // observed_alleles_cumulative_popcounts_w, x) calls with x =
7540 // raw_allele_ct. In this case, we may need one more entry.
7541 if (unlikely(bigstack_calloc_w(raw_variant_ctl, &observed_variants) ||
7542 bigstack_calloc_w(raw_allele_ctl, &observed_alleles) ||
7543 bigstack_alloc_w(1 + (raw_allele_ct / kBitsPerWord), &observed_alleles_cumulative_popcounts_w) ||
7544 bigstack_end_calloc_d(raw_allele_ct, &best_ln_pvals))) {
7545 goto ClumpReports_ret_NOMEM;
7546 }
7547 unsigned char* bigstack_mark2 = g_bigstack_base;
7548 unsigned char* bigstack_end_mark2 = g_bigstack_end;
7549 uint32_t file_ct = 0;
7550 do {
7551 char* fname_end = strnul(fname_iter);
7552 ++file_ct;
7553 fname_iter = &(fname_end[1]);
7554 } while (*fname_iter);
7555 assert(file_ct < 0x40000000);
7556 const ClumpFlags flags = clump_ip->flags;
7557 const uint32_t force_a1 = (flags / kfClumpForceA1) & 1;
7558 uint32_t* best_fidx_x2s = nullptr;
7559 if (((file_ct > 1) && (flags & (kfClumpColMaybeF | kfClumpColF | kfClumpColSp2))) || force_a1) {
7560 if (unlikely(bigstack_alloc_u32(raw_allele_ct, &best_fidx_x2s))) {
7561 goto ClumpReports_ret_NOMEM;
7562 }
7563 }
7564 const double* ln_bin_boundaries = nullptr;
7565 uint32_t bin_bound_ct = 0;
7566 if (flags & kfClumpColBins) {
7567 bin_bound_ct = clump_ip->bin_bound_ct;
7568 if (!bin_bound_ct) {
7569 ln_bin_boundaries = kClumpDefaultLnBinBounds;
7570 bin_bound_ct = 4;
7571 } else {
7572 ln_bin_boundaries = clump_ip->ln_bin_boundaries;
7573 }
7574 }
7575 const char* range_fname = clump_ip->range_fname;
7576 const uint32_t sp2_col = flags & kfClumpColSp2;
7577 const uint32_t ranges_col = !!range_fname;
7578 const uint32_t bounds_col = (flags & kfClumpColBounds) || ((flags & kfClumpColMaybeBounds) && ranges_col);
7579 const double ln_p1 = clump_ip->ln_p1;
7580 const double ln_p2 = (sp2_col || bounds_col || ranges_col)? clump_ip->ln_p2 : -DBL_MAX;
7581 double load_ln_pthresh = MAXV(ln_p1, ln_p2);
7582 if (bin_bound_ct && (load_ln_pthresh < ln_bin_boundaries[bin_bound_ct - 1])) {
7583 load_ln_pthresh = ln_bin_boundaries[bin_bound_ct - 1];
7584 }
7585 ClumpEntry** clump_entries = nullptr;
7586 uintptr_t* nonsig_arr = nullptr;
7587 uint32_t allow_overlap = (flags / kfClumpAllowOverlap) & 1;
7588 if ((flags & (kfClumpColTotal | kfClumpColBins | kfClumpColSp2)) || bounds_col || range_fname) {
7589 if (unlikely(BIGSTACK_ALLOC_X(ClumpEntry*, raw_allele_ct + 1, &clump_entries))) {
7590 goto ClumpReports_ret_NOMEM;
7591 }
7592 ZeroPtrArr(raw_allele_ct, clump_entries);
7593 const uint32_t nonsig_needed = ((flags & (kfClumpColTotal | kfClumpColBins)) != 0) && (load_ln_pthresh < 0.0);
7594 if (nonsig_needed) {
7595 if (unlikely(bigstack_calloc_w(raw_allele_ct, &nonsig_arr))) {
7596 goto ClumpReports_ret_NOMEM;
7597 }
7598 }
7599 } else if (allow_overlap) {
7600 allow_overlap = 0;
7601 logputs("Note: --clump-allow-overlap has no effect when --clump 'total', 'bins', and\n'sp2' column-sets are all absent.\n");
7602 }
7603
7604 uint32_t* variant_id_htable;
7605 uint32_t variant_id_htable_size;
7606 reterr = AllocAndPopulateIdHtableMt(variant_include, variant_ids, variant_ct, bigstack_left() / 2, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr);
7607 if (unlikely(reterr)) {
7608 goto ClumpReports_ret_1;
7609 }
7610
7611 const uint32_t search_a1 = force_a1 || (allele_idx_offsets && (!(flags & kfClumpNoA1)));
7612 const uint32_t search_test = !(flags & kfClumpNoTest);
7613 const char* col_search_order[4];
7614 col_search_order[0] = clump_ip->id_field? clump_ip->id_field : "ID\0SNP\0";
7615 col_search_order[1] = search_a1? (clump_ip->a1_field? clump_ip->a1_field : "A1\0") : "";
7616 col_search_order[2] = search_test? (clump_ip->test_field? clump_ip->test_field : "TEST\0") : "";
7617 const uint32_t input_log10 = flags & kfClumpInputLog10;
7618 col_search_order[3] = clump_ip->p_field? clump_ip->p_field : (input_log10? "LOG10_P\0NEG_LOG10_P\0P\0" : "P\0");
7619 const char* test_name_flattened = clump_ip->test_name? clump_ip->test_name : "ADD\0";
7620 const uint32_t save_all_fidxs = ((file_ct > 1) || force_a1) && sp2_col;
7621
7622 LlStr* missing_variant_ids = nullptr;
7623 LlStr* missing_variant_allele_pairs = nullptr;
7624 uintptr_t missing_variant_id_ct = 0;
7625 uintptr_t missing_variant_id_max_slen = 0;
7626 uintptr_t missing_variant_allele_pair_ct = 0;
7627 uintptr_t missing_variant_allele_pair_max_slen = 0;
7628 // A1 allele normally doesn't matter for biallelic variants, so we default
7629 // to treating it as always-REF (may as well avoid a few +1s in the code).
7630 unsigned char* tmp_alloc_base = nullptr;
7631 unsigned char* tmp_alloc_end = bigstack_end_mark2;
7632 const uint32_t two_minus_force_a1 = 2 - force_a1;
7633 uint32_t cur_allele_ct = 2;
7634 uint32_t biallelic_forced_a1_alt = 0;
7635 for (uint32_t file_idx1 = file_ct; file_idx1; --file_idx1) {
7636 if (file_idx1 == 1) {
7637 fname_iter = clump_ip->fnames_flattened;
7638 } else {
7639 fname_iter = &(fname_iter[-3]);
7640 while (*fname_iter) {
7641 --fname_iter;
7642 }
7643 ++fname_iter;
7644 }
7645 if (file_idx1 == file_ct) {
7646 reterr = SizeAndInitTextStream(fname_iter, bigstack_left() / 8, MAXV(1, max_thread_ct - 1), &txs);
7647 tmp_alloc_base = g_bigstack_base;
7648 } else {
7649 reterr = TextRetarget(fname_iter, &txs);
7650 }
7651 if (unlikely(reterr)) {
7652 goto ClumpReports_ret_TSTREAM_FAIL;
7653 }
7654
7655 line_idx = 0;
7656 const char* header_start;
7657 do {
7658 ++line_idx;
7659 header_start = TextGet(&txs);
7660 if (unlikely(!header_start)) {
7661 reterr = TextStreamRawErrcode(&txs);
7662 if (reterr == kPglRetEof) {
7663 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", fname_iter);
7664 goto ClumpReports_ret_MALFORMED_INPUT_WW;
7665 }
7666 goto ClumpReports_ret_TSTREAM_FAIL;
7667 }
7668 } while (strequal_k_unsafe(header_start, "##"));
7669 if (*header_start == '#') {
7670 ++header_start;
7671 }
7672
7673 // [0] = ID
7674 // [1] = A1
7675 // [2] = TEST
7676 // [3] = P
7677 uint32_t col_skips[4];
7678 uint32_t col_types[4];
7679 uint32_t relevant_col_ct;
7680 uint32_t found_type_bitset;
7681 reterr = SearchHeaderLine(header_start, col_search_order, "--clump", 4, &relevant_col_ct, &found_type_bitset, col_skips, col_types);
7682 if (unlikely(reterr)) {
7683 goto ClumpReports_ret_1;
7684 }
7685 if (unlikely((found_type_bitset & 0x9) != 0x9)) {
7686 logerrputs("Error: --clump requires ID and P columns.\n");
7687 goto ClumpReports_ret_INCONSISTENT_INPUT;
7688 }
7689 if (unlikely(force_a1 && (!(found_type_bitset & 0x2)))) {
7690 snprintf(g_logbuf, kLogbufSize, "Error: --clump-force-a1 was specified, but there is no A1 column in %s.\n", fname_iter);
7691 goto ClumpReports_ret_INCONSISTENT_INPUT_WW;
7692 }
7693
7694 while (1) {
7695 ++line_idx;
7696 const char* line_start = TextGet(&txs);
7697 if (!line_start) {
7698 if (likely(!TextStreamErrcode2(&txs, &reterr))) {
7699 break;
7700 }
7701 goto ClumpReports_ret_TSTREAM_FAIL;
7702 }
7703 const char* token_ptrs[4];
7704 uint32_t token_slens[4];
7705 if (unlikely(!TokenLexK0(line_start, col_types, col_skips, relevant_col_ct, token_ptrs, token_slens))) {
7706 goto ClumpReports_ret_MISSING_TOKENS;
7707 }
7708 if (found_type_bitset & 0x4) {
7709 if (!InMultistr(test_name_flattened, token_ptrs[2], token_slens[2])) {
7710 continue;
7711 }
7712 }
7713 const char* pval_str = token_ptrs[3];
7714 double ln_pval;
7715 if (!input_log10) {
7716 if (!ScantokLn(pval_str, &ln_pval)) {
7717 uint32_t cur_slen;
7718 ClumpReports_alphabetic_pval:
7719 cur_slen = token_slens[3];
7720 if (IsNanStr(pval_str, cur_slen)) {
7721 continue;
7722 }
7723 if (likely(strequal_k(pval_str, "INF", cur_slen) ||
7724 (input_log10 && strequal_k(pval_str, "inf", cur_slen)))) {
7725 // PLINK 1.x underflow
7726 ln_pval = kLnNormalMin;
7727 } else {
7728 goto ClumpReports_ret_INVALID_PVAL;
7729 }
7730 }
7731 } else {
7732 double neglog10_pval;
7733 if (!ScantokDouble(pval_str, &neglog10_pval)) {
7734 goto ClumpReports_alphabetic_pval;
7735 }
7736 ln_pval = neglog10_pval * (-kLn10);
7737 if (unlikely(ln_pval > 0.0)) {
7738 goto ClumpReports_ret_INVALID_PVAL;
7739 }
7740 }
7741 const char* variant_id = token_ptrs[0];
7742 const uint32_t variant_id_slen = token_slens[0];
7743 const uint32_t variant_uidx = VariantIdDupflagHtableFind(token_ptrs[0], variant_ids, variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen);
7744 if (variant_uidx & 0x80000000U) {
7745 if (unlikely(variant_uidx != UINT32_MAX)) {
7746 snprintf(g_logbuf, kLogbufSize, "Error: --clump variant ID '%s' appears multiple times in main dataset.\n", variant_ids[variant_uidx & 0x7fffffff]);
7747 goto ClumpReports_ret_INCONSISTENT_INPUT_WW;
7748 }
7749 if (ln_pval <= ln_p1) {
7750 if (unlikely(PtrWSubCk(tmp_alloc_base, sizeof(LlStr) + RoundUpPow2(variant_id_slen + 1, sizeof(intptr_t)), &tmp_alloc_end))) {
7751 goto ClumpReports_ret_NOMEM;
7752 }
7753 LlStr* new_entry = R_CAST(LlStr*, tmp_alloc_end);
7754 new_entry->next = missing_variant_ids;
7755 memcpyx(new_entry->str, variant_id, variant_id_slen, '\0');
7756 missing_variant_ids = new_entry;
7757 ++missing_variant_id_ct;
7758 if (variant_id_slen > missing_variant_id_max_slen) {
7759 missing_variant_id_max_slen = variant_id_slen;
7760 }
7761 }
7762 continue;
7763 }
7764 uintptr_t allele_idx_offset_base = variant_uidx * 2;
7765 if (allele_idx_offsets) {
7766 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
7767 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
7768 }
7769 uint32_t aidx = 0;
7770 if (cur_allele_ct > two_minus_force_a1) {
7771 if (unlikely(!(found_type_bitset & 0x2))) {
7772 snprintf(g_logbuf, kLogbufSize, "Error: Variant ID on line %" PRIuPTR " of %s is multiallelic, but there is no A1 column.\n", line_idx, fname_iter);
7773 goto ClumpReports_ret_INCONSISTENT_INPUT_WW;
7774 }
7775 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
7776 const char* allele_code = token_ptrs[1];
7777 const uint32_t allele_slen = token_slens[1];
7778 for (; aidx != cur_allele_ct; ++aidx) {
7779 if (strequal_unsafe(cur_alleles[aidx], allele_code, allele_slen)) {
7780 break;
7781 }
7782 }
7783 if (aidx == cur_allele_ct) {
7784 if (ln_pval <= ln_p1) {
7785 const uint32_t variant_allele_pair_slen = variant_id_slen + allele_slen + 1;
7786 if (unlikely(PtrWSubCk(tmp_alloc_base, sizeof(LlStr) + RoundUpPow2(variant_allele_pair_slen + 1, sizeof(intptr_t)), &tmp_alloc_end))) {
7787 goto ClumpReports_ret_NOMEM;
7788 }
7789 LlStr* new_entry = R_CAST(LlStr*, tmp_alloc_end);
7790 new_entry->next = missing_variant_allele_pairs;
7791 char* write_iter = memcpyax(new_entry->str, variant_id, variant_id_slen, '\t');
7792 memcpyx(write_iter, allele_code, allele_slen, '\0');
7793 missing_variant_allele_pairs = new_entry;
7794 ++missing_variant_allele_pair_ct;
7795 if (variant_allele_pair_slen > missing_variant_allele_pair_max_slen) {
7796 missing_variant_allele_pair_max_slen = variant_allele_pair_slen;
7797 }
7798 }
7799 continue;
7800 }
7801 if (cur_allele_ct == 2) {
7802 biallelic_forced_a1_alt = aidx;
7803 aidx = 0;
7804 }
7805 }
7806 const uintptr_t allele_idx = allele_idx_offset_base + aidx;
7807 if (ln_pval > load_ln_pthresh) {
7808 if (unlikely(ln_pval > 0.0)) {
7809 snprintf(g_logbuf, kLogbufSize, "Error: p-value > 1 on line %" PRIuPTR " of %s.\n", line_idx, fname_iter);
7810 goto ClumpReports_ret_MALFORMED_INPUT_WW;
7811 }
7812 if (nonsig_arr && ((!bin_bound_ct) || (ln_pval > ln_bin_boundaries[bin_bound_ct - 1]))) {
7813 nonsig_arr[allele_idx] += 1;
7814 // Still need to determine which index-variant this belongs to.
7815 SetBit(allele_idx, observed_alleles);
7816 SetBit(variant_uidx, observed_variants);
7817 }
7818 continue;
7819 }
7820 const uint32_t file_idx1_x2 = (file_idx1 << 1) + biallelic_forced_a1_alt;
7821 // >= rather than >, to break ties in favor of file_idx1 == 1
7822 if (best_ln_pvals[allele_idx] >= ln_pval) {
7823 best_ln_pvals[allele_idx] = ln_pval;
7824 if (best_fidx_x2s) {
7825 best_fidx_x2s[allele_idx] = file_idx1_x2;
7826 }
7827 }
7828 SetBit(allele_idx, observed_alleles);
7829 SetBit(variant_uidx, observed_variants); // could defer this?
7830 if (clump_entries) {
7831 if (unlikely(PtrWSubCk(tmp_alloc_base, RoundUpPow2(sizeof(ClumpEntry), sizeof(intptr_t)), &tmp_alloc_end))) {
7832 goto ClumpReports_ret_NOMEM;
7833 }
7834 uint32_t pval_bin_x2 = (ln_pval > ln_p2);
7835 if (bin_bound_ct) {
7836 pval_bin_x2 |= LowerBoundNonemptyD(ln_bin_boundaries, bin_bound_ct, ln_pval) << 1;
7837 }
7838 ClumpEntry* new_entry = R_CAST(ClumpEntry*, tmp_alloc_end);
7839 new_entry->next = clump_entries[allele_idx];
7840 new_entry->pval_bin_x2 = pval_bin_x2;
7841 new_entry->file_idx1_x2 = file_idx1_x2;
7842 clump_entries[allele_idx] = new_entry;
7843 }
7844 }
7845 }
7846 if (unlikely(CleanupTextStream2(fname_iter, &txs, &reterr))) {
7847 goto ClumpReports_ret_1;
7848 }
7849
7850 BigstackEndSet(tmp_alloc_end);
7851
7852 FillCumulativePopcountsW(observed_alleles, raw_allele_ctl, observed_alleles_cumulative_popcounts_w);
7853 const uintptr_t observed_allele_ct = observed_alleles_cumulative_popcounts_w[raw_allele_ctl - 1] + PopcountWord(observed_alleles[raw_allele_ctl - 1]);
7854 if ((raw_allele_ct % kBitsPerWord) == 0) {
7855 observed_alleles_cumulative_popcounts_w[raw_allele_ctl] = observed_allele_ct;
7856 }
7857 const uint32_t output_zst = (flags / kfClumpZs) & 1;
7858 // Now we have efficient (variant_uidx, aidx) -> oaidx lookup.
7859 // Free some memory by compacting the information in best_ln_pvals, etc. to
7860 // exclude unused (variant_uidx, aidx) slots.
7861 BigstackReset(bigstack_mark2);
7862 unsigned char** clump_entry_varints = nullptr;
7863 {
7864 if (best_fidx_x2s) {
7865 const uint32_t* best_fidx_x2s_dying = best_fidx_x2s;
7866 best_fidx_x2s = S_CAST(uint32_t*, bigstack_alloc_raw_rd(observed_allele_ct * sizeof(int32_t)));
7867 uintptr_t allele_idx_base = 0;
7868 uintptr_t cur_bits = observed_alleles[0];
7869 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
7870 const uintptr_t allele_idx = BitIter1(observed_alleles, &allele_idx_base, &cur_bits);
7871 best_fidx_x2s[oaidx] = best_fidx_x2s_dying[allele_idx];
7872 }
7873 }
7874
7875 if (clump_entries) {
7876 ClumpEntry** clump_entries_dying = clump_entries;
7877 clump_entries = S_CAST(ClumpEntry**, bigstack_alloc_raw_rd((observed_allele_ct + 1) * sizeof(intptr_t)));
7878 uintptr_t allele_idx_base = 0;
7879 uintptr_t cur_bits = observed_alleles[0];
7880 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
7881 const uintptr_t allele_idx = BitIter1(observed_alleles, &allele_idx_base, &cur_bits);
7882 clump_entries[oaidx] = clump_entries_dying[allele_idx];
7883 }
7884
7885 if (nonsig_arr) {
7886 const uintptr_t* nonsig_arr_dying = nonsig_arr;
7887 nonsig_arr = S_CAST(uintptr_t*, bigstack_alloc_raw_rd(observed_allele_ct * sizeof(intptr_t)));
7888 allele_idx_base = 0;
7889 cur_bits = observed_alleles[0];
7890 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
7891 const uintptr_t allele_idx = BitIter1(observed_alleles, &allele_idx_base, &cur_bits);
7892 nonsig_arr[oaidx] = nonsig_arr_dying[allele_idx];
7893 }
7894 }
7895 }
7896
7897 if (missing_variant_ids) {
7898 // natural-sort, deduplicate, and write
7899 bigstack_mark2 = g_bigstack_base;
7900
7901 const char** strptr_arr;
7902 if (unlikely(bigstack_alloc_kcp(missing_variant_id_ct, &strptr_arr))) {
7903 goto ClumpReports_ret_NOMEM;
7904 }
7905 for (uintptr_t ulii = 0; ulii != missing_variant_id_ct; ++ulii) {
7906 strptr_arr[ulii] = missing_variant_ids->str;
7907 missing_variant_ids = missing_variant_ids->next;
7908 }
7909 assert(missing_variant_ids == nullptr);
7910 OutnameZstSet(".clumps.missing_id", output_zst, outname_end);
7911 uintptr_t nwrite;
7912 reterr = NsortDedupAndWrite(outname, missing_variant_id_ct, missing_variant_id_max_slen, output_zst, max_thread_ct, strptr_arr, &nwrite);
7913 if (unlikely(reterr)) {
7914 goto ClumpReports_ret_1;
7915 }
7916 logerrprintfww("Warning: %" PRIuPTR " top variant ID%s in --clump file%s missing from main dataset. ID%s written to %s .\n", nwrite, (nwrite == 1)? "" : "s", (file_ct == 1)? "" : "s", (nwrite == 1)? "" : "s", outname);
7917 BigstackReset(bigstack_mark2);
7918 }
7919
7920 if (missing_variant_allele_pairs) {
7921 bigstack_mark2 = g_bigstack_base;
7922
7923 const char** strptr_arr;
7924 if (unlikely(bigstack_alloc_kcp(missing_variant_allele_pair_ct, &strptr_arr))) {
7925 goto ClumpReports_ret_NOMEM;
7926 }
7927 for (uintptr_t ulii = 0; ulii != missing_variant_allele_pair_ct; ++ulii) {
7928 strptr_arr[ulii] = missing_variant_allele_pairs->str;
7929 missing_variant_allele_pairs = missing_variant_allele_pairs->next;
7930 }
7931 assert(missing_variant_allele_pairs == nullptr);
7932 OutnameZstSet(".clumps.missing_allele", output_zst, outname_end);
7933 uintptr_t nwrite;
7934 reterr = NsortDedupAndWrite(outname, missing_variant_allele_pair_ct, missing_variant_allele_pair_max_slen, output_zst, max_thread_ct, strptr_arr, &nwrite);
7935 if (unlikely(reterr)) {
7936 goto ClumpReports_ret_1;
7937 }
7938 logerrprintfww("Warning: %" PRIuPTR " top (variant ID, A1 allele) pair%s in --clump file%s missing from main dataset due to allele rather than variant ID. (Variant ID, A1 allele) pair%s written to %s .\n", nwrite, (nwrite == 1)? "" : "s", (file_ct == 1)? "" : "s", (nwrite == 1)? "" : "s", outname);
7939 BigstackReset(bigstack_mark2);
7940 }
7941
7942 if (clump_entries) {
7943 // Now save pval_bin_x2 values, as well as fidxs if necessary, as
7944 // varints.
7945 unsigned char* varint_write_iter = g_bigstack_base;
7946 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
7947 ClumpEntry* ll_iter = clump_entries[oaidx];
7948 // assign to clump_entries instead of clump_entry_varints, so we
7949 // don't break strict-aliasing rule
7950 clump_entries[oaidx] = R_CAST(ClumpEntry*, varint_write_iter);
7951 while (ll_iter) {
7952 varint_write_iter = Vint32Append(ll_iter->pval_bin_x2, varint_write_iter);
7953 if (save_all_fidxs) {
7954 varint_write_iter = Vint32Append(ll_iter->file_idx1_x2, varint_write_iter);
7955 }
7956 if (unlikely(varint_write_iter > tmp_alloc_end)) {
7957 goto ClumpReports_ret_NOMEM;
7958 }
7959 ll_iter = ll_iter->next;
7960 }
7961 }
7962 clump_entry_varints = R_CAST(unsigned char**, clump_entries);
7963 clump_entry_varints[observed_allele_ct] = varint_write_iter;
7964 if (unlikely(BigstackBaseSetChecked(varint_write_iter))) {
7965 goto ClumpReports_ret_NOMEM;
7966 }
7967 // defensive
7968 clump_entries = nullptr;
7969 }
7970 }
7971 // We're done processing all the linked lists allocated next to
7972 // g_bigstack_end.
7973 BigstackEndReset(bigstack_end_mark2);
7974 // Create sorted list of index-variant candidates, then free best_ln_pvals.
7975 uintptr_t* icandidate_vbitvec_fill;
7976 uintptr_t* icandidate_abitvec_fill;
7977 ClumpPval* index_candidates;
7978 if (unlikely(bigstack_calloc_w(raw_variant_ctl, &icandidate_vbitvec_fill) ||
7979 bigstack_calloc_w(raw_allele_ctl, &icandidate_abitvec_fill) ||
7980 BIGSTACK_ALLOC_X(ClumpPval, observed_allele_ct, &index_candidates))) {
7981 goto ClumpReports_ret_NOMEM;
7982 }
7983 uint32_t index_candidate_ct;
7984 {
7985 uintptr_t index_candidate_ct_w = 0;
7986 for (uint32_t variant_uidx = 0; ; ++variant_uidx) {
7987 variant_uidx = AdvBoundedTo1Bit(observed_variants, variant_uidx, raw_variant_ct);
7988 if (variant_uidx == raw_variant_ct) {
7989 break;
7990 }
7991 uintptr_t allele_idx_offset_base = variant_uidx * 2;
7992 if (allele_idx_offsets) {
7993 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
7994 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
7995 }
7996 const uintptr_t allele_idx_stop = allele_idx_offset_base + cur_allele_ct;
7997 for (uintptr_t allele_idx = allele_idx_offset_base; allele_idx != allele_idx_stop; ++allele_idx) {
7998 if (!IsSet(observed_alleles, allele_idx)) {
7999 continue;
8000 }
8001 const double cur_ln_pval = best_ln_pvals[allele_idx];
8002 if (cur_ln_pval <= ln_p1) {
8003 index_candidates[index_candidate_ct_w].ln_pval = cur_ln_pval;
8004 index_candidates[index_candidate_ct_w].allele_idx = allele_idx;
8005 ++index_candidate_ct_w;
8006 SetBit(variant_uidx, icandidate_vbitvec_fill);
8007 SetBit(allele_idx, icandidate_abitvec_fill);
8008 }
8009 }
8010 }
8011 if (!index_candidate_ct_w) {
8012 logerrputs("Warning: No significant --clump results. Skipping.\n");
8013 goto ClumpReports_ret_1;
8014 }
8015 #ifdef __LP64__
8016 if (unlikely(index_candidate_ct_w >= 0xffffffffU)) {
8017 logerrputs("Error: --clump does not support >= 2^32 - 1 index-variant candidates.\n");
8018 goto ClumpReports_ret_NOT_YET_SUPPORTED;
8019 }
8020 #endif
8021 index_candidate_ct = index_candidate_ct_w;
8022 BigstackShrinkTop(index_candidates, sizeof(ClumpPval) * index_candidate_ct);
8023 // About to make a bunch of cacheline-aligned allocations at end of
8024 // bigstack.
8025 // (This is awkward, should be a single function call...)
8026 BigstackEndReset(bigstack_end_mark);
8027 bigstack_end_clalign();
8028 STD_SORT_PAR_UNSEQ(index_candidate_ct, ClumpPvalCmp, index_candidates);
8029 }
8030 const uintptr_t* icandidate_vbitvec = icandidate_vbitvec_fill;
8031 const uintptr_t* icandidate_abitvec = icandidate_abitvec_fill;
8032 // Main algorithm:
8033 // - Identify independent "islands", induced by the --clump-kb setting.
8034 // - Process one island (or island-group, if the island is inefficiently
8035 // small) at a time.
8036 // - Usually, all we need to determine is: for each remaining (variant
8037 // ID, aidx) pair, what clump was it assigned to? (clump-index is
8038 // defined by index_candidates[] position. Some clump-indexes are
8039 // skipped.)
8040 // - If --clump-allow-overlap is in effect, this doesn't work since
8041 // non-index variants can belong to multiple clumps. We spill a
8042 // temporary file to disk tracking, for each clump, which (variant ID,
8043 // aidx) pairs are a member. This file could be very big, so we use
8044 // varints and delta encoding to reduce waste.
8045 // (In principle, seekable zstd should be useful here as well, but I
8046 // won't investigate that unless/until I decide to use seekable zstd in
8047 // other applications.)
8048 // - After we're done processing all islands, we have the information
8049 // needed to write the final p-value sorted report.
8050
8051 // Create an icandidate_idx -> index_candidates lookup table, to support
8052 // island-based processing.
8053 // "_destructive" because the main loop modifies this array in-place.
8054 uint32_t* icandidate_idx_to_rank0_destructive;
8055 {
8056 uint32_t* icandidate_popcounts;
8057 if (unlikely(bigstack_alloc_u32(index_candidate_ct, &icandidate_idx_to_rank0_destructive) ||
8058 bigstack_alloc_u32(raw_allele_ctl, &icandidate_popcounts))) {
8059 goto ClumpReports_ret_NOMEM;
8060 }
8061 FillCumulativePopcounts(icandidate_abitvec, raw_allele_ctl, icandidate_popcounts);
8062 for (uint32_t rank0 = 0; rank0 != index_candidate_ct; ++rank0) {
8063 const uintptr_t allele_idx = index_candidates[rank0].allele_idx;
8064 const uint32_t icandidate_idx = RawToSubsettedPos(icandidate_abitvec, icandidate_popcounts, allele_idx);
8065 icandidate_idx_to_rank0_destructive[icandidate_idx] = rank0;
8066 }
8067 BigstackReset(icandidate_popcounts);
8068 }
8069
8070 uint32_t* oallele_idx_to_clump_idx = nullptr;
8071 uint64_t* clump_idx_to_overlap_fpos_and_len = nullptr;
8072 if (!allow_overlap) {
8073 if (unlikely(bigstack_alloc_u32(observed_allele_ct, &oallele_idx_to_clump_idx))) {
8074 goto ClumpReports_ret_NOMEM;
8075 }
8076 SetAllU32Arr(observed_allele_ct, oallele_idx_to_clump_idx);
8077 } else {
8078 snprintf(outname_end, kMaxOutfnameExtBlen, ".clumps.tmp");
8079 if (unlikely(fopen_checked(outname, FOPEN_WB, &clump_overlap_tmp))) {
8080 goto ClumpReports_ret_OPEN_FAIL;
8081 }
8082 // make starting fpos > 0, so we know fpos == 0 marks no clump
8083 if (unlikely(putc_unlocked(0, clump_overlap_tmp) == EOF)) {
8084 goto ClumpReports_ret_WRITE_FAIL;
8085 }
8086 if (unlikely(bigstack_calloc_u64(index_candidate_ct * (2 * k1LU), &clump_idx_to_overlap_fpos_and_len))) {
8087 goto ClumpReports_ret_NOMEM;
8088 }
8089 }
8090
8091 // We switch between two parallelization strategies, depending on
8092 // available memory.
8093 // 1. In the best case, we can load the entire set of (variant ID, aidx)
8094 // pairs on at least one island into memory, and encode them in an
8095 // LD-computation-friendly form. In that case, we parallelize that
8096 // operation first, and then iterate through the on-island index
8097 // candidates.
8098 // 2. Otherwise, the main thread reads and unpacks the index (variant,
8099 // aidx), then reads an affordable number of other variants at a time
8100 // for the worker threads to unpack / r^2-compute with.
8101 //
8102 // We choose the worker thread count to ensure at least strategy #2 works.
8103 const uintptr_t observed_allele_ctl = BitCtToWordCt(observed_allele_ct);
8104 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
8105 const uint32_t founder_ctv = BitCtToVecCt(founder_ct);
8106 const uint32_t founder_ctv2 = NypCtToVecCt(founder_ct);
8107 const uint32_t founder_ctaw = founder_ctv * kWordsPerVec;
8108 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
8109 const uint32_t founder_male_ct = PopcountWordsIntersect(founder_info, sex_male, raw_sample_ctl);
8110 const uint32_t founder_nonmale_ct = founder_ct - founder_male_ct;
8111 uint32_t founder_nosex_ct = 0;
8112 if (nosex_ct) {
8113 founder_nosex_ct = founder_ct - PopcountWordsIntersect(founder_info, sex_nm, raw_sample_ctl);
8114 }
8115 uintptr_t* candidate_oabitvec;
8116 uint32_t* founder_info_cumulative_popcounts;
8117 if (unlikely(bigstack_alloc_w(observed_allele_ctl, &candidate_oabitvec) ||
8118 bigstack_alloc_u32(raw_sample_ctl, &founder_info_cumulative_popcounts))) {
8119 goto ClumpReports_ret_NOMEM;
8120 }
8121 SetAllBits(observed_allele_ct, candidate_oabitvec);
8122 uintptr_t* icandidate_oabitvec = candidate_oabitvec;
8123 if (allow_overlap) {
8124 if (unlikely(bigstack_alloc_w(observed_allele_ctl, &icandidate_oabitvec))) {
8125 goto ClumpReports_ret_NOMEM;
8126 }
8127 SetAllBits(observed_allele_ct, icandidate_oabitvec);
8128 }
8129 FillCumulativePopcounts(founder_info, raw_sample_ctl, founder_info_cumulative_popcounts);
8130 uint32_t x_code;
8131 if (XymtExists(cip, kChrOffsetX, &x_code)) {
8132 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code];
8133 const uint32_t x_start = cip->chr_fo_vidx_start[chr_fo_idx];
8134 const uint32_t x_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
8135 if (AllBitsAreZero(icandidate_vbitvec, x_start, x_end)) {
8136 x_code = UINT32_MAXM1;
8137 }
8138 }
8139 // If founder_nonmale_ct == 0 or founder_male_ct == 0, main loop sets
8140 // is_x to 0 and is_haploid appropriately.
8141 const uint32_t x_exists = (x_code < UINT32_MAXM1) && founder_nonmale_ct && founder_male_ct;
8142 uint32_t y_code;
8143 if (XymtExists(cip, kChrOffsetY, &y_code)) {
8144 const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[y_code];
8145 const uint32_t y_start = cip->chr_fo_vidx_start[chr_fo_idx];
8146 const uint32_t y_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
8147 if (AllBitsAreZero(icandidate_vbitvec, y_start, y_end)) {
8148 y_code = UINT32_MAXM1;
8149 } else if (unlikely(founder_male_ct + founder_nosex_ct == 0)) {
8150 // Rather not worry about this case.
8151 logerrputs("Error: --clump: chrY index variant(s) are present, but all founders in the main\ndataset are females.\n");
8152 goto ClumpReports_ret_INCONSISTENT_INPUT;
8153 }
8154 }
8155 // If founder_nonfemale_ct == founder_ct, we can just treat as is_y=0,
8156 // is_haploid=1.
8157 const uint32_t y_exists = (y_code < UINT32_MAXM1) && (founder_male_ct + founder_nosex_ct != founder_ct);
8158 const uintptr_t bitvec_byte_ct = BitCtToVecCt(founder_ct) * kBytesPerVec;
8159 uintptr_t* founder_male_collapsed = nullptr;
8160 Dosage* male_dosage_invmask = nullptr;
8161 uintptr_t* founder_nonmale_collapsed = nullptr;
8162 Dosage* nonmale_dosage_invmask = nullptr;
8163 if (x_exists) {
8164 const uint32_t founder_ctad = RoundUpPow2(founder_ct, kDosagePerVec);
8165 if (unlikely(bigstack_alloc_w(founder_ctl, &founder_male_collapsed) ||
8166 bigstack_alloc_dosage(founder_ctad, &male_dosage_invmask) ||
8167 bigstack_alloc_w(founder_ctaw, &founder_nonmale_collapsed) ||
8168 bigstack_alloc_dosage(founder_ctad, &nonmale_dosage_invmask))) {
8169 goto ClumpReports_ret_NOMEM;
8170 }
8171 CopyBitarrSubset(sex_male, founder_info, founder_ct, founder_male_collapsed);
8172 BitvecInvertCopy(founder_male_collapsed, founder_ctl, founder_nonmale_collapsed);
8173 ZeroTrailingBits(founder_ct, founder_nonmale_collapsed);
8174 // potentially needed for correct founder_female_collapsed_interleaved
8175 // initialization
8176 ZeroTrailingWords(founder_ctl, founder_nonmale_collapsed);
8177 Expand1bitTo16(founder_male_collapsed, founder_ctad, 0xffff, male_dosage_invmask);
8178 Expand1bitTo16(founder_nonmale_collapsed, founder_ctad, 0xffff, nonmale_dosage_invmask);
8179 }
8180 uintptr_t* founder_female_collapsed = nullptr;
8181 uintptr_t* founder_female_collapsed_interleaved = nullptr;
8182 if (y_exists) {
8183 if (founder_nonmale_collapsed && (!nosex_ct)) {
8184 founder_female_collapsed = founder_nonmale_collapsed;
8185 } else {
8186 uintptr_t* founder_female_tmp;
8187 if (unlikely(bigstack_alloc_w(founder_ctaw, &founder_female_collapsed) ||
8188 bigstack_alloc_w(raw_sample_ctl, &founder_female_tmp))) {
8189 goto ClumpReports_ret_NOMEM;
8190 }
8191 BitvecInvmaskCopy(sex_nm, sex_male, raw_sample_ctl, founder_female_tmp);
8192 CopyBitarrSubset(founder_female_tmp, founder_info, founder_ct, founder_female_collapsed);
8193 ZeroTrailingWords(founder_ctl, founder_female_collapsed);
8194 BigstackReset(founder_female_tmp);
8195 }
8196 if (unlikely(bigstack_alloc_w(founder_ctaw, &founder_female_collapsed_interleaved))) {
8197 goto ClumpReports_ret_NOMEM;
8198 }
8199 FillInterleavedMaskVec(founder_female_collapsed, founder_ctv, founder_female_collapsed_interleaved);
8200 }
8201 const uint32_t check_dosage = (pgfip->gflags / kfPgenGlobalDosagePresent) & 1;
8202 uintptr_t dosagevec_byte_ct = 0;
8203 if (check_dosage) {
8204 dosagevec_byte_ct = DivUp(founder_ct, kDosagePerVec) * kBytesPerVec;
8205 }
8206
8207 uint32_t calc_thread_ct = MAXV(1, max_thread_ct - 1);
8208 // no big deal if these are slightly overallocated
8209 if (unlikely(BIGSTACK_ALLOC_X(PgenReader*, calc_thread_ct, &ctx.pgr_ptrs) ||
8210 bigstack_alloc_w(calc_thread_ct + 2, &(ctx.a[0].oaidx_starts)) ||
8211 bigstack_alloc_w(calc_thread_ct + 2, &(ctx.a[1].oaidx_starts)) ||
8212 bigstack_alloc_wp(calc_thread_ct + 1, &(ctx.ld_idx_found)))) {
8213 goto ClumpReports_ret_NOMEM;
8214 }
8215 ctx.raregeno_bufs = nullptr;
8216 ctx.difflist_sample_id_bufs = nullptr;
8217 ctx.chrx_workspaces = nullptr;
8218 const uint32_t phased_r2 = !(flags & kfClumpUnphased);
8219 if (!phased_r2) {
8220 if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.raregeno_bufs) ||
8221 bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs))) {
8222 goto ClumpReports_ret_NOMEM;
8223 }
8224 }
8225 if (x_exists) {
8226 if (unlikely(bigstack_alloc_wp(calc_thread_ct + 1, &ctx.chrx_workspaces))) {
8227 goto ClumpReports_ret_NOMEM;
8228 }
8229 }
8230 // Now determine real calc_thread_ct.
8231 // This function's logic is sufficiently different from the usual
8232 // PgfiMultiread use case that we fork PgenMtLoadInit()'s computation here
8233 // instead of modifying that function.
8234
8235 const uint32_t all_haploid = IsSet(cip->haploid_mask, 0);
8236 const uint32_t check_phase = phased_r2 && (!all_haploid) && (pgfip->gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent));
8237 PgenGlobalFlags effective_gflags = pgfip->gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
8238 if (!check_phase) {
8239 effective_gflags &= kfPgenGlobalDosagePresent;
8240 }
8241
8242 if (unlikely(BigstackAllocPgv(founder_ct, 0, effective_gflags, &ctx.pgv_base))) {
8243 goto ClumpReports_ret_NOMEM;
8244 }
8245 const uintptr_t pgv_byte_stride = g_bigstack_base - R_CAST(unsigned char*, ctx.pgv_base.genovec);
8246
8247 uintptr_t unpacked_byte_stride;
8248 if (check_dosage) {
8249 const uintptr_t dosage_trail_byte_ct = LdDosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_r2), x_exists);
8250 unpacked_byte_stride = dosagevec_byte_ct * (1 + phased_r2 + check_phase) + bitvec_byte_ct + dosage_trail_byte_ct;
8251 } else {
8252 unpacked_byte_stride = RoundUpPow2(16, kBytesPerVec) + bitvec_byte_ct * (3 + 2 * check_phase);
8253 #ifndef USE_AVX2
8254 const uint32_t max_simple_difflist_len = founder_ct / 64;
8255 const uintptr_t sparse_req = RoundUpPow2((6 + max_simple_difflist_len) * sizeof(int32_t), kBytesPerVec) + NypCtToVecCt(max_simple_difflist_len) * kBytesPerVec + RoundUpPow2(founder_ctl * (kBytesPerWord + sizeof(int32_t)), kBytesPerVec);
8256 if (sparse_req > unpacked_byte_stride) {
8257 unpacked_byte_stride = sparse_req;
8258 }
8259 #endif
8260 const uintptr_t nondosage_trail_byte_ct = LdNondosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_r2), x_exists);
8261 unpacked_byte_stride += nondosage_trail_byte_ct;
8262 }
8263 const uintptr_t unpacked_byte_stride_cachealign = RoundUpPow2(unpacked_byte_stride, kCacheline);
8264 const uintptr_t pgr_struct_alloc = RoundUpPow2(sizeof(PgenReader), kCacheline);
8265
8266 // Haven't counted PgenReader instance, two unpacked_variants slots, or
8267 // ld_idx_found slots required by main thread yet.
8268
8269 // FillGaussianDArr() uses a minimum per-thread job size of ~4 MiB of
8270 // memory writes. I'm guessing that is also a reasonable unpacked_variants
8271 // shard size to aim for.
8272 const uint32_t min_pgv_per_thread = 1 + 4194303 / pgv_byte_stride;
8273 uintptr_t sparse_alloc = 0;
8274 uint32_t raregeno_word_ct = 0;
8275 uintptr_t chrx_alloc = 0;
8276 if (x_exists) {
8277 const uint32_t larger_half = MAXV(founder_male_ct, founder_nonmale_ct);
8278 chrx_alloc = RoundUpPow2(BitCtToVecCt(larger_half) + larger_half * sizeof(Dosage), kCacheline);
8279 }
8280 {
8281 const uintptr_t min_ld_idx_found_alloc = WordCtToCachelineCt(min_pgv_per_thread + 1) * kCacheline;
8282 const uintptr_t min_u32_alloc = Int32CtToCachelineCt(min_pgv_per_thread) * kCacheline;
8283 const uintptr_t phasepresent_alloc = check_phase * min_u32_alloc;
8284 const uintptr_t dosage_ct_alloc = check_dosage * min_u32_alloc;
8285 const uintptr_t dphase_ct_alloc = dosage_ct_alloc * check_phase;
8286 if (!phased_r2) {
8287 const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
8288 const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec);
8289 const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec);
8290 sparse_alloc = RoundUpPow2((raregeno_vec_ct + difflist_sample_id_vec_ct) * kBytesPerVec, kCacheline);
8291 raregeno_word_ct = raregeno_vec_ct * kWordsPerVec;
8292 }
8293
8294 uintptr_t bytes_avail = bigstack_left();
8295 const uintptr_t more_base_alloc = pgr_struct_alloc + pgr_alloc_cacheline_ct * kCacheline + 2 * unpacked_byte_stride_cachealign + min_ld_idx_found_alloc + phasepresent_alloc + dosage_ct_alloc + dphase_ct_alloc + chrx_alloc;
8296 if (unlikely(bytes_avail < more_base_alloc)) {
8297 goto ClumpReports_ret_NOMEM;
8298 }
8299 bytes_avail -= more_base_alloc;
8300
8301 const uintptr_t per_thread_target_alloc = 2 * min_pgv_per_thread * pgv_byte_stride + unpacked_byte_stride_cachealign + pgr_struct_alloc + pgr_alloc_cacheline_ct * kCacheline + min_ld_idx_found_alloc + sparse_alloc + chrx_alloc;
8302 if (bytes_avail < per_thread_target_alloc * calc_thread_ct) {
8303 calc_thread_ct = bytes_avail / per_thread_target_alloc;
8304 if (unlikely(!calc_thread_ct)) {
8305 goto ClumpReports_ret_NOMEM;
8306 }
8307 }
8308 }
8309 // Ready to initialize the rest of ctx.
8310 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
8311 goto ClumpReports_ret_NOMEM;
8312 }
8313
8314 // Effective end of pgv-buffer allocation, in highmem case.
8315 g_bigstack_base += calc_thread_ct * pgv_byte_stride;
8316
8317 // Make this non-null, because PgrInit() branches on that. However, exact
8318 // value doesn't matter here.
8319 pgfip->block_base = g_bigstack_base;
8320 for (uint32_t tidx = 0; tidx <= calc_thread_ct; ++tidx) {
8321 ctx.pgr_ptrs[tidx] = S_CAST(PgenReader*, bigstack_end_alloc_raw(pgr_struct_alloc));
8322 unsigned char* pgr_alloc = S_CAST(unsigned char*, bigstack_end_alloc_raw(pgr_alloc_cacheline_ct * kCacheline));
8323
8324 // shouldn't be possible for this to fail
8325 PgrInit(nullptr, 0, pgfip, ctx.pgr_ptrs[tidx], pgr_alloc);
8326
8327 if (!phased_r2) {
8328 uintptr_t* raregeno_buf = S_CAST(uintptr_t*, bigstack_end_alloc_raw(sparse_alloc));
8329 ctx.raregeno_bufs[tidx] = raregeno_buf;
8330 ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, &(raregeno_buf[raregeno_word_ct]));
8331 }
8332 if (x_exists) {
8333 ctx.chrx_workspaces[tidx] = S_CAST(uintptr_t*, bigstack_end_alloc_raw(chrx_alloc));
8334 }
8335 }
8336
8337 unsigned char* multiread_base[2];
8338 multiread_base[0] = g_bigstack_base;
8339 multiread_base[1] = nullptr;
8340 // Decide on a maximum value upfront, rather than reconfiguring this for
8341 // each island-group.
8342 uintptr_t multiread_byte_target;
8343 {
8344 // Allow up to 1/8 of remaining workspace, going lower if there's always
8345 // enough memory for a full Vblock (65536 variants).
8346 const uint32_t observed_variant_ct = PopcountWords(observed_variants, raw_variant_ctl);
8347 const uint64_t vblock_based_cacheline_ct_limit = PgfiMultireadGetCachelineReq(observed_variants, pgfip, observed_variant_ct, kPglVblockSize);
8348 const uint64_t proportional_cacheline_ct_limit = bigstack_left() / (8 * kCacheline);
8349 // Stick to lowmem mode if this rule can't even guarantee 1/500th of a
8350 // Vblock.
8351 if (vblock_based_cacheline_ct_limit <= 500 * proportional_cacheline_ct_limit) {
8352 multiread_byte_target = kCacheline * MINV(vblock_based_cacheline_ct_limit, proportional_cacheline_ct_limit);
8353 } else {
8354 // (this value should guarantee lowmem mode is always selected)
8355 multiread_byte_target = (~k0LU) >> 1;
8356 }
8357 }
8358
8359 ctx.observed_variants = observed_variants;
8360 ctx.allele_idx_offsets = allele_idx_offsets;
8361 ctx.variant_last_alidxs = variant_last_alidxs;
8362 ctx.variant_last_alidxs_cumulative_popcounts = variant_last_alidxs_cumulative_popcounts;
8363 ctx.observed_alleles = observed_alleles;
8364 ctx.observed_alleles_cumulative_popcounts_w = observed_alleles_cumulative_popcounts_w;
8365 ctx.founder_info = founder_info;
8366 ctx.founder_info_cumulative_popcounts = founder_info_cumulative_popcounts;
8367 ctx.founder_male_collapsed = founder_male_collapsed;
8368 ctx.male_dosage_invmask = male_dosage_invmask;
8369 ctx.founder_nonmale_collapsed = founder_nonmale_collapsed;
8370 ctx.nonmale_dosage_invmask = nonmale_dosage_invmask;
8371 ctx.founder_female_collapsed = founder_female_collapsed;
8372 ctx.founder_female_collapsed_interleaved = founder_female_collapsed_interleaved;
8373 ctx.founder_ct = founder_ct;
8374 ctx.founder_male_ct = founder_male_ct;
8375 ctx.pgv_byte_stride = pgv_byte_stride;
8376 ctx.bitvec_byte_ct = bitvec_byte_ct;
8377 ctx.dosagevec_byte_ct = dosagevec_byte_ct;
8378 ctx.r2_thresh = clump_ip->r2;
8379 ctx.allow_overlap = allow_overlap;
8380 ctx.candidate_oabitvec = candidate_oabitvec;
8381 ctx.err_info = (~0LLU) << 32;
8382
8383 unsigned char* lowmem_unpacked_variants = &(g_bigstack_end[(2 + calc_thread_ct) * (-S_CAST(intptr_t, unpacked_byte_stride_cachealign))]);
8384 uint32_t* phasepresent_cts = nullptr;
8385 uint32_t* dosage_cts = nullptr;
8386 uint32_t* dphase_cts = nullptr;
8387 uintptr_t* lowmem_ld_idx_found_base;
8388 uintptr_t max_lowmem_nonindex_ct;
8389 {
8390 // In lowmem mode, split remaining memory between
8391 // ctx.lowmem_pgv_base, phasepresent_cts, dosage_cts, dphase_cts, and
8392 // ld_idx_found.
8393 unsigned char* alloc_iter = R_CAST(unsigned char*, ctx.pgv_base.genovec);
8394 const uintptr_t bytes_avail = lowmem_unpacked_variants - alloc_iter;
8395 const uintptr_t u32_field_ct = check_phase + check_dosage + check_dosage * check_phase;
8396 const uintptr_t per_variant_cost = pgv_byte_stride + sizeof(intptr_t) + sizeof(int32_t) * u32_field_ct;
8397 max_lowmem_nonindex_ct = bytes_avail / per_variant_cost;
8398 while (max_lowmem_nonindex_ct * pgv_byte_stride + RoundUpPow2(max_lowmem_nonindex_ct * sizeof(intptr_t), kCacheline) + u32_field_ct * RoundUpPow2(max_lowmem_nonindex_ct * sizeof(int32_t), kCacheline) > bytes_avail) {
8399 // pgv_byte_stride is a positive multiple of kCacheline, and we lose
8400 // less than 4 cachelines to adverse rounding, so this will exit
8401 // quickly enough.
8402 --max_lowmem_nonindex_ct;
8403 }
8404 const uintptr_t pgv_alloc = max_lowmem_nonindex_ct * pgv_byte_stride;
8405 alloc_iter = &(alloc_iter[pgv_alloc]);
8406 const uintptr_t u32_alloc = RoundUpPow2(max_lowmem_nonindex_ct * sizeof(int32_t), kCacheline);
8407 if (check_phase) {
8408 phasepresent_cts = R_CAST(uint32_t*, alloc_iter);
8409 alloc_iter = &(alloc_iter[u32_alloc]);
8410 }
8411 if (check_dosage) {
8412 dosage_cts = R_CAST(uint32_t*, alloc_iter);
8413 alloc_iter = &(alloc_iter[u32_alloc]);
8414 if (check_phase) {
8415 dphase_cts = R_CAST(uint32_t*, alloc_iter);
8416 alloc_iter = &(alloc_iter[u32_alloc]);
8417 }
8418 }
8419 lowmem_ld_idx_found_base = R_CAST(uintptr_t*, alloc_iter);
8420 }
8421 ctx.phasepresent_cts = phasepresent_cts;
8422 ctx.dosage_cts = dosage_cts;
8423 ctx.dphase_cts = dphase_cts;
8424
8425 SetThreadFuncAndData(ClumpThread, &ctx, &tg);
8426
8427 // Main loop:
8428 // 1. Identify boundaries of next island. (An island is a set of variants
8429 // that is distant enough from the rest of the variants that it can be
8430 // processed independently.)
8431 // 2. Determine highest memory mode that still fits.
8432 // 3. Holding the memory mode constant, check if additional small islands
8433 // can be appended to the group.
8434 // 4. Process the island-group.
8435 PgrSampleSubsetIndex pssi;
8436 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
8437 uintptr_t max_overlap_clump_size = 0; // does not count self
8438 uint32_t clump_ct = 0;
8439 const uintptr_t bytes_avail = bigstack_left();
8440 const uint32_t bp_radius = clump_ip->bp_radius;
8441 uint32_t parity = 0;
8442 uint32_t next_vidx_end = 0;
8443 uint32_t next_chr_fo_idx = 0;
8444 uintptr_t next_allele_idx_first;
8445 uintptr_t next_allele_idx_last;
8446 uintptr_t next_oaidx_start;
8447 uintptr_t next_oaidx_end;
8448 uint32_t next_vidx_start = GetNextIslandIdxs(cip, variant_bps, allele_idx_offsets, icandidate_vbitvec, observed_variants, observed_alleles, observed_alleles_cumulative_popcounts_w, raw_variant_ct, bp_radius, &next_oaidx_start, &next_oaidx_end, &next_vidx_end, &next_chr_fo_idx, &next_allele_idx_first, &next_allele_idx_last);
8449 uint32_t chr_fo_idx = UINT32_MAX;
8450 uint32_t is_x = 0;
8451 uint32_t is_y = 0;
8452 uint32_t is_haploid = 0;
8453 for (uint32_t icandidate_idx_start = 0; icandidate_idx_start < index_candidate_ct; ) {
8454 uint32_t vidx_start = next_vidx_start;
8455 uint32_t vidx_end = next_vidx_end;
8456 if (chr_fo_idx != next_chr_fo_idx) {
8457 chr_fo_idx = next_chr_fo_idx;
8458 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
8459 is_haploid = IsSet(cip->haploid_mask, chr_idx);
8460 is_x = (chr_idx == x_code);
8461 is_y = (chr_idx == y_code);
8462 if (is_x) {
8463 if (!founder_nonmale_ct) {
8464 is_x = 0;
8465 } else if (!founder_male_ct) {
8466 is_x = 0;
8467 is_haploid = 0;
8468 }
8469 }
8470 }
8471
8472 const uintptr_t allele_idx_first = next_allele_idx_first;
8473 uintptr_t allele_idx_last = next_allele_idx_last;
8474 uintptr_t oaidx_start = next_oaidx_start;
8475 uintptr_t oaidx_end = next_oaidx_end;
8476 uintptr_t candidate_ct = oaidx_end - oaidx_start;
8477 uint32_t relevant_phase_exists = 0;
8478 uint32_t load_dosage = 0;
8479 ScanPhaseDosage(observed_variants, pgfip, vidx_start, vidx_end, check_phase && ((!is_haploid) || is_x), check_dosage, &relevant_phase_exists, &load_dosage);
8480 R2PhaseType phase_type = GetR2PhaseType(phased_r2, relevant_phase_exists);
8481 ctx.is_x = is_x;
8482 ctx.is_y = is_y;
8483 ctx.igroup_oaidx_start = oaidx_start;
8484 ctx.allele_widx_start = allele_idx_first / kBitsPerWord;
8485
8486 uint64_t unpacked_variant_byte_stride = UnpackedByteStride(&ctx, phase_type, x_exists, load_dosage);
8487
8488 next_vidx_end = vidx_end;
8489 next_chr_fo_idx = chr_fo_idx;
8490 next_vidx_start = GetNextIslandIdxs(cip, variant_bps, allele_idx_offsets, icandidate_vbitvec, observed_variants, observed_alleles, observed_alleles_cumulative_popcounts_w, raw_variant_ct, bp_radius, &next_oaidx_start, &next_oaidx_end, &next_vidx_end, &next_chr_fo_idx, &next_allele_idx_first, &next_allele_idx_last);
8491
8492 // Highmem requirement:
8493 // candidate_ct * unpacked_variant_byte_stride for unpacked variants
8494 // max(multiread_byte_target for PgfiMultiread,
8495 // (candidate_ct + calc_thread_ct) * sizeof(intptr_t) for
8496 // ld_idx_found)
8497 const uintptr_t high_result_byte_req = RoundUpPow2((candidate_ct + calc_thread_ct) * sizeof(intptr_t), 2 * kCacheline);
8498 uintptr_t cur_high_multiread_byte_target = MAXV(high_result_byte_req / 2, multiread_byte_target);
8499 uint32_t icandidate_ct;
8500 if (bytes_avail >= candidate_ct * unpacked_variant_byte_stride + 2 * cur_high_multiread_byte_target) {
8501 // highmem loop
8502 // Don't continue trying to extend if we've reached the end of the
8503 // chromosome, or the current island-group already appears to be large
8504 // enough for good worker-thread utilization.
8505 while ((next_chr_fo_idx == chr_fo_idx) && (candidate_ct * unpacked_variant_byte_stride < (4194304 * k1LU) * calc_thread_ct)) {
8506 uint32_t ext_relevant_phase_exists = relevant_phase_exists;
8507 uint32_t ext_load_dosage = load_dosage;
8508 ScanPhaseDosage(observed_variants, pgfip, next_vidx_start, next_vidx_end, check_phase && ((!is_haploid) || is_x), check_dosage, &ext_relevant_phase_exists, &ext_load_dosage);
8509 const R2PhaseType ext_phase_type = GetR2PhaseType(phased_r2, ext_relevant_phase_exists);
8510 const uintptr_t ext_candidate_ct = candidate_ct + next_oaidx_end - next_oaidx_start;
8511 const uint64_t ext_unpacked_variant_byte_stride = UnpackedByteStride(&ctx, ext_phase_type, x_exists, ext_load_dosage);
8512 const uintptr_t ext_high_multiread_byte_target = MAXV(RoundUpPow2((ext_candidate_ct + calc_thread_ct) * sizeof(intptr_t), 2 * kCacheline) / 2, multiread_byte_target);
8513 if (bytes_avail < ext_candidate_ct * S_CAST(uint64_t, ext_unpacked_variant_byte_stride) + 2 * ext_high_multiread_byte_target) {
8514 // Insufficient memory to extend.
8515 break;
8516 }
8517 vidx_end = next_vidx_end;
8518 allele_idx_last = next_allele_idx_last;
8519 candidate_ct = ext_candidate_ct;
8520 unpacked_variant_byte_stride = ext_unpacked_variant_byte_stride;
8521 cur_high_multiread_byte_target = ext_high_multiread_byte_target;
8522 phase_type = ext_phase_type;
8523 load_dosage = ext_load_dosage;
8524 next_vidx_start = GetNextIslandIdxs(cip, variant_bps, allele_idx_offsets, icandidate_vbitvec, observed_variants, observed_alleles, observed_alleles_cumulative_popcounts_w, raw_variant_ct, bp_radius, nullptr, &next_oaidx_end, &next_vidx_end, &next_chr_fo_idx, &next_allele_idx_first, &next_allele_idx_last);
8525 }
8526 multiread_base[1] = &(g_bigstack_base[cur_high_multiread_byte_target]);
8527 unsigned char* unpacked_variants = &(multiread_base[1][cur_high_multiread_byte_target]);
8528 pgfip->block_base = multiread_base[parity];
8529 icandidate_ct = PopcountBitRange(icandidate_abitvec, allele_idx_first, allele_idx_last + 1);
8530 ctx.unpacked_variants = unpacked_variants;
8531 ctx.unpacked_byte_stride = unpacked_variant_byte_stride;
8532 ctx.phase_type = phase_type;
8533 ctx.load_dosage = load_dosage;
8534 ctx.allele_widx_end = 1 + (allele_idx_last / kBitsPerWord);
8535 ctx.job_type = kClumpJobHighmemUnpack;
8536 uint32_t multiread_vidx_start = vidx_start;
8537 const uint64_t fpos_end = GetPgfiFpos(pgfip, vidx_end);
8538 while (1) {
8539 // Similar to MultireadNonempty(), but we don't (i) expect to start
8540 // on a block boundary or (ii) expect to continue all the way to
8541 // the end of the file.
8542 const uint64_t fpos_start = GetPgfiLdbaseFpos(pgfip, multiread_vidx_start);
8543 uint32_t multiread_vidx_end = vidx_end;
8544 if (fpos_end - fpos_start > cur_high_multiread_byte_target) {
8545 if (!pgfip->var_fpos) {
8546 multiread_vidx_end = multiread_vidx_start + cur_high_multiread_byte_target / pgfip->const_vrec_width;
8547 } else {
8548 multiread_vidx_end = LastLeqU64(pgfip->var_fpos, multiread_vidx_start, raw_variant_ct, fpos_start + cur_high_multiread_byte_target);
8549 }
8550 multiread_vidx_end = 1 + FindLast1BitBefore(observed_variants, multiread_vidx_end);
8551 }
8552 const uint32_t load_variant_ct = PopcountBitRange(observed_variants, multiread_vidx_start, multiread_vidx_end);
8553 reterr = PgfiMultiread(observed_variants, multiread_vidx_start, multiread_vidx_end, load_variant_ct, pgfip);
8554 if (unlikely(reterr)) {
8555 goto ClumpReports_ret_PGR_FAIL;
8556 }
8557 uintptr_t multiread_allele_idx_start;
8558 uintptr_t multiread_allele_idx_end;
8559 if (allele_idx_offsets) {
8560 multiread_allele_idx_start = allele_idx_offsets[multiread_vidx_start];
8561 multiread_allele_idx_end = allele_idx_offsets[multiread_vidx_end];
8562 } else {
8563 multiread_allele_idx_start = 2 * multiread_vidx_start;
8564 multiread_allele_idx_end = 2 * multiread_vidx_end;
8565 }
8566 const uintptr_t multiread_oaidx_start = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, multiread_allele_idx_start);
8567 const uintptr_t multiread_oaidx_end = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, multiread_allele_idx_end);
8568 FillWStarts(calc_thread_ct, multiread_oaidx_start, multiread_oaidx_end - multiread_oaidx_start, ctx.a[parity].oaidx_starts);
8569 ctx.a[parity].oaidx_starts[calc_thread_ct] = multiread_oaidx_end;
8570 if (multiread_vidx_start != vidx_start) {
8571 JoinThreads(&tg);
8572 reterr = S_CAST(PglErr, ctx.err_info);
8573 if (unlikely(reterr)) {
8574 PgenErrPrintNV(reterr, ctx.err_info >> 32);
8575 goto ClumpReports_ret_1;
8576 }
8577 }
8578
8579 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
8580 if (unlikely(SpawnThreads(&tg))) {
8581 goto ClumpReports_ret_THREAD_CREATE_FAIL;
8582 }
8583 parity = 1 - parity;
8584
8585 if (multiread_vidx_end == vidx_end) {
8586 break;
8587 }
8588 multiread_vidx_start = AdvTo1Bit(observed_variants, multiread_vidx_end);
8589 pgfip->block_base = multiread_base[parity];
8590 }
8591 STD_SORT(icandidate_ct, u32cmp, &(icandidate_idx_to_rank0_destructive[icandidate_idx_start]));
8592 JoinThreads(&tg);
8593 reterr = S_CAST(PglErr, ctx.err_info);
8594 if (unlikely(reterr)) {
8595 PgenErrPrintNV(reterr, ctx.err_info >> 32);
8596 goto ClumpReports_ret_1;
8597 }
8598 // Now iterate through index variants.
8599 ctx.job_type = kClumpJobHighmemR2;
8600 for (uint32_t icandidate_idx = 0; icandidate_idx != icandidate_ct; ++icandidate_idx) {
8601 if ((icandidate_idx_start + icandidate_idx) % 1000 == 0) {
8602 printf("\r--clump: %u/%u index candidate%s processed.", icandidate_idx_start + icandidate_idx, index_candidate_ct, (index_candidate_ct == 1)? "" : "s");
8603 fflush(stdout);
8604 }
8605 const uint32_t rank0 = icandidate_idx_to_rank0_destructive[icandidate_idx_start + icandidate_idx];
8606 const uintptr_t allele_idx = index_candidates[rank0].allele_idx;
8607 const uintptr_t index_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_idx);
8608 if (!IsSet(icandidate_oabitvec, index_oaidx)) {
8609 // Already included in another clump.
8610 continue;
8611 }
8612 ++clump_ct;
8613 uint32_t variant_uidx;
8614 if (!variant_last_alidxs) {
8615 variant_uidx = allele_idx / 2;
8616 } else {
8617 variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, allele_idx);
8618 }
8619 uint32_t window_start_vidx = vidx_start;
8620 uint32_t window_end_vidx = vidx_end;
8621 GetBpWindow(observed_variants, variant_bps, variant_uidx, bp_radius, &window_start_vidx, &window_end_vidx);
8622 uintptr_t window_allele_idx_start;
8623 uintptr_t window_allele_idx_end;
8624 if (!allele_idx_offsets) {
8625 window_allele_idx_start = window_start_vidx * 2;
8626 window_allele_idx_end = window_end_vidx * 2;
8627 } else {
8628 window_allele_idx_start = allele_idx_offsets[window_start_vidx];
8629 window_allele_idx_end = allele_idx_offsets[window_end_vidx];
8630 }
8631 uintptr_t window_oaidx_start = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, window_allele_idx_start);
8632 window_oaidx_start = AdvTo1Bit(candidate_oabitvec, window_oaidx_start);
8633 uintptr_t window_oaidx_end = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, window_allele_idx_end);
8634 window_oaidx_end = 1 + FindLast1BitBefore(candidate_oabitvec, window_oaidx_end);
8635 // Wait till this point to clear the bit, to simplify
8636 // window_oaidx_start and window_oaidx_end initialization.
8637 ClearBit(index_oaidx, candidate_oabitvec);
8638 if (oallele_idx_to_clump_idx) {
8639 oallele_idx_to_clump_idx[index_oaidx] = rank0;
8640 } else {
8641 const uint64_t fpos = ftello(clump_overlap_tmp);
8642 clump_idx_to_overlap_fpos_and_len[rank0 * 2] = fpos;
8643 }
8644 uintptr_t nonindex_ct = PopcountBitRange(candidate_oabitvec, window_oaidx_start, window_oaidx_end);
8645 if (!nonindex_ct) {
8646 // No remaining non-index variants to clump with this.
8647 continue;
8648 }
8649 // If there's exactly one non-index variant to check, there's no
8650 // point in waking up the worker threads.
8651 // Possible todo: if allow_overlap is false, each worker thread could
8652 // operate independently. Ideally, the number of worker threads
8653 // assigned to a single index variant is limited by the job size.
8654 // (However, in the allow_overlap true case, maybe just tune this
8655 // threshold and leave everything else the same.)
8656 const uint32_t cur_thread_ct = (nonindex_ct == 1)? 1 : (calc_thread_ct + 1);
8657 FillWSubsetStarts(candidate_oabitvec, cur_thread_ct, window_oaidx_start, nonindex_ct, ctx.a[parity].oaidx_starts);
8658 ctx.index_oaidx_offset = index_oaidx - oaidx_start;
8659 uintptr_t* ld_idx_found_base = R_CAST(uintptr_t*, multiread_base[0]);
8660 ctx.cur_nonindex_ct = nonindex_ct;
8661 ctx.ld_idx_found[0] = ld_idx_found_base;
8662 for (uint32_t tidx = 1; tidx != cur_thread_ct; ++tidx) {
8663 const uintptr_t offset = (tidx * S_CAST(uint64_t, nonindex_ct)) / (cur_thread_ct);
8664 // These are (~k0LU)-terminated sequences of oaidxs (usual case) or
8665 // allele_idxs (--clump-allow-overlap case). Leave enough room for
8666 // all possible indexes to be included, plus the terminator.
8667 ctx.ld_idx_found[tidx] = &(ld_idx_found_base[offset + tidx]);
8668 }
8669 if (cur_thread_ct > 1) {
8670 SpawnThreads(&tg);
8671 }
8672 ClumpHighmemR2(cur_thread_ct - 1, cur_thread_ct, parity, &ctx);
8673 if (cur_thread_ct > 1) {
8674 JoinThreads(&tg);
8675 }
8676 if (oallele_idx_to_clump_idx) {
8677 for (uint32_t tidx = 0; tidx != cur_thread_ct; ++tidx) {
8678 const uintptr_t* read_iter = ctx.ld_idx_found[tidx];
8679 for (; ; ++read_iter) {
8680 const uintptr_t oaidx = *read_iter;
8681 if (oaidx == ~k0LU) {
8682 break;
8683 }
8684 ClearBit(oaidx, candidate_oabitvec);
8685 oallele_idx_to_clump_idx[oaidx] = rank0;
8686 }
8687 }
8688 } else {
8689 uintptr_t prev_save_allele_idx = 0;
8690 uintptr_t clump_size = 0;
8691 if (unlikely(ClumpSpillResults(observed_alleles, observed_alleles_cumulative_popcounts_w, ctx.ld_idx_found, cur_thread_ct, &prev_save_allele_idx, &clump_size, icandidate_oabitvec, clump_overlap_tmp))) {
8692 goto ClumpReports_ret_WRITE_FAIL;
8693 }
8694 if (clump_size > max_overlap_clump_size) {
8695 max_overlap_clump_size = clump_size;
8696 }
8697 clump_idx_to_overlap_fpos_and_len[rank0 * 2 + 1] = ftello(clump_overlap_tmp) - clump_idx_to_overlap_fpos_and_len[rank0 * 2];
8698 }
8699 if (cur_thread_ct > 1) {
8700 parity = 1 - parity;
8701 }
8702 }
8703 } else {
8704 icandidate_ct = PopcountBitRange(icandidate_abitvec, allele_idx_first, allele_idx_last + 1);
8705 ctx.unpacked_variants = lowmem_unpacked_variants;
8706 ctx.unpacked_byte_stride = unpacked_byte_stride_cachealign;
8707 ctx.phase_type = phase_type;
8708 ctx.load_dosage = load_dosage;
8709 ctx.allele_widx_end = 1 + (allele_idx_last / kBitsPerWord);
8710 ctx.job_type = kClumpJobLowmemR2;
8711 STD_SORT(icandidate_ct, u32cmp, &(icandidate_idx_to_rank0_destructive[icandidate_idx_start]));
8712 const uintptr_t* cur_founder_male_collapsed = is_x? founder_male_collapsed : nullptr;
8713 const Dosage* cur_male_dosage_invmask = is_x? male_dosage_invmask : nullptr;
8714 const uint32_t icandidate_idx_end = icandidate_idx_start + icandidate_ct;
8715 for (uint32_t icandidate_idx = icandidate_idx_start; icandidate_idx != icandidate_idx_end; ++icandidate_idx) {
8716 if (icandidate_idx % 1000 == 0) {
8717 printf("\r--clump: %u/%u index candidate%s processed.", icandidate_idx, index_candidate_ct, (index_candidate_ct == 1)? "" : "s");
8718 fflush(stdout);
8719 }
8720 const uint32_t rank0 = icandidate_idx_to_rank0_destructive[icandidate_idx];
8721 const uintptr_t index_allele_idx = index_candidates[rank0].allele_idx;
8722 const uintptr_t index_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, index_allele_idx);
8723 if (!IsSet(icandidate_oabitvec, index_oaidx)) {
8724 // Already included in another clump.
8725 continue;
8726 }
8727 ++clump_ct;
8728 uint32_t index_variant_uidx;
8729 AlleleCode index_aidx;
8730 if (!variant_last_alidxs) {
8731 index_variant_uidx = index_allele_idx / 2;
8732 index_aidx = index_allele_idx % 2;
8733 } else {
8734 index_variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, index_allele_idx);
8735 index_aidx = index_allele_idx - allele_idx_offsets[index_variant_uidx];
8736 }
8737 uint32_t window_start_vidx = vidx_start;
8738 uint32_t window_end_vidx = vidx_end;
8739 GetBpWindow(observed_variants, variant_bps, index_variant_uidx, bp_radius, &window_start_vidx, &window_end_vidx);
8740 uintptr_t window_allele_idx_start;
8741 uintptr_t window_allele_idx_end;
8742 if (!allele_idx_offsets) {
8743 window_allele_idx_start = window_start_vidx * 2;
8744 window_allele_idx_end = window_end_vidx * 2;
8745 } else {
8746 window_allele_idx_start = allele_idx_offsets[window_start_vidx];
8747 window_allele_idx_end = allele_idx_offsets[window_end_vidx];
8748 }
8749 uintptr_t window_oaidx_cur = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, window_allele_idx_start);
8750 window_oaidx_cur = AdvTo1Bit(candidate_oabitvec, window_oaidx_cur);
8751 uintptr_t window_oaidx_end = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, window_allele_idx_end);
8752 window_oaidx_end = 1 + FindLast1BitBefore(candidate_oabitvec, window_oaidx_end);
8753 // Wait till this point to clear the bit, to simplify
8754 // window_oaidx_cur and window_oaidx_end initialization.
8755 ClearBit(index_oaidx, candidate_oabitvec);
8756 if (oallele_idx_to_clump_idx) {
8757 oallele_idx_to_clump_idx[index_oaidx] = rank0;
8758 } else {
8759 const uint64_t fpos = ftello(clump_overlap_tmp);
8760 clump_idx_to_overlap_fpos_and_len[rank0 * 2] = fpos;
8761 }
8762 uintptr_t rem_nonindex_ct = PopcountBitRange(candidate_oabitvec, window_oaidx_cur, window_oaidx_end);
8763 if (!rem_nonindex_ct) {
8764 // No remaining non-index variants to clump with this.
8765 continue;
8766 }
8767 const uintptr_t allele_widx_end = DivUp(window_allele_idx_end, kBitsPerWord);
8768 uintptr_t allele_widx_start = window_allele_idx_start / kBitsPerWord;
8769 uintptr_t prev_save_allele_idx = 0;
8770 uintptr_t clump_size = 0;
8771 uint32_t index_variant_needed = 1;
8772 do {
8773 const uintptr_t cur_nonindex_ct = MINV(rem_nonindex_ct, max_lowmem_nonindex_ct);
8774 const uint32_t cur_thread_ct = (cur_nonindex_ct == 1)? 1 : (calc_thread_ct + 1);
8775 FillWSubsetStarts(candidate_oabitvec, cur_thread_ct, window_oaidx_cur, cur_nonindex_ct, ctx.a[parity].oaidx_starts);
8776
8777 uintptr_t next_window_oaidx_cur = window_oaidx_end;
8778 if (cur_nonindex_ct < rem_nonindex_ct) {
8779 const uintptr_t last_bit_ct = cur_nonindex_ct - (cur_nonindex_ct * S_CAST(uint64_t, cur_thread_ct - 1)) / cur_thread_ct;
8780 next_window_oaidx_cur = FindNth1BitFrom(candidate_oabitvec, ctx.a[parity].oaidx_starts[cur_thread_ct - 1], last_bit_ct + 1);
8781 }
8782
8783 // Load PgenVariants serially.
8784 PgenVariant pgv = ctx.pgv_base;
8785 uintptr_t oaidx_base;
8786 uintptr_t cur_oaidx_bits;
8787 BitIter1Start(candidate_oabitvec, window_oaidx_cur, &oaidx_base, &cur_oaidx_bits);
8788 for (uintptr_t nonindex_idx = 0; nonindex_idx != cur_nonindex_ct; ) {
8789 uintptr_t variant_uidx;
8790 AlleleCode aidx;
8791 if (index_variant_needed) {
8792 variant_uidx = index_variant_uidx;
8793 aidx = index_aidx;
8794 } else {
8795 const uintptr_t oaidx = BitIter1(candidate_oabitvec, &oaidx_base, &cur_oaidx_bits);
8796 const uintptr_t allele_idx = ExpsearchIdxToUidxW(observed_alleles, observed_alleles_cumulative_popcounts_w, allele_widx_end, oaidx, &allele_widx_start);
8797 if (!allele_idx_offsets) {
8798 variant_uidx = allele_idx / 2;
8799 aidx = allele_idx % 2;
8800 } else {
8801 variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, allele_idx);
8802 aidx = allele_idx - allele_idx_offsets[variant_uidx];
8803 }
8804 }
8805 if (load_dosage) {
8806 if (phase_type == kR2PhaseTypePresent) {
8807 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, &pgv);
8808 } else {
8809 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
8810 }
8811 if (is_y) {
8812 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
8813 }
8814 } else {
8815 if (phase_type == kR2PhaseTypePresent) {
8816 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
8817 } else {
8818 reterr = PgrGetInv1(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec);
8819 }
8820 if (is_y) {
8821 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
8822 }
8823 }
8824 if (unlikely(reterr)) {
8825 goto ClumpReports_ret_PGR_FAIL;
8826 }
8827 if (!index_variant_needed) {
8828 ClumpPgenVariantIncr(pgv_byte_stride, &pgv);
8829 if (phasepresent_cts) {
8830 phasepresent_cts[nonindex_idx] = pgv.phasepresent_ct;
8831 }
8832 if (dosage_cts) {
8833 dosage_cts[nonindex_idx] = pgv.dosage_ct;
8834 }
8835 if (dphase_cts) {
8836 dphase_cts[nonindex_idx] = pgv.dphase_ct;
8837 }
8838 ++nonindex_idx;
8839 } else {
8840 if (load_dosage) {
8841 LdUnpackDosage(&pgv, cur_founder_male_collapsed, cur_male_dosage_invmask, founder_ct, phase_type, lowmem_unpacked_variants);
8842 } else {
8843 LdUnpackNondosageDense(&pgv, cur_founder_male_collapsed, founder_ct, phase_type, lowmem_unpacked_variants);
8844 }
8845 index_variant_needed = 0;
8846 }
8847 }
8848
8849 // Compute r^2s for PgenVariants against index variant in parallel.
8850 ctx.cur_nonindex_ct = cur_nonindex_ct;
8851 ctx.ld_idx_found[0] = lowmem_ld_idx_found_base;
8852 for (uint32_t tidx = 1; tidx != cur_thread_ct; ++tidx) {
8853 const uintptr_t offset = (tidx * S_CAST(uint64_t, cur_nonindex_ct)) / cur_thread_ct;
8854 ctx.ld_idx_found[tidx] = &(lowmem_ld_idx_found_base[offset + tidx]);
8855 }
8856 if (cur_thread_ct > 1) {
8857 if (unlikely(SpawnThreads(&tg))) {
8858 goto ClumpReports_ret_THREAD_CREATE_FAIL;
8859 }
8860 }
8861 ClumpLowmemR2(cur_thread_ct - 1, cur_thread_ct, parity, &ctx);
8862 if (cur_thread_ct > 1) {
8863 JoinThreads(&tg);
8864 }
8865 if (oallele_idx_to_clump_idx) {
8866 for (uint32_t tidx = 0; tidx != cur_thread_ct; ++tidx) {
8867 const uintptr_t* read_iter = ctx.ld_idx_found[tidx];
8868 for (; ; ++read_iter) {
8869 const uintptr_t oaidx = *read_iter;
8870 if (oaidx == ~k0LU) {
8871 break;
8872 }
8873 ClearBit(oaidx, candidate_oabitvec);
8874 oallele_idx_to_clump_idx[oaidx] = rank0;
8875 }
8876 }
8877 } else {
8878 if (unlikely(ClumpSpillResults(observed_alleles, observed_alleles_cumulative_popcounts_w, ctx.ld_idx_found, cur_thread_ct, &prev_save_allele_idx, &clump_size, icandidate_oabitvec, clump_overlap_tmp))) {
8879 goto ClumpReports_ret_WRITE_FAIL;
8880 }
8881 }
8882 window_oaidx_cur = next_window_oaidx_cur;
8883 rem_nonindex_ct -= cur_nonindex_ct;
8884 if (cur_thread_ct > 1) {
8885 parity = 1 - parity;
8886 }
8887 } while (rem_nonindex_ct);
8888 if (clump_idx_to_overlap_fpos_and_len) {
8889 if (clump_size > max_overlap_clump_size) {
8890 max_overlap_clump_size = clump_size;
8891 }
8892 clump_idx_to_overlap_fpos_and_len[rank0 * 2 + 1] = ftello(clump_overlap_tmp) - clump_idx_to_overlap_fpos_and_len[rank0 * 2];
8893 }
8894 }
8895 }
8896
8897 icandidate_idx_start += icandidate_ct;
8898 }
8899 ctx.job_type = kClumpJobNone;
8900 DeclareLastThreadBlock(&tg);
8901 if (unlikely(SpawnThreads(&tg))) {
8902 goto ClumpReports_ret_THREAD_CREATE_FAIL;
8903 }
8904 JoinThreads(&tg);
8905
8906 fputs("\r", stdout);
8907 logprintf("--clump: %u clump%s formed from %u index candidate%s.", clump_ct, (clump_ct == 1)? "" : "s", index_candidate_ct, (index_candidate_ct == 1)? "" : "s");
8908 fputs(" ", stdout);
8909 logputs("\n");
8910
8911 // Usual (i.e. not --clump-allow-overlap) postprocessing algorithm:
8912 // 1. Count the number of (variant, aidx)s associated with each clump.
8913 // 2. Allocate ordered_members[]; partial count-sums give each clump's
8914 // starting position within ordered_members[].
8915 // 3. Fill ordered_members.
8916 BigstackDoubleReset(candidate_oabitvec, bigstack_end_mark);
8917 uintptr_t* clump_ends = nullptr;
8918 uintptr_t* ordered_members = nullptr;
8919 unsigned char* overlap_raw_loadbuf = nullptr;
8920 uintptr_t* overlap_allele_idxs = nullptr;
8921 if (!allow_overlap) {
8922 uintptr_t* clump_sizes;
8923 if (unlikely(bigstack_calloc_w(index_candidate_ct, &clump_sizes))) {
8924 goto ClumpReports_ret_NOMEM;
8925 }
8926 uintptr_t running_total = 0;
8927 // could parallelize this, but doesn't realistically matter
8928 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
8929 const uint32_t clump_idx = oallele_idx_to_clump_idx[oaidx];
8930 if (clump_idx != UINT32_MAX) {
8931 clump_sizes[clump_idx] += 1;
8932 }
8933 }
8934 // convert clump_sizes to clump_write_offsets
8935 for (uint32_t clump_idx = 0; clump_idx != index_candidate_ct; ++clump_idx) {
8936 const uintptr_t cur_clump_size = clump_sizes[clump_idx];
8937 clump_sizes[clump_idx] = running_total;
8938 running_total += cur_clump_size;
8939 }
8940 uintptr_t* clump_write_offsets = clump_sizes;
8941 if (unlikely(bigstack_alloc_w(running_total, &ordered_members))) {
8942 goto ClumpReports_ret_NOMEM;
8943 }
8944 // Now fill ordered_members, convert oaidxs to allele_idxs, and convert
8945 // clump_write_offsets to clump_ends as a side-effect.
8946 uintptr_t allele_idx_base = 0;
8947 uintptr_t cur_bits = observed_alleles[0];
8948 for (uintptr_t oaidx = 0; oaidx != observed_allele_ct; ++oaidx) {
8949 const uintptr_t allele_idx = BitIter1(observed_alleles, &allele_idx_base, &cur_bits);
8950 const uint32_t clump_idx = oallele_idx_to_clump_idx[oaidx];
8951 if (clump_idx != UINT32_MAX) {
8952 const uintptr_t write_offset = clump_write_offsets[clump_idx];
8953 ordered_members[write_offset] = allele_idx;
8954 clump_write_offsets[clump_idx] += 1;
8955 }
8956 }
8957 clump_ends = clump_write_offsets;
8958 } else {
8959 uint64_t max_vint_byte_ct = 0;
8960 for (uint32_t clump_idx = 0; clump_idx != index_candidate_ct; ++clump_idx) {
8961 const uint64_t vint_byte_ct = clump_idx_to_overlap_fpos_and_len[clump_idx * 2 + 1];
8962 if (vint_byte_ct > max_vint_byte_ct) {
8963 max_vint_byte_ct = vint_byte_ct;
8964 }
8965 }
8966 if (unlikely(bigstack_alloc64_uc(max_vint_byte_ct, &overlap_raw_loadbuf) ||
8967 bigstack_alloc_w(max_overlap_clump_size + 1, &overlap_allele_idxs))) {
8968 goto ClumpReports_ret_NOMEM;
8969 }
8970 if (unlikely(fclose_null(&clump_overlap_tmp))) {
8971 goto ClumpReports_ret_WRITE_FAIL;
8972 }
8973 if (unlikely(fopen_checked(outname, FOPEN_RB, &clump_overlap_tmp))) {
8974 goto ClumpReports_ret_OPEN_FAIL;
8975 }
8976 }
8977
8978 char* range_group_names = nullptr;
8979 uintptr_t* rg_chr_bounds = nullptr;
8980 uint32_t** rg_setdefs = nullptr;
8981 uintptr_t max_range_group_id_blen = 0;
8982 if (range_fname) {
8983 uintptr_t ignored_group_ct;
8984 uintptr_t ignored_chr_max_group_ct;
8985 reterr = LoadAndSortIntervalBed(range_fname, cip, nullptr, (flags / kfClumpRange0) & 1, clump_ip->range_border, 0, 0, max_thread_ct, &ignored_group_ct, &range_group_names, &max_range_group_id_blen, &rg_chr_bounds, &rg_setdefs, &ignored_chr_max_group_ct);
8986 if (unlikely(reterr)) {
8987 goto ClumpReports_ret_1;
8988 }
8989 }
8990
8991 const uint32_t overflow_buf_size = kCompressStreamBlock + MAXV(kMaxIdSlen + max_variant_id_slen + max_allele_slen, bin_bound_ct * (kMaxLnGSlen + 1)) + 256;
8992 OutnameZstSet(".clumps", output_zst, outname_end);
8993 reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep);
8994 if (unlikely(reterr)) {
8995 goto ClumpReports_ret_1;
8996 }
8997 const uint32_t chr_col = flags & kfClumpColChrom;
8998 const uint32_t pos_col = flags & kfClumpColPos;
8999 const uint32_t ref_col = flags & kfClumpColRef;
9000 const uint32_t alt1_col = flags & kfClumpColAlt1;
9001 const uint32_t alt_col = flags & kfClumpColAlt;
9002 const uintptr_t* nonref_flags = pgfip->nonref_flags;
9003 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
9004 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, flags / kfClumpColMaybeprovref, raw_variant_ct, all_nonref);
9005 const uint32_t a1_col = (flags & kfClumpColA1) || ((flags & kfClumpColMaybeA1) && MultiallelicVariantPresent(variant_include, allele_idx_offsets, variant_ct));
9006 const uint32_t f_col = (flags & kfClumpColF) || ((flags & kfClumpColMaybeF) && (file_ct > 1));
9007 const uint32_t f_in_sp2 = sp2_col && ((flags & kfClumpColF) || (file_ct > 1));
9008 const uint32_t output_log10 = flags & kfClumpOutputLog10;
9009 const uint32_t total_col = flags & kfClumpColTotal;
9010 uintptr_t* cur_bin_counts = nullptr;
9011 if (bin_bound_ct) {
9012 if (unlikely(bigstack_alloc_w(bin_bound_ct + 1, &cur_bin_counts))) {
9013 goto ClumpReports_ret_NOMEM;
9014 }
9015 }
9016 *cswritep++ = '#';
9017 if (chr_col) {
9018 cswritep = strcpya_k(cswritep, "CHROM\t");
9019 }
9020 if (pos_col) {
9021 cswritep = strcpya_k(cswritep, "POS\t");
9022 }
9023 cswritep = strcpya_k(cswritep, "ID\t");
9024 if (ref_col) {
9025 cswritep = strcpya_k(cswritep, "REF\t");
9026 }
9027 if (alt1_col) {
9028 cswritep = strcpya_k(cswritep, "ALT1\t");
9029 }
9030 if (alt_col) {
9031 cswritep = strcpya_k(cswritep, "ALT\t");
9032 }
9033 if (provref_col) {
9034 cswritep = strcpya_k(cswritep, "PROVISIONAL_REF?\t");
9035 }
9036 if (a1_col) {
9037 cswritep = strcpya_k(cswritep, "A1\t");
9038 }
9039 if (f_col) {
9040 cswritep = strcpya_k(cswritep, "F\t");
9041 }
9042 if (output_log10) {
9043 cswritep = strcpya_k(cswritep, "NEG_LOG10_");
9044 }
9045 *cswritep++ = 'P';
9046 if (total_col) {
9047 cswritep = strcpya_k(cswritep, "\tTOTAL");
9048 }
9049 if (bounds_col) {
9050 cswritep = strcpya_k(cswritep, "\tCLUMP_FIRST_POS\tCLUMP_LAST_POS");
9051 }
9052 if (bin_bound_ct) {
9053 cswritep = strcpya_k(cswritep, "\tNONSIG");
9054 for (uint32_t bin_idx = bin_bound_ct; bin_idx; ) {
9055 --bin_idx;
9056 cswritep = strcpya_k(cswritep, "\tS");
9057 cswritep = lntoa_g(ln_bin_boundaries[bin_idx], cswritep);
9058 }
9059 }
9060 if (sp2_col) {
9061 cswritep = strcpya_k(cswritep, "\tSP2");
9062 }
9063 if (ranges_col) {
9064 cswritep = strcpya_k(cswritep, "\tRANGES");
9065 }
9066 AppendBinaryEoln(&cswritep);
9067 if (unlikely(Cswrite(&css, &cswritep))) {
9068 goto ClumpReports_ret_WRITE_FAIL;
9069 }
9070
9071 uintptr_t* clump_allele_idxs = overlap_allele_idxs;
9072 uintptr_t prev_clump_end = 0;
9073 uint32_t chr_idx = 0;
9074 uint32_t index_allele_ct = 2;
9075 uint32_t index_file_idx1 = 1;
9076 uint32_t file_idx1 = 1;
9077 uint32_t first_bp = 0;
9078 uint32_t last_bp = 0;
9079 for (uint32_t clump_idx = 0; clump_idx != index_candidate_ct; ++clump_idx) {
9080 const uintptr_t index_allele_idx = index_candidates[clump_idx].allele_idx;
9081 uintptr_t clump_size_including_self;
9082 if (!allow_overlap) {
9083 const uintptr_t cur_clump_end = clump_ends[clump_idx];
9084 if (cur_clump_end == prev_clump_end) {
9085 continue;
9086 }
9087 clump_allele_idxs = &(ordered_members[prev_clump_end]);
9088 clump_size_including_self = cur_clump_end - prev_clump_end;
9089 prev_clump_end = cur_clump_end;
9090 } else {
9091 const uint64_t fpos = clump_idx_to_overlap_fpos_and_len[clump_idx * 2];
9092 if (fpos == 0) {
9093 continue;
9094 }
9095 const uint64_t vint_byte_ct = clump_idx_to_overlap_fpos_and_len[clump_idx * 2 + 1];
9096 if (vint_byte_ct) {
9097 if (unlikely(fseeko(clump_overlap_tmp, fpos, SEEK_SET) ||
9098 fread_checked(overlap_raw_loadbuf, vint_byte_ct, clump_overlap_tmp))) {
9099 goto ClumpReports_ret_READ_FAIL;
9100 }
9101 }
9102 const unsigned char* read_iter = overlap_raw_loadbuf;
9103 const unsigned char* read_end = &(read_iter[vint_byte_ct]);
9104 uintptr_t* write_iter = clump_allele_idxs;
9105 uintptr_t last_allele_idx = 0;
9106 while (read_iter != read_end) {
9107 const uintptr_t allele_idx_incr = GetVint64Unsafe(&read_iter);
9108 last_allele_idx += allele_idx_incr;
9109 if (last_allele_idx > index_allele_idx) {
9110 break;
9111 }
9112 *write_iter++ = last_allele_idx;
9113 }
9114 *write_iter++ = index_allele_idx;
9115 if (last_allele_idx > index_allele_idx) {
9116 *write_iter++ = last_allele_idx;
9117 }
9118 while (read_iter != read_end) {
9119 const uintptr_t allele_idx_incr = GetVint64Unsafe(&read_iter);
9120 last_allele_idx += allele_idx_incr;
9121 *write_iter++ = last_allele_idx;
9122 }
9123 clump_size_including_self = write_iter - clump_allele_idxs;
9124 }
9125
9126 uintptr_t index_allele_idx_offset_base;
9127 uint32_t index_variant_uidx;
9128 if (!allele_idx_offsets) {
9129 index_variant_uidx = index_allele_idx / 2;
9130 index_allele_idx_offset_base = index_allele_idx & (~k1LU);
9131 } else {
9132 index_variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, index_allele_idx);
9133 index_allele_idx_offset_base = allele_idx_offsets[index_variant_uidx];
9134 index_allele_ct = allele_idx_offsets[index_variant_uidx + 1] - index_allele_idx_offset_base;
9135 }
9136 if (chr_col || ranges_col) {
9137 chr_idx = GetVariantChr(cip, index_variant_uidx);
9138 if (chr_col) {
9139 cswritep = chrtoa(cip, chr_idx, cswritep);
9140 *cswritep++ = '\t';
9141 }
9142 }
9143 if (pos_col) {
9144 cswritep = u32toa_x(variant_bps[index_variant_uidx], '\t', cswritep);
9145 }
9146 cswritep = strcpyax(cswritep, variant_ids[index_variant_uidx], '\t');
9147 if (ref_col) {
9148 cswritep = strcpyax(cswritep, allele_storage[index_allele_idx_offset_base], '\t');
9149 if (unlikely(Cswrite(&css, &cswritep))) {
9150 goto ClumpReports_ret_WRITE_FAIL;
9151 }
9152 }
9153 if (alt1_col) {
9154 cswritep = strcpyax(cswritep, allele_storage[index_allele_idx_offset_base + 1], '\t');
9155 if (unlikely(Cswrite(&css, &cswritep))) {
9156 goto ClumpReports_ret_WRITE_FAIL;
9157 }
9158 }
9159 if (alt_col) {
9160 for (uint32_t aidx = 1; aidx != index_allele_ct; ++aidx) {
9161 cswritep = strcpya(cswritep, allele_storage[index_allele_idx_offset_base + aidx]);
9162 if (unlikely(Cswrite(&css, &cswritep))) {
9163 goto ClumpReports_ret_WRITE_FAIL;
9164 }
9165 *cswritep++ = ',';
9166 }
9167 cswritep[-1] = '\t';
9168 }
9169 if (provref_col) {
9170 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, index_variant_uidx)))? 'Y' : 'N';
9171 *cswritep++ = '\t';
9172 }
9173 const uintptr_t index_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, index_allele_idx);
9174 if (a1_col) {
9175 if (index_allele_ct == 2) {
9176 if (force_a1) {
9177 const uint32_t aidx = best_fidx_x2s[index_oaidx] & 1;
9178 cswritep = strcpyax(cswritep, allele_storage[index_allele_idx_offset_base + aidx], '\t');
9179 if (unlikely(Cswrite(&css, &cswritep))) {
9180 goto ClumpReports_ret_WRITE_FAIL;
9181 }
9182 } else {
9183 cswritep = strcpya_k(cswritep, ".\t");
9184 }
9185 } else {
9186 cswritep = strcpyax(cswritep, allele_storage[index_allele_idx], '\t');
9187 if (unlikely(Cswrite(&css, &cswritep))) {
9188 goto ClumpReports_ret_WRITE_FAIL;
9189 }
9190 }
9191 }
9192 if (best_fidx_x2s) {
9193 index_file_idx1 = best_fidx_x2s[index_oaidx] >> 1;
9194 }
9195 if (f_col) {
9196 cswritep = u32toa_x(index_file_idx1, '\t', cswritep);
9197 }
9198 const double index_ln_pval = index_candidates[clump_idx].ln_pval;
9199 if (!output_log10) {
9200 const double reported_ln = MAXV(index_ln_pval, output_min_ln);
9201 cswritep = lntoa_g(reported_ln, cswritep);
9202 } else {
9203 const double reported_val = (-kRecipLn10) * index_ln_pval;
9204 cswritep = dtoa_g(reported_val, cswritep);
9205 }
9206 if (total_col || bin_bound_ct) {
9207 uintptr_t total_ct = 0;
9208 if (bin_bound_ct) {
9209 ZeroWArr(bin_bound_ct + 1, cur_bin_counts);
9210 for (uintptr_t member_idx = 0; member_idx != clump_size_including_self; ++member_idx) {
9211 const uintptr_t cur_allele_idx = clump_allele_idxs[member_idx];
9212 const uintptr_t cur_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, cur_allele_idx);
9213 if (nonsig_arr) {
9214 cur_bin_counts[bin_bound_ct] += nonsig_arr[cur_oaidx];
9215 }
9216 const unsigned char* varint_read_iter = clump_entry_varints[cur_oaidx];
9217 const unsigned char* varint_read_end = clump_entry_varints[cur_oaidx + 1];
9218 while (varint_read_iter != varint_read_end) {
9219 const uint32_t pval_bin = GetVint32Unsafe(&varint_read_iter) >> 1;
9220 cur_bin_counts[pval_bin] += 1;
9221 if (save_all_fidxs) {
9222 SkipVintUnsafe(&varint_read_iter);
9223 }
9224 }
9225 }
9226 // Keep appearances of this (variant, uidx) in other files, but don't
9227 // count the central appearance.
9228 const uint32_t index_pval_bin = LowerBoundNonemptyD(ln_bin_boundaries, bin_bound_ct, index_ln_pval);
9229 cur_bin_counts[index_pval_bin] -= 1;
9230
9231 for (uint32_t bin_idx = 0; bin_idx <= bin_bound_ct; ++bin_idx) {
9232 total_ct += cur_bin_counts[bin_idx];
9233 }
9234 } else {
9235 for (uintptr_t member_idx = 0; member_idx != clump_size_including_self; ++member_idx) {
9236 const uintptr_t cur_allele_idx = clump_allele_idxs[member_idx];
9237 const uintptr_t cur_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, cur_allele_idx);
9238 if (nonsig_arr) {
9239 total_ct += nonsig_arr[cur_oaidx];
9240 }
9241 const unsigned char* varint_read_start = clump_entry_varints[cur_oaidx];
9242 const unsigned char* varint_read_end = clump_entry_varints[cur_oaidx + 1];
9243 const uintptr_t varint_ct = CountVints(varint_read_start, varint_read_end);
9244 total_ct += varint_ct >> save_all_fidxs;
9245 }
9246 --total_ct;
9247 }
9248 if (total_col) {
9249 *cswritep++ = '\t';
9250 cswritep = wtoa(total_ct, cswritep);
9251 }
9252 }
9253 if (bounds_col || ranges_col) {
9254 for (intptr_t direction = 1; direction != -3; direction -= 2) {
9255 uint32_t pval_too_high = 1;
9256 uintptr_t member_idx = (direction == 1)? 0 : (clump_size_including_self - 1);
9257 for (; member_idx != clump_size_including_self ; member_idx += direction) {
9258 const uintptr_t cur_allele_idx = clump_allele_idxs[member_idx];
9259 const uintptr_t cur_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, cur_allele_idx);
9260 const unsigned char* varint_read_iter = clump_entry_varints[cur_oaidx];
9261 const unsigned char* varint_read_end = clump_entry_varints[cur_oaidx + 1];
9262 while (varint_read_iter != varint_read_end) {
9263 pval_too_high = GetVint32Unsafe(&varint_read_iter) & 1;
9264 if (!pval_too_high) {
9265 break;
9266 }
9267 }
9268 if (!pval_too_high) {
9269 uint32_t variant_uidx;
9270 if (!allele_idx_offsets) {
9271 variant_uidx = cur_allele_idx / 2;
9272 } else {
9273 variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, cur_allele_idx);
9274 }
9275 if (direction == 1) {
9276 first_bp = variant_bps[variant_uidx];
9277 } else {
9278 last_bp = variant_bps[variant_uidx];
9279 }
9280 break;
9281 }
9282 }
9283 if (member_idx == clump_size_including_self) {
9284 // special case: no --clump-p2 hits at all, not even index variant
9285 assert(ln_p1 > ln_p2);
9286 first_bp = UINT32_MAX;
9287 break;
9288 }
9289 }
9290 if (bounds_col) {
9291 *cswritep++ = '\t';
9292 if (first_bp != UINT32_MAX) {
9293 cswritep = u32toa_x(first_bp, '\t', cswritep);
9294 cswritep = u32toa(last_bp, cswritep);
9295 } else {
9296 cswritep = strcpya_k(cswritep, ".\t.");
9297 }
9298 }
9299 }
9300 if (bin_bound_ct) {
9301 if (unlikely(Cswrite(&css, &cswritep))) {
9302 goto ClumpReports_ret_WRITE_FAIL;
9303 }
9304 for (uint32_t bin_idx = bin_bound_ct + 1; bin_idx; ) {
9305 --bin_idx;
9306 *cswritep++ = '\t';
9307 cswritep = wtoa(cur_bin_counts[bin_idx], cswritep);
9308 }
9309 }
9310 if (sp2_col) {
9311 *cswritep++ = '\t';
9312 uint32_t nonempty = 0;
9313 for (uintptr_t member_idx = 0; member_idx != clump_size_including_self; ++member_idx) {
9314 const uintptr_t cur_allele_idx = clump_allele_idxs[member_idx];
9315 const uintptr_t cur_oaidx = RawToSubsettedPosW(observed_alleles, observed_alleles_cumulative_popcounts_w, cur_allele_idx);
9316 const unsigned char* varint_read_iter = clump_entry_varints[cur_oaidx];
9317 const unsigned char* varint_read_end = clump_entry_varints[cur_oaidx + 1];
9318 while (varint_read_iter != varint_read_end) {
9319 const uint32_t pval_too_high = GetVint32Unsafe(&varint_read_iter) & 1;
9320 if (!pval_too_high) {
9321 if (save_all_fidxs) {
9322 const uint32_t file_idx1_x2 = GetVint32Unsafe(&varint_read_iter);
9323 file_idx1 = file_idx1_x2 >> 1;
9324 biallelic_forced_a1_alt = file_idx1_x2 & 1;
9325 }
9326 if ((cur_allele_idx != index_allele_idx) || (file_idx1 != index_file_idx1)) {
9327 if (unlikely(Cswrite(&css, &cswritep))) {
9328 goto ClumpReports_ret_WRITE_FAIL;
9329 }
9330 nonempty = 1;
9331 uintptr_t cur_allele_idx_offset_base;
9332 uint32_t cur_variant_uidx;
9333 if (!allele_idx_offsets) {
9334 cur_variant_uidx = cur_allele_idx / 2;
9335 cur_allele_idx_offset_base = cur_allele_idx & (~k1LU);
9336 } else {
9337 cur_variant_uidx = RawToSubsettedPos(variant_last_alidxs, variant_last_alidxs_cumulative_popcounts, cur_allele_idx);
9338 cur_allele_idx_offset_base = allele_idx_offsets[cur_variant_uidx];
9339 cur_allele_ct = allele_idx_offsets[cur_variant_uidx + 1] - cur_allele_idx_offset_base;
9340 }
9341 cswritep = strcpya(cswritep, variant_ids[cur_variant_uidx]);
9342 if (force_a1 || (cur_allele_ct > 2)) {
9343 *cswritep++ = '(';
9344 cswritep = strcpyax(cswritep, allele_storage[cur_allele_idx + biallelic_forced_a1_alt], ')');
9345 }
9346 if (f_in_sp2) {
9347 *cswritep++ = '(';
9348 cswritep = u32toa_x(file_idx1, ')', cswritep);
9349 }
9350 *cswritep++ = ',';
9351 }
9352 } else {
9353 if (save_all_fidxs) {
9354 SkipVintUnsafe(&varint_read_iter);
9355 }
9356 }
9357 }
9358 }
9359 if (nonempty) {
9360 --cswritep;
9361 } else {
9362 *cswritep++ = '.';
9363 }
9364 }
9365 if (ranges_col) {
9366 *cswritep++ = '\t';
9367 uint32_t nonempty = 0;
9368 if (first_bp != UINT32_MAX) {
9369 const uintptr_t cur_rg_start_idx = rg_chr_bounds[chr_idx];
9370 uint32_t** cur_rg_setdefs = &(rg_setdefs[cur_rg_start_idx]);
9371 const char* cur_rg_names = &(range_group_names[cur_rg_start_idx * max_range_group_id_blen + kMaxChrCodeDigits]);
9372 const uintptr_t cur_rg_ct = rg_chr_bounds[chr_idx + 1] - cur_rg_start_idx;
9373 const uint32_t end_bp = last_bp + 1;
9374 for (uintptr_t rg_idx = 0; rg_idx != cur_rg_ct; ++rg_idx) {
9375 if (IntervalInSetdef(cur_rg_setdefs[rg_idx], first_bp, end_bp)) {
9376 if (unlikely(Cswrite(&css, &cswritep))) {
9377 goto ClumpReports_ret_WRITE_FAIL;
9378 }
9379 nonempty = 1;
9380 cswritep = strcpyax(cswritep, &(cur_rg_names[rg_idx * max_range_group_id_blen]), ',');
9381 }
9382 }
9383 }
9384 if (nonempty) {
9385 --cswritep;
9386 } else {
9387 *cswritep++ = '.';
9388 }
9389 }
9390 AppendBinaryEoln(&cswritep);
9391 if (unlikely(Cswrite(&css, &cswritep))) {
9392 goto ClumpReports_ret_WRITE_FAIL;
9393 }
9394 }
9395
9396 if (unlikely(CswriteCloseNull(&css, cswritep))) {
9397 goto ClumpReports_ret_WRITE_FAIL;
9398 }
9399 logprintf("Results written to %s .\n", outname);
9400 if (clump_overlap_tmp) {
9401 if (unlikely(fclose_null(&clump_overlap_tmp))) {
9402 goto ClumpReports_ret_READ_FAIL;
9403 }
9404 snprintf(outname_end, kMaxOutfnameExtBlen, ".clumps.tmp");
9405 if (unlikely(unlink(outname))) {
9406 goto ClumpReports_ret_WRITE_FAIL;
9407 }
9408 }
9409 }
9410 while (0) {
9411 ClumpReports_ret_NOMEM:
9412 reterr = kPglRetNomem;
9413 break;
9414 ClumpReports_ret_OPEN_FAIL:
9415 reterr = kPglRetOpenFail;
9416 break;
9417 ClumpReports_ret_READ_FAIL:
9418 if (feof_unlocked(clump_overlap_tmp)) {
9419 errno = 0;
9420 }
9421 logerrprintfww(kErrprintfFread, "--clump-allow-overlap temporary file", rstrerror(errno));
9422 reterr = kPglRetReadFail;
9423 break;
9424 ClumpReports_ret_PGR_FAIL:
9425 PgenErrPrintN(reterr);
9426 break;
9427 ClumpReports_ret_WRITE_FAIL:
9428 reterr = kPglRetWriteFail;
9429 break;
9430 ClumpReports_ret_TSTREAM_FAIL:
9431 TextStreamErrPrint("--clump file", &txs);
9432 break;
9433 ClumpReports_ret_MALFORMED_INPUT_WW:
9434 WordWrapB(0);
9435 logerrputsb();
9436 reterr = kPglRetMalformedInput;
9437 break;
9438 ClumpReports_ret_MISSING_TOKENS:
9439 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, fname_iter);
9440 ClumpReports_ret_INCONSISTENT_INPUT_WW:
9441 WordWrapB(0);
9442 logerrputsb();
9443 ClumpReports_ret_INCONSISTENT_INPUT:
9444 reterr = kPglRetInconsistentInput;
9445 break;
9446 ClumpReports_ret_INVALID_PVAL:
9447 logerrprintfww("Error: Invalid p-value on line %" PRIuPTR " of %s.\n", line_idx, fname_iter);
9448 reterr = kPglRetInconsistentInput;
9449 break;
9450 ClumpReports_ret_THREAD_CREATE_FAIL:
9451 reterr = kPglRetThreadCreateFail;
9452 break;
9453 ClumpReports_ret_NOT_YET_SUPPORTED:
9454 reterr = kPglRetNotYetSupported;
9455 break;
9456 }
9457 ClumpReports_ret_1:
9458 CleanupThreads(&tg);
9459 CswriteCloseCond(&css, cswritep);
9460 CleanupTextStream2("--clump file", &txs, &reterr);
9461 fclose_cond(clump_overlap_tmp);
9462 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
9463 pgfip->block_base = nullptr;
9464 return reterr;
9465 }
9466
9467 // indexes here are all subsetted (founder_idx / variant_idx), not sample_uidx
9468 // / variant_uidx.
9469 typedef struct VcorMatrixCtxStruct {
9470 // Shared constants.
9471 const uintptr_t* founder_male_collapsed;
9472 const uintptr_t* founder_nonmale_collapsed;
9473 // invmask is the most useful representation, since we have a bunch of
9474 // dosage-processing functions which interpret 65535 as missing.
9475 const Dosage* male_dosage_invmask;
9476 const Dosage* nonmale_dosage_invmask;
9477 const uint32_t* chr_fo_idx_end;
9478 uint32_t chr_ct;
9479 uint32_t chrx_idx; // UINT32_MAX if not present
9480 uint32_t founder_ct;
9481 uint32_t founder_male_ct;
9482 unsigned char is_unsquared;
9483 unsigned char triangle_calc; // true for both square0 and triangle
9484 unsigned char phase_type;
9485 unsigned char check_dosage;
9486 uint32_t variant_ct;
9487 uintptr_t unpacked_variant_byte_stride;
9488
9489 // Input data.
9490 unsigned char* unpacked_row_variants[2]; // read from [row_parity]
9491 unsigned char* unpacked_col_variants[2]; // read from [col_parity]
9492 uint32_t cur_row_variant_idx_start;
9493 uint32_t row_window_size;
9494 uint32_t cur_col_variant_idx_start;
9495 uint32_t col_window_size;
9496
9497 // per-thread chrX workspaces.
9498 uintptr_t** cur_nm_bufs;
9499 Dosage** invmask_bufs;
9500
9501 // Output double-buffer. write to [row_parity]
9502 double* results_d[2];
9503 float* results_f[2];
9504 } VcorMatrixCtx;
9505
9506 THREAD_FUNC_DECL VcorMatrixThread(void* raw_arg) {
9507 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
9508 const uint32_t tidx = arg->tidx;
9509 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
9510 VcorMatrixCtx* ctx = S_CAST(VcorMatrixCtx*, arg->sharedp->context);
9511 const uintptr_t* founder_male_collapsed = ctx->founder_male_collapsed;
9512 const uintptr_t* founder_nonmale_collapsed = ctx->founder_nonmale_collapsed;
9513 const Dosage* male_dosage_invmask = ctx->male_dosage_invmask;
9514 const Dosage* nonmale_dosage_invmask = ctx->nonmale_dosage_invmask;
9515 uintptr_t* cur_nm_buf = ctx->cur_nm_bufs? ctx->cur_nm_bufs[tidx] : nullptr;
9516 Dosage* invmask_buf = ctx->invmask_bufs? ctx->invmask_bufs[tidx] : nullptr;
9517 const uint32_t* chr_fo_idx_end = ctx->chr_fo_idx_end;
9518 const uint32_t chr_ct = ctx->chr_ct;
9519 const uint32_t chrx_idx = ctx->chrx_idx;
9520 const uint32_t x_exists = (chrx_idx < UINT32_MAXM1);
9521 const uint32_t founder_ct = ctx->founder_ct;
9522 const uint32_t founder_male_ct = ctx->founder_male_ct;
9523 const uint32_t is_unsquared = ctx->is_unsquared;
9524 const uint32_t triangle_calc = ctx->triangle_calc;
9525 const R2PhaseType unpack_phase_type = S_CAST(R2PhaseType, ctx->phase_type);
9526 const uint32_t check_dosage = ctx->check_dosage;
9527 const uintptr_t variant_ct = ctx->variant_ct;
9528 const uintptr_t unpacked_variant_byte_stride = ctx->unpacked_variant_byte_stride;
9529 // only flips when moving to next row-window. detect this with
9530 // (cur_col_variant_idx_start == 0).
9531 // initialize to 1 instead of 0 so we don't need to special-case first row.
9532 uint32_t row_parity = 1;
9533
9534 // always flips
9535 uint32_t col_parity = 0;
9536 do {
9537 const uint32_t cur_row_variant_idx_start = ctx->cur_row_variant_idx_start;
9538 const uint32_t cur_col_variant_idx_start = ctx->cur_col_variant_idx_start;
9539 if (cur_col_variant_idx_start == 0) {
9540 row_parity = 1 - row_parity;
9541 }
9542 const uint64_t row_window_size = ctx->row_window_size;
9543 const uint32_t row_start_offset = (row_window_size * tidx) / calc_thread_ct;
9544 const uint32_t row_end_offset = (row_window_size * (tidx + 1)) / calc_thread_ct;
9545 const uintptr_t shard_row_variant_idx_end = cur_row_variant_idx_start + row_end_offset;
9546 uintptr_t shard_row_variant_idx_start = cur_row_variant_idx_start + row_start_offset;
9547 uint64_t start_coord;
9548 if (triangle_calc) {
9549 start_coord = (cur_row_variant_idx_start * S_CAST(uint64_t, cur_row_variant_idx_start + 1)) / 2;
9550 if (cur_col_variant_idx_start > shard_row_variant_idx_start) {
9551 // shards are rectangle-shaped. we're computing the lower-left
9552 // half-triangle of the matrix.
9553 // so shards closer to the upper-right may have truncated or even empty
9554 // intersection with the region we're computing.
9555 shard_row_variant_idx_start = cur_col_variant_idx_start;
9556 }
9557 } else {
9558 start_coord = cur_row_variant_idx_start * S_CAST(uint64_t, variant_ct);
9559 }
9560 if (shard_row_variant_idx_end > shard_row_variant_idx_start) {
9561 const unsigned char* unpacked_row_variants_iter = &(ctx->unpacked_row_variants[row_parity][row_start_offset * unpacked_variant_byte_stride]);
9562 const unsigned char* unpacked_col_variants = ctx->unpacked_col_variants[col_parity];
9563 double* results_d = ctx->results_d[row_parity];
9564 float* results_f = ctx->results_f[row_parity];
9565 double* results_d_row = nullptr;
9566 float* results_f_row = nullptr;
9567 const uint32_t col_initial_chr_idx = LowerBoundNonemptyU32(chr_fo_idx_end, chr_ct, cur_col_variant_idx_start + 1);
9568 uint32_t row_chr_idx = LowerBoundNonemptyU32(chr_fo_idx_end, chr_ct, shard_row_variant_idx_start + 1);
9569 uint32_t row_chr_end = chr_fo_idx_end[row_chr_idx];
9570 uint32_t row_is_chrx = (row_chr_idx == chrx_idx);
9571 const uint32_t shard_col_variant_idx_end = cur_col_variant_idx_start + ctx->col_window_size;
9572 uint32_t col_variant_idx_stop = shard_col_variant_idx_end;
9573 for (uint32_t row_variant_idx = shard_row_variant_idx_start; row_variant_idx != shard_row_variant_idx_end; ++row_variant_idx, unpacked_row_variants_iter = &(unpacked_row_variants_iter[unpacked_variant_byte_stride])) {
9574 if (row_variant_idx == row_chr_end) {
9575 ++row_chr_idx;
9576 row_chr_end = chr_fo_idx_end[row_chr_idx];
9577 row_is_chrx = (row_chr_idx == chrx_idx);
9578 }
9579 uint64_t row_start_coord;
9580 if (triangle_calc) {
9581 row_start_coord = (row_variant_idx * S_CAST(uint64_t, row_variant_idx + 1)) / 2;
9582 col_variant_idx_stop = MINV(row_variant_idx + 1, shard_col_variant_idx_end);
9583 } else {
9584 row_start_coord = row_variant_idx * S_CAST(uint64_t, variant_ct);
9585 }
9586 {
9587 const uintptr_t row_start_coord_offset = row_start_coord - start_coord;
9588 if (results_d) {
9589 results_d_row = &(results_d[row_start_coord_offset]);
9590 } else {
9591 results_f_row = &(results_f[row_start_coord_offset]);
9592 }
9593 }
9594 R2Variant row_r2v;
9595 FillR2V(unpacked_row_variants_iter, founder_ct, unpack_phase_type, x_exists, check_dosage, &row_r2v);
9596 uint32_t col_chr_idx = col_initial_chr_idx;
9597 uint32_t col_chr_end = chr_fo_idx_end[col_chr_idx];
9598 uint32_t col_is_chrx = (col_chr_idx == chrx_idx);
9599 uint32_t either_is_chrx = row_is_chrx || col_is_chrx;
9600 uint32_t same_chr = (row_chr_idx == col_chr_idx);
9601 R2PhaseType compare_phase_type = same_chr? unpack_phase_type : R2PhaseOmit(unpack_phase_type);
9602 const unsigned char* unpacked_col_variants_iter = unpacked_col_variants;
9603 for (uint32_t col_variant_idx = cur_col_variant_idx_start; col_variant_idx != col_variant_idx_stop; ++col_variant_idx, unpacked_col_variants_iter = &(unpacked_col_variants_iter[unpacked_variant_byte_stride])) {
9604 if (col_variant_idx == col_chr_end) {
9605 ++col_chr_idx;
9606 col_chr_end = chr_fo_idx_end[col_chr_idx];
9607 col_is_chrx = (col_chr_idx == chrx_idx);
9608 either_is_chrx = row_is_chrx || col_is_chrx;
9609 same_chr = (row_chr_idx == col_chr_idx);
9610 compare_phase_type = same_chr? unpack_phase_type : R2PhaseOmit(unpack_phase_type);
9611 }
9612 R2Variant col_r2v;
9613 FillR2V(unpacked_col_variants_iter, founder_ct, unpack_phase_type, either_is_chrx, check_dosage, &col_r2v);
9614 double result;
9615 uint32_t is_neg;
9616 if (!either_is_chrx) {
9617 result = ComputeR2(&row_r2v, &col_r2v, founder_ct, compare_phase_type, check_dosage, nullptr, nullptr, &is_neg);
9618 } else {
9619 result = ComputeXR2(&row_r2v, &col_r2v, founder_male_collapsed, founder_nonmale_collapsed, male_dosage_invmask, nonmale_dosage_invmask, founder_ct, founder_male_ct, compare_phase_type, check_dosage, same_chr, nullptr, nullptr, &is_neg, cur_nm_buf, invmask_buf);
9620 }
9621 if (result == -DBL_MAX) {
9622 result = 0.0 / 0.0;
9623 } else if (is_unsquared) {
9624 result = sqrt(result);
9625 if (is_neg) {
9626 result = -result;
9627 }
9628 }
9629 if (results_d_row) {
9630 results_d_row[col_variant_idx] = result;
9631 } else {
9632 results_f_row[col_variant_idx] = S_CAST(float, result);
9633 }
9634 }
9635 }
9636 }
9637 col_parity = 1 - col_parity;
9638 } while (!THREAD_BLOCK_FINISH(arg));
9639 THREAD_RETURN;
9640 }
9641
9642 typedef struct VcorMatrixWriteCtxStruct {
9643 unsigned char* zbuf;
9644 VcorFlags flags;
9645 uint32_t orig_variant_ct;
9646
9647 uint32_t cur_row_variant_idx_start;
9648 uint32_t row_window_size;
9649
9650 double* results_d[2];
9651 float* results_f[2];
9652
9653 FILE* outfile;
9654 CompressStreamState css;
9655 char* cswritep;
9656
9657 PglErr reterr;
9658 } VcorMatrixWriteCtx;
9659
9660 THREAD_FUNC_DECL VcorMatrixWriteThread(void* raw_arg) {
9661 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
9662 VcorMatrixWriteCtx* ctx = S_CAST(VcorMatrixWriteCtx*, arg->sharedp->context);
9663 const unsigned char* zbuf = ctx->zbuf;
9664 const VcorFlags flags = ctx->flags;
9665 const uintptr_t orig_variant_ct = ctx->orig_variant_ct;
9666 const uint32_t triangle_calc = ((flags & (kfVcorMatrixSq0 | kfVcorMatrixTri)) != 0);
9667 const uint32_t is_square0 = (flags / kfVcorMatrixSq0) & 1;
9668 const uint32_t is_bin = ((flags & (kfVcorBin8 | kfVcorBin4)) != 0);
9669 const uint32_t is_bin4 = (flags / kfVcorBin4) & 1;
9670 uint32_t row_parity = 0;
9671 do {
9672 double* cur_results_d_iter = ctx->results_d[row_parity];
9673 const uintptr_t row_idx_start = ctx->cur_row_variant_idx_start;
9674 const uintptr_t row_window_size = ctx->row_window_size;
9675 if (is_bin) {
9676 FILE* outfile = ctx->outfile;
9677 if (is_bin4) {
9678 float* cur_results_f_iter = ctx->results_f[row_parity];
9679 if (is_square0) {
9680 const uintptr_t row_idx_stop = row_idx_start + row_window_size;
9681 for (uintptr_t row_idx_p1 = row_idx_start + 1; row_idx_p1 <= row_idx_stop; ++row_idx_p1) {
9682 if (unlikely(fwrite_checked(cur_results_f_iter, row_idx_p1 * sizeof(float), outfile) ||
9683 fwrite_checked(zbuf, (orig_variant_ct - row_idx_p1) * sizeof(float), outfile))) {
9684 goto VcorMatrixWriteThread_ret_WRITE_FAIL;
9685 }
9686 cur_results_f_iter = &(cur_results_f_iter[row_idx_p1]);
9687 }
9688 } else {
9689 uintptr_t entry_ct;
9690 if (triangle_calc) {
9691 entry_ct = ((row_idx_start * 2 + row_window_size + 1) * row_window_size) / 2;
9692 } else {
9693 entry_ct = row_window_size * orig_variant_ct;
9694 }
9695 if (unlikely(fwrite_checked(cur_results_f_iter, entry_ct * sizeof(float), outfile))) {
9696 goto VcorMatrixWriteThread_ret_WRITE_FAIL;
9697 }
9698 }
9699 } else {
9700 if (is_square0) {
9701 const uintptr_t row_idx_stop = row_idx_start + row_window_size;
9702 for (uintptr_t row_idx_p1 = row_idx_start + 1; row_idx_p1 <= row_idx_stop; ++row_idx_p1) {
9703 if (unlikely(fwrite_checked(cur_results_d_iter, row_idx_p1 * sizeof(double), outfile) ||
9704 fwrite_checked(zbuf, (orig_variant_ct - row_idx_p1) * sizeof(double), outfile))) {
9705 goto VcorMatrixWriteThread_ret_WRITE_FAIL;
9706 }
9707 cur_results_d_iter = &(cur_results_d_iter[row_idx_p1]);
9708 }
9709 } else {
9710 uintptr_t entry_ct;
9711 if (triangle_calc) {
9712 entry_ct = ((row_idx_start * 2 + row_window_size + 1) * row_window_size) / 2;
9713 } else {
9714 entry_ct = row_window_size * orig_variant_ct;
9715 }
9716 if (unlikely(fwrite_checked(cur_results_d_iter, entry_ct * sizeof(double), outfile))) {
9717 goto VcorMatrixWriteThread_ret_WRITE_FAIL;
9718 }
9719 }
9720 }
9721 } else {
9722 char* cswritep = ctx->cswritep;
9723 CompressStreamState* cssp = &(ctx->css);
9724 const uintptr_t row_idx_stop = row_idx_start + row_window_size;
9725 uintptr_t col_idx_stop = triangle_calc? (row_idx_start + 1) : orig_variant_ct;
9726 for (uintptr_t row_idx = row_idx_start; row_idx != row_idx_stop; ++row_idx) {
9727 for (uintptr_t col_idx = 0; col_idx != col_idx_stop; ++col_idx) {
9728 cswritep = dtoa_g(*cur_results_d_iter++, cswritep);
9729 *cswritep++ = '\t';
9730 }
9731 if (triangle_calc) {
9732 if (is_square0) {
9733 AppendZerotabsUnsafe(orig_variant_ct - col_idx_stop, &cswritep);
9734 }
9735 ++col_idx_stop;
9736 }
9737 --cswritep;
9738 AppendBinaryEoln(&cswritep);
9739 if (unlikely(Cswrite(cssp, &cswritep))) {
9740 goto VcorMatrixWriteThread_ret_WRITE_FAIL;
9741 }
9742 }
9743 ctx->cswritep = cswritep;
9744 }
9745 row_parity = 1 - row_parity;
9746 while (0) {
9747 VcorMatrixWriteThread_ret_WRITE_FAIL:
9748 ctx->reterr = kPglRetWriteFail;
9749 }
9750 } while (!THREAD_BLOCK_FINISH(arg));
9751 THREAD_RETURN;
9752 }
9753
9754 PglErr VcorMatrix(const uintptr_t* orig_variant_include, const ChrInfo* cip, const char* const* variant_ids, const AlleleCode* maj_alleles, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const VcorInfo* vcip, const char* flagname, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
9755 // todo: take a real look at BLIS
9756 // todo: if we can't just rework the whole function around BLIS, try using
9757 // dsyrk() for just the unphased, dosage-present, no-missing-genotype,
9758 // no-chrX-mixed-sex, no-chrY-nonmale case (see CalcGrm[Part]Thread())
9759 unsigned char* bigstack_mark = g_bigstack_base;
9760 unsigned char* bigstack_end_mark = g_bigstack_end;
9761 PglErr reterr = kPglRetSuccess;
9762 VcorMatrixCtx ctx;
9763 VcorMatrixWriteCtx write_ctx;
9764 ThreadGroup tg;
9765 ThreadGroup write_tg;
9766 write_ctx.outfile = nullptr;
9767 PreinitCstream(&write_ctx.css);
9768 write_ctx.cswritep = nullptr;
9769 PreinitThreads(&tg);
9770 PreinitThreads(&write_tg);
9771 {
9772 // Don't want to do much shared initialization with VcorTable() upfront,
9773 // since chrX/chrY presence may be affected by
9774 // --ld-snp/--ld-snps/--ld-snp-list
9775 const VcorFlags flags = vcip->flags;
9776 if (unlikely((orig_variant_ct > 400000) && (parallel_tot == 1) && (!(flags & kfVcorYesReally)))) {
9777 logerrprintfww("Error: Gigantic (over 400k variants) %s unfiltered, non-distributed computation. Rerun with the 'yes-really' modifier if you are SURE you have enough hard drive space and want to do this.\n", flagname);
9778 goto VcorMatrix_ret_INCONSISTENT_INPUT;
9779 }
9780 const uint32_t triangle_calc = ((flags & (kfVcorMatrixSq0 | kfVcorMatrixTri)) != 0);
9781 const uint32_t first_variant_uidx = FindNth1BitFrom(orig_variant_include, 0, 1);
9782 uint32_t row_variant_uidx_start = first_variant_uidx;
9783 uint32_t row_variant_idx_start = 0;
9784 uint32_t row_variant_idx_stop = orig_variant_ct;
9785 uint32_t variant_uidx_stop = raw_variant_ct;
9786 uint32_t variant_ct = orig_variant_ct;
9787 const uintptr_t* variant_include = orig_variant_include;
9788 if (parallel_tot != 1) {
9789 if (unlikely(variant_ct < 2 * parallel_tot)) {
9790 logerrprintf("Error: Too few variants in %s run for --parallel %u %u.\n", flagname, parallel_idx + 1, parallel_tot);
9791 goto VcorMatrix_ret_INCONSISTENT_INPUT;
9792 }
9793 if (triangle_calc) {
9794 ParallelBounds(variant_ct, 0, parallel_idx, parallel_tot, R_CAST(int32_t*, &row_variant_idx_start), R_CAST(int32_t*, &row_variant_idx_stop));
9795 if (row_variant_idx_stop != variant_ct) {
9796 // Outside of square0's zero-padding, we can just act as if there are
9797 // fewer variants.
9798 // (though we need to be a bit careful with chrX/chrY check)
9799 variant_ct = row_variant_idx_stop;
9800 variant_uidx_stop = 1 + FindNth1BitFrom(variant_include, 0, variant_ct);
9801 const uint32_t variant_uidx_stopl = BitCtToWordCt(variant_uidx_stop);
9802 uintptr_t* new_variant_include;
9803 if (unlikely(bigstack_alloc_w(variant_uidx_stopl, &new_variant_include))) {
9804 goto VcorMatrix_ret_INCONSISTENT_INPUT;
9805 }
9806 memcpy(new_variant_include, variant_include, variant_uidx_stopl * sizeof(intptr_t));
9807 ZeroTrailingBits(variant_uidx_stop, new_variant_include);
9808 variant_include = new_variant_include;
9809 }
9810 } else {
9811 row_variant_idx_start = (S_CAST(uint64_t, variant_ct) * parallel_idx) / parallel_tot;
9812 row_variant_idx_stop = (S_CAST(uint64_t, variant_ct) * (parallel_idx + 1)) / parallel_tot;
9813 }
9814 if (row_variant_idx_start) {
9815 row_variant_uidx_start = FindNth1BitFrom(variant_include, first_variant_uidx, 1 + row_variant_idx_start);
9816 }
9817 }
9818
9819 const uint32_t phased_calc = (flags / kfVcorPhased) & 1;
9820 const uint32_t is_unsquared = (flags / kfVcorUnsquared) & 1;
9821 const uint32_t is_bin = ((flags & (kfVcorBin8 | kfVcorBin4)) != 0);
9822 const uint32_t is_bin4 = (flags / kfVcorBin4) & 1;
9823 const uint32_t matrix_output_zst = (flags / kfVcorZs) & 1;
9824 {
9825 write_ctx.zbuf = nullptr;
9826 if ((flags & kfVcorMatrixSq0) && is_bin) {
9827 const uintptr_t max_zeroes_needed = orig_variant_ct + 1 - row_variant_idx_start;
9828 const uintptr_t max_zerobytes_needed = (2 - is_bin4) * 4 * max_zeroes_needed;
9829 if (bigstack_alloc_uc(max_zerobytes_needed, &write_ctx.zbuf)) {
9830 goto VcorMatrix_ret_NOMEM;
9831 }
9832 memset(write_ctx.zbuf, 0, max_zerobytes_needed);
9833 }
9834
9835 // Write .vars file (unless parallel_idx > 0), and initialize main
9836 // filename
9837 char* outname_write_iter = outname_end;
9838 *outname_write_iter++ = '.';
9839 if (!phased_calc) {
9840 outname_write_iter = strcpya_k(outname_write_iter, "un");
9841 }
9842 outname_write_iter = strcpya_k(outname_write_iter, "phased.vcor");
9843 *outname_write_iter++ = '2' - is_unsquared;
9844 if (is_bin) {
9845 outname_write_iter = strcpya_k(outname_write_iter, ".bin");
9846 }
9847
9848 if (parallel_idx == 0) {
9849 strcpy_k(outname_write_iter, ".vars");
9850 // this is never .zst-compressed since, if it's large enough for that
9851 // to matter, the matrix itself is ridiculously large
9852 if (fopen_checked(outname, FOPEN_WB, &write_ctx.outfile)) {
9853 goto VcorMatrix_ret_OPEN_FAIL;
9854 }
9855 // variant IDs limited to 16k chars
9856 char* write_iter = g_textbuf;
9857 char* write_flush = &(g_textbuf[kMaxMediumLine]);
9858 uintptr_t variant_uidx_base = 0;
9859 uintptr_t cur_bits = variant_include[0];
9860 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) {
9861 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
9862 write_iter = strcpya(write_iter, variant_ids[variant_uidx]);
9863 AppendBinaryEoln(&write_iter);
9864 if (unlikely(fwrite_ck(write_flush, write_ctx.outfile, &write_iter))) {
9865 goto VcorMatrix_ret_WRITE_FAIL;
9866 }
9867 }
9868 if (fclose_flush_null(write_flush, write_iter, &write_ctx.outfile)) {
9869 goto VcorMatrix_ret_WRITE_FAIL;
9870 }
9871 logprintfww("%s: Variant IDs written to %s .\n", flagname, outname);
9872 }
9873 if (parallel_tot != 1) {
9874 *outname_write_iter++ = '.';
9875 outname_write_iter = u32toa(parallel_idx + 1, outname_write_iter);
9876 }
9877 if (matrix_output_zst) {
9878 outname_write_iter = strcpya_k(outname_write_iter, ".zst");
9879 }
9880 *outname_write_iter = '\0';
9881 }
9882
9883 if (is_bin) {
9884 if (fopen_checked(outname, FOPEN_WB, &write_ctx.outfile)) {
9885 goto VcorMatrix_ret_OPEN_FAIL;
9886 }
9887 } else {
9888 const uintptr_t overflow_buf_size = kCompressStreamBlock + (kMaxDoubleGSlen + 1) * variant_ct + strlen(EOLN_STR) - 1;
9889 uint32_t compress_thread_ct = 1;
9890 if ((!phased_calc) && (max_thread_ct > 4) && (founder_ct <= 8192)) {
9891 compress_thread_ct = 2 + ((max_thread_ct > 8) && (founder_ct <= 4096));
9892 }
9893 reterr = InitCstreamAlloc(outname, 0, matrix_output_zst, compress_thread_ct, overflow_buf_size, &write_ctx.css, &write_ctx.cswritep);
9894 if (unlikely(reterr)) {
9895 goto VcorMatrix_ret_1;
9896 }
9897 }
9898
9899 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9900 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
9901 const uint32_t founder_ctv = BitCtToVecCt(founder_ct);
9902 const uint32_t founder_ctv2 = NypCtToVecCt(founder_ct);
9903 const uint32_t founder_ctaw = founder_ctv * kWordsPerVec;
9904 const uint32_t founder_male_ct = PopcountWordsIntersect(founder_info, sex_male, raw_sample_ctl);
9905 const uint32_t all_haploid = IsSet(cip->haploid_mask, 0);
9906 PgenGlobalFlags effective_gflags = PgrGetGflags(simple_pgrp) & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
9907 if (variant_ct < variant_uidx_stop) {
9908 effective_gflags &= GflagsVfilter(variant_include, PgrGetVrtypes(simple_pgrp), variant_uidx_stop, effective_gflags);
9909 }
9910 const uint32_t check_phase = phased_calc && (!all_haploid) && (effective_gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent));
9911 if (!check_phase) {
9912 effective_gflags &= kfPgenGlobalDosagePresent;
9913 }
9914 const R2PhaseType phase_type = GetR2PhaseType(phased_calc, check_phase);
9915 const uint32_t check_dosage = (effective_gflags / kfPgenGlobalDosagePresent) & 1;
9916
9917 uintptr_t* raregeno = nullptr;
9918 uint32_t* difflist_sample_ids = nullptr;
9919 const uint32_t max_simple_difflist_len = founder_ct / 64;
9920 if (!phased_calc) {
9921 const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
9922 if (unlikely(bigstack_alloc_w(NypCtToWordCt(max_returned_difflist_len), &raregeno) ||
9923 bigstack_alloc_u32(max_returned_difflist_len, &difflist_sample_ids))) {
9924 goto VcorMatrix_ret_NOMEM;
9925 }
9926 }
9927
9928 // create abbreviated chromosome-view for use by worker threads.
9929 // they may need to know where each chromosome starts/ends (use phase or
9930 // not?), and which chromosome is X; that's it
9931 uint32_t x_code = UINT32_MAX;
9932 uint32_t x_fo_idx = UINT32_MAX;
9933 // if all-males, we can ignore phase on chrX, as well as skipping
9934 // male/nonmale-specific stats
9935 // if all-nonmales, we initialize x_code to prevent phase from being
9936 // ignored, but can skip the male/nonmale-specific stats
9937 if (founder_male_ct != founder_ct) {
9938 if (XymtExists(cip, kChrOffsetX, &x_code) && (founder_male_ct != 0)) {
9939 x_fo_idx = cip->chr_idx_to_foidx[x_code];
9940 }
9941 }
9942 const uintptr_t* founder_male_collapsed = nullptr;
9943 const Dosage* male_dosage_invmask = nullptr;
9944 ctx.founder_nonmale_collapsed = nullptr;
9945 ctx.nonmale_dosage_invmask = nullptr;
9946 {
9947 const uint32_t chr_ct = cip->chr_ct;
9948 uint32_t* chr_fo_idx_end;
9949 if (bigstack_alloc_u32(chr_ct, &chr_fo_idx_end)) {
9950 goto VcorMatrix_ret_NOMEM;
9951 }
9952 // not quite the same as FillSubsetChrFoVidxStart since we prune
9953 // now-empty chromosomes. may want to have this logic in plink2_common
9954 // too
9955 uint32_t new_chr_ct = 0;
9956 uint32_t chr_variant_uidx_start = 0;
9957 uint32_t chr_variant_idx_start = 0;
9958 ctx.chrx_idx = UINT32_MAX;
9959 for (uint32_t chr_fo_idx = 0; chr_variant_idx_start < variant_ct; ++chr_fo_idx) {
9960 uint32_t chr_variant_uidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
9961 if (chr_variant_uidx_end > variant_uidx_stop) {
9962 chr_variant_uidx_end = variant_uidx_stop;
9963 }
9964 const uint32_t chr_variant_ct = PopcountBitRange(variant_include, chr_variant_uidx_start, chr_variant_uidx_end);
9965 if (chr_variant_ct) {
9966 if (chr_fo_idx == x_fo_idx) {
9967 ctx.chrx_idx = new_chr_ct;
9968 }
9969 const uint32_t chr_variant_idx_end = chr_variant_idx_start + chr_variant_ct;
9970 chr_fo_idx_end[new_chr_ct++] = chr_variant_idx_end;
9971 chr_variant_idx_start = chr_variant_idx_end;
9972 }
9973 chr_variant_uidx_start = chr_variant_uidx_end;
9974 }
9975 assert(chr_variant_idx_start == variant_ct);
9976 ctx.chr_ct = new_chr_ct;
9977 BigstackShrinkTop(chr_fo_idx_end, new_chr_ct * sizeof(int32_t));
9978 ctx.chr_fo_idx_end = chr_fo_idx_end;
9979 if (ctx.chrx_idx != UINT32_MAX) {
9980 uintptr_t* founder_male_collapsed_fill;
9981 uintptr_t* founder_nonmale_collapsed;
9982 if (unlikely(bigstack_alloc_w(founder_ctl, &founder_male_collapsed_fill) ||
9983 bigstack_alloc_w(founder_ctl, &founder_nonmale_collapsed))) {
9984 goto VcorMatrix_ret_NOMEM;
9985 }
9986 CopyBitarrSubset(sex_male, founder_info, founder_ct, founder_male_collapsed_fill);
9987 founder_male_collapsed = founder_male_collapsed_fill;
9988 BitvecInvertCopy(founder_male_collapsed, founder_ctl, founder_nonmale_collapsed);
9989 ZeroTrailingBits(founder_ct, founder_nonmale_collapsed);
9990 ctx.founder_nonmale_collapsed = founder_nonmale_collapsed;
9991 if (check_dosage) {
9992 const uint32_t founder_ctad = RoundUpPow2(founder_ct, kDosagePerVec);
9993 Dosage* male_dosage_invmask_fill;
9994 Dosage* nonmale_dosage_invmask;
9995 if (bigstack_alloc_dosage(founder_ctad, &male_dosage_invmask_fill) ||
9996 bigstack_alloc_dosage(founder_ctad, &nonmale_dosage_invmask)) {
9997 goto VcorMatrix_ret_NOMEM;
9998 }
9999 Expand1bitTo16(founder_male_collapsed, founder_ctad, 0xffff, male_dosage_invmask_fill);
10000 Expand1bitTo16(founder_nonmale_collapsed, founder_ctad, 0xffff, nonmale_dosage_invmask);
10001 male_dosage_invmask = male_dosage_invmask_fill;
10002 ctx.nonmale_dosage_invmask = nonmale_dosage_invmask;
10003 }
10004 }
10005 }
10006 const uint32_t x_exists = (ctx.chrx_idx < UINT32_MAXM1);
10007 ctx.founder_male_collapsed = founder_male_collapsed;
10008 ctx.male_dosage_invmask = male_dosage_invmask;
10009
10010 uint32_t y_start;
10011 uint32_t y_end;
10012 GetXymtStartAndEnd(cip, kChrOffsetY, &y_start, &y_end);
10013 uintptr_t* founder_female_collapsed = nullptr;
10014 uintptr_t* founder_female_collapsed_interleaved = nullptr;
10015 if (y_end) {
10016 if (y_end > variant_uidx_stop) {
10017 y_end = variant_uidx_stop;
10018 }
10019 if ((founder_male_ct == founder_ct) || (y_start >= variant_uidx_stop) || AllBitsAreZero(variant_include, y_start, y_end)) {
10020 y_start = 0;
10021 y_end = 0;
10022 }
10023 if (y_end) {
10024 uintptr_t* founder_female;
10025 if (bigstack_end_alloc_w(raw_sample_ctl, &founder_female)) {
10026 goto VcorMatrix_ret_NOMEM;
10027 }
10028 BitvecInvmaskCopy(sex_nm, sex_male, raw_sample_ctl, founder_female);
10029 BitvecAnd(founder_info, raw_sample_ctl, founder_female);
10030 if (AllWordsAreZero(founder_female, raw_sample_ctl)) {
10031 y_start = 0;
10032 y_end = 0;
10033 } else {
10034 if (bigstack_alloc_w(founder_ctaw, &founder_female_collapsed) ||
10035 bigstack_alloc_w(founder_ctaw, &founder_female_collapsed_interleaved)) {
10036 goto VcorMatrix_ret_NOMEM;
10037 }
10038 CopyBitarrSubset(founder_female, founder_info, founder_ct, founder_female_collapsed);
10039 ZeroTrailingWords(founder_ctl, founder_female_collapsed);
10040 FillInterleavedMaskVec(founder_female_collapsed, founder_ctv, founder_female_collapsed_interleaved);
10041 }
10042 BigstackEndReset(bigstack_end_mark);
10043 }
10044 }
10045 ctx.founder_ct = founder_ct;
10046 ctx.founder_male_ct = founder_male_ct;
10047 ctx.is_unsquared = is_unsquared;
10048 ctx.triangle_calc = triangle_calc;
10049
10050 const uintptr_t bitvec_byte_ct = BitCtToVecCt(founder_ct) * kBytesPerVec;
10051 uintptr_t dosagevec_byte_ct = 0;
10052 uintptr_t unpacked_variant_byte_stride;
10053 if (check_dosage) {
10054 dosagevec_byte_ct = DivUp(founder_ct, kDosagePerVec) * kBytesPerVec;
10055 const uintptr_t dosage_trail_byte_ct = LdDosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_calc), x_exists);
10056 unpacked_variant_byte_stride = dosagevec_byte_ct * (1 + phased_calc + check_phase) + bitvec_byte_ct + dosage_trail_byte_ct;
10057 } else {
10058 unpacked_variant_byte_stride = RoundUpPow2(16, kBytesPerVec) + bitvec_byte_ct * (3 + 2 * check_phase);
10059 #ifndef USE_AVX2
10060 const uintptr_t sparse_req = RoundUpPow2((6 + max_simple_difflist_len) * sizeof(int32_t), kBytesPerVec) + NypCtToVecCt(max_simple_difflist_len) * kBytesPerVec + RoundUpPow2(founder_ctl * (kBytesPerWord + sizeof(int32_t)), kBytesPerVec);
10061 if (sparse_req > unpacked_variant_byte_stride) {
10062 unpacked_variant_byte_stride = sparse_req;
10063 }
10064 #endif
10065 const uintptr_t nondosage_trail_byte_ct = LdNondosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_calc), x_exists);
10066 unpacked_variant_byte_stride += nondosage_trail_byte_ct;
10067 }
10068 uint32_t* founder_info_cumulative_popcounts;
10069 PgenVariant pgv;
10070 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &founder_info_cumulative_popcounts) ||
10071 BigstackAllocPgv(founder_ct, 0, effective_gflags, &pgv))) {
10072 goto VcorMatrix_ret_NOMEM;
10073 }
10074 FillCumulativePopcounts(founder_info, raw_sample_ctl, founder_info_cumulative_popcounts);
10075 PgrSampleSubsetIndex pssi;
10076 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
10077
10078 ctx.phase_type = phase_type;
10079 ctx.check_dosage = check_dosage;
10080 ctx.variant_ct = variant_ct;
10081 ctx.unpacked_variant_byte_stride = unpacked_variant_byte_stride;
10082
10083 // Determine row-window size. Byte cost of each row-window variant:
10084 // unpacked_variant_byte_stride for preprocessed variant data
10085 // variant_ct * 4 * (2 - is_bin4) for results (this is an overestimate
10086 // for triangle case)
10087 // Assign up to ~half of remaining memory to this (ok to overshoot
10088 // slightly).
10089 uint32_t usual_row_window_size = row_variant_idx_stop - row_variant_idx_start;
10090 uint32_t calc_thread_ct = max_thread_ct - (max_thread_ct > 4) - (max_thread_ct > 8);
10091 if (calc_thread_ct > usual_row_window_size) {
10092 calc_thread_ct = usual_row_window_size;
10093 }
10094 ctx.cur_nm_bufs = nullptr;
10095 ctx.invmask_bufs = nullptr;
10096 if (ctx.chrx_idx != UINT32_MAX) {
10097 if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.cur_nm_bufs))) {
10098 goto VcorMatrix_ret_NOMEM;
10099 }
10100 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
10101 if (unlikely(bigstack_alloc_w(founder_ctl, &(ctx.cur_nm_bufs[tidx])))) {
10102 goto VcorMatrix_ret_NOMEM;
10103 }
10104 }
10105 if (check_dosage) {
10106 if (unlikely(bigstack_alloc_dosagep(calc_thread_ct, &ctx.invmask_bufs))) {
10107 goto VcorMatrix_ret_NOMEM;
10108 }
10109 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
10110 // allocation automatically rounded up to at least end of vector
10111 if (unlikely(bigstack_alloc_dosage(founder_ct, &(ctx.invmask_bufs[tidx])))) {
10112 goto VcorMatrix_ret_NOMEM;
10113 }
10114 }
10115 }
10116 }
10117 {
10118 const uintptr_t row_byte_cost = unpacked_variant_byte_stride + variant_ct * (4 * k1LU) * (2 - is_bin4);
10119 const uintptr_t row_capacity = bigstack_left() / (4 * row_byte_cost);
10120 if (row_capacity < usual_row_window_size) {
10121 // If multipass, may as well make usual_row_window_size a multiple of
10122 // thread_ct.
10123 if (row_capacity < calc_thread_ct) {
10124 calc_thread_ct = row_capacity;
10125 }
10126 const uint32_t thread_workload = row_capacity / calc_thread_ct;
10127 if (unlikely(!thread_workload)) {
10128 goto VcorMatrix_ret_NOMEM;
10129 }
10130 usual_row_window_size = thread_workload * calc_thread_ct;
10131 }
10132 }
10133 ctx.cur_row_variant_idx_start = row_variant_idx_start;
10134 ctx.row_window_size = usual_row_window_size;
10135 if (unlikely(bigstack_alloc_uc(usual_row_window_size * unpacked_variant_byte_stride, &(ctx.unpacked_row_variants[0])) ||
10136 bigstack_alloc_uc(usual_row_window_size * unpacked_variant_byte_stride, &(ctx.unpacked_row_variants[1])))) {
10137 goto VcorMatrix_ret_NOMEM;
10138 }
10139 {
10140 const uintptr_t slot_ct = usual_row_window_size * variant_ct;
10141 if (is_bin4) {
10142 if (unlikely(bigstack_alloc_f(slot_ct, &(ctx.results_f[0])) ||
10143 bigstack_alloc_f(slot_ct, &(ctx.results_f[1])))) {
10144 goto VcorMatrix_ret_NOMEM;
10145 }
10146 ctx.results_d[0] = nullptr;
10147 ctx.results_d[1] = nullptr;
10148 } else {
10149 if (unlikely(bigstack_alloc_d(slot_ct, &(ctx.results_d[0])) ||
10150 bigstack_alloc_d(slot_ct, &(ctx.results_d[1])))) {
10151 goto VcorMatrix_ret_NOMEM;
10152 }
10153 ctx.results_f[0] = nullptr;
10154 ctx.results_f[1] = nullptr;
10155 }
10156 }
10157 write_ctx.flags = flags;
10158 write_ctx.orig_variant_ct = orig_variant_ct;
10159 write_ctx.row_window_size = usual_row_window_size;
10160 write_ctx.results_d[0] = ctx.results_d[0];
10161 write_ctx.results_d[1] = ctx.results_d[1];
10162 write_ctx.results_f[0] = ctx.results_f[0];
10163 write_ctx.results_f[1] = ctx.results_f[1];
10164 write_ctx.reterr = kPglRetSuccess;
10165 if (unlikely(SetThreadCt(1, &write_tg))) {
10166 goto VcorMatrix_ret_NOMEM;
10167 }
10168 SetThreadFuncAndData(VcorMatrixWriteThread, &write_ctx, &write_tg);
10169
10170 uint32_t usual_col_window_size = variant_ct;
10171 {
10172 const uintptr_t half_bytes_avail = RoundDownPow2(bigstack_left() / 2, kCacheline);
10173 if (unlikely(half_bytes_avail < unpacked_variant_byte_stride)) {
10174 goto VcorMatrix_ret_NOMEM;
10175 }
10176 if (variant_ct * S_CAST(uint64_t, unpacked_variant_byte_stride) > half_bytes_avail) {
10177 usual_col_window_size = half_bytes_avail / unpacked_variant_byte_stride;
10178 }
10179 }
10180 if (unlikely(bigstack_alloc_uc(usual_col_window_size * unpacked_variant_byte_stride, &(ctx.unpacked_col_variants[0])) ||
10181 bigstack_alloc_uc(usual_col_window_size * unpacked_variant_byte_stride, &(ctx.unpacked_col_variants[1])))) {
10182 goto VcorMatrix_ret_NOMEM;
10183 }
10184 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
10185 goto VcorMatrix_ret_NOMEM;
10186 }
10187 SetThreadFuncAndData(VcorMatrixThread, &ctx, &tg);
10188 uint64_t job_size;
10189 if (triangle_calc) {
10190 job_size = ((S_CAST(uint64_t, row_variant_idx_stop) * (row_variant_idx_stop + 1)) - (S_CAST(uint64_t, row_variant_idx_start) * (row_variant_idx_start + 1))) / 2;
10191 } else {
10192 job_size = (row_variant_idx_stop - row_variant_idx_start) * S_CAST(uint64_t, variant_ct);
10193 }
10194 if (flags & kfVcorRefBased) {
10195 maj_alleles = nullptr;
10196 }
10197 AlleleCode aidx = 0;
10198 uint64_t job_done = 0;
10199 uint64_t next_job_done = 0;
10200 uint64_t pct_thresh = job_size / 100;
10201 uint32_t pct = 0;
10202 uint32_t cur_row_variant_idx_start = row_variant_idx_start;
10203 uint32_t row_window_size = usual_row_window_size;
10204 uint32_t col_variant_idx_stop = variant_ct;
10205 uint32_t row_chr_fo_idx = UINT32_MAX; // deliberate overflow
10206 uint32_t row_chr_end = 0;
10207 uint32_t row_read_phase = 0;
10208 uint32_t row_parity = 0;
10209 uint32_t col_parity = 0;
10210 uintptr_t row_variant_uidx_base;
10211 uintptr_t row_cur_bits;
10212 BitIter1Start(variant_include, row_variant_uidx_start, &row_variant_uidx_base, &row_cur_bits);
10213 printf("%s: 0%%", flagname);
10214 fflush(stdout);
10215 do {
10216 // 1. unpack all variants in current row block.
10217 // 2. iterate through column blocks.
10218 if (cur_row_variant_idx_start + row_window_size > row_variant_idx_stop) {
10219 row_window_size = row_variant_idx_stop - cur_row_variant_idx_start;
10220 }
10221 unsigned char* row_load_iter = ctx.unpacked_row_variants[row_parity];
10222 for (uint32_t vidx_offset = 0; vidx_offset != row_window_size; ++vidx_offset, row_load_iter = &(row_load_iter[unpacked_variant_byte_stride])) {
10223 const uint32_t variant_uidx = BitIter1(variant_include, &row_variant_uidx_base, &row_cur_bits);
10224 if (variant_uidx >= row_chr_end) {
10225 do {
10226 ++row_chr_fo_idx;
10227 row_chr_end = cip->chr_fo_vidx_start[row_chr_fo_idx + 1];
10228 } while (variant_uidx >= row_chr_end);
10229 if (phase_type == kR2PhaseTypePresent) {
10230 const uint32_t row_chr_idx = cip->chr_file_order[row_chr_fo_idx];
10231 row_read_phase = (!IsSet(cip->haploid_mask, row_chr_idx)) || (row_chr_idx == x_code);
10232 if (!row_read_phase) {
10233 pgv.phasepresent_ct = 0;
10234 pgv.dphase_ct = 0;
10235 }
10236 }
10237 }
10238 if (maj_alleles) {
10239 aidx = maj_alleles[variant_uidx];
10240 }
10241 const uint32_t is_y = (variant_uidx < y_end) && (variant_uidx >= y_start);
10242 if (check_dosage) {
10243 if (row_read_phase) {
10244 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, &pgv);
10245 } else {
10246 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
10247 }
10248 if (unlikely(reterr)) {
10249 goto VcorMatrix_ret_PGR_FAIL;
10250 }
10251 if (is_y) {
10252 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
10253 }
10254 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, row_load_iter);
10255 } else {
10256 if ((!phased_calc) && (!is_y)) {
10257 uint32_t difflist_common_geno;
10258 uint32_t difflist_len;
10259 reterr = PgrGetInv1DifflistOrGenovec(founder_info, pssi, founder_ct, max_simple_difflist_len, variant_uidx, aidx, simple_pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
10260 if (unlikely(reterr)) {
10261 goto VcorMatrix_ret_PGR_FAIL;
10262 }
10263 if (difflist_common_geno != UINT32_MAX) {
10264 if (difflist_len <= max_simple_difflist_len) {
10265 LdUnpackNondosageSparse(raregeno, difflist_sample_ids, founder_male_collapsed, founder_ct, founder_male_ct, difflist_common_geno, difflist_len, row_load_iter);
10266 continue;
10267 }
10268 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, founder_ct, difflist_len, pgv.genovec);
10269 }
10270 } else {
10271 if (row_read_phase) {
10272 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
10273 } else {
10274 reterr = PgrGetInv1(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec);
10275 }
10276 if (unlikely(reterr)) {
10277 goto VcorMatrix_ret_PGR_FAIL;
10278 }
10279 if (is_y) {
10280 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
10281 }
10282 }
10283 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, row_load_iter);
10284 }
10285 }
10286 const uint32_t cur_row_variant_idx_stop = cur_row_variant_idx_start + row_window_size;
10287 if (triangle_calc) {
10288 col_variant_idx_stop = cur_row_variant_idx_stop;
10289 }
10290 uint32_t cur_col_variant_idx_start = 0;
10291 uint32_t col_window_size = usual_col_window_size;
10292 uint32_t col_chr_fo_idx = UINT32_MAX; // deliberate overflow
10293 uint32_t col_chr_end = 0;
10294 uint32_t col_read_phase = 0;
10295 uintptr_t col_variant_uidx_base;
10296 uintptr_t col_cur_bits;
10297 BitIter1Start(variant_include, first_variant_uidx, &col_variant_uidx_base, &col_cur_bits);
10298 do {
10299 if (cur_col_variant_idx_start + col_window_size > col_variant_idx_stop) {
10300 col_window_size = col_variant_idx_stop - cur_col_variant_idx_start;
10301 }
10302 unsigned char* col_load_iter = ctx.unpacked_col_variants[col_parity];
10303 // possible todo: don't duplicate already-unpacked row variants
10304 for (uint32_t vidx_offset = 0; vidx_offset != col_window_size; ++vidx_offset, col_load_iter = &(col_load_iter[unpacked_variant_byte_stride])) {
10305 const uint32_t variant_uidx = BitIter1(variant_include, &col_variant_uidx_base, &col_cur_bits);
10306 if (variant_uidx >= col_chr_end) {
10307 do {
10308 ++col_chr_fo_idx;
10309 col_chr_end = cip->chr_fo_vidx_start[col_chr_fo_idx + 1];
10310 } while (variant_uidx >= col_chr_end);
10311 if (phase_type == kR2PhaseTypePresent) {
10312 const uint32_t col_chr_idx = cip->chr_file_order[col_chr_fo_idx];
10313 col_read_phase = (!IsSet(cip->haploid_mask, col_chr_idx)) || (col_chr_idx == x_code);
10314 if (!col_read_phase) {
10315 pgv.phasepresent_ct = 0;
10316 pgv.dphase_ct = 0;
10317 }
10318 }
10319 }
10320 if (maj_alleles) {
10321 aidx = maj_alleles[variant_uidx];
10322 }
10323 const uint32_t is_y = (variant_uidx < y_end) && (variant_uidx >= y_start);
10324 if (check_dosage) {
10325 if (col_read_phase) {
10326 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, &pgv);
10327 } else {
10328 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
10329 }
10330 if (unlikely(reterr)) {
10331 goto VcorMatrix_ret_PGR_FAIL;
10332 }
10333 if (is_y) {
10334 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
10335 }
10336 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, col_load_iter);
10337 } else {
10338 if ((!phased_calc) && (!is_y)) {
10339 uint32_t difflist_common_geno;
10340 uint32_t difflist_len;
10341 reterr = PgrGetInv1DifflistOrGenovec(founder_info, pssi, founder_ct, max_simple_difflist_len, variant_uidx, aidx, simple_pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
10342 if (unlikely(reterr)) {
10343 goto VcorMatrix_ret_PGR_FAIL;
10344 }
10345 if (difflist_common_geno != UINT32_MAX) {
10346 if (difflist_len <= max_simple_difflist_len) {
10347 LdUnpackNondosageSparse(raregeno, difflist_sample_ids, founder_male_collapsed, founder_ct, founder_male_ct, difflist_common_geno, difflist_len, col_load_iter);
10348 continue;
10349 }
10350 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, founder_ct, difflist_len, pgv.genovec);
10351 }
10352 } else {
10353 if (col_read_phase) {
10354 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
10355 } else {
10356 reterr = PgrGetInv1(founder_info, pssi, founder_ct, variant_uidx, aidx, simple_pgrp, pgv.genovec);
10357 }
10358 if (unlikely(reterr)) {
10359 goto VcorMatrix_ret_PGR_FAIL;
10360 }
10361 if (is_y) {
10362 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
10363 }
10364 }
10365 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, col_load_iter);
10366 }
10367 }
10368 const uint32_t cur_col_variant_idx_stop = cur_col_variant_idx_start + col_window_size;
10369 job_done = next_job_done;
10370 if (triangle_calc) {
10371 // Shard shape can be generalized as a (possibly-zero-height)
10372 // trapezoid stacked on a (possibly-zero-height) rectangle.
10373 //
10374 // Trapezoid starts on the first nonempty row, and ends either after
10375 // the first full row or, if that's not in the shard, at the shard
10376 // bottom. Rectangle starts where the trapezoid ends.
10377
10378 // both of these values are guaranteed to be less than
10379 // cur_row_variant_idx_stop == col_variant_idx_stop
10380 const uintptr_t trapezoid_start_row_idx = MAXV(cur_row_variant_idx_start, cur_col_variant_idx_start);
10381
10382 const uintptr_t trapezoid_stop_row_idx = MINV(cur_row_variant_idx_stop, MAXV(cur_row_variant_idx_start, cur_col_variant_idx_stop));
10383 const uintptr_t trapezoid_height = trapezoid_stop_row_idx - trapezoid_start_row_idx;
10384 if (trapezoid_height) {
10385 const uintptr_t first_row_len = trapezoid_start_row_idx + 1 - cur_col_variant_idx_start;
10386 const uintptr_t last_row_len = trapezoid_stop_row_idx - cur_col_variant_idx_start;
10387 next_job_done += (S_CAST(uint64_t, trapezoid_height) * (first_row_len + last_row_len)) / 2;
10388 }
10389 next_job_done += (cur_row_variant_idx_stop - trapezoid_stop_row_idx) * S_CAST(uint64_t, col_window_size);
10390 } else {
10391 next_job_done += row_window_size * S_CAST(uint64_t, col_window_size);
10392 }
10393 if ((cur_row_variant_idx_start > row_variant_idx_start) || cur_col_variant_idx_start) {
10394 JoinThreads(&tg);
10395 if (!cur_col_variant_idx_start) {
10396 const uint32_t prev_row_variant_idx_start = cur_row_variant_idx_start - usual_row_window_size;
10397 if (prev_row_variant_idx_start > row_variant_idx_start) {
10398 JoinThreads(&write_tg);
10399 if (unlikely(write_ctx.reterr)) {
10400 reterr = write_ctx.reterr;
10401 goto VcorMatrix_ret_1;
10402 }
10403 }
10404 write_ctx.cur_row_variant_idx_start = prev_row_variant_idx_start;
10405 if (unlikely(SpawnThreads(&write_tg))) {
10406 goto VcorMatrix_ret_THREAD_CREATE_FAIL;
10407 }
10408 ctx.cur_row_variant_idx_start = cur_row_variant_idx_start;
10409 ctx.row_window_size = row_window_size;
10410 }
10411 }
10412 ctx.cur_col_variant_idx_start = cur_col_variant_idx_start;
10413 ctx.col_window_size = col_window_size;
10414 if (next_job_done == job_size) {
10415 DeclareLastThreadBlock(&tg);
10416 }
10417 if (unlikely(SpawnThreads(&tg))) {
10418 goto VcorMatrix_ret_THREAD_CREATE_FAIL;
10419 }
10420 col_parity = 1 - col_parity;
10421
10422 if (job_done >= pct_thresh) {
10423 if (pct > 10) {
10424 putc_unlocked('\b', stdout);
10425 }
10426 pct = (job_done * 100) / job_size;
10427 printf("\b\b%u%%", pct++);
10428 fflush(stdout);
10429 pct_thresh = (pct * job_size) / 100;
10430 }
10431 cur_col_variant_idx_start = cur_col_variant_idx_stop;
10432 } while (cur_col_variant_idx_start != col_variant_idx_stop);
10433 cur_row_variant_idx_start = cur_row_variant_idx_stop;
10434 row_parity = 1 - row_parity;
10435 } while (cur_row_variant_idx_start != row_variant_idx_stop);
10436 JoinThreads(&tg);
10437 const uint32_t prev_row_variant_idx_start = cur_row_variant_idx_start - row_window_size;
10438 if (prev_row_variant_idx_start > row_variant_idx_start) {
10439 JoinThreads(&write_tg);
10440 if (unlikely(write_ctx.reterr)) {
10441 reterr = write_ctx.reterr;
10442 goto VcorMatrix_ret_1;
10443 }
10444 }
10445 DeclareLastThreadBlock(&write_tg);
10446 write_ctx.cur_row_variant_idx_start = prev_row_variant_idx_start;
10447 write_ctx.row_window_size = row_window_size;
10448 if (unlikely(SpawnThreads(&write_tg))) {
10449 goto VcorMatrix_ret_THREAD_CREATE_FAIL;
10450 }
10451 JoinThreads(&write_tg);
10452 if (unlikely(write_ctx.reterr)) {
10453 reterr = write_ctx.reterr;
10454 goto VcorMatrix_ret_1;
10455 }
10456 fputs("\r", stdout);
10457 logprintfww("%s: Matrix%s written to %s .\n", flagname, (parallel_tot == 1)? "" : " piece", outname);
10458 }
10459 while (0) {
10460 VcorMatrix_ret_NOMEM:
10461 reterr = kPglRetNomem;
10462 break;
10463 VcorMatrix_ret_OPEN_FAIL:
10464 reterr = kPglRetOpenFail;
10465 break;
10466 VcorMatrix_ret_WRITE_FAIL:
10467 reterr = kPglRetWriteFail;
10468 break;
10469 VcorMatrix_ret_INCONSISTENT_INPUT:
10470 reterr = kPglRetInconsistentInput;
10471 break;
10472 VcorMatrix_ret_THREAD_CREATE_FAIL:
10473 reterr = kPglRetThreadCreateFail;
10474 break;
10475 VcorMatrix_ret_PGR_FAIL:
10476 PgenErrPrintN(reterr);
10477 break;
10478 }
10479 VcorMatrix_ret_1:
10480 CleanupThreads(&write_tg);
10481 CleanupThreads(&tg);
10482 CswriteCloseCond(&write_ctx.css, write_ctx.cswritep);
10483 fclose_cond(write_ctx.outfile);
10484 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
10485 return reterr;
10486 }
10487
10488 // indexes here are all subsetted (founder_idx / variant_idx), not sample_uidx
10489 // / variant_uidx.
10490 typedef struct VcorTableCtxStruct {
10491 // Shared constants.
10492 const uintptr_t* founder_male_collapsed;
10493 const uintptr_t* founder_nonmale_collapsed;
10494 const Dosage* male_dosage_invmask;
10495 const Dosage* nonmale_dosage_invmask;
10496 uint32_t chrx_idx; // UINT32_MAX if not present
10497 uint32_t founder_ct;
10498 uint32_t founder_male_ct;
10499 unsigned char is_unsquared;
10500 unsigned char phase_type;
10501 unsigned char check_dosage;
10502 unsigned char report_d;
10503 unsigned char report_dprime;
10504 uintptr_t unpacked_variant_byte_stride;
10505
10506 // Input data.
10507 unsigned char* unpacked_variants[2]; // read from [col_parity]
10508 // uint32_t* row_uvidxs[2]; // read from [row_parity]
10509 uint32_t* col_uvidxs[2]; // read from [col_parity]
10510 ChrIdx* row_chr_idxs[2]; // read from [row_parity]
10511 ChrIdx* col_chr_idxs[2]; // read from [col_parity]
10512 uint32_t* col_offset_starts[2]; // read from [row_parity]
10513 // read from [row_parity].
10514 // col_offset_end = write_idx_starts[k+1] - write_idx_starts[k].
10515 // Note that these intervals usually include col_variant_idx ==
10516 // row_variant_idx. Those entries are skipped by the writer and aren't
10517 // filled.
10518 // In the --ld-snp/--ld-snps/--ld-snp-list case, if col_variant_idx is in the
10519 // row-variant set, and col_variant_idx < row_variant_idx, the writer skips
10520 // the entry (since it was previously written with row/column swapped), but
10521 // we currently don't optimize out the computation.
10522 uintptr_t* write_idx_starts[2];
10523
10524 uint32_t* row_window_sizes; // read from [row_parity]
10525 uint32_t col_window_starts[2]; // read from [col_parity]
10526 uint32_t col_window_ends[2]; // read from [col_parity]
10527
10528 // per-thread chrX workspaces.
10529 uintptr_t** cur_nm_bufs;
10530 Dosage** invmask_bufs;
10531
10532 // Output double-buffer. Write to [row_parity]. For better locality,
10533 // r^2 / d / dprime are adjacent (and in that order) if we're writing more
10534 // than one of them.
10535 double* results[2];
10536 } VcorTableCtx;
10537
10538 THREAD_FUNC_DECL VcorTableThread(void* raw_arg) {
10539 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10540 const uint32_t tidx = arg->tidx;
10541 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
10542 VcorTableCtx* ctx = S_CAST(VcorTableCtx*, arg->sharedp->context);
10543 const uintptr_t* founder_male_collapsed = ctx->founder_male_collapsed;
10544 const uintptr_t* founder_nonmale_collapsed = ctx->founder_nonmale_collapsed;
10545 const Dosage* male_dosage_invmask = ctx->male_dosage_invmask;
10546 const Dosage* nonmale_dosage_invmask = ctx->nonmale_dosage_invmask;
10547 uintptr_t* cur_nm_buf = ctx->cur_nm_bufs? ctx->cur_nm_bufs[tidx] : nullptr;
10548 Dosage* invmask_buf = ctx->invmask_bufs? ctx->invmask_bufs[tidx] : nullptr;
10549 const uint32_t chrx_idx = ctx->chrx_idx;
10550 const uint32_t x_exists = (chrx_idx < UINT32_MAXM1);
10551 const uint32_t founder_ct = ctx->founder_ct;
10552 const uint32_t founder_male_ct = ctx->founder_male_ct;
10553 const uint32_t is_unsquared = ctx->is_unsquared;
10554 const R2PhaseType unpack_phase_type = S_CAST(R2PhaseType, ctx->phase_type);
10555 const uint32_t check_dosage = ctx->check_dosage;
10556 const uint32_t report_d = ctx->report_d;
10557 const uint32_t report_dprime = ctx->report_dprime;
10558 const uintptr_t unpacked_variant_byte_stride = ctx->unpacked_variant_byte_stride;
10559 const uintptr_t result_stride = 1 + report_d + report_dprime;
10560 // only flips when moving to next row-window. detect this with
10561 // (col_window_start == 0).
10562 // initialize to 1 instead of 0 so we don't need to special-case first row.
10563 uint32_t row_parity = 1;
10564
10565 // always flips
10566 uint32_t col_parity = 0;
10567 double dd = 0.0;
10568 double dprime = 0.0;
10569 double* d_ptr = report_d? (&dd) : nullptr;
10570 double* dprime_ptr = report_dprime? (&dprime) : nullptr;
10571 do {
10572 const uint32_t col_window_start = ctx->col_window_starts[col_parity];
10573 const uint32_t col_window_end = ctx->col_window_ends[col_parity];
10574 if (col_window_start == 0) {
10575 row_parity = 1 - row_parity;
10576 }
10577 const uint64_t row_window_size = ctx->row_window_sizes[row_parity];
10578 const uint32_t row_start_offset = (row_window_size * tidx) / calc_thread_ct;
10579 const uint32_t row_end_offset = (row_window_size * (tidx + 1)) / calc_thread_ct;
10580 if (row_end_offset > row_start_offset) {
10581 unsigned char* unpacked_variants = ctx->unpacked_variants[col_parity];
10582 // uint32_t* row_uvidxs = ctx->row_uvidxs[row_parity];
10583 uint32_t* col_uvidxs = ctx->col_uvidxs[col_parity];
10584 const ChrIdx* row_chr_idxs = ctx->row_chr_idxs[row_parity];
10585 const ChrIdx* col_chr_idxs = ctx->col_chr_idxs[col_parity];
10586 const uint32_t* col_offset_starts = ctx->col_offset_starts[row_parity];
10587 const uintptr_t* write_idx_starts = ctx->write_idx_starts[row_parity];
10588 double* results = ctx->results[row_parity];
10589 for (uint32_t row_offset_idx = row_start_offset; row_offset_idx != row_end_offset; ++row_offset_idx) {
10590 const uint32_t col_offset_start = col_offset_starts[row_offset_idx];
10591 const uintptr_t write_idx_start = write_idx_starts[row_offset_idx];
10592 uint32_t col_offset_stop = (write_idx_starts[row_offset_idx + 1] - write_idx_start) + col_offset_start;
10593 if ((col_offset_start >= col_window_end) || (col_offset_stop <= col_window_start)) {
10594 continue;
10595 }
10596 if (col_offset_stop > col_window_end) {
10597 col_offset_stop = col_window_end;
10598 }
10599 // const uint32_t cur_row_uvidx = row_uvidxs[row_offset_idx];
10600 const uint32_t cur_row_uvidx = row_offset_idx;
10601 const unsigned char* unpacked_row_ptr = &(unpacked_variants[row_offset_idx * unpacked_variant_byte_stride]);
10602 R2Variant row_r2v;
10603 FillR2V(unpacked_row_ptr, founder_ct, unpack_phase_type, x_exists, check_dosage, &row_r2v);
10604 const uint32_t row_chr_idx = row_chr_idxs[row_offset_idx];
10605 const uint32_t row_is_chrx = (row_chr_idx == chrx_idx);
10606 uint32_t col_offset_idx = MAXV(col_offset_start, col_window_start);
10607 double* write_iter = &(results[(write_idx_start + col_offset_idx - col_offset_start) * result_stride]);
10608 for (; col_offset_idx != col_offset_stop; ++col_offset_idx) {
10609 // bugfix (18 Apr 2024): must subtract col_window_start
10610 const uint32_t cur_col_uvidx = col_uvidxs[col_offset_idx - col_window_start];
10611 if (cur_row_uvidx == cur_col_uvidx) {
10612 write_iter = &(write_iter[result_stride]);
10613 continue;
10614 }
10615 const unsigned char* unpacked_col_ptr = &(unpacked_variants[cur_col_uvidx * unpacked_variant_byte_stride]);
10616 const uint32_t col_chr_idx = col_chr_idxs[col_offset_idx - col_window_start];
10617 const uint32_t either_is_chrx = row_is_chrx || (col_chr_idx == chrx_idx);
10618 R2Variant col_r2v;
10619 FillR2V(unpacked_col_ptr, founder_ct, unpack_phase_type, either_is_chrx, check_dosage, &col_r2v);
10620 const uint32_t same_chr = (row_chr_idx == col_chr_idx);
10621 R2PhaseType compare_phase_type = same_chr? unpack_phase_type : R2PhaseOmit(unpack_phase_type);
10622 double r_or_r2;
10623 uint32_t is_neg;
10624 if (!either_is_chrx) {
10625 r_or_r2 = ComputeR2(&row_r2v, &col_r2v, founder_ct, compare_phase_type, check_dosage, d_ptr, dprime_ptr, &is_neg);
10626 } else {
10627 r_or_r2 = ComputeXR2(&row_r2v, &col_r2v, founder_male_collapsed, founder_nonmale_collapsed, male_dosage_invmask, nonmale_dosage_invmask, founder_ct, founder_male_ct, compare_phase_type, check_dosage, same_chr, d_ptr, dprime_ptr, &is_neg, cur_nm_buf, invmask_buf);
10628 }
10629 if (r_or_r2 == -DBL_MAX) {
10630 r_or_r2 = 0.0 / 0.0;
10631 } else if (is_unsquared) {
10632 r_or_r2 = sqrt(r_or_r2) ;
10633 if (is_neg) {
10634 r_or_r2 = -r_or_r2;
10635 }
10636 }
10637 *write_iter++ = r_or_r2;
10638 if (report_d) {
10639 *write_iter++ = dd;
10640 }
10641 if (report_dprime) {
10642 *write_iter++ = dprime;
10643 }
10644 }
10645 }
10646 }
10647 col_parity = 1 - col_parity;
10648 } while (!THREAD_BLOCK_FINISH(arg));
10649 THREAD_RETURN;
10650 }
10651
10652 typedef struct VcorTableWriteCtxStruct {
10653 const uintptr_t* variant_include;
10654 const uint32_t* variant_include_cumulative_popcounts;
10655 const uintptr_t* row_variant_include;
10656 const uint32_t* row_variant_include_cumulative_popcounts;
10657 const uintptr_t* row_subset_exclude;
10658 const ChrInfo* cip;
10659 const uint32_t* variant_bps;
10660 const char* const* variant_ids;
10661 const uintptr_t* allele_idx_offsets;
10662 const char* const* allele_storage;
10663 const uintptr_t* nonref_flags;
10664 const AlleleCode* maj_alleles;
10665 const double* allele_freqs;
10666 double r_or_r2_thresh;
10667 uint32_t raw_variant_ct;
10668 VcorFlags flags;
10669 unsigned char all_nonref;
10670 unsigned char provref_col;
10671
10672 // these are relative to row_variant_include
10673 uint32_t variant_ridx_starts[2];
10674 uint32_t* row_window_sizes; // [2]
10675
10676 // these are relative to variant_include
10677 uint32_t col_variant_idx_starts[2];
10678 uint32_t* col_offset_starts[2];
10679 uintptr_t* write_idx_starts[2];
10680
10681 double* results[2];
10682
10683 char* row_chr_buf;
10684 char* col_chr_buf;
10685
10686 CompressStreamState css;
10687 char* cswritep;
10688
10689 PglErr reterr;
10690 } VcorTableWriteCtx;
10691
10692 THREAD_FUNC_DECL VcorTableWriteThread(void* raw_arg) {
10693 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
10694 VcorTableWriteCtx* ctx = S_CAST(VcorTableWriteCtx*, arg->sharedp->context);
10695 const uintptr_t* variant_include = ctx->variant_include;
10696 const uint32_t* variant_include_cumulative_popcounts = ctx->variant_include_cumulative_popcounts;
10697 const uintptr_t* row_variant_include = ctx->row_variant_include;
10698 const uint32_t* row_variant_include_cumulative_popcounts = ctx->row_variant_include_cumulative_popcounts;
10699 const uintptr_t* row_subset_exclude = ctx->row_subset_exclude;
10700 const ChrInfo* cip = ctx->cip;
10701 const uint32_t* variant_bps = ctx->variant_bps;
10702 const char* const* variant_ids = ctx->variant_ids;
10703 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
10704 const char* const* allele_storage = ctx->allele_storage;
10705 const uintptr_t* nonref_flags = ctx->nonref_flags;
10706 const AlleleCode* maj_alleles = ctx->maj_alleles;
10707 const double* allele_freqs = ctx->allele_freqs;
10708 const VcorFlags flags = ctx->flags;
10709 const uint32_t inter_chr = (flags / kfVcorInterChr) & 1;
10710 const uint32_t chr_col = (flags / kfVcorColChrom) & 1;
10711 const uint32_t pos_col = (flags / kfVcorColPos) & 1;
10712 const uint32_t id_col = (flags / kfVcorColId) & 1;
10713 const uint32_t ref_col = (flags / kfVcorColRef) & 1;
10714 const uint32_t alt1_col = (flags / kfVcorColAlt1) & 1;
10715 const uint32_t alt_col = (flags / kfVcorColAlt) & 1;
10716 const uint32_t all_nonref = ctx->all_nonref;
10717 const uint32_t provref_col = ctx->provref_col;
10718 const uint32_t maj_col = (flags / kfVcorColMaj) & 1;
10719 const uint32_t nonmaj_col = (flags / kfVcorColNonmaj) & 1;
10720 const uint32_t freq_col = (flags / kfVcorColFreq) & 1;
10721 const uint32_t d_col = (flags / kfVcorColD) & 1;
10722 const uint32_t dprime_col = ((flags & (kfVcorColDprime | kfVcorColDprimeAbs)) != 0);
10723 const uint32_t dprime_abs = (flags / kfVcorColDprimeAbs) & 1;
10724 const uint32_t results_stride = 1 + d_col + dprime_col;
10725 const double r_or_r2_thresh = ctx->r_or_r2_thresh;
10726 const uint32_t raw_variant_ctl = BitCtToWordCt(ctx->raw_variant_ct);
10727
10728 char* row_chr_buf = ctx->row_chr_buf;
10729 char* col_chr_buf = ctx->col_chr_buf;
10730 uint32_t row_chr_fo_idx = UINT32_MAX;
10731 uint32_t row_chr_end = 0;
10732 uint32_t row_chr_blen = 0;
10733 uint32_t col_chr_fo_idx = UINT32_MAX;
10734 uint32_t col_chr_end = 0;
10735 uint32_t col_chr_blen = 0;
10736 uint32_t row_allele_ct = 2;
10737 uint32_t col_allele_ct = 2;
10738 uint32_t maj_allele_idx = 0;
10739
10740 uint32_t row_parity = 0;
10741 do {
10742 const uint32_t* col_offset_starts = ctx->col_offset_starts[row_parity];
10743 const uintptr_t* write_idx_starts = ctx->write_idx_starts[row_parity];
10744 const double* cur_results_iter = ctx->results[row_parity];
10745 const uintptr_t variant_ridx_start = ctx->variant_ridx_starts[row_parity];
10746 const uint32_t row_window_size = ctx->row_window_sizes[row_parity];
10747 const uint32_t col_variant_idx_start = ctx->col_variant_idx_starts[row_parity];
10748 char* cswritep = ctx->cswritep;
10749 CompressStreamState* cssp = &(ctx->css);
10750 const uint32_t row_variant_uidx_start = IdxToUidx(row_variant_include, row_variant_include_cumulative_popcounts, 0, raw_variant_ctl, variant_ridx_start);
10751 uintptr_t row_variant_uidx_base;
10752 uintptr_t row_cur_bits;
10753 BitIter1Start(row_variant_include, row_variant_uidx_start, &row_variant_uidx_base, &row_cur_bits);
10754 uint32_t col_variant_widx = 0;
10755 for (uint32_t row_offset = 0; row_offset != row_window_size; ++row_offset) {
10756 const uint32_t row_variant_uidx = BitIter1(row_variant_include, &row_variant_uidx_base, &row_cur_bits);
10757 if (row_variant_uidx >= row_chr_end) {
10758 do {
10759 ++row_chr_fo_idx;
10760 row_chr_end = cip->chr_fo_vidx_start[row_chr_fo_idx + 1];
10761 } while (row_variant_uidx >= row_chr_end);
10762 if (row_chr_buf) {
10763 const uint32_t row_chr_idx = cip->chr_file_order[row_chr_fo_idx];
10764 char* chr_name_end = chrtoa(cip, row_chr_idx, row_chr_buf);
10765 *chr_name_end = '\t';
10766 row_chr_blen = 1 + S_CAST(uintptr_t, chr_name_end - row_chr_buf);
10767 // row_chr_buf == col_chr_buf except in inter_chr case
10768 col_chr_blen = row_chr_blen;
10769 }
10770 }
10771 uintptr_t row_allele_idx_offset_base = row_variant_uidx * 2;
10772 if (allele_idx_offsets) {
10773 row_allele_idx_offset_base = allele_idx_offsets[row_variant_uidx];
10774 row_allele_ct = allele_idx_offsets[row_variant_uidx + 1] - row_allele_idx_offset_base;
10775 }
10776 const char* const* cur_row_alleles = &(allele_storage[row_allele_idx_offset_base]);
10777 const uint32_t col_offset_start = col_offset_starts[row_offset];
10778 const uint32_t col_offset_stop = write_idx_starts[row_offset + 1] - write_idx_starts[row_offset] + col_offset_start;
10779 if (inter_chr) {
10780 col_chr_fo_idx = UINT32_MAX;
10781 col_chr_end = 0;
10782 }
10783 const uint32_t col_variant_uidx_start = ExpsearchIdxToUidx(variant_include, variant_include_cumulative_popcounts, raw_variant_ctl, col_variant_idx_start + col_offset_start, &col_variant_widx);
10784 uintptr_t col_variant_uidx_base;
10785 uintptr_t col_cur_bits;
10786 BitIter1Start(variant_include, col_variant_uidx_start, &col_variant_uidx_base, &col_cur_bits);
10787 for (uint32_t col_offset = col_offset_start; col_offset != col_offset_stop; ++col_offset) {
10788 const uint32_t col_variant_uidx = BitIter1(variant_include, &col_variant_uidx_base, &col_cur_bits);
10789 if (col_variant_uidx == row_variant_uidx) {
10790 cur_results_iter = &(cur_results_iter[results_stride]);
10791 continue;
10792 }
10793 // In the usual case, we can report each pair exactly once by requiring
10794 // col_variant_uidx > row_variant_uidx.
10795 // However, if --ld-snp/--ld-snps/--ld-snp-list is in effect, that may
10796 // cause some variant-pairs to not be reported at all. In that case,
10797 // we only enforce the col_variant_uidx > row_variant_uidx rule when
10798 // col_variant_uidx corresponds to a row-variant. (row_subset_exclude
10799 // usually points to row_variant_include; the exception is when
10800 // --parallel is also in effect.)
10801 if (row_subset_exclude && (col_variant_uidx < row_variant_uidx) && IsSet(row_subset_exclude, col_variant_uidx)) {
10802 cur_results_iter = &(cur_results_iter[results_stride]);
10803 continue;
10804 }
10805 const double r_or_r2 = *cur_results_iter;
10806 // !(a >= b) instead of (a < b) so that NaN is handled properly
10807 if ((r_or_r2_thresh >= 0.0) && (!(fabs(r_or_r2) >= r_or_r2_thresh))) {
10808 cur_results_iter = &(cur_results_iter[results_stride]);
10809 continue;
10810 }
10811 ++cur_results_iter;
10812
10813 if (col_variant_uidx >= col_chr_end) {
10814 do {
10815 ++col_chr_fo_idx;
10816 col_chr_end = cip->chr_fo_vidx_start[col_chr_fo_idx + 1];
10817 } while (col_variant_uidx >= col_chr_end);
10818 if (col_chr_buf) {
10819 const uint32_t col_chr_idx = cip->chr_file_order[col_chr_fo_idx];
10820 char* chr_name_end = chrtoa(cip, col_chr_idx, col_chr_buf);
10821 *chr_name_end = '\t';
10822 col_chr_blen = 1 + S_CAST(uintptr_t, chr_name_end - col_chr_buf);
10823 }
10824 }
10825 if (chr_col) {
10826 cswritep = memcpya(cswritep, row_chr_buf, row_chr_blen);
10827 }
10828 if (pos_col) {
10829 cswritep = u32toa_x(variant_bps[row_variant_uidx], '\t', cswritep);
10830 }
10831 if (id_col) {
10832 cswritep = strcpyax(cswritep, variant_ids[row_variant_uidx], '\t');
10833 }
10834 if (ref_col) {
10835 cswritep = strcpyax(cswritep, cur_row_alleles[0], '\t');
10836 }
10837 if (alt1_col) {
10838 cswritep = strcpyax(cswritep, cur_row_alleles[1], '\t');
10839 }
10840 if (alt_col) {
10841 for (uint32_t allele_idx = 1; allele_idx != row_allele_ct; ++allele_idx) {
10842 if (unlikely(Cswrite(cssp, &cswritep))) {
10843 goto VcorTableWriteThread_ret_WRITE_FAIL;
10844 }
10845 cswritep = strcpyax(cswritep, cur_row_alleles[allele_idx], ',');
10846 }
10847 cswritep[-1] = '\t';
10848 }
10849 if (provref_col) {
10850 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, row_variant_uidx)))? 'Y' : 'N';
10851 *cswritep++ = '\t';
10852 }
10853 if (maj_col || nonmaj_col || freq_col) {
10854 if (maj_alleles) {
10855 maj_allele_idx = maj_alleles[row_variant_uidx];
10856 }
10857 if (maj_col) {
10858 cswritep = strcpyax(cswritep, cur_row_alleles[maj_allele_idx], '\t');
10859 }
10860 if (nonmaj_col) {
10861 for (uint32_t allele_idx = 0; allele_idx != row_allele_ct; ++allele_idx) {
10862 if (allele_idx == maj_allele_idx) {
10863 continue;
10864 }
10865 if (unlikely(Cswrite(cssp, &cswritep))) {
10866 goto VcorTableWriteThread_ret_WRITE_FAIL;
10867 }
10868 cswritep = strcpyax(cswritep, cur_row_alleles[allele_idx], ',');
10869 }
10870 cswritep[-1] = '\t';
10871 }
10872 if (freq_col) {
10873 const double maj_freq = GetAlleleFreq(&(allele_freqs[row_allele_idx_offset_base - row_variant_uidx]), maj_allele_idx, row_allele_ct);
10874 cswritep = dtoa_g(1.0 - maj_freq, cswritep);
10875 *cswritep++ = '\t';
10876 }
10877 }
10878
10879 if (chr_col) {
10880 cswritep = memcpya(cswritep, col_chr_buf, col_chr_blen);
10881 }
10882 if (pos_col) {
10883 cswritep = u32toa_x(variant_bps[col_variant_uidx], '\t', cswritep);
10884 }
10885 if (id_col) {
10886 cswritep = strcpyax(cswritep, variant_ids[col_variant_uidx], '\t');
10887 }
10888 uintptr_t col_allele_idx_offset_base = col_variant_uidx * 2;
10889 if (allele_idx_offsets) {
10890 col_allele_idx_offset_base = allele_idx_offsets[col_variant_uidx];
10891 col_allele_ct = allele_idx_offsets[col_variant_uidx + 1] - col_allele_idx_offset_base;
10892 }
10893 const char* const* cur_col_alleles = &(allele_storage[col_allele_idx_offset_base]);
10894 if (ref_col) {
10895 cswritep = strcpyax(cswritep, cur_col_alleles[0], '\t');
10896 }
10897 if (alt1_col) {
10898 cswritep = strcpyax(cswritep, cur_col_alleles[1], '\t');
10899 }
10900 if (alt_col) {
10901 for (uint32_t allele_idx = 1; allele_idx != col_allele_ct; ++allele_idx) {
10902 if (unlikely(Cswrite(cssp, &cswritep))) {
10903 goto VcorTableWriteThread_ret_WRITE_FAIL;
10904 }
10905 cswritep = strcpyax(cswritep, cur_col_alleles[allele_idx], ',');
10906 }
10907 cswritep[-1] = '\t';
10908 }
10909 if (provref_col) {
10910 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, col_variant_uidx)))? 'Y' : 'N';
10911 *cswritep++ = '\t';
10912 }
10913 if (maj_col || nonmaj_col || freq_col) {
10914 if (maj_alleles) {
10915 maj_allele_idx = maj_alleles[col_variant_uidx];
10916 }
10917 if (maj_col) {
10918 cswritep = strcpyax(cswritep, cur_col_alleles[maj_allele_idx], '\t');
10919 }
10920 if (nonmaj_col) {
10921 for (uint32_t allele_idx = 0; allele_idx != col_allele_ct; ++allele_idx) {
10922 if (allele_idx == maj_allele_idx) {
10923 continue;
10924 }
10925 if (unlikely(Cswrite(cssp, &cswritep))) {
10926 goto VcorTableWriteThread_ret_WRITE_FAIL;
10927 }
10928 cswritep = strcpyax(cswritep, cur_col_alleles[allele_idx], ',');
10929 }
10930 cswritep[-1] = '\t';
10931 }
10932 if (freq_col) {
10933 const double maj_freq = GetAlleleFreq(&(allele_freqs[col_allele_idx_offset_base - col_variant_uidx]), maj_allele_idx, col_allele_ct);
10934 cswritep = dtoa_g(1.0 - maj_freq, cswritep);
10935 *cswritep++ = '\t';
10936 }
10937 }
10938
10939 // R or R2
10940 cswritep = dtoa_g(r_or_r2, cswritep);
10941 if (d_col) {
10942 *cswritep++ = '\t';
10943 cswritep = dtoa_g(*cur_results_iter++, cswritep);
10944 }
10945 if (dprime_col) {
10946 *cswritep++ = '\t';
10947 double dprime = *cur_results_iter++;
10948 if (dprime_abs) {
10949 dprime = fabs(dprime);
10950 }
10951 cswritep = dtoa_g(dprime, cswritep);
10952 }
10953 AppendBinaryEoln(&cswritep);
10954 if (unlikely(Cswrite(cssp, &cswritep))) {
10955 goto VcorTableWriteThread_ret_WRITE_FAIL;
10956 }
10957 }
10958 }
10959 ctx->cswritep = cswritep;
10960 row_parity = 1 - row_parity;
10961 while (0) {
10962 VcorTableWriteThread_ret_WRITE_FAIL:
10963 ctx->reterr = kPglRetWriteFail;
10964 }
10965 } while (!THREAD_BLOCK_FINISH(arg));
10966 THREAD_RETURN;
10967 }
10968
10969 // Determine --ld-window-kb, --ld-window-cm, and --ld-window intersection.
10970 // Assumes chr_start_uidx <= uidx_start <= uidx_end on entry, and that
10971 // uidx_start and uidx_end are not greater than their true values for the
10972 // current variant.
10973 void UpdateVcorWindow(const uintptr_t* variant_include, const uint32_t* variant_bps, const double* variant_cms, uint32_t row_snp_subset, uint32_t var_ct_radius, uint32_t bp_radius, double cm_radius, uint32_t chr_end_uidx, uint32_t center_uidx, uint32_t* uidx_startp, uint32_t* uidx_endp) {
10974 const uint32_t cur_bp = variant_bps[center_uidx];
10975 if (row_snp_subset) {
10976 uint32_t uidx_start = *uidx_startp;
10977 if (cur_bp > bp_radius) {
10978 uidx_start = ExpsearchU32(variant_bps, uidx_start, center_uidx, cur_bp - bp_radius);
10979 }
10980 if (variant_cms) {
10981 const double cur_cm = variant_cms[center_uidx];
10982 uidx_start = ExpsearchD(variant_cms, uidx_start, center_uidx, cur_cm - cm_radius);
10983 }
10984 // var_ct_radius <= 0x7fffffff, so no overflow risk
10985 if (uidx_start + var_ct_radius < center_uidx) {
10986 const uint32_t leading_var_ct = PopcountBitRange(variant_include, uidx_start, center_uidx);
10987 if (leading_var_ct > var_ct_radius) {
10988 uidx_start = FindNth1BitFrom(variant_include, uidx_start + 1, leading_var_ct - var_ct_radius);
10989 }
10990 }
10991 *uidx_startp = uidx_start;
10992 } else {
10993 *uidx_startp = center_uidx;
10994 }
10995
10996 uint32_t uidx_end = MAXV(*uidx_endp, center_uidx + 1);
10997 if (uidx_end < chr_end_uidx) {
10998 uint32_t uidx_end_ceil = ExpsearchU32(variant_bps, uidx_end, chr_end_uidx, cur_bp + bp_radius + 1);
10999 if (variant_cms) {
11000 const double cur_cm = variant_cms[center_uidx];
11001 uidx_end_ceil = ExpsearchD(variant_cms, uidx_end, uidx_end_ceil, cur_cm + cm_radius);
11002 }
11003 if (center_uidx + 1 + var_ct_radius < uidx_end_ceil) {
11004 const uint32_t trailing_var_ct = PopcountBitRange(variant_include, center_uidx + 1, uidx_end_ceil);
11005 if (trailing_var_ct > var_ct_radius) {
11006 uidx_end_ceil = 1 + FindNth1BitFrom(variant_include, center_uidx + 1, var_ct_radius);
11007 }
11008 }
11009 uidx_end = uidx_end_ceil;
11010 }
11011 *uidx_endp = uidx_end;
11012 }
11013
11014 PglErr VcorTable(const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const double* variant_cms, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const AlleleCode* maj_alleles, const double* allele_freqs, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const VcorInfo* vcip, const char* flagname, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
11015 unsigned char* bigstack_mark = g_bigstack_base;
11016 unsigned char* bigstack_end_mark = g_bigstack_end;
11017 PglErr reterr = kPglRetSuccess;
11018 VcorTableCtx ctx;
11019 VcorTableWriteCtx write_ctx;
11020 ThreadGroup tg;
11021 ThreadGroup write_tg;
11022 PreinitCstream(&write_ctx.css);
11023 write_ctx.cswritep = nullptr;
11024 PreinitThreads(&tg);
11025 PreinitThreads(&write_tg);
11026 {
11027 const VcorFlags flags = vcip->flags;
11028 const uint32_t is_unsquared = (flags / kfVcorUnsquared) & 1;
11029 const uint32_t phased_calc = (flags / kfVcorPhased) & 1;
11030 const uint32_t ref_based = (flags / kfVcorRefBased) & 1;
11031 if (!(flags & kfVcorAllowAmbiguousAllele)) {
11032 if (is_unsquared) {
11033 uint32_t is_ambiguous_biallelic = 0;
11034 if (!ref_based) {
11035 is_ambiguous_biallelic = !(flags & (kfVcorColMaj | kfVcorColNonmaj));
11036 } else {
11037 const VcorFlags relevant_allele_cols = flags & (kfVcorColRef | kfVcorColAlt1 | kfVcorColAlt);
11038 if (relevant_allele_cols != kfVcorColAlt1) {
11039 is_ambiguous_biallelic = (relevant_allele_cols == kfVcor0);
11040 } else {
11041 if (unlikely(MultiallelicVariantPresent(orig_variant_include, allele_idx_offsets, orig_variant_ct))) {
11042 logerrprintfww("Error: The meaning of r's sign cannot be consistently inferred from just the %s 'alt1' column-set at multiallelic variants. Either filter out multiallelic variants, revise the column-set, or use the 'allow-ambiguous-allele' modifier to override this error.\n", flagname);
11043 return kPglRetInconsistentInput;
11044 }
11045 }
11046 }
11047 if (unlikely(is_ambiguous_biallelic)) {
11048 logerrprintfww("Error: %s column-set doesn't include allele columns which clarify the meaning of r's sign. Either switch to --r2-%sphased, add a disambiguating column-set, or use the 'allow-ambiguous-allele' modifier to override this error.\n", flagname, phased_calc? "" : "un");
11049 return kPglRetInconsistentInput;
11050 }
11051 } else {
11052 uint32_t is_ambiguous_multiallelic;
11053 if (!ref_based) {
11054 is_ambiguous_multiallelic = !(flags & (kfVcorColMaj | kfVcorColNonmaj));
11055 } else {
11056 is_ambiguous_multiallelic = !(flags & (kfVcorColRef | kfVcorColAlt));
11057 }
11058 if (unlikely(is_ambiguous_multiallelic && MultiallelicVariantPresent(orig_variant_include, allele_idx_offsets, orig_variant_ct))) {
11059 logerrprintfww("Error: %s column-set doesn't include allele columns which clarify which calculation is being performed at multiallelic variants. Either filter out multiallelic variants, revise the column-set (with e.g. \"cols=+%s\"), or use the 'allow-ambiguous-allele' modifier to override this error.\n", flagname, ref_based? "ref" : "maj");
11060 return kPglRetInconsistentInput;
11061 }
11062 }
11063 }
11064 // 1. If not inter-chr, remove unplaced variants.
11065 // 2. If --parallel and/or --ld-snp/--ld-snps/--ld-snp-list, initialize
11066 // row_variant_include, then try to shrink variant_include:
11067 // - If inter-chr + --parallel, and this isn't the first piece, we can
11068 // remove leading variants.
11069 // - If not inter-chr, we can remove all variants that are out of range
11070 // of row_variant_include elements.
11071 const uint32_t inter_chr = (flags / kfVcorInterChr) & 1;
11072 const char* ld_snp_list_fname = vcip->ld_snp_list_fname;
11073 const RangeList* ld_snp_range_listp = &(vcip->ld_snp_range_list);
11074 const uint32_t row_snp_subset = ld_snp_list_fname || (ld_snp_range_listp->name_ct != 0);
11075 const double min_r2 = vcip->min_r2;
11076 if (unlikely(inter_chr && (!row_snp_subset) && (min_r2 <= 0.0) && (orig_variant_ct > 400000) && (parallel_tot == 1) && (!(flags & kfVcorYesReally)))) {
11077 logerrprintfww("Error: Gigantic (over 400k variants) %s unfiltered, non-distributed computation. Rerun with the 'yes-really' modifier if you are SURE you have enough hard drive space and want to do this.\n", flagname);
11078 goto VcorTable_ret_INCONSISTENT_INPUT;
11079 }
11080 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
11081 // There are conditions under which we can optimize out these allocations,
11082 // but we don't realistically need the memory under those conditions, so
11083 // just go ahead and make copies 100% of the time.
11084 uintptr_t* variant_include_buf;
11085 uintptr_t* row_variant_include_buf;
11086 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_buf) ||
11087 bigstack_alloc_w(raw_variant_ctl, &row_variant_include_buf))) {
11088 goto VcorTable_ret_NOMEM;
11089 }
11090 memcpy(variant_include_buf, orig_variant_include, raw_variant_ctl * sizeof(intptr_t));
11091 memcpy(row_variant_include_buf, orig_variant_include, raw_variant_ctl * sizeof(intptr_t));
11092 uintptr_t* row_subset_exclude_buf = nullptr;
11093 if (row_snp_subset && (parallel_idx != 0)) {
11094 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &row_subset_exclude_buf))) {
11095 goto VcorTable_ret_NOMEM;
11096 }
11097 }
11098 uint32_t variant_ct = orig_variant_ct;
11099 if (!inter_chr) {
11100 uint32_t skipped_variant_ct = StripUnplacedMut(cip, variant_include_buf);
11101 if (skipped_variant_ct) {
11102 logprintf("%s: Ignoring %u chromosome 0 variant%s.\n", flagname, skipped_variant_ct, (skipped_variant_ct == 1)? "" : "s");
11103 variant_ct -= skipped_variant_ct;
11104 }
11105 }
11106 const uint32_t var_ct_radius = vcip->var_ct_radius;
11107 const uint32_t bp_radius = vcip->bp_radius;
11108 const double cm_radius = vcip->cm_radius;
11109 if (cm_radius == -1.0) {
11110 variant_cms = nullptr;
11111 }
11112 uint32_t row_variant_ct = variant_ct;
11113 if ((parallel_tot != 1) || row_snp_subset) {
11114 if (row_snp_subset) {
11115 unsigned char* bigstack_mark2 = g_bigstack_base;
11116 uint32_t* variant_id_htable;
11117 uint32_t* htable_dup_base;
11118 uint32_t variant_id_htable_size;
11119 AllocAndPopulateIdHtableMt(variant_include_buf, variant_ids, variant_ct, bigstack_left() / 2, max_thread_ct, &variant_id_htable, &htable_dup_base, &variant_id_htable_size, nullptr);
11120 if (ld_snp_list_fname) {
11121 const uint32_t fname_slen = strlen(ld_snp_list_fname);
11122 char* fnames_tmp;
11123 if (unlikely(bigstack_alloc_c(fname_slen + 2, &fnames_tmp))) {
11124 goto VcorTable_ret_NOMEM;
11125 }
11126 memcpy(fnames_tmp, ld_snp_list_fname, fname_slen + 1);
11127 fnames_tmp[fname_slen + 1] = '\0';
11128 reterr = TokenExtractExclude(variant_ids, variant_id_htable, htable_dup_base, fnames_tmp, "ld-snp-list", raw_variant_ct, max_variant_id_slen, variant_id_htable_size, kVfilterExtract, max_thread_ct, row_variant_include_buf, &row_variant_ct);
11129 if (unlikely(reterr)) {
11130 goto VcorTable_ret_1;
11131 }
11132 } else {
11133 uintptr_t* seen_uidxs;
11134 if (unlikely(bigstack_calloc_w(raw_variant_ctl, &seen_uidxs))) {
11135 goto VcorTable_ret_NOMEM;
11136 }
11137 reterr = InterpretVariantRangeList(variant_ids, variant_id_htable, htable_dup_base, ld_snp_range_listp, "--ld-snps", max_variant_id_slen, variant_id_htable_size, seen_uidxs);
11138 if (unlikely(reterr)) {
11139 goto VcorTable_ret_1;
11140 }
11141 BitvecAnd(seen_uidxs, raw_variant_ctl, row_variant_include_buf);
11142 row_variant_ct = PopcountWords(row_variant_include_buf, raw_variant_ctl);
11143 }
11144 BigstackReset(bigstack_mark2);
11145 }
11146 if (parallel_tot > 1) {
11147 const uint32_t row_shard_start = (S_CAST(uint64_t, row_variant_ct) * parallel_idx) / parallel_tot;
11148 const uint32_t row_uidx_start = IdxToUidxBasic(row_variant_include_buf, row_shard_start);
11149 if ((parallel_idx != 0) && row_snp_subset) {
11150 memcpy(row_subset_exclude_buf, row_variant_include_buf, raw_variant_ctl * sizeof(intptr_t));
11151 }
11152 if (row_uidx_start) {
11153 ClearBitsNz(0, row_uidx_start, row_variant_include_buf);
11154 }
11155 uint32_t row_shard_end = row_variant_ct;
11156 if (parallel_idx + 1 != parallel_tot) {
11157 row_shard_end = (S_CAST(uint64_t, row_variant_ct) * (parallel_idx + 1)) / parallel_tot;
11158 const uint32_t row_vecidx_start = row_uidx_start / kBitsPerVec;
11159 const uint32_t row_uidx_end = row_vecidx_start * kBitsPerVec + IdxToUidxBasic(&(row_variant_include_buf[row_vecidx_start * kWordsPerVec]), row_shard_end - row_shard_start);
11160 ClearBitsNz(row_uidx_end, raw_variant_ct, row_variant_include_buf);
11161 }
11162 row_variant_ct = row_shard_end - row_shard_start;
11163 if ((row_shard_start != 0) && (!row_snp_subset)) {
11164 // Safe to remove column-variants before the current row-shard.
11165 variant_ct -= PopcountBitRange(variant_include_buf, 0, row_uidx_start);
11166 ClearBitsNz(0, row_uidx_start, variant_include_buf);
11167 }
11168 }
11169 }
11170 if (!inter_chr) {
11171 // Safe to remove column-variants out of range of all row variants, as
11172 // well as "orphan" row variants.
11173 uint32_t row_chr_fo_idx = UINT32_MAX;
11174 uint32_t row_chr_end = 0;
11175
11176 uint32_t uidx_start = 0;
11177 uint32_t uidx_end = 0;
11178
11179 uintptr_t row_variant_uidx_base = 0;
11180 uintptr_t row_cur_bits = row_variant_include_buf[0];
11181 for (uint32_t row_variant_idx = 0; row_variant_idx != row_variant_ct; ++row_variant_idx) {
11182 const uint32_t row_variant_uidx = BitIter1(row_variant_include_buf, &row_variant_uidx_base, &row_cur_bits);
11183 if (row_variant_uidx >= row_chr_end) {
11184 do {
11185 ++row_chr_fo_idx;
11186 row_chr_end = cip->chr_fo_vidx_start[row_chr_fo_idx + 1];
11187 } while (row_variant_uidx >= row_chr_end);
11188 const uint32_t row_chr_start = cip->chr_fo_vidx_start[row_chr_fo_idx];
11189 uidx_start = row_chr_start;
11190 uidx_end = row_chr_start;
11191 }
11192 const uint32_t prev_uidx_end = uidx_end;
11193 UpdateVcorWindow(variant_include_buf, variant_bps, variant_cms, row_snp_subset, var_ct_radius, bp_radius, cm_radius, row_chr_end, row_variant_uidx, &uidx_start, &uidx_end);
11194 if (prev_uidx_end < uidx_start) {
11195 ClearBitsNz(prev_uidx_end, uidx_start, variant_include_buf);
11196 }
11197 if (row_snp_subset && (uidx_start + 1 == uidx_end)) {
11198 // No variants in range. This row-variant is an "orphan" and can be
11199 // skipped.
11200 ClearBit(uidx_start, variant_include_buf);
11201 }
11202 }
11203 BitvecAnd(variant_include_buf, raw_variant_ctl, row_variant_include_buf);
11204 variant_ct = PopcountWords(variant_include_buf, raw_variant_ctl);
11205 }
11206 const uintptr_t* variant_include = variant_include_buf;
11207 const uintptr_t* row_variant_include = row_variant_include_buf;
11208 const uint32_t* variant_include_cumulative_popcounts;
11209 const uint32_t* row_variant_include_cumulative_popcounts;
11210 {
11211 // bugfix (16 May 2024): there are RawToSubsettedPos(variant_include,
11212 // variant_include_cumulative_popcounts, x) calls with x =
11213 // raw_variant_ct. In this case, we may need one more entry.
11214 uint32_t* variant_include_cumulative_popcounts_buf;
11215 uint32_t* row_variant_include_cumulative_popcounts_buf;
11216 if (unlikely(bigstack_alloc_u32(1 + (raw_variant_ct / kBitsPerWord), &variant_include_cumulative_popcounts_buf) ||
11217 bigstack_alloc_u32(raw_variant_ctl, &row_variant_include_cumulative_popcounts_buf))) {
11218 goto VcorTable_ret_NOMEM;
11219 }
11220
11221 FillCumulativePopcounts(variant_include, raw_variant_ctl, variant_include_cumulative_popcounts_buf);
11222 if ((raw_variant_ct % kBitsPerWord) == 0) {
11223 variant_include_cumulative_popcounts_buf[raw_variant_ctl] = variant_ct;
11224 }
11225 FillCumulativePopcounts(row_variant_include, raw_variant_ctl, row_variant_include_cumulative_popcounts_buf);
11226 variant_include_cumulative_popcounts = variant_include_cumulative_popcounts_buf;
11227 row_variant_include_cumulative_popcounts = row_variant_include_cumulative_popcounts_buf;
11228 }
11229 row_variant_ct = row_variant_include_cumulative_popcounts[raw_variant_ctl - 1] + PopcountWord(row_variant_include[raw_variant_ctl - 1]);
11230 // variant_ct == 0 is possible here. In that case, we want to write the
11231 // header line (or nothing at all if parallel_idx > 0) and skip the main
11232 // loop, not error out.
11233
11234 const uintptr_t* nonref_flags = PgrGetNonrefFlags(simple_pgrp);
11235 // "&& (!nonref_flags)" needed since this is after --ref-allele, etc. in
11236 // the order of operations.
11237 const uint32_t all_nonref = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref) && (!nonref_flags);
11238 write_ctx.all_nonref = all_nonref;
11239 const uint32_t provref_col = (flags & kfVcorColRef) && ProvrefCol(variant_include, nonref_flags, flags / kfVcorColMaybeprovref, raw_variant_ct, all_nonref);
11240 const uint32_t d_col = (flags / kfVcorColD) & 1;
11241 const uint32_t dprime_col = ((flags & (kfVcorColDprime | kfVcorColDprimeAbs)) != 0);
11242 write_ctx.row_chr_buf = nullptr;
11243 write_ctx.col_chr_buf = nullptr;
11244 {
11245 uintptr_t overflow_buf_size = kCompressStreamBlock + 512;
11246 const uint32_t chr_col = (flags / kfVcorColChrom) & 1;
11247 const uint32_t pos_col = (flags / kfVcorColPos) & 1;
11248 const uint32_t id_col = (flags / kfVcorColId) & 1;
11249 const uint32_t ref_col = (flags / kfVcorColRef) & 1;
11250 const uint32_t alt1_col = (flags / kfVcorColAlt1) & 1;
11251 const uint32_t alt_col = (flags / kfVcorColAlt) & 1;
11252 // provref_col defined earlier
11253 const uint32_t maj_col = (flags / kfVcorColMaj) & 1;
11254 const uint32_t nonmaj_col = (flags / kfVcorColNonmaj) & 1;
11255 const uint32_t freq_col = (flags / kfVcorColFreq) & 1;
11256 // d_col, dprime_col defined earlier
11257 if (chr_col) {
11258 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
11259 if (unlikely(bigstack_alloc_c(max_chr_blen, &write_ctx.row_chr_buf) ||
11260 bigstack_alloc_c(max_chr_blen, &write_ctx.col_chr_buf))) {
11261 goto VcorTable_ret_NOMEM;
11262 }
11263 overflow_buf_size += 2 * max_chr_blen;
11264 }
11265 if (id_col) {
11266 overflow_buf_size += 2 * (max_variant_id_slen + 1);
11267 }
11268 uintptr_t n_allele = ref_col + alt1_col + maj_col;
11269 if (!n_allele) {
11270 if (alt_col || nonmaj_col) {
11271 n_allele = 1;
11272 }
11273 }
11274 overflow_buf_size += n_allele * (max_allele_slen + 1);
11275 const uint32_t output_zst = (flags / kfVcorZs) & 1;
11276 char* outname_write_iter = strcpya_k(outname_end, ".vcor");
11277 if (parallel_tot != 1) {
11278 *outname_write_iter++ = '.';
11279 outname_write_iter = u32toa(parallel_idx + 1, outname_write_iter);
11280 }
11281 uint32_t compress_thread_ct = 1;
11282 if (output_zst) {
11283 outname_write_iter = strcpya_k(outname_write_iter, ".zst");
11284 // more room to tune this, but this is an easy win
11285 if ((!phased_calc) && (min_r2 <= 0.0) && (max_thread_ct > 4) && (founder_ct <= 65536)) {
11286 compress_thread_ct = 2 + ((max_thread_ct > 8) && (founder_ct <= 32768));
11287 }
11288 }
11289 *outname_write_iter = '\0';
11290 reterr = InitCstreamAlloc(outname, 0, output_zst, compress_thread_ct, overflow_buf_size, &write_ctx.css, &write_ctx.cswritep);
11291 if (unlikely(reterr)) {
11292 goto VcorTable_ret_1;
11293 }
11294 if (parallel_idx == 0) {
11295 char* cswritep = write_ctx.cswritep;
11296 *cswritep++ = '#';
11297 if (chr_col) {
11298 cswritep = strcpya_k(cswritep, "CHROM_A\t");
11299 }
11300 if (pos_col) {
11301 cswritep = strcpya_k(cswritep, "POS_A\t");
11302 }
11303 if (id_col) {
11304 cswritep = strcpya_k(cswritep, "ID_A\t");
11305 }
11306 if (ref_col) {
11307 cswritep = strcpya_k(cswritep, "REF_A\t");
11308 }
11309 if (alt1_col) {
11310 cswritep = strcpya_k(cswritep, "ALT1_A\t");
11311 }
11312 if (alt_col) {
11313 cswritep = strcpya_k(cswritep, "ALT_A\t");
11314 }
11315 if (provref_col) {
11316 cswritep = strcpya_k(cswritep, "PROVISIONAL_REF_A?\t");
11317 }
11318 if (maj_col) {
11319 cswritep = strcpya_k(cswritep, "MAJ_A\t");
11320 }
11321 if (nonmaj_col) {
11322 cswritep = strcpya_k(cswritep, "NONMAJ_A\t");
11323 }
11324 if (freq_col) {
11325 cswritep = strcpya_k(cswritep, "NONMAJ_FREQ_A\t");
11326 }
11327
11328 if (chr_col) {
11329 cswritep = strcpya_k(cswritep, "CHROM_B\t");
11330 }
11331 if (pos_col) {
11332 cswritep = strcpya_k(cswritep, "POS_B\t");
11333 }
11334 if (id_col) {
11335 cswritep = strcpya_k(cswritep, "ID_B\t");
11336 }
11337 if (ref_col) {
11338 cswritep = strcpya_k(cswritep, "REF_B\t");
11339 }
11340 if (alt1_col) {
11341 cswritep = strcpya_k(cswritep, "ALT1_B\t");
11342 }
11343 if (alt_col) {
11344 cswritep = strcpya_k(cswritep, "ALT_B\t");
11345 }
11346 if (provref_col) {
11347 cswritep = strcpya_k(cswritep, "PROVISIONAL_REF_B?\t");
11348 }
11349 if (maj_col) {
11350 cswritep = strcpya_k(cswritep, "MAJ_B\t");
11351 }
11352 if (nonmaj_col) {
11353 cswritep = strcpya_k(cswritep, "NONMAJ_B\t");
11354 }
11355 if (freq_col) {
11356 cswritep = strcpya_k(cswritep, "NONMAJ_FREQ_B\t");
11357 }
11358
11359 if (!phased_calc) {
11360 cswritep = strcpya_k(cswritep, "UN");
11361 }
11362 cswritep = strcpya_k(cswritep, "PHASED_R");
11363 if (!is_unsquared) {
11364 *cswritep++ = '2';
11365 }
11366
11367 if (d_col) {
11368 cswritep = strcpya_k(cswritep, "\tD");
11369 }
11370 if (dprime_col) {
11371 *cswritep++ = '\t';
11372 if (flags & kfVcorColDprimeAbs) {
11373 cswritep = strcpya_k(cswritep, "ABS_");
11374 }
11375 cswritep = strcpya_k(cswritep, "DPRIME");
11376 }
11377 AppendBinaryEoln(&cswritep);
11378
11379 write_ctx.cswritep = cswritep;
11380 }
11381 }
11382 if (!row_variant_ct) {
11383 logprintf("%s: No variant-pairs to process.\n", flagname);
11384 goto VcorTable_ret_1;
11385 }
11386 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
11387 const uint32_t founder_ctl = BitCtToWordCt(founder_ct);
11388 const uint32_t founder_ctv = BitCtToVecCt(founder_ct);
11389 const uint32_t founder_ctv2 = NypCtToVecCt(founder_ct);
11390 const uint32_t founder_ctaw = founder_ctv * kWordsPerVec;
11391 const uint32_t founder_male_ct = PopcountWordsIntersect(founder_info, sex_male, raw_sample_ctl);
11392 const uint32_t all_haploid = IsSet(cip->haploid_mask, 0);
11393 PgenGlobalFlags effective_gflags = PgrGetGflags(simple_pgrp) & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePresent | kfPgenGlobalDosagePhasePresent);
11394 const uint32_t check_phase = phased_calc && (!all_haploid) && (effective_gflags & (kfPgenGlobalHardcallPhasePresent | kfPgenGlobalDosagePhasePresent));
11395 if (!check_phase) {
11396 effective_gflags &= kfPgenGlobalDosagePresent;
11397 }
11398 const R2PhaseType phase_type = GetR2PhaseType(phased_calc, check_phase);
11399 const uint32_t check_dosage = (effective_gflags / kfPgenGlobalDosagePresent) & 1;
11400
11401 uintptr_t* raregeno = nullptr;
11402 uint32_t* difflist_sample_ids = nullptr;
11403 const uint32_t max_simple_difflist_len = founder_ct / 64;
11404 if (!phased_calc) {
11405 const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
11406 if (unlikely(bigstack_alloc_w(NypCtToWordCt(max_returned_difflist_len), &raregeno) ||
11407 bigstack_alloc_u32(max_returned_difflist_len, &difflist_sample_ids))) {
11408 goto VcorTable_ret_NOMEM;
11409 }
11410 }
11411
11412 const uintptr_t* founder_male_collapsed = nullptr;
11413 const Dosage* male_dosage_invmask = nullptr;
11414 ctx.founder_nonmale_collapsed = nullptr;
11415 ctx.nonmale_dosage_invmask = nullptr;
11416 ctx.chrx_idx = UINT32_MAX;
11417 uint32_t x_code = UINT32_MAX;
11418 // if all-males, we can ignore phase on chrX, as well as skipping
11419 // male/nonmale-specific stats
11420 // if all-nonmales, we initialize x_code to prevent phase from being
11421 // ignored, but can skip the male/nonmale-specific stats
11422 if (founder_male_ct != founder_ct) {
11423 if (XymtExists(cip, kChrOffsetX, &x_code) && (founder_male_ct != 0)) {
11424 const uint32_t x_fo_idx = cip->chr_idx_to_foidx[x_code];
11425 const uint32_t start_vidx = cip->chr_fo_vidx_start[x_fo_idx];
11426 const uint32_t end_vidx = cip->chr_fo_vidx_start[x_fo_idx + 1];
11427 if (!AllBitsAreZero(variant_include, start_vidx, end_vidx)) {
11428 ctx.chrx_idx = x_code;
11429 uintptr_t* founder_male_collapsed_fill;
11430 uintptr_t* founder_nonmale_collapsed;
11431 if (unlikely(bigstack_alloc_w(founder_ctl, &founder_male_collapsed_fill) ||
11432 bigstack_alloc_w(founder_ctl, &founder_nonmale_collapsed))) {
11433 goto VcorTable_ret_NOMEM;
11434 }
11435 CopyBitarrSubset(sex_male, founder_info, founder_ct, founder_male_collapsed_fill);
11436 founder_male_collapsed = founder_male_collapsed_fill;
11437 BitvecInvertCopy(founder_male_collapsed, founder_ctl, founder_nonmale_collapsed);
11438 ZeroTrailingBits(founder_ct, founder_nonmale_collapsed);
11439 ctx.founder_nonmale_collapsed = founder_nonmale_collapsed;
11440 if (check_dosage) {
11441 const uint32_t founder_ctad = RoundUpPow2(founder_ct, kDosagePerVec);
11442 Dosage* male_dosage_invmask_fill;
11443 Dosage* nonmale_dosage_invmask;
11444 if (bigstack_alloc_dosage(founder_ctad, &male_dosage_invmask_fill) ||
11445 bigstack_alloc_dosage(founder_ctad, &nonmale_dosage_invmask)) {
11446 goto VcorTable_ret_NOMEM;
11447 }
11448 Expand1bitTo16(founder_male_collapsed, founder_ctad, 0xffff, male_dosage_invmask_fill);
11449 Expand1bitTo16(founder_nonmale_collapsed, founder_ctad, 0xffff, nonmale_dosage_invmask);
11450 male_dosage_invmask = male_dosage_invmask_fill;
11451 ctx.nonmale_dosage_invmask = nonmale_dosage_invmask;
11452 }
11453 }
11454 }
11455 }
11456 const uint32_t x_exists = (ctx.chrx_idx < UINT32_MAXM1);
11457 ctx.founder_male_collapsed = founder_male_collapsed;
11458 ctx.male_dosage_invmask = male_dosage_invmask;
11459
11460 uint32_t y_start;
11461 uint32_t y_end;
11462 GetXymtStartAndEnd(cip, kChrOffsetY, &y_start, &y_end);
11463 uintptr_t* founder_female_collapsed = nullptr;
11464 uintptr_t* founder_female_collapsed_interleaved = nullptr;
11465 if (y_end) {
11466 if ((founder_male_ct == founder_ct) || AllBitsAreZero(variant_include, y_start, y_end)) {
11467 y_start = 0;
11468 y_end = 0;
11469 }
11470 if (y_end) {
11471 uintptr_t* founder_female;
11472 if (bigstack_end_alloc_w(raw_sample_ctl, &founder_female)) {
11473 goto VcorTable_ret_NOMEM;
11474 }
11475 BitvecInvmaskCopy(sex_nm, sex_male, raw_sample_ctl, founder_female);
11476 BitvecAnd(founder_info, raw_sample_ctl, founder_female);
11477 if (AllWordsAreZero(founder_female, raw_sample_ctl)) {
11478 y_start = 0;
11479 y_end = 0;
11480 } else {
11481 if (bigstack_alloc_w(founder_ctaw, &founder_female_collapsed) ||
11482 bigstack_alloc_w(founder_ctaw, &founder_female_collapsed_interleaved)) {
11483 goto VcorTable_ret_NOMEM;
11484 }
11485 CopyBitarrSubset(founder_female, founder_info, founder_ct, founder_female_collapsed);
11486 ZeroTrailingWords(founder_ctl, founder_female_collapsed);
11487 FillInterleavedMaskVec(founder_female_collapsed, founder_ctv, founder_female_collapsed_interleaved);
11488 }
11489 BigstackEndReset(bigstack_end_mark);
11490 }
11491 }
11492 ctx.founder_ct = founder_ct;
11493 ctx.founder_male_ct = founder_male_ct;
11494 ctx.is_unsquared = is_unsquared;
11495
11496 const uintptr_t bitvec_byte_ct = BitCtToVecCt(founder_ct) * kBytesPerVec;
11497 uintptr_t dosagevec_byte_ct = 0;
11498 uintptr_t unpacked_variant_byte_stride;
11499 if (check_dosage) {
11500 dosagevec_byte_ct = DivUp(founder_ct, kDosagePerVec) * kBytesPerVec;
11501 const uintptr_t dosage_trail_byte_ct = LdDosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_calc), x_exists);
11502 unpacked_variant_byte_stride = dosagevec_byte_ct * (1 + phased_calc + check_phase) + bitvec_byte_ct + dosage_trail_byte_ct;
11503 } else {
11504 unpacked_variant_byte_stride = RoundUpPow2(16, kBytesPerVec) + bitvec_byte_ct * (3 + 2 * check_phase);
11505 #ifndef USE_AVX2
11506 const uintptr_t sparse_req = RoundUpPow2((6 + max_simple_difflist_len) * sizeof(int32_t), kBytesPerVec) + NypCtToVecCt(max_simple_difflist_len) * kBytesPerVec + RoundUpPow2(founder_ctl * (kBytesPerWord + sizeof(int32_t)), kBytesPerVec);
11507 if (sparse_req > unpacked_variant_byte_stride) {
11508 unpacked_variant_byte_stride = sparse_req;
11509 }
11510 #endif
11511 const uintptr_t nondosage_trail_byte_ct = LdNondosageTrailAlignedByteCt(S_CAST(R2PhaseType, phased_calc), x_exists);
11512 unpacked_variant_byte_stride += nondosage_trail_byte_ct;
11513 }
11514 uint32_t* founder_info_cumulative_popcounts;
11515 PgenVariant pgv;
11516 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &founder_info_cumulative_popcounts) ||
11517 BigstackAllocPgv(founder_ct, 0, effective_gflags, &pgv))) {
11518 goto VcorTable_ret_NOMEM;
11519 }
11520 FillCumulativePopcounts(founder_info, raw_sample_ctl, founder_info_cumulative_popcounts);
11521 PgrSampleSubsetIndex pssi;
11522 PgrSetSampleSubsetIndex(founder_info_cumulative_popcounts, simple_pgrp, &pssi);
11523
11524 ctx.phase_type = phase_type;
11525 ctx.check_dosage = check_dosage;
11526 ctx.report_d = d_col;
11527 ctx.report_dprime = dprime_col;
11528 ctx.unpacked_variant_byte_stride = unpacked_variant_byte_stride;
11529 // Some room to tune this, e.g. if .zst compression is on, founder_ct is
11530 // small, and computation is unphased, we may want more than 1 compression
11531 // thread. But this should be good enough for now.
11532 uint32_t calc_thread_ct = max_thread_ct - (max_thread_ct > 4) - (max_thread_ct > 8);
11533 ctx.cur_nm_bufs = nullptr;
11534 ctx.invmask_bufs = nullptr;
11535 if (x_exists) {
11536 if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.cur_nm_bufs) ||
11537 bigstack_alloc_dosagep(calc_thread_ct, &ctx.invmask_bufs))) {
11538 goto VcorTable_ret_NOMEM;
11539 }
11540 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
11541 if (unlikely(bigstack_alloc_w(founder_ctl, &(ctx.cur_nm_bufs[tidx])) ||
11542 bigstack_alloc_dosage(founder_ct, &(ctx.invmask_bufs[tidx])))) {
11543 goto VcorTable_ret_NOMEM;
11544 }
11545 }
11546 }
11547
11548 // Now initialize the parts of write_ctx that don't depend on uv_capacity.
11549 write_ctx.variant_include = variant_include;
11550 write_ctx.variant_include_cumulative_popcounts = variant_include_cumulative_popcounts;
11551 write_ctx.row_variant_include = row_variant_include;
11552 write_ctx.row_variant_include_cumulative_popcounts = row_variant_include_cumulative_popcounts;
11553 write_ctx.row_subset_exclude = nullptr;
11554 if (row_snp_subset) {
11555 write_ctx.row_subset_exclude = (parallel_idx == 0)? row_variant_include : row_subset_exclude_buf;
11556 }
11557 write_ctx.cip = cip;
11558 write_ctx.variant_bps = variant_bps;
11559 write_ctx.variant_ids = variant_ids;
11560 write_ctx.allele_idx_offsets = allele_idx_offsets;
11561 write_ctx.allele_storage = allele_storage;
11562 write_ctx.nonref_flags = nonref_flags;
11563 write_ctx.maj_alleles = maj_alleles;
11564 write_ctx.allele_freqs = allele_freqs;
11565 if (!is_unsquared) {
11566 write_ctx.r_or_r2_thresh = min_r2;
11567 } else {
11568 write_ctx.r_or_r2_thresh = (min_r2 < 0.0)? -1.0 : sqrt(min_r2);
11569 }
11570 write_ctx.raw_variant_ct = raw_variant_ct;
11571 write_ctx.flags = flags;
11572 write_ctx.provref_col = provref_col;
11573 write_ctx.reterr = kPglRetSuccess;
11574
11575 // Assign ~half of remaining workspace to input buffers and ~half to output
11576 // buffers.
11577 const uintptr_t results_stride = 1 + d_col + dprime_col;
11578 const uintptr_t result_capacity = bigstack_left() / (4 * sizeof(double) * results_stride);
11579 if (unlikely(bigstack_alloc_d(result_capacity * results_stride, &(ctx.results[0])) ||
11580 bigstack_alloc_d(result_capacity * results_stride, &(ctx.results[1])))) {
11581 goto VcorTable_ret_NOMEM;
11582 }
11583 write_ctx.results[0] = ctx.results[0];
11584 write_ctx.results[1] = ctx.results[1];
11585
11586 uint32_t* col_offset_starts_storage[2];
11587 uintptr_t* write_idx_starts_storage[2];
11588 uint32_t row_window_sizes[2];
11589 ctx.row_window_sizes = row_window_sizes;
11590 write_ctx.row_window_sizes = row_window_sizes;
11591 // All remaining allocation sizes are a function of uv_capacity. Set its
11592 // value.
11593 uintptr_t uv_capacity;
11594 {
11595 // ctx:
11596 // unpacked_variants: 2 * unpacked_variant_byte_stride
11597 // (no row_uvidxs)
11598 // col_uvidxs: 2 * sizeof(int32_t)
11599 // row_chr_idxs: 2 * sizeof(ChrIdx)
11600 // col_chr_idxs: 2 * sizeof(ChrIdx)
11601 // col_offset_starts: 2 * sizeof(int32_t)
11602 // write_idx_starts: 2 * sizeof(intptr_t) (length (uv_capacity + 1))
11603 // (could optimize row_chr_idxs and col_chr_idxs out)
11604 uintptr_t bytes_left = bigstack_left();
11605 // defend against adverse rounding
11606 if (unlikely(bytes_left < 11 * kCacheline)) {
11607 goto VcorTable_ret_NOMEM;
11608 }
11609 bytes_left -= 11 * kCacheline;
11610 const uintptr_t bytes_per_unpacked_variant = 2 * (unpacked_variant_byte_stride + 2 * sizeof(int32_t) + 2 * sizeof(ChrIdx) + sizeof(intptr_t));
11611 uv_capacity = bytes_left / bytes_per_unpacked_variant;
11612 if (unlikely(uv_capacity < 2)) {
11613 goto VcorTable_ret_NOMEM;
11614 }
11615 if (uv_capacity > variant_ct) {
11616 uv_capacity = variant_ct;
11617 }
11618 // shouldn't be possible for these allocations to fail
11619 if (unlikely(bigstack_alloc_uc(uv_capacity * unpacked_variant_byte_stride, &(ctx.unpacked_variants[0])) ||
11620 bigstack_alloc_uc(uv_capacity * unpacked_variant_byte_stride, &(ctx.unpacked_variants[1])) ||
11621 bigstack_alloc_u32(uv_capacity, &(ctx.col_uvidxs[0])) ||
11622 bigstack_alloc_u32(uv_capacity, &(ctx.col_uvidxs[1])) ||
11623 bigstack_alloc_chridx(uv_capacity, &(ctx.row_chr_idxs[0])) ||
11624 bigstack_alloc_chridx(uv_capacity, &(ctx.row_chr_idxs[1])) ||
11625 bigstack_alloc_chridx(uv_capacity, &(ctx.col_chr_idxs[0])) ||
11626 bigstack_alloc_chridx(uv_capacity, &(ctx.col_chr_idxs[1])) ||
11627 bigstack_alloc_u32(uv_capacity, &(col_offset_starts_storage[0])) ||
11628 bigstack_alloc_u32(uv_capacity, &(col_offset_starts_storage[1])) ||
11629 bigstack_alloc_w(uv_capacity + 1, &(write_idx_starts_storage[0])) ||
11630 bigstack_alloc_w(uv_capacity + 1, &(write_idx_starts_storage[1])))) {
11631 // shouldn't be possible
11632 goto VcorTable_ret_NOMEM;
11633 }
11634 ctx.col_offset_starts[0] = col_offset_starts_storage[0];
11635 ctx.col_offset_starts[1] = col_offset_starts_storage[1];
11636 ctx.write_idx_starts[0] = write_idx_starts_storage[0];
11637 ctx.write_idx_starts[1] = write_idx_starts_storage[1];
11638 write_ctx.col_offset_starts[0] = col_offset_starts_storage[0];
11639 write_ctx.col_offset_starts[1] = col_offset_starts_storage[1];
11640 write_ctx.write_idx_starts[0] = write_idx_starts_storage[0];
11641 write_ctx.write_idx_starts[1] = write_idx_starts_storage[1];
11642 }
11643 if (calc_thread_ct > uv_capacity) {
11644 calc_thread_ct = uv_capacity;
11645 }
11646 if (unlikely(SetThreadCt(calc_thread_ct, &tg) ||
11647 SetThreadCt(1, &write_tg))) {
11648 goto VcorTable_ret_NOMEM;
11649 }
11650 SetThreadFuncAndData(VcorTableThread, &ctx, &tg);
11651 SetThreadFuncAndData(VcorTableWriteThread, &write_ctx, &write_tg);
11652
11653 if (ref_based) {
11654 maj_alleles = nullptr;
11655 }
11656 AlleleCode aidx = 0;
11657
11658 logprintf("Running %s with the following filter%s:\n", flagname, inter_chr? "" : "s");
11659 if (!inter_chr) {
11660 if (var_ct_radius < 0x7fffffff) {
11661 logprintf(" --ld-window: %u\n", var_ct_radius + 1);
11662 }
11663 logprintf(" --ld-window-kb: %g\n", 0.001 * u31tod(bp_radius));
11664 if (cm_radius != -1.0) {
11665 logprintf(" --ld-window-cm: %g\n", cm_radius);
11666 }
11667 }
11668 logprintf(" --ld-window-r2: %g\n", min_r2);
11669 if (row_snp_subset) {
11670 if (ld_snp_list_fname) {
11671 logputs(" --ld-snp-list\n");
11672 } else {
11673 logputs(" --ld-snp[s]\n");
11674 }
11675 }
11676 uint32_t next_print_variant_ridx = row_variant_ct / 100;
11677 uint32_t pct = 0;
11678 uint32_t prev_variant_ridx_start = 0;
11679 uint32_t cur_variant_ridx_start = 0;
11680 uint32_t row_chr_fo_idx = UINT32_MAX; // deliberate overflow
11681 uint32_t row_chr_idx = 0;
11682 uint32_t row_chr_start = 0;
11683 uint32_t row_chr_end = 0;
11684 uint32_t row_read_phase = 0;
11685 uint32_t row_parity = 0;
11686 uint32_t col_parity = 0;
11687 uint32_t col_variant_widx = 0;
11688 uintptr_t row_variant_uidx_base;
11689 uintptr_t row_cur_bits;
11690 BitIter1Start(row_variant_include, 0, &row_variant_uidx_base, &row_cur_bits);
11691 printf("%s: 0%%", flagname);
11692 fflush(stdout);
11693 do {
11694 // Since we're using a double- rather than a triple-buffer, we must wait
11695 // for the writer to finish flushing results for block (n-2) before we
11696 // overwrite with information about block n.
11697 if (prev_variant_ridx_start) {
11698 JoinThreads(&write_tg);
11699 if (unlikely(write_ctx.reterr)) {
11700 reterr = write_ctx.reterr;
11701 goto VcorTable_ret_1;
11702 }
11703 }
11704 // 1. Determine col_offset_start and col_offset_end for each row-variant
11705 // in the new row-window, and what the current row_window_size is.
11706 // Constraints:
11707 // * Can't run out of results-capacity.
11708 // * Unless variant_ct == uv_capacity, there's also:
11709 // * row_window_size <= row_variant_ct - cur_variant_ridx_start.
11710 // * row_window_size <= uv_capacity / 2. This is unnecessarily
11711 // tight in many cases, but never by a factor of more than 2 (4 if
11712 // we take results-space into account), and I did not find that to
11713 // be a big deal in my testing.
11714 // Fill row_parity-indexed buffers.
11715 // 2. col_capacity := uv_capacity - row_window_size; iterate through
11716 // column-shard(s).
11717 // uint32_t* row_uvidxs = ctx.row_uvidxs[row_parity];
11718 ChrIdx* row_chr_idxs = ctx.row_chr_idxs[row_parity];
11719 uint32_t* col_offset_starts = col_offset_starts_storage[row_parity];
11720 uintptr_t* write_idx_starts = write_idx_starts_storage[row_parity];
11721 uintptr_t write_idx = 0;
11722 uint32_t row_variant_uidx_first = 0;
11723 uint32_t row_variant_uidx_last = 0;
11724 uint32_t col_variant_idx_start = 0;
11725 uint32_t row_window_size;
11726 uint32_t cur_variant_ridx_stop;
11727 uint32_t col_variant_idx_ct;
11728 {
11729 uint32_t row_offset_limit = row_variant_ct - cur_variant_ridx_start;
11730 if ((uv_capacity < variant_ct) && ((uv_capacity / 2) < row_offset_limit)) {
11731 row_offset_limit = uv_capacity / 2;
11732 }
11733
11734 // ok for these to be less than true value
11735 uint32_t uidx_start = row_chr_start;
11736 uint32_t uidx_end = row_chr_start;
11737
11738 unsigned char* row_load_iter = ctx.unpacked_variants[col_parity];
11739 uint32_t row_offset = 0;
11740 // in inter-chr case, should save col-window size
11741 // if row-subset, start at variant_idx=0 instead of at diagonal
11742 for (; row_offset != row_offset_limit; ++row_offset, row_load_iter = &(row_load_iter[unpacked_variant_byte_stride])) {
11743 const uint32_t row_variant_uidx = BitIter1(row_variant_include, &row_variant_uidx_base, &row_cur_bits);
11744 if (row_variant_uidx >= row_chr_end) {
11745 do {
11746 ++row_chr_fo_idx;
11747 row_chr_end = cip->chr_fo_vidx_start[row_chr_fo_idx + 1];
11748 } while (row_variant_uidx >= row_chr_end);
11749 row_chr_idx = cip->chr_file_order[row_chr_fo_idx];
11750 row_chr_start = cip->chr_fo_vidx_start[row_chr_fo_idx];
11751 uidx_start = row_chr_start;
11752 uidx_end = row_chr_start;
11753 if (phase_type == kR2PhaseTypePresent) {
11754 row_read_phase = (!IsSet(cip->haploid_mask, row_chr_idx)) || (row_chr_idx == x_code);
11755 if (!row_read_phase) {
11756 pgv.phasepresent_ct = 0;
11757 pgv.dphase_ct = 0;
11758 }
11759 }
11760 }
11761 uint32_t cur_col_offset_start;
11762 uint32_t cur_col_offset_end;
11763 if (inter_chr) {
11764 if (row_offset == 0) {
11765 row_variant_uidx_first = row_variant_uidx;
11766 if (!row_snp_subset) {
11767 col_variant_idx_start = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, row_variant_uidx);
11768 }
11769 }
11770 cur_col_offset_start = row_snp_subset? 0 : row_offset;
11771 cur_col_offset_end = variant_ct - col_variant_idx_start;
11772 } else {
11773 UpdateVcorWindow(variant_include, variant_bps, variant_cms, row_snp_subset, var_ct_radius, bp_radius, cm_radius, row_chr_end, row_variant_uidx, &uidx_start, &uidx_end);
11774 if (row_offset == 0) {
11775 row_variant_uidx_first = row_variant_uidx;
11776 col_variant_idx_start = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, uidx_start);
11777 }
11778 cur_col_offset_start = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, uidx_start) - col_variant_idx_start;
11779 cur_col_offset_end = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, uidx_end) - col_variant_idx_start;
11780 }
11781 const uintptr_t next_write_idx = write_idx + cur_col_offset_end - cur_col_offset_start;
11782 if (next_write_idx > result_capacity) {
11783 // Need to backtrack.
11784 row_variant_uidx_base = RoundDownPow2(row_variant_uidx, kBitsPerWord);
11785 row_cur_bits = row_variant_include[row_variant_uidx / kBitsPerWord] & (-(k1LU << (row_variant_uidx % kBitsPerWord)));
11786 break;
11787 }
11788 row_variant_uidx_last = row_variant_uidx;
11789 row_chr_idxs[row_offset] = row_chr_idx;
11790 col_offset_starts[row_offset] = cur_col_offset_start;
11791 write_idx_starts[row_offset] = write_idx;
11792 write_idx = next_write_idx;
11793
11794 if (maj_alleles) {
11795 aidx = maj_alleles[row_variant_uidx];
11796 }
11797 const uint32_t is_y = (row_variant_uidx < y_end) && (row_variant_uidx >= y_start);
11798 if (check_dosage) {
11799 if (row_read_phase) {
11800 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, row_variant_uidx, aidx, simple_pgrp, &pgv);
11801 } else {
11802 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, row_variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
11803 }
11804 if (unlikely(reterr)) {
11805 goto VcorTable_ret_PGR_FAIL;
11806 }
11807 if (is_y) {
11808 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
11809 }
11810 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, row_load_iter);
11811 } else {
11812 if ((!phased_calc) && (!is_y)) {
11813 uint32_t difflist_common_geno;
11814 uint32_t difflist_len;
11815 reterr = PgrGetInv1DifflistOrGenovec(founder_info, pssi, founder_ct, max_simple_difflist_len, row_variant_uidx, aidx, simple_pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
11816 if (unlikely(reterr)) {
11817 goto VcorTable_ret_PGR_FAIL;
11818 }
11819 if (difflist_common_geno != UINT32_MAX) {
11820 if (difflist_len <= max_simple_difflist_len) {
11821 LdUnpackNondosageSparse(raregeno, difflist_sample_ids, founder_male_collapsed, founder_ct, founder_male_ct, difflist_common_geno, difflist_len, row_load_iter);
11822 continue;
11823 }
11824 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, founder_ct, difflist_len, pgv.genovec);
11825 }
11826 } else {
11827 if (row_read_phase) {
11828 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, row_variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
11829 } else {
11830 reterr = PgrGetInv1(founder_info, pssi, founder_ct, row_variant_uidx, aidx, simple_pgrp, pgv.genovec);
11831 }
11832 if (unlikely(reterr)) {
11833 goto VcorTable_ret_PGR_FAIL;
11834 }
11835 if (is_y) {
11836 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
11837 }
11838 }
11839 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, row_load_iter);
11840 }
11841 }
11842 row_window_size = row_offset;
11843 write_idx_starts[row_window_size] = write_idx;
11844 cur_variant_ridx_stop = cur_variant_ridx_start + row_window_size;
11845 write_ctx.variant_ridx_starts[row_parity] = cur_variant_ridx_start;
11846 row_window_sizes[row_parity] = row_window_size;
11847 write_ctx.col_variant_idx_starts[row_parity] = col_variant_idx_start;
11848 col_variant_idx_ct = col_offset_starts[row_window_size - 1] + write_idx - write_idx_starts[row_window_size - 1];
11849 }
11850 uint32_t col_window_start = 0;
11851 uint32_t col_offset = 0;
11852 uint32_t col_read_phase = 0;
11853 uint32_t col_chr_fo_idx;
11854 uint32_t col_chr_idx;
11855 uint32_t col_chr_end;
11856 uintptr_t col_variant_uidx_base;
11857 uintptr_t col_cur_bits;
11858 {
11859 const uint32_t col_variant_uidx_start = ExpsearchIdxToUidx(variant_include, variant_include_cumulative_popcounts, raw_variant_ctl, col_variant_idx_start, &col_variant_widx);
11860 col_chr_fo_idx = GetVariantChrFoIdx(cip, col_variant_uidx_start);
11861 col_chr_idx = cip->chr_file_order[col_chr_fo_idx];
11862 col_chr_end = cip->chr_fo_vidx_start[col_chr_fo_idx + 1];
11863 if (phase_type == kR2PhaseTypePresent) {
11864 col_read_phase = (!IsSet(cip->haploid_mask, col_chr_idx)) || (col_chr_idx == x_code);
11865 if (!col_read_phase) {
11866 pgv.phasepresent_ct = 0;
11867 pgv.dphase_ct = 0;
11868 }
11869 }
11870 BitIter1Start(variant_include, col_variant_uidx_start, &col_variant_uidx_base, &col_cur_bits);
11871 }
11872 do {
11873 unsigned char* col_load_iter;
11874 {
11875 unsigned char* unpacked_variants = ctx.unpacked_variants[col_parity];
11876 const uintptr_t row_unpacked_variants_byte_ct = row_window_size * unpacked_variant_byte_stride;
11877 if (col_offset != 0) {
11878 memcpy(unpacked_variants, ctx.unpacked_variants[1 - col_parity], row_unpacked_variants_byte_ct);
11879 }
11880 col_load_iter = &(unpacked_variants[row_unpacked_variants_byte_ct]);
11881 }
11882 const uint32_t col_window_limit = MINV(col_window_start + uv_capacity, col_variant_idx_ct);
11883 uint32_t* col_uvidxs = ctx.col_uvidxs[col_parity];
11884 ChrIdx* col_chr_idxs = ctx.col_chr_idxs[col_parity];
11885 uint32_t col_uvidx = row_window_size;
11886 for (; col_offset != col_window_limit; ++col_offset) {
11887 const uint32_t col_variant_uidx = BitIter1(variant_include, &col_variant_uidx_base, &col_cur_bits);
11888 if (col_variant_uidx >= col_chr_end) {
11889 do {
11890 ++col_chr_fo_idx;
11891 col_chr_end = cip->chr_fo_vidx_start[col_chr_fo_idx + 1];
11892 } while (col_variant_uidx >= col_chr_end);
11893 col_chr_idx = cip->chr_file_order[col_chr_fo_idx];
11894 if (phase_type == kR2PhaseTypePresent) {
11895 col_read_phase = (!IsSet(cip->haploid_mask, col_chr_idx)) || (col_chr_idx == x_code);
11896 if (!col_read_phase) {
11897 pgv.phasepresent_ct = 0;
11898 pgv.dphase_ct = 0;
11899 }
11900 }
11901 }
11902 if (IsSet(row_variant_include, col_variant_uidx) && (col_variant_uidx >= row_variant_uidx_first) && (col_variant_uidx <= row_variant_uidx_last)) {
11903 // bugfix (18 Apr 2024): must subtract col_window_start
11904 col_uvidxs[col_offset - col_window_start] = RawToSubsettedPos(row_variant_include, row_variant_include_cumulative_popcounts, col_variant_uidx) - cur_variant_ridx_start;
11905 col_chr_idxs[col_offset - col_window_start] = col_chr_idx;
11906 continue;
11907 }
11908 if (col_uvidx == uv_capacity) {
11909 col_variant_uidx_base = RoundDownPow2(col_variant_uidx, kBitsPerWord);
11910 col_cur_bits = variant_include[col_variant_uidx / kBitsPerWord] & (-(k1LU << (col_variant_uidx % kBitsPerWord)));
11911 break;
11912 }
11913 col_uvidxs[col_offset - col_window_start] = col_uvidx++;
11914 col_chr_idxs[col_offset - col_window_start] = col_chr_idx;
11915 if (maj_alleles) {
11916 aidx = maj_alleles[col_variant_uidx];
11917 }
11918 const uint32_t is_y = (col_variant_uidx < y_end) && (col_variant_uidx >= y_start);
11919 if (check_dosage) {
11920 if (col_read_phase) {
11921 reterr = PgrGetInv1Dp(founder_info, pssi, founder_ct, col_variant_uidx, aidx, simple_pgrp, &pgv);
11922 } else {
11923 reterr = PgrGetInv1D(founder_info, pssi, founder_ct, col_variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct);
11924 }
11925 if (unlikely(reterr)) {
11926 goto VcorTable_ret_PGR_FAIL;
11927 }
11928 if (is_y) {
11929 InterleavedSetMissingCleardosage(founder_female_collapsed, founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec, &pgv.dosage_ct, pgv.dosage_present, pgv.dosage_main);
11930 }
11931 LdUnpackDosage(&pgv, founder_male_collapsed, male_dosage_invmask, founder_ct, phase_type, col_load_iter);
11932 } else {
11933 if ((!phased_calc) && (!is_y)) {
11934 uint32_t difflist_common_geno;
11935 uint32_t difflist_len;
11936 reterr = PgrGetInv1DifflistOrGenovec(founder_info, pssi, founder_ct, max_simple_difflist_len, col_variant_uidx, aidx, simple_pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
11937 if (unlikely(reterr)) {
11938 goto VcorTable_ret_PGR_FAIL;
11939 }
11940 if (difflist_common_geno != UINT32_MAX) {
11941 if (difflist_len <= max_simple_difflist_len) {
11942 LdUnpackNondosageSparse(raregeno, difflist_sample_ids, founder_male_collapsed, founder_ct, founder_male_ct, difflist_common_geno, difflist_len, col_load_iter);
11943 goto VcorTable_col_finish;
11944 }
11945 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, founder_ct, difflist_len, pgv.genovec);
11946 }
11947 } else {
11948 if (col_read_phase) {
11949 reterr = PgrGetInv1P(founder_info, pssi, founder_ct, col_variant_uidx, aidx, simple_pgrp, pgv.genovec, pgv.phasepresent, pgv.phaseinfo, &pgv.phasepresent_ct);
11950 } else {
11951 reterr = PgrGetInv1(founder_info, pssi, founder_ct, col_variant_uidx, aidx, simple_pgrp, pgv.genovec);
11952 }
11953 if (unlikely(reterr)) {
11954 goto VcorTable_ret_PGR_FAIL;
11955 }
11956 if (is_y) {
11957 InterleavedSetMissing(founder_female_collapsed_interleaved, founder_ctv2, pgv.genovec);
11958 }
11959 }
11960 LdUnpackNondosageDense(&pgv, founder_male_collapsed, founder_ct, phase_type, col_load_iter);
11961 }
11962 VcorTable_col_finish:
11963 col_load_iter = &(col_load_iter[unpacked_variant_byte_stride]);
11964 }
11965 ctx.col_window_starts[col_parity] = col_window_start;
11966 ctx.col_window_ends[col_parity] = col_offset;
11967
11968 if (cur_variant_ridx_start || col_window_start) {
11969 JoinThreads(&tg);
11970 if (!col_window_start) {
11971 if (unlikely(SpawnThreads(&write_tg))) {
11972 goto VcorTable_ret_THREAD_CREATE_FAIL;
11973 }
11974 }
11975 }
11976 if ((cur_variant_ridx_stop == row_variant_ct) && (col_offset == col_variant_idx_ct)) {
11977 DeclareLastThreadBlock(&tg);
11978 }
11979 if (unlikely(SpawnThreads(&tg))) {
11980 goto VcorTable_ret_THREAD_CREATE_FAIL;
11981 }
11982 col_window_start = col_offset;
11983 col_parity = 1 - col_parity;
11984 } while (col_offset != col_variant_idx_ct);
11985 if (cur_variant_ridx_start >= next_print_variant_ridx) {
11986 if (pct > 10) {
11987 putc_unlocked('\b', stdout);
11988 }
11989 pct = (cur_variant_ridx_start * 100LLU) / row_variant_ct;
11990 printf("\b\b%u%%", pct++);
11991 fflush(stdout);
11992 next_print_variant_ridx = (pct * S_CAST(uint64_t, row_variant_ct)) / 100;
11993 }
11994 prev_variant_ridx_start = cur_variant_ridx_start;
11995 cur_variant_ridx_start = cur_variant_ridx_stop;
11996 row_parity = 1 - row_parity;
11997 } while (cur_variant_ridx_start != row_variant_ct);
11998 JoinThreads(&tg);
11999 if (prev_variant_ridx_start) {
12000 JoinThreads(&write_tg);
12001 if (unlikely(write_ctx.reterr)) {
12002 reterr = write_ctx.reterr;
12003 goto VcorTable_ret_1;
12004 }
12005 }
12006 DeclareLastThreadBlock(&write_tg);
12007 if (unlikely(SpawnThreads(&write_tg))) {
12008 goto VcorTable_ret_THREAD_CREATE_FAIL;
12009 }
12010 JoinThreads(&write_tg);
12011 if (unlikely(write_ctx.reterr)) {
12012 reterr = write_ctx.reterr;
12013 goto VcorTable_ret_1;
12014 }
12015 fputs("\r", stdout);
12016 logprintfww("%s: Results written to %s .\n", flagname, outname);
12017 }
12018 while (0) {
12019 VcorTable_ret_NOMEM:
12020 reterr = kPglRetNomem;
12021 break;
12022 VcorTable_ret_INCONSISTENT_INPUT:
12023 reterr = kPglRetInconsistentInput;
12024 break;
12025 VcorTable_ret_THREAD_CREATE_FAIL:
12026 reterr = kPglRetThreadCreateFail;
12027 break;
12028 VcorTable_ret_PGR_FAIL:
12029 PgenErrPrintN(reterr);
12030 break;
12031 }
12032 VcorTable_ret_1:
12033 CleanupThreads(&write_tg);
12034 CleanupThreads(&tg);
12035 CswriteCloseCond(&write_ctx.css, write_ctx.cswritep);
12036 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
12037 return reterr;
12038 }
12039
12040 PglErr Vcor(const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const double* variant_cms, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const AlleleCode* maj_alleles, const double* allele_freqs, const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const VcorInfo* vcip, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t raw_sample_ct, uint32_t founder_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
12041 const VcorFlags flags = vcip->flags;
12042 const uint32_t phased_calc = (flags / kfVcorPhased) & 1;
12043 const uint32_t is_unsquared = (flags / kfVcorUnsquared) & 1;
12044 const char* flagname;
12045 if (phased_calc) {
12046 flagname = is_unsquared? "--r-phased" : "--r2-phased";
12047 } else {
12048 flagname = is_unsquared? "--r-unphased" : "--r2-unphased";
12049 }
12050 if (unlikely(founder_ct < 2)) {
12051 logerrprintfww("Error: %s requires at least two founders. (--make-founders may come in handy here.)\n", flagname);
12052 return kPglRetInconsistentInput;
12053 } else if (founder_ct > 0x3fffffff) {
12054 logerrprintf("Error: %s does not support >= 2^30 founders.\n", flagname);
12055 return kPglRetNotYetSupported;
12056 }
12057
12058 const uint32_t is_matrix = ((flags & (kfVcorBin8 | kfVcorBin4 | kfVcorMatrixShapemask)) != 0);
12059 PglErr reterr;
12060 if (is_matrix) {
12061 reterr = VcorMatrix(orig_variant_include, cip, variant_ids, maj_alleles, founder_info, sex_nm, sex_male, vcip, flagname, raw_variant_ct, orig_variant_ct, raw_sample_ct, founder_ct, parallel_idx, parallel_tot, max_thread_ct, simple_pgrp, outname, outname_end);
12062 } else {
12063 reterr = VcorTable(orig_variant_include, cip, variant_bps, variant_ids, variant_cms, allele_idx_offsets, allele_storage, maj_alleles, allele_freqs, founder_info, sex_nm, sex_male, vcip, flagname, raw_variant_ct, orig_variant_ct, raw_sample_ct, founder_ct, max_variant_id_slen, max_allele_slen, parallel_idx, parallel_tot, max_thread_ct, simple_pgrp, outname, outname_end);
12064 }
12065 return reterr;
12066 }
12067
12068 #ifdef __cplusplus
12069 } // namespace plink2
12070 #endif