Debian Codegraph @

plink2_matrix_calc.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 "plink2_compress_stream.h"
19 #include "plink2_matrix.h"
20 #include "plink2_matrix_calc.h"
21 #include "plink2_random.h"
22
23 #ifdef USE_CUDA
24 # include "cuda/plink2_matrix_cuda.h"
25 #endif
26
27 #include <unistd.h> // unlink()
28
29 #ifdef __cplusplus
30 namespace plink2 {
31 #endif
32
33 void InitScore(ScoreInfo* score_info_ptr) {
34 score_info_ptr->flags = kfScore0;
35 score_info_ptr->varid_col_p1 = 1;
36 score_info_ptr->allele_col_p1 = 0; // defensive
37 score_info_ptr->input_fname = nullptr;
38 InitRangeList(&(score_info_ptr->input_col_idx_range_list));
39
40 score_info_ptr->qsr_range_fname = nullptr;
41 score_info_ptr->qsr_data_fname = nullptr;
42 score_info_ptr->qsr_varid_col_p1 = 1;
43 score_info_ptr->qsr_val_col_p1 = 0; // defensive
44 }
45
46 void CleanupScore(ScoreInfo* score_info_ptr) {
47 free_cond(score_info_ptr->input_fname);
48 CleanupRangeList(&(score_info_ptr->input_col_idx_range_list));
49
50 free_cond(score_info_ptr->qsr_range_fname);
51 free_cond(score_info_ptr->qsr_data_fname);
52 }
53
54 void InitPhenoSvd(PhenoSvdInfo* pheno_svd_info_ptr) {
55 pheno_svd_info_ptr->flags = kfPhenoSvd0;
56 pheno_svd_info_ptr->ct = 0;
57 pheno_svd_info_ptr->min_variance_explained = 0.0;
58 }
59
60
61 // Cost function for thread load-balancing: (max - min) * ((max + min)/2)
62 // i.e. we don't waste any time processing entries in the irrelevant
63 // upper-right triangle
64 // set align to 1 for no alignment
65 void TriangleFill(uint32_t ct, uint32_t piece_ct, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t start, uint32_t align, uint32_t* target_arr) {
66 int32_t modif = 1 - start * 2;
67 int64_t cur_prod_x2;
68 int32_t lbound;
69 int32_t ubound;
70 uint32_t uii;
71 uint32_t align_m1;
72 ParallelBounds(ct, start, parallel_idx, parallel_tot, &lbound, &ubound);
73 // x(x+1)/2 is divisible by y iff (x % (2y)) is 0 or (2y - 1).
74 align *= 2;
75 align_m1 = align - 1;
76 target_arr[0] = lbound;
77 target_arr[piece_ct] = ubound;
78 cur_prod_x2 = S_CAST(int64_t, lbound) * (lbound + modif);
79 const int64_t ct_tr = (S_CAST(int64_t, ubound) * (ubound + modif) - cur_prod_x2) / piece_ct;
80 for (uint32_t piece_idx = 1; piece_idx != piece_ct; ++piece_idx) {
81 cur_prod_x2 += ct_tr;
82 lbound = TriangleDivide(cur_prod_x2, modif);
83 uii = (lbound - S_CAST(int32_t, start)) & align_m1;
84 if ((uii) && (uii != align_m1)) {
85 lbound = start + ((lbound - S_CAST(int32_t, start)) | align_m1);
86 }
87 // lack of this check caused a nasty bug earlier
88 if (S_CAST(uint32_t, lbound) > ct) {
89 lbound = ct;
90 }
91 target_arr[piece_idx] = lbound;
92 }
93 }
94
95 // Cost function for thread load-balancing: (max - min) * max
96 // i.e. when we can't avoid processing entries in the irrelevant upper-right
97 // triangle
98 void TriangleFill2(uint32_t ct, uint32_t piece_ct, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t start, uint32_t* target_arr) {
99 int32_t lbound_s;
100 int32_t ubound_s;
101 ParallelBounds(ct, start, parallel_idx, parallel_tot, &lbound_s, &ubound_s);
102 uint32_t lbound = lbound_s;
103 const uint32_t ubound = ubound_s;
104 target_arr[0] = lbound;
105 target_arr[piece_ct] = ubound;
106
107 uint32_t remaining_row_ct = ubound - lbound;
108 uint32_t remaining_piece_ct = piece_ct;
109
110 for (uint32_t piece_idx = 1; piece_idx != piece_ct; ++piece_idx) {
111 // Start by assigning an equal-row-count piece, rounding up (since later
112 // pieces are wider). Then compare current-piece cost with a lower bound
113 // of average remaining-piece cost, and append rows until current-piece
114 // cost exceeds that average.
115 uint32_t candidate_piece_size = (remaining_row_ct + remaining_piece_ct - 1) / remaining_piece_ct;
116 remaining_row_ct -= candidate_piece_size;
117 remaining_piece_ct -= 1;
118 uint32_t candidate_boundary = lbound + candidate_piece_size;
119
120 // Consider lbound == 0, ubound == 8, piece_ct == 3. The ideal solution
121 // would be:
122 //
123 // row 0: 0 0 0 0
124 // row 1: 0 0 0 0
125 // row 2: 0 0 0 0
126 // row 3: 0 0 0 0
127 // row 4: 1 1 1 1 1 1
128 // row 5: 1 1 1 1 1 1
129 // row 6: 2 2 2 2 2 2 2 2
130 // row 7: 2 2 2 2 2 2 2 2
131 //
132 // The initial candidate_piece_size is 3.
133 //
134 // With no waste, the remaining cost would be (8-3) * (8+3+1)/2 = 30.
135 // The true remaining cost is at least 34, because there are 5 remaining
136 // rows, the upper-right-triangle waste is minimized if they're split as
137 // evenly as possible between the remaining threads, and that {3, 2} split
138 // results in waste of 3 for the 3-row piece and 1 for the 2-row piece.
139 //
140 // So current cost is 9, average remaining cost is 17. If we incremented
141 // candidate_piece_size, the current cost would become 16, and the
142 // average remaining cost would drop to ~15 (actually 14, but we use a
143 // slight overestimate in the current comparison); the latter pair of
144 // numbers is closer, so we perform the increment.
145 //
146 // On the next iteration, we clearly don't want to increment
147 // candidate_piece_size any more.
148 //
149 //
150 // Then, when determining the boundary between threads 1 and 2,
151 // candidate_piece_size starts at 2. Current cost is 6*2=12, average
152 // remaining cost is 16. If we incremented, candidate_piece_size, the
153 // current cost would become 21, and the average remaining cost would drop
154 // to ~8. |16-12| is smaller, so thread 1 gets just 2 rows.
155
156
157 // If the remaining rows were split as evenly as possible, what's the
158 // smaller chunk size?
159 uint32_t remaining_piece_lower_size = remaining_row_ct / remaining_piece_ct;
160 // What's the waste associated with that smaller chunk size?
161 uint64_t remaining_piece_lower_waste = (S_CAST(uint64_t, remaining_piece_lower_size) * (remaining_piece_lower_size - 1)) >> 1;
162 // How many threads would be assigned the higher chunk size?
163 uint32_t remaining_piece_higher_ct = remaining_row_ct - remaining_piece_lower_size * remaining_piece_ct;
164 // Note that the waste associated with the larger chunk size is
165 // (remaining_piece_lower_waste + remaining_piece_lower_size).
166 const uint64_t min_waste = remaining_piece_lower_waste * remaining_piece_ct + remaining_piece_higher_ct * remaining_piece_lower_size;
167 uint64_t remaining_cost = ((remaining_row_ct * (ubound + 1LLU + candidate_boundary)) >> 1) + min_waste;
168 while (1) {
169 const uint64_t candidate_piece_cost = S_CAST(uint64_t, candidate_piece_size) * candidate_boundary;
170 const uint64_t next_candidate_piece_cost = candidate_piece_cost + candidate_piece_size + candidate_boundary + 1;
171 // printf("lbound: %u ubound: %u candidate_piece_cost: %" PRIu64 " remaining_piece_ct: %u remaining_cost: %" PRIu64 "\n", lbound, ubound, candidate_piece_cost, remaining_piece_ct, remaining_cost);
172 if ((candidate_piece_cost + next_candidate_piece_cost) * remaining_piece_ct > 2 * (remaining_cost - candidate_boundary)) {
173 break;
174 }
175 // There are circumstances where we can make larger jumps here, but the
176 // overall computational cost here is low enough; let's keep this
177 // simpler.
178 ++candidate_piece_size;
179 --remaining_row_ct;
180 ++candidate_boundary;
181 // Incremental update of non-waste portion of remaining_cost.
182 remaining_cost -= candidate_boundary;
183 // Incremental update of waste portion of remaining_cost.
184 if (remaining_piece_higher_ct) {
185 --remaining_piece_higher_ct;
186 remaining_cost -= remaining_piece_lower_size;
187 } else {
188 --remaining_piece_lower_size;
189 remaining_piece_lower_waste -= remaining_piece_lower_size;
190 remaining_cost -= remaining_piece_lower_size;
191 remaining_piece_higher_ct = remaining_piece_ct - 1;
192 }
193 }
194 lbound += candidate_piece_size;
195 target_arr[piece_idx] = lbound;
196 }
197 }
198
199 // Returns 0 if cells_avail is insufficient.
200 uint32_t CountTrianglePasses(uintptr_t start_idx, uintptr_t end_idx, uintptr_t is_no_diag, uintptr_t cells_avail) {
201 start_idx -= is_no_diag;
202 end_idx -= is_no_diag;
203 if (cells_avail < end_idx) {
204 return 0;
205 }
206 cells_avail *= 2; // don't want to worry about /2 in triangular numbers
207 const uint64_t end_tri = S_CAST(uint64_t, end_idx) * (end_idx + 1);
208 uint64_t start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
209 for (uint32_t pass_ct = 1; ; ++pass_ct) {
210 const uint64_t delta_tri = end_tri - start_tri;
211 if (delta_tri <= cells_avail) {
212 return pass_ct;
213 }
214 const uint64_t next_target = start_tri + cells_avail;
215 start_idx = S_CAST(int64_t, sqrt(u63tod(next_target)));
216 start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
217 if (start_tri > next_target) {
218 --start_idx;
219 start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
220 assert(start_tri <= next_target);
221 }
222 }
223 }
224
225 uint64_t NextTrianglePass(uintptr_t start_idx, uintptr_t grand_end_idx, uintptr_t is_no_diag, uintptr_t cells_avail) {
226 cells_avail *= 2;
227 start_idx -= is_no_diag;
228 grand_end_idx -= is_no_diag;
229 const uint64_t end_tri = S_CAST(uint64_t, grand_end_idx) * (grand_end_idx + 1);
230 uint64_t start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
231 const uint64_t delta_tri = end_tri - start_tri;
232 if (delta_tri <= cells_avail) {
233 return grand_end_idx + is_no_diag;
234 }
235 const uint64_t next_target = start_tri + cells_avail;
236 start_idx = S_CAST(int64_t, sqrt(u63tod(next_target)));
237 start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
238 return start_idx + is_no_diag - (start_tri > next_target);
239 }
240
241 void TriangleLoadBalance(uint32_t piece_ct, uintptr_t start_idx, uintptr_t end_idx, uint32_t is_no_diag, uint32_t* target_arr) {
242 target_arr[0] = start_idx;
243 target_arr[piece_ct] = end_idx;
244 start_idx -= is_no_diag;
245 end_idx -= is_no_diag;
246 const uint64_t end_tri = S_CAST(uint64_t, end_idx) * (end_idx + 1);
247 uint64_t cur_target = S_CAST(uint64_t, start_idx) * (start_idx + 1);
248 const uint64_t std_size = (end_tri - cur_target) / piece_ct;
249 for (uint32_t piece_idx = 1; piece_idx != piece_ct; ++piece_idx) {
250 // don't use cur_target = start_tri + (piece_idx * delta_tri) / piece_ct
251 // because of potential overflow
252 cur_target += std_size;
253 start_idx = S_CAST(int64_t, sqrt(u63tod(cur_target)));
254 const uint64_t start_tri = S_CAST(uint64_t, start_idx) * (start_idx + 1);
255 if (start_tri > cur_target) {
256 --start_idx;
257 }
258 target_arr[piece_idx] = start_idx + is_no_diag;
259 }
260 }
261
262 PglErr KinshipPruneDestructive(uintptr_t* kinship_table, uintptr_t* sample_include, uint32_t* sample_ct_ptr) {
263 PglErr reterr = kPglRetSuccess;
264 {
265 const uintptr_t orig_sample_ct = *sample_ct_ptr;
266 const uintptr_t orig_sample_ctl = BitCtToWordCt(orig_sample_ct);
267 uintptr_t* sample_include_collapsed_nz;
268 uintptr_t* sample_remove_collapsed;
269 uint32_t* vertex_degree;
270 if (unlikely(bigstack_calloc_w(orig_sample_ctl, &sample_include_collapsed_nz) ||
271 bigstack_calloc_w(orig_sample_ctl, &sample_remove_collapsed) ||
272 bigstack_alloc_u32(orig_sample_ct, &vertex_degree))) {
273 goto KinshipPruneDestructive_ret_NOMEM;
274 }
275 // 1. count the number of constraints for each remaining sample
276 uint32_t degree_1_vertex_ct = 0;
277 for (uint32_t sample_idx = 0; sample_idx != orig_sample_ct; ++sample_idx) {
278 const uintptr_t woffset = sample_idx * orig_sample_ctl;
279 const uintptr_t* read_iter1 = &(kinship_table[woffset]);
280 // don't currently guarantee vector-alignment of kinship_table rows, so
281 // can't use PopcountWords(). (change this?)
282 uint32_t cur_degree = 0;
283 for (uint32_t widx = 0; widx != orig_sample_ctl; ++widx) {
284 const uintptr_t cur_word = *read_iter1++;
285 cur_degree += PopcountWord(cur_word);
286 }
287 if (cur_degree) {
288 vertex_degree[sample_idx] = cur_degree;
289 degree_1_vertex_ct += (cur_degree == 1);
290 SetBit(sample_idx, sample_include_collapsed_nz);
291 }
292 }
293 uint32_t cur_sample_nz_ct = PopcountWords(sample_include_collapsed_nz, orig_sample_ctl);
294 // 2. as long as edges remain,
295 // a. remove partner of first degree-one vertex, if such a vertex exists
296 // b. otherwise, remove first maximal-degree vertex
297 // (similar to plink 1.9 rel_cutoff_batch(), but data structure is not
298 // triangular since more speed is needed)
299 while (cur_sample_nz_ct) {
300 uint32_t prune_uidx;
301 uint32_t cur_degree;
302 if (degree_1_vertex_ct) {
303 uint32_t degree_1_vertex_uidx = 0;
304 while (1) {
305 // sparse
306 degree_1_vertex_uidx = AdvTo1Bit(sample_include_collapsed_nz, degree_1_vertex_uidx);
307 if (vertex_degree[degree_1_vertex_uidx] == 1) {
308 break;
309 }
310 ++degree_1_vertex_uidx;
311 }
312 // find partner
313 prune_uidx = AdvTo1Bit(&(kinship_table[degree_1_vertex_uidx * orig_sample_ctl]), 0);
314 cur_degree = vertex_degree[prune_uidx];
315 } else {
316 uint32_t sample_uidx = AdvTo1Bit(sample_include_collapsed_nz, 0);
317 cur_degree = vertex_degree[sample_uidx];
318 prune_uidx = sample_uidx;
319 for (uint32_t sample_idx = 1; sample_idx != cur_sample_nz_ct; ++sample_idx) {
320 // sparse
321 sample_uidx = AdvTo1Bit(sample_include_collapsed_nz, sample_uidx + 1);
322 const uint32_t new_degree = vertex_degree[sample_uidx];
323 if (new_degree > cur_degree) {
324 cur_degree = new_degree;
325 prune_uidx = sample_uidx;
326 }
327 }
328 }
329 // remove row/column
330 uintptr_t* cur_kinship_col = &(kinship_table[prune_uidx / kBitsPerWord]);
331 const uintptr_t kinship_col_mask = ~(k1LU << (prune_uidx % kBitsPerWord));
332 uintptr_t* cur_kinship_row = &(kinship_table[prune_uidx * orig_sample_ctl]);
333 uint32_t sample_uidx = 0;
334 for (uint32_t partner_idx = 0; partner_idx != cur_degree; ++partner_idx, ++sample_uidx) {
335 // sparse
336 sample_uidx = AdvTo1Bit(cur_kinship_row, sample_uidx);
337 const uint32_t new_degree = vertex_degree[sample_uidx] - 1;
338 if (!new_degree) {
339 ClearBit(sample_uidx, sample_include_collapsed_nz);
340 --degree_1_vertex_ct;
341 --cur_sample_nz_ct;
342 // unnecessary to write to kinship_table[] or vertex_degree[]
343 } else {
344 cur_kinship_col[sample_uidx * orig_sample_ctl] &= kinship_col_mask;
345 degree_1_vertex_ct += (new_degree == 1);
346 vertex_degree[sample_uidx] = new_degree;
347 }
348 }
349 if (vertex_degree[prune_uidx] == 1) {
350 --degree_1_vertex_ct;
351 }
352 sample_remove_collapsed[prune_uidx / kBitsPerWord] |= ~kinship_col_mask;
353 sample_include_collapsed_nz[prune_uidx / kBitsPerWord] &= kinship_col_mask;
354 // unnecessary to update current kinship_table[] row
355 --cur_sample_nz_ct;
356 }
357 uint32_t sample_ct = orig_sample_ct;
358 uintptr_t sample_widx = 0;
359 uintptr_t cur_bits = sample_include[0];
360 for (uint32_t sample_idx = 0; sample_idx != orig_sample_ct; ++sample_idx) {
361 const uintptr_t lowbit = BitIter1y(sample_include, &sample_widx, &cur_bits);
362 if (IsSet(sample_remove_collapsed, sample_idx)) {
363 sample_include[sample_widx] ^= lowbit;
364 --sample_ct;
365 }
366 }
367 *sample_ct_ptr = sample_ct;
368 }
369 while (0) {
370 KinshipPruneDestructive_ret_NOMEM:
371 reterr = kPglRetNomem;
372 break;
373 }
374 return reterr;
375 }
376
377 PglErr KingCutoffBatchBinary(const SampleIdInfo* siip, uint32_t raw_sample_ct, double king_cutoff, uintptr_t* sample_include, char* king_cutoff_fprefix, uint32_t* sample_ct_ptr) {
378 unsigned char* bigstack_mark = g_bigstack_base;
379 FILE* binfile = nullptr;
380 char* fprefix_end = &(king_cutoff_fprefix[strlen(king_cutoff_fprefix)]);
381 uintptr_t line_idx = 0;
382 PglErr reterr = kPglRetSuccess;
383 TextStream txs;
384 PreinitTextStream(&txs);
385 {
386 uint32_t sample_ct = *sample_ct_ptr;
387 const uint32_t orig_sample_ctl = BitCtToWordCt(sample_ct);
388 uintptr_t* kinship_table;
389 uint32_t* sample_uidx_to_king_uidx;
390 if (unlikely(bigstack_calloc_w(sample_ct * orig_sample_ctl, &kinship_table) ||
391 bigstack_alloc_u32(raw_sample_ct, &sample_uidx_to_king_uidx))) {
392 goto KingCutoffBatchBinary_ret_NOMEM;
393 }
394
395 snprintf(fprefix_end, 9, ".king.id");
396 reterr = InitTextStream(king_cutoff_fprefix, kTextStreamBlenFast, 1, &txs);
397 if (unlikely(reterr)) {
398 goto KingCutoffBatchBinary_ret_TSTREAM_FAIL;
399 }
400 // bugfix (18 Aug 2018): this missed some xid_mode possibilities
401 // todo: try to simplify this interface, it's bordering on incomprehensible
402 char* line_start;
403 XidMode xid_mode;
404 reterr = LoadXidHeader("king-cutoff", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
405 if (unlikely(reterr)) {
406 if (reterr == kPglRetEof) {
407 logerrputs("Error: Empty --king-cutoff ID file.\n");
408 goto KingCutoffBatchBinary_ret_MALFORMED_INPUT;
409 }
410 goto KingCutoffBatchBinary_ret_TSTREAM_XID_FAIL;
411 }
412
413 uint32_t* xid_map; // IDs not collapsed
414 char* sorted_xidbox;
415 uintptr_t max_xid_blen;
416 reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
417 if (unlikely(reterr)) {
418 goto KingCutoffBatchBinary_ret_1;
419 }
420 char* idbuf;
421 if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) {
422 goto KingCutoffBatchBinary_ret_NOMEM;
423 }
424 SetAllU32Arr(raw_sample_ct, sample_uidx_to_king_uidx);
425 uintptr_t king_id_ct = 0;
426 if (*line_start == '#') {
427 ++line_idx;
428 line_start = TextGet(&txs);
429 }
430 for (; line_start; ++line_idx, line_start = TextGet(&txs)) {
431 const char* linebuf_iter = line_start;
432 uint32_t sample_uidx;
433 if (SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx, idbuf)) {
434 if (unlikely(!linebuf_iter)) {
435 goto KingCutoffBatchBinary_ret_MISSING_TOKENS;
436 }
437 continue;
438 }
439 if (unlikely(sample_uidx_to_king_uidx[sample_uidx] != UINT32_MAX)) {
440 char* first_tab = AdvToDelim(idbuf, '\t');
441 char* second_tab = strchr(&(first_tab[1]), '\t');
442 *first_tab = ' ';
443 if (second_tab) {
444 *second_tab = ' ';
445 }
446 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s .\n", idbuf, king_cutoff_fprefix);
447 goto KingCutoffBatchBinary_ret_MALFORMED_INPUT_WW;
448 }
449 sample_uidx_to_king_uidx[sample_uidx] = king_id_ct;
450 ++king_id_ct;
451 }
452 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
453 goto KingCutoffBatchBinary_ret_TSTREAM_FAIL;
454 }
455
456 BigstackReset(TextStreamMemStart(&txs));
457 if (unlikely(CleanupTextStream2(king_cutoff_fprefix, &txs, &reterr))) {
458 goto KingCutoffBatchBinary_ret_1;
459 }
460 uintptr_t* king_include;
461 uint32_t* king_uidx_to_sample_idx;
462 if (unlikely(bigstack_calloc_w(BitCtToWordCt(king_id_ct), &king_include) ||
463 bigstack_alloc_u32(king_id_ct, &king_uidx_to_sample_idx))) {
464 goto KingCutoffBatchBinary_ret_NOMEM;
465 }
466 uintptr_t sample_uidx_base = 0;
467 uintptr_t sample_include_bits = sample_include[0];
468 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
469 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
470 const uint32_t king_uidx = sample_uidx_to_king_uidx[sample_uidx];
471 if (king_uidx != UINT32_MAX) {
472 SetBit(king_uidx, king_include);
473 king_uidx_to_sample_idx[king_uidx] = sample_idx;
474 }
475 }
476 snprintf(fprefix_end, 10, ".king.bin");
477 if (unlikely(fopen_checked(king_cutoff_fprefix, FOPEN_RB, &binfile))) {
478 goto KingCutoffBatchBinary_ret_OPEN_FAIL;
479 }
480 if (unlikely(fseeko(binfile, 0, SEEK_END))) {
481 goto KingCutoffBatchBinary_ret_READ_FAIL;
482 }
483 const uint64_t fsize = ftello(binfile);
484 const uint64_t fsize_double_expected = (king_id_ct * (S_CAST(uint64_t, king_id_ct) - 1) * (sizeof(double) / 2));
485 const uint32_t is_double = (fsize == fsize_double_expected);
486 rewind(binfile);
487 const uint32_t first_king_uidx = AdvBoundedTo1Bit(king_include, 0, king_id_ct);
488 uintptr_t king_uidx = AdvBoundedTo1Bit(king_include, first_king_uidx + 1, king_id_ct);
489 if (king_uidx > 1) {
490 if (fseeko(binfile, king_uidx * (S_CAST(uint64_t, king_uidx) - 1) * (2 + (2 * is_double)), SEEK_SET)) {
491 goto KingCutoffBatchBinary_ret_READ_FAIL;
492 }
493 }
494 uintptr_t constraint_ct = 0;
495 if (is_double) {
496 // fread limit
497 assert(king_id_ct <= ((kMaxBytesPerIO / sizeof(double)) + 1));
498 double* king_drow;
499 if (unlikely(bigstack_alloc_d(king_id_ct - 1, &king_drow))) {
500 goto KingCutoffBatchBinary_ret_NOMEM;
501 }
502 for (uint32_t king_idx = 1; king_uidx != king_id_ct; ++king_idx, ++king_uidx) {
503 if (!IsSet(king_include, king_uidx)) {
504 king_uidx = AdvBoundedTo1Bit(king_include, king_uidx + 1, king_id_ct);
505 if (king_uidx == king_id_ct) {
506 break;
507 }
508 if (unlikely(fseeko(binfile, S_CAST(uint64_t, king_uidx) * (king_uidx - 1) * (sizeof(double) / 2), SEEK_SET))) {
509 goto KingCutoffBatchBinary_ret_READ_FAIL;
510 }
511 }
512 if (unlikely(!fread_unlocked(king_drow, king_uidx * sizeof(double), 1, binfile))) {
513 goto KingCutoffBatchBinary_ret_READ_FAIL;
514 }
515 const uintptr_t sample_idx = king_uidx_to_sample_idx[king_uidx];
516 uintptr_t* kinship_table_row = &(kinship_table[sample_idx * orig_sample_ctl]);
517 uintptr_t* kinship_table_col = &(kinship_table[sample_idx / kBitsPerWord]);
518 const uintptr_t kinship_new_bit = k1LU << (sample_idx % kBitsPerWord);
519 uintptr_t king_uidx2_base;
520 uintptr_t king_include_bits;
521 BitIter1Start(king_include, first_king_uidx, &king_uidx2_base, &king_include_bits);
522 for (uint32_t king_idx2 = 0; king_idx2 != king_idx; ++king_idx2) {
523 const uintptr_t king_uidx2 = BitIter1(king_include, &king_uidx2_base, &king_include_bits);
524 if (king_drow[king_uidx2] > king_cutoff) {
525 const uintptr_t sample_idx2 = king_uidx_to_sample_idx[king_uidx2];
526 SetBit(sample_idx2, kinship_table_row);
527 kinship_table_col[sample_idx2 * orig_sample_ctl] |= kinship_new_bit;
528 ++constraint_ct;
529 }
530 }
531 }
532 } else {
533 if (unlikely(fsize != (fsize_double_expected / 2))) {
534 const uint64_t fsize_double_square = king_id_ct * S_CAST(uint64_t, king_id_ct) * sizeof(double);
535 if ((fsize == fsize_double_square) || (fsize == fsize_double_square / 2)) {
536 logerrputs("Error: --king-cutoff currently requires a *triangular* .bin file; the provided\nfile appears to be square.\n");
537 } else {
538 logerrprintfww("Error: Invalid --king-cutoff .bin file size (expected %" PRIu64 " or %" PRIu64 " bytes).\n", fsize_double_expected / 2, fsize_double_expected);
539 }
540 goto KingCutoffBatchBinary_ret_MALFORMED_INPUT;
541 }
542 assert(king_id_ct <= ((0x7ffff000 / sizeof(float)) + 1));
543 const float king_cutoff_f = S_CAST(float, king_cutoff);
544 float* king_frow;
545 if (unlikely(bigstack_alloc_f(king_id_ct - 1, &king_frow))) {
546 goto KingCutoffBatchBinary_ret_NOMEM;
547 }
548 for (uint32_t king_idx = 1; king_uidx != king_id_ct; ++king_idx, ++king_uidx) {
549 if (!IsSet(king_include, king_uidx)) {
550 king_uidx = AdvBoundedTo1Bit(king_include, king_uidx + 1, king_id_ct);
551 if (king_uidx == king_id_ct) {
552 break;
553 }
554 if (unlikely(fseeko(binfile, S_CAST(uint64_t, king_uidx) * (king_uidx - 1) * (sizeof(float) / 2), SEEK_SET))) {
555 goto KingCutoffBatchBinary_ret_READ_FAIL;
556 }
557 }
558 if (unlikely(!fread_unlocked(king_frow, king_uidx * sizeof(float), 1, binfile))) {
559 goto KingCutoffBatchBinary_ret_READ_FAIL;
560 }
561 const uintptr_t sample_idx = king_uidx_to_sample_idx[king_uidx];
562 uintptr_t* kinship_table_row = &(kinship_table[sample_idx * orig_sample_ctl]);
563 uintptr_t* kinship_table_col = &(kinship_table[sample_idx / kBitsPerWord]);
564 const uintptr_t kinship_new_bit = k1LU << (sample_idx % kBitsPerWord);
565 uintptr_t king_uidx2_base;
566 uintptr_t king_include_bits;
567 BitIter1Start(king_include, first_king_uidx, &king_uidx2_base, &king_include_bits);
568 for (uint32_t king_idx2 = 0; king_idx2 != king_idx; ++king_idx2) {
569 const uintptr_t king_uidx2 = BitIter1(king_include, &king_uidx2_base, &king_include_bits);
570 if (king_frow[king_uidx2] > king_cutoff_f) {
571 const uintptr_t sample_idx2 = king_uidx_to_sample_idx[king_uidx2];
572 SetBit(sample_idx2, kinship_table_row);
573 kinship_table_col[sample_idx2 * orig_sample_ctl] |= kinship_new_bit;
574 ++constraint_ct;
575 }
576 }
577 }
578 }
579 logprintf("--king-cutoff: %" PRIuPTR " constraint%s loaded.\n", constraint_ct, (constraint_ct == 1)? "" : "s");
580 BigstackReset(sample_uidx_to_king_uidx);
581 if (unlikely(KinshipPruneDestructive(kinship_table, sample_include, sample_ct_ptr))) {
582 goto KingCutoffBatchBinary_ret_NOMEM;
583 }
584 }
585 while (0) {
586 KingCutoffBatchBinary_ret_NOMEM:
587 reterr = kPglRetNomem;
588 break;
589 KingCutoffBatchBinary_ret_OPEN_FAIL:
590 reterr = kPglRetOpenFail;
591 break;
592 KingCutoffBatchBinary_ret_READ_FAIL:
593 if (feof_unlocked(binfile)) {
594 errno = 0;
595 }
596 logerrprintfww(kErrprintfFread, king_cutoff_fprefix, rstrerror(errno));
597 reterr = kPglRetReadFail;
598 break;
599 KingCutoffBatchBinary_ret_MISSING_TOKENS:
600 logerrprintfww("Error: Fewer tokens than expected on line %" PRIuPTR " of %s .\n", line_idx, king_cutoff_fprefix);
601 reterr = kPglRetMalformedInput;
602 break;
603 KingCutoffBatchBinary_ret_TSTREAM_XID_FAIL:
604 if (!TextStreamErrcode(&txs)) {
605 break;
606 }
607 KingCutoffBatchBinary_ret_TSTREAM_FAIL:
608 TextStreamErrPrint(king_cutoff_fprefix, &txs);
609 break;
610 KingCutoffBatchBinary_ret_MALFORMED_INPUT_WW:
611 WordWrapB(0);
612 logerrputsb();
613 KingCutoffBatchBinary_ret_MALFORMED_INPUT:
614 reterr = kPglRetMalformedInput;
615 break;
616 }
617 KingCutoffBatchBinary_ret_1:
618 fclose_cond(binfile);
619 if (CleanupTextStream(&txs, &reterr)) {
620 snprintf(fprefix_end, 9, ".king.id");
621 logerrprintfww(kErrprintfFread, king_cutoff_fprefix, rstrerror(errno));
622 }
623 BigstackReset(bigstack_mark);
624 return reterr;
625 }
626
627 PglErr KingCutoffBatchTable(const SampleIdInfo* siip, const char* kin0_fname, uint32_t raw_sample_ct, double king_cutoff, uintptr_t* sample_include, uint32_t* sample_ct_ptr) {
628 unsigned char* bigstack_mark = g_bigstack_base;
629 uintptr_t line_idx = 0;
630 PglErr reterr = kPglRetSuccess;
631 TextStream txs;
632 PreinitTextStream(&txs);
633 {
634 // defend from ScanadvDouble() rounding error
635 king_cutoff *= 1.0 + kSmallEpsilon;
636
637 const uint32_t orig_sample_ct = *sample_ct_ptr;
638 const uint32_t orig_sample_ctl = BitCtToWordCt(orig_sample_ct);
639 uintptr_t* kinship_table;
640 if (unlikely(bigstack_calloc_w(orig_sample_ct * orig_sample_ctl, &kinship_table))) {
641 goto KingCutoffBatchTable_ret_NOMEM;
642 }
643
644 // possible todo: deduplicate with CalcKingTableSubset() .kin0 header-line
645 // scanner.
646 uint32_t kinship_skip = 0;
647 XidMode xid_mode = siip->sids? kfXidModeFidIidSid : kfXidModeIidSid;
648 reterr = InitTextStream(kin0_fname, kTextStreamBlenFast, 1, &txs);
649 if (unlikely(reterr)) {
650 if (reterr == kPglRetEof) {
651 logerrputs("Error: Empty --king-cutoff-table file.\n");
652 goto KingCutoffBatchTable_ret_MALFORMED_INPUT;
653 }
654 goto KingCutoffBatchTable_ret_TSTREAM_FAIL;
655 }
656 ++line_idx;
657 {
658 // Parse header line.
659 const char* linebuf_iter = TextGet(&txs);
660 if (unlikely(!linebuf_iter)) {
661 if (!TextStreamErrcode2(&txs, &reterr)) {
662 logerrputs("Error: Empty --king-cutoff-table file.\n");
663 goto KingCutoffBatchTable_ret_MALFORMED_INPUT;
664 }
665 goto KingCutoffBatchTable_ret_TSTREAM_FAIL;
666 }
667 const char* token_end = CurTokenEnd(linebuf_iter);
668 uint32_t token_slen = token_end - linebuf_iter;
669 // Make this work with both KING- and plink2-generated .kin0 files.
670 const uint32_t fid_present = strequal_k(linebuf_iter, "#FID1", token_slen) || strequal_k(linebuf_iter, "FID", token_slen);
671 if (fid_present) {
672 linebuf_iter = FirstNonTspace(token_end);
673 token_end = CurTokenEnd(linebuf_iter);
674 token_slen = token_end - linebuf_iter;
675 xid_mode = kfXidModeFidIid;
676 } else {
677 if (unlikely(*linebuf_iter != '#')) {
678 goto KingCutoffBatchTable_ret_INVALID_HEADER;
679 }
680 ++linebuf_iter;
681 --token_slen;
682 xid_mode = kfXidModeIid;
683 }
684 if (unlikely((!strequal_k(linebuf_iter, "ID1", token_slen)) && (!strequal_k(linebuf_iter, "IID1", token_slen)))) {
685 goto KingCutoffBatchTable_ret_INVALID_HEADER;
686 }
687 linebuf_iter = FirstNonTspace(token_end);
688 token_end = CurTokenEnd(linebuf_iter);
689 token_slen = token_end - linebuf_iter;
690 if (strequal_k(linebuf_iter, "SID1", token_slen)) {
691 if (siip->sids) {
692 xid_mode = fid_present? kfXidModeFidIidSid : kfXidModeIidSid;
693 } else {
694 xid_mode |= kfXidModeFlagSkipSid;
695 }
696 linebuf_iter = FirstNonTspace(token_end);
697 token_end = CurTokenEnd(linebuf_iter);
698 token_slen = token_end - linebuf_iter;
699 }
700 if (fid_present) {
701 if (unlikely(!strequal_k(linebuf_iter, "FID2", token_slen))) {
702 goto KingCutoffBatchTable_ret_INVALID_HEADER;
703 }
704 linebuf_iter = FirstNonTspace(token_end);
705 token_end = CurTokenEnd(linebuf_iter);
706 token_slen = token_end - linebuf_iter;
707 }
708 if (unlikely((!strequal_k(linebuf_iter, "ID2", token_slen)) && (!strequal_k(linebuf_iter, "IID2", token_slen)))) {
709 goto KingCutoffBatchTable_ret_INVALID_HEADER;
710 }
711 if (xid_mode & (kfXidModeFlagSid | kfXidModeFlagSkipSid)) {
712 linebuf_iter = FirstNonTspace(token_end);
713 token_end = CurTokenEnd(linebuf_iter);
714 token_slen = token_end - linebuf_iter;
715 if (unlikely(!strequal_k(linebuf_iter, "SID2", token_slen))) {
716 goto KingCutoffBatchTable_ret_INVALID_HEADER;
717 }
718 }
719 while (1) {
720 linebuf_iter = FirstNonTspace(token_end);
721 token_end = CurTokenEnd(linebuf_iter);
722 token_slen = token_end - linebuf_iter;
723 if (unlikely(!token_slen)) {
724 logerrputs("Error: No kinship-coefficient column in --king-cutoff-table file.\n");
725 goto KingCutoffBatchTable_ret_INCONSISTENT_INPUT;
726 }
727 if (strequal_k(linebuf_iter, "KINSHIP", token_slen) || strequal_k(linebuf_iter, "Kinship", token_slen)) {
728 break;
729 }
730 ++kinship_skip;
731 }
732 }
733
734 uint32_t* xid_cmap;
735 char* sorted_xidbox;
736 uintptr_t max_xid_blen;
737 {
738 uint32_t* xid_umap; // IDs not collapsed
739 reterr = SortedXidboxInitAlloc(sample_include, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_umap, &max_xid_blen);
740 if (unlikely(reterr)) {
741 goto KingCutoffBatchTable_ret_1;
742 }
743 xid_cmap = xid_umap;
744 if (orig_sample_ct != raw_sample_ct) {
745 // Convert to collapsed IDs in-place.
746 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
747 uint32_t* sample_include_cumulative_popcounts;
748 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts))) {
749 goto KingCutoffBatchTable_ret_NOMEM;
750 }
751 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
752 UidxsToIdxs(sample_include, sample_include_cumulative_popcounts, orig_sample_ct, xid_cmap);
753 BigstackReset(sample_include_cumulative_popcounts);
754 }
755 }
756 char* idbuf;
757 if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) {
758 goto KingCutoffBatchTable_ret_NOMEM;
759 }
760
761 // possible todo: deduplicate with KingTableSubsetLoad().
762 ++line_idx;
763 uintptr_t constraint_ct = 0;
764 for (char* line_iter = TextLineEnd(&txs); TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
765 const char* linebuf_iter = line_iter;
766 uint32_t sample_idx1;
767 if (SortedXidboxReadFind(sorted_xidbox, xid_cmap, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_idx1, idbuf)) {
768 if (unlikely(!linebuf_iter)) {
769 goto KingCutoffBatchTable_ret_MISSING_TOKENS;
770 }
771 line_iter = K_CAST(char*, linebuf_iter);
772 continue;
773 }
774 linebuf_iter = FirstNonTspace(linebuf_iter);
775 uint32_t sample_idx2;
776 if (SortedXidboxReadFind(sorted_xidbox, xid_cmap, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_idx2, idbuf)) {
777 if (unlikely(!linebuf_iter)) {
778 goto KingCutoffBatchTable_ret_MISSING_TOKENS;
779 }
780 line_iter = K_CAST(char*, linebuf_iter);
781 continue;
782 }
783 if (unlikely(sample_idx1 == sample_idx2)) {
784 // could technically be due to unloaded SID, so use inconsistent-input
785 // error code
786 snprintf(g_logbuf, kLogbufSize, "Error: Identical sample IDs on line %" PRIuPTR " of --king-cutoff-table file.\n", line_idx);
787 goto KingCutoffBatchTable_ret_INCONSISTENT_INPUT_WW;
788 }
789 linebuf_iter = FirstNonTspace(linebuf_iter);
790 linebuf_iter = NextTokenMult0(linebuf_iter, kinship_skip);
791 if (unlikely(!linebuf_iter)) {
792 goto KingCutoffBatchTable_ret_MISSING_TOKENS;
793 }
794 double cur_kinship;
795 const char* kinship_end = ScanadvDouble(linebuf_iter, &cur_kinship);
796 if (!kinship_end) {
797 line_iter = K_CAST(char*, linebuf_iter);
798 continue;
799 }
800 if (unlikely(!IsSpaceOrEoln(*kinship_end))) {
801 kinship_end = CurTokenEnd(kinship_end);
802 *K_CAST(char*, kinship_end) = '\0';
803 logerrprintfww("Error: Invalid numeric token '%s' on line %" PRIuPTR " of --king-cutoff-table file.\n", linebuf_iter, line_idx);
804 goto KingCutoffBatchTable_ret_MALFORMED_INPUT;
805 }
806 if (cur_kinship > king_cutoff) {
807 SetBit(sample_idx2, &(kinship_table[sample_idx1 * orig_sample_ctl]));
808 SetBit(sample_idx1, &(kinship_table[sample_idx2 * orig_sample_ctl]));
809 ++constraint_ct;
810 }
811 }
812
813 logprintf("--king-cutoff-table: %" PRIuPTR " constraint%s loaded.\n", constraint_ct, (constraint_ct == 1)? "" : "s");
814 if (unlikely(KinshipPruneDestructive(kinship_table, sample_include, sample_ct_ptr))) {
815 goto KingCutoffBatchTable_ret_NOMEM;
816 }
817 }
818 while (0) {
819 KingCutoffBatchTable_ret_NOMEM:
820 reterr = kPglRetNomem;
821 break;
822 KingCutoffBatchTable_ret_MISSING_TOKENS:
823 logerrprintfww("Error: Fewer tokens than expected on line %" PRIuPTR " of %s .\n", line_idx, kin0_fname);
824 reterr = kPglRetMalformedInput;
825 break;
826 KingCutoffBatchTable_ret_TSTREAM_FAIL:
827 TextStreamErrPrint(kin0_fname, &txs);
828 break;
829 KingCutoffBatchTable_ret_INVALID_HEADER:
830 logerrputs("Error: Invalid header line in --king-cutoff-table file.\n");
831 reterr = kPglRetMalformedInput;
832 break;
833 KingCutoffBatchTable_ret_MALFORMED_INPUT:
834 reterr = kPglRetMalformedInput;
835 break;
836 KingCutoffBatchTable_ret_INCONSISTENT_INPUT_WW:
837 WordWrapB(0);
838 logerrputsb();
839 KingCutoffBatchTable_ret_INCONSISTENT_INPUT:
840 reterr = kPglRetInconsistentInput;
841 break;
842 }
843 KingCutoffBatchTable_ret_1:
844 BigstackReset(bigstack_mark);
845 return reterr;
846 }
847
848 CONSTI32(kKingOffsetIbs0, 0);
849 CONSTI32(kKingOffsetHethet, 1);
850 CONSTI32(kKingOffsetHet2Hom1, 2);
851 CONSTI32(kKingOffsetHet1Hom2, 3);
852 CONSTI32(kKingOffsetHomhom, 4);
853
854 typedef struct CalcKingSparseCtxStruct {
855 const uintptr_t* variant_include_orig;
856 uintptr_t* sample_include;
857 uint32_t* sample_include_cumulative_popcounts;
858 uint32_t row_start_idx;
859 uint32_t row_end_idx;
860 uint32_t homhom_needed;
861
862 uint32_t max_sparse_ct;
863
864 uint32_t read_block_size; // guaranteed to be power of 2
865
866 PgenReader** pgr_ptrs;
867 uintptr_t** genovecs;
868 uint32_t* read_variant_uidx_starts;
869
870 // this has length >= 3 * max_sparse_ct
871 uint32_t** thread_idx_bufs;
872
873 uint32_t cur_block_size;
874
875 uint32_t** thread_singleton_het_cts;
876 uint32_t** thread_singleton_hom_cts;
877 uint32_t** thread_singleton_missing_cts;
878 uint32_t* thread_skip_cts;
879
880 // single global copy
881 uint32_t* king_counts;
882
883 uintptr_t** thread_sparse_excludes[2];
884
885 uint64_t err_info;
886 } CalcKingSparseCtx;
887
888 THREAD_FUNC_DECL CalcKingSparseThread(void* raw_arg) {
889 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
890 const uintptr_t tidx = arg->tidx;
891 CalcKingSparseCtx* ctx = S_CAST(CalcKingSparseCtx*, arg->sharedp->context);
892
893 const uintptr_t* variant_include_orig = ctx->variant_include_orig;
894 const uintptr_t* sample_include = ctx->sample_include;
895
896 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
897 PgrSampleSubsetIndex pssi;
898 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
899 uintptr_t* genovec = ctx->genovecs[tidx];
900 uint32_t row_start_idx = ctx->row_start_idx;
901 const uint64_t tri_start = ((row_start_idx - 1) * S_CAST(uint64_t, row_start_idx)) / 2;
902 if (row_start_idx == 1) {
903 row_start_idx = 0;
904 }
905 const uint32_t sample_ct = ctx->row_end_idx;
906 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
907 const uint32_t remainder = sample_ct % kBitsPerWordD2;
908 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
909 const uint32_t homhom_needed = ctx->homhom_needed;
910 const uintptr_t homhom_needed_p4 = homhom_needed + 4;
911 const uint32_t max_sparse_ct = ctx->max_sparse_ct;
912 const uint32_t read_block_size_mask = ctx->read_block_size - 1;
913 const uint32_t read_block_sizel = ctx->read_block_size / kBitsPerWord;
914
915 uint32_t* idx_bufs[4];
916 idx_bufs[0] = nullptr;
917 idx_bufs[1] = ctx->thread_idx_bufs[tidx];
918 idx_bufs[2] = &(idx_bufs[1][max_sparse_ct]);
919 idx_bufs[3] = &(idx_bufs[2][max_sparse_ct]);
920 const uint32_t min_common_ct = sample_ct - max_sparse_ct;
921
922 uint32_t* singleton_het_cts = ctx->thread_singleton_het_cts[tidx];
923 uint32_t* singleton_hom_cts = ctx->thread_singleton_hom_cts[tidx];
924 uint32_t* singleton_missing_cts = ctx->thread_singleton_missing_cts[tidx];
925 ZeroU32Arr(sample_ct, singleton_het_cts);
926 ZeroU32Arr(sample_ct, singleton_hom_cts);
927 ZeroU32Arr(sample_ct, singleton_missing_cts);
928 uint32_t skip_ct = 0;
929
930 uint32_t* king_counts = ctx->king_counts;
931 uint64_t new_err_info = 0;
932 {
933 // This matrix can be huge, so we multithread zero-initialization.
934 const uint64_t entry_ct = homhom_needed_p4 * (((sample_ct - 1) * S_CAST(uint64_t, sample_ct)) / 2 - tri_start);
935 const uintptr_t fill_start = RoundDownPow2((tidx * entry_ct) / calc_thread_ct, kInt32PerCacheline);
936 uintptr_t fill_end = entry_ct;
937 if (tidx + 1 != calc_thread_ct) {
938 fill_end = RoundDownPow2(((tidx + 1) * entry_ct) / calc_thread_ct, kInt32PerCacheline);
939 }
940 ZeroU32Arr(fill_end - fill_start, &(king_counts[fill_start]));
941 }
942 uint32_t parity = 0;
943 // sync.Once before main loop; we need the other threads to be done with
944 // their zero-initialization jobs before we can proceed.
945 while (!THREAD_BLOCK_FINISH(arg)) {
946 const uint32_t cur_block_size = ctx->cur_block_size;
947 const uint32_t idx_end = ((tidx + 1) * cur_block_size) / calc_thread_ct;
948 uintptr_t variant_uidx_base;
949 uintptr_t variant_include_bits;
950 BitIter1Start(variant_include_orig, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
951 uintptr_t* sparse_exclude = ctx->thread_sparse_excludes[parity][tidx];
952 ZeroWArr(read_block_sizel, sparse_exclude);
953 // probable todo: better load-balancing
954 for (uint32_t cur_idx = (tidx * cur_block_size) / calc_thread_ct; cur_idx != idx_end; ++cur_idx) {
955 const uint32_t variant_uidx = BitIter1(variant_include_orig, &variant_uidx_base, &variant_include_bits);
956 // tried DifflistOrGenovec, difference was negligible. Not really worth
957 // considering it when calculation is inherently >O(mn).
958 const PglErr reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, pgrp, genovec);
959 if (unlikely(reterr)) {
960 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
961 goto CalcKingSparseThread_err;
962 }
963 STD_ARRAY_DECL(uint32_t, 4, genocounts);
964 ZeroTrailingNyps(sample_ct, genovec);
965 GenoarrCountFreqsUnsafe(genovec, sample_ct, genocounts);
966 uintptr_t mask_word;
967 uintptr_t common_idx;
968 if (genocounts[0] >= min_common_ct) {
969 common_idx = 0;
970 mask_word = 0;
971 } else if (genocounts[2] >= min_common_ct) {
972 common_idx = 2;
973 mask_word = kMaskAAAA;
974 } else if (genocounts[3] >= min_common_ct) {
975 common_idx = 3;
976 mask_word = ~k0LU;
977 ++skip_ct;
978 } else {
979 if ((!homhom_needed) && ((genocounts[0] + genocounts[3] == sample_ct) || (genocounts[2] + genocounts[3] == sample_ct))) {
980 SetBit(variant_uidx & read_block_size_mask, sparse_exclude);
981 ++skip_ct;
982 }
983 continue;
984 }
985 SetBit(variant_uidx & read_block_size_mask, sparse_exclude);
986 if (genocounts[common_idx] == sample_ct) {
987 continue;
988 }
989 if (remainder) {
990 genovec[sample_ctl2 - 1] |= mask_word << (2 * remainder);
991 }
992 uint32_t* idx_buf_iters[4];
993 memcpy(idx_buf_iters, idx_bufs, 4 * sizeof(intptr_t));
994 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
995 uintptr_t xor_word = genovec[widx] ^ mask_word;
996 if (xor_word) {
997 const uint32_t offset_base = widx * kBitsPerWordD2;
998 do {
999 const uint32_t shift_ct = ctzw(xor_word) & (~1);
1000 const uint32_t cur_xor = (xor_word >> shift_ct) & 3;
1001 *(idx_buf_iters[cur_xor])++ = offset_base + (shift_ct / 2);
1002 xor_word &= ~((3 * k1LU) << shift_ct);
1003 } while (xor_word);
1004 }
1005 }
1006 // We do two things here.
1007 // 1. Update singleton_{het,hom,missing}_cts for every observed rare
1008 // genotype. This is enough for correct accounting for any pair
1009 // involving only one (or none) of these rare genotypes, and the
1010 // arrays are small enough that each thread can keep its own copy
1011 // (they're added up at the end).
1012 // 2. For each pair of rare genotypes, atomically correct the main
1013 // king_counts[] array. This is messy (9x2 cases) but conceptually
1014 // straightforward.
1015 const uint32_t* het_idxs = idx_bufs[common_idx ^ 1];
1016 const uint32_t het_ct = genocounts[1];
1017 if (common_idx != 3) {
1018 const uint32_t* other_hom_idxs = idx_bufs[2];
1019 const uint32_t* missing_idxs = idx_bufs[common_idx ^ 3];
1020 const uint32_t other_hom_ct = idx_buf_iters[2] - other_hom_idxs;
1021 const uint32_t missing_ct = genocounts[3];
1022 for (uint32_t uii = 0; uii != het_ct; ++uii) {
1023 // We want to iterate over one row at a time, for better
1024 // memory-access locality. So the outer loop must correspond to the
1025 // larger sample-index.
1026 const uintptr_t sample_idx_hi = het_idxs[uii];
1027 singleton_het_cts[sample_idx_hi] += 1;
1028 if (sample_idx_hi < row_start_idx) {
1029 continue;
1030 }
1031 const uintptr_t tri_base = (S_CAST(uint64_t, sample_idx_hi) * (sample_idx_hi - 1)) / 2 - tri_start;
1032 for (uint32_t ujj = 0; ujj != uii; ++ujj) {
1033 const uintptr_t sample_idx_lo = het_idxs[ujj];
1034 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1035 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1036 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHethet]), 1, __ATOMIC_RELAXED);
1037 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetHet2Hom1]), 1, __ATOMIC_RELAXED);
1038 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetHet1Hom2]), 1, __ATOMIC_RELAXED);
1039 if (homhom_needed) {
1040 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1041 }
1042 }
1043 for (uint32_t ujj = 0; ujj != other_hom_ct; ++ujj) {
1044 const uintptr_t sample_idx_lo = other_hom_idxs[ujj];
1045 if (sample_idx_lo > sample_idx_hi) {
1046 break;
1047 }
1048 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1049 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1050 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetIbs0]), 1, __ATOMIC_RELAXED);
1051 }
1052 for (uint32_t ujj = 0; ujj != missing_ct; ++ujj) {
1053 const uintptr_t sample_idx_lo = missing_idxs[ujj];
1054 if (sample_idx_lo > sample_idx_hi) {
1055 break;
1056 }
1057 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1058 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1059 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetHet2Hom1]), 1, __ATOMIC_RELAXED);
1060 if (homhom_needed) {
1061 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1062 }
1063 }
1064 }
1065 for (uint32_t uii = 0; uii != other_hom_ct; ++uii) {
1066 const uintptr_t sample_idx_hi = other_hom_idxs[uii];
1067 singleton_hom_cts[sample_idx_hi] += 1;
1068 if (sample_idx_hi < row_start_idx) {
1069 continue;
1070 }
1071 const uintptr_t tri_base = (S_CAST(uint64_t, sample_idx_hi) * (sample_idx_hi - 1)) / 2 - tri_start;
1072 for (uint32_t ujj = 0; ujj != uii; ++ujj) {
1073 const uintptr_t sample_idx_lo = other_hom_idxs[ujj];
1074 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1075 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1076 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetIbs0]), 2, __ATOMIC_RELAXED);
1077 }
1078 for (uint32_t ujj = 0; ujj != het_ct; ++ujj) {
1079 const uintptr_t sample_idx_lo = het_idxs[ujj];
1080 if (sample_idx_lo > sample_idx_hi) {
1081 break;
1082 }
1083 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1084 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1085 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetIbs0]), 1, __ATOMIC_RELAXED);
1086 }
1087 for (uint32_t ujj = 0; ujj != missing_ct; ++ujj) {
1088 const uintptr_t sample_idx_lo = missing_idxs[ujj];
1089 if (sample_idx_lo > sample_idx_hi) {
1090 break;
1091 }
1092 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1093 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1094 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetIbs0]), 1, __ATOMIC_RELAXED);
1095 if (homhom_needed) {
1096 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1097 }
1098 }
1099 }
1100 for (uint32_t uii = 0; uii != missing_ct; ++uii) {
1101 const uintptr_t sample_idx_hi = missing_idxs[uii];
1102 singleton_missing_cts[sample_idx_hi] += 1;
1103 if (sample_idx_hi < row_start_idx) {
1104 continue;
1105 }
1106 const uintptr_t tri_base = (S_CAST(uint64_t, sample_idx_hi) * (sample_idx_hi - 1)) / 2 - tri_start;
1107 if (homhom_needed) {
1108 for (uint32_t ujj = 0; ujj != uii; ++ujj) {
1109 const uintptr_t sample_idx_lo = missing_idxs[ujj];
1110 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1111 // bugfix (12 Nov 2019): added 4 twice
1112 uint32_t* king_counts_ptr = &(king_counts[tri_coord * 5]);
1113 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1114 }
1115 }
1116 for (uint32_t ujj = 0; ujj != het_ct; ++ujj) {
1117 const uintptr_t sample_idx_lo = het_idxs[ujj];
1118 if (sample_idx_lo > sample_idx_hi) {
1119 break;
1120 }
1121 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1122 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1123 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetHet1Hom2]), 1, __ATOMIC_RELAXED);
1124 if (homhom_needed) {
1125 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1126 }
1127 }
1128 for (uint32_t ujj = 0; ujj != other_hom_ct; ++ujj) {
1129 const uintptr_t sample_idx_lo = other_hom_idxs[ujj];
1130 if (sample_idx_lo > sample_idx_hi) {
1131 break;
1132 }
1133 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1134 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1135 __atomic_fetch_sub(&(king_counts_ptr[kKingOffsetIbs0]), 1, __ATOMIC_RELAXED);
1136 if (homhom_needed) {
1137 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1138 }
1139 }
1140 }
1141 } else {
1142 // merge hom0 and hom2 cases.
1143 for (uint32_t hom_geno = 0; hom_geno != 4; hom_geno += 2) {
1144 const uint32_t* cur_hom_idxs = idx_bufs[3 - hom_geno];
1145 const uint32_t* opp_hom_idxs = idx_bufs[1 + hom_geno];
1146 const uint32_t cur_hom_ct = genocounts[hom_geno];
1147 const uint32_t opp_hom_ct = genocounts[2 - hom_geno];
1148 for (uint32_t uii = 0; uii != cur_hom_ct; ++uii) {
1149 const uintptr_t sample_idx_hi = cur_hom_idxs[uii];
1150 if (sample_idx_hi < row_start_idx) {
1151 continue;
1152 }
1153 const uintptr_t tri_base = (S_CAST(uint64_t, sample_idx_hi) * (sample_idx_hi - 1)) / 2 - tri_start;
1154 if (homhom_needed) {
1155 for (uint32_t ujj = 0; ujj != uii; ++ujj) {
1156 const uintptr_t sample_idx_lo = cur_hom_idxs[ujj];
1157 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1158 uint32_t* king_counts_ptr = &(king_counts[tri_coord * 5]);
1159 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1160 }
1161 }
1162 for (uint32_t ujj = 0; ujj != het_ct; ++ujj) {
1163 const uintptr_t sample_idx_lo = het_idxs[ujj];
1164 if (sample_idx_lo > sample_idx_hi) {
1165 break;
1166 }
1167 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1168 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1169 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHet1Hom2]), 1, __ATOMIC_RELAXED);
1170 }
1171 for (uint32_t ujj = 0; ujj != opp_hom_ct; ++ujj) {
1172 const uintptr_t sample_idx_lo = opp_hom_idxs[ujj];
1173 if (sample_idx_lo > sample_idx_hi) {
1174 break;
1175 }
1176 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1177 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1178 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetIbs0]), 1, __ATOMIC_RELAXED);
1179 if (homhom_needed) {
1180 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHomhom]), 1, __ATOMIC_RELAXED);
1181 }
1182 }
1183 }
1184 }
1185 const uint32_t* hom0_idxs = idx_bufs[3];
1186 const uint32_t* hom2_idxs = idx_bufs[1];
1187 const uint32_t hom0_ct = genocounts[0];
1188 const uint32_t hom2_ct = genocounts[2];
1189 for (uint32_t uii = 0; uii != het_ct; ++uii) {
1190 const uintptr_t sample_idx_hi = het_idxs[uii];
1191 if (sample_idx_hi < row_start_idx) {
1192 continue;
1193 }
1194 const uintptr_t tri_base = (S_CAST(uint64_t, sample_idx_hi) * (sample_idx_hi - 1)) / 2 - tri_start;
1195 for (uint32_t ujj = 0; ujj != uii; ++ujj) {
1196 const uintptr_t sample_idx_lo = het_idxs[ujj];
1197 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1198 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1199 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHethet]), 1, __ATOMIC_RELAXED);
1200 }
1201 for (uint32_t ujj = 0; ujj != hom0_ct; ++ujj) {
1202 const uintptr_t sample_idx_lo = hom0_idxs[ujj];
1203 if (sample_idx_lo > sample_idx_hi) {
1204 break;
1205 }
1206 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1207 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1208 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHet2Hom1]), 1, __ATOMIC_RELAXED);
1209 }
1210 for (uint32_t ujj = 0; ujj != hom2_ct; ++ujj) {
1211 const uintptr_t sample_idx_lo = hom2_idxs[ujj];
1212 if (sample_idx_lo > sample_idx_hi) {
1213 break;
1214 }
1215 const uintptr_t tri_coord = tri_base + sample_idx_lo;
1216 uint32_t* king_counts_ptr = &(king_counts[tri_coord * homhom_needed_p4]);
1217 __atomic_fetch_add(&(king_counts_ptr[kKingOffsetHet2Hom1]), 1, __ATOMIC_RELAXED);
1218 }
1219 }
1220 }
1221 }
1222 parity = 1 - parity;
1223 }
1224 {
1225 ctx->thread_skip_cts[tidx] = skip_ct;
1226 }
1227 while (0) {
1228 CalcKingSparseThread_err:
1229 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
1230 THREAD_BLOCK_FINISH(arg);
1231 break;
1232 }
1233 THREAD_RETURN;
1234 }
1235
1236 #ifdef USE_SSE42
1237 CONSTI32(kKingMultiplex, 1024);
1238 CONSTI32(kKingMultiplexWords, kKingMultiplex / kBitsPerWord);
1239 void IncrKing(const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts_iter) {
1240 // Tried adding another level of blocking, but couldn't get it to make a
1241 // difference.
1242 for (uint32_t second_idx = start_idx; second_idx != end_idx; ++second_idx) {
1243 // technically overflows for huge sample_ct
1244 const uint32_t second_offset = second_idx * kKingMultiplexWords;
1245 const uintptr_t* second_hom = &(smaj_hom[second_offset]);
1246 const uintptr_t* second_ref2het = &(smaj_ref2het[second_offset]);
1247 const uintptr_t* first_hom_iter = smaj_hom;
1248 const uintptr_t* first_ref2het_iter = smaj_ref2het;
1249 while (first_hom_iter < second_hom) {
1250 uint32_t acc_ibs0 = 0;
1251 uint32_t acc_hethet = 0;
1252 uint32_t acc_het2hom1 = 0;
1253 uint32_t acc_het1hom2 = 0;
1254 for (uint32_t widx = 0; widx != kKingMultiplexWords; ++widx) {
1255 const uintptr_t hom1 = first_hom_iter[widx];
1256 const uintptr_t hom2 = second_hom[widx];
1257 const uintptr_t ref2het1 = first_ref2het_iter[widx];
1258 const uintptr_t ref2het2 = second_ref2het[widx];
1259 const uintptr_t homhom = hom1 & hom2;
1260 const uintptr_t het1 = ref2het1 & (~hom1);
1261 const uintptr_t het2 = ref2het2 & (~hom2);
1262 acc_ibs0 += PopcountWord((ref2het1 ^ ref2het2) & homhom);
1263 acc_hethet += PopcountWord(het1 & het2);
1264 acc_het2hom1 += PopcountWord(hom1 & het2);
1265 acc_het1hom2 += PopcountWord(hom2 & het1);
1266 }
1267 king_counts_iter[kKingOffsetIbs0] += acc_ibs0;
1268 king_counts_iter[kKingOffsetHethet] += acc_hethet;
1269 king_counts_iter[kKingOffsetHet2Hom1] += acc_het2hom1;
1270 king_counts_iter[kKingOffsetHet1Hom2] += acc_het1hom2;
1271 king_counts_iter = &(king_counts_iter[4]);
1272
1273 first_hom_iter = &(first_hom_iter[kKingMultiplexWords]);
1274 first_ref2het_iter = &(first_ref2het_iter[kKingMultiplexWords]);
1275 }
1276 }
1277 }
1278
1279 void IncrKingHomhom(const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts_iter) {
1280 for (uint32_t second_idx = start_idx; second_idx != end_idx; ++second_idx) {
1281 // technically overflows for huge sample_ct
1282 const uint32_t second_offset = second_idx * kKingMultiplexWords;
1283 const uintptr_t* second_hom = &(smaj_hom[second_offset]);
1284 const uintptr_t* second_ref2het = &(smaj_ref2het[second_offset]);
1285 const uintptr_t* first_hom_iter = smaj_hom;
1286 const uintptr_t* first_ref2het_iter = smaj_ref2het;
1287 while (first_hom_iter < second_hom) {
1288 uint32_t acc_homhom = 0;
1289 uint32_t acc_ibs0 = 0;
1290 uint32_t acc_hethet = 0;
1291 uint32_t acc_het2hom1 = 0;
1292 uint32_t acc_het1hom2 = 0;
1293 for (uint32_t widx = 0; widx != kKingMultiplexWords; ++widx) {
1294 const uintptr_t hom1 = first_hom_iter[widx];
1295 const uintptr_t hom2 = second_hom[widx];
1296 const uintptr_t ref2het1 = first_ref2het_iter[widx];
1297 const uintptr_t ref2het2 = second_ref2het[widx];
1298 const uintptr_t homhom = hom1 & hom2;
1299 const uintptr_t het1 = ref2het1 & (~hom1);
1300 const uintptr_t het2 = ref2het2 & (~hom2);
1301 acc_homhom += PopcountWord(homhom);
1302 acc_ibs0 += PopcountWord((ref2het1 ^ ref2het2) & homhom);
1303 acc_hethet += PopcountWord(het1 & het2);
1304 acc_het2hom1 += PopcountWord(hom1 & het2);
1305 acc_het1hom2 += PopcountWord(hom2 & het1);
1306 }
1307 king_counts_iter[kKingOffsetIbs0] += acc_ibs0;
1308 king_counts_iter[kKingOffsetHethet] += acc_hethet;
1309 king_counts_iter[kKingOffsetHet2Hom1] += acc_het2hom1;
1310 king_counts_iter[kKingOffsetHet1Hom2] += acc_het1hom2;
1311 king_counts_iter[kKingOffsetHomhom] += acc_homhom;
1312 king_counts_iter = &(king_counts_iter[5]);
1313
1314 first_hom_iter = &(first_hom_iter[kKingMultiplexWords]);
1315 first_ref2het_iter = &(first_ref2het_iter[kKingMultiplexWords]);
1316 }
1317 }
1318 }
1319 #else // !USE_SSE42
1320 # ifdef __LP64__
1321 CONSTI32(kKingMultiplex, 1536);
1322 # else
1323 CONSTI32(kKingMultiplex, 960);
1324 # endif
1325 static_assert(kKingMultiplex % (3 * kBitsPerVec) == 0, "Invalid kKingMultiplex value.");
1326 CONSTI32(kKingMultiplexWords, kKingMultiplex / kBitsPerWord);
1327 CONSTI32(kKingMultiplexVecs, kKingMultiplex / kBitsPerVec);
1328 // expensive PopcountWord(). Use Lauradoux/Walisch accumulators, since
1329 // Harley-Seal requires too many variables.
1330 void IncrKing(const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts_iter) {
1331 const VecW m1 = VCONST_W(kMask5555);
1332 const VecW m2 = VCONST_W(kMask3333);
1333 const VecW m4 = VCONST_W(kMask0F0F);
1334 for (uint32_t second_idx = start_idx; second_idx != end_idx; ++second_idx) {
1335 // technically overflows for huge sample_ct
1336 const uint32_t second_offset = second_idx * kKingMultiplexWords;
1337 const VecW* second_hom = R_CAST(const VecW*, &(smaj_hom[second_offset]));
1338 const VecW* second_ref2het = R_CAST(const VecW*, &(smaj_ref2het[second_offset]));
1339 const VecW* first_hom_iter = R_CAST(const VecW*, smaj_hom);
1340 const VecW* first_ref2het_iter = R_CAST(const VecW*, smaj_ref2het);
1341 while (first_hom_iter < second_hom) {
1342 UniVec acc_ibs0;
1343 UniVec acc_hethet;
1344 UniVec acc_het2hom1;
1345 UniVec acc_het1hom2;
1346 acc_ibs0.vw = vecw_setzero();
1347 acc_hethet.vw = vecw_setzero();
1348 acc_het2hom1.vw = vecw_setzero();
1349 acc_het1hom2.vw = vecw_setzero();
1350 for (uint32_t vec_idx = 0; vec_idx < kKingMultiplexVecs; vec_idx += 3) {
1351 VecW hom1 = first_hom_iter[vec_idx];
1352 VecW hom2 = second_hom[vec_idx];
1353 VecW ref2het1 = first_ref2het_iter[vec_idx];
1354 VecW ref2het2 = second_ref2het[vec_idx];
1355 VecW het1 = vecw_and_notfirst(hom1, ref2het1);
1356 VecW het2 = vecw_and_notfirst(hom2, ref2het2);
1357 VecW agg_ibs0 = (ref2het1 ^ ref2het2) & (hom1 & hom2);
1358 VecW agg_hethet = het1 & het2;
1359 VecW agg_het2hom1 = hom1 & het2;
1360 VecW agg_het1hom2 = hom2 & het1;
1361 agg_ibs0 = agg_ibs0 - (vecw_srli(agg_ibs0, 1) & m1);
1362 agg_hethet = agg_hethet - (vecw_srli(agg_hethet, 1) & m1);
1363 agg_het2hom1 = agg_het2hom1 - (vecw_srli(agg_het2hom1, 1) & m1);
1364 agg_het1hom2 = agg_het1hom2 - (vecw_srli(agg_het1hom2, 1) & m1);
1365 agg_ibs0 = (agg_ibs0 & m2) + (vecw_srli(agg_ibs0, 2) & m2);
1366 agg_hethet = (agg_hethet & m2) + (vecw_srli(agg_hethet, 2) & m2);
1367 agg_het2hom1 = (agg_het2hom1 & m2) + (vecw_srli(agg_het2hom1, 2) & m2);
1368 agg_het1hom2 = (agg_het1hom2 & m2) + (vecw_srli(agg_het1hom2, 2) & m2);
1369
1370 for (uint32_t offset = 1; offset != 3; ++offset) {
1371 hom1 = first_hom_iter[vec_idx + offset];
1372 hom2 = second_hom[vec_idx + offset];
1373 ref2het1 = first_ref2het_iter[vec_idx + offset];
1374 ref2het2 = second_ref2het[vec_idx + offset];
1375 het1 = vecw_and_notfirst(hom1, ref2het1);
1376 het2 = vecw_and_notfirst(hom2, ref2het2);
1377 VecW cur_ibs0 = (ref2het1 ^ ref2het2) & (hom1 & hom2);
1378 VecW cur_hethet = het1 & het2;
1379 VecW cur_het2hom1 = hom1 & het2;
1380 VecW cur_het1hom2 = hom2 & het1;
1381 cur_ibs0 = cur_ibs0 - (vecw_srli(cur_ibs0, 1) & m1);
1382 cur_hethet = cur_hethet - (vecw_srli(cur_hethet, 1) & m1);
1383 cur_het2hom1 = cur_het2hom1 - (vecw_srli(cur_het2hom1, 1) & m1);
1384 cur_het1hom2 = cur_het1hom2 - (vecw_srli(cur_het1hom2, 1) & m1);
1385 agg_ibs0 += (cur_ibs0 & m2) + (vecw_srli(cur_ibs0, 2) & m2);
1386 agg_hethet += (cur_hethet & m2) + (vecw_srli(cur_hethet, 2) & m2);
1387 agg_het2hom1 += (cur_het2hom1 & m2) + (vecw_srli(cur_het2hom1, 2) & m2);
1388 agg_het1hom2 += (cur_het1hom2 & m2) + (vecw_srli(cur_het1hom2, 2) & m2);
1389 }
1390 acc_ibs0.vw = acc_ibs0.vw + (agg_ibs0 & m4) + (vecw_srli(agg_ibs0, 4) & m4);
1391 acc_hethet.vw = acc_hethet.vw + (agg_hethet & m4) + (vecw_srli(agg_hethet, 4) & m4);
1392 acc_het2hom1.vw = acc_het2hom1.vw + (agg_het2hom1 & m4) + (vecw_srli(agg_het2hom1, 4) & m4);
1393 acc_het1hom2.vw = acc_het1hom2.vw + (agg_het1hom2 & m4) + (vecw_srli(agg_het1hom2, 4) & m4);
1394 }
1395 const VecW m8 = VCONST_W(kMask00FF);
1396 acc_ibs0.vw = (acc_ibs0.vw & m8) + (vecw_srli(acc_ibs0.vw, 8) & m8);
1397 acc_hethet.vw = (acc_hethet.vw & m8) + (vecw_srli(acc_hethet.vw, 8) & m8);
1398 acc_het2hom1.vw = (acc_het2hom1.vw & m8) + (vecw_srli(acc_het2hom1.vw, 8) & m8);
1399 acc_het1hom2.vw = (acc_het1hom2.vw & m8) + (vecw_srli(acc_het1hom2.vw, 8) & m8);
1400 king_counts_iter[kKingOffsetIbs0] += UniVecHsum16(acc_ibs0);
1401 king_counts_iter[kKingOffsetHethet] += UniVecHsum16(acc_hethet);
1402 king_counts_iter[kKingOffsetHet2Hom1] += UniVecHsum16(acc_het2hom1);
1403 king_counts_iter[kKingOffsetHet1Hom2] += UniVecHsum16(acc_het1hom2);
1404 king_counts_iter = &(king_counts_iter[4]);
1405
1406 first_hom_iter = &(first_hom_iter[kKingMultiplexVecs]);
1407 first_ref2het_iter = &(first_ref2het_iter[kKingMultiplexVecs]);
1408 }
1409 }
1410 }
1411
1412 void IncrKingHomhom(const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts_iter) {
1413 const VecW m1 = VCONST_W(kMask5555);
1414 const VecW m2 = VCONST_W(kMask3333);
1415 const VecW m4 = VCONST_W(kMask0F0F);
1416 for (uint32_t second_idx = start_idx; second_idx != end_idx; ++second_idx) {
1417 // technically overflows for huge sample_ct
1418 const uint32_t second_offset = second_idx * kKingMultiplexWords;
1419 const VecW* second_hom = R_CAST(const VecW*, &(smaj_hom[second_offset]));
1420 const VecW* second_ref2het = R_CAST(const VecW*, &(smaj_ref2het[second_offset]));
1421 const VecW* first_hom_iter = R_CAST(const VecW*, smaj_hom);
1422 const VecW* first_ref2het_iter = R_CAST(const VecW*, smaj_ref2het);
1423 while (first_hom_iter < second_hom) {
1424 UniVec acc_homhom;
1425 UniVec acc_ibs0;
1426 UniVec acc_hethet;
1427 UniVec acc_het2hom1;
1428 UniVec acc_het1hom2;
1429 acc_homhom.vw = vecw_setzero();
1430 acc_ibs0.vw = vecw_setzero();
1431 acc_hethet.vw = vecw_setzero();
1432 acc_het2hom1.vw = vecw_setzero();
1433 acc_het1hom2.vw = vecw_setzero();
1434 for (uint32_t vec_idx = 0; vec_idx < kKingMultiplexVecs; vec_idx += 3) {
1435 VecW hom1 = first_hom_iter[vec_idx];
1436 VecW hom2 = second_hom[vec_idx];
1437 VecW ref2het1 = first_ref2het_iter[vec_idx];
1438 VecW ref2het2 = second_ref2het[vec_idx];
1439 VecW agg_homhom = hom1 & hom2;
1440 VecW het1 = vecw_and_notfirst(hom1, ref2het1);
1441 VecW het2 = vecw_and_notfirst(hom2, ref2het2);
1442 VecW agg_ibs0 = (ref2het1 ^ ref2het2) & agg_homhom;
1443 VecW agg_hethet = het1 & het2;
1444 VecW agg_het2hom1 = hom1 & het2;
1445 VecW agg_het1hom2 = hom2 & het1;
1446 agg_homhom = agg_homhom - (vecw_srli(agg_homhom, 1) & m1);
1447 agg_ibs0 = agg_ibs0 - (vecw_srli(agg_ibs0, 1) & m1);
1448 agg_hethet = agg_hethet - (vecw_srli(agg_hethet, 1) & m1);
1449 agg_het2hom1 = agg_het2hom1 - (vecw_srli(agg_het2hom1, 1) & m1);
1450 agg_het1hom2 = agg_het1hom2 - (vecw_srli(agg_het1hom2, 1) & m1);
1451 agg_homhom = (agg_homhom & m2) + (vecw_srli(agg_homhom, 2) & m2);
1452 agg_ibs0 = (agg_ibs0 & m2) + (vecw_srli(agg_ibs0, 2) & m2);
1453 agg_hethet = (agg_hethet & m2) + (vecw_srli(agg_hethet, 2) & m2);
1454 agg_het2hom1 = (agg_het2hom1 & m2) + (vecw_srli(agg_het2hom1, 2) & m2);
1455 agg_het1hom2 = (agg_het1hom2 & m2) + (vecw_srli(agg_het1hom2, 2) & m2);
1456
1457 for (uint32_t offset = 1; offset != 3; ++offset) {
1458 hom1 = first_hom_iter[vec_idx + offset];
1459 hom2 = second_hom[vec_idx + offset];
1460 ref2het1 = first_ref2het_iter[vec_idx + offset];
1461 ref2het2 = second_ref2het[vec_idx + offset];
1462 VecW cur_homhom = hom1 & hom2;
1463 het1 = vecw_and_notfirst(hom1, ref2het1);
1464 het2 = vecw_and_notfirst(hom2, ref2het2);
1465 VecW cur_ibs0 = (ref2het1 ^ ref2het2) & cur_homhom;
1466 VecW cur_hethet = het1 & het2;
1467 VecW cur_het2hom1 = hom1 & het2;
1468 VecW cur_het1hom2 = hom2 & het1;
1469 cur_homhom = cur_homhom - (vecw_srli(cur_homhom, 1) & m1);
1470 cur_ibs0 = cur_ibs0 - (vecw_srli(cur_ibs0, 1) & m1);
1471 cur_hethet = cur_hethet - (vecw_srli(cur_hethet, 1) & m1);
1472 cur_het2hom1 = cur_het2hom1 - (vecw_srli(cur_het2hom1, 1) & m1);
1473 cur_het1hom2 = cur_het1hom2 - (vecw_srli(cur_het1hom2, 1) & m1);
1474 agg_homhom += (cur_homhom & m2) + (vecw_srli(cur_homhom, 2) & m2);
1475 agg_ibs0 += (cur_ibs0 & m2) + (vecw_srli(cur_ibs0, 2) & m2);
1476 agg_hethet += (cur_hethet & m2) + (vecw_srli(cur_hethet, 2) & m2);
1477 agg_het2hom1 += (cur_het2hom1 & m2) + (vecw_srli(cur_het2hom1, 2) & m2);
1478 agg_het1hom2 += (cur_het1hom2 & m2) + (vecw_srli(cur_het1hom2, 2) & m2);
1479 }
1480 acc_homhom.vw = acc_homhom.vw + (agg_homhom & m4) + (vecw_srli(agg_homhom, 4) & m4);
1481 acc_ibs0.vw = acc_ibs0.vw + (agg_ibs0 & m4) + (vecw_srli(agg_ibs0, 4) & m4);
1482 acc_hethet.vw = acc_hethet.vw + (agg_hethet & m4) + (vecw_srli(agg_hethet, 4) & m4);
1483 acc_het2hom1.vw = acc_het2hom1.vw + (agg_het2hom1 & m4) + (vecw_srli(agg_het2hom1, 4) & m4);
1484 acc_het1hom2.vw = acc_het1hom2.vw + (agg_het1hom2 & m4) + (vecw_srli(agg_het1hom2, 4) & m4);
1485 }
1486 const VecW m8 = VCONST_W(kMask00FF);
1487 acc_homhom.vw = (acc_homhom.vw & m8) + (vecw_srli(acc_homhom.vw, 8) & m8);
1488 acc_ibs0.vw = (acc_ibs0.vw & m8) + (vecw_srli(acc_ibs0.vw, 8) & m8);
1489 acc_hethet.vw = (acc_hethet.vw & m8) + (vecw_srli(acc_hethet.vw, 8) & m8);
1490 acc_het2hom1.vw = (acc_het2hom1.vw & m8) + (vecw_srli(acc_het2hom1.vw, 8) & m8);
1491 acc_het1hom2.vw = (acc_het1hom2.vw & m8) + (vecw_srli(acc_het1hom2.vw, 8) & m8);
1492 king_counts_iter[kKingOffsetIbs0] += UniVecHsum16(acc_ibs0);
1493 king_counts_iter[kKingOffsetHethet] += UniVecHsum16(acc_hethet);
1494 king_counts_iter[kKingOffsetHet2Hom1] += UniVecHsum16(acc_het2hom1);
1495 king_counts_iter[kKingOffsetHet1Hom2] += UniVecHsum16(acc_het1hom2);
1496 king_counts_iter[kKingOffsetHomhom] += UniVecHsum16(acc_homhom);
1497 king_counts_iter = &(king_counts_iter[5]);
1498
1499 first_hom_iter = &(first_hom_iter[kKingMultiplexVecs]);
1500 first_ref2het_iter = &(first_ref2het_iter[kKingMultiplexVecs]);
1501 }
1502 }
1503 }
1504 #endif
1505 static_assert(!(kKingMultiplexWords % 2), "kKingMultiplexWords must be even for safe bit-transpose.");
1506
1507 typedef struct CalcKingDenseCtxStruct {
1508 uintptr_t* smaj_hom[2];
1509 uintptr_t* smaj_ref2het[2];
1510 uint32_t homhom_needed;
1511
1512 uint32_t* thread_start;
1513
1514 uint32_t* king_counts;
1515 } CalcKingDenseCtx;
1516
1517 THREAD_FUNC_DECL CalcKingDenseThread(void* raw_arg) {
1518 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
1519 const uintptr_t tidx = arg->tidx;
1520 CalcKingDenseCtx* ctx = S_CAST(CalcKingDenseCtx*, arg->sharedp->context);
1521
1522 const uint64_t mem_start_idx = ctx->thread_start[0];
1523 const uint64_t start_idx = ctx->thread_start[tidx];
1524 const uint32_t end_idx = ctx->thread_start[tidx + 1];
1525 const uint32_t homhom_needed = ctx->homhom_needed;
1526 uint32_t parity = 0;
1527 do {
1528 if (homhom_needed) {
1529 IncrKingHomhom(ctx->smaj_hom[parity], ctx->smaj_ref2het[parity], start_idx, end_idx, &(ctx->king_counts[((start_idx * (start_idx - 1) - mem_start_idx * (mem_start_idx - 1)) / 2) * 5]));
1530 } else {
1531 IncrKing(ctx->smaj_hom[parity], ctx->smaj_ref2het[parity], start_idx, end_idx, &(ctx->king_counts[(start_idx * (start_idx - 1) - mem_start_idx * (mem_start_idx - 1)) * 2]));
1532 }
1533 parity = 1 - parity;
1534 } while (!THREAD_BLOCK_FINISH(arg));
1535 THREAD_RETURN;
1536 }
1537
1538 /*
1539 double ComputeKinship(const uint32_t* king_counts_entry) {
1540 const uint32_t ibs0_ct = king_counts_entry[kKingOffsetIbs0];
1541 const uint32_t hethet_ct = king_counts_entry[kKingOffsetHethet];
1542 const uint32_t het2hom1_ct = king_counts_entry[kKingOffsetHet2Hom1];
1543 const uint32_t het1hom2_ct = king_counts_entry[kKingOffsetHet1Hom2];
1544 const intptr_t smaller_het_ct = hethet_ct + MINV(het1hom2_ct, het2hom1_ct);
1545 return 0.5 - (S_CAST(double, 4 * S_CAST(intptr_t, ibs0_ct) + het1hom2_ct + het2hom1_ct) / S_CAST(double, 4 * smaller_het_ct));
1546 }
1547 */
1548
1549 // '2' refers to the larger index here
1550 double ComputeKinship(const uint32_t* king_counts_entry, uint32_t singleton_het1_ct, uint32_t singleton_hom1_ct, uint32_t singleton_het2_ct, uint32_t singleton_hom2_ct) {
1551 const uint32_t ibs0_ct = king_counts_entry[kKingOffsetIbs0] + singleton_hom1_ct + singleton_hom2_ct;
1552 const uint32_t hethet_ct = king_counts_entry[kKingOffsetHethet];
1553 const uint32_t het2hom1_ct = king_counts_entry[kKingOffsetHet2Hom1] + singleton_het2_ct;
1554 const uint32_t het1hom2_ct = king_counts_entry[kKingOffsetHet1Hom2] + singleton_het1_ct;
1555 const intptr_t smaller_het_ct = hethet_ct + MINV(het1hom2_ct, het2hom1_ct);
1556 return 0.5 - (S_CAST(double, 4 * S_CAST(intptr_t, ibs0_ct) + het1hom2_ct + het2hom1_ct) / S_CAST(double, 4 * smaller_het_ct));
1557 }
1558
1559 // could also return pointer to end?
1560 void SetKingMatrixFname(KingFlags king_flags, uint32_t parallel_idx, uint32_t parallel_tot, char* outname_end) {
1561 if (!(king_flags & (kfKingMatrixBin | kfKingMatrixBin4))) {
1562 char* outname_end2 = strcpya_k(outname_end, ".king");
1563 const uint32_t output_zst = king_flags & kfKingMatrixZs;
1564 if (parallel_tot != 1) {
1565 *outname_end2++ = '.';
1566 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
1567 }
1568 if (output_zst) {
1569 outname_end2 = strcpya_k(outname_end2, ".zst");
1570 }
1571 *outname_end2 = '\0';
1572 return;
1573 }
1574 char* outname_end2 = strcpya_k(outname_end, ".king.bin");
1575 if (parallel_tot != 1) {
1576 *outname_end2++ = '.';
1577 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
1578 }
1579 *outname_end2 = '\0';
1580 }
1581
1582 void SetKingTableFname(KingFlags king_flags, uint32_t parallel_idx, uint32_t parallel_tot, char* outname_end) {
1583 char* outname_end2 = strcpya_k(outname_end, ".kin0");
1584 const uint32_t output_zst = king_flags & kfKingTableZs;
1585 if (parallel_tot != 1) {
1586 *outname_end2++ = '.';
1587 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
1588 }
1589 if (output_zst) {
1590 outname_end2 = strcpya_k(outname_end2, ".zst");
1591 }
1592 *outname_end2 = '\0';
1593 }
1594
1595 char* AppendKingTableHeader(KingFlags king_flags, uint32_t king_col_fid, uint32_t king_col_sid, char* cswritep) {
1596 *cswritep++ = '#';
1597 if (king_flags & kfKingColId) {
1598 if (king_col_fid) {
1599 cswritep = strcpya_k(cswritep, "FID1\t");
1600 }
1601 // Was 'ID1' before alpha 3, but that's inconsistent with other plink2
1602 // commands, and in the meantime the header line still doesn't perfectly
1603 // match KING due to e.g. capitalization.
1604 cswritep = strcpya_k(cswritep, "IID1\t");
1605 if (king_col_sid) {
1606 cswritep = strcpya_k(cswritep, "SID1\t");
1607 }
1608 if (king_col_fid) {
1609 cswritep = strcpya_k(cswritep, "FID2\t");
1610 }
1611 cswritep = strcpya_k(cswritep, "IID2\t");
1612 if (king_col_sid) {
1613 cswritep = strcpya_k(cswritep, "SID2\t");
1614 }
1615 }
1616 if (king_flags & kfKingColNsnp) {
1617 cswritep = strcpya_k(cswritep, "NSNP\t");
1618 }
1619 if (king_flags & kfKingColHethet) {
1620 cswritep = strcpya_k(cswritep, "HETHET\t");
1621 }
1622 if (king_flags & kfKingColIbs0) {
1623 cswritep = strcpya_k(cswritep, "IBS0\t");
1624 }
1625 if (king_flags & kfKingColIbs1) {
1626 cswritep = strcpya_k(cswritep, "HET1_HOM2\tHET2_HOM1\t");
1627 }
1628 if (king_flags & kfKingColKinship) {
1629 cswritep = strcpya_k(cswritep, "KINSHIP\t");
1630 }
1631 DecrAppendBinaryEoln(&cswritep);
1632 return cswritep;
1633 }
1634
1635 uint32_t KingMaxSparseCt(uint32_t row_end_idx) {
1636 #ifdef USE_AVX2
1637 return row_end_idx / 33;
1638 #else
1639 return row_end_idx / 30;
1640 #endif
1641 }
1642
1643 PglErr CalcKing(const SampleIdInfo* siip, const uintptr_t* variant_include_orig, const ChrInfo* cip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, double king_cutoff, double king_table_filter, KingFlags king_flags, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, PgenReader* simple_pgrp, uintptr_t* sample_include, uint32_t* sample_ct_ptr, char* outname, char* outname_end) {
1644 unsigned char* bigstack_mark = g_bigstack_base;
1645 FILE* outfile = nullptr;
1646 char* cswritep = nullptr;
1647 char* cswritetp = nullptr;
1648 CompressStreamState css;
1649 CompressStreamState csst;
1650 ThreadGroup tg;
1651 PglErr reterr = kPglRetSuccess;
1652 PreinitCstream(&css);
1653 PreinitCstream(&csst);
1654 PreinitThreads(&tg);
1655 {
1656 const KingFlags matrix_shape = king_flags & kfKingMatrixShapemask;
1657 const char* flagname = matrix_shape? "--make-king" : ((king_flags & kfKingColAll)? "--make-king-table" : "--king-cutoff");
1658 if (unlikely(IsSet(cip->haploid_mask, 0))) {
1659 logerrprintf("Error: %s cannot be used on haploid genomes.\n", flagname);
1660 goto CalcKing_ret_INCONSISTENT_INPUT;
1661 }
1662 uint32_t sample_ct = *sample_ct_ptr;
1663 if (unlikely(sample_ct < 2)) {
1664 logerrprintf("Error: %s requires at least 2 samples.\n", flagname);
1665 goto CalcKing_ret_DEGENERATE_DATA;
1666 }
1667 #ifdef __LP64__
1668 // there's also a UINT32_MAX / kKingMultiplexWords limit, but that's not
1669 // relevant for now
1670 if (unlikely(sample_ct > 134000000)) {
1671 // for text output, 134m * 16 is just below kMaxLongLine
1672 logerrprintf("Error: %s does not support > 134000000 samples.\n", flagname);
1673 reterr = kPglRetNotYetSupported;
1674 goto CalcKing_ret_1;
1675 }
1676 #endif
1677 const uintptr_t sample_ctl = BitCtToWordCt(sample_ct);
1678 uintptr_t* kinship_table = nullptr;
1679 if (king_cutoff != -1) {
1680 if (unlikely(bigstack_calloc_w(sample_ct * sample_ctl, &kinship_table))) {
1681 goto CalcKing_ret_NOMEM;
1682 }
1683 }
1684 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
1685 const uint32_t non_autosomal_variant_ct = CountNonAutosomalVariants(variant_include_orig, cip, 1, 1);
1686 if (non_autosomal_variant_ct) {
1687 uintptr_t* variant_include_next;
1688 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_next))) {
1689 goto CalcKing_ret_NOMEM;
1690 }
1691 logprintf("Excluding %u variant%s on non-autosomes from KING-robust calculation.\n", non_autosomal_variant_ct, (non_autosomal_variant_ct == 1)? "" : "s");
1692 variant_ct -= non_autosomal_variant_ct;
1693 if (!variant_ct) {
1694 logerrprintf("Error: No variants remaining for KING-robust calculation.\n");
1695 goto CalcKing_ret_DEGENERATE_DATA;
1696 }
1697 memcpy(variant_include_next, variant_include_orig, raw_variant_ctl * sizeof(intptr_t));
1698 ExcludeNonAutosomalVariants(cip, variant_include_next);
1699 variant_include_orig = variant_include_next;
1700 }
1701 uintptr_t* variant_include;
1702
1703 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include))) {
1704 goto CalcKing_ret_NOMEM;
1705 }
1706
1707 uint32_t grand_row_start_idx;
1708 uint32_t grand_row_end_idx;
1709 ParallelBounds(sample_ct, 1, parallel_idx, parallel_tot, R_CAST(int32_t*, &grand_row_start_idx), R_CAST(int32_t*, &grand_row_end_idx));
1710
1711 // possible todo: allow this to change between passes
1712 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
1713 if (calc_thread_ct > sample_ct / 32) {
1714 calc_thread_ct = sample_ct / 32;
1715 }
1716 if (!calc_thread_ct) {
1717 calc_thread_ct = 1;
1718 }
1719 const uint32_t homhom_needed = (king_flags & kfKingColNsnp) || ((!(king_flags & kfKingCounts)) && (king_flags & (kfKingColHethet | kfKingColIbs0 | kfKingColIbs1)));
1720 CalcKingSparseCtx sparse_ctx;
1721 uint32_t sparse_read_block_size = 0;
1722 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
1723 // These values are now permitted to underflow from sparse-optimization.
1724 // Might want to change them to int32_t*.
1725 uint32_t* singleton_het_cts;
1726 uint32_t* singleton_hom_cts;
1727 uint32_t* singleton_missing_cts;
1728 {
1729 sparse_ctx.variant_include_orig = variant_include_orig;
1730 sparse_ctx.homhom_needed = homhom_needed;
1731 const uint32_t max_sparse_ct = KingMaxSparseCt(grand_row_end_idx);
1732 // Ok for this to be a slight underestimate, since bigstack_left()/8 is
1733 // an arbitrary limit anyway.
1734 const uintptr_t thread_xalloc_cacheline_ct = DivUp((3 * k1LU) * (max_sparse_ct + grand_row_end_idx), kInt32PerCacheline) + ((kPglVblockSize * 2) / kBitsPerCacheline);
1735 if (unlikely(PgenMtLoadInit(variant_include_orig, grand_row_end_idx, variant_ct, bigstack_left() / 8, pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &sparse_ctx.genovecs, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &sparse_read_block_size, nullptr, main_loadbufs, &sparse_ctx.pgr_ptrs, &sparse_ctx.read_variant_uidx_starts))) {
1736 goto CalcKing_ret_NOMEM;
1737 }
1738 sparse_ctx.read_block_size = sparse_read_block_size;
1739 sparse_ctx.err_info = (~0LLU) << 32;
1740 if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &sparse_ctx.thread_idx_bufs) ||
1741 bigstack_alloc_u32p(calc_thread_ct, &sparse_ctx.thread_singleton_het_cts) ||
1742 bigstack_alloc_u32p(calc_thread_ct, &sparse_ctx.thread_singleton_hom_cts) ||
1743 bigstack_alloc_u32p(calc_thread_ct, &sparse_ctx.thread_singleton_missing_cts) ||
1744 bigstack_alloc_u32(calc_thread_ct, &sparse_ctx.thread_skip_cts) ||
1745 bigstack_alloc_wp(calc_thread_ct, &sparse_ctx.thread_sparse_excludes[0]) ||
1746 bigstack_alloc_wp(calc_thread_ct, &sparse_ctx.thread_sparse_excludes[1]))) {
1747 goto CalcKing_ret_NOMEM;
1748 }
1749 const uint32_t read_block_sizel = sparse_read_block_size / kBitsPerWord;
1750 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1751 if (unlikely(bigstack_alloc_u32(3 * max_sparse_ct, &(sparse_ctx.thread_idx_bufs[tidx])) ||
1752 bigstack_alloc_u32(grand_row_end_idx, &(sparse_ctx.thread_singleton_het_cts[tidx])) ||
1753 bigstack_alloc_u32(grand_row_end_idx, &(sparse_ctx.thread_singleton_hom_cts[tidx])) ||
1754 bigstack_alloc_u32(grand_row_end_idx, &(sparse_ctx.thread_singleton_missing_cts[tidx])) ||
1755 bigstack_alloc_w(read_block_sizel, &(sparse_ctx.thread_sparse_excludes[0][tidx])) ||
1756 bigstack_alloc_w(read_block_sizel, &(sparse_ctx.thread_sparse_excludes[1][tidx])))) {
1757 goto CalcKing_ret_NOMEM;
1758 }
1759 }
1760 singleton_het_cts = sparse_ctx.thread_singleton_het_cts[0];
1761 singleton_hom_cts = sparse_ctx.thread_singleton_hom_cts[0];
1762 singleton_missing_cts = sparse_ctx.thread_singleton_missing_cts[0];
1763 }
1764
1765 CalcKingDenseCtx dense_ctx;
1766 if (unlikely(SetThreadCt(calc_thread_ct, &tg) ||
1767 bigstack_alloc_u32(calc_thread_ct + 1, &dense_ctx.thread_start))) {
1768 goto CalcKing_ret_NOMEM;
1769 }
1770 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1771 const uint32_t grei_ctaw = BitCtToAlignedWordCt(grand_row_end_idx);
1772 const uint32_t grei_ctaw2 = NypCtToAlignedWordCt(grand_row_end_idx);
1773 dense_ctx.homhom_needed = homhom_needed;
1774 const uint32_t king_bufsizew = kKingMultiplexWords * grand_row_end_idx;
1775 const uint32_t homhom_needed_p4 = dense_ctx.homhom_needed + 4;
1776 uintptr_t* cur_sample_include;
1777 uint32_t* sample_include_cumulative_popcounts;
1778 uintptr_t* loadbuf;
1779 uintptr_t* splitbuf_hom;
1780 uintptr_t* splitbuf_ref2het;
1781 VecW* vecaligned_buf;
1782 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_sample_include) ||
1783 bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
1784 bigstack_alloc_w(grei_ctaw2, &loadbuf) ||
1785 bigstack_alloc_w(kPglBitTransposeBatch * grei_ctaw, &splitbuf_hom) ||
1786 bigstack_alloc_w(kPglBitTransposeBatch * grei_ctaw, &splitbuf_ref2het) ||
1787 bigstack_alloc_w(king_bufsizew, &(dense_ctx.smaj_hom[0])) ||
1788 bigstack_alloc_w(king_bufsizew, &(dense_ctx.smaj_ref2het[0])) ||
1789 bigstack_alloc_w(king_bufsizew, &(dense_ctx.smaj_hom[1])) ||
1790 bigstack_alloc_w(king_bufsizew, &(dense_ctx.smaj_ref2het[1])) ||
1791 bigstack_alloc_v(kPglBitTransposeBufvecs, &vecaligned_buf))) {
1792 goto CalcKing_ret_NOMEM;
1793 }
1794
1795 // Make this automatically multipass when there's insufficient memory. So
1796 // we open the output file(s) here, and just append in the main loop.
1797 unsigned char* numbuf = nullptr;
1798 if (matrix_shape) {
1799 SetKingMatrixFname(king_flags, parallel_idx, parallel_tot, outname_end);
1800 if (!(king_flags & (kfKingMatrixBin | kfKingMatrixBin4))) {
1801 // text matrix
1802 // won't be >2gb since sample_ct <= 134m
1803 const uint32_t overflow_buf_size = kCompressStreamBlock + 16 * sample_ct;
1804 reterr = InitCstreamAlloc(outname, 0, king_flags & kfKingMatrixZs, max_thread_ct, overflow_buf_size, &css, &cswritep);
1805 if (unlikely(reterr)) {
1806 goto CalcKing_ret_1;
1807 }
1808 } else {
1809 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
1810 goto CalcKing_ret_OPEN_FAIL;
1811 }
1812 if (unlikely(bigstack_alloc_uc(sample_ct * 4 * (2 - ((king_flags / kfKingMatrixBin4) & 1)), &numbuf))) {
1813 goto CalcKing_ret_OPEN_FAIL;
1814 }
1815 }
1816 }
1817 uint32_t king_col_fid = 0;
1818 uint32_t king_col_sid = 0;
1819 uintptr_t max_sample_fmtid_blen = 0;
1820 char* collapsed_sample_fmtids = nullptr;
1821 if (king_flags & kfKingColAll) {
1822 const uint32_t overflow_buf_size = kCompressStreamBlock + kMaxMediumLine;
1823 SetKingTableFname(king_flags, parallel_idx, parallel_tot, outname_end);
1824 reterr = InitCstreamAlloc(outname, 0, king_flags & kfKingTableZs, max_thread_ct, overflow_buf_size, &csst, &cswritetp);
1825 if (unlikely(reterr)) {
1826 goto CalcKing_ret_1;
1827 }
1828
1829 king_col_fid = FidColIsRequired(siip, king_flags / kfKingColMaybefid);
1830 king_col_sid = SidColIsRequired(siip->sids, king_flags / kfKingColMaybesid);
1831 if (!parallel_idx) {
1832 cswritetp = AppendKingTableHeader(king_flags, king_col_fid, king_col_sid, cswritetp);
1833 }
1834 if (unlikely(CollapsedSampleFmtidInitAlloc(sample_include, siip, grand_row_end_idx, king_col_fid, king_col_sid, &collapsed_sample_fmtids, &max_sample_fmtid_blen))) {
1835 goto CalcKing_ret_NOMEM;
1836 }
1837 }
1838 uint64_t king_table_filter_ct = 0;
1839 const uintptr_t cells_avail = bigstack_left() / (sizeof(int32_t) * homhom_needed_p4);
1840 const uint32_t pass_ct = CountTrianglePasses(grand_row_start_idx, grand_row_end_idx, 1, cells_avail);
1841 if (unlikely(!pass_ct)) {
1842 goto CalcKing_ret_NOMEM;
1843 }
1844 if (unlikely((pass_ct > 1) && (king_flags & kfKingMatrixSq))) {
1845 logerrputs("Insufficient memory for --make-king square output. Try square0 or triangle\nshape instead.\n");
1846 goto CalcKing_ret_NOMEM;
1847 }
1848 uint32_t row_end_idx = grand_row_start_idx;
1849 sparse_ctx.king_counts = R_CAST(uint32_t*, g_bigstack_base);
1850 dense_ctx.king_counts = sparse_ctx.king_counts;
1851 for (uint32_t pass_idx_p1 = 1; pass_idx_p1 <= pass_ct; ++pass_idx_p1) {
1852 const uint32_t row_start_idx = row_end_idx;
1853 row_end_idx = NextTrianglePass(row_start_idx, grand_row_end_idx, 1, cells_avail);
1854 TriangleLoadBalance(calc_thread_ct, row_start_idx, row_end_idx, 1, dense_ctx.thread_start);
1855 memcpy(cur_sample_include, sample_include, raw_sample_ctl * sizeof(intptr_t));
1856 // bugfix (20 Nov 2019): forgot that --parallel could cause the old
1857 // row_end_idx != grand_row_end_idx comparison not work
1858 if (row_end_idx != orig_sample_ct) {
1859 uint32_t sample_uidx_end = IdxToUidxBasic(sample_include, row_end_idx);
1860 ClearBitsNz(sample_uidx_end, raw_sample_ct, cur_sample_include);
1861 }
1862 FillCumulativePopcounts(cur_sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
1863 pgfip->block_base = main_loadbufs[0]; // needed after first pass
1864 // Update (9 Nov 2019): The one-time singleton/monomorphic scan has been
1865 // replaced with a more effective sparse-variant scan which happens on
1866 // every pass.
1867 sparse_ctx.sample_include = cur_sample_include;
1868 sparse_ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
1869 sparse_ctx.row_start_idx = row_start_idx;
1870 sparse_ctx.row_end_idx = row_end_idx;
1871 sparse_ctx.max_sparse_ct = KingMaxSparseCt(row_end_idx);
1872 logprintf("%s pass %u/%u: Scanning for rare variants... ", flagname, pass_idx_p1, pass_ct);
1873 fputs("0%", stdout);
1874 fflush(stdout);
1875 SetThreadFuncAndData(CalcKingSparseThread, &sparse_ctx, &tg);
1876 if (unlikely(SpawnThreads(&tg))) {
1877 goto CalcKing_ret_THREAD_CREATE_FAIL;
1878 }
1879 memcpy(variant_include, variant_include_orig, raw_variant_ctl * sizeof(intptr_t));
1880
1881 {
1882 const uint32_t read_block_sizel = sparse_read_block_size / kBitsPerWord;
1883 uint32_t prev_read_block_idx = 0;
1884 uint32_t read_block_idx = 0;
1885 uint32_t pct = 0;
1886 uint32_t next_print_variant_idx = variant_ct / 100;
1887 uint32_t parity = 0;
1888 for (uint32_t variant_idx = 0; ; ) {
1889 const uint32_t cur_block_size = MultireadNonempty(variant_include_orig, &tg, raw_variant_ct, sparse_read_block_size, pgfip, &read_block_idx, &reterr);
1890 if (unlikely(reterr)) {
1891 goto CalcKing_ret_PGR_FAIL;
1892 }
1893 JoinThreads(&tg);
1894 reterr = S_CAST(PglErr, sparse_ctx.err_info);
1895 if (unlikely(reterr)) {
1896 PgenErrPrintNV(reterr, sparse_ctx.err_info >> 32);
1897 goto CalcKing_ret_1;
1898 }
1899 if (!IsLastBlock(&tg)) {
1900 sparse_ctx.cur_block_size = cur_block_size;
1901 ComputeUidxStartPartition(variant_include_orig, cur_block_size, calc_thread_ct, read_block_idx * sparse_read_block_size, sparse_ctx.read_variant_uidx_starts);
1902 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, sparse_ctx.pgr_ptrs);
1903 if (variant_idx + cur_block_size == variant_ct) {
1904 DeclareLastThreadBlock(&tg);
1905 }
1906 SpawnThreads(&tg);
1907 }
1908 parity = 1 - parity;
1909 if (variant_idx) {
1910 uintptr_t* variant_include_update = &(variant_include[prev_read_block_idx * read_block_sizel]);
1911 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1912 BitvecInvmask(sparse_ctx.thread_sparse_excludes[parity][tidx], read_block_sizel, variant_include_update);
1913 }
1914 if (variant_idx == variant_ct) {
1915 break;
1916 }
1917 if (variant_idx >= next_print_variant_idx) {
1918 if (pct > 10) {
1919 putc_unlocked('\b', stdout);
1920 }
1921 pct = (variant_idx * 100LLU) / variant_ct;
1922 printf("\b\b%u%%", pct++);
1923 fflush(stdout);
1924 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
1925 }
1926 }
1927 prev_read_block_idx = read_block_idx;
1928 ++read_block_idx;
1929 variant_idx += cur_block_size;
1930 pgfip->block_base = main_loadbufs[parity];
1931 }
1932 if (pct > 10) {
1933 putc_unlocked('\b', stdout);
1934 }
1935 }
1936 fputs("\b\b", stdout);
1937 logputs("done.\n");
1938 const uint32_t cur_variant_ct = PopcountWords(variant_include, raw_variant_ctl);
1939 uint32_t sparse_variant_ct = variant_ct - cur_variant_ct;
1940 logprintf("%u variant%s handled by initial scan (%u remaining).\n", sparse_variant_ct, (sparse_variant_ct == 1)? "" : "s", cur_variant_ct);
1941 uint32_t skip_ct = sparse_ctx.thread_skip_cts[0];
1942 const uint32_t vec_ct = DivUp(row_end_idx, kInt32PerVec);
1943 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
1944 U32CastVecAdd(sparse_ctx.thread_singleton_het_cts[tidx], vec_ct, singleton_het_cts);
1945 U32CastVecAdd(sparse_ctx.thread_singleton_hom_cts[tidx], vec_ct, singleton_hom_cts);
1946 U32CastVecAdd(sparse_ctx.thread_singleton_missing_cts[tidx], vec_ct, singleton_missing_cts);
1947 skip_ct += sparse_ctx.thread_skip_cts[tidx];
1948 }
1949 sparse_variant_ct -= skip_ct;
1950 if (cur_variant_ct) {
1951 SetThreadFuncAndData(CalcKingDenseThread, &dense_ctx, &tg);
1952 const uint32_t row_end_idxaw = BitCtToAlignedWordCt(row_end_idx);
1953 const uint32_t row_end_idxaw2 = NypCtToAlignedWordCt(row_end_idx);
1954 if (row_end_idxaw % 2) {
1955 const uint32_t cur_king_bufsizew = kKingMultiplexWords * row_end_idx;
1956 uintptr_t* smaj_hom0_last = &(dense_ctx.smaj_hom[0][kKingMultiplexWords - 1]);
1957 uintptr_t* smaj_ref2het0_last = &(dense_ctx.smaj_ref2het[0][kKingMultiplexWords - 1]);
1958 uintptr_t* smaj_hom1_last = &(dense_ctx.smaj_hom[1][kKingMultiplexWords - 1]);
1959 uintptr_t* smaj_ref2het1_last = &(dense_ctx.smaj_ref2het[1][kKingMultiplexWords - 1]);
1960 for (uint32_t offset = 0; offset < cur_king_bufsizew; offset += kKingMultiplexWords) {
1961 smaj_hom0_last[offset] = 0;
1962 smaj_ref2het0_last[offset] = 0;
1963 smaj_hom1_last[offset] = 0;
1964 smaj_ref2het1_last[offset] = 0;
1965 }
1966 }
1967 uintptr_t variant_uidx_base = 0;
1968 uintptr_t cur_bits = variant_include[0];
1969 uint32_t variants_completed = 0;
1970 uint32_t parity = 0;
1971 const uint32_t sample_batch_ct_m1 = (row_end_idx - 1) / kPglBitTransposeBatch;
1972 // Similar to plink 1.9 --genome. For each pair of samples S1-S2, we
1973 // need to determine counts of the following:
1974 // * S1 hom-S2 opposite hom
1975 // * het-het
1976 // * S1 hom-S2 het
1977 // * S2 hom-S1 het
1978 // * sometimes S1 hom-S2 same hom
1979 // * (nonmissing determined via subtraction)
1980 // We handle this as follows:
1981 // 1. set n=0, reader thread loads first kKingMultiplex variants and
1982 // converts+transposes the data to a sample-major format suitable
1983 // for multithreaded computation.
1984 // 2. spawn threads
1985 //
1986 // 3. increment n by 1
1987 // 4. load block n unless eof
1988 // 5. permit threads to continue to next block, unless eof
1989 // 6. goto step 3 unless eof
1990 //
1991 // 7. write results
1992 // Results are always reported in lower-triangular order, rather than
1993 // KING's upper-triangular order, since the former plays more nicely
1994 // with incremental addition of samples.
1995 PgrSampleSubsetIndex pssi;
1996 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
1997 do {
1998 const uint32_t cur_block_size = MINV(cur_variant_ct - variants_completed, kKingMultiplex);
1999 uintptr_t* cur_smaj_hom = dense_ctx.smaj_hom[parity];
2000 uintptr_t* cur_smaj_ref2het = dense_ctx.smaj_ref2het[parity];
2001 // "block" = distance computation granularity, usually 1024 or 1536
2002 // variants
2003 // "batch" = variant-major-to-sample-major transpose granularity,
2004 // currently 512 variants
2005 uint32_t variant_batch_size = kPglBitTransposeBatch;
2006 uint32_t variant_batch_size_rounded_up = kPglBitTransposeBatch;
2007 const uint32_t write_batch_ct_m1 = (cur_block_size - 1) / kPglBitTransposeBatch;
2008 for (uint32_t write_batch_idx = 0; ; ++write_batch_idx) {
2009 if (write_batch_idx >= write_batch_ct_m1) {
2010 if (write_batch_idx > write_batch_ct_m1) {
2011 break;
2012 }
2013 variant_batch_size = ModNz(cur_block_size, kPglBitTransposeBatch);
2014 variant_batch_size_rounded_up = variant_batch_size;
2015 const uint32_t variant_batch_size_rem = variant_batch_size % kBitsPerWord;
2016 if (variant_batch_size_rem) {
2017 const uint32_t trailing_variant_ct = kBitsPerWord - variant_batch_size_rem;
2018 variant_batch_size_rounded_up += trailing_variant_ct;
2019 ZeroWArr(trailing_variant_ct * row_end_idxaw, &(splitbuf_hom[variant_batch_size * row_end_idxaw]));
2020 ZeroWArr(trailing_variant_ct * row_end_idxaw, &(splitbuf_ref2het[variant_batch_size * row_end_idxaw]));
2021 }
2022 }
2023 uintptr_t* hom_iter = splitbuf_hom;
2024 uintptr_t* ref2het_iter = splitbuf_ref2het;
2025 for (uint32_t uii = 0; uii != variant_batch_size; ++uii) {
2026 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2027 // Model does not cleanly generalize to multiallelic variants
2028 // (unless there's something I overlooked, which is quite
2029 // possible).
2030 // Thought about using major allele counts in that case, but that
2031 // sacrifices a really nice property of this method: estimated
2032 // relationship coefficient between each pair of samples is
2033 // independent of estimated allele frequencies. And the accuracy
2034 // improvement we'd get in return is microscopic. So we stick to
2035 // REF/ALT allele counts instead.
2036 reterr = PgrGet(cur_sample_include, pssi, row_end_idx, variant_uidx, simple_pgrp, loadbuf);
2037 if (unlikely(reterr)) {
2038 PgenErrPrintNV(reterr, variant_uidx);
2039 goto CalcKing_ret_1;
2040 }
2041 SetTrailingNyps(row_end_idx, loadbuf);
2042 SplitHomRef2hetUnsafeW(loadbuf, row_end_idxaw2, hom_iter, ref2het_iter);
2043 hom_iter = &(hom_iter[row_end_idxaw]);
2044 ref2het_iter = &(ref2het_iter[row_end_idxaw]);
2045 }
2046 // uintptr_t* read_iter = loadbuf;
2047 uintptr_t* write_hom_iter = &(cur_smaj_hom[write_batch_idx * kPglBitTransposeWords]);
2048 uintptr_t* write_ref2het_iter = &(cur_smaj_ref2het[write_batch_idx * kPglBitTransposeWords]);
2049 uint32_t write_batch_size = kPglBitTransposeBatch;
2050 for (uint32_t sample_batch_idx = 0; ; ++sample_batch_idx) {
2051 if (sample_batch_idx >= sample_batch_ct_m1) {
2052 if (sample_batch_idx > sample_batch_ct_m1) {
2053 break;
2054 }
2055 write_batch_size = ModNz(row_end_idx, kPglBitTransposeBatch);
2056 }
2057 // bugfix: read_batch_size must be rounded up to word boundary,
2058 // since we want to one-out instead of zero-out the trailing bits
2059 //
2060 // bugfix: if we always use kPglBitTransposeBatch instead of
2061 // variant_batch_size_rounded_up, we read/write past the
2062 // kKingMultiplex limit and clobber the first variants of the
2063 // next sample with garbage.
2064 TransposeBitblock(&(splitbuf_hom[sample_batch_idx * kPglBitTransposeWords]), row_end_idxaw, kKingMultiplexWords, variant_batch_size_rounded_up, write_batch_size, write_hom_iter, vecaligned_buf);
2065 TransposeBitblock(&(splitbuf_ref2het[sample_batch_idx * kPglBitTransposeWords]), row_end_idxaw, kKingMultiplexWords, variant_batch_size_rounded_up, write_batch_size, write_ref2het_iter, vecaligned_buf);
2066 write_hom_iter = &(write_hom_iter[kKingMultiplex * kPglBitTransposeWords]);
2067 write_ref2het_iter = &(write_ref2het_iter[kKingMultiplex * kPglBitTransposeWords]);
2068 }
2069 }
2070 const uint32_t cur_block_sizew = BitCtToWordCt(cur_block_size);
2071 if (cur_block_sizew < kKingMultiplexWords) {
2072 uintptr_t* write_hom_iter = &(cur_smaj_hom[cur_block_sizew]);
2073 uintptr_t* write_ref2het_iter = &(cur_smaj_ref2het[cur_block_sizew]);
2074 const uint32_t write_word_ct = kKingMultiplexWords - cur_block_sizew;
2075 for (uint32_t sample_idx = 0; sample_idx != row_end_idx; ++sample_idx) {
2076 ZeroWArr(write_word_ct, write_hom_iter);
2077 ZeroWArr(write_word_ct, write_ref2het_iter);
2078 write_hom_iter = &(write_hom_iter[kKingMultiplexWords]);
2079 write_ref2het_iter = &(write_ref2het_iter[kKingMultiplexWords]);
2080 }
2081 }
2082 if (variants_completed) {
2083 JoinThreads(&tg);
2084 // CalcKingThread() never errors out
2085 }
2086 // this update must occur after JoinThreads() call
2087 if (variants_completed + cur_block_size == cur_variant_ct) {
2088 DeclareLastThreadBlock(&tg);
2089 }
2090 if (unlikely(SpawnThreads(&tg))) {
2091 goto CalcKing_ret_THREAD_CREATE_FAIL;
2092 }
2093 printf("\r%s pass %u/%u: %u variants complete.", flagname, pass_idx_p1, pass_ct, variants_completed);
2094 fflush(stdout);
2095 variants_completed += cur_block_size;
2096 parity = 1 - parity;
2097 } while (!IsLastBlock(&tg));
2098 JoinThreads(&tg);
2099 }
2100 if (matrix_shape || (king_flags & kfKingColAll)) {
2101 printf("\r%s pass %u/%u: Writing... \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", flagname, pass_idx_p1, pass_ct);
2102 fflush(stdout);
2103 // allow simultaneous --make-king + --make-king-table
2104 if (matrix_shape) {
2105 if (!(king_flags & (kfKingMatrixBin | kfKingMatrixBin4))) {
2106 const uint32_t is_squarex = king_flags & (kfKingMatrixSq | kfKingMatrixSq0);
2107 const uint32_t is_square0 = king_flags & kfKingMatrixSq0;
2108 uint32_t* results_iter = dense_ctx.king_counts;
2109 uint32_t sample_idx1 = row_start_idx;
2110 if (is_squarex && (!parallel_idx) && (pass_idx_p1)) {
2111 // dump "empty" first row
2112 sample_idx1 = 0;
2113 }
2114 for (; sample_idx1 != row_end_idx; ++sample_idx1) {
2115 const uint32_t singleton_het1_ct = singleton_het_cts[sample_idx1];
2116 const uint32_t singleton_hom1_ct = singleton_hom_cts[sample_idx1];
2117 for (uint32_t sample_idx2 = 0; sample_idx2 < sample_idx1; ++sample_idx2) {
2118 const double kinship_coeff = ComputeKinship(results_iter, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2], singleton_het1_ct, singleton_hom1_ct);
2119 if (kinship_table && (kinship_coeff > king_cutoff)) {
2120 SetBit(sample_idx2, &(kinship_table[sample_idx1 * sample_ctl]));
2121 SetBit(sample_idx1, &(kinship_table[sample_idx2 * sample_ctl]));
2122 }
2123 cswritep = dtoa_g(kinship_coeff, cswritep);
2124 *cswritep++ = '\t';
2125 results_iter = &(results_iter[homhom_needed_p4]);
2126 }
2127 if (is_squarex) {
2128 cswritep = strcpya_k(cswritep, "0.5");
2129 if (is_square0) {
2130 // (roughly same performance as creating a tab-zero constant
2131 // buffer in advance)
2132 const uint32_t zcount = sample_ct - sample_idx1 - 1;
2133 const uint32_t wct = DivUp(zcount, kBytesPerWord / 2);
2134 // assumes little-endian
2135 const uintptr_t tabzero_word = 0x3009 * kMask0001;
2136 unsigned char* tabzero_write_iter = R_CAST(unsigned char*, cswritep);
2137 for (uintptr_t widx = 0; widx != wct; ++widx) {
2138 AppendW(tabzero_word, &tabzero_write_iter);
2139 }
2140 cswritep = &(cswritep[zcount * 2]);
2141 } else {
2142 const uint32_t* results_iter2 = &(results_iter[sample_idx1 * homhom_needed_p4]);
2143 // 0
2144 // 1 2
2145 // 3 4 5
2146 // 6 7 8 9
2147 // 10 11 12 13 14
2148
2149 // sample_idx1 = 0: [0] 0 1 3 6 10...
2150 // sample_idx1 = 1: [1] 2 4 7 11...
2151 // sample_idx1 = 2: [3] 5 8 12...
2152 // sample_idx1 = 3: [6] 9 13...
2153 for (uint32_t sample_idx2 = sample_idx1 + 1; sample_idx2 != sample_ct; ++sample_idx2) {
2154 *cswritep++ = '\t';
2155 cswritep = dtoa_g(ComputeKinship(results_iter2, singleton_het1_ct, singleton_hom1_ct, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2]), cswritep);
2156 results_iter2 = &(results_iter2[sample_idx2 * homhom_needed_p4]);
2157 }
2158 }
2159 ++cswritep;
2160 }
2161 DecrAppendBinaryEoln(&cswritep);
2162 if (unlikely(Cswrite(&css, &cswritep))) {
2163 goto CalcKing_ret_WRITE_FAIL;
2164 }
2165 }
2166 } else {
2167 // binary matrix output
2168 // er, probably want to revise this so there's less duplicated code
2169 // from text matrix output...
2170 const uint32_t is_squarex = king_flags & (kfKingMatrixSq | kfKingMatrixSq0);
2171 const uint32_t is_square0 = king_flags & kfKingMatrixSq0;
2172 uint32_t* results_iter = dense_ctx.king_counts;
2173 uint32_t sample_idx1 = row_start_idx;
2174 if (is_squarex && (!parallel_idx)) {
2175 sample_idx1 = 0;
2176 }
2177 if (king_flags & kfKingMatrixBin4) {
2178 float* write_row = R_CAST(float*, numbuf);
2179 uintptr_t row_byte_ct = sample_ct * sizeof(float);
2180 for (; sample_idx1 != row_end_idx; ++sample_idx1) {
2181 const uint32_t singleton_het1_ct = singleton_het_cts[sample_idx1];
2182 const uint32_t singleton_hom1_ct = singleton_hom_cts[sample_idx1];
2183 for (uint32_t sample_idx2 = 0; sample_idx2 != sample_idx1; ++sample_idx2) {
2184 const double kinship_coeff = ComputeKinship(results_iter, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2], singleton_het1_ct, singleton_hom1_ct);
2185 if (kinship_table && (kinship_coeff > king_cutoff)) {
2186 SetBit(sample_idx2, &(kinship_table[sample_idx1 * sample_ctl]));
2187 SetBit(sample_idx1, &(kinship_table[sample_idx2 * sample_ctl]));
2188 }
2189 write_row[sample_idx2] = S_CAST(float, kinship_coeff);
2190 results_iter = &(results_iter[homhom_needed_p4]);
2191 }
2192 if (is_squarex) {
2193 write_row[sample_idx1] = 0.5f;
2194 if (is_square0) {
2195 const uint32_t right_fill_idx = sample_idx1 + 1;
2196 ZeroFArr(sample_ct - right_fill_idx, &(write_row[right_fill_idx]));
2197 } else {
2198 const uint32_t* results_iter2 = &(results_iter[sample_idx1 * homhom_needed_p4]);
2199 for (uint32_t sample_idx2 = sample_idx1 + 1; sample_idx2 != sample_ct; ++sample_idx2) {
2200 write_row[sample_idx2] = S_CAST(float, ComputeKinship(results_iter2, singleton_het1_ct, singleton_hom1_ct, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2]));
2201 results_iter2 = &(results_iter2[sample_idx2 * homhom_needed_p4]);
2202 }
2203 }
2204 } else {
2205 row_byte_ct = sample_idx1 * sizeof(float);
2206 }
2207 if (unlikely(fwrite_checked(write_row, row_byte_ct, outfile))) {
2208 goto CalcKing_ret_WRITE_FAIL;
2209 }
2210 }
2211 } else {
2212 double* write_row = R_CAST(double*, numbuf);
2213 uintptr_t row_byte_ct = sample_ct * sizeof(double);
2214 for (; sample_idx1 != row_end_idx; ++sample_idx1) {
2215 const uint32_t singleton_het1_ct = singleton_het_cts[sample_idx1];
2216 const uint32_t singleton_hom1_ct = singleton_hom_cts[sample_idx1];
2217 for (uint32_t sample_idx2 = 0; sample_idx2 != sample_idx1; ++sample_idx2) {
2218 const double kinship_coeff = ComputeKinship(results_iter, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2], singleton_het1_ct, singleton_hom1_ct);
2219 if (kinship_table && (kinship_coeff > king_cutoff)) {
2220 SetBit(sample_idx2, &(kinship_table[sample_idx1 * sample_ctl]));
2221 SetBit(sample_idx1, &(kinship_table[sample_idx2 * sample_ctl]));
2222 }
2223 write_row[sample_idx2] = kinship_coeff;
2224 results_iter = &(results_iter[homhom_needed_p4]);
2225 }
2226 if (is_squarex) {
2227 write_row[sample_idx1] = 0.5;
2228 if (is_square0) {
2229 const uint32_t right_fill_idx = sample_idx1 + 1;
2230 ZeroDArr(sample_ct - right_fill_idx, &(write_row[right_fill_idx]));
2231 } else {
2232 const uint32_t* results_iter2 = &(results_iter[sample_idx1 * homhom_needed_p4]);
2233 for (uint32_t sample_idx2 = sample_idx1 + 1; sample_idx2 != sample_ct; ++sample_idx2) {
2234 write_row[sample_idx2] = ComputeKinship(results_iter2, singleton_het1_ct, singleton_hom1_ct, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2]);
2235 results_iter2 = &(results_iter2[sample_idx2 * homhom_needed_p4]);
2236 }
2237 }
2238 } else {
2239 row_byte_ct = sample_idx1 * sizeof(double);
2240 }
2241 if (unlikely(fwrite_checked(write_row, row_byte_ct, outfile))) {
2242 goto CalcKing_ret_WRITE_FAIL;
2243 }
2244 }
2245 }
2246 }
2247 }
2248 if (king_flags & kfKingColAll) {
2249 uintptr_t* kinship_table_backup = nullptr;
2250 if (matrix_shape) {
2251 // We already updated the table; don't do it again.
2252 kinship_table_backup = kinship_table;
2253 kinship_table = nullptr;
2254 }
2255 const uint32_t king_col_id = king_flags & kfKingColId;
2256 const uint32_t king_col_nsnp = king_flags & kfKingColNsnp;
2257 const uint32_t king_col_hethet = king_flags & kfKingColHethet;
2258 const uint32_t king_col_ibs0 = king_flags & kfKingColIbs0;
2259 const uint32_t king_col_ibs1 = king_flags & kfKingColIbs1;
2260 const uint32_t king_col_kinship = king_flags & kfKingColKinship;
2261 const uint32_t report_counts = king_flags & kfKingCounts;
2262 uint32_t* results_iter = dense_ctx.king_counts;
2263 double nonmiss_recip = 0.0;
2264 for (uint32_t sample_idx1 = row_start_idx; sample_idx1 != row_end_idx; ++sample_idx1) {
2265 const char* sample_fmtid1 = &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx1]);
2266 const uint32_t singleton_het1_ct = singleton_het_cts[sample_idx1];
2267 const uint32_t singleton_hom1_ct = singleton_hom_cts[sample_idx1];
2268 const uint32_t sample_fmtid1_slen = strlen(sample_fmtid1);
2269 for (uint32_t sample_idx2 = 0; sample_idx2 != sample_idx1; ++sample_idx2, results_iter = &(results_iter[homhom_needed_p4])) {
2270 const uint32_t singleton_het2_ct = singleton_het_cts[sample_idx2];
2271 const uint32_t singleton_hom2_ct = singleton_hom_cts[sample_idx2];
2272 const uint32_t ibs0_ct = results_iter[kKingOffsetIbs0] + singleton_hom2_ct + singleton_hom1_ct;
2273 const uint32_t hethet_ct = results_iter[kKingOffsetHethet];
2274 // '2' here refers to the larger index, so this is swapped
2275 const uint32_t het2hom1_ct = results_iter[kKingOffsetHet2Hom1] + singleton_het1_ct;
2276 const uint32_t het1hom2_ct = results_iter[kKingOffsetHet1Hom2] + singleton_het2_ct;
2277 const intptr_t smaller_het_ct = hethet_ct + MINV(het1hom2_ct, het2hom1_ct);
2278 const double kinship_coeff = 0.5 - (S_CAST(double, 4 * S_CAST(intptr_t, ibs0_ct) + het1hom2_ct + het2hom1_ct) / S_CAST(double, 4 * smaller_het_ct));
2279 if (kinship_table && (kinship_coeff > king_cutoff)) {
2280 SetBit(sample_idx2, &(kinship_table[sample_idx1 * sample_ctl]));
2281 SetBit(sample_idx1, &(kinship_table[sample_idx2 * sample_ctl]));
2282 }
2283 // edge case fix (18 Nov 2017): kinship_coeff can be -inf when
2284 // smaller_het_ct is zero. Don't filter those lines out when
2285 // --king-table-filter wasn't specified.
2286 if ((king_table_filter != -DBL_MAX) && (kinship_coeff < king_table_filter)) {
2287 ++king_table_filter_ct;
2288 continue;
2289 }
2290 if (king_col_id) {
2291 cswritetp = memcpyax(cswritetp, sample_fmtid1, sample_fmtid1_slen, '\t');
2292 cswritetp = strcpyax(cswritetp, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx2]), '\t');
2293 }
2294 if (homhom_needed_p4 == 5) {
2295 const uint32_t homhom_ct = results_iter[kKingOffsetHomhom] + sparse_variant_ct - singleton_het2_ct - singleton_missing_cts[sample_idx2] - singleton_het1_ct - singleton_missing_cts[sample_idx1];
2296 const uint32_t nonmiss_ct = het1hom2_ct + het2hom1_ct + homhom_ct + hethet_ct;
2297 if (king_col_nsnp) {
2298 cswritetp = u32toa_x(nonmiss_ct, '\t', cswritetp);
2299 }
2300 if (!report_counts) {
2301 nonmiss_recip = 1.0 / u31tod(nonmiss_ct);
2302 }
2303 }
2304 if (king_col_hethet) {
2305 if (report_counts) {
2306 cswritetp = u32toa(hethet_ct, cswritetp);
2307 } else {
2308 cswritetp = dtoa_g(nonmiss_recip * u31tod(hethet_ct), cswritetp);
2309 }
2310 *cswritetp++ = '\t';
2311 }
2312 if (king_col_ibs0) {
2313 if (report_counts) {
2314 cswritetp = u32toa(ibs0_ct, cswritetp);
2315 } else {
2316 cswritetp = dtoa_g(nonmiss_recip * u31tod(ibs0_ct), cswritetp);
2317 }
2318 *cswritetp++ = '\t';
2319 }
2320 if (king_col_ibs1) {
2321 if (report_counts) {
2322 cswritetp = u32toa_x(het1hom2_ct, '\t', cswritetp);
2323 cswritetp = u32toa(het2hom1_ct, cswritetp);
2324 } else {
2325 cswritetp = dtoa_g(nonmiss_recip * u31tod(het1hom2_ct), cswritetp);
2326 *cswritetp++ = '\t';
2327 cswritetp = dtoa_g(nonmiss_recip * u31tod(het2hom1_ct), cswritetp);
2328 }
2329 *cswritetp++ = '\t';
2330 }
2331 if (king_col_kinship) {
2332 cswritetp = dtoa_g(kinship_coeff, cswritetp);
2333 ++cswritetp;
2334 }
2335 DecrAppendBinaryEoln(&cswritetp);
2336 if (unlikely(Cswrite(&csst, &cswritetp))) {
2337 goto CalcKing_ret_WRITE_FAIL;
2338 }
2339 }
2340 }
2341
2342 if (matrix_shape) {
2343 kinship_table = kinship_table_backup;
2344 }
2345 }
2346 } else {
2347 printf("\r%s pass %u/%u: Condensing... \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", flagname, pass_idx_p1, pass_ct);
2348 fflush(stdout);
2349 uint32_t* results_iter = dense_ctx.king_counts;
2350 for (uint32_t sample_idx1 = row_start_idx; sample_idx1 != row_end_idx; ++sample_idx1) {
2351 const uint32_t singleton_het1_ct = singleton_het_cts[sample_idx1];
2352 const uint32_t singleton_hom1_ct = singleton_hom_cts[sample_idx1];
2353 for (uint32_t sample_idx2 = 0; sample_idx2 != sample_idx1; ++sample_idx2) {
2354 const double kinship_coeff = ComputeKinship(results_iter, singleton_het_cts[sample_idx2], singleton_hom_cts[sample_idx2], singleton_het1_ct, singleton_hom1_ct);
2355 if (kinship_coeff > king_cutoff) {
2356 SetBit(sample_idx2, &(kinship_table[sample_idx1 * sample_ctl]));
2357 SetBit(sample_idx1, &(kinship_table[sample_idx2 * sample_ctl]));
2358 }
2359 results_iter = &(results_iter[homhom_needed_p4]);
2360 }
2361 }
2362 }
2363 fputs(" done.\n", stdout);
2364 }
2365 logprintf("%s: %u variant%s processed.\n", flagname, variant_ct, (variant_ct == 1)? "" : "s");
2366 // end-of-loop operations
2367 if (matrix_shape) {
2368 if (!(king_flags & (kfKingMatrixBin | kfKingMatrixBin4))) {
2369 if (unlikely(CswriteCloseNull(&css, cswritep))) {
2370 goto CalcKing_ret_WRITE_FAIL;
2371 }
2372 } else {
2373 if (unlikely(fclose_null(&outfile))) {
2374 goto CalcKing_ret_WRITE_FAIL;
2375 }
2376 }
2377 // Necessary to regenerate filename since it may have been overwritten by
2378 // --make-king-table.
2379 SetKingMatrixFname(king_flags, parallel_idx, parallel_tot, outname_end);
2380
2381 char* write_iter = strcpya_k(g_logbuf, "Results written to ");
2382 const uint32_t outname_base_slen = S_CAST(uintptr_t, outname_end - outname);
2383 write_iter = memcpya(write_iter, outname, outname_base_slen + strlen(outname_end));
2384 write_iter = strcpya_k(write_iter, " and ");
2385 strcpy_k(&(outname_end[5]), ".id");
2386 write_iter = memcpya(write_iter, outname, outname_base_slen + 8);
2387 strcpy_k(write_iter, " .\n");
2388 WordWrapB(0);
2389 logputsb();
2390 reterr = WriteSampleIds(sample_include, siip, outname, sample_ct);
2391 if (unlikely(reterr)) {
2392 goto CalcKing_ret_1;
2393 }
2394 }
2395 if (king_flags & kfKingColAll) {
2396 if (unlikely(CswriteCloseNull(&csst, cswritetp))) {
2397 goto CalcKing_ret_WRITE_FAIL;
2398 }
2399 SetKingTableFname(king_flags, parallel_idx, parallel_tot, outname_end);
2400 char* write_iter = strcpya_k(g_logbuf, "Results written to ");
2401 const uint32_t outname_base_slen = S_CAST(uintptr_t, outname_end - outname);
2402 write_iter = memcpya(write_iter, outname, outname_base_slen + strlen(outname_end));
2403 if ((!parallel_idx) && (!(king_flags & kfKingColId))) {
2404 write_iter = strcpya_k(write_iter, " and ");
2405 strcpy_k(&(outname_end[5]), ".id");
2406 write_iter = memcpya(write_iter, outname, outname_base_slen + 8);
2407 strcpy_k(write_iter, " .\n");
2408 WordWrapB(0);
2409 logputsb();
2410 reterr = WriteSampleIds(sample_include, siip, outname, sample_ct);
2411 if (unlikely(reterr)) {
2412 goto CalcKing_ret_1;
2413 }
2414 } else {
2415 strcpy_k(write_iter, " .\n");
2416 WordWrapB(0);
2417 logputsb();
2418 }
2419 if (king_table_filter != -DBL_MAX) {
2420 const uint64_t grand_tot_cells = (S_CAST(uint64_t, grand_row_end_idx) * (grand_row_end_idx - 1) - S_CAST(uint64_t, grand_row_start_idx) * (grand_row_start_idx - 1)) / 2;
2421 const uint64_t reported_ct = grand_tot_cells - king_table_filter_ct;
2422 logprintf("--king-table-filter: %" PRIu64 " relationship%s reported (%" PRIu64 " filtered out).\n", reported_ct, (reported_ct == 1)? "" : "s", king_table_filter_ct);
2423 }
2424 }
2425 if (kinship_table) {
2426 BigstackReset(sample_include_cumulative_popcounts);
2427 *sample_ct_ptr = sample_ct;
2428 if (unlikely(KinshipPruneDestructive(kinship_table, sample_include, sample_ct_ptr))) {
2429 goto CalcKing_ret_NOMEM;
2430 }
2431 }
2432 }
2433 while (0) {
2434 CalcKing_ret_NOMEM:
2435 reterr = kPglRetNomem;
2436 break;
2437 CalcKing_ret_OPEN_FAIL:
2438 reterr = kPglRetOpenFail;
2439 break;
2440 CalcKing_ret_PGR_FAIL:
2441 PgenErrPrintN(reterr);
2442 break;
2443 CalcKing_ret_WRITE_FAIL:
2444 reterr = kPglRetWriteFail;
2445 break;
2446 CalcKing_ret_INCONSISTENT_INPUT:
2447 reterr = kPglRetInconsistentInput;
2448 break;
2449 CalcKing_ret_THREAD_CREATE_FAIL:
2450 reterr = kPglRetThreadCreateFail;
2451 break;
2452 CalcKing_ret_DEGENERATE_DATA:
2453 reterr = kPglRetDegenerateData;
2454 break;
2455 }
2456 CalcKing_ret_1:
2457 CleanupThreads(&tg);
2458 CswriteCloseCond(&csst, cswritetp);
2459 CswriteCloseCond(&css, cswritep);
2460 fclose_cond(outfile);
2461 BigstackReset(bigstack_mark);
2462 pgfip->block_base = nullptr;
2463 return reterr;
2464 }
2465
2466 #ifdef USE_SSE42
2467 void IncrKingSubset(const uint32_t* loaded_sample_idx_pairs, const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts) {
2468 const uint32_t* sample_idx_pair_iter = &(loaded_sample_idx_pairs[(2 * k1LU) * start_idx]);
2469 const uint32_t* sample_idx_pair_stop = &(loaded_sample_idx_pairs[(2 * k1LU) * end_idx]);
2470 uint32_t* king_counts_iter = &(king_counts[(4 * k1LU) * start_idx]);
2471 while (sample_idx_pair_iter != sample_idx_pair_stop) {
2472 // technically overflows for huge sample_ct
2473 const uint32_t first_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2474 const uint32_t second_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2475 const uintptr_t* first_hom = &(smaj_hom[first_offset]);
2476 const uintptr_t* first_ref2het = &(smaj_ref2het[first_offset]);
2477 const uintptr_t* second_hom = &(smaj_hom[second_offset]);
2478 const uintptr_t* second_ref2het = &(smaj_ref2het[second_offset]);
2479 uint32_t acc_ibs0 = 0;
2480 uint32_t acc_hethet = 0;
2481 uint32_t acc_het2hom1 = 0;
2482 uint32_t acc_het1hom2 = 0;
2483 for (uint32_t widx = 0; widx != kKingMultiplexWords; ++widx) {
2484 const uintptr_t hom1 = first_hom[widx];
2485 const uintptr_t hom2 = second_hom[widx];
2486 const uintptr_t ref2het1 = first_ref2het[widx];
2487 const uintptr_t ref2het2 = second_ref2het[widx];
2488 const uintptr_t homhom = hom1 & hom2;
2489 const uintptr_t het1 = ref2het1 & (~hom1);
2490 const uintptr_t het2 = ref2het2 & (~hom2);
2491 acc_ibs0 += PopcountWord((ref2het1 ^ ref2het2) & homhom);
2492 acc_hethet += PopcountWord(het1 & het2);
2493 acc_het2hom1 += PopcountWord(hom1 & het2);
2494 acc_het1hom2 += PopcountWord(hom2 & het1);
2495 }
2496 *king_counts_iter++ += acc_ibs0;
2497 *king_counts_iter++ += acc_hethet;
2498 *king_counts_iter++ += acc_het2hom1;
2499 *king_counts_iter++ += acc_het1hom2;
2500 }
2501 }
2502
2503 void IncrKingSubsetHomhom(const uint32_t* loaded_sample_idx_pairs, const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts) {
2504 const uint32_t* sample_idx_pair_iter = &(loaded_sample_idx_pairs[(2 * k1LU) * start_idx]);
2505 const uint32_t* sample_idx_pair_stop = &(loaded_sample_idx_pairs[(2 * k1LU) * end_idx]);
2506 uint32_t* king_counts_iter = &(king_counts[(5 * k1LU) * start_idx]);
2507 while (sample_idx_pair_iter != sample_idx_pair_stop) {
2508 // technically overflows for huge sample_ct
2509 const uint32_t first_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2510 const uint32_t second_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2511 const uintptr_t* first_hom = &(smaj_hom[first_offset]);
2512 const uintptr_t* first_ref2het = &(smaj_ref2het[first_offset]);
2513 const uintptr_t* second_hom = &(smaj_hom[second_offset]);
2514 const uintptr_t* second_ref2het = &(smaj_ref2het[second_offset]);
2515 uint32_t acc_homhom = 0;
2516 uint32_t acc_ibs0 = 0;
2517 uint32_t acc_hethet = 0;
2518 uint32_t acc_het2hom1 = 0;
2519 uint32_t acc_het1hom2 = 0;
2520 for (uint32_t widx = 0; widx != kKingMultiplexWords; ++widx) {
2521 const uintptr_t hom1 = first_hom[widx];
2522 const uintptr_t hom2 = second_hom[widx];
2523 const uintptr_t ref2het1 = first_ref2het[widx];
2524 const uintptr_t ref2het2 = second_ref2het[widx];
2525 const uintptr_t homhom = hom1 & hom2;
2526 const uintptr_t het1 = ref2het1 & (~hom1);
2527 const uintptr_t het2 = ref2het2 & (~hom2);
2528 acc_homhom += PopcountWord(homhom);
2529 acc_ibs0 += PopcountWord((ref2het1 ^ ref2het2) & homhom);
2530 acc_hethet += PopcountWord(het1 & het2);
2531 acc_het2hom1 += PopcountWord(hom1 & het2);
2532 acc_het1hom2 += PopcountWord(hom2 & het1);
2533 }
2534 *king_counts_iter++ += acc_ibs0;
2535 *king_counts_iter++ += acc_hethet;
2536 *king_counts_iter++ += acc_het2hom1;
2537 *king_counts_iter++ += acc_het1hom2;
2538 *king_counts_iter++ += acc_homhom;
2539 }
2540 }
2541 #else
2542 void IncrKingSubset(const uint32_t* loaded_sample_idx_pairs, const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts) {
2543 const VecW m1 = VCONST_W(kMask5555);
2544 const VecW m2 = VCONST_W(kMask3333);
2545 const VecW m4 = VCONST_W(kMask0F0F);
2546 const uint32_t* sample_idx_pair_iter = &(loaded_sample_idx_pairs[(2 * k1LU) * start_idx]);
2547 const uint32_t* sample_idx_pair_stop = &(loaded_sample_idx_pairs[(2 * k1LU) * end_idx]);
2548 uint32_t* king_counts_iter = &(king_counts[(4 * k1LU) * start_idx]);
2549 while (sample_idx_pair_iter != sample_idx_pair_stop) {
2550 // technically overflows for huge sample_ct
2551 const uint32_t first_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2552 const uint32_t second_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2553 const VecW* first_hom = R_CAST(const VecW*, &(smaj_hom[first_offset]));
2554 const VecW* first_ref2het = R_CAST(const VecW*, &(smaj_ref2het[first_offset]));
2555 const VecW* second_hom = R_CAST(const VecW*, &(smaj_hom[second_offset]));
2556 const VecW* second_ref2het = R_CAST(const VecW*, &(smaj_ref2het[second_offset]));
2557 UniVec acc_ibs0;
2558 UniVec acc_hethet;
2559 UniVec acc_het2hom1;
2560 UniVec acc_het1hom2;
2561 acc_ibs0.vw = vecw_setzero();
2562 acc_hethet.vw = vecw_setzero();
2563 acc_het2hom1.vw = vecw_setzero();
2564 acc_het1hom2.vw = vecw_setzero();
2565 for (uint32_t vec_idx = 0; vec_idx < kKingMultiplexVecs; vec_idx += 3) {
2566 VecW hom1 = first_hom[vec_idx];
2567 VecW hom2 = second_hom[vec_idx];
2568 VecW ref2het1 = first_ref2het[vec_idx];
2569 VecW ref2het2 = second_ref2het[vec_idx];
2570 VecW het1 = vecw_and_notfirst(hom1, ref2het1);
2571 VecW het2 = vecw_and_notfirst(hom2, ref2het2);
2572 VecW agg_ibs0 = (ref2het1 ^ ref2het2) & (hom1 & hom2);
2573 VecW agg_hethet = het1 & het2;
2574 VecW agg_het2hom1 = hom1 & het2;
2575 VecW agg_het1hom2 = hom2 & het1;
2576 agg_ibs0 = agg_ibs0 - (vecw_srli(agg_ibs0, 1) & m1);
2577 agg_hethet = agg_hethet - (vecw_srli(agg_hethet, 1) & m1);
2578 agg_het2hom1 = agg_het2hom1 - (vecw_srli(agg_het2hom1, 1) & m1);
2579 agg_het1hom2 = agg_het1hom2 - (vecw_srli(agg_het1hom2, 1) & m1);
2580 agg_ibs0 = (agg_ibs0 & m2) + (vecw_srli(agg_ibs0, 2) & m2);
2581 agg_hethet = (agg_hethet & m2) + (vecw_srli(agg_hethet, 2) & m2);
2582 agg_het2hom1 = (agg_het2hom1 & m2) + (vecw_srli(agg_het2hom1, 2) & m2);
2583 agg_het1hom2 = (agg_het1hom2 & m2) + (vecw_srli(agg_het1hom2, 2) & m2);
2584
2585 for (uint32_t offset = 1; offset != 3; ++offset) {
2586 hom1 = first_hom[vec_idx + offset];
2587 hom2 = second_hom[vec_idx + offset];
2588 ref2het1 = first_ref2het[vec_idx + offset];
2589 ref2het2 = second_ref2het[vec_idx + offset];
2590 het1 = vecw_and_notfirst(hom1, ref2het1);
2591 het2 = vecw_and_notfirst(hom2, ref2het2);
2592 VecW cur_ibs0 = (ref2het1 ^ ref2het2) & (hom1 & hom2);
2593 VecW cur_hethet = het1 & het2;
2594 VecW cur_het2hom1 = hom1 & het2;
2595 VecW cur_het1hom2 = hom2 & het1;
2596 cur_ibs0 = cur_ibs0 - (vecw_srli(cur_ibs0, 1) & m1);
2597 cur_hethet = cur_hethet - (vecw_srli(cur_hethet, 1) & m1);
2598 cur_het2hom1 = cur_het2hom1 - (vecw_srli(cur_het2hom1, 1) & m1);
2599 cur_het1hom2 = cur_het1hom2 - (vecw_srli(cur_het1hom2, 1) & m1);
2600 agg_ibs0 += (cur_ibs0 & m2) + (vecw_srli(cur_ibs0, 2) & m2);
2601 agg_hethet += (cur_hethet & m2) + (vecw_srli(cur_hethet, 2) & m2);
2602 agg_het2hom1 += (cur_het2hom1 & m2) + (vecw_srli(cur_het2hom1, 2) & m2);
2603 agg_het1hom2 += (cur_het1hom2 & m2) + (vecw_srli(cur_het1hom2, 2) & m2);
2604 }
2605 acc_ibs0.vw = acc_ibs0.vw + (agg_ibs0 & m4) + (vecw_srli(agg_ibs0, 4) & m4);
2606 acc_hethet.vw = acc_hethet.vw + (agg_hethet & m4) + (vecw_srli(agg_hethet, 4) & m4);
2607 acc_het2hom1.vw = acc_het2hom1.vw + (agg_het2hom1 & m4) + (vecw_srli(agg_het2hom1, 4) & m4);
2608 acc_het1hom2.vw = acc_het1hom2.vw + (agg_het1hom2 & m4) + (vecw_srli(agg_het1hom2, 4) & m4);
2609 }
2610 const VecW m8 = VCONST_W(kMask00FF);
2611 acc_ibs0.vw = (acc_ibs0.vw & m8) + (vecw_srli(acc_ibs0.vw, 8) & m8);
2612 acc_hethet.vw = (acc_hethet.vw & m8) + (vecw_srli(acc_hethet.vw, 8) & m8);
2613 acc_het2hom1.vw = (acc_het2hom1.vw & m8) + (vecw_srli(acc_het2hom1.vw, 8) & m8);
2614 acc_het1hom2.vw = (acc_het1hom2.vw & m8) + (vecw_srli(acc_het1hom2.vw, 8) & m8);
2615 *king_counts_iter++ += UniVecHsum16(acc_ibs0);
2616 *king_counts_iter++ += UniVecHsum16(acc_hethet);
2617 *king_counts_iter++ += UniVecHsum16(acc_het2hom1);
2618 *king_counts_iter++ += UniVecHsum16(acc_het1hom2);
2619 }
2620 }
2621
2622 void IncrKingSubsetHomhom(const uint32_t* loaded_sample_idx_pairs, const uintptr_t* smaj_hom, const uintptr_t* smaj_ref2het, uint32_t start_idx, uint32_t end_idx, uint32_t* king_counts) {
2623 const VecW m1 = VCONST_W(kMask5555);
2624 const VecW m2 = VCONST_W(kMask3333);
2625 const VecW m4 = VCONST_W(kMask0F0F);
2626 const uint32_t* sample_idx_pair_iter = &(loaded_sample_idx_pairs[(2 * k1LU) * start_idx]);
2627 const uint32_t* sample_idx_pair_stop = &(loaded_sample_idx_pairs[(2 * k1LU) * end_idx]);
2628 uint32_t* king_counts_iter = &(king_counts[(5 * k1LU) * start_idx]);
2629 while (sample_idx_pair_iter != sample_idx_pair_stop) {
2630 // technically overflows for huge sample_ct
2631 const uint32_t first_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2632 const uint32_t second_offset = (*sample_idx_pair_iter++) * kKingMultiplexWords;
2633 const VecW* first_hom = R_CAST(const VecW*, &(smaj_hom[first_offset]));
2634 const VecW* first_ref2het = R_CAST(const VecW*, &(smaj_ref2het[first_offset]));
2635 const VecW* second_hom = R_CAST(const VecW*, &(smaj_hom[second_offset]));
2636 const VecW* second_ref2het = R_CAST(const VecW*, &(smaj_ref2het[second_offset]));
2637 UniVec acc_homhom;
2638 UniVec acc_ibs0;
2639 UniVec acc_hethet;
2640 UniVec acc_het2hom1;
2641 UniVec acc_het1hom2;
2642 acc_homhom.vw = vecw_setzero();
2643 acc_ibs0.vw = vecw_setzero();
2644 acc_hethet.vw = vecw_setzero();
2645 acc_het2hom1.vw = vecw_setzero();
2646 acc_het1hom2.vw = vecw_setzero();
2647 for (uint32_t vec_idx = 0; vec_idx < kKingMultiplexVecs; vec_idx += 3) {
2648 VecW hom1 = first_hom[vec_idx];
2649 VecW hom2 = second_hom[vec_idx];
2650 VecW ref2het1 = first_ref2het[vec_idx];
2651 VecW ref2het2 = second_ref2het[vec_idx];
2652 VecW agg_homhom = hom1 & hom2;
2653 VecW het1 = vecw_and_notfirst(hom1, ref2het1);
2654 VecW het2 = vecw_and_notfirst(hom2, ref2het2);
2655 VecW agg_ibs0 = (ref2het1 ^ ref2het2) & agg_homhom;
2656 VecW agg_hethet = het1 & het2;
2657 VecW agg_het2hom1 = hom1 & het2;
2658 VecW agg_het1hom2 = hom2 & het1;
2659 agg_homhom = agg_homhom - (vecw_srli(agg_homhom, 1) & m1);
2660 agg_ibs0 = agg_ibs0 - (vecw_srli(agg_ibs0, 1) & m1);
2661 agg_hethet = agg_hethet - (vecw_srli(agg_hethet, 1) & m1);
2662 agg_het2hom1 = agg_het2hom1 - (vecw_srli(agg_het2hom1, 1) & m1);
2663 agg_het1hom2 = agg_het1hom2 - (vecw_srli(agg_het1hom2, 1) & m1);
2664 agg_homhom = (agg_homhom & m2) + (vecw_srli(agg_homhom, 2) & m2);
2665 agg_ibs0 = (agg_ibs0 & m2) + (vecw_srli(agg_ibs0, 2) & m2);
2666 agg_hethet = (agg_hethet & m2) + (vecw_srli(agg_hethet, 2) & m2);
2667 agg_het2hom1 = (agg_het2hom1 & m2) + (vecw_srli(agg_het2hom1, 2) & m2);
2668 agg_het1hom2 = (agg_het1hom2 & m2) + (vecw_srli(agg_het1hom2, 2) & m2);
2669
2670 for (uint32_t offset = 1; offset != 3; ++offset) {
2671 hom1 = first_hom[vec_idx + offset];
2672 hom2 = second_hom[vec_idx + offset];
2673 ref2het1 = first_ref2het[vec_idx + offset];
2674 ref2het2 = second_ref2het[vec_idx + offset];
2675 VecW cur_homhom = hom1 & hom2;
2676 het1 = vecw_and_notfirst(hom1, ref2het1);
2677 het2 = vecw_and_notfirst(hom2, ref2het2);
2678 VecW cur_ibs0 = (ref2het1 ^ ref2het2) & cur_homhom;
2679 VecW cur_hethet = het1 & het2;
2680 VecW cur_het2hom1 = hom1 & het2;
2681 VecW cur_het1hom2 = hom2 & het1;
2682 cur_homhom = cur_homhom - (vecw_srli(cur_homhom, 1) & m1);
2683 cur_ibs0 = cur_ibs0 - (vecw_srli(cur_ibs0, 1) & m1);
2684 cur_hethet = cur_hethet - (vecw_srli(cur_hethet, 1) & m1);
2685 cur_het2hom1 = cur_het2hom1 - (vecw_srli(cur_het2hom1, 1) & m1);
2686 cur_het1hom2 = cur_het1hom2 - (vecw_srli(cur_het1hom2, 1) & m1);
2687 agg_homhom += (cur_homhom & m2) + (vecw_srli(cur_homhom, 2) & m2);
2688 agg_ibs0 += (cur_ibs0 & m2) + (vecw_srli(cur_ibs0, 2) & m2);
2689 agg_hethet += (cur_hethet & m2) + (vecw_srli(cur_hethet, 2) & m2);
2690 agg_het2hom1 += (cur_het2hom1 & m2) + (vecw_srli(cur_het2hom1, 2) & m2);
2691 agg_het1hom2 += (cur_het1hom2 & m2) + (vecw_srli(cur_het1hom2, 2) & m2);
2692 }
2693 acc_homhom.vw = acc_homhom.vw + (agg_homhom & m4) + (vecw_srli(agg_homhom, 4) & m4);
2694 acc_ibs0.vw = acc_ibs0.vw + (agg_ibs0 & m4) + (vecw_srli(agg_ibs0, 4) & m4);
2695 acc_hethet.vw = acc_hethet.vw + (agg_hethet & m4) + (vecw_srli(agg_hethet, 4) & m4);
2696 acc_het2hom1.vw = acc_het2hom1.vw + (agg_het2hom1 & m4) + (vecw_srli(agg_het2hom1, 4) & m4);
2697 acc_het1hom2.vw = acc_het1hom2.vw + (agg_het1hom2 & m4) + (vecw_srli(agg_het1hom2, 4) & m4);
2698 }
2699 const VecW m8 = VCONST_W(kMask00FF);
2700 acc_homhom.vw = (acc_homhom.vw & m8) + (vecw_srli(acc_homhom.vw, 8) & m8);
2701 acc_ibs0.vw = (acc_ibs0.vw & m8) + (vecw_srli(acc_ibs0.vw, 8) & m8);
2702 acc_hethet.vw = (acc_hethet.vw & m8) + (vecw_srli(acc_hethet.vw, 8) & m8);
2703 acc_het2hom1.vw = (acc_het2hom1.vw & m8) + (vecw_srli(acc_het2hom1.vw, 8) & m8);
2704 acc_het1hom2.vw = (acc_het1hom2.vw & m8) + (vecw_srli(acc_het1hom2.vw, 8) & m8);
2705 *king_counts_iter++ += UniVecHsum16(acc_ibs0);
2706 *king_counts_iter++ += UniVecHsum16(acc_hethet);
2707 *king_counts_iter++ += UniVecHsum16(acc_het2hom1);
2708 *king_counts_iter++ += UniVecHsum16(acc_het1hom2);
2709 *king_counts_iter++ += UniVecHsum16(acc_homhom);
2710 }
2711 }
2712 #endif
2713
2714 typedef struct CalcKingTableSubsetCtxStruct {
2715 uintptr_t* smaj_hom[2];
2716 uintptr_t* smaj_ref2het[2];
2717 uint32_t* loaded_sample_idx_pairs;
2718 uint32_t homhom_needed;
2719
2720 uint32_t* thread_start;
2721
2722 uint32_t* king_counts;
2723 } CalcKingTableSubsetCtx;
2724
2725 THREAD_FUNC_DECL CalcKingTableSubsetThread(void* raw_arg) {
2726 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
2727 const uintptr_t tidx = arg->tidx;
2728 CalcKingTableSubsetCtx* ctx = S_CAST(CalcKingTableSubsetCtx*, arg->sharedp->context);
2729
2730 const uint32_t start_idx = ctx->thread_start[tidx];
2731 const uint32_t end_idx = ctx->thread_start[tidx + 1];
2732 const uint32_t homhom_needed = ctx->homhom_needed;
2733 uint32_t parity = 0;
2734 do {
2735 if (homhom_needed) {
2736 IncrKingSubsetHomhom(ctx->loaded_sample_idx_pairs, ctx->smaj_hom[parity], ctx->smaj_ref2het[parity], start_idx, end_idx, ctx->king_counts);
2737 } else {
2738 IncrKingSubset(ctx->loaded_sample_idx_pairs, ctx->smaj_hom[parity], ctx->smaj_ref2het[parity], start_idx, end_idx, ctx->king_counts);
2739 }
2740 parity = 1 - parity;
2741 } while (!THREAD_BLOCK_FINISH(arg));
2742 THREAD_RETURN;
2743 }
2744
2745 PglErr KingTableSubsetLoad(const char* sorted_xidbox, const uint32_t* xid_map, const uintptr_t* sample_require, uintptr_t max_xid_blen, uintptr_t orig_sample_ct, double king_table_subset_thresh, XidMode xid_mode, uint32_t rel_check, uint32_t require_xor, uint32_t kinship_skip, uint32_t is_first_parallel_scan, uint64_t pair_idx_start, uint64_t pair_idx_stop, uintptr_t line_idx, TextStream* txsp, uint64_t* pair_idx_ptr, uint32_t* loaded_sample_idx_pairs, char* idbuf) {
2746 PglErr reterr = kPglRetSuccess;
2747 {
2748 // In --king-table-require case, sample1_in_require + sample2_in_require
2749 // can be either 1 or 2. In --king-table-require-xor case, it must be 1.
2750 const uint32_t require_sum_mask = require_xor? 1 : 3;
2751 uint64_t pair_idx = *pair_idx_ptr;
2752 // Assumes header line already read if pair_idx == 0, and if pair_idx is
2753 // positive, we're that far into the file.
2754 uint32_t* loaded_sample_idx_pairs_iter = loaded_sample_idx_pairs;
2755 ++line_idx;
2756 for (char* line_iter = TextLineEnd(txsp); TextGetUnsafe2(txsp, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) {
2757 const char* linebuf_iter = line_iter;
2758 uint32_t sample_uidx1;
2759 if (SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx1, idbuf)) {
2760 if (unlikely(!linebuf_iter)) {
2761 goto KingTableSubsetLoad_ret_MISSING_TOKENS;
2762 }
2763 line_iter = K_CAST(char*, linebuf_iter);
2764 continue;
2765 }
2766 linebuf_iter = FirstNonTspace(linebuf_iter);
2767 if (rel_check) {
2768 // linebuf_iter must point to the start of the second FID, while
2769 // line_iter points to the start of the first.
2770 const uint32_t first_fid_slen = CurTokenEnd(line_iter) - line_iter;
2771 const uint32_t second_fid_slen = CurTokenEnd(linebuf_iter) - linebuf_iter;
2772 if ((first_fid_slen != second_fid_slen) || (!memequal(line_iter, linebuf_iter, first_fid_slen))) {
2773 line_iter = K_CAST(char*, linebuf_iter);
2774 continue;
2775 }
2776 }
2777 uint32_t sample_uidx2;
2778 if (SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx2, idbuf)) {
2779 if (unlikely(!linebuf_iter)) {
2780 goto KingTableSubsetLoad_ret_MISSING_TOKENS;
2781 }
2782 line_iter = K_CAST(char*, linebuf_iter);
2783 continue;
2784 }
2785 if (unlikely(sample_uidx1 == sample_uidx2)) {
2786 // could technically be due to unloaded SID, so use inconsistent-input
2787 // error code
2788 snprintf(g_logbuf, kLogbufSize, "Error: Identical sample IDs on line %" PRIuPTR " of --king-table-subset file.\n", line_idx);
2789 goto KingTableSubsetLoad_ret_INCONSISTENT_INPUT_WW;
2790 }
2791 if (sample_require) {
2792 const uint32_t sample1_in_require = IsSet(sample_require, sample_uidx1);
2793 const uint32_t sample2_in_require = IsSet(sample_require, sample_uidx2);
2794 if (!((sample1_in_require + sample2_in_require) & require_sum_mask)) {
2795 line_iter = K_CAST(char*, linebuf_iter);
2796 continue;
2797 }
2798 }
2799 if (king_table_subset_thresh != -DBL_MAX) {
2800 linebuf_iter = FirstNonTspace(linebuf_iter);
2801 linebuf_iter = NextTokenMult0(linebuf_iter, kinship_skip);
2802 if (unlikely(!linebuf_iter)) {
2803 goto KingTableSubsetLoad_ret_MISSING_TOKENS;
2804 }
2805 double cur_kinship;
2806 const char* kinship_end = ScanadvDouble(linebuf_iter, &cur_kinship);
2807 if (!kinship_end) {
2808 line_iter = K_CAST(char*, linebuf_iter);
2809 continue;
2810 }
2811 if (unlikely(!IsSpaceOrEoln(*kinship_end))) {
2812 kinship_end = CurTokenEnd(kinship_end);
2813 *K_CAST(char*, kinship_end) = '\0';
2814 logerrprintfww("Error: Invalid numeric token '%s' on line %" PRIuPTR " of --king-table-subset file.\n", linebuf_iter, line_idx);
2815 goto KingTableSubsetLoad_ret_MALFORMED_INPUT;
2816 }
2817 if (cur_kinship < king_table_subset_thresh) {
2818 line_iter = K_CAST(char*, kinship_end);
2819 continue;
2820 }
2821 }
2822 line_iter = K_CAST(char*, linebuf_iter);
2823 if (pair_idx < pair_idx_start) {
2824 ++pair_idx;
2825 continue;
2826 }
2827 *loaded_sample_idx_pairs_iter++ = sample_uidx1;
2828 *loaded_sample_idx_pairs_iter++ = sample_uidx2;
2829 ++pair_idx;
2830 if (pair_idx == pair_idx_stop) {
2831 if (!is_first_parallel_scan) {
2832 TextSetPos(AdvPastDelim(line_iter, '\n'), txsp);
2833 goto KingTableSubsetLoad_finish;
2834 }
2835 // large --parallel job, first pass: count number of valid pairs, don't
2836 // save the remainder
2837 pair_idx_start = ~0LLU;
2838 }
2839 }
2840 if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
2841 goto KingTableSubsetLoad_ret_TSTREAM_FAIL;
2842 }
2843 KingTableSubsetLoad_finish:
2844 *pair_idx_ptr = pair_idx;
2845 }
2846 while (0) {
2847 KingTableSubsetLoad_ret_TSTREAM_FAIL:
2848 TextStreamErrPrint("--king-table-subset file", txsp);
2849 break;
2850 KingTableSubsetLoad_ret_MALFORMED_INPUT:
2851 reterr = kPglRetMalformedInput;
2852 break;
2853 KingTableSubsetLoad_ret_MISSING_TOKENS:
2854 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --king-table-subset file has fewer tokens than expected.\n", line_idx);
2855 KingTableSubsetLoad_ret_INCONSISTENT_INPUT_WW:
2856 WordWrapB(0);
2857 logerrputsb();
2858 reterr = kPglRetInconsistentInput;
2859 break;
2860 }
2861 return reterr;
2862 }
2863
2864 typedef struct FidPairIteratorStruct {
2865 uint32_t block_start_idx;
2866 uint32_t block_end_idx;
2867 uint32_t idx1;
2868 uint32_t idx2;
2869 } FidPairIterator;
2870
2871 void InitFidPairIterator(FidPairIterator* fpip) {
2872 fpip->block_start_idx = UINT32_MAX; // deliberate overflow
2873 fpip->block_end_idx = 0;
2874 fpip->idx1 = 0;
2875 fpip->idx2 = 0; // defensive
2876 }
2877
2878 uint64_t CountRelCheckPairs(const char* nsorted_xidbox, uintptr_t max_xid_blen, uintptr_t orig_sample_ct, char* idbuf) {
2879 uint64_t total = 0;
2880 for (uintptr_t block_start_idx = 0; block_start_idx != orig_sample_ct; ) {
2881 const char* fid_start = &(nsorted_xidbox[block_start_idx * max_xid_blen]);
2882 const uint32_t fid_slen = AdvToDelim(fid_start, '\t') - fid_start;
2883 memcpy(idbuf, fid_start, fid_slen);
2884 idbuf[fid_slen] = ' ';
2885 // bugfix (14 Jan 2020): forgot that natural-sorting was used...
2886 idbuf[fid_slen + 1] = '\0';
2887 const uintptr_t block_end_idx = ExpsearchNsortStrLb(idbuf, nsorted_xidbox, max_xid_blen, orig_sample_ct, block_start_idx + 1);
2888 const uint64_t cur_block_size = block_end_idx - block_start_idx;
2889 total += (cur_block_size * (cur_block_size - 1)) / 2;
2890 block_start_idx = block_end_idx;
2891 }
2892 return total;
2893 }
2894
2895 uint64_t CountRelCheckPairsSampleRequire(const char* nsorted_xidbox, const uint32_t* xid_map, const uintptr_t* sample_require, uintptr_t max_xid_blen, uintptr_t orig_sample_ct, uint32_t require_xor, char* idbuf) {
2896 uint64_t total = 0;
2897 for (uintptr_t block_start_idx = 0; block_start_idx != orig_sample_ct; ) {
2898 const char* fid_start = &(nsorted_xidbox[block_start_idx * max_xid_blen]);
2899 const uint32_t fid_slen = AdvToDelim(fid_start, '\t') - fid_start;
2900 memcpy(idbuf, fid_start, fid_slen);
2901 idbuf[fid_slen] = ' ';
2902 idbuf[fid_slen + 1] = '\0';
2903 const uintptr_t block_end_idx = ExpsearchNsortStrLb(idbuf, nsorted_xidbox, max_xid_blen, orig_sample_ct, block_start_idx + 1);
2904 const uint64_t cur_block_size = block_end_idx - block_start_idx;
2905 uintptr_t required_ct = 0;
2906 for (uintptr_t block_idx = block_start_idx; block_idx != block_end_idx; ++block_idx) {
2907 const uint32_t sample_uidx = xid_map[block_idx];
2908 required_ct += IsSet(sample_require, sample_uidx);
2909 }
2910 const uint64_t optional_ct = cur_block_size - required_ct;
2911 if (!require_xor) {
2912 total += ((cur_block_size * (cur_block_size - 1)) - (optional_ct * (optional_ct - 1))) / 2;
2913 } else {
2914 total += required_ct * optional_ct;
2915 }
2916 block_start_idx = block_end_idx;
2917 }
2918 return total;
2919 }
2920
2921 void GetRelCheckOrKTRequirePairs(const char* nsorted_xidbox, const uint32_t* xid_map, const uintptr_t* sample_require, uintptr_t max_xid_blen, uintptr_t orig_sample_ct, uint32_t rel_check, uint32_t require_xor, uint32_t is_first_parallel_scan, uint64_t pair_idx_start, uint64_t pair_idx_stop, FidPairIterator* fpip, uint64_t* pair_idx_ptr, uint32_t* loaded_sample_idx_pairs, char* idbuf) {
2922 // Support "--make-king-table rel-check" without an actual subset-file.
2923 // These loops aren't really optimized, since actual rel-check use cases
2924 // should have small families where it doesn't matter.
2925 //
2926 // In the is_first_parallel_scan case, *pair_idx_ptr is set to the total
2927 // number of eligible pairs, even if it's greater than pair_idx_stop.
2928 // Otherwise, *pair_idx_ptr will not be set to larger than pair_idx_stop.
2929 uint32_t block_start_idx = fpip->block_start_idx;
2930 uint32_t block_end_idx = fpip->block_end_idx;
2931 uint32_t idx1 = fpip->idx1;
2932 uint32_t idx2 = fpip->idx2;
2933 uint64_t pair_idx = *pair_idx_ptr;
2934 uint32_t* loaded_sample_idx_pairs_iter = loaded_sample_idx_pairs;
2935 if (!sample_require) {
2936 while (1) {
2937 for (; idx1 != block_end_idx; ++idx1) {
2938 // idx1 >= idx2.
2939 uint32_t cur_pair_ct = idx1 - idx2;
2940 uint32_t idx2_stop = idx1;
2941 if (pair_idx_stop - pair_idx < cur_pair_ct) {
2942 cur_pair_ct = pair_idx_stop - pair_idx;
2943 idx2_stop = idx2 + cur_pair_ct;
2944 }
2945 if (pair_idx < pair_idx_start) {
2946 // possible in later --parallel shards
2947 const uint64_t skip_ct = pair_idx_start - pair_idx;
2948 if (skip_ct >= cur_pair_ct) {
2949 idx2 = idx2_stop;
2950 } else {
2951 idx2 += skip_ct;
2952 }
2953 // pair_idx is updated correctly after the inner loop
2954 }
2955 const uint32_t sample_uidx1 = xid_map[idx1];
2956 for (; idx2 != idx2_stop; ++idx2) {
2957 const uint32_t sample_uidx2 = xid_map[idx2];
2958 *loaded_sample_idx_pairs_iter++ = sample_uidx1;
2959 *loaded_sample_idx_pairs_iter++ = sample_uidx2;
2960 }
2961 pair_idx += cur_pair_ct;
2962 if (pair_idx == pair_idx_stop) {
2963 if (is_first_parallel_scan) {
2964 pair_idx = CountRelCheckPairs(nsorted_xidbox, max_xid_blen, orig_sample_ct, idbuf);
2965 }
2966 goto GetRelCheckOrKTRequirePairs_early_exit;
2967 }
2968 idx2 = block_start_idx;
2969 }
2970 block_start_idx = block_end_idx;
2971 if (block_start_idx == orig_sample_ct) {
2972 break;
2973 }
2974 idx2 = block_start_idx;
2975 const char* fid_start = &(nsorted_xidbox[block_start_idx * max_xid_blen]);
2976 const uint32_t fid_slen = AdvToDelim(fid_start, '\t') - fid_start;
2977 memcpy(idbuf, fid_start, fid_slen);
2978 idbuf[fid_slen] = ' ';
2979 idbuf[fid_slen + 1] = '\0';
2980 block_end_idx = ExpsearchNsortStrLb(idbuf, nsorted_xidbox, max_xid_blen, orig_sample_ct, block_start_idx + 1);
2981 }
2982 } else {
2983 // --king-table-require[-xor]
2984 while (1) {
2985 for (; idx1 != block_end_idx; ++idx1) {
2986 // idx1 >= idx2.
2987 uint32_t cur_pair_ct = 0;
2988 const uint32_t sample_uidx1 = xid_map[idx1];
2989 if (IsSet(sample_require, sample_uidx1)) {
2990 if (!require_xor) {
2991 cur_pair_ct = idx1 - idx2;
2992 uint32_t idx2_stop = idx1;
2993 if (pair_idx_stop - pair_idx < cur_pair_ct) {
2994 cur_pair_ct = pair_idx_stop - pair_idx;
2995 idx2_stop = idx2 + cur_pair_ct;
2996 }
2997 if (pair_idx < pair_idx_start) {
2998 const uint64_t skip_ct = pair_idx_start - pair_idx;
2999 if (skip_ct >= cur_pair_ct) {
3000 idx2 = idx2_stop;
3001 } else {
3002 idx2 += skip_ct;
3003 }
3004 }
3005 for (; idx2 != idx2_stop; ++idx2) {
3006 const uint32_t sample_uidx2 = xid_map[idx2];
3007 *loaded_sample_idx_pairs_iter++ = sample_uidx1;
3008 *loaded_sample_idx_pairs_iter++ = sample_uidx2;
3009 }
3010 } else {
3011 // --king-table-require-xor
3012 cur_pair_ct += idx1 - idx2;
3013 for (uint32_t idx = idx2; idx != idx1; ++idx) {
3014 const uint32_t sample_uidx = xid_map[idx];
3015 cur_pair_ct -= IsSet(sample_require, sample_uidx);
3016 }
3017 uint32_t idx2_stop = idx1;
3018 if (pair_idx_stop - pair_idx < cur_pair_ct) {
3019 cur_pair_ct = pair_idx_stop - pair_idx;
3020 idx2_stop = idx2;
3021 uint32_t remaining_required_pair_ct = cur_pair_ct;
3022 while (1) {
3023 const uint32_t sample_uidx = xid_map[idx2_stop];
3024 ++idx2_stop;
3025 if (!IsSet(sample_require, sample_uidx)) {
3026 --remaining_required_pair_ct;
3027 if (!remaining_required_pair_ct) {
3028 break;
3029 }
3030 }
3031 }
3032 }
3033 if (pair_idx < pair_idx_start) {
3034 const uint64_t skip_ct = pair_idx_start - pair_idx;
3035 if (skip_ct >= cur_pair_ct) {
3036 idx2 = idx2_stop;
3037 } else {
3038 uint32_t remaining_skip_ct = skip_ct;
3039 while (1) {
3040 const uint32_t sample_uidx = xid_map[idx2];
3041 ++idx2;
3042 if (!IsSet(sample_require, sample_uidx)) {
3043 --remaining_skip_ct;
3044 if (!remaining_skip_ct) {
3045 break;
3046 }
3047 }
3048 }
3049 }
3050 }
3051 for (; idx2 != idx2_stop; ++idx2) {
3052 const uint32_t sample_uidx2 = xid_map[idx2];
3053 if (!IsSet(sample_require, sample_uidx2)) {
3054 *loaded_sample_idx_pairs_iter++ = sample_uidx1;
3055 *loaded_sample_idx_pairs_iter++ = sample_uidx2;
3056 }
3057 }
3058 }
3059 } else {
3060 // !IsSet(sample_require, sample_uidx1)
3061 for (uint32_t idx = idx2; idx != idx1; ++idx) {
3062 const uint32_t sample_uidx = xid_map[idx];
3063 cur_pair_ct += IsSet(sample_require, sample_uidx);
3064 }
3065 uint32_t idx2_stop = idx1;
3066 if (pair_idx_stop - pair_idx < cur_pair_ct) {
3067 cur_pair_ct = pair_idx_stop - pair_idx;
3068 idx2_stop = idx2;
3069 uint32_t remaining_required_pair_ct = cur_pair_ct;
3070 while (1) {
3071 const uint32_t sample_uidx = xid_map[idx2_stop];
3072 ++idx2_stop;
3073 if (IsSet(sample_require, sample_uidx)) {
3074 --remaining_required_pair_ct;
3075 if (!remaining_required_pair_ct) {
3076 break;
3077 }
3078 }
3079 }
3080 }
3081 if (pair_idx < pair_idx_start) {
3082 const uint64_t skip_ct = pair_idx_start - pair_idx;
3083 if (skip_ct >= cur_pair_ct) {
3084 idx2 = idx2_stop;
3085 } else {
3086 uint32_t remaining_skip_ct = skip_ct;
3087 while (1) {
3088 const uint32_t sample_uidx = xid_map[idx2];
3089 ++idx2;
3090 if (IsSet(sample_require, sample_uidx)) {
3091 --remaining_skip_ct;
3092 if (!remaining_skip_ct) {
3093 break;
3094 }
3095 }
3096 }
3097 }
3098 }
3099 for (; idx2 != idx2_stop; ++idx2) {
3100 const uint32_t sample_uidx2 = xid_map[idx2];
3101 if (IsSet(sample_require, sample_uidx2)) {
3102 *loaded_sample_idx_pairs_iter++ = sample_uidx1;
3103 *loaded_sample_idx_pairs_iter++ = sample_uidx2;
3104 }
3105 }
3106 }
3107 pair_idx += cur_pair_ct;
3108 // bugfix (21 Jun 2023): forgot to handle the usual rel_check==0 case.
3109 // (didn't notice since I was testing on IID-only data.)
3110 if (pair_idx == pair_idx_stop) {
3111 if (is_first_parallel_scan) {
3112 if (!rel_check) {
3113 const uint64_t orig_sample_ct64 = orig_sample_ct;
3114 const uintptr_t orig_sample_ctl = BitCtToWordCt(orig_sample_ct);
3115 const uint64_t optional_ct = orig_sample_ct - PopcountWords(sample_require, orig_sample_ctl);
3116 if (!require_xor) {
3117 pair_idx = ((orig_sample_ct64 * (orig_sample_ct - 1)) - (optional_ct * (optional_ct - 1))) / 2;
3118 } else {
3119 pair_idx = orig_sample_ct64 * optional_ct;
3120 }
3121 } else {
3122 pair_idx = CountRelCheckPairsSampleRequire(nsorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, require_xor, idbuf);
3123 }
3124 }
3125 goto GetRelCheckOrKTRequirePairs_early_exit;
3126 }
3127 idx2 = block_start_idx;
3128 }
3129 block_start_idx = block_end_idx;
3130 if (block_start_idx == orig_sample_ct) {
3131 break;
3132 }
3133 idx2 = block_start_idx;
3134 if (!rel_check) {
3135 block_end_idx = orig_sample_ct;
3136 } else {
3137 const char* fid_start = &(nsorted_xidbox[block_start_idx * max_xid_blen]);
3138 const uint32_t fid_slen = AdvToDelim(fid_start, '\t') - fid_start;
3139 memcpy(idbuf, fid_start, fid_slen);
3140 idbuf[fid_slen] = ' ';
3141 idbuf[fid_slen + 1] = '\0';
3142 block_end_idx = ExpsearchNsortStrLb(idbuf, nsorted_xidbox, max_xid_blen, orig_sample_ct, block_start_idx + 1);
3143 }
3144 }
3145 }
3146 GetRelCheckOrKTRequirePairs_early_exit:
3147 *pair_idx_ptr = pair_idx;
3148 fpip->block_start_idx = block_start_idx;
3149 fpip->block_end_idx = block_end_idx;
3150 fpip->idx1 = idx1;
3151 fpip->idx2 = idx2;
3152 }
3153
3154 PglErr CalcKingTableSubset(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* variant_include, const ChrInfo* cip, const char* subset_fname, const char* require_fnames, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, double king_table_filter, double king_table_subset_thresh, uint32_t rel_check, KingFlags king_flags, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
3155 // subset_fname permitted to be nullptr when rel_check is true.
3156 unsigned char* bigstack_mark = g_bigstack_base;
3157 FILE* outfile = nullptr;
3158 char* cswritep = nullptr;
3159 PglErr reterr = kPglRetSuccess;
3160 TextStream txs;
3161 CompressStreamState css;
3162 ThreadGroup tg;
3163 PreinitTextStream(&txs);
3164 PreinitCstream(&css);
3165 PreinitThreads(&tg);
3166 {
3167 if (unlikely(IsSet(cip->haploid_mask, 0))) {
3168 logerrputs("Error: --make-king-table cannot be used on haploid genomes.\n");
3169 goto CalcKingTableSubset_ret_INCONSISTENT_INPUT;
3170 }
3171 reterr = ConditionalAllocateNonAutosomalVariants(cip, "--make-king-table", raw_variant_ct, &variant_include, &variant_ct);
3172 if (unlikely(reterr)) {
3173 goto CalcKingTableSubset_ret_1;
3174 }
3175
3176 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
3177 const uintptr_t* sample_require = nullptr;
3178 const uint32_t require_xor = (king_flags / kfKingTableRequireXor) & 1;
3179 if (require_fnames) {
3180 uintptr_t* sample_require_tmp;
3181 reterr = LoadSampleIds(require_fnames, orig_sample_include, siip, "make-king-table", raw_sample_ct, orig_sample_ct, kfLoadSampleIdsMultifile, &sample_require_tmp, nullptr);
3182 if (unlikely(reterr)) {
3183 goto CalcKingTableSubset_ret_1;
3184 }
3185 sample_require = sample_require_tmp;
3186 const uint32_t require_set_size = PopcountWords(sample_require, raw_sample_ctl);
3187 if (unlikely(!require_set_size)) {
3188 logerrputs("Error: No sample ID(s) in --king-table-require[-xor] file(s) are in the current\ndataset.\n");
3189 goto CalcKingTableSubset_ret_INCONSISTENT_INPUT;
3190 }
3191 if (unlikely(require_xor && (require_set_size == orig_sample_ct))) {
3192 logerrputs("Error: All sample ID(s) in --king-table-require-xor file(s) are in the current\ndataset.\n");
3193 goto CalcKingTableSubset_ret_INCONSISTENT_INPUT;
3194 }
3195 logprintf("--king-table-require%s: %u sample ID%s loaded.\n", require_xor? "-xor" : "", require_set_size, (require_set_size == 1)? "" : "s");
3196 }
3197 // 1. Write output header line if necessary.
3198 // 2. Count number of relevant sample pairs (higher uidx in high 32 bits),
3199 // and load as much as may be useful during first pass (usually there
3200 // will be only one pass).
3201 // 3. If list is empty, error out.
3202 // 4. If --parallel, discard part of the list, then exit if remainder
3203 // empty.
3204 // 5. If remainder of list is too large to process in one pass, determine
3205 // number of necessary passes. If output filename refers to the same
3206 // thing as input file, append ~ to input filename.
3207 // Loop:
3208 // * Determine which sample indexes appear in this part of the list.
3209 // Compute current cumulative_popcounts, perform uidx -> idx conversion.
3210 // (Don't bother sorting the pairs, since that prevents
3211 // --parallel/multipass mode from delivering the same results.)
3212 // * Execute usual KING-robust computation, write .kin0 entries.
3213 // * If not last pass, reload input .kin0, etc.
3214 //
3215 // Could store the pairs in a more compact manner, but can live with 50%
3216 // space bloat for now.
3217 uint32_t sample_ctaw = BitCtToAlignedWordCt(orig_sample_ct);
3218 uint32_t sample_ctaw2 = NypCtToAlignedWordCt(orig_sample_ct);
3219 uint32_t king_bufsizew = kKingMultiplexWords * orig_sample_ct;
3220 uintptr_t* cur_sample_include;
3221 uint32_t* sample_include_cumulative_popcounts;
3222 uintptr_t* loadbuf;
3223 uintptr_t* splitbuf_hom;
3224 uintptr_t* splitbuf_ref2het;
3225 VecW* vecaligned_buf;
3226 // ok if allocations are a bit oversized
3227 CalcKingTableSubsetCtx ctx;
3228 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_sample_include) ||
3229 bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
3230 bigstack_alloc_w(sample_ctaw2, &loadbuf) ||
3231 bigstack_alloc_w(kPglBitTransposeBatch * sample_ctaw, &splitbuf_hom) ||
3232 bigstack_alloc_w(kPglBitTransposeBatch * sample_ctaw, &splitbuf_ref2het) ||
3233 bigstack_alloc_w(king_bufsizew, &(ctx.smaj_hom[0])) ||
3234 bigstack_alloc_w(king_bufsizew, &(ctx.smaj_ref2het[0])) ||
3235 bigstack_alloc_w(king_bufsizew, &(ctx.smaj_hom[1])) ||
3236 bigstack_alloc_w(king_bufsizew, &(ctx.smaj_ref2het[1])) ||
3237 bigstack_alloc_v(kPglBitTransposeBufvecs, &vecaligned_buf))) {
3238 goto CalcKingTableSubset_ret_NOMEM;
3239 }
3240 SetKingTableFname(king_flags, parallel_idx, parallel_tot, outname_end);
3241 if (subset_fname) {
3242 uint32_t fname_slen;
3243 #ifdef _WIN32
3244 fname_slen = GetFullPathName(subset_fname, kPglFnamesize, g_textbuf, nullptr);
3245 if (unlikely((!fname_slen) || (fname_slen > kPglFnamesize)))
3246 #else
3247 if (unlikely(!realpath(subset_fname, g_textbuf)))
3248 #endif
3249 {
3250 logerrprintfww(kErrprintfFopen, subset_fname, strerror(errno));
3251 goto CalcKingTableSubset_ret_OPEN_FAIL;
3252 }
3253 if (RealpathIdentical(outname, g_textbuf, &(g_textbuf[kPglFnamesize + 64]))) {
3254 logerrputs("Warning: --king-table-subset input filename matches --make-king-table output\nfilename. Appending '~' to input filename.\n");
3255 fname_slen = strlen(subset_fname);
3256 memcpy(g_textbuf, subset_fname, fname_slen);
3257 strcpy_k(&(g_textbuf[fname_slen]), "~");
3258 if (unlikely(rename(subset_fname, g_textbuf))) {
3259 logerrputs("Error: Failed to append '~' to --king-table-subset input filename.\n");
3260 goto CalcKingTableSubset_ret_OPEN_FAIL;
3261 }
3262 subset_fname = g_textbuf;
3263 }
3264 }
3265
3266 // Safe to "write" the header line now, if necessary.
3267 reterr = InitCstreamAlloc(outname, 0, king_flags & kfKingTableZs, max_thread_ct, kMaxMediumLine + kCompressStreamBlock, &css, &cswritep);
3268 if (unlikely(reterr)) {
3269 goto CalcKingTableSubset_ret_1;
3270 }
3271 const uint32_t king_col_fid = FidColIsRequired(siip, king_flags / kfKingColMaybefid);
3272 const uint32_t king_col_sid = SidColIsRequired(siip->sids, king_flags / kfKingColMaybesid);
3273 if (!parallel_idx) {
3274 cswritep = AppendKingTableHeader(king_flags, king_col_fid, king_col_sid, cswritep);
3275 }
3276 const uintptr_t max_sample_fmtid_blen = GetMaxSampleFmtidBlen(siip, king_col_fid, king_col_sid);
3277 char* collapsed_sample_fmtids;
3278 if (unlikely(bigstack_alloc_c(max_sample_fmtid_blen * orig_sample_ct, &collapsed_sample_fmtids))) {
3279 goto CalcKingTableSubset_ret_NOMEM;
3280 }
3281 // possible todo: allow this to change between passes
3282 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
3283 if (calc_thread_ct > orig_sample_ct / 32) {
3284 calc_thread_ct = orig_sample_ct / 32;
3285 }
3286 if (!calc_thread_ct) {
3287 calc_thread_ct = 1;
3288 }
3289 // could eventually have 64-bit ctx.thread_start?
3290 if (unlikely(SetThreadCt(calc_thread_ct, &tg) ||
3291 bigstack_alloc_u32(calc_thread_ct + 1, &ctx.thread_start))) {
3292 goto CalcKingTableSubset_ret_NOMEM;
3293 }
3294
3295 uintptr_t line_idx = 0;
3296 uint32_t kinship_skip = 0;
3297 // we overwrite this in subset_fname case, so no need to check for
3298 // --strict-sid0
3299 XidMode xid_mode = siip->sids? kfXidModeFidIidSid : kfXidModeIidSid;
3300 if (subset_fname) {
3301 reterr = InitTextStream(subset_fname, kTextStreamBlenFast, 1, &txs);
3302 if (unlikely(reterr)) {
3303 if (reterr == kPglRetEof) {
3304 logerrputs("Error: Empty --king-table-subset file.\n");
3305 goto CalcKingTableSubset_ret_MALFORMED_INPUT;
3306 }
3307 goto CalcKingTableSubset_ret_TSTREAM_FAIL;
3308 }
3309 ++line_idx;
3310 const char* linebuf_iter = TextGet(&txs);
3311 if (unlikely(!linebuf_iter)) {
3312 if (!TextStreamErrcode2(&txs, &reterr)) {
3313 logerrputs("Error: Empty --king-table-subset file.\n");
3314 goto CalcKingTableSubset_ret_MALFORMED_INPUT;
3315 }
3316 goto CalcKingTableSubset_ret_TSTREAM_FAIL;
3317 }
3318 const char* token_end = CurTokenEnd(linebuf_iter);
3319 uint32_t token_slen = token_end - linebuf_iter;
3320 // Make this work with both KING- and plink2-generated .kin0 files.
3321 uint32_t fid_present = strequal_k(linebuf_iter, "#FID1", token_slen) || strequal_k(linebuf_iter, "FID", token_slen);
3322 if (fid_present) {
3323 linebuf_iter = FirstNonTspace(token_end);
3324 token_end = CurTokenEnd(linebuf_iter);
3325 token_slen = token_end - linebuf_iter;
3326 xid_mode = kfXidModeFidIid;
3327 } else {
3328 if (unlikely(*linebuf_iter != '#')) {
3329 goto CalcKingTableSubset_ret_INVALID_HEADER;
3330 }
3331 ++linebuf_iter;
3332 --token_slen;
3333 xid_mode = kfXidModeIid;
3334 }
3335 if (unlikely((!strequal_k(linebuf_iter, "ID1", token_slen)) && (!strequal_k(linebuf_iter, "IID1", token_slen)))) {
3336 goto CalcKingTableSubset_ret_INVALID_HEADER;
3337 }
3338 linebuf_iter = FirstNonTspace(token_end);
3339 token_end = CurTokenEnd(linebuf_iter);
3340 token_slen = token_end - linebuf_iter;
3341 if (strequal_k(linebuf_iter, "SID1", token_slen)) {
3342 if (siip->sids) {
3343 xid_mode = fid_present? kfXidModeFidIidSid : kfXidModeIidSid;
3344 } else {
3345 xid_mode |= kfXidModeFlagSkipSid;
3346 }
3347 linebuf_iter = FirstNonTspace(token_end);
3348 token_end = CurTokenEnd(linebuf_iter);
3349 token_slen = token_end - linebuf_iter;
3350 }
3351 if (fid_present) {
3352 if (unlikely(!strequal_k(linebuf_iter, "FID2", token_slen))) {
3353 goto CalcKingTableSubset_ret_INVALID_HEADER;
3354 }
3355 linebuf_iter = FirstNonTspace(token_end);
3356 token_end = CurTokenEnd(linebuf_iter);
3357 token_slen = token_end - linebuf_iter;
3358 }
3359 if (unlikely((!strequal_k(linebuf_iter, "ID2", token_slen)) && (!strequal_k(linebuf_iter, "IID2", token_slen)))) {
3360 goto CalcKingTableSubset_ret_INVALID_HEADER;
3361 }
3362 if (xid_mode & (kfXidModeFlagSid | kfXidModeFlagSkipSid)) {
3363 linebuf_iter = FirstNonTspace(token_end);
3364 token_end = CurTokenEnd(linebuf_iter);
3365 token_slen = token_end - linebuf_iter;
3366 if (unlikely(!strequal_k(linebuf_iter, "SID2", token_slen))) {
3367 goto CalcKingTableSubset_ret_INVALID_HEADER;
3368 }
3369 }
3370 if (king_table_subset_thresh != -DBL_MAX) {
3371 king_table_subset_thresh *= 1.0 - kSmallEpsilon;
3372 while (1) {
3373 linebuf_iter = FirstNonTspace(token_end);
3374 token_end = CurTokenEnd(linebuf_iter);
3375 token_slen = token_end - linebuf_iter;
3376 if (unlikely(!token_slen)) {
3377 logerrputs("Error: No kinship-coefficient column in --king-table-subset file.\n");
3378 goto CalcKingTableSubset_ret_INCONSISTENT_INPUT;
3379 }
3380 if (strequal_k(linebuf_iter, "KINSHIP", token_slen) || strequal_k(linebuf_iter, "Kinship", token_slen)) {
3381 break;
3382 }
3383 ++kinship_skip;
3384 }
3385 }
3386 }
3387
3388 uint32_t* xid_map; // IDs not collapsed
3389 char* sorted_xidbox;
3390 uintptr_t max_xid_blen;
3391 // may as well use natural-sort order in rel-check-only case
3392 reterr = SortedXidboxInitAlloc(orig_sample_include, siip, orig_sample_ct, xid_mode, (!subset_fname), &sorted_xidbox, &xid_map, &max_xid_blen);
3393 if (unlikely(reterr)) {
3394 goto CalcKingTableSubset_ret_1;
3395 }
3396 char* idbuf;
3397 if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) {
3398 goto CalcKingTableSubset_ret_NOMEM;
3399 }
3400
3401 ctx.homhom_needed = (king_flags & kfKingColNsnp) || ((!(king_flags & kfKingCounts)) && (king_flags & (kfKingColHethet | kfKingColIbs0 | kfKingColIbs1)));
3402 const uint32_t homhom_needed_p4 = ctx.homhom_needed + 4;
3403 // if homhom_needed, 8 + 20 bytes per pair, otherwise 8 + 16
3404 uintptr_t pair_buf_capacity = bigstack_left();
3405 if (unlikely(pair_buf_capacity < 2 * kCacheline)) {
3406 goto CalcKingTableSubset_ret_NOMEM;
3407 }
3408 // adverse rounding
3409 pair_buf_capacity = (pair_buf_capacity - 2 * kCacheline) / (24 + 4 * ctx.homhom_needed);
3410 if (pair_buf_capacity > 0xffffffffU) {
3411 // 32-bit ctx.thread_start[] for now
3412 pair_buf_capacity = 0xffffffffU;
3413 }
3414 ctx.loaded_sample_idx_pairs = S_CAST(uint32_t*, bigstack_alloc_raw_rd(pair_buf_capacity * 2 * sizeof(int32_t)));
3415 ctx.king_counts = R_CAST(uint32_t*, g_bigstack_base);
3416 SetThreadFuncAndData(CalcKingTableSubsetThread, &ctx, &tg);
3417
3418 FidPairIterator fpi;
3419 InitFidPairIterator(&fpi);
3420
3421 uint64_t pair_idx = 0;
3422 if (!subset_fname) {
3423 GetRelCheckOrKTRequirePairs(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, rel_check, require_xor, (parallel_tot != 1), 0, pair_buf_capacity, &fpi, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3424 } else {
3425 fputs("Scanning --king-table-subset file...", stdout);
3426 fflush(stdout);
3427 reterr = KingTableSubsetLoad(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, king_table_subset_thresh, xid_mode, rel_check, require_xor, kinship_skip, (parallel_tot != 1), 0, pair_buf_capacity, line_idx, &txs, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3428 if (unlikely(reterr)) {
3429 goto CalcKingTableSubset_ret_1;
3430 }
3431 }
3432 uint64_t pair_idx_global_start = 0;
3433 uint64_t pair_idx_global_stop = ~0LLU;
3434 if (parallel_tot != 1) {
3435 const uint64_t parallel_pair_ct = pair_idx;
3436 pair_idx_global_start = (parallel_idx * parallel_pair_ct) / parallel_tot;
3437 pair_idx_global_stop = ((parallel_idx + 1) * parallel_pair_ct) / parallel_tot;
3438 if (pair_idx > pair_buf_capacity) {
3439 // may as well document possible overflow
3440 if (unlikely(parallel_pair_ct > ((~0LLU) / kParallelMax))) {
3441 if (!subset_fname) {
3442 // This is easy to support if there's ever a need, of course.
3443 logerrputs("Error: Too many \"--make-king-table rel-check\" sample pairs for this " PROG_NAME_STR "\nbuild.\n");
3444 } else {
3445 logerrputs("Error: Too many --king-table-subset sample pairs for this " PROG_NAME_STR " build.\n");
3446 }
3447 reterr = kPglRetNotYetSupported;
3448 goto CalcKingTableSubset_ret_1;
3449 }
3450 if (pair_idx_global_stop > pair_buf_capacity) {
3451 // large --parallel job
3452 pair_idx = 0;
3453 if (!subset_fname) {
3454 InitFidPairIterator(&fpi);
3455 GetRelCheckOrKTRequirePairs(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, rel_check, require_xor, 0, pair_idx_global_start, MINV(pair_idx_global_stop, pair_idx_global_start + pair_buf_capacity), &fpi, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3456 } else {
3457 reterr = TextRewind(&txs);
3458 if (unlikely(reterr)) {
3459 goto CalcKingTableSubset_ret_TSTREAM_FAIL;
3460 }
3461 // bugfix (4 Oct 2019): forgot a bunch of reinitialization here
3462 line_idx = 1;
3463 char* header_throwaway;
3464 reterr = TextNextLineLstrip(&txs, &header_throwaway);
3465 if (unlikely(reterr)) {
3466 goto CalcKingTableSubset_ret_TSTREAM_REWIND_FAIL;
3467 }
3468 reterr = KingTableSubsetLoad(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, king_table_subset_thresh, xid_mode, rel_check, require_xor, kinship_skip, 0, pair_idx_global_start, MINV(pair_idx_global_stop, pair_idx_global_start + pair_buf_capacity), line_idx, &txs, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3469 if (unlikely(reterr)) {
3470 goto CalcKingTableSubset_ret_1;
3471 }
3472 }
3473 } else {
3474 pair_idx = pair_idx_global_stop;
3475 if (pair_idx_global_start) {
3476 memmove(ctx.loaded_sample_idx_pairs, &(ctx.loaded_sample_idx_pairs[pair_idx_global_start * 2]), (pair_idx_global_stop - pair_idx_global_start) * 2 * sizeof(int32_t));
3477 }
3478 }
3479 } else {
3480 pair_idx = pair_idx_global_stop;
3481 if (pair_idx_global_start) {
3482 memmove(ctx.loaded_sample_idx_pairs, &(ctx.loaded_sample_idx_pairs[pair_idx_global_start * 2]), (pair_idx_global_stop - pair_idx_global_start) * 2 * sizeof(int32_t));
3483 }
3484 }
3485 }
3486 uint64_t pair_idx_cur_start = pair_idx_global_start;
3487 uint64_t king_table_filter_ct = 0;
3488 uintptr_t pass_idx = 1;
3489 while (pair_idx_cur_start < pair_idx) {
3490 ZeroWArr(raw_sample_ctl, cur_sample_include);
3491 const uintptr_t cur_pair_ct = pair_idx - pair_idx_cur_start;
3492 const uintptr_t cur_pair_ct_x2 = 2 * cur_pair_ct;
3493 for (uintptr_t ulii = 0; ulii != cur_pair_ct_x2; ++ulii) {
3494 SetBit(ctx.loaded_sample_idx_pairs[ulii], cur_sample_include);
3495 }
3496 FillCumulativePopcounts(cur_sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
3497 const uint32_t cur_sample_ct = sample_include_cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(cur_sample_include[raw_sample_ctl - 1]);
3498 const uint32_t cur_sample_ctaw = BitCtToAlignedWordCt(cur_sample_ct);
3499 const uint32_t cur_sample_ctaw2 = NypCtToAlignedWordCt(cur_sample_ct);
3500 if (cur_sample_ct != raw_sample_ct) {
3501 for (uintptr_t ulii = 0; ulii != cur_pair_ct_x2; ++ulii) {
3502 ctx.loaded_sample_idx_pairs[ulii] = RawToSubsettedPos(cur_sample_include, sample_include_cumulative_popcounts, ctx.loaded_sample_idx_pairs[ulii]);
3503 }
3504 }
3505 ZeroU32Arr(cur_pair_ct * homhom_needed_p4, ctx.king_counts);
3506 CollapsedSampleFmtidInit(cur_sample_include, siip, cur_sample_ct, king_col_fid, king_col_sid, max_sample_fmtid_blen, collapsed_sample_fmtids);
3507 for (uint32_t tidx = 0; tidx <= calc_thread_ct; ++tidx) {
3508 ctx.thread_start[tidx] = (tidx * S_CAST(uint64_t, cur_pair_ct)) / calc_thread_ct;
3509 }
3510 if (pass_idx != 1) {
3511 ReinitThreads(&tg);
3512 }
3513 // possible todo: singleton/monomorphic optimization for sufficiently
3514 // large jobs
3515 uintptr_t variant_uidx_base = 0;
3516 uintptr_t cur_bits = variant_include[0];
3517 uint32_t variants_completed = 0;
3518 uint32_t parity = 0;
3519 const uint32_t sample_batch_ct_m1 = (cur_sample_ct - 1) / kPglBitTransposeBatch;
3520 PgrSampleSubsetIndex pssi;
3521 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
3522 do {
3523 const uint32_t cur_block_size = MINV(variant_ct - variants_completed, kKingMultiplex);
3524 uintptr_t* cur_smaj_hom = ctx.smaj_hom[parity];
3525 uintptr_t* cur_smaj_ref2het = ctx.smaj_ref2het[parity];
3526 // "block" = distance computation granularity, usually 1024 or 1536
3527 // variants
3528 // "batch" = variant-major-to-sample-major transpose granularity,
3529 // currently 512 variants
3530 uint32_t variant_batch_size = kPglBitTransposeBatch;
3531 uint32_t variant_batch_size_rounded_up = kPglBitTransposeBatch;
3532 const uint32_t write_batch_ct_m1 = (cur_block_size - 1) / kPglBitTransposeBatch;
3533 for (uint32_t write_batch_idx = 0; ; ++write_batch_idx) {
3534 if (write_batch_idx >= write_batch_ct_m1) {
3535 if (write_batch_idx > write_batch_ct_m1) {
3536 break;
3537 }
3538 variant_batch_size = ModNz(cur_block_size, kPglBitTransposeBatch);
3539 variant_batch_size_rounded_up = variant_batch_size;
3540 const uint32_t variant_batch_size_rem = variant_batch_size % kBitsPerWord;
3541 if (variant_batch_size_rem) {
3542 const uint32_t trailing_variant_ct = kBitsPerWord - variant_batch_size_rem;
3543 variant_batch_size_rounded_up += trailing_variant_ct;
3544 ZeroWArr(trailing_variant_ct * cur_sample_ctaw, &(splitbuf_hom[variant_batch_size * cur_sample_ctaw]));
3545 ZeroWArr(trailing_variant_ct * cur_sample_ctaw, &(splitbuf_ref2het[variant_batch_size * cur_sample_ctaw]));
3546 }
3547 }
3548 uintptr_t* hom_iter = splitbuf_hom;
3549 uintptr_t* ref2het_iter = splitbuf_ref2het;
3550 for (uint32_t uii = 0; uii != variant_batch_size; ++uii) {
3551 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
3552 reterr = PgrGet(cur_sample_include, pssi, cur_sample_ct, variant_uidx, simple_pgrp, loadbuf);
3553 if (unlikely(reterr)) {
3554 PgenErrPrintNV(reterr, variant_uidx);
3555 goto CalcKingTableSubset_ret_1;
3556 }
3557 // may want to support some sort of low-MAF optimization here
3558 SetTrailingNyps(cur_sample_ct, loadbuf);
3559 SplitHomRef2hetUnsafeW(loadbuf, cur_sample_ctaw2, hom_iter, ref2het_iter);
3560 hom_iter = &(hom_iter[cur_sample_ctaw]);
3561 ref2het_iter = &(ref2het_iter[cur_sample_ctaw]);
3562 }
3563 // uintptr_t* read_iter = loadbuf;
3564 uintptr_t* write_hom_iter = &(cur_smaj_hom[write_batch_idx * kPglBitTransposeWords]);
3565 uintptr_t* write_ref2het_iter = &(cur_smaj_ref2het[write_batch_idx * kPglBitTransposeWords]);
3566 uint32_t write_batch_size = kPglBitTransposeBatch;
3567 for (uint32_t sample_batch_idx = 0; ; ++sample_batch_idx) {
3568 if (sample_batch_idx >= sample_batch_ct_m1) {
3569 if (sample_batch_idx > sample_batch_ct_m1) {
3570 break;
3571 }
3572 write_batch_size = ModNz(cur_sample_ct, kPglBitTransposeBatch);
3573 }
3574 // bugfix: read_batch_size must be rounded up to word boundary,
3575 // since we want to one-out instead of zero-out the trailing bits
3576 //
3577 // bugfix: if we always use kPglBitTransposeBatch instead of
3578 // variant_batch_size_rounded_up, we read/write past the
3579 // kKingMultiplex limit and clobber the first variants of the next
3580 // sample with garbage.
3581 TransposeBitblock(&(splitbuf_hom[sample_batch_idx * kPglBitTransposeWords]), cur_sample_ctaw, kKingMultiplexWords, variant_batch_size_rounded_up, write_batch_size, write_hom_iter, vecaligned_buf);
3582 TransposeBitblock(&(splitbuf_ref2het[sample_batch_idx * kPglBitTransposeWords]), cur_sample_ctaw, kKingMultiplexWords, variant_batch_size_rounded_up, write_batch_size, write_ref2het_iter, vecaligned_buf);
3583 write_hom_iter = &(write_hom_iter[kKingMultiplex * kPglBitTransposeWords]);
3584 write_ref2het_iter = &(write_ref2het_iter[kKingMultiplex * kPglBitTransposeWords]);
3585 }
3586 }
3587 const uint32_t cur_block_sizew = BitCtToWordCt(cur_block_size);
3588 if (cur_block_sizew < kKingMultiplexWords) {
3589 uintptr_t* write_hom_iter = &(cur_smaj_hom[cur_block_sizew]);
3590 uintptr_t* write_ref2het_iter = &(cur_smaj_ref2het[cur_block_sizew]);
3591 const uint32_t write_word_ct = kKingMultiplexWords - cur_block_sizew;
3592 for (uint32_t sample_idx = 0; sample_idx != cur_sample_ct; ++sample_idx) {
3593 ZeroWArr(write_word_ct, write_hom_iter);
3594 ZeroWArr(write_word_ct, write_ref2het_iter);
3595 write_hom_iter = &(write_hom_iter[kKingMultiplexWords]);
3596 write_ref2het_iter = &(write_ref2het_iter[kKingMultiplexWords]);
3597 }
3598 }
3599 if (variants_completed) {
3600 JoinThreads(&tg);
3601 // CalcKingTableSubsetThread() never errors out
3602 }
3603 // this update must occur after JoinThreads() call
3604 if (variants_completed + cur_block_size == variant_ct) {
3605 DeclareLastThreadBlock(&tg);
3606 }
3607 if (unlikely(SpawnThreads(&tg))) {
3608 goto CalcKingTableSubset_ret_THREAD_CREATE_FAIL;
3609 }
3610 printf("\r--make-king-table pass %" PRIuPTR ": %u variants complete.", pass_idx, variants_completed);
3611 fflush(stdout);
3612 variants_completed += cur_block_size;
3613 parity = 1 - parity;
3614 } while (!IsLastBlock(&tg));
3615 JoinThreads(&tg);
3616 printf("\r--make-king-table pass %" PRIuPTR ": Writing... \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", pass_idx);
3617 fflush(stdout);
3618
3619 const uint32_t king_col_id = king_flags & kfKingColId;
3620 const uint32_t king_col_nsnp = king_flags & kfKingColNsnp;
3621 const uint32_t king_col_hethet = king_flags & kfKingColHethet;
3622 const uint32_t king_col_ibs0 = king_flags & kfKingColIbs0;
3623 const uint32_t king_col_ibs1 = king_flags & kfKingColIbs1;
3624 const uint32_t king_col_kinship = king_flags & kfKingColKinship;
3625 const uint32_t report_counts = king_flags & kfKingCounts;
3626 uint32_t* results_iter = ctx.king_counts;
3627 double nonmiss_recip = 0.0;
3628 for (uintptr_t cur_pair_idx = 0; cur_pair_idx != cur_pair_ct; ++cur_pair_idx, results_iter = &(results_iter[homhom_needed_p4])) {
3629 const uint32_t ibs0_ct = results_iter[kKingOffsetIbs0];
3630 const uint32_t hethet_ct = results_iter[kKingOffsetHethet];
3631 const uint32_t het2hom1_ct = results_iter[kKingOffsetHet2Hom1];
3632 const uint32_t het1hom2_ct = results_iter[kKingOffsetHet1Hom2];
3633 const intptr_t smaller_het_ct = hethet_ct + MINV(het1hom2_ct, het2hom1_ct);
3634 const double kinship_coeff = 0.5 - (S_CAST(double, 4 * S_CAST(intptr_t, ibs0_ct) + het1hom2_ct + het2hom1_ct) / S_CAST(double, 4 * smaller_het_ct));
3635 if ((king_table_filter != -DBL_MAX) && (kinship_coeff < king_table_filter)) {
3636 ++king_table_filter_ct;
3637 continue;
3638 }
3639 const uint32_t sample_idx1 = ctx.loaded_sample_idx_pairs[2 * cur_pair_idx];
3640 const uint32_t sample_idx2 = ctx.loaded_sample_idx_pairs[2 * cur_pair_idx + 1];
3641 if (king_col_id) {
3642 cswritep = strcpyax(cswritep, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx1]), '\t');
3643 cswritep = strcpyax(cswritep, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx2]), '\t');
3644 }
3645 if (homhom_needed_p4 == 5) {
3646 const uint32_t homhom_ct = results_iter[kKingOffsetHomhom];
3647 const uint32_t nonmiss_ct = het1hom2_ct + het2hom1_ct + homhom_ct + hethet_ct;
3648 if (king_col_nsnp) {
3649 cswritep = u32toa_x(nonmiss_ct, '\t', cswritep);
3650 }
3651 if (!report_counts) {
3652 nonmiss_recip = 1.0 / u31tod(nonmiss_ct);
3653 }
3654 }
3655 if (king_col_hethet) {
3656 if (report_counts) {
3657 cswritep = u32toa(hethet_ct, cswritep);
3658 } else {
3659 cswritep = dtoa_g(nonmiss_recip * u31tod(hethet_ct), cswritep);
3660 }
3661 *cswritep++ = '\t';
3662 }
3663 if (king_col_ibs0) {
3664 if (report_counts) {
3665 cswritep = u32toa(ibs0_ct, cswritep);
3666 } else {
3667 cswritep = dtoa_g(nonmiss_recip * u31tod(ibs0_ct), cswritep);
3668 }
3669 *cswritep++ = '\t';
3670 }
3671 if (king_col_ibs1) {
3672 if (report_counts) {
3673 cswritep = u32toa_x(het1hom2_ct, '\t', cswritep);
3674 cswritep = u32toa(het2hom1_ct, cswritep);
3675 } else {
3676 cswritep = dtoa_g(nonmiss_recip * u31tod(het1hom2_ct), cswritep);
3677 *cswritep++ = '\t';
3678 cswritep = dtoa_g(nonmiss_recip * u31tod(het2hom1_ct), cswritep);
3679 }
3680 *cswritep++ = '\t';
3681 }
3682 if (king_col_kinship) {
3683 cswritep = dtoa_g(kinship_coeff, cswritep);
3684 ++cswritep;
3685 }
3686 DecrAppendBinaryEoln(&cswritep);
3687 if (unlikely(Cswrite(&css, &cswritep))) {
3688 goto CalcKingTableSubset_ret_WRITE_FAIL;
3689 }
3690 }
3691
3692 putc_unlocked('\r', stdout);
3693 const uint64_t pair_complete_ct = pair_idx - pair_idx_global_start;
3694 logprintf("Subsetted --make-king-table: %" PRIu64 " pair%s complete.\n", pair_complete_ct, (pair_complete_ct == 1)? "" : "s");
3695 if (TextEof(&txs) || (pair_idx == pair_idx_global_stop)) {
3696 break;
3697 }
3698 pair_idx_cur_start = pair_idx;
3699 if (!subset_fname) {
3700 GetRelCheckOrKTRequirePairs(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, rel_check, require_xor, 0, pair_idx_global_start, MINV(pair_idx_global_stop, pair_idx_global_start + pair_buf_capacity), &fpi, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3701 } else {
3702 fputs("Scanning --king-table-subset file...", stdout);
3703 fflush(stdout);
3704 reterr = KingTableSubsetLoad(sorted_xidbox, xid_map, sample_require, max_xid_blen, orig_sample_ct, king_table_subset_thresh, xid_mode, rel_check, require_xor, kinship_skip, 0, pair_idx_cur_start, MINV(pair_idx_global_stop, pair_idx_cur_start + pair_buf_capacity), line_idx, &txs, &pair_idx, ctx.loaded_sample_idx_pairs, idbuf);
3705 if (unlikely(reterr)) {
3706 goto CalcKingTableSubset_ret_1;
3707 }
3708 }
3709 ++pass_idx;
3710 }
3711 if (unlikely(CswriteCloseNull(&css, cswritep))) {
3712 goto CalcKingTableSubset_ret_WRITE_FAIL;
3713 }
3714 logprintfww("Results written to %s .\n", outname);
3715 if (king_table_filter != -DBL_MAX) {
3716 const uint64_t reported_ct = pair_idx - pair_idx_global_start - king_table_filter_ct;
3717 logprintf("--king-table-filter: %" PRIu64 " relationship%s reported (%" PRIu64 " filtered out).\n", reported_ct, (reported_ct == 1)? "" : "s", king_table_filter_ct);
3718 }
3719 }
3720 while (0) {
3721 CalcKingTableSubset_ret_NOMEM:
3722 reterr = kPglRetNomem;
3723 break;
3724 CalcKingTableSubset_ret_OPEN_FAIL:
3725 reterr = kPglRetOpenFail;
3726 break;
3727 CalcKingTableSubset_ret_TSTREAM_REWIND_FAIL:
3728 TextStreamErrPrintRewind("--king-table-subset file", &txs, &reterr);
3729 break;
3730 CalcKingTableSubset_ret_TSTREAM_FAIL:
3731 TextStreamErrPrint("--king-table-subset file", &txs);
3732 break;
3733 CalcKingTableSubset_ret_WRITE_FAIL:
3734 reterr = kPglRetWriteFail;
3735 break;
3736 CalcKingTableSubset_ret_INVALID_HEADER:
3737 logerrputs("Error: Invalid header line in --king-table-subset file.\n");
3738 CalcKingTableSubset_ret_MALFORMED_INPUT:
3739 reterr = kPglRetMalformedInput;
3740 break;
3741 CalcKingTableSubset_ret_INCONSISTENT_INPUT:
3742 reterr = kPglRetInconsistentInput;
3743 break;
3744 CalcKingTableSubset_ret_THREAD_CREATE_FAIL:
3745 reterr = kPglRetThreadCreateFail;
3746 break;
3747 }
3748 CalcKingTableSubset_ret_1:
3749 CleanupThreads(&tg);
3750 CleanupTextStream2("--king-table-subset file", &txs, &reterr);
3751 CswriteCloseCond(&css, cswritep);
3752 fclose_cond(outfile);
3753 BigstackReset(bigstack_mark);
3754 return reterr;
3755 }
3756
3757 // assumes trailing bits of genovec are zeroed out
3758 PglErr ExpandCenteredVarmaj(const uintptr_t* genovec, const uintptr_t* dosage_present, const Dosage* dosage_main, uint32_t variance_standardize, uint32_t is_haploid, uint32_t sample_ct, uint32_t dosage_ct, double ref_freq, double* normed_dosages) {
3759 const double alt_freq = 1.0 - ref_freq;
3760 double inv_stdev;
3761 if (variance_standardize) {
3762 const double variance = 2 * ref_freq * alt_freq;
3763 if (!(variance > kSmallEpsilon)) {
3764 // See LoadMultiallelicCenteredVarmaj(). This check was tightened up in
3765 // alpha 3 to reject all-het and monomorphic-wrong-allele variants.
3766 STD_ARRAY_DECL(uint32_t, 4, genocounts);
3767 GenoarrCountFreqsUnsafe(genovec, sample_ct, genocounts);
3768 if (unlikely(dosage_ct || genocounts[1])) {
3769 return kPglRetDegenerateData;
3770 }
3771 if (variance != variance) {
3772 if (unlikely(genocounts[0] || genocounts[2])) {
3773 return kPglRetDegenerateData;
3774 }
3775 } else {
3776 if (ref_freq > 0.5) {
3777 if (unlikely(genocounts[2])) {
3778 return kPglRetDegenerateData;
3779 }
3780 } else {
3781 if (unlikely(genocounts[0])) {
3782 return kPglRetDegenerateData;
3783 }
3784 }
3785 }
3786 ZeroDArr(sample_ct, normed_dosages);
3787 return kPglRetSuccess;
3788 }
3789 inv_stdev = 1.0 / sqrt(variance);
3790 if (is_haploid) {
3791 // For our purposes, variance is doubled in haploid case.
3792 inv_stdev *= (1.0 / kSqrt2);
3793 }
3794 // possible todo:
3795 // * Could use one inv_stdev for males and one for nonmales for chrX
3796 // --score (while still leaving that out of GRM... or just leave males
3797 // out there?). This depends on dosage compensation model; discussed in
3798 // e.g. GCTA paper.
3799 } else {
3800 // Extra factor of 2 removed from haploid 'cov' formula in alpha 3.
3801 inv_stdev = is_haploid? 0.5 : 1.0;
3802 }
3803 PopulateRescaledDosage(genovec, dosage_present, dosage_main, inv_stdev, -2 * alt_freq * inv_stdev, 0.0, sample_ct, dosage_ct, normed_dosages);
3804 return kPglRetSuccess;
3805 }
3806
3807 // This breaks the "don't pass pssi between functions" rule since it's a thin
3808 // wrapper around PgrGetInv1D().
3809 PglErr LoadBiallelicCenteredVarmaj(const uintptr_t* sample_include, PgrSampleSubsetIndex pssi, uint32_t variance_standardize, uint32_t is_haploid, uint32_t sample_ct, uint32_t variant_uidx, double ref_freq, PgenReader* simple_pgrp, uint32_t* missing_presentp, double* normed_dosages, uintptr_t* genovec_buf, uintptr_t* dosage_present_buf, Dosage* dosage_main_buf) {
3810 uint32_t dosage_ct;
3811 PglErr reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, genovec_buf, dosage_present_buf, dosage_main_buf, &dosage_ct);
3812 if (unlikely(reterr)) {
3813 // don't print malformed-.pgen error message here, since this is called
3814 // from multithreaded loops
3815 return reterr;
3816 }
3817 ZeroTrailingNyps(sample_ct, genovec_buf);
3818 if (missing_presentp) {
3819 // missing_present assumed to be initialized to 0
3820 // this should probably be a library function...
3821 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
3822 if (!dosage_ct) {
3823 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3824 const uintptr_t detect_11 = Word11(genovec_buf[widx]);
3825 if (detect_11) {
3826 *missing_presentp = 1;
3827 break;
3828 }
3829 }
3830 } else {
3831 Halfword* dosage_present_alias = R_CAST(Halfword*, dosage_present_buf);
3832 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3833 const uintptr_t detect_11 = Word11(genovec_buf[widx]);
3834 if (detect_11) {
3835 if (PackWordToHalfword(detect_11) & (~dosage_present_alias[widx])) {
3836 *missing_presentp = 1;
3837 break;
3838 }
3839 }
3840 }
3841 }
3842 }
3843 return ExpandCenteredVarmaj(genovec_buf, dosage_present_buf, dosage_main_buf, variance_standardize, is_haploid, sample_ct, dosage_ct, ref_freq, normed_dosages);
3844 }
3845
3846 double ComputeDiploidMultiallelicVariance(const double* cur_allele_freqs, uint32_t cur_allele_ct) {
3847 const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1;
3848 double variance = 0.0;
3849 double freq_sum = 0.0;
3850 for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct_m1; ++allele_idx) {
3851 const double cur_allele_freq = cur_allele_freqs[allele_idx];
3852 variance += cur_allele_freq * (1.0 - cur_allele_freq);
3853 freq_sum += cur_allele_freq;
3854 }
3855 if (freq_sum < 1.0 - kSmallEpsilon) {
3856 const double last_allele_freq = 1.0 - freq_sum;
3857 variance += freq_sum * last_allele_freq;
3858 }
3859 return variance;
3860 }
3861
3862 // Assumes trailing bits of pgvp->genovec have been zeroed out.
3863 BoolErr CheckMultiallelicDegenVariance(const PgenVariant* pgvp, const double* cur_allele_freqs, uint32_t sample_ct, uint32_t cur_allele_ct, double variance) {
3864 // One allele has 100% frequency (or all frequencies are NaN).
3865 // If it's the REF allele, error out unless all nonmissing genotypes are
3866 // homozygous-ref, in which case this row can be filled with zeroes (or
3867 // omitted).
3868 // If it's ALT1, error out unless all nonmissing genotypes are hom-ALT1, etc.
3869 const uintptr_t* genovec_buf = pgvp->genovec;
3870 STD_ARRAY_DECL(uint32_t, 4, genocounts);
3871 GenoarrCountFreqsUnsafe(genovec_buf, sample_ct, genocounts);
3872 if (unlikely(pgvp->dosage_ct || genocounts[1])) {
3873 return 1;
3874 }
3875 const uint32_t nm_sample_ct = genocounts[2];
3876 if (variance != variance) {
3877 // NaN frequency is possible when all founder genotypes/dosages are
3878 // missing. Error out in this case unless all other genotypes/dosages are
3879 // also missing.
3880 return (genocounts[0] || nm_sample_ct);
3881 }
3882 if (cur_allele_freqs[0] > 0.5) {
3883 return (nm_sample_ct != 0);
3884 }
3885 if (unlikely(genocounts[0])) {
3886 return 1;
3887 }
3888 if (cur_allele_freqs[1] > 0.5) {
3889 return (pgvp->patch_10_ct != 0);
3890 }
3891 if (pgvp->patch_10_ct != nm_sample_ct) {
3892 return 0;
3893 }
3894 const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1;
3895 uint32_t mono_allele_idx;
3896 for (mono_allele_idx = 2; mono_allele_idx != cur_allele_ct_m1; ++mono_allele_idx) {
3897 if (cur_allele_freqs[mono_allele_idx] > 0.5) {
3898 break;
3899 }
3900 }
3901 return !AllBytesAreX(pgvp->patch_10_vals, mono_allele_idx, 2 * nm_sample_ct);
3902 }
3903
3904 PglErr LoadMultiallelicCenteredVarmaj(const uintptr_t* sample_include, PgrSampleSubsetIndex pssi, const double* cur_allele_freqs, uint32_t variance_standardize, uint32_t is_haploid, uint32_t sample_ct, uint32_t variant_uidx, uint32_t cur_allele_ct, uint32_t allele_idx_start, uint32_t allele_idx_end, PgenReader* simple_pgrp, uint32_t* missing_presentp, double* normed_dosages, PgenVariant* pgvp, double* allele_1copy_buf) {
3905 // This handles cur_allele_ct == 2 correctly. But we typically don't use it
3906 // in that case since it does ~2x as much work as necessary: the two
3907 // normed_dosages[] rows are identical except for opposite sign, so it's best
3908 // to combine them into one row.
3909 PglErr reterr = PgrGetMD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgvp);
3910 if (unlikely(reterr)) {
3911 return reterr;
3912 }
3913 ZeroTrailingNyps(sample_ct, pgvp->genovec);
3914 const uintptr_t* genovec_buf = pgvp->genovec;
3915 if (missing_presentp) {
3916 // missing_present assumed to be initialized to 0
3917 const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct);
3918 if (!pgvp->dosage_ct) {
3919 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3920 const uintptr_t detect_11 = Word11(genovec_buf[widx]);
3921 if (detect_11) {
3922 *missing_presentp = 1;
3923 break;
3924 }
3925 }
3926 } else {
3927 Halfword* dosage_present_alias = R_CAST(Halfword*, pgvp->dosage_present);
3928 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3929 const uintptr_t detect_11 = Word11(genovec_buf[widx]);
3930 if (detect_11) {
3931 if (PackWordToHalfword(detect_11) & (~dosage_present_alias[widx])) {
3932 *missing_presentp = 1;
3933 break;
3934 }
3935 }
3936 }
3937 }
3938 }
3939 const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1;
3940 double freq_sum = cur_allele_freqs[0];
3941 for (uint32_t uii = 1; uii != cur_allele_ct_m1; ++uii) {
3942 freq_sum += cur_allele_freqs[uii];
3943 }
3944 const double last_allele_freq = 1.0 - freq_sum;
3945 double inv_stdev;
3946 if (variance_standardize) {
3947 const double variance = ComputeDiploidMultiallelicVariance(cur_allele_freqs, cur_allele_ct);
3948 if (!(variance > kSmallEpsilon)) {
3949 if (unlikely(CheckMultiallelicDegenVariance(pgvp, cur_allele_freqs, sample_ct, cur_allele_ct, variance))) {
3950 return kPglRetDegenerateData;
3951 }
3952 ZeroDArr(S_CAST(uintptr_t, sample_ct) * (allele_idx_end - allele_idx_start), normed_dosages);
3953 return kPglRetSuccess;
3954 }
3955 inv_stdev = (1.0 / kSqrt2) / sqrt(variance);
3956 if (is_haploid) {
3957 inv_stdev *= (1.0 / kSqrt2);
3958 }
3959 } else {
3960 inv_stdev = is_haploid? (0.5 / kSqrt2) : (1.0 / kSqrt2);
3961 }
3962 if (!pgvp->dosage_ct) {
3963 // diploid:
3964 // \sum_i x_i * (1 - x_i)
3965 double lookup_vals[32] ALIGNV16;
3966 double* normed_dosages0 = normed_dosages - (allele_idx_start * S_CAST(uintptr_t, sample_ct));
3967 double alt1_intercept = 0.0;
3968 for (uint32_t allele_idx = allele_idx_start; allele_idx != allele_idx_end; ++allele_idx) {
3969 double cur_allele_freq;
3970 if (allele_idx != cur_allele_ct_m1) {
3971 cur_allele_freq = cur_allele_freqs[allele_idx];
3972 } else {
3973 cur_allele_freq = last_allele_freq;
3974 }
3975 const double intercept = -2 * cur_allele_freq * inv_stdev;
3976 if (!allele_idx) {
3977 // genovec entry of 0 corresponds to 2 copies of REF allele, etc.
3978 lookup_vals[0] = intercept + 2 * inv_stdev;
3979 lookup_vals[2] = intercept + inv_stdev;
3980 lookup_vals[4] = intercept;
3981 lookup_vals[6] = 0.0;
3982 InitLookup16x8bx2(lookup_vals);
3983 GenoarrLookup16x8bx2(genovec_buf, lookup_vals, sample_ct, normed_dosages0);
3984 continue;
3985 }
3986 allele_1copy_buf[allele_idx] = intercept + inv_stdev;
3987 if (allele_idx == 1) {
3988 alt1_intercept = intercept;
3989 lookup_vals[0] = intercept;
3990 lookup_vals[2] = intercept + inv_stdev;
3991 lookup_vals[4] = intercept + 2 * inv_stdev;
3992 lookup_vals[6] = 0.0;
3993 InitLookup16x8bx2(lookup_vals);
3994 GenoarrLookup16x8bx2(genovec_buf, lookup_vals, sample_ct, &(normed_dosages0[sample_ct]));
3995 } else {
3996 // bugfix (28 May 2023): missing genotypes in multiallelic variants
3997 // were not handled correctly here
3998 lookup_vals[0] = intercept;
3999 lookup_vals[2] = intercept;
4000 lookup_vals[4] = intercept;
4001 lookup_vals[6] = 0.0;
4002 InitLookup16x8bx2(lookup_vals);
4003 double* normed_dosages_cur_allele = &(normed_dosages0[allele_idx * S_CAST(uintptr_t, sample_ct)]);
4004 GenoarrLookup16x8bx2(genovec_buf, lookup_vals, sample_ct, normed_dosages_cur_allele);
4005 }
4006 }
4007 const uintptr_t* patch_01_set = pgvp->patch_01_set;
4008 const AlleleCode* patch_01_vals = pgvp->patch_01_vals;
4009 const uintptr_t* patch_10_set = pgvp->patch_10_set;
4010 const AlleleCode* patch_10_vals = pgvp->patch_10_vals;
4011 const uint32_t patch_01_ct = pgvp->patch_01_ct;
4012 const uint32_t patch_10_ct = pgvp->patch_10_ct;
4013 if ((allele_idx_start < 2) && (allele_idx_end >= 2)) {
4014 if (patch_01_ct) {
4015 uintptr_t sample_idx_base = 0;
4016 uintptr_t cur_bits = patch_01_set[0];
4017 if (cur_allele_ct == allele_idx_end) {
4018 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
4019 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits);
4020 normed_dosages0[sample_ct + sample_idx] = alt1_intercept;
4021 const uintptr_t cur_allele_code = patch_01_vals[uii];
4022 normed_dosages0[cur_allele_code * sample_ct + sample_idx] = allele_1copy_buf[cur_allele_code];
4023 }
4024 } else {
4025 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
4026 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits);
4027 normed_dosages0[sample_ct + sample_idx] = alt1_intercept;
4028 const uintptr_t cur_allele_code = patch_01_vals[uii];
4029 if (cur_allele_code < allele_idx_end) {
4030 normed_dosages0[cur_allele_code * sample_ct + sample_idx] = allele_1copy_buf[cur_allele_code];
4031 }
4032 }
4033 }
4034 }
4035 if (patch_10_ct) {
4036 uintptr_t sample_idx_base = 0;
4037 uintptr_t cur_bits = patch_10_set[0];
4038 if (cur_allele_ct == allele_idx_end) {
4039 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
4040 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits);
4041 normed_dosages0[sample_ct + sample_idx] = alt1_intercept;
4042 const uintptr_t ac0 = patch_10_vals[2 * uii];
4043 const uintptr_t ac1 = patch_10_vals[2 * uii + 1];
4044 const double ac0_1copy_val = allele_1copy_buf[ac0];
4045 if (ac0 == ac1) {
4046 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val + inv_stdev;
4047 } else {
4048 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val;
4049 normed_dosages0[ac1 * sample_ct + sample_idx] = allele_1copy_buf[ac1];
4050 }
4051 }
4052 } else {
4053 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
4054 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits);
4055 normed_dosages0[sample_ct + sample_idx] = alt1_intercept;
4056 const uintptr_t ac0 = patch_10_vals[2 * uii];
4057 if (ac0 >= allele_idx_end) {
4058 continue;
4059 }
4060 const uintptr_t ac1 = patch_10_vals[2 * uii + 1];
4061 const double ac0_1copy_val = allele_1copy_buf[ac0];
4062 if (ac0 == ac1) {
4063 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val + inv_stdev;
4064 } else {
4065 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val;
4066 if (ac1 < allele_idx_end) {
4067 normed_dosages0[ac1 * sample_ct + sample_idx] = allele_1copy_buf[ac1];
4068 }
4069 }
4070 }
4071 }
4072 }
4073 } else {
4074 if (patch_01_ct) {
4075 uintptr_t sample_idx_base = 0;
4076 uintptr_t cur_bits = patch_01_set[0];
4077 for (uint32_t uii = 0; uii != patch_01_ct; ++uii) {
4078 const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &cur_bits);
4079 const uintptr_t cur_allele_code = patch_01_vals[uii];
4080 if ((cur_allele_code >= allele_idx_start) && (cur_allele_code < allele_idx_end)) {
4081 normed_dosages0[cur_allele_code * sample_ct + sample_idx] = allele_1copy_buf[cur_allele_code];
4082 }
4083 }
4084 }
4085 if (patch_10_ct) {
4086 uintptr_t sample_idx_base = 0;
4087 uintptr_t cur_bits = patch_10_set[0];
4088 for (uint32_t uii = 0; uii != patch_10_ct; ++uii) {
4089 const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &cur_bits);
4090 const uintptr_t ac0 = patch_10_vals[2 * uii];
4091 if (ac0 >= allele_idx_end) {
4092 continue;
4093 }
4094 const uintptr_t ac1 = patch_10_vals[2 * uii + 1];
4095 if (ac1 < allele_idx_start) {
4096 continue;
4097 }
4098 const double ac0_1copy_val = allele_1copy_buf[ac0];
4099 if (ac0 == ac1) {
4100 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val + inv_stdev;
4101 } else {
4102 if (ac0 >= allele_idx_start) {
4103 normed_dosages0[ac0 * sample_ct + sample_idx] = ac0_1copy_val;
4104 }
4105 if (ac1 < allele_idx_end) {
4106 normed_dosages0[ac1 * sample_ct + sample_idx] = allele_1copy_buf[ac1];
4107 }
4108 }
4109 }
4110 }
4111 }
4112 return kPglRetSuccess;
4113 }
4114 fputs("true multiallelic dosages not yet supported by LoadMultiallelicCenteredVarmaj()\n", stderr);
4115 exit(S_CAST(int32_t, kPglRetNotYetSupported));
4116 return kPglRetSuccess;
4117 }
4118
4119 // This function handles error-message-logging.
4120 PglErr LoadCenteredVarmajBlock(const uintptr_t* sample_include, PgrSampleSubsetIndex pssi, const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const double* allele_freqs, uint32_t variance_standardize, uint32_t is_haploid, uint32_t sample_ct, uint32_t variant_ct, PgenReader* simple_pgrp, double* normed_vmaj_iter, uintptr_t* variant_include_has_missing, uint32_t* cur_batch_sizep, uint32_t* variant_idxp, uintptr_t* variant_uidxp, uintptr_t* allele_idx_basep, uint32_t* cur_allele_ctp, uint32_t* incomplete_allele_idxp, PgenVariant* pgvp, double* allele_1copy_buf) {
4121 const uint32_t std_batch_size = *cur_batch_sizep;
4122 uint32_t variant_idx = *variant_idxp;
4123 uintptr_t variant_uidx = *variant_uidxp;
4124 uintptr_t allele_idx_base = *allele_idx_basep;
4125 uint32_t cur_allele_ct = *cur_allele_ctp;
4126 uint32_t incomplete_allele_idx = *incomplete_allele_idxp;
4127 uintptr_t variant_uidx_base;
4128 uintptr_t cur_bits;
4129 BitIter1Start(variant_include, variant_uidx + (incomplete_allele_idx != 0), &variant_uidx_base, &cur_bits);
4130 for (uint32_t allele_bidx = 0; allele_bidx != std_batch_size; ) {
4131 uint32_t missing_present = 0;
4132 if (!incomplete_allele_idx) {
4133 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4134 if (!allele_idx_offsets) {
4135 allele_idx_base = variant_uidx;
4136 } else {
4137 allele_idx_base = allele_idx_offsets[variant_uidx];
4138 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_base;
4139 allele_idx_base -= variant_uidx;
4140 }
4141 }
4142 uint32_t allele_idx_stop;
4143 uint32_t allele_idx_end;
4144 PglErr reterr;
4145 if (cur_allele_ct == 2) {
4146 allele_idx_stop = 1;
4147 allele_idx_end = 1;
4148 reterr = LoadBiallelicCenteredVarmaj(sample_include, pssi, variance_standardize, is_haploid, sample_ct, variant_uidx, allele_freqs[allele_idx_base], simple_pgrp, variant_include_has_missing? (&missing_present) : nullptr, normed_vmaj_iter, pgvp->genovec, pgvp->dosage_present, pgvp->dosage_main);
4149 } else {
4150 allele_idx_end = cur_allele_ct;
4151 allele_idx_stop = std_batch_size + incomplete_allele_idx - allele_bidx;
4152 if (allele_idx_stop > allele_idx_end) {
4153 allele_idx_stop = allele_idx_end;
4154 }
4155 reterr = LoadMultiallelicCenteredVarmaj(sample_include, pssi, &(allele_freqs[allele_idx_base]), variance_standardize, is_haploid, sample_ct, variant_uidx, cur_allele_ct, incomplete_allele_idx, allele_idx_stop, simple_pgrp, variant_include_has_missing? (&missing_present) : nullptr, normed_vmaj_iter, pgvp, allele_1copy_buf);
4156 }
4157 if (unlikely(reterr)) {
4158 if (reterr == kPglRetDegenerateData) {
4159 logputs("\n");
4160 logerrputs("Error: Zero-MAF variant is not actually monomorphic. (This is possible when\ne.g. MAF is estimated from founders, but the minor allele was only observed in\nnonfounders. In any case, you should be using e.g. --maf to filter out all\nvery-low-MAF variants, since the relationship matrix distance formula does not\nhandle them well.)\n");
4161 } else {
4162 PgenErrPrintNV(reterr, variant_uidx);
4163 }
4164 return reterr;
4165 }
4166 if (missing_present) {
4167 SetBit(variant_uidx, variant_include_has_missing);
4168 }
4169 const uintptr_t incr = allele_idx_stop - incomplete_allele_idx;
4170 normed_vmaj_iter = &(normed_vmaj_iter[incr * sample_ct]);
4171 allele_bidx += incr;
4172 if (allele_idx_stop == allele_idx_end) {
4173 if (++variant_idx == variant_ct) {
4174 *cur_batch_sizep = allele_bidx;
4175 break;
4176 }
4177 incomplete_allele_idx = 0;
4178 } else {
4179 incomplete_allele_idx = allele_idx_stop;
4180 }
4181 }
4182 *variant_idxp = variant_idx;
4183 *variant_uidxp = variant_uidx + (incomplete_allele_idx == 0);
4184 *allele_idx_basep = allele_idx_base;
4185 *cur_allele_ctp = cur_allele_ct;
4186 *incomplete_allele_idxp = incomplete_allele_idx;
4187 return kPglRetSuccess;
4188 }
4189
4190 CONSTI32(kGrmVariantBlockSize, 144);
4191
4192 typedef struct CalcGrmPartCtxStruct {
4193 uint32_t* thread_start;
4194 uint32_t sample_ct;
4195
4196 uint32_t cur_batch_size;
4197 double* normed_dosage_vmaj_bufs[2];
4198 double* normed_dosage_smaj_bufs[2];
4199
4200 double* grm;
4201 } CalcGrmPartCtx;
4202
4203 // turns out dsyrk_ does exactly what we want here
4204 THREAD_FUNC_DECL CalcGrmThread(void* raw_arg) {
4205 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
4206 assert(!arg->tidx);
4207 CalcGrmPartCtx* ctx = S_CAST(CalcGrmPartCtx*, arg->sharedp->context);
4208 const uint32_t sample_ct = ctx->sample_ct;
4209 double* grm = ctx->grm;
4210 uint32_t parity = 0;
4211 do {
4212 const uint32_t cur_batch_size = ctx->cur_batch_size;
4213 if (cur_batch_size) {
4214 TransposeMultiplySelfIncr(ctx->normed_dosage_vmaj_bufs[parity], sample_ct, cur_batch_size, grm);
4215 }
4216 parity = 1 - parity;
4217 } while (!THREAD_BLOCK_FINISH(arg));
4218 THREAD_RETURN;
4219 }
4220
4221 // can't use dsyrk_, so we manually partition the GRM piece we need to compute
4222 // into an appropriate number of sub-pieces
4223 THREAD_FUNC_DECL CalcGrmPartThread(void* raw_arg) {
4224 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
4225 const uintptr_t tidx = arg->tidx;
4226 CalcGrmPartCtx* ctx = S_CAST(CalcGrmPartCtx*, arg->sharedp->context);
4227
4228 const uintptr_t sample_ct = ctx->sample_ct;
4229 const uintptr_t first_thread_row_start_idx = ctx->thread_start[0];
4230 const uintptr_t row_start_idx = ctx->thread_start[tidx];
4231 const uintptr_t sample_idx_end = ctx->thread_start[tidx + 1];
4232 const uintptr_t row_ct = sample_idx_end - row_start_idx;
4233 double* grm_piece = &(ctx->grm[(row_start_idx - first_thread_row_start_idx) * sample_ct]);
4234 uint32_t parity = 0;
4235 do {
4236 const uintptr_t cur_batch_size = ctx->cur_batch_size;
4237 if (cur_batch_size) {
4238 double* normed_vmaj = ctx->normed_dosage_vmaj_bufs[parity];
4239 double* normed_smaj = ctx->normed_dosage_smaj_bufs[parity];
4240 // quasi-bugfix (18 Mar 2022): forgot to skip extra right-side columns
4241 RowMajorMatrixMultiplyStridedIncr(&(normed_smaj[row_start_idx * cur_batch_size]), normed_vmaj, row_ct, cur_batch_size, sample_idx_end, sample_ct, cur_batch_size, sample_ct, grm_piece);
4242 }
4243 parity = 1 - parity;
4244 } while (!THREAD_BLOCK_FINISH(arg));
4245 THREAD_RETURN;
4246 }
4247
4248 CONSTI32(kDblMissingBlockWordCt, 128 / kBitsPerWord);
4249 CONSTI32(kDblMissingBlockSize, 128);
4250
4251 typedef struct CalcDblMissingCtxStruct {
4252 uint32_t* thread_start;
4253 // missing_nz bit is set iff that sample has at least one missing entry in
4254 // current block
4255 uintptr_t* missing_nz[2];
4256 uintptr_t* missing_smaj[2];
4257 uint32_t* missing_dbl_exclude_cts;
4258 } CalcDblMissingCtx;
4259
4260 THREAD_FUNC_DECL CalcDblMissingThread(void* raw_arg) {
4261 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
4262 const uintptr_t tidx = arg->tidx;
4263 CalcDblMissingCtx* ctx = S_CAST(CalcDblMissingCtx*, arg->sharedp->context);
4264
4265 const uint64_t first_thread_row_start_idx = ctx->thread_start[0];
4266 const uint64_t dbl_exclude_offset = (first_thread_row_start_idx * (first_thread_row_start_idx - 1)) / 2;
4267 const uint32_t row_start_idx = ctx->thread_start[tidx];
4268 const uintptr_t row_end_idx = ctx->thread_start[tidx + 1];
4269 uint32_t* missing_dbl_exclude_cts = ctx->missing_dbl_exclude_cts;
4270 uint32_t parity = 0;
4271 do {
4272 const uintptr_t* missing_nz = ctx->missing_nz[parity];
4273 const uintptr_t* missing_smaj = ctx->missing_smaj[parity];
4274 const uint32_t first_idx = AdvBoundedTo1Bit(missing_nz, 0, row_end_idx);
4275 uint32_t sample_idx = first_idx;
4276 uint32_t prev_missing_nz_ct = 0;
4277 if (sample_idx < row_start_idx) {
4278 sample_idx = AdvBoundedTo1Bit(missing_nz, row_start_idx, row_end_idx);
4279 if (sample_idx != row_end_idx) {
4280 prev_missing_nz_ct = PopcountBitRange(missing_nz, 0, row_start_idx);
4281 }
4282 }
4283 while (sample_idx < row_end_idx) {
4284 // todo: compare this explicit unroll with ordinary iteration over a
4285 // cur_words[] array
4286 // todo: try 1 word at a time, and 30 words at a time
4287 const uintptr_t cur_word0 = missing_smaj[sample_idx * kDblMissingBlockWordCt];
4288 const uintptr_t cur_word1 = missing_smaj[sample_idx * kDblMissingBlockWordCt + 1];
4289 #ifndef __LP64__
4290 const uintptr_t cur_word2 = missing_smaj[sample_idx * kDblMissingBlockWordCt + 2];
4291 const uintptr_t cur_word3 = missing_smaj[sample_idx * kDblMissingBlockWordCt + 3];
4292 #endif
4293 uintptr_t sample_idx2_base;
4294 uintptr_t cur_bits;
4295 BitIter1Start(missing_nz, first_idx, &sample_idx2_base, &cur_bits);
4296 // (sample_idx - 1) underflow ok
4297 uint32_t* write_base = &(missing_dbl_exclude_cts[((S_CAST(uint64_t, sample_idx) * (sample_idx - 1)) / 2) - dbl_exclude_offset]);
4298 for (uint32_t uii = 0; uii != prev_missing_nz_ct; ++uii) {
4299 const uint32_t sample_idx2 = BitIter1(missing_nz, &sample_idx2_base, &cur_bits);
4300 const uintptr_t* cur_missing_smaj_base = &(missing_smaj[sample_idx2 * kDblMissingBlockWordCt]);
4301 const uintptr_t cur_and0 = cur_word0 & cur_missing_smaj_base[0];
4302 const uintptr_t cur_and1 = cur_word1 & cur_missing_smaj_base[1];
4303 #ifdef __LP64__
4304 if (cur_and0 || cur_and1) {
4305 write_base[sample_idx2] += Popcount2Words(cur_and0, cur_and1);
4306 }
4307 #else
4308 const uintptr_t cur_and2 = cur_word2 & cur_missing_smaj_base[2];
4309 const uintptr_t cur_and3 = cur_word3 & cur_missing_smaj_base[3];
4310 if (cur_and0 || cur_and1 || cur_and2 || cur_and3) {
4311 write_base[sample_idx2] += Popcount4Words(cur_and0, cur_and1, cur_and2, cur_and3);
4312 }
4313 #endif
4314 }
4315 ++prev_missing_nz_ct;
4316 sample_idx = AdvBoundedTo1Bit(missing_nz, sample_idx + 1, row_end_idx);
4317 }
4318 parity = 1 - parity;
4319 } while (!THREAD_BLOCK_FINISH(arg));
4320 THREAD_RETURN;
4321 }
4322
4323 PglErr CalcMissingMatrix(const uintptr_t* sample_include, const uint32_t* sample_include_cumulative_popcounts, const uintptr_t* variant_include, uint32_t sample_ct, uint32_t variant_ct, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t row_start_idx, uintptr_t row_end_idx, uint32_t max_thread_ct, PgenReader* simple_pgrp, uint32_t** missing_cts_ptr, uint32_t** missing_dbl_exclude_cts_ptr) {
4324 unsigned char* bigstack_mark = g_bigstack_base;
4325 ThreadGroup tg;
4326 PreinitThreads(&tg);
4327 PglErr reterr = kPglRetSuccess;
4328 {
4329 const uintptr_t row_end_idxl = BitCtToWordCt(row_end_idx);
4330 // bugfix (1 Oct 2017): missing_vmaj rows must be vector-aligned
4331 const uintptr_t row_end_idxaw = BitCtToAlignedWordCt(row_end_idx);
4332 uintptr_t* missing_vmaj = nullptr;
4333 uintptr_t* genovec_buf = nullptr;
4334 CalcDblMissingCtx ctx;
4335 if (unlikely(bigstack_calloc_u32(row_end_idx, missing_cts_ptr) ||
4336 bigstack_calloc_u32((S_CAST(uint64_t, row_end_idx) * (row_end_idx - 1) - S_CAST(uint64_t, row_start_idx) * (row_start_idx - 1)) / 2, missing_dbl_exclude_cts_ptr) ||
4337 bigstack_calloc_w(row_end_idxl, &ctx.missing_nz[0]) ||
4338 bigstack_calloc_w(row_end_idxl, &ctx.missing_nz[1]) ||
4339 bigstack_alloc_w(NypCtToWordCt(row_end_idx), &genovec_buf) ||
4340 bigstack_alloc_w(row_end_idxaw * (k1LU * kDblMissingBlockSize), &missing_vmaj) ||
4341 bigstack_alloc_w(RoundUpPow2(row_end_idx, 2) * kDblMissingBlockWordCt, &ctx.missing_smaj[0]) ||
4342 bigstack_alloc_w(RoundUpPow2(row_end_idx, 2) * kDblMissingBlockWordCt, &ctx.missing_smaj[1]))) {
4343 goto CalcMissingMatrix_ret_NOMEM;
4344 }
4345 uint32_t* missing_cts = *missing_cts_ptr;
4346 uint32_t* missing_dbl_exclude_cts = *missing_dbl_exclude_cts_ptr;
4347 ctx.missing_dbl_exclude_cts = missing_dbl_exclude_cts;
4348 VecW* transpose_bitblock_wkspace = S_CAST(VecW*, bigstack_alloc_raw(kPglBitTransposeBufbytes));
4349 uint32_t calc_thread_ct = (max_thread_ct > 8)? (max_thread_ct - 1) : max_thread_ct;
4350 if (unlikely(SetThreadCt(calc_thread_ct, &tg) ||
4351 bigstack_alloc_u32(calc_thread_ct + 1, &ctx.thread_start))) {
4352 goto CalcMissingMatrix_ret_NOMEM;
4353 }
4354 // note that this ctx.thread_start[] may have different values than the one
4355 // computed by CalcGrm(), since calc_thread_ct changes in the MTBLAS and
4356 // OS X cases.
4357 TriangleFill(sample_ct, calc_thread_ct, parallel_idx, parallel_tot, 0, 1, ctx.thread_start);
4358 assert(ctx.thread_start[0] == row_start_idx);
4359 assert(ctx.thread_start[calc_thread_ct] == row_end_idx);
4360 SetThreadFuncAndData(CalcDblMissingThread, &ctx, &tg);
4361 const uint32_t sample_transpose_batch_ct_m1 = (row_end_idx - 1) / kPglBitTransposeBatch;
4362
4363 uintptr_t variant_uidx_base = 0;
4364 uintptr_t cur_bits = variant_include[0];
4365 uint32_t parity = 0;
4366 uint32_t pct = 0;
4367 uint32_t next_print_variant_idx = variant_ct / 100;
4368 // caller's responsibility to print this
4369 // logputs("Correcting for missingness: ");
4370 fputs("0%", stdout);
4371 fflush(stdout);
4372 PgrSampleSubsetIndex pssi;
4373 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
4374 for (uint32_t cur_variant_idx_start = 0; ; ) {
4375 uint32_t cur_batch_size = 0;
4376 if (!IsLastBlock(&tg)) {
4377 cur_batch_size = kDblMissingBlockSize;
4378 uint32_t cur_variant_idx_end = cur_variant_idx_start + cur_batch_size;
4379 if (cur_variant_idx_end > variant_ct) {
4380 cur_batch_size = variant_ct - cur_variant_idx_start;
4381 cur_variant_idx_end = variant_ct;
4382 ZeroWArr((kDblMissingBlockSize - cur_batch_size) * row_end_idxaw, &(missing_vmaj[cur_batch_size * row_end_idxaw]));
4383 }
4384 uintptr_t* missing_vmaj_iter = missing_vmaj;
4385 for (uint32_t variant_idx = cur_variant_idx_start; variant_idx != cur_variant_idx_end; ++variant_idx) {
4386 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
4387 reterr = PgrGetMissingnessD(sample_include, pssi, row_end_idx, variant_uidx, simple_pgrp, nullptr, missing_vmaj_iter, nullptr, genovec_buf);
4388 if (unlikely(reterr)) {
4389 PgenErrPrintNV(reterr, variant_uidx);
4390 goto CalcMissingMatrix_ret_1;
4391 }
4392 missing_vmaj_iter = &(missing_vmaj_iter[row_end_idxaw]);
4393 }
4394 uintptr_t* cur_missing_smaj_iter = ctx.missing_smaj[parity];
4395 uint32_t sample_batch_size = kPglBitTransposeBatch;
4396 for (uint32_t sample_transpose_batch_idx = 0; ; ++sample_transpose_batch_idx) {
4397 if (sample_transpose_batch_idx >= sample_transpose_batch_ct_m1) {
4398 if (sample_transpose_batch_idx > sample_transpose_batch_ct_m1) {
4399 break;
4400 }
4401 sample_batch_size = ModNz(row_end_idx, kPglBitTransposeBatch);
4402 }
4403 // missing_smaj offset needs to be 64-bit if kDblMissingBlockWordCt
4404 // increases
4405 TransposeBitblock(&(missing_vmaj[sample_transpose_batch_idx * kPglBitTransposeWords]), row_end_idxaw, kDblMissingBlockWordCt, kDblMissingBlockSize, sample_batch_size, &(cur_missing_smaj_iter[sample_transpose_batch_idx * kPglBitTransposeBatch * kDblMissingBlockWordCt]), transpose_bitblock_wkspace);
4406 }
4407 uintptr_t* cur_missing_nz = ctx.missing_nz[parity];
4408 ZeroWArr(row_end_idxl, cur_missing_nz);
4409 for (uint32_t sample_idx = 0; sample_idx != row_end_idx; ++sample_idx) {
4410 const uintptr_t cur_word0 = *cur_missing_smaj_iter++;
4411 const uintptr_t cur_word1 = *cur_missing_smaj_iter++;
4412 #ifdef __LP64__
4413 if (cur_word0 || cur_word1) {
4414 SetBit(sample_idx, cur_missing_nz);
4415 missing_cts[sample_idx] += Popcount2Words(cur_word0, cur_word1);
4416 }
4417 #else
4418 const uintptr_t cur_word2 = *cur_missing_smaj_iter++;
4419 const uintptr_t cur_word3 = *cur_missing_smaj_iter++;
4420 if (cur_word0 || cur_word1 || cur_word2 || cur_word3) {
4421 SetBit(sample_idx, cur_missing_nz);
4422 missing_cts[sample_idx] += Popcount4Words(cur_word0, cur_word1, cur_word2, cur_word3);
4423 }
4424 #endif
4425 }
4426 }
4427 if (cur_variant_idx_start) {
4428 JoinThreads(&tg);
4429 // CalcDblMissingThread() never errors out
4430 if (IsLastBlock(&tg)) {
4431 break;
4432 }
4433 if (cur_variant_idx_start >= next_print_variant_idx) {
4434 if (pct > 10) {
4435 putc_unlocked('\b', stdout);
4436 }
4437 pct = (cur_variant_idx_start * 100LLU) / variant_ct;
4438 printf("\b\b%u%%", pct++);
4439 fflush(stdout);
4440 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
4441 }
4442 }
4443 if (cur_variant_idx_start + cur_batch_size == variant_ct) {
4444 DeclareLastThreadBlock(&tg);
4445 }
4446 if (unlikely(SpawnThreads(&tg))) {
4447 goto CalcMissingMatrix_ret_THREAD_CREATE_FAIL;
4448 }
4449 cur_variant_idx_start += cur_batch_size;
4450 parity = 1 - parity;
4451 }
4452 if (pct > 10) {
4453 putc_unlocked('\b', stdout);
4454 }
4455 fputs("\b\b", stdout);
4456 logputs("done.\n");
4457 bigstack_mark = R_CAST(unsigned char*, ctx.missing_nz[0]);
4458 }
4459 while (0) {
4460 CalcMissingMatrix_ret_NOMEM:
4461 reterr = kPglRetNomem;
4462 break;
4463 CalcMissingMatrix_ret_THREAD_CREATE_FAIL:
4464 reterr = kPglRetThreadCreateFail;
4465 break;
4466 }
4467 CalcMissingMatrix_ret_1:
4468 CleanupThreads(&tg);
4469 BigstackReset(bigstack_mark);
4470 return reterr;
4471 }
4472
4473 PglErr CalcGrm(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const double* allele_freqs, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, GrmFlags grm_flags, uint32_t parallel_idx, uint32_t parallel_tot, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end, double** grm_ptr) {
4474 unsigned char* bigstack_mark = g_bigstack_base;
4475 unsigned char* bigstack_end_mark = g_bigstack_end;
4476 FILE* outfile = nullptr;
4477 char* cswritep = nullptr;
4478 CompressStreamState css;
4479 ThreadGroup tg;
4480 PglErr reterr = kPglRetSuccess;
4481 PreinitCstream(&css);
4482 PreinitThreads(&tg);
4483 {
4484 assert(variant_ct);
4485 #if defined(__APPLE__) || defined(USE_MTBLAS)
4486 uint32_t calc_thread_ct = 1;
4487 #else
4488 uint32_t calc_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
4489 if (calc_thread_ct * parallel_tot > sample_ct / 32) {
4490 calc_thread_ct = sample_ct / (32 * parallel_tot);
4491 if (!calc_thread_ct) {
4492 calc_thread_ct = 1;
4493 }
4494 }
4495 #endif
4496 if (unlikely(sample_ct < 2)) {
4497 logerrputs("Error: GRM construction requires at least two samples.\n");
4498 goto CalcGrm_ret_DEGENERATE_DATA;
4499 }
4500 const uintptr_t* sample_include = orig_sample_include;
4501 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
4502 uint32_t row_start_idx = 0;
4503 uintptr_t row_end_idx = sample_ct;
4504 uint32_t* thread_start = nullptr;
4505 if ((calc_thread_ct != 1) || (parallel_tot != 1)) {
4506 // note that grm should be allocated on bottom if no --parallel, since it
4507 // may continue to be used after function exit. So we allocate this on
4508 // top.
4509 if (unlikely(bigstack_end_alloc_u32(calc_thread_ct + 1, &thread_start))) {
4510 goto CalcGrm_ret_NOMEM;
4511 }
4512 // slightly different from plink 1.9 since we don't bother to treat the
4513 // diagonal as a special case any more.
4514 TriangleFill2(sample_ct, calc_thread_ct, parallel_idx, parallel_tot, 0, thread_start);
4515 row_start_idx = thread_start[0];
4516 row_end_idx = thread_start[calc_thread_ct];
4517 if (row_end_idx < sample_ct) {
4518 // 0
4519 // 0 0
4520 // 0 0 0
4521 // 0 0 0 0
4522 // 1 1 1 1 1
4523 // 1 1 1 1 1 1
4524 // 2 2 2 2 2 2 2
4525 // 2 2 2 2 2 2 2 2
4526 // If we're computing part 0, we never need to load the last 4 samples;
4527 // if part 1, we don't need the last two; etc.
4528 uintptr_t* new_sample_include;
4529 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &new_sample_include))) {
4530 goto CalcGrm_ret_NOMEM;
4531 }
4532 const uint32_t sample_uidx_end = 1 + IdxToUidxBasic(orig_sample_include, row_end_idx - 1);
4533 memcpy(new_sample_include, orig_sample_include, RoundUpPow2(sample_uidx_end, kBitsPerWord) / CHAR_BIT);
4534 ClearBitsNz(sample_uidx_end, raw_sample_ctl * kBitsPerWord, new_sample_include);
4535 sample_include = new_sample_include;
4536 }
4537 if ((!parallel_idx) && (calc_thread_ct == 1)) {
4538 thread_start = nullptr;
4539 }
4540 }
4541
4542 CalcGrmPartCtx ctx;
4543 ctx.thread_start = thread_start;
4544 double* grm;
4545 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
4546 goto CalcGrm_ret_NOMEM;
4547 }
4548 if (unlikely(bigstack_calloc64_d(S_CAST(uint64_t, row_end_idx - row_start_idx) * row_end_idx, &grm))) {
4549 if (!grm_ptr) {
4550 logerrputs("Error: Out of memory. If you are SURE you are performing the right matrix\ncomputation, you can split it into smaller pieces with --parallel, and then\nconcatenate the results. But before you try this, make sure the program you're\nproviding the matrix to can actually handle such a large input file.\n");
4551 } else {
4552 // Need to edit this if there are ever non-PCA ways to get here.
4553 if (!(grm_flags & (kfGrmMatrixShapemask | kfGrmListmask | kfGrmBin))) {
4554 logerrputs("Error: Out of memory. Consider \"--pca approx\" instead.\n");
4555 } else {
4556 logerrputs("Error: Out of memory. Consider \"--pca approx\" (and not writing the GRM to\ndisk) instead.\n");
4557 }
4558 }
4559 goto CalcGrm_ret_NOMEM_CUSTOM;
4560 }
4561 ctx.sample_ct = row_end_idx;
4562 ctx.grm = grm;
4563 uint32_t* sample_include_cumulative_popcounts;
4564 PgenVariant pgv;
4565 double* allele_1copy_buf;
4566 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
4567 BigstackAllocPgv(row_end_idx, allele_idx_offsets != nullptr, PgrGetGflags(simple_pgrp), &pgv) ||
4568 bigstack_alloc_d(max_allele_ct, &allele_1copy_buf))) {
4569 goto CalcGrm_ret_NOMEM;
4570 }
4571 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
4572 reterr = ConditionalAllocateNonAutosomalVariants(cip, "GRM construction", raw_variant_ct, &variant_include, &variant_ct);
4573 if (unlikely(reterr)) {
4574 goto CalcGrm_ret_1;
4575 }
4576 if (unlikely(bigstack_alloc_d(row_end_idx * kGrmVariantBlockSize, &ctx.normed_dosage_vmaj_bufs[0]) ||
4577 bigstack_alloc_d(row_end_idx * kGrmVariantBlockSize, &ctx.normed_dosage_vmaj_bufs[1]))) {
4578 goto CalcGrm_ret_NOMEM;
4579 }
4580 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
4581 uintptr_t* variant_include_has_missing = nullptr;
4582 if (!(grm_flags & kfGrmMeanimpute)) {
4583 if (unlikely(bigstack_calloc_w(raw_variant_ctl, &variant_include_has_missing))) {
4584 goto CalcGrm_ret_NOMEM;
4585 }
4586 }
4587 if (thread_start) {
4588 if (unlikely(bigstack_alloc_d(row_end_idx * kGrmVariantBlockSize, &ctx.normed_dosage_smaj_bufs[0]) ||
4589 bigstack_alloc_d(row_end_idx * kGrmVariantBlockSize, &ctx.normed_dosage_smaj_bufs[1]))) {
4590 goto CalcGrm_ret_NOMEM;
4591 }
4592 SetThreadFuncAndData(CalcGrmPartThread, &ctx, &tg);
4593 } else {
4594 // defensive
4595 ctx.normed_dosage_smaj_bufs[0] = nullptr;
4596 ctx.normed_dosage_smaj_bufs[1] = nullptr;
4597 SetThreadFuncAndData(CalcGrmThread, &ctx, &tg);
4598 }
4599 #ifdef USE_MTBLAS
4600 const uint32_t blas_thread_ct = (max_thread_ct > 2)? (max_thread_ct - 1) : max_thread_ct;
4601 BLAS_SET_NUM_THREADS(blas_thread_ct);
4602 #endif
4603 // Main workflow:
4604 // 1. Set n=0, load batch 0
4605 //
4606 // 2. Spawn threads processing batch n
4607 // 3. Increment n by 1
4608 // 4. Load batch n unless eof
4609 // 5. Join threads
4610 // 6. Goto step 2 unless eof
4611 const uint32_t variance_standardize = !(grm_flags & kfGrmCov);
4612 const uint32_t is_haploid = cip->haploid_mask[0] & 1;
4613 uint32_t cur_batch_size = kGrmVariantBlockSize;
4614 uint32_t variant_idx_start = 0;
4615 uint32_t variant_idx = 0;
4616 uintptr_t variant_uidx = 0;
4617 uintptr_t allele_idx_base = 0;
4618 uint32_t cur_allele_ct = 2;
4619 uint32_t incomplete_allele_idx = 0;
4620 uint32_t parity = 0;
4621 uint32_t is_not_first_block = 0;
4622 uint32_t pct = 0;
4623 uint32_t next_print_variant_idx = variant_ct / 100;
4624 logputs("Constructing GRM: ");
4625 fputs("0%", stdout);
4626 fflush(stdout);
4627 PgrSampleSubsetIndex pssi;
4628 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
4629 while (1) {
4630 if (!IsLastBlock(&tg)) {
4631 double* normed_vmaj = ctx.normed_dosage_vmaj_bufs[parity];
4632 reterr = LoadCenteredVarmajBlock(sample_include, pssi, variant_include, allele_idx_offsets, allele_freqs, variance_standardize, is_haploid, row_end_idx, variant_ct, simple_pgrp, normed_vmaj, variant_include_has_missing, &cur_batch_size, &variant_idx, &variant_uidx, &allele_idx_base, &cur_allele_ct, &incomplete_allele_idx, &pgv, allele_1copy_buf);
4633 if (unlikely(reterr)) {
4634 goto CalcGrm_ret_1;
4635 }
4636 if (thread_start) {
4637 MatrixTransposeCopy(normed_vmaj, cur_batch_size, row_end_idx, ctx.normed_dosage_smaj_bufs[parity]);
4638 }
4639 }
4640 if (is_not_first_block) {
4641 JoinThreads(&tg);
4642 // CalcGrmPartThread() and CalcGrmThread() never error out
4643 if (IsLastBlock(&tg)) {
4644 break;
4645 }
4646 if (variant_idx_start >= next_print_variant_idx) {
4647 if (pct > 10) {
4648 putc_unlocked('\b', stdout);
4649 }
4650 pct = (variant_idx_start * 100LLU) / variant_ct;
4651 printf("\b\b%u%%", pct++);
4652 fflush(stdout);
4653 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
4654 }
4655 }
4656 ctx.cur_batch_size = cur_batch_size;
4657 if (variant_idx == variant_ct) {
4658 DeclareLastThreadBlock(&tg);
4659 cur_batch_size = 0;
4660 }
4661 if (unlikely(SpawnThreads(&tg))) {
4662 goto CalcGrm_ret_THREAD_CREATE_FAIL;
4663 }
4664 is_not_first_block = 1;
4665 variant_idx_start = variant_idx;
4666 parity = 1 - parity;
4667 }
4668 BLAS_SET_NUM_THREADS(1);
4669 if (pct > 10) {
4670 putc_unlocked('\b', stdout);
4671 }
4672 fputs("\b\b", stdout);
4673 logputs("done.\n");
4674 uint32_t* missing_cts = nullptr; // stays null iff meanimpute
4675 uint32_t* missing_dbl_exclude_cts = nullptr;
4676 if (variant_include_has_missing) {
4677 const uint32_t variant_ct_with_missing = PopcountWords(variant_include_has_missing, raw_variant_ctl);
4678 // if no missing calls at all, act as if meanimpute was on
4679 if (variant_ct_with_missing) {
4680 logputs("Correcting for missingness... ");
4681 reterr = CalcMissingMatrix(sample_include, sample_include_cumulative_popcounts, variant_include_has_missing, sample_ct, variant_ct_with_missing, parallel_idx, parallel_tot, row_start_idx, row_end_idx, max_thread_ct, simple_pgrp, &missing_cts, &missing_dbl_exclude_cts);
4682 if (unlikely(reterr)) {
4683 goto CalcGrm_ret_1;
4684 }
4685 }
4686 }
4687 if (missing_cts) {
4688 // could parallelize this loop if it ever matters
4689 const uint32_t* missing_dbl_exclude_iter = missing_dbl_exclude_cts;
4690 for (uintptr_t row_idx = row_start_idx; row_idx != row_end_idx; ++row_idx) {
4691 const uint32_t variant_ct_base = variant_ct - missing_cts[row_idx];
4692 double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4693 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
4694 *grm_iter++ /= u31tod(variant_ct_base - missing_cts[col_idx] + (*missing_dbl_exclude_iter++));
4695 }
4696 *grm_iter++ /= u31tod(variant_ct_base);
4697 }
4698 } else {
4699 const double variant_ct_recip = 1.0 / u31tod(variant_ct);
4700 for (uintptr_t row_idx = row_start_idx; row_idx != row_end_idx; ++row_idx) {
4701 double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4702 for (uint32_t col_idx = 0; col_idx <= row_idx; ++col_idx) {
4703 *grm_iter++ *= variant_ct_recip;
4704 }
4705 }
4706 }
4707 // N.B. Only the lower right of grm[] is valid when parallel_tot == 1.
4708
4709 // possible todo: allow simultaneous --make-rel and
4710 // --make-grm-list/--make-grm-bin
4711 // (note that this routine may also be called by --pca, which may not write
4712 // a matrix to disk at all.)
4713 if (grm_flags & (kfGrmMatrixShapemask | kfGrmListmask | kfGrmBin)) {
4714 const GrmFlags matrix_shape = grm_flags & kfGrmMatrixShapemask;
4715 char* log_write_iter;
4716 if (matrix_shape) {
4717 // --make-rel
4718 fputs("--make-rel: Writing...", stdout);
4719 fflush(stdout);
4720 if (grm_flags & kfGrmMatrixBin) {
4721 char* outname_end2 = strcpya_k(outname_end, ".rel.bin");
4722 if (parallel_tot != 1) {
4723 *outname_end2++ = '.';
4724 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4725 }
4726 *outname_end2 = '\0';
4727 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
4728 goto CalcGrm_ret_OPEN_FAIL;
4729 }
4730 double* write_double_buf = nullptr;
4731 if (matrix_shape == kfGrmMatrixSq0) {
4732 write_double_buf = R_CAST(double*, g_textbuf);
4733 ZeroDArr(kTextbufMainSize / sizeof(double), write_double_buf);
4734 } else if (matrix_shape == kfGrmMatrixSq) {
4735 if (unlikely(bigstack_alloc_d(row_end_idx - row_start_idx - 1, &write_double_buf))) {
4736 goto CalcGrm_ret_NOMEM;
4737 }
4738 }
4739 for (uintptr_t row_idx = row_start_idx; ; ) {
4740 const double* grm_row = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4741 ++row_idx;
4742 if (unlikely(fwrite_checked(grm_row, row_idx * sizeof(double), outfile))) {
4743 goto CalcGrm_ret_WRITE_FAIL;
4744 }
4745 if (row_idx == row_end_idx) {
4746 break;
4747 }
4748 if (matrix_shape == kfGrmMatrixSq0) {
4749 uintptr_t zbytes_to_dump = (sample_ct - row_idx) * sizeof(double);
4750 while (zbytes_to_dump >= kTextbufMainSize) {
4751 if (unlikely(fwrite_checked(write_double_buf, kTextbufMainSize, outfile))) {
4752 goto CalcGrm_ret_WRITE_FAIL;
4753 }
4754 zbytes_to_dump -= kTextbufMainSize;
4755 }
4756 if (zbytes_to_dump) {
4757 if (unlikely(fwrite_checked(write_double_buf, zbytes_to_dump, outfile))) {
4758 goto CalcGrm_ret_WRITE_FAIL;
4759 }
4760 }
4761 } else if (matrix_shape == kfGrmMatrixSq) {
4762 double* write_double_iter = write_double_buf;
4763 const double* grm_col = &(grm[row_idx - 1]);
4764 for (uintptr_t row_idx2 = row_idx; row_idx2 != sample_ct; ++row_idx2) {
4765 *write_double_iter++ = grm_col[(row_idx2 - row_start_idx) * sample_ct];
4766 }
4767 if (unlikely(fwrite_checked(write_double_buf, (sample_ct - row_idx) * sizeof(double), outfile))) {
4768 goto CalcGrm_ret_WRITE_FAIL;
4769 }
4770 }
4771 }
4772 if (unlikely(fclose_null(&outfile))) {
4773 goto CalcGrm_ret_WRITE_FAIL;
4774 }
4775 } else if (grm_flags & kfGrmMatrixBin4) {
4776 // downcode all entries to floats
4777 char* outname_end2 = strcpya_k(outname_end, ".rel.bin");
4778 if (parallel_tot != 1) {
4779 *outname_end2++ = '.';
4780 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4781 }
4782 *outname_end2 = '\0';
4783 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
4784 goto CalcGrm_ret_OPEN_FAIL;
4785 }
4786 float* write_float_buf;
4787 if (unlikely(bigstack_alloc_f(row_end_idx, &write_float_buf))) {
4788 goto CalcGrm_ret_NOMEM;
4789 }
4790 uintptr_t row_idx = row_start_idx;
4791 do {
4792 const double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4793 float* write_float_iter = write_float_buf;
4794 for (uint32_t col_idx = 0; col_idx <= row_idx; ++col_idx) {
4795 *write_float_iter++ = S_CAST(float, *grm_iter++);
4796 }
4797 ++row_idx;
4798 if (matrix_shape == kfGrmMatrixSq0) {
4799 ZeroFArr(sample_ct - row_idx, write_float_iter);
4800 write_float_iter = &(write_float_buf[sample_ct]);
4801 } else if (matrix_shape == kfGrmMatrixSq) {
4802 const double* grm_col = &(grm[row_idx - 1]);
4803 for (uintptr_t row_idx2 = row_idx; row_idx2 != sample_ct; ++row_idx2) {
4804 *write_float_iter++ = S_CAST(float, grm_col[(row_idx2 - row_start_idx) * sample_ct]);
4805 }
4806 }
4807 if (unlikely(fwrite_checked(write_float_buf, sizeof(float) * S_CAST(uintptr_t, write_float_iter - write_float_buf), outfile))) {
4808 goto CalcGrm_ret_WRITE_FAIL;
4809 }
4810 } while (row_idx < row_end_idx);
4811 if (unlikely(fclose_null(&outfile))) {
4812 goto CalcGrm_ret_WRITE_FAIL;
4813 }
4814 } else {
4815 char* outname_end2 = strcpya_k(outname_end, ".rel");
4816 if (parallel_tot != 1) {
4817 *outname_end2++ = '.';
4818 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4819 }
4820 const uint32_t output_zst = (grm_flags / kfGrmMatrixZs) & 1;
4821 if (output_zst) {
4822 outname_end2 = strcpya_k(outname_end2, ".zst");
4823 }
4824 *outname_end2 = '\0';
4825 reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, kCompressStreamBlock + 16 * row_end_idx, &css, &cswritep);
4826 if (unlikely(reterr)) {
4827 goto CalcGrm_ret_1;
4828 }
4829 uintptr_t row_idx = row_start_idx;
4830 do {
4831 const double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4832 ++row_idx;
4833 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
4834 cswritep = dtoa_g(*grm_iter++, cswritep);
4835 *cswritep++ = '\t';
4836 }
4837 if (matrix_shape == kfGrmMatrixSq0) {
4838 AppendZerotabsUnsafe(sample_ct - row_idx, &cswritep);
4839 } else if (matrix_shape == kfGrmMatrixSq) {
4840 const double* grm_col = &(grm[row_idx - 1]);
4841 for (uintptr_t row_idx2 = row_idx; row_idx2 != sample_ct; ++row_idx2) {
4842 cswritep = dtoa_g(grm_col[(row_idx2 - row_start_idx) * sample_ct], cswritep);
4843 *cswritep++ = '\t';
4844 }
4845 }
4846 DecrAppendBinaryEoln(&cswritep);
4847 if (unlikely(Cswrite(&css, &cswritep))) {
4848 goto CalcGrm_ret_WRITE_FAIL;
4849 }
4850 } while (row_idx < row_end_idx);
4851 if (unlikely(CswriteCloseNull(&css, cswritep))) {
4852 goto CalcGrm_ret_WRITE_FAIL;
4853 }
4854 }
4855 putc_unlocked('\r', stdout);
4856 log_write_iter = strcpya_k(g_logbuf, "--make-rel: GRM ");
4857 if (parallel_tot != 1) {
4858 log_write_iter = strcpya_k(log_write_iter, "component ");
4859 }
4860 log_write_iter = strcpya_k(log_write_iter, "written to ");
4861 log_write_iter = strcpya(log_write_iter, outname);
4862 } else {
4863 const uint32_t* missing_dbl_exclude_iter = missing_dbl_exclude_cts;
4864 if (grm_flags & kfGrmBin) {
4865 // --make-grm-bin
4866 float* write_float_buf;
4867 if (unlikely(bigstack_alloc_f(row_end_idx, &write_float_buf))) {
4868 goto CalcGrm_ret_NOMEM;
4869 }
4870 char* outname_end2 = strcpya_k(outname_end, ".grm.bin");
4871 if (parallel_tot != 1) {
4872 *outname_end2++ = '.';
4873 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4874 }
4875 *outname_end2 = '\0';
4876 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
4877 goto CalcGrm_ret_OPEN_FAIL;
4878 }
4879 fputs("--make-grm-bin: Writing...", stdout);
4880 fflush(stdout);
4881 for (uintptr_t row_idx = row_start_idx; row_idx != row_end_idx; ++row_idx) {
4882 const double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4883 for (uint32_t col_idx = 0; col_idx <= row_idx; ++col_idx) {
4884 write_float_buf[col_idx] = S_CAST(float, *grm_iter++);
4885 }
4886 if (unlikely(fwrite_checked(write_float_buf, (row_idx + 1) * sizeof(float), outfile))) {
4887 goto CalcGrm_ret_WRITE_FAIL;
4888 }
4889 }
4890 if (unlikely(fclose_null(&outfile))) {
4891 goto CalcGrm_ret_WRITE_FAIL;
4892 }
4893
4894 outname_end2 = strcpya_k(outname_end, ".grm.N.bin");
4895 if (parallel_tot != 1) {
4896 *outname_end2++ = '.';
4897 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4898 }
4899 *outname_end2 = '\0';
4900 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
4901 goto CalcGrm_ret_OPEN_FAIL;
4902 }
4903 if (!missing_cts) {
4904 // trivial case: write the same number repeatedly
4905 const uintptr_t tot_cells = (S_CAST(uint64_t, row_end_idx) * (row_end_idx + 1) - S_CAST(uint64_t, row_start_idx) * (row_start_idx + 1)) / 2;
4906 const float variant_ctf = u31tof(variant_ct);
4907 write_float_buf = R_CAST(float*, g_textbuf);
4908 for (uint32_t uii = 0; uii != (kTextbufMainSize / sizeof(float)); ++uii) {
4909 write_float_buf[uii] = variant_ctf;
4910 }
4911 const uintptr_t full_write_ct = tot_cells / (kTextbufMainSize / sizeof(float));
4912 for (uintptr_t ulii = 0; ulii != full_write_ct; ++ulii) {
4913 if (unlikely(fwrite_checked(write_float_buf, kTextbufMainSize, outfile))) {
4914 goto CalcGrm_ret_WRITE_FAIL;
4915 }
4916 }
4917 const uintptr_t remainder = tot_cells % (kTextbufMainSize / sizeof(float));
4918 if (remainder) {
4919 if (unlikely(fwrite_checked(write_float_buf, remainder * sizeof(float), outfile))) {
4920 goto CalcGrm_ret_WRITE_FAIL;
4921 }
4922 }
4923 } else {
4924 for (uintptr_t row_idx = row_start_idx; row_idx != row_end_idx; ++row_idx) {
4925 const uint32_t variant_ct_base = variant_ct - missing_cts[row_idx];
4926 for (uint32_t col_idx = 0; col_idx <= row_idx; ++col_idx) {
4927 uint32_t cur_obs_ct = variant_ct_base;
4928 if (col_idx != row_idx) {
4929 cur_obs_ct = cur_obs_ct - missing_cts[col_idx] + (*missing_dbl_exclude_iter++);
4930 }
4931 write_float_buf[col_idx] = u31tof(cur_obs_ct);
4932 }
4933 if (unlikely(fwrite_checked(write_float_buf, (row_idx + 1) * sizeof(float), outfile))) {
4934 goto CalcGrm_ret_WRITE_FAIL;
4935 }
4936 }
4937 }
4938 if (unlikely(fclose_null(&outfile))) {
4939 goto CalcGrm_ret_WRITE_FAIL;
4940 }
4941 putc_unlocked('\r', stdout);
4942 const uint32_t outname_copy_byte_ct = 5 + S_CAST(uintptr_t, outname_end - outname);
4943 log_write_iter = strcpya_k(g_logbuf, "--make-grm-bin: GRM ");
4944 if (parallel_tot != 1) {
4945 log_write_iter = strcpya_k(log_write_iter, "component ");
4946 }
4947 log_write_iter = strcpya_k(log_write_iter, "written to ");
4948 log_write_iter = memcpya(log_write_iter, outname, outname_copy_byte_ct);
4949 log_write_iter = strcpya_k(log_write_iter, "bin");
4950 if (parallel_tot != 1) {
4951 *log_write_iter++ = '.';
4952 log_write_iter = u32toa(parallel_idx + 1, log_write_iter);
4953 }
4954 log_write_iter = strcpya_k(log_write_iter, " , ");
4955 if (parallel_idx) {
4956 log_write_iter = strcpya_k(log_write_iter, "and ");
4957 }
4958 log_write_iter = strcpya_k(log_write_iter, "observation counts to ");
4959 log_write_iter = memcpya(log_write_iter, outname, outname_end2 - outname);
4960 } else {
4961 // --make-grm-list
4962 char* outname_end2 = strcpya_k(outname_end, ".grm");
4963 if (parallel_tot != 1) {
4964 *outname_end2++ = '.';
4965 outname_end2 = u32toa(parallel_idx + 1, outname_end2);
4966 }
4967 if (grm_flags & kfGrmListZs) {
4968 outname_end2 = strcpya_k(outname_end2, ".zst");
4969 }
4970 *outname_end2 = '\0';
4971 reterr = InitCstreamAlloc(outname, 0, !(grm_flags & kfGrmListNoGz), max_thread_ct, kCompressStreamBlock + kMaxMediumLine, &css, &cswritep);
4972 if (unlikely(reterr)) {
4973 goto CalcGrm_ret_1;
4974 }
4975 fputs("--make-grm-list: Writing...", stdout);
4976 fflush(stdout);
4977 for (uintptr_t row_idx = row_start_idx; row_idx != row_end_idx; ++row_idx) {
4978 uint32_t variant_ct_base = variant_ct;
4979 if (missing_cts) {
4980 variant_ct_base -= missing_cts[row_idx];
4981 }
4982 const double* grm_iter = &(grm[(row_idx - row_start_idx) * row_end_idx]);
4983 for (uint32_t col_idx = 0; col_idx <= row_idx; ++col_idx) {
4984 cswritep = u32toa_x(row_idx + 1, '\t', cswritep);
4985 cswritep = u32toa_x(col_idx + 1, '\t', cswritep);
4986 if (missing_cts) {
4987 uint32_t cur_obs_ct = variant_ct_base;
4988 if (col_idx != row_idx) {
4989 cur_obs_ct = cur_obs_ct - missing_cts[col_idx] + (*missing_dbl_exclude_iter++);
4990 }
4991 cswritep = u32toa(cur_obs_ct, cswritep);
4992 } else {
4993 cswritep = u32toa(variant_ct_base, cswritep);
4994 }
4995 *cswritep++ = '\t';
4996 cswritep = dtoa_g(*grm_iter++, cswritep);
4997 AppendBinaryEoln(&cswritep);
4998 if (unlikely(Cswrite(&css, &cswritep))) {
4999 goto CalcGrm_ret_WRITE_FAIL;
5000 }
5001 }
5002 }
5003 if (unlikely(CswriteCloseNull(&css, cswritep))) {
5004 goto CalcGrm_ret_WRITE_FAIL;
5005 }
5006 putc_unlocked('\r', stdout);
5007 log_write_iter = strcpya_k(g_logbuf, "--make-grm-list: GRM ");
5008 if (parallel_tot != 1) {
5009 log_write_iter = strcpya_k(log_write_iter, "component ");
5010 }
5011 log_write_iter = strcpya_k(log_write_iter, "written to ");
5012 log_write_iter = strcpya(log_write_iter, outname);
5013 }
5014 }
5015 if (!parallel_idx) {
5016 SampleIdFlags id_print_flags = siip->flags & kfSampleIdFidPresent;
5017 if (grm_flags & kfGrmNoIdHeader) {
5018 id_print_flags |= kfSampleIdNoIdHeader;
5019 if (grm_flags & kfGrmNoIdHeaderIidOnly) {
5020 id_print_flags |= kfSampleIdNoIdHeaderIidOnly;
5021 }
5022 }
5023 snprintf(&(outname_end[4]), kMaxOutfnameExtBlen - 4, ".id");
5024 reterr = WriteSampleIdsOverride(orig_sample_include, siip, outname, sample_ct, id_print_flags);
5025 if (unlikely(reterr)) {
5026 goto CalcGrm_ret_1;
5027 }
5028 log_write_iter = strcpya_k(log_write_iter, " , and IDs to ");
5029 log_write_iter = strcpya(log_write_iter, outname);
5030 }
5031 snprintf(log_write_iter, kLogbufSize - 2 * kPglFnamesize - 256, " .\n");
5032 WordWrapB(0);
5033 logputsb();
5034 }
5035
5036 if (grm_ptr) {
5037 *grm_ptr = grm;
5038 // allocation right on top of grm[]
5039 bigstack_mark = R_CAST(unsigned char*, sample_include_cumulative_popcounts);
5040 }
5041 }
5042 while (0) {
5043 CalcGrm_ret_NOMEM:
5044 reterr = kPglRetNomem;
5045 break;
5046 CalcGrm_ret_NOMEM_CUSTOM:
5047 reterr = kPglRetNomemCustomMsg;
5048 break;
5049 CalcGrm_ret_OPEN_FAIL:
5050 reterr = kPglRetOpenFail;
5051 break;
5052 CalcGrm_ret_WRITE_FAIL:
5053 reterr = kPglRetWriteFail;
5054 break;
5055 CalcGrm_ret_THREAD_CREATE_FAIL:
5056 reterr = kPglRetThreadCreateFail;
5057 break;
5058 CalcGrm_ret_DEGENERATE_DATA:
5059 reterr = kPglRetDegenerateData;
5060 break;
5061 }
5062 CalcGrm_ret_1:
5063 CswriteCloseCond(&css, cswritep);
5064 fclose_cond(outfile);
5065 CleanupThreads(&tg);
5066 BLAS_SET_NUM_THREADS(1);
5067 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
5068 return reterr;
5069 }
5070
5071 // should be able to remove NOLAPACK later since we already have a non-LAPACK
5072 // SVD implementation
5073 #ifndef NOLAPACK
5074 // This seems to be better than 256 (due to avoidance of cache critical
5075 // stride?)
5076 // (still want this to be a multiple of 8, for cleaner multithreading)
5077 // TODO: try to allow run to proceed with a smaller value when 240 induces an
5078 // out-of-memory error. It's cutting it close for UK Biobank. Though we don't
5079 // want to reduce the default value, I've tested that and it degrades
5080 // performance.
5081 CONSTI32(kPcaVariantBlockSize, 240);
5082
5083 typedef struct CalcPcaCtxStruct {
5084 uint32_t sample_ct;
5085 uint32_t pc_ct;
5086
5087 double* yy_bufs[2];
5088
5089 uint32_t cur_batch_size;
5090
5091 double* g1;
5092 double* qq;
5093 double** y_transpose_bufs;
5094 double** g2_bb_part_bufs;
5095 } CalcPcaCtx;
5096
5097 THREAD_FUNC_DECL CalcPcaXtxaThread(void* raw_arg) {
5098 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5099 const uintptr_t tidx = arg->tidx;
5100 CalcPcaCtx* ctx = S_CAST(CalcPcaCtx*, arg->sharedp->context);
5101
5102 const uint32_t sample_ct = ctx->sample_ct;
5103 const uint32_t pc_ct_x2 = ctx->pc_ct * 2;
5104 const uintptr_t qq_col_ct = (ctx->pc_ct + 1) * pc_ct_x2;
5105 const uint32_t vidx_offset = tidx * kPcaVariantBlockSize;
5106 const double* g1 = ctx->g1;
5107 double* qq_iter = ctx->qq;
5108 double* y_transpose_buf = ctx->y_transpose_bufs[tidx];
5109 double* g2_part_buf = ctx->g2_bb_part_bufs[tidx];
5110 uint32_t parity = 0;
5111 do {
5112 const uint32_t cur_batch_size = ctx->cur_batch_size;
5113 if (vidx_offset < cur_batch_size) {
5114 uint32_t cur_thread_batch_size = cur_batch_size - vidx_offset;
5115 if (cur_thread_batch_size > kPcaVariantBlockSize) {
5116 cur_thread_batch_size = kPcaVariantBlockSize;
5117 }
5118 const double* yy_buf = &(ctx->yy_bufs[parity][S_CAST(uintptr_t, vidx_offset) * sample_ct]);
5119 double* cur_qq = &(qq_iter[vidx_offset * qq_col_ct]);
5120 RowMajorMatrixMultiplyStrided(yy_buf, g1, cur_thread_batch_size, sample_ct, pc_ct_x2, pc_ct_x2, sample_ct, qq_col_ct, cur_qq);
5121 MatrixTransposeCopy(yy_buf, cur_thread_batch_size, sample_ct, y_transpose_buf);
5122 RowMajorMatrixMultiplyStridedIncr(y_transpose_buf, cur_qq, sample_ct, cur_thread_batch_size, pc_ct_x2, qq_col_ct, cur_thread_batch_size, pc_ct_x2, g2_part_buf);
5123 qq_iter = &(qq_iter[cur_batch_size * qq_col_ct]);
5124 }
5125 parity = 1 - parity;
5126 } while (!THREAD_BLOCK_FINISH(arg));
5127 THREAD_RETURN;
5128 }
5129
5130 THREAD_FUNC_DECL CalcPcaXaThread(void* raw_arg) {
5131 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5132 const uintptr_t tidx = arg->tidx;
5133 CalcPcaCtx* ctx = S_CAST(CalcPcaCtx*, arg->sharedp->context);
5134
5135 const uint32_t sample_ct = ctx->sample_ct;
5136 const uint32_t pc_ct_x2 = ctx->pc_ct * 2;
5137 const uintptr_t qq_col_ct = (ctx->pc_ct + 1) * pc_ct_x2;
5138 const uint32_t vidx_offset = tidx * kPcaVariantBlockSize;
5139 const double* g1 = ctx->g1;
5140 double* qq_iter = ctx->qq;
5141 uint32_t parity = 0;
5142 do {
5143 const uint32_t cur_batch_size = ctx->cur_batch_size;
5144 if (vidx_offset < cur_batch_size) {
5145 uint32_t cur_thread_batch_size = cur_batch_size - vidx_offset;
5146 if (cur_thread_batch_size > kPcaVariantBlockSize) {
5147 cur_thread_batch_size = kPcaVariantBlockSize;
5148 }
5149 const double* yy_buf = &(ctx->yy_bufs[parity][S_CAST(uintptr_t, vidx_offset) * sample_ct]);
5150 double* cur_qq = &(qq_iter[vidx_offset * qq_col_ct]);
5151 RowMajorMatrixMultiplyStrided(yy_buf, g1, cur_thread_batch_size, sample_ct, pc_ct_x2, pc_ct_x2, sample_ct, qq_col_ct, cur_qq);
5152 qq_iter = &(qq_iter[cur_batch_size * qq_col_ct]);
5153 }
5154 parity = 1 - parity;
5155 } while (!THREAD_BLOCK_FINISH(arg));
5156 THREAD_RETURN;
5157 }
5158
5159 THREAD_FUNC_DECL CalcPcaXtbThread(void* raw_arg) {
5160 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5161 const uintptr_t tidx = arg->tidx;
5162 CalcPcaCtx* ctx = S_CAST(CalcPcaCtx*, arg->sharedp->context);
5163
5164 const uint32_t sample_ct = ctx->sample_ct;
5165 const uint32_t pc_ct_x2 = ctx->pc_ct * 2;
5166 const uintptr_t qq_col_ct = (ctx->pc_ct + 1) * pc_ct_x2;
5167 const uint32_t vidx_offset = tidx * kPcaVariantBlockSize;
5168 const double* qq_iter = &(ctx->qq[vidx_offset * qq_col_ct]);
5169 double* y_transpose_buf = ctx->y_transpose_bufs[tidx];
5170 double* bb_part_buf = ctx->g2_bb_part_bufs[tidx];
5171 uint32_t parity = 0;
5172 do {
5173 const uint32_t cur_batch_size = ctx->cur_batch_size;
5174 if (vidx_offset < cur_batch_size) {
5175 uint32_t cur_thread_batch_size = cur_batch_size - vidx_offset;
5176 if (cur_thread_batch_size > kPcaVariantBlockSize) {
5177 cur_thread_batch_size = kPcaVariantBlockSize;
5178 }
5179 const double* yy_buf = &(ctx->yy_bufs[parity][S_CAST(uintptr_t, vidx_offset) * sample_ct]);
5180 MatrixTransposeCopy(yy_buf, cur_thread_batch_size, sample_ct, y_transpose_buf);
5181 RowMajorMatrixMultiplyIncr(y_transpose_buf, qq_iter, sample_ct, qq_col_ct, cur_thread_batch_size, bb_part_buf);
5182 qq_iter = &(qq_iter[cur_batch_size * qq_col_ct]);
5183 }
5184 parity = 1 - parity;
5185 } while (!THREAD_BLOCK_FINISH(arg));
5186 THREAD_RETURN;
5187 }
5188
5189 typedef struct CalcPcaVarWtsCtxStruct {
5190 uint32_t sample_ct;
5191 uint32_t pc_ct;
5192
5193 double* sample_wts_smaj;
5194
5195 double* yy_bufs[2];
5196
5197 uint32_t cur_batch_size;
5198
5199 double* var_wts;
5200 } CalcPcaVarWtsCtx;
5201
5202 THREAD_FUNC_DECL CalcPcaVarWtsThread(void* raw_arg) {
5203 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
5204 const uintptr_t tidx = arg->tidx;
5205 CalcPcaVarWtsCtx* ctx = S_CAST(CalcPcaVarWtsCtx*, arg->sharedp->context);
5206
5207 const uint32_t sample_ct = ctx->sample_ct;
5208 const uint32_t pc_ct = ctx->pc_ct;
5209 const uint32_t vidx_offset = tidx * kPcaVariantBlockSize;
5210
5211 // either first batch size is calc_thread_ct * kPcaVariantBlockSize, or there
5212 // is only one batch
5213 const uintptr_t var_wts_part_size = S_CAST(uintptr_t, pc_ct) * ctx->cur_batch_size;
5214
5215 const double* sample_wts = ctx->sample_wts_smaj; // sample-major, pc_ct columns
5216 uint32_t parity = 0;
5217 do {
5218 const uint32_t cur_batch_size = ctx->cur_batch_size;
5219 if (vidx_offset < cur_batch_size) {
5220 uint32_t cur_thread_batch_size = cur_batch_size - vidx_offset;
5221 if (cur_thread_batch_size > kPcaVariantBlockSize) {
5222 cur_thread_batch_size = kPcaVariantBlockSize;
5223 }
5224 const double* yy_buf = &(ctx->yy_bufs[parity][S_CAST(uintptr_t, vidx_offset) * sample_ct]);
5225 // Variant weight matrix = X^T * S * D^{-1/2}, where X^T is the
5226 // variance-standardized genotype matrix, S is the sample weight matrix,
5227 // and D is a diagonal eigenvalue matrix.
5228 // We postpone the D^{-1/2} part for now, but it's straightforward to
5229 // switch to using precomputed (S * D^{-1/2}).
5230 double* cur_var_wts_part = &(ctx->var_wts[parity * var_wts_part_size + vidx_offset * S_CAST(uintptr_t, pc_ct)]);
5231 RowMajorMatrixMultiply(yy_buf, sample_wts, cur_thread_batch_size, pc_ct, sample_ct, cur_var_wts_part);
5232 }
5233 parity = 1 - parity;
5234 } while (!THREAD_BLOCK_FINISH(arg));
5235 THREAD_RETURN;
5236 }
5237
5238 PglErr FlushBiallelicVarWts(const uintptr_t* 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* nonref_flags, const AlleleCode* maj_alleles, const double* var_wts_iter, const double* eigval_inv_sqrts, uint32_t batch_size, uint32_t pc_ct, PcaFlags pca_flags, uint32_t provref_col, uint32_t all_nonref, CompressStreamState* cssp, char** cswritepp, char* chr_buf, uint32_t* variant_idxp, uintptr_t* variant_uidxp, uint32_t* chr_fo_idxp, uint32_t* chr_endp, uint32_t* chr_buf_blenp) {
5239 char* cswritep = *cswritepp;
5240 uint32_t variant_idx = *variant_idxp;
5241 uintptr_t variant_uidx = *variant_uidxp;
5242 uint32_t chr_fo_idx = *chr_fo_idxp;
5243 uint32_t chr_end = *chr_endp;
5244 uint32_t chr_buf_blen = *chr_buf_blenp;
5245
5246 const uint32_t variant_idx_stop = variant_idx + batch_size;
5247 const uint32_t ref_col = pca_flags & kfPcaVcolRef;
5248 const uint32_t alt1_col = pca_flags & kfPcaVcolAlt1;
5249 const uint32_t alt_col = pca_flags & kfPcaVcolAlt;
5250 const uint32_t maj_col = pca_flags & kfPcaVcolMaj;
5251 const uint32_t nonmaj_col = pca_flags & kfPcaVcolNonmaj;
5252
5253 uintptr_t variant_uidx_base;
5254 uintptr_t cur_bits;
5255 BitIter1Start(variant_include, variant_uidx, &variant_uidx_base, &cur_bits);
5256 for (; variant_idx != variant_idx_stop; ++variant_idx) {
5257 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5258 if (chr_buf) {
5259 // ok to skip this logic if chr_col not printed
5260 if (variant_uidx >= chr_end) {
5261 do {
5262 ++chr_fo_idx;
5263 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5264 } while (variant_uidx >= chr_end);
5265 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
5266 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
5267 *chr_name_end = '\t';
5268 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
5269 }
5270 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
5271 }
5272 if (variant_bps) {
5273 cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
5274 }
5275 cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
5276 uintptr_t allele_idx_offset_base = variant_uidx * 2;
5277 if (allele_idx_offsets) {
5278 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
5279 }
5280 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5281 if (ref_col) {
5282 *cswritep++ = '\t';
5283 cswritep = strcpya(cswritep, cur_alleles[0]);
5284 }
5285 if (alt1_col) {
5286 *cswritep++ = '\t';
5287 cswritep = strcpya(cswritep, cur_alleles[1]);
5288 }
5289 if (alt_col) {
5290 *cswritep++ = '\t';
5291 // guaranteed biallelic
5292 cswritep = strcpya(cswritep, cur_alleles[1]);
5293 }
5294 if (provref_col) {
5295 *cswritep++ = '\t';
5296 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
5297 }
5298 const uint32_t maj_allele_idx = maj_alleles[variant_uidx];
5299 if (maj_col) {
5300 if (unlikely(Cswrite(cssp, &cswritep))) {
5301 return kPglRetWriteFail;
5302 }
5303 *cswritep++ = '\t';
5304 cswritep = strcpya(cswritep, cur_alleles[maj_allele_idx]);
5305 }
5306 if (nonmaj_col) {
5307 *cswritep++ = '\t';
5308 cswritep = strcpya(cswritep, cur_alleles[1 - maj_allele_idx]);
5309 }
5310 if (!maj_allele_idx) {
5311 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5312 *cswritep++ = '\t';
5313 // could avoid these multiplications by premultiplying the
5314 // sample weight matrix
5315 cswritep = dtoa_g((*var_wts_iter++) * eigval_inv_sqrts[pc_idx], cswritep);
5316 }
5317 } else {
5318 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5319 *cswritep++ = '\t';
5320 cswritep = dtoa_g((*var_wts_iter++) * (-eigval_inv_sqrts[pc_idx]), cswritep);
5321 }
5322 }
5323 AppendBinaryEoln(&cswritep);
5324 if (unlikely(Cswrite(cssp, &cswritep))) {
5325 // bugfix (15 Dec 2017): prevent buffer overflow when ALT, MAJ,
5326 // and NONMAJ columns all missing.
5327 return kPglRetWriteFail;
5328 }
5329 }
5330 *cswritepp = cswritep;
5331 *variant_idxp = variant_idx_stop;
5332 *variant_uidxp = variant_uidx + 1;
5333 *chr_fo_idxp = chr_fo_idx;
5334 *chr_endp = chr_end;
5335 *chr_buf_blenp = chr_buf_blen;
5336 return kPglRetSuccess;
5337 }
5338
5339 PglErr FlushAlleleWts(const uintptr_t* 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* nonref_flags, const double* var_wts_iter, const double* eigval_inv_sqrts, uint32_t batch_size, uint32_t pc_ct, PcaFlags pca_flags, uint32_t provref_col, uint32_t all_nonref, CompressStreamState* cssp, char** cswritepp, char* chr_buf, uint32_t* variant_idxp, uintptr_t* variant_uidxp, uintptr_t* allele_idx_offset_basep, uint32_t* cur_allele_ctp, uint32_t* incomplete_allele_idxp, uint32_t* chr_fo_idxp, uint32_t* chr_endp, uint32_t* chr_buf_blenp) {
5340 char* cswritep = *cswritepp;
5341 uint32_t variant_idx = *variant_idxp;
5342 uintptr_t variant_uidx = *variant_uidxp;
5343 uintptr_t allele_idx_offset_base = *allele_idx_offset_basep;
5344 uint32_t cur_allele_ct = *cur_allele_ctp;
5345 uint32_t incomplete_allele_idx = *incomplete_allele_idxp;
5346 uint32_t chr_fo_idx = *chr_fo_idxp;
5347 uint32_t chr_end = *chr_endp;
5348 uint32_t chr_buf_blen = *chr_buf_blenp;
5349
5350 const uint32_t ref_col = pca_flags & kfPcaVcolRef;
5351 const uint32_t alt1_col = pca_flags & kfPcaVcolAlt1;
5352 const uint32_t alt_col = pca_flags & kfPcaVcolAlt;
5353 const uint32_t ax_col = pca_flags & kfPcaVcolAx;
5354
5355 uintptr_t variant_uidx_base;
5356 uintptr_t cur_bits;
5357 BitIter1Start(variant_include, variant_uidx + (incomplete_allele_idx != 0), &variant_uidx_base, &cur_bits);
5358 for (uint32_t allele_bidx = 0; allele_bidx != batch_size; ) {
5359 if (!incomplete_allele_idx) {
5360 variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
5361 if (chr_buf && (variant_uidx >= chr_end)) {
5362 do {
5363 ++chr_fo_idx;
5364 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5365 } while (variant_uidx >= chr_end);
5366 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
5367 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
5368 *chr_name_end = '\t';
5369 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
5370 }
5371 if (!allele_idx_offsets) {
5372 allele_idx_offset_base = variant_uidx * 2;
5373 } else {
5374 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
5375 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
5376 }
5377 }
5378 uint32_t allele_idx_end = cur_allele_ct;
5379 uint32_t allele_idx_stop;
5380 uint32_t incr;
5381 if (cur_allele_ct == 2) {
5382 allele_idx_stop = 2;
5383 incr = 1;
5384 } else {
5385 allele_idx_stop = batch_size + incomplete_allele_idx - allele_bidx;
5386 if (allele_idx_stop > allele_idx_end) {
5387 allele_idx_stop = allele_idx_end;
5388 }
5389 incr = allele_idx_stop - incomplete_allele_idx;
5390 }
5391 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5392 for (uint32_t allele_idx = incomplete_allele_idx; allele_idx != allele_idx_stop; ++allele_idx) {
5393 if (chr_buf) {
5394 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
5395 }
5396 if (variant_bps) {
5397 cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep);
5398 }
5399 cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
5400 if (ref_col) {
5401 *cswritep++ = '\t';
5402 cswritep = strcpya(cswritep, cur_alleles[0]);
5403 }
5404 if (alt1_col) {
5405 *cswritep++ = '\t';
5406 cswritep = strcpya(cswritep, cur_alleles[1]);
5407 }
5408 if (alt_col) {
5409 *cswritep++ = '\t';
5410 for (uint32_t allele_idx2 = 1; allele_idx2 != cur_allele_ct; ++allele_idx2) {
5411 if (unlikely(Cswrite(cssp, &cswritep))) {
5412 return kPglRetWriteFail;
5413 }
5414 cswritep = strcpyax(cswritep, cur_alleles[allele_idx2], ',');
5415 }
5416 --cswritep;
5417 }
5418 if (provref_col) {
5419 *cswritep++ = '\t';
5420 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N';
5421 }
5422 // A1 col always present
5423 if (unlikely(Cswrite(cssp, &cswritep))) {
5424 return kPglRetWriteFail;
5425 }
5426 *cswritep++ = '\t';
5427 cswritep = strcpya(cswritep, cur_alleles[allele_idx]);
5428 if (ax_col) {
5429 *cswritep++ = '\t';
5430 for (uint32_t allele_idx2 = 0; allele_idx2 != cur_allele_ct; ++allele_idx2) {
5431 if (allele_idx2 == allele_idx) {
5432 continue;
5433 }
5434 if (unlikely(Cswrite(cssp, &cswritep))) {
5435 return kPglRetWriteFail;
5436 }
5437 cswritep = strcpyax(cswritep, cur_alleles[allele_idx2], ',');
5438 }
5439 --cswritep;
5440 }
5441 if (cur_allele_ct == 2) {
5442 const double mult = allele_idx? -0.5 : 0.5;
5443 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5444 *cswritep++ = '\t';
5445 cswritep = dtoa_g((*var_wts_iter++) * mult * eigval_inv_sqrts[pc_idx], cswritep);
5446 }
5447 if (!allele_idx) {
5448 var_wts_iter -= pc_ct;
5449 }
5450 } else {
5451 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5452 *cswritep++ = '\t';
5453 cswritep = dtoa_g((*var_wts_iter++) * eigval_inv_sqrts[pc_idx], cswritep);
5454 }
5455 }
5456 AppendBinaryEoln(&cswritep);
5457 if (unlikely(Cswrite(cssp, &cswritep))) {
5458 return kPglRetWriteFail;
5459 }
5460 }
5461 allele_bidx += incr;
5462 if (allele_idx_stop == allele_idx_end) {
5463 ++variant_idx;
5464 incomplete_allele_idx = 0;
5465 } else {
5466 incomplete_allele_idx = allele_idx_stop;
5467 }
5468 }
5469 *cswritepp = cswritep;
5470 *variant_idxp = variant_idx;
5471 *variant_uidxp = variant_uidx + (incomplete_allele_idx == 0);
5472 *allele_idx_offset_basep = allele_idx_offset_base;
5473 *cur_allele_ctp = cur_allele_ct;
5474 *incomplete_allele_idxp = incomplete_allele_idx;
5475 *chr_fo_idxp = chr_fo_idx;
5476 *chr_endp = chr_end;
5477 *chr_buf_blenp = chr_buf_blen;
5478 return kPglRetSuccess;
5479 }
5480
5481 PglErr CalcPca(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* 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 AlleleCode* maj_alleles, const double* allele_freqs, uint32_t raw_sample_ct, uintptr_t pca_sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, uint32_t pc_ct, PcaFlags pca_flags, uint32_t max_thread_ct, PgenReader* simple_pgrp, sfmt_t* sfmtp, double* grm, char* outname, char* outname_end) {
5482 unsigned char* bigstack_mark = g_bigstack_base;
5483 FILE* outfile = nullptr;
5484 char* cswritep = nullptr;
5485 CompressStreamState css;
5486 ThreadGroup tg;
5487 PreinitThreads(&tg);
5488 PglErr reterr = kPglRetSuccess;
5489 PreinitCstream(&css);
5490 {
5491 const uint32_t write_fid = FidColIsRequired(siip, pca_flags / kfPcaScolMaybefid);
5492 const char* sample_ids = siip->sample_ids;
5493 const char* sids = siip->sids;
5494 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
5495 const uintptr_t max_sid_blen = siip->max_sid_blen;
5496 const uint32_t write_sid = SidColIsRequired(sids, pca_flags / kfPcaScolMaybesid);
5497 const uint32_t is_approx = (pca_flags / kfPcaApprox) & 1;
5498 reterr = ConditionalAllocateNonAutosomalVariants(cip, is_approx? "PCA approximation" : "PCA", raw_variant_ct, &variant_include, &variant_ct);
5499 if (unlikely(reterr)) {
5500 goto CalcPca_ret_1;
5501 }
5502 #ifdef __APPLE__
5503 // min OS X version is 10.7, so we can take Grand Central Dispatch dgemm
5504 // for granted
5505 // (tried this with Linux MKL + OpenMP as well, but results were inferior)
5506 uint32_t calc_thread_ct = 1;
5507 #else
5508 // I/O thread generally has <1/8 of workload
5509 // TODO: recheck this, now that I/O thread is also responsible for fully
5510 // expanding dosages. Still shouldn't be a big deal, but we probably want
5511 // sample_ct to affect the decision boundary now.
5512 uint32_t calc_thread_ct = (max_thread_ct > 8)? (max_thread_ct - 1) : max_thread_ct;
5513 if ((calc_thread_ct - 1) * kPcaVariantBlockSize >= variant_ct) {
5514 calc_thread_ct = 1 + (variant_ct - 1) / kPcaVariantBlockSize;
5515 }
5516 #endif
5517 if (unlikely(pc_ct > pca_sample_ct)) {
5518 // minor update (alpha 3): just error out here instead of trying to
5519 // auto-adjust PC count, number of .eigenvec output columns should be
5520 // easily predictable
5521 logerrprintf("Error: Too few samples to compute %u PCs with \"--pca approx\".\n", pc_ct);
5522 goto CalcPca_ret_DEGENERATE_DATA;
5523 }
5524 const uint32_t wts_requested = ((pca_flags & (kfPcaAlleleWts | kfPcaBiallelicVarWts)) != 0);
5525 const uint32_t biallelic_variant_ct = CountBiallelicVariants(variant_include, allele_idx_offsets, variant_ct);
5526 double* cur_var_wts = nullptr;
5527 double* eigval_inv_sqrts = nullptr;
5528 char* chr_buf = nullptr;
5529 uintptr_t overflow_buf_size = 3 * kMaxMediumLine;
5530 if (wts_requested) {
5531 if (pca_flags & kfPcaBiallelicVarWts) {
5532 if (unlikely(biallelic_variant_ct != variant_ct)) {
5533 logerrputs("Error: Multiallelic variant present in \"--pca biallelic-var-wts\" run.\n");
5534 goto CalcPca_ret_INCONSISTENT_INPUT;
5535 }
5536 }
5537 if (unlikely(bigstack_alloc_d(pc_ct, &cur_var_wts) ||
5538 bigstack_alloc_d(pc_ct, &eigval_inv_sqrts))) {
5539 goto CalcPca_ret_NOMEM;
5540 }
5541 uint32_t max_chr_blen = 0;
5542 if (pca_flags & kfPcaVcolChrom) {
5543 max_chr_blen = GetMaxChrSlen(cip) + 1;
5544 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
5545 goto CalcPca_ret_NOMEM;
5546 }
5547 }
5548 const uintptr_t overflow_buf_size2 = RoundUpPow2(kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 2 * max_allele_slen + 32 + 16 * pc_ct, kCacheline);
5549 if (overflow_buf_size2 > overflow_buf_size) {
5550 overflow_buf_size = overflow_buf_size2;
5551 }
5552 }
5553 uintptr_t writebuf_alloc = overflow_buf_size;
5554 if (pca_flags & kfPcaVarZs) {
5555 writebuf_alloc += CstreamWkspaceReq(overflow_buf_size);
5556 }
5557 // temporary
5558 // todo: additional --pca-clusters allocations
5559 const uintptr_t* pca_sample_include = sample_include;
5560 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
5561 uint32_t* pca_sample_include_cumulative_popcounts;
5562 PgenVariant pgv;
5563 double* allele_1copy_buf = nullptr; // spurious g++ 4.8 warning
5564 double* eigvals;
5565 CalcPcaCtx ctx;
5566 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &pca_sample_include_cumulative_popcounts) ||
5567 BigstackAllocPgv(pca_sample_ct, allele_idx_offsets != nullptr, PgrGetGflags(simple_pgrp), &pgv) ||
5568 bigstack_alloc_d(max_allele_ct, &allele_1copy_buf) ||
5569 bigstack_alloc_d(pc_ct, &eigvals) ||
5570 SetThreadCt(calc_thread_ct, &tg))) {
5571 goto CalcPca_ret_NOMEM;
5572 }
5573 FillCumulativePopcounts(pca_sample_include, raw_sample_ctl, pca_sample_include_cumulative_popcounts);
5574 PgrSampleSubsetIndex pssi;
5575 PgrSetSampleSubsetIndex(pca_sample_include_cumulative_popcounts, simple_pgrp, &pssi);
5576 ctx.sample_ct = pca_sample_ct;
5577 ctx.pc_ct = pc_ct;
5578 const uintptr_t pca_row_ct = CountAlleles(variant_include, allele_idx_offsets, raw_variant_ct, variant_ct) - biallelic_variant_ct;
5579 const uint32_t is_haploid = cip->haploid_mask[0] & 1;
5580 uint32_t cur_allele_ct = 2;
5581 double* qq = nullptr;
5582 double* eigvecs_smaj;
5583 char* writebuf;
5584 if (is_approx) {
5585 if (pca_sample_ct <= 5000) {
5586 logerrputs("Warning: \"--pca approx\" is only recommended for analysis of >5000 samples.\n");
5587 }
5588 if (pca_row_ct > 5000000) {
5589 logerrputs("Warning: Use of \"--pca approx\" on >5m rows is not advisable. Apply a MAF\nfilter if you haven't done so yet, and consider LD-pruning your variant set as\nwell.\n");
5590 }
5591 // This is ported from EIGENSOFT 6 src/ksrc/kjg_fpca.c , which is in turn
5592 // primarily based on Halko N, Martinsson P, Shkolnisky Y, Tygert M
5593 // (2011) An Algorithm for the Principal Component Analysis of Large Data
5594 // Sets.
5595 const uintptr_t pc_ct_x2 = pc_ct * 2;
5596 const uintptr_t qq_col_ct = (pc_ct + 1) * pc_ct_x2;
5597 // bugfix (30 Jan 2019): First SvdRectFused() call returns
5598 // min(variant_ct, qq_col_ct) singular vectors; this was previously
5599 // assumed to always be qq_col_ct, and very inaccurate results were
5600 // produced when the assumption wasn't true.
5601 // Simplest solution is to force the user to request fewer PCs, since the
5602 // final PCs wouldn't be accurate anyway.
5603 if (qq_col_ct > variant_ct) {
5604 logerrprintfww("Error: Too few variants to compute %u PCs with \"--pca approx\" (%u required).\n", pc_ct, qq_col_ct);
5605 goto CalcPca_ret_DEGENERATE_DATA;
5606 }
5607 #ifndef LAPACK_ILP64
5608 if (unlikely((pca_row_ct * S_CAST(uint64_t, qq_col_ct)) > 0x7effffff)) {
5609 logerrputs("Error: \"--pca approx\" problem instance too large for this " PROG_NAME_STR " build. If\nthis is really the computation you want, use a " PROG_NAME_STR " build with large-matrix\nsupport.\n");
5610 goto CalcPca_ret_INCONSISTENT_INPUT;
5611 }
5612 #endif
5613 const double variant_ct_recip = 1.0 / u31tod(variant_ct);
5614
5615 const uintptr_t gg_size = pca_sample_ct * pc_ct_x2;
5616 __CLPK_integer svd_rect_lwork;
5617 #ifdef LAPACK_ILP64
5618 GetSvdRectLwork(MAXV(pca_sample_ct, pca_row_ct), qq_col_ct, &svd_rect_lwork);
5619 #else
5620 if (unlikely(GetSvdRectLwork(MAXV(pca_sample_ct, pca_row_ct), qq_col_ct, &svd_rect_lwork))) {
5621 logerrputs("Error: \"--pca approx\" problem instance too large for this " PROG_NAME_STR " build. If\nthis is really the computation you want, use a " PROG_NAME_STR " build with large-matrix\nsupport.\n");
5622 goto CalcPca_ret_INCONSISTENT_INPUT;
5623 }
5624 #endif
5625 uintptr_t svd_rect_wkspace_size = (svd_rect_lwork + qq_col_ct * qq_col_ct) * sizeof(double);
5626 if (svd_rect_wkspace_size < writebuf_alloc) {
5627 // used as writebuf later
5628 svd_rect_wkspace_size = writebuf_alloc;
5629 }
5630
5631 unsigned char* svd_rect_wkspace;
5632 double* ss;
5633 double* g1;
5634 if (unlikely(bigstack_alloc_d(qq_col_ct, &ss) ||
5635 bigstack_alloc_d(pca_row_ct * qq_col_ct, &qq) ||
5636 bigstack_alloc_dp(calc_thread_ct, &ctx.y_transpose_bufs) ||
5637 bigstack_alloc_dp(calc_thread_ct, &ctx.g2_bb_part_bufs) ||
5638 bigstack_alloc_uc(svd_rect_wkspace_size, &svd_rect_wkspace) ||
5639 bigstack_alloc_d(gg_size, &g1))) {
5640 goto CalcPca_ret_NOMEM;
5641 }
5642 const uintptr_t yy_alloc_incr = RoundUpPow2(kPcaVariantBlockSize * pca_sample_ct * sizeof(double), kCacheline);
5643 const uintptr_t b_size = pca_sample_ct * qq_col_ct;
5644 const uintptr_t g2_bb_part_alloc = RoundUpPow2(b_size * sizeof(double), kCacheline);
5645 // bugfix (16 Jan 2020)
5646 const uintptr_t per_thread_alloc = 3 * yy_alloc_incr + g2_bb_part_alloc;
5647
5648 const uintptr_t bigstack_avail = bigstack_left();
5649 if (per_thread_alloc * calc_thread_ct > bigstack_avail) {
5650 if (unlikely(bigstack_avail < per_thread_alloc)) {
5651 goto CalcPca_ret_NOMEM;
5652 }
5653 calc_thread_ct = bigstack_avail / per_thread_alloc;
5654 }
5655 const uintptr_t yy_main_alloc = RoundUpPow2(kPcaVariantBlockSize * calc_thread_ct * pca_sample_ct * sizeof(double), kCacheline);
5656 ctx.yy_bufs[0] = S_CAST(double*, bigstack_alloc_raw(yy_main_alloc));
5657 ctx.yy_bufs[1] = S_CAST(double*, bigstack_alloc_raw(yy_main_alloc));
5658 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
5659 ctx.y_transpose_bufs[tidx] = S_CAST(double*, bigstack_alloc_raw(yy_alloc_incr));
5660 ctx.g2_bb_part_bufs[tidx] = S_CAST(double*, bigstack_alloc_raw(g2_bb_part_alloc));
5661 }
5662 FillGaussianDArr(gg_size / 2, max_thread_ct, sfmtp, g1);
5663 ctx.g1 = g1;
5664 #ifdef __APPLE__
5665 fputs("Projecting random vectors... ", stdout);
5666 #else
5667 printf("Projecting random vectors (%u compute thread%s)... ", calc_thread_ct, (calc_thread_ct == 1)? "" : "s");
5668 #endif
5669 fflush(stdout);
5670 for (uint32_t iter_idx = 0; iter_idx <= pc_ct; ++iter_idx) {
5671 // kjg_fpca_XTXA(), kjg_fpca_XA()
5672 if (iter_idx < pc_ct) {
5673 SetThreadFuncAndData(CalcPcaXtxaThread, &ctx, &tg);
5674 } else {
5675 SetThreadFuncAndData(CalcPcaXaThread, &ctx, &tg);
5676 }
5677 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
5678 ZeroDArr(gg_size, ctx.g2_bb_part_bufs[tidx]);
5679 }
5680 double* qq_iter = &(qq[iter_idx * pc_ct_x2]); // offset on first row
5681 ctx.qq = qq_iter;
5682
5683 // Main workflow:
5684 // 1. Set n=0, load batch 0
5685 //
5686 // 2. Spawn threads processing batch n
5687 // 3. Increment n by 1
5688 // 4. Load batch n unless eof
5689 // 5. Join threads
5690 // 6. Goto step 2 unless eof
5691 //
5692 // 7. Assemble next g1 by summing g2_parts
5693 uint32_t cur_batch_size = calc_thread_ct * kPcaVariantBlockSize;
5694 uint32_t variant_idx = 0;
5695 uintptr_t variant_uidx = 0;
5696 uintptr_t allele_idx_base = 0;
5697 uint32_t incomplete_allele_idx = 0;
5698 uint32_t parity = 0;
5699 uint32_t is_not_first_block = 0;
5700 while (1) {
5701 if (!IsLastBlock(&tg)) {
5702 reterr = LoadCenteredVarmajBlock(pca_sample_include, pssi, variant_include, allele_idx_offsets, allele_freqs, 1, is_haploid, pca_sample_ct, variant_ct, simple_pgrp, ctx.yy_bufs[parity], nullptr, &cur_batch_size, &variant_idx, &variant_uidx, &allele_idx_base, &cur_allele_ct, &incomplete_allele_idx, &pgv, allele_1copy_buf);
5703 if (unlikely(reterr)) {
5704 goto CalcPca_ret_1;
5705 }
5706 }
5707 if (is_not_first_block) {
5708 JoinThreads(&tg);
5709 if (IsLastBlock(&tg)) {
5710 break;
5711 }
5712 }
5713 ctx.cur_batch_size = cur_batch_size;
5714 if (variant_idx == variant_ct) {
5715 DeclareLastThreadBlock(&tg);
5716 cur_batch_size = 0;
5717 }
5718 if (unlikely(SpawnThreads(&tg))) {
5719 goto CalcPca_ret_THREAD_CREATE_FAIL;
5720 }
5721 is_not_first_block = 1;
5722 parity = 1 - parity;
5723 }
5724 if (iter_idx < pc_ct) {
5725 memcpy(g1, ctx.g2_bb_part_bufs[0], gg_size * sizeof(double));
5726 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
5727 const double* cur_g2_part = ctx.g2_bb_part_bufs[tidx];
5728 for (uintptr_t ulii = 0; ulii != gg_size; ++ulii) {
5729 g1[ulii] += cur_g2_part[ulii];
5730 }
5731 }
5732 for (uintptr_t ulii = 0; ulii != gg_size; ++ulii) {
5733 g1[ulii] *= variant_ct_recip;
5734 }
5735 }
5736 #ifdef __APPLE__
5737 printf("\rProjecting random vectors... %u/%u", iter_idx + 1, pc_ct + 1);
5738 #else
5739 printf("\rProjecting random vectors (%u compute thread%s)... %u/%u", calc_thread_ct, (calc_thread_ct == 1)? "" : "s", iter_idx + 1, pc_ct + 1);
5740 #endif
5741 fflush(stdout);
5742 }
5743 fputs(".\n", stdout);
5744 logputs("Computing SVD of Krylov matrix... ");
5745 fflush(stdout);
5746 BLAS_SET_NUM_THREADS(max_thread_ct);
5747 IntErr svd_rect_err = SvdRectFused(pca_row_ct, qq_col_ct, svd_rect_lwork, qq, ss, svd_rect_wkspace);
5748 if (unlikely(svd_rect_err)) {
5749 logputs("\n");
5750 snprintf(g_logbuf, kLogbufSize, "Error: Failed to compute SVD of Krylov matrix (DGESVD info=%d).\n", S_CAST(int32_t, svd_rect_err));
5751 goto CalcPca_ret_DEGENERATE_DATA_2;
5752 }
5753 BLAS_SET_NUM_THREADS(1);
5754 logputs("done.\nRecovering top PCs from range approximation... ");
5755 fflush(stdout);
5756
5757 // kjg_fpca_XTB()
5758 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
5759 ZeroDArr(b_size, ctx.g2_bb_part_bufs[tidx]);
5760 }
5761 SetThreadFuncAndData(CalcPcaXtbThread, &ctx, &tg);
5762 ctx.qq = qq;
5763 uint32_t cur_batch_size = calc_thread_ct * kPcaVariantBlockSize;
5764 uint32_t variant_idx = 0;
5765 uintptr_t variant_uidx = 0;
5766 uintptr_t allele_idx_base = 0;
5767 uint32_t incomplete_allele_idx = 0;
5768 uint32_t parity = 0;
5769 uint32_t is_not_first_block = 0;
5770 while (1) {
5771 if (!IsLastBlock(&tg)) {
5772 reterr = LoadCenteredVarmajBlock(pca_sample_include, pssi, variant_include, allele_idx_offsets, allele_freqs, 1, is_haploid, pca_sample_ct, variant_ct, simple_pgrp, ctx.yy_bufs[parity], nullptr, &cur_batch_size, &variant_idx, &variant_uidx, &allele_idx_base, &cur_allele_ct, &incomplete_allele_idx, &pgv, allele_1copy_buf);
5773 if (unlikely(reterr)) {
5774 // This error *didn't* happen on an earlier pass, so assign blame
5775 // to I/O. (This may be additive with an error message printed by
5776 // LoadCenteredVarmajBlock().)
5777 goto CalcPca_ret_REWIND_FAIL;
5778 }
5779 }
5780 if (is_not_first_block) {
5781 JoinThreads(&tg);
5782 if (IsLastBlock(&tg)) {
5783 break;
5784 }
5785 }
5786 ctx.cur_batch_size = cur_batch_size;
5787 if (variant_idx == variant_ct) {
5788 DeclareLastThreadBlock(&tg);
5789 cur_batch_size = 0;
5790 }
5791 if (unlikely(SpawnThreads(&tg))) {
5792 goto CalcPca_ret_THREAD_CREATE_FAIL;
5793 }
5794 is_not_first_block = 1;
5795 parity = 1 - parity;
5796 }
5797 double* bb = ctx.g2_bb_part_bufs[0];
5798 for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) {
5799 const double* cur_bb_part = ctx.g2_bb_part_bufs[tidx];
5800 for (uintptr_t ulii = 0; ulii != b_size; ++ulii) {
5801 bb[ulii] += cur_bb_part[ulii];
5802 }
5803 }
5804 BLAS_SET_NUM_THREADS(max_thread_ct);
5805 svd_rect_err = SvdRectFused(pca_sample_ct, qq_col_ct, svd_rect_lwork, bb, ss, svd_rect_wkspace);
5806 if (unlikely(svd_rect_err)) {
5807 logputs("\n");
5808 snprintf(g_logbuf, kLogbufSize, "Error: Failed to compute SVD of final matrix (DGESVD info=%d).\n", S_CAST(int32_t, svd_rect_err));
5809 goto CalcPca_ret_DEGENERATE_DATA_2;
5810 }
5811 BLAS_SET_NUM_THREADS(1);
5812 logputs("done.\n");
5813 eigvecs_smaj = g1;
5814 for (uint32_t sample_idx = 0; sample_idx != pca_sample_ct; ++sample_idx) {
5815 memcpy(&(eigvecs_smaj[sample_idx * S_CAST(uintptr_t, pc_ct)]), &(bb[sample_idx * qq_col_ct]), pc_ct * sizeof(double));
5816 }
5817 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5818 eigvals[pc_idx] = ss[pc_idx] * ss[pc_idx] * variant_ct_recip;
5819 }
5820 writebuf = R_CAST(char*, svd_rect_wkspace);
5821 // bugfix (25 Jun 2018): eigvals[] computation was missing a divide-by-2
5822 // somewhere, in both diploid and haploid cases.
5823 // update (30 Jan 2019): er, actually, no.
5824 if (is_haploid) {
5825 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5826 eigvals[pc_idx] *= 0.5;
5827 }
5828 }
5829 } else {
5830 #ifndef LAPACK_ILP64
5831 if (unlikely(pca_sample_ct > 46340)) {
5832 logerrputs("Error: --pca non-approximate problem instance too large for this " PROG_NAME_STR " build.\nTry \"--pca approx\" instead, or a " PROG_NAME_STR " build with large-matrix support.\n");
5833 goto CalcPca_ret_INCONSISTENT_INPUT;
5834 }
5835 #endif
5836 {
5837 // If there are NaNs in grm, ExtractEigvecs should fail; but we want to
5838 // print a customized error message in that case, and grm is destroyed
5839 // by ExtractEigvecs(). Okay, checking it for NaNs after the fact
5840 // probably works in practice, but I'd rather not risk it; checking for
5841 // NaNs in advance is cheap enough.
5842 uintptr_t row_idx;
5843 uintptr_t col_idx;
5844 if (LowerTriangularFirstInfOrNan(grm, pca_sample_ct, &row_idx, &col_idx)) {
5845 const double invalid_val = grm[row_idx * pca_sample_ct + col_idx];
5846 char* id_pair_str = g_textbuf;
5847 {
5848 char* write_iter = id_pair_str;
5849 if (row_idx == col_idx) {
5850 write_iter = strcpya_k(write_iter, " '");
5851 } else {
5852 write_iter = strcpya_k(write_iter, "s '");
5853 }
5854 const uintptr_t sample_uidx1 = IdxToUidxBasic(sample_include, col_idx);
5855 write_iter = AppendSpacedXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx1, write_iter);
5856 if (row_idx == col_idx) {
5857 strcpy_k(write_iter, "' and itself");
5858 } else {
5859 write_iter = strcpya_k(write_iter, "' and '");
5860 const uintptr_t sample_uidx2 = IdxToUidxBasic(sample_include, row_idx);
5861 write_iter = AppendSpacedXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx2, write_iter);
5862 strcpy_k(write_iter, "'");
5863 }
5864 }
5865 if (invalid_val != invalid_val) {
5866 logerrprintfww("Error: NaN value present in GRM, between sample%s. This usually occurs when you have samples with an extremely high amount of missing data; use e.g. --mind to filter them out before retrying.\n", id_pair_str);
5867 goto CalcPca_ret_DEGENERATE_DATA;
5868 }
5869 // I'll call this an internal error, even though in principle this
5870 // could result from malicious --read-freq input.
5871 logerrprintfww("Error: Infinite value present in GRM, between sample%s. This should never happen; you have probably encountered a plink2 bug. If you report the error on GitHub or the plink2-users Google group (make sure to include the full .log file in your report), we'll try to address it.\n", id_pair_str);
5872 reterr = kPglRetInternalError;
5873 goto CalcPca_ret_1;
5874 }
5875 }
5876 __CLPK_integer lwork;
5877 __CLPK_integer liwork;
5878 uintptr_t wkspace_byte_ct;
5879 if (unlikely(GetExtractEigvecsLworks(pca_sample_ct, pc_ct, &lwork, &liwork, &wkspace_byte_ct))) {
5880 goto CalcPca_ret_NOMEM;
5881 }
5882 const uintptr_t eigvecs_smaj_alloc = pc_ct * pca_sample_ct * sizeof(double);
5883 if (wkspace_byte_ct < eigvecs_smaj_alloc) {
5884 wkspace_byte_ct = eigvecs_smaj_alloc;
5885 }
5886 double* reverse_eigvecs_pcmaj;
5887 unsigned char* extract_eigvecs_wkspace;
5888 if (unlikely(bigstack_alloc_d(pc_ct * pca_sample_ct, &reverse_eigvecs_pcmaj) ||
5889 bigstack_alloc_uc(wkspace_byte_ct, &extract_eigvecs_wkspace))) {
5890 goto CalcPca_ret_NOMEM;
5891 }
5892 logprintf("Extracting eigenvalue%s and eigenvector%s... ", (pc_ct == 1)? "" : "s", (pc_ct == 1)? "" : "s");
5893 fflush(stdout);
5894 BLAS_SET_NUM_THREADS(max_thread_ct);
5895 // not putting unlikely() here for now.
5896 if (ExtractEigvecs(pca_sample_ct, pc_ct, lwork, liwork, grm, eigvals, reverse_eigvecs_pcmaj, extract_eigvecs_wkspace)) {
5897 logputs("\n");
5898 logerrputs("Error: Failed to extract eigenvector(s) from GRM.\n");
5899 goto CalcPca_ret_DEGENERATE_DATA;
5900 }
5901 BLAS_SET_NUM_THREADS(1);
5902 logputs("done.\n");
5903 eigvecs_smaj = R_CAST(double*, extract_eigvecs_wkspace);
5904 BigstackShrinkTop(eigvecs_smaj, eigvecs_smaj_alloc);
5905 if (unlikely(bigstack_alloc_c(writebuf_alloc, &writebuf))) {
5906 goto CalcPca_ret_NOMEM;
5907 }
5908
5909 // ExtractEigvecs() results are in reverse order, and we also need to
5910 // transpose eigenvectors to sample-major
5911 const uint32_t pc_ct_m1 = pc_ct - 1;
5912 const uint32_t pc_ct_div2 = pc_ct / 2;
5913 for (uint32_t pc_idx = 0; pc_idx != pc_ct_div2; ++pc_idx) {
5914 double tmp_eigval = eigvals[pc_idx];
5915 eigvals[pc_idx] = eigvals[pc_ct_m1 - pc_idx];
5916 eigvals[pc_ct_m1 - pc_idx] = tmp_eigval;
5917 }
5918 double* eigvecs_smaj_iter = eigvecs_smaj;
5919 for (uint32_t sample_idx = 0; sample_idx != pca_sample_ct; ++sample_idx) {
5920 uintptr_t pc_inv_idx = pc_ct;
5921 const double* reverse_eigvecs_col = &(reverse_eigvecs_pcmaj[sample_idx]);
5922 do {
5923 --pc_inv_idx;
5924 *eigvecs_smaj_iter++ = reverse_eigvecs_col[pc_inv_idx * pca_sample_ct];
5925 } while (pc_inv_idx);
5926 }
5927 }
5928 // (later: --pca-cluster-names, --pca-clusters)
5929 char* writebuf_flush = &(writebuf[kMaxMediumLine]);
5930
5931 if (wts_requested) {
5932 CalcPcaVarWtsCtx vwctx;
5933 vwctx.sample_ct = pca_sample_ct;
5934 vwctx.pc_ct = pc_ct;
5935 vwctx.sample_wts_smaj = eigvecs_smaj;
5936 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
5937 eigval_inv_sqrts[pc_idx] = 1.0 / sqrt(eigvals[pc_idx]);
5938 }
5939
5940 const uint32_t allele_wts = (pca_flags / kfPcaAlleleWts) & 1;
5941 const uint32_t output_zst = (pca_flags / kfPcaVarZs) & 1;
5942 if (allele_wts) {
5943 OutnameZstSet(".eigenvec.allele", output_zst, outname_end);
5944 } else {
5945 OutnameZstSet(".eigenvec.var", output_zst, outname_end);
5946 }
5947 reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, writebuf, R_CAST(unsigned char*, &(writebuf[overflow_buf_size])), &css);
5948 if (unlikely(reterr)) {
5949 goto CalcPca_ret_1;
5950 }
5951 cswritep = writebuf;
5952 *cswritep++ = '#';
5953 if (chr_buf) {
5954 cswritep = strcpya_k(cswritep, "CHROM\t");
5955 }
5956 if (pca_flags & kfPcaVcolPos) {
5957 cswritep = strcpya_k(cswritep, "POS\t");
5958 } else {
5959 variant_bps = nullptr;
5960 }
5961 cswritep = strcpya_k(cswritep, "ID");
5962 if (pca_flags & kfPcaVcolRef) {
5963 cswritep = strcpya_k(cswritep, "\tREF");
5964 }
5965 if (pca_flags & kfPcaVcolAlt1) {
5966 cswritep = strcpya_k(cswritep, "\tALT1");
5967 }
5968 if (pca_flags & kfPcaVcolAlt) {
5969 cswritep = strcpya_k(cswritep, "\tALT");
5970 }
5971 const uintptr_t* nonref_flags = PgrGetNonrefFlags(simple_pgrp);
5972 const uint32_t all_nonref = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref) && (!nonref_flags);
5973 const uint32_t provref_col = (pca_flags & kfPcaVcolRef) && ProvrefCol(variant_include, nonref_flags, pca_flags / kfPcaVcolMaybeprovref, raw_variant_ct, all_nonref);
5974 if (provref_col) {
5975 cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
5976 }
5977 if (allele_wts) {
5978 cswritep = strcpya_k(cswritep, "\tA1");
5979 }
5980 if (pca_flags & kfPcaVcolAx) {
5981 cswritep = strcpya_k(cswritep, "\tAX");
5982 }
5983 if (pca_flags & kfPcaVcolMaj) {
5984 cswritep = strcpya_k(cswritep, "\tMAJ");
5985 }
5986 if (pca_flags & kfPcaVcolNonmaj) {
5987 cswritep = strcpya_k(cswritep, "\tNONMAJ");
5988 }
5989 for (uint32_t pc_idx = 1; pc_idx <= pc_ct; ++pc_idx) {
5990 cswritep = strcpya_k(cswritep, "\tPC");
5991 cswritep = u32toa(pc_idx, cswritep);
5992 }
5993 AppendBinaryEoln(&cswritep);
5994
5995 // Main workflow:
5996 // 1. Set n=0, load batch 0
5997 //
5998 // 2. Spawn threads processing batch n
5999 // 3. If n>0, write results and update projection for block (n-1)
6000 // 4. Increment n by 1
6001 // 5. Load batch n unless eof
6002 // 6. Join threads
6003 // 7. Goto step 2 unless eof
6004 //
6005 // 8. Write results and update projection for last block
6006 #ifndef __APPLE__
6007 if (output_zst) {
6008 // compression is relatively expensive?
6009 calc_thread_ct = 1;
6010 }
6011 #endif
6012 uintptr_t var_wts_part_size;
6013 double* var_wts = qq;
6014 if (var_wts) {
6015 var_wts_part_size = (MINV(pca_row_ct, calc_thread_ct * kPcaVariantBlockSize)) * S_CAST(uintptr_t, pc_ct);
6016 vwctx.yy_bufs[0] = ctx.yy_bufs[0];
6017 vwctx.yy_bufs[1] = ctx.yy_bufs[1];
6018 vwctx.var_wts = ctx.qq;
6019 } else {
6020 // non-approximate PCA, some buffers have not been allocated yet
6021
6022 // if grm[] (which we no longer need) has at least as much remaining
6023 // space as bigstack, allocate from grm
6024 unsigned char* arena_bottom = R_CAST(unsigned char*, grm);
6025 unsigned char* arena_top = bigstack_mark;
6026 uintptr_t arena_avail = arena_top - arena_bottom;
6027 if (arena_avail < bigstack_left()) {
6028 arena_bottom = g_bigstack_base;
6029 arena_top = g_bigstack_end;
6030 arena_avail = bigstack_left();
6031 }
6032 const uintptr_t var_wts_part_alloc = RoundUpPow2(2 * kPcaVariantBlockSize * sizeof(double) * pc_ct, kCacheline);
6033 const uintptr_t yy_alloc_incr = RoundUpPow2(kPcaVariantBlockSize * pca_sample_ct * sizeof(double), kCacheline);
6034 const uintptr_t per_thread_alloc = 2 * yy_alloc_incr + var_wts_part_alloc;
6035 if (per_thread_alloc * calc_thread_ct > arena_avail) {
6036 if (unlikely(arena_avail < per_thread_alloc)) {
6037 goto CalcPca_ret_NOMEM;
6038 }
6039 calc_thread_ct = arena_avail / per_thread_alloc;
6040 }
6041 const uintptr_t yy_main_alloc = RoundUpPow2(kPcaVariantBlockSize * calc_thread_ct * pca_sample_ct * sizeof(double), kCacheline);
6042 vwctx.yy_bufs[0] = S_CAST(double*, arena_alloc_raw(yy_main_alloc, &arena_bottom));
6043 vwctx.yy_bufs[1] = S_CAST(double*, arena_alloc_raw(yy_main_alloc, &arena_bottom));
6044 var_wts_part_size = (MINV(pca_row_ct, calc_thread_ct * kPcaVariantBlockSize)) * S_CAST(uintptr_t, pc_ct);
6045 var_wts = S_CAST(double*, arena_alloc_raw_rd(2 * var_wts_part_size * sizeof(double), &arena_bottom));
6046 vwctx.var_wts = var_wts;
6047 #ifndef NDEBUG
6048 if (arena_top == g_bigstack_end) {
6049 // we shouldn't make any more allocations, but just in case...
6050 g_bigstack_base = arena_bottom;
6051 }
6052 #endif
6053 }
6054 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
6055 goto CalcPca_ret_NOMEM;
6056 }
6057 SetThreadFuncAndData(CalcPcaVarWtsThread, &vwctx, &tg);
6058 uint32_t prev_batch_size = 0;
6059 uint32_t cur_batch_size = calc_thread_ct * kPcaVariantBlockSize;
6060
6061 uint32_t variant_idx_load = 0;
6062 uintptr_t variant_uidx_load = 0;
6063 uintptr_t allele_idx_base_load = 0;
6064 uint32_t cur_allele_ct_load = 2;
6065 uint32_t incomplete_allele_idx_load = 0;
6066
6067 uint32_t variant_idx_write = 0;
6068 uintptr_t variant_uidx_write = 0;
6069 uintptr_t allele_idx_offset_write = 0;
6070 // cur_allele_ct = 2;
6071 uint32_t incomplete_allele_idx_write = 0;
6072 uint32_t chr_fo_idx = UINT32_MAX;
6073 uint32_t chr_end = 0;
6074 uint32_t chr_buf_blen = 0;
6075
6076 uint32_t parity = 0;
6077 uint32_t is_not_first_block = 0;
6078 while (1) {
6079 if (!IsLastBlock(&tg)) {
6080 reterr = LoadCenteredVarmajBlock(pca_sample_include, pssi, variant_include, allele_idx_offsets, allele_freqs, 1, is_haploid, pca_sample_ct, variant_ct, simple_pgrp, vwctx.yy_bufs[parity], nullptr, &cur_batch_size, &variant_idx_load, &variant_uidx_load, &allele_idx_base_load, &cur_allele_ct_load, &incomplete_allele_idx_load, &pgv, allele_1copy_buf);
6081 if (unlikely(reterr)) {
6082 goto CalcPca_ret_1;
6083 }
6084 }
6085 if (is_not_first_block) {
6086 JoinThreads(&tg);
6087 }
6088 if (!IsLastBlock(&tg)) {
6089 vwctx.cur_batch_size = cur_batch_size;
6090 if (variant_idx_load == variant_ct) {
6091 DeclareLastThreadBlock(&tg);
6092 }
6093 if (unlikely(SpawnThreads(&tg))) {
6094 goto CalcPca_ret_THREAD_CREATE_FAIL;
6095 }
6096 }
6097 parity = 1 - parity;
6098 if (is_not_first_block) {
6099 // write *previous* block results
6100 const double* var_wts_iter = &(var_wts[parity * var_wts_part_size]);
6101 // (todo: update projection here)
6102 if (allele_wts) {
6103 reterr = FlushAlleleWts(variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, nonref_flags, var_wts_iter, eigval_inv_sqrts, prev_batch_size, pc_ct, pca_flags, provref_col, all_nonref, &css, &cswritep, chr_buf, &variant_idx_write, &variant_uidx_write, &allele_idx_offset_write, &cur_allele_ct, &incomplete_allele_idx_write, &chr_fo_idx, &chr_end, &chr_buf_blen);
6104 } else {
6105 reterr = FlushBiallelicVarWts(variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, nonref_flags, maj_alleles, var_wts_iter, eigval_inv_sqrts, prev_batch_size, pc_ct, pca_flags, provref_col, all_nonref, &css, &cswritep, chr_buf, &variant_idx_write, &variant_uidx_write, &chr_fo_idx, &chr_end, &chr_buf_blen);
6106 }
6107 if (unlikely(reterr)) {
6108 // only write_fail possible in practice
6109 goto CalcPca_ret_1;
6110 }
6111 if (variant_idx_write == variant_ct) {
6112 break;
6113 }
6114 }
6115 is_not_first_block = 1;
6116 prev_batch_size = cur_batch_size;
6117 }
6118 if (unlikely(CswriteCloseNull(&css, cswritep))) {
6119 goto CalcPca_ret_WRITE_FAIL;
6120 }
6121 logprintfww("--pca%s: %s weights written to %s .\n", is_approx? " approx" : "", allele_wts? "Allele" : "Variant", outname);
6122 }
6123
6124 snprintf(outname_end, kMaxOutfnameExtBlen, ".eigenvec");
6125 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
6126 goto CalcPca_ret_OPEN_FAIL;
6127 }
6128 char* write_iter = writebuf;
6129 *write_iter++ = '#';
6130 if (write_fid) {
6131 write_iter = strcpya_k(write_iter, "FID\t");
6132 }
6133 write_iter = strcpya_k(write_iter, "IID");
6134 if (write_sid) {
6135 write_iter = strcpya_k(write_iter, "\tSID");
6136 }
6137 for (uint32_t pc_idx = 1; pc_idx <= pc_ct; ++pc_idx) {
6138 write_iter = strcpya_k(write_iter, "\tPC");
6139 write_iter = u32toa(pc_idx, write_iter);
6140 }
6141 AppendBinaryEoln(&write_iter);
6142 const uint32_t sample_ct = pca_sample_ct;
6143 uintptr_t sample_uidx_base = 0;
6144 uintptr_t sample_include_bits = sample_include[0];
6145 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
6146 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
6147 write_iter = AppendXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter);
6148 double* sample_wts_iter = &(eigvecs_smaj[sample_idx * pc_ct]);
6149 // todo: read from proj_sample_wts instead when pca_sample_include bit
6150 // not set
6151 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
6152 *write_iter++ = '\t';
6153 write_iter = dtoa_g(*sample_wts_iter++, write_iter);
6154 }
6155 AppendBinaryEoln(&write_iter);
6156 if (unlikely(fwrite_ck(writebuf_flush, outfile, &write_iter))) {
6157 goto CalcPca_ret_WRITE_FAIL;
6158 }
6159 }
6160 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
6161 goto CalcPca_ret_WRITE_FAIL;
6162 }
6163
6164 snprintf(outname_end, kMaxOutfnameExtBlen, ".eigenval");
6165 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
6166 goto CalcPca_ret_OPEN_FAIL;
6167 }
6168 write_iter = writebuf;
6169 for (uint32_t pc_idx = 0; pc_idx != pc_ct; ++pc_idx) {
6170 write_iter = dtoa_g(eigvals[pc_idx], write_iter);
6171 AppendBinaryEoln(&write_iter);
6172 }
6173 if (unlikely(fclose_flush_null(writebuf_flush, write_iter, &outfile))) {
6174 goto CalcPca_ret_WRITE_FAIL;
6175 }
6176 *outname_end = '\0';
6177 logprintfww("--pca%s: Eigenvector%s written to %s.eigenvec , and eigenvalue%s written to %s.eigenval .\n", is_approx? " approx" : "", (pc_ct == 1)? "" : "s", outname, (pc_ct == 1)? "" : "s", outname);
6178 }
6179 while (0) {
6180 CalcPca_ret_NOMEM:
6181 reterr = kPglRetNomem;
6182 break;
6183 CalcPca_ret_OPEN_FAIL:
6184 reterr = kPglRetOpenFail;
6185 break;
6186 CalcPca_ret_REWIND_FAIL:
6187 logerrprintfww(kErrprintfRewind, ".pgen file");
6188 break;
6189 CalcPca_ret_WRITE_FAIL:
6190 reterr = kPglRetWriteFail;
6191 break;
6192 CalcPca_ret_INCONSISTENT_INPUT:
6193 reterr = kPglRetInconsistentInput;
6194 break;
6195 CalcPca_ret_THREAD_CREATE_FAIL:
6196 reterr = kPglRetThreadCreateFail;
6197 break;
6198 CalcPca_ret_DEGENERATE_DATA_2:
6199 logerrputsb();
6200 CalcPca_ret_DEGENERATE_DATA:
6201 reterr = kPglRetDegenerateData;
6202 break;
6203 }
6204 CalcPca_ret_1:
6205 CleanupThreads(&tg);
6206 BLAS_SET_NUM_THREADS(1);
6207 CswriteCloseCond(&css, cswritep);
6208 fclose_cond(outfile);
6209 if (grm) {
6210 // nothing after --pca in the plink2 order of operations uses grm[]
6211 BigstackReset(grm);
6212 } else {
6213 BigstackReset(bigstack_mark);
6214 }
6215 return reterr;
6216 }
6217 #endif
6218
6219 PglErr ScoreListLoad(const char* list_fname, TextStream* score_txsp, LlStr** fname_iterp, uint32_t* infile_ctp) {
6220 PglErr reterr = kPglRetSuccess;
6221 {
6222 LlStr** llstr_endp = fname_iterp;
6223 uintptr_t infile_ct = 0;
6224 while (1) {
6225 const char* fname = TextGet(score_txsp);
6226 if (!fname) {
6227 break;
6228 }
6229 ++infile_ct;
6230 const char* fname_end = CurTokenEnd(fname);
6231 const uint32_t fname_slen = fname_end - fname;
6232 LlStr* new_entry;
6233 if (unlikely(bigstack_end_alloc_llstr(fname_slen + 1, &new_entry))) {
6234 goto ScoreListLoad_ret_NOMEM;
6235 }
6236 new_entry->next = nullptr;
6237 memcpyx(new_entry->str, fname, fname_slen, '\0');
6238 *llstr_endp = new_entry;
6239 llstr_endp = &(new_entry->next);
6240 }
6241 if (unlikely(!infile_ct)) {
6242 logerrprintfww("Error: --score-list: %s is empty.\n", list_fname);
6243 goto ScoreListLoad_ret_MALFORMED_INPUT;
6244 }
6245 #ifdef __LP64__
6246 if (unlikely(infile_ct > 0xffffffffU)) {
6247 logerrprintfww("Error: --score-list: Too many entries in %s.\n", list_fname);
6248 reterr = kPglRetNotYetSupported;
6249 goto ScoreListLoad_ret_1;
6250 }
6251 #endif
6252 reterr = TextRetarget((*fname_iterp)->str, score_txsp);
6253 if (unlikely(reterr)) {
6254 goto ScoreListLoad_ret_TSTREAM_FAIL;
6255 }
6256 *infile_ctp = infile_ct;
6257 }
6258 while (0) {
6259 ScoreListLoad_ret_NOMEM:
6260 reterr = kPglRetNomem;
6261 break;
6262 ScoreListLoad_ret_TSTREAM_FAIL:
6263 TextStreamErrPrint(list_fname, score_txsp);
6264 break;
6265 ScoreListLoad_ret_MALFORMED_INPUT:
6266 reterr = kPglRetMalformedInput;
6267 break;
6268 }
6269 #ifdef __LP64__
6270 ScoreListLoad_ret_1:
6271 #endif
6272 return reterr;
6273 }
6274
6275 // to test: do we actually want cur_dosage_ints to be uint64_t* instead of
6276 // uint32_t*?
6277 void FillDdosageInts(const uintptr_t* genovec_buf, const uintptr_t* dosage_present, const Dosage* dosage_main_buf, uint32_t sample_ct, uint32_t dosage_ct, uint32_t is_diploid, uint64_t* cur_ddosage_ints) {
6278 uint64_t lookup_table[32] ALIGNV16;
6279 lookup_table[0] = 0;
6280 lookup_table[2] = (kDosageMid * k1LU) << is_diploid;
6281 lookup_table[4] = (kDosageMax * k1LU) << is_diploid;
6282 lookup_table[6] = 0;
6283 InitLookup16x8bx2(lookup_table);
6284 GenoarrLookup16x8bx2(genovec_buf, lookup_table, sample_ct, cur_ddosage_ints);
6285 if (!dosage_ct) {
6286 return;
6287 }
6288 uintptr_t sample_idx_base = 0;
6289 uintptr_t cur_bits = dosage_present[0];
6290 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
6291 const uintptr_t sample_idx = BitIter1(dosage_present, &sample_idx_base, &cur_bits);
6292 cur_ddosage_ints[sample_idx] = (dosage_main_buf[dosage_idx] * k1LU) << is_diploid;
6293 }
6294 }
6295
6296 CONSTI32(kScoreVariantBlockSize, 240);
6297
6298 // must be a power of 2, >= kBitsPerWord
6299 #ifdef USE_AVX2
6300 CONSTI32(kScoreSampleShardSizeAlign, 256);
6301 #else
6302 CONSTI32(kScoreSampleShardSizeAlign, 128);
6303 #endif
6304
6305 // The previous implementation had poor parallelism; the main thread was
6306 // responsible for too many per-sample uint64_t and floating-point operations.
6307 // We now shard those operations across all worker threads, and leave only
6308 // much faster bitvector and similar operations in the main thread.
6309 typedef struct CalcScoreCtxStruct {
6310 const uintptr_t* variant_include;
6311 const uint32_t* variant_include_cumulative_popcounts;
6312 const uintptr_t* qsr_include;
6313 const uintptr_t* sex_nonmale_collapsed;
6314 const uintptr_t* sex_female_collapsed;
6315 uint32_t score_final_col_ct;
6316 uint32_t sample_shard_size;
6317 uint32_t sample_ct;
6318 uint32_t max_returned_difflist_len;
6319 ScoreFlags flags;
6320 uint32_t qsr_ct;
6321
6322 uint32_t* variant_uidxs[2];
6323 uintptr_t* genovecs[2];
6324 uintptr_t* raregenos[2];
6325 uint32_t* difflist_lens[2];
6326 uint32_t* difflist_sample_ids[2];
6327 int8_t* difflist_common_genos[2];
6328 uintptr_t* dosage_presents[2];
6329 Dosage* dosage_mains[2];
6330 uint32_t* dosage_cts[2];
6331 uintptr_t* missing_bitvecs[2];
6332 uintptr_t* missing_male_bitvecs[2];
6333 uintptr_t* missing_nonfemale_bitvecs[2];
6334 double* allele_freqs[2];
6335 double* geno_slopes[2];
6336 double* geno_intercepts[2];
6337 double* score_dense_coefs_cmaj[2];
6338 double* score_sparse_coefs_vmaj[2];
6339 unsigned char is_nonx_haploids[2][kScoreVariantBlockSize];
6340 unsigned char is_relevant_xs[2][kScoreVariantBlockSize];
6341 unsigned char is_ys[2][kScoreVariantBlockSize];
6342 unsigned char ploidy_m1s[2][kScoreVariantBlockSize];
6343 uint32_t cur_variant_batch_size;
6344
6345 // per-thread buffers
6346 uint64_t** ddosage_incrs;
6347 double** dosages_vmaj;
6348
6349 // final results
6350 uint64_t* ddosage_sums;
6351 double** sharded_final_scores_cmaj;
6352 } CalcScoreCtx;
6353
6354 THREAD_FUNC_DECL CalcScoreThread(void* raw_arg) {
6355 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
6356 const uintptr_t tidx = arg->tidx;
6357 CalcScoreCtx* ctx = S_CAST(CalcScoreCtx*, arg->sharedp->context);
6358
6359 const uintptr_t* variant_include = ctx->variant_include;
6360 const uint32_t* variant_include_cumulative_popcounts = ctx->variant_include_cumulative_popcounts;
6361 const uintptr_t* qsr_include = ctx->qsr_include;
6362
6363 const uint32_t score_final_col_ct = ctx->score_final_col_ct;
6364 uint32_t sample_shard_size = ctx->sample_shard_size;
6365 const uint32_t sample_idx_start = tidx * sample_shard_size;
6366 double* shard_final_scores_cmaj = ctx->sharded_final_scores_cmaj[tidx];
6367 const uint32_t sample_ct = ctx->sample_ct;
6368 if (sample_shard_size + sample_idx_start > sample_ct) {
6369 sample_shard_size = sample_ct - sample_idx_start;
6370 }
6371 const uint32_t sample_idx_startl2 = NypCtToWordCt(sample_idx_start);
6372 const uint32_t sample_idx_startl = BitCtToWordCt(sample_idx_start);
6373 const uint32_t shard_sizel = BitCtToWordCt(sample_shard_size);
6374 const uint32_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
6375 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
6376 const uint32_t max_returned_difflist_len = ctx->max_returned_difflist_len;
6377 const uintptr_t raregeno_stride = NypCtToAlignedWordCt(max_returned_difflist_len);
6378 const uintptr_t difflist_sample_ids_stride = RoundUpPow2(max_returned_difflist_len, kInt32PerVec);
6379 const uint32_t dosage_main_stride = RoundUpPow2(sample_ct, kDosagePerVec);
6380 const uintptr_t* shard_sex_nonmale_collapsed = &(ctx->sex_nonmale_collapsed[sample_idx_startl]);
6381 const uintptr_t* shard_sex_female_collapsed = &(ctx->sex_female_collapsed[sample_idx_startl]);
6382 const uint32_t shard_nonmale_ct = PopcountWords(shard_sex_nonmale_collapsed, shard_sizel);
6383 const uint32_t shard_male_ct = sample_shard_size - shard_nonmale_ct;
6384 const uint32_t shard_female_ct = PopcountWords(shard_sex_female_collapsed, shard_sizel);
6385 const uint32_t shard_nonfemale_ct = sample_shard_size - shard_female_ct;
6386 const ScoreFlags flags = ctx->flags;
6387 const uint32_t model_dominant = (flags / kfScoreDominant) & 1;
6388 const uint32_t domrec = model_dominant || (flags & kfScoreRecessive);
6389 const uint32_t no_meanimpute = (flags / kfScoreNoMeanimpute) & 1;
6390 const uint32_t se_mode = (flags / kfScoreSe) & 1;
6391 const uint32_t qsr_ct = ctx->qsr_ct;
6392
6393 uint64_t* ddosage_incrs = ctx->ddosage_incrs[tidx];
6394 double* dosages_vmaj = ctx->dosages_vmaj[tidx];
6395
6396 uint64_t* shard_ddosage_sums = &(ctx->ddosage_sums[sample_idx_start]);
6397
6398 double cur_allele_freq = 0.0;
6399 double geno_slope = kRecipDosageMax;
6400 double geno_intercept = 0.0;
6401 uint32_t parity = 0;
6402 do {
6403 const uint32_t cur_variant_batch_size = ctx->cur_variant_batch_size;
6404 if (cur_variant_batch_size) {
6405 const uint32_t* variant_uidxs = ctx->variant_uidxs[parity];
6406 const uintptr_t* genovec_iter = &(ctx->genovecs[parity][sample_idx_startl2]);
6407 const uintptr_t* raregeno_iter = ctx->raregenos[parity];
6408 const uint32_t* difflist_lens = ctx->difflist_lens[parity];
6409 const uint32_t* difflist_sample_ids_iter = ctx->difflist_sample_ids[parity];
6410 const int8_t* difflist_common_genos = ctx->difflist_common_genos[parity];
6411 const uintptr_t* dosage_present_iter = ctx->dosage_presents[parity];
6412 const Dosage* dosage_main_iter = ctx->dosage_mains[parity];
6413 const uint32_t* dosage_cts = ctx->dosage_cts[parity];
6414 const uintptr_t* missing_bitvec_iter = &(ctx->missing_bitvecs[parity][sample_idx_startl]);
6415 const uintptr_t* missing_male_bitvec_iter = &(ctx->missing_male_bitvecs[parity][sample_idx_startl]);
6416 const uintptr_t* missing_nonfemale_bitvec_iter = &(ctx->missing_nonfemale_bitvecs[parity][sample_idx_startl]);
6417 const double* allele_freqs = ctx->allele_freqs[parity];
6418 const double* geno_slopes = ctx->geno_slopes[parity];
6419 const double* geno_intercepts = ctx->geno_intercepts[parity];
6420 const double* score_sparse_coefs_vmaj_iter = ctx->score_sparse_coefs_vmaj[parity];
6421 const unsigned char* is_nonx_haploids = &(ctx->is_nonx_haploids[parity][0]);
6422 const unsigned char* is_relevant_xs = &(ctx->is_relevant_xs[parity][0]);
6423 const unsigned char* is_ys = &(ctx->is_ys[parity][0]);
6424 const unsigned char* ploidy_m1s = &(ctx->ploidy_m1s[parity][0]);
6425 const uintptr_t* shard_dosage_present = nullptr;
6426 const Dosage* shard_dosage_main = nullptr;
6427 double* dosages_vmaj_iter = dosages_vmaj;
6428
6429 uint32_t sparse_vidx = 0;
6430 uint32_t shard_dosage_ct = 0;
6431 for (uint32_t vidx = 0; vidx != cur_variant_batch_size; ++vidx) {
6432 const uint32_t is_nonx_haploid = is_nonx_haploids[vidx];
6433 const uint32_t is_relevant_x = is_relevant_xs[vidx];
6434 const uint32_t is_y = is_ys[vidx];
6435 if (dosage_cts) {
6436 // defensive
6437 shard_dosage_present = nullptr;
6438 shard_dosage_main = nullptr;
6439 // bugfix (3 Jun 2022)
6440 shard_dosage_ct = 0;
6441 const uint32_t dosage_ct = dosage_cts[vidx];
6442 if (dosage_ct) {
6443 const uint32_t dosage_main_offset = PopcountWords(dosage_present_iter, sample_idx_startl);
6444 if (dosage_main_offset != dosage_ct) {
6445 shard_dosage_ct = PopcountWords(&(dosage_present_iter[sample_idx_startl]), shard_sizel);
6446 if (shard_dosage_ct) {
6447 shard_dosage_present = &(dosage_present_iter[sample_idx_startl]);
6448 shard_dosage_main = &(dosage_main_iter[dosage_main_offset]);
6449 }
6450 }
6451 }
6452 } else if (!domrec) {
6453 // For now, the sparse-genotype optimization is only considered if
6454 // there are no dosages in the entire .pgen, and
6455 // 'dominant'/'recessive' wasn't specified.
6456 // It's actually straightforward to support domrec
6457 // (modifying difflist_common_geno and raregeno upfront is almost
6458 // enough), but let's get this working first.
6459 const uint32_t difflist_common_geno = S_CAST(int32_t, difflist_common_genos[vidx]);
6460 if (difflist_common_geno != UINT32_MAX) {
6461 const uint32_t difflist_len = difflist_lens[sparse_vidx];
6462 if (difflist_len) {
6463 uint32_t difflist_start_idx = 0;
6464 if (sample_idx_start) {
6465 difflist_start_idx = LowerBoundNonemptyU32(difflist_sample_ids_iter, difflist_len, sample_idx_start);
6466 }
6467 if (difflist_len > difflist_start_idx) {
6468 const uint32_t shard_difflist_len = LowerBoundNonemptyU32(&(difflist_sample_ids_iter[difflist_start_idx]), difflist_len - difflist_start_idx, sample_idx_start + sample_shard_size);
6469 if (shard_difflist_len) {
6470 // Shard contains at least one uncommon genotype, so we have
6471 // some work to do.
6472 if (allele_freqs) {
6473 cur_allele_freq = allele_freqs[vidx];
6474 geno_slope = geno_slopes[vidx];
6475 geno_intercept = geno_intercepts[vidx];
6476 }
6477 uint64_t ddosage_incr_lookup_table[4];
6478 ddosage_incr_lookup_table[0] = 0;
6479 ddosage_incr_lookup_table[1] = kDosageMax;
6480 ddosage_incr_lookup_table[2] = kDosageMax * 2LL;
6481 ddosage_incr_lookup_table[3] = 0;
6482 const uint64_t common_ddosage = ddosage_incr_lookup_table[difflist_common_geno];
6483 if (common_ddosage) {
6484 for (uint32_t uii = 0; uii != 4; ++uii) {
6485 // deliberate underflow
6486 ddosage_incr_lookup_table[uii] -= common_ddosage;
6487 }
6488 }
6489 double dosage_incr_lookup_table[4];
6490 dosage_incr_lookup_table[0] = geno_intercept;
6491 const double geno_incr = kDosageMax * geno_slope;
6492 dosage_incr_lookup_table[1] = geno_incr + geno_intercept;
6493 dosage_incr_lookup_table[2] = dosage_incr_lookup_table[1] + geno_incr;
6494 dosage_incr_lookup_table[3] = 0.0;
6495 if (!no_meanimpute) {
6496 dosage_incr_lookup_table[3] = kDosageMax * 2LL * cur_allele_freq * geno_slope;
6497 }
6498 if (se_mode) {
6499 for (uint32_t uii = 0; uii != 4; ++uii) {
6500 dosage_incr_lookup_table[uii] *= dosage_incr_lookup_table[uii];
6501 }
6502 }
6503 const double common_dosage = dosage_incr_lookup_table[difflist_common_geno];
6504 for (uint32_t uii = 0; uii != 4; ++uii) {
6505 dosage_incr_lookup_table[uii] -= common_dosage;
6506 }
6507
6508 const uint32_t difflist_end_idx = difflist_start_idx + shard_difflist_len;
6509 const uint32_t widx_last = (difflist_end_idx - 1) / kBitsPerWordD2;
6510 uint32_t widx = difflist_start_idx / kBitsPerWordD2;
6511 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids_iter[widx * kBitsPerWordD2]);
6512 uint32_t difflist_idx_lowbits = difflist_start_idx % kBitsPerWordD2;
6513 uint32_t difflist_idx_lowbits_end = kBitsPerWordD2;
6514 if (widx == widx_last) {
6515 difflist_idx_lowbits_end = ModNz(difflist_end_idx, kBitsPerWordD2);
6516 }
6517 uintptr_t raregeno_word = raregeno_iter[widx] >> (2 * difflist_idx_lowbits);
6518 while (1) {
6519 for (; difflist_idx_lowbits != difflist_idx_lowbits_end; ++difflist_idx_lowbits) {
6520 const uintptr_t cur_geno = raregeno_word & 3;
6521 const uint32_t shard_sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits] - sample_idx_start;
6522 uint64_t* ddosage_sum_col_base = &(shard_ddosage_sums[shard_sample_idx]);
6523 const uint64_t cur_ddosage_incr = ddosage_incr_lookup_table[cur_geno];
6524 if (!qsr_ct) {
6525 ddosage_sum_col_base[0] += cur_ddosage_incr;
6526 } else {
6527 const uint32_t variant_uidx = variant_uidxs[vidx];
6528 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
6529 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
6530 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
6531 ddosage_sum_col_base[qsr_idx * sample_ct] += cur_ddosage_incr;
6532 }
6533 }
6534 }
6535 double* final_score_col_iter = &(shard_final_scores_cmaj[shard_sample_idx]);
6536 const double cur_dosage_incr = dosage_incr_lookup_table[cur_geno];
6537 for (uint32_t uii = 0; uii != score_final_col_ct; ++uii) {
6538 *final_score_col_iter += cur_dosage_incr * score_sparse_coefs_vmaj_iter[uii];
6539 final_score_col_iter = &(final_score_col_iter[sample_shard_size]);
6540 }
6541 raregeno_word = raregeno_word >> 2;
6542 }
6543 ++widx;
6544 if (widx >= widx_last) {
6545 if (widx > widx_last) {
6546 break;
6547 }
6548 difflist_idx_lowbits_end = ModNz(difflist_end_idx, kBitsPerWordD2);
6549 }
6550 cur_difflist_sample_ids = &(cur_difflist_sample_ids[kBitsPerWordD2]);
6551 difflist_idx_lowbits = 0;
6552 raregeno_word = raregeno_iter[widx];
6553 }
6554 }
6555 }
6556 }
6557
6558 genovec_iter = &(genovec_iter[sample_ctaw2]);
6559 missing_bitvec_iter = &(missing_bitvec_iter[sample_ctaw]);
6560 missing_male_bitvec_iter = &(missing_male_bitvec_iter[sample_ctaw]);
6561 missing_nonfemale_bitvec_iter = &(missing_nonfemale_bitvec_iter[sample_ctaw]);
6562 score_sparse_coefs_vmaj_iter = &(score_sparse_coefs_vmaj_iter[score_final_col_ct]);
6563 ++sparse_vidx;
6564 raregeno_iter = &(raregeno_iter[raregeno_stride]);
6565 difflist_sample_ids_iter = &(difflist_sample_ids_iter[difflist_sample_ids_stride]);
6566 continue;
6567 }
6568 }
6569 FillDdosageInts(genovec_iter, shard_dosage_present, shard_dosage_main, sample_shard_size, shard_dosage_ct, 1 - is_nonx_haploid, ddosage_incrs);
6570 if (is_y) {
6571 if (shard_female_ct) {
6572 uintptr_t shard_sample_idx_base = 0;
6573 uintptr_t shard_sex_female_collapsed_bits = shard_sex_female_collapsed[0];
6574 for (uint32_t shard_female_idx = 0; shard_female_idx != shard_female_ct; ++shard_female_idx) {
6575 const uintptr_t shard_sample_idx = BitIter1(shard_sex_female_collapsed, &shard_sample_idx_base, &shard_sex_female_collapsed_bits);
6576 ddosage_incrs[shard_sample_idx] = 0;
6577 }
6578 }
6579 } else if (is_relevant_x) {
6580 uintptr_t shard_sample_idx_base = 0;
6581 uintptr_t shard_sex_nonmale_collapsed_inv_bits = ~shard_sex_nonmale_collapsed[0];
6582 for (uint32_t shard_male_idx = 0; shard_male_idx != shard_male_ct; ++shard_male_idx) {
6583 const uintptr_t shard_sample_idx = BitIter0(shard_sex_nonmale_collapsed, &shard_sample_idx_base, &shard_sex_nonmale_collapsed_inv_bits);
6584 ddosage_incrs[shard_sample_idx] /= 2;
6585 }
6586 }
6587 if (domrec) {
6588 if (model_dominant) {
6589 for (uint32_t shard_sample_idx = 0; shard_sample_idx != sample_shard_size; ++shard_sample_idx) {
6590 if (ddosage_incrs[shard_sample_idx] > kDosageMax) {
6591 ddosage_incrs[shard_sample_idx] = kDosageMax;
6592 }
6593 }
6594 } else {
6595 // recessive
6596 for (uint32_t shard_sample_idx = 0; shard_sample_idx != sample_shard_size; ++shard_sample_idx) {
6597 uint64_t cur_ddosage_incr = ddosage_incrs[shard_sample_idx];
6598 if (cur_ddosage_incr <= kDosageMax) {
6599 cur_ddosage_incr = 0;
6600 } else {
6601 cur_ddosage_incr -= kDosageMax;
6602 }
6603 ddosage_incrs[shard_sample_idx] = cur_ddosage_incr;
6604 }
6605 }
6606 }
6607 if (!qsr_ct) {
6608 for (uint32_t shard_sample_idx = 0; shard_sample_idx != sample_shard_size; ++shard_sample_idx) {
6609 shard_ddosage_sums[shard_sample_idx] += ddosage_incrs[shard_sample_idx];
6610 }
6611 } else {
6612 const uint32_t variant_uidx = variant_uidxs[vidx];
6613 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
6614 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
6615 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
6616 uint64_t* cur_ddosage_sums = &(shard_ddosage_sums[qsr_idx * sample_ct]);
6617 for (uint32_t shard_sample_idx = 0; shard_sample_idx != sample_shard_size; ++shard_sample_idx) {
6618 cur_ddosage_sums[shard_sample_idx] += ddosage_incrs[shard_sample_idx];
6619 }
6620 }
6621 }
6622 }
6623 if (allele_freqs) {
6624 cur_allele_freq = allele_freqs[vidx];
6625 geno_slope = geno_slopes[vidx];
6626 geno_intercept = geno_intercepts[vidx];
6627 }
6628 if ((!shard_dosage_ct) && (!is_nonx_haploid) && (!is_relevant_x)) {
6629 // Fast path for common no-dosage case.
6630 // (We wait till this point to branch since the shard_ddosage_sums
6631 // update isn't that expensive.)
6632 double lookup_table[32] ALIGNV16;
6633 lookup_table[0] = geno_intercept;
6634 const double geno_incr = kDosageMax * geno_slope;
6635 const double geno_one = geno_incr + geno_intercept;
6636 if (!domrec) {
6637 lookup_table[2] = geno_one;
6638 lookup_table[4] = geno_incr + geno_one;
6639 } else {
6640 lookup_table[2] = model_dominant? geno_one : geno_intercept;
6641 lookup_table[4] = geno_one;
6642 }
6643 lookup_table[6] = 0.0;
6644 if (!no_meanimpute) {
6645 double missing_effect = kDosageMax * cur_allele_freq * geno_slope;
6646 if (!domrec) {
6647 missing_effect *= 2;
6648 }
6649 lookup_table[6] = missing_effect;
6650 }
6651 if (se_mode) {
6652 lookup_table[0] *= lookup_table[0];
6653 lookup_table[2] *= lookup_table[2];
6654 lookup_table[4] *= lookup_table[4];
6655 lookup_table[6] *= lookup_table[6];
6656 }
6657 InitLookup16x8bx2(lookup_table);
6658 GenoarrLookup16x8bx2(genovec_iter, lookup_table, sample_shard_size, dosages_vmaj_iter);
6659 } else {
6660 const uint32_t shard_missing_ct = PopcountWords(missing_bitvec_iter, shard_sizel);
6661 if (shard_missing_ct) {
6662 double missing_effect = 0.0;
6663 if (!no_meanimpute) {
6664 missing_effect = kDosageMax * cur_allele_freq * geno_slope;
6665 }
6666 if (is_y) {
6667 ZeroDArr(sample_shard_size, dosages_vmaj_iter);
6668 if ((!no_meanimpute) && shard_nonfemale_ct) {
6669 for (uint32_t shard_widx = 0; shard_widx != shard_sizel; ++shard_widx) {
6670 uintptr_t cur_missing_nonfemale_bits = missing_nonfemale_bitvec_iter[shard_widx];
6671 if (!cur_missing_nonfemale_bits) {
6672 continue;
6673 }
6674 double* cur_dosages_vmaj_iter = &(dosages_vmaj_iter[shard_widx * kBitsPerWord]);
6675 do {
6676 const uint32_t sample_idx_lowbits = ctzw(cur_missing_nonfemale_bits);
6677 cur_dosages_vmaj_iter[sample_idx_lowbits] = missing_effect;
6678 cur_missing_nonfemale_bits &= cur_missing_nonfemale_bits - 1;
6679 } while (cur_missing_nonfemale_bits);
6680 }
6681 }
6682 } else if (is_relevant_x) {
6683 ZeroDArr(sample_shard_size, dosages_vmaj_iter);
6684 if (!no_meanimpute) {
6685 if (shard_male_ct) {
6686 for (uint32_t shard_widx = 0; shard_widx != shard_sizel; ++shard_widx) {
6687 uintptr_t cur_missing_male_bits = missing_male_bitvec_iter[shard_widx];
6688 if (!cur_missing_male_bits) {
6689 continue;
6690 }
6691 double* cur_dosages_vmaj_iter = &(dosages_vmaj_iter[shard_widx * kBitsPerWord]);
6692 do {
6693 const uint32_t sample_idx_lowbits = ctzw(cur_missing_male_bits);
6694 cur_dosages_vmaj_iter[sample_idx_lowbits] = missing_effect;
6695 cur_missing_male_bits &= cur_missing_male_bits - 1;
6696 } while (cur_missing_male_bits);
6697 }
6698 }
6699 if (shard_nonmale_ct) {
6700 missing_effect *= 2;
6701 for (uint32_t shard_widx = 0; shard_widx != shard_sizel; ++shard_widx) {
6702 uintptr_t cur_missing_nonmale_bits = missing_bitvec_iter[shard_widx] & shard_sex_nonmale_collapsed[shard_widx];
6703 if (!cur_missing_nonmale_bits) {
6704 continue;
6705 }
6706 double* cur_dosages_vmaj_iter = &(dosages_vmaj_iter[shard_widx * kBitsPerWord]);
6707 do {
6708 const uint32_t sample_idx_lowbits = ctzw(cur_missing_nonmale_bits);
6709 cur_dosages_vmaj_iter[sample_idx_lowbits] = missing_effect;
6710 cur_missing_nonmale_bits &= cur_missing_nonmale_bits - 1;
6711 } while (cur_missing_nonmale_bits);
6712 }
6713 }
6714 }
6715 } else {
6716 const double ploidy_d = ploidy_m1s[vidx]? 2.0 : 1.0;
6717 missing_effect *= ploidy_d;
6718 uintptr_t shard_sample_idx_base = 0;
6719 uintptr_t missing_bits = missing_bitvec_iter[0];
6720 for (uint32_t missing_idx = 0; missing_idx != shard_missing_ct; ++missing_idx) {
6721 const uintptr_t shard_sample_idx = BitIter1(missing_bitvec_iter, &shard_sample_idx_base, &missing_bits);
6722 dosages_vmaj_iter[shard_sample_idx] = missing_effect;
6723 }
6724 }
6725 }
6726 const uint32_t shard_nm_sample_ct = sample_shard_size - shard_missing_ct;
6727 uintptr_t shard_sample_idx_base = 0;
6728 uintptr_t missing_inv_bits = ~missing_bitvec_iter[0];
6729 for (uint32_t shard_nm_sample_idx = 0; shard_nm_sample_idx != shard_nm_sample_ct; ++shard_nm_sample_idx) {
6730 const uintptr_t shard_sample_idx = BitIter0(missing_bitvec_iter, &shard_sample_idx_base, &missing_inv_bits);
6731 dosages_vmaj_iter[shard_sample_idx] = u63tod(ddosage_incrs[shard_sample_idx]) * geno_slope + geno_intercept;
6732 }
6733 if (se_mode) {
6734 // Suppose our score coefficients are drawn from independent
6735 // Gaussians. Then the variance of the final score average is the
6736 // sum of the variances of the individual terms, divided by (T^2)
6737 // where T is the number of terms. These individual variances are
6738 // of the form (<genotype value> * <stdev>)^2.
6739 //
6740 // Thus, we can use the same inner loop to compute standard errors,
6741 // as long as
6742 // 1. we square the genotypes and the standard errors before
6743 // matrix multiplication, and
6744 // 2. we take the square root of the sums at the end.
6745 for (uint32_t shard_sample_idx = 0; shard_sample_idx != sample_shard_size; ++shard_sample_idx) {
6746 dosages_vmaj_iter[shard_sample_idx] *= dosages_vmaj_iter[shard_sample_idx];
6747 }
6748 }
6749 }
6750 dosages_vmaj_iter = &(dosages_vmaj_iter[sample_shard_size]);
6751
6752 genovec_iter = &(genovec_iter[sample_ctaw2]);
6753 missing_bitvec_iter = &(missing_bitvec_iter[sample_ctaw]);
6754 missing_male_bitvec_iter = &(missing_male_bitvec_iter[sample_ctaw]);
6755 missing_nonfemale_bitvec_iter = &(missing_nonfemale_bitvec_iter[sample_ctaw]);
6756 if (dosage_present_iter) {
6757 dosage_present_iter = &(dosage_present_iter[sample_ctaw]);
6758 dosage_main_iter = &(dosage_main_iter[dosage_main_stride]);
6759 }
6760 }
6761
6762 const uint32_t dense_variant_ct = cur_variant_batch_size - sparse_vidx;
6763 if (dense_variant_ct) {
6764 const double* score_dense_coefs_cmaj = ctx->score_dense_coefs_cmaj[parity];
6765 RowMajorMatrixMultiplyStridedIncr(score_dense_coefs_cmaj, dosages_vmaj, score_final_col_ct, kScoreVariantBlockSize, sample_shard_size, sample_shard_size, dense_variant_ct, sample_shard_size, shard_final_scores_cmaj);
6766 }
6767 }
6768 parity = 1 - parity;
6769 } while (!THREAD_BLOCK_FINISH(arg));
6770 THREAD_RETURN;
6771 }
6772
6773 typedef struct ParsedQscoreRangeStruct {
6774 char* range_name;
6775 double lbound;
6776 double ubound;
6777 } ParsedQscoreRange;
6778
6779 PglErr ScoreReport(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, 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 double* allele_freqs, const ScoreInfo* score_info_ptr, const char* output_missing_pheno, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t nosex_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_variant_id_slen, uint32_t xchr_model, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) {
6780 unsigned char* bigstack_mark = g_bigstack_base;
6781 unsigned char* bigstack_end_mark = g_bigstack_end;
6782 uintptr_t line_idx = 0;
6783 const char* cur_input_fname = nullptr;
6784 char* cswritep = nullptr;
6785 FILE* score_tmpfile = nullptr;
6786 PglErr reterr = kPglRetSuccess;
6787 TextStream score_txs;
6788 ThreadGroup tg;
6789 CompressStreamState css;
6790 PreinitTextStream(&score_txs);
6791 PreinitThreads(&tg);
6792 PreinitCstream(&css);
6793 {
6794 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
6795 if (!xchr_model) {
6796 uint32_t x_code;
6797 if (XymtExists(cip, kChrOffsetX, &x_code)) {
6798 uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
6799 uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx];
6800 uint32_t x_end = cip->chr_fo_vidx_start[x_chr_fo_idx + 1];
6801 if (!AllBitsAreZero(variant_include, x_start, x_end)) {
6802 uintptr_t* variant_include_no_x;
6803 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_no_x))) {
6804 goto ScoreReport_ret_NOMEM;
6805 }
6806 memcpy(variant_include_no_x, variant_include, raw_variant_ctl * sizeof(intptr_t));
6807 ClearBitsNz(x_start, x_end, variant_include_no_x);
6808 variant_include = variant_include_no_x;
6809 }
6810 }
6811 } else if (xchr_model == 2) {
6812 xchr_model = 0;
6813 }
6814 // now xchr_model is set iff it's 1
6815
6816 const ScoreFlags flags = score_info_ptr->flags;
6817 const uint32_t multi_input = (flags / kfScoreMultiInput) & 1;
6818 if (multi_input) {
6819 assert(!(flags & (kfScoreListVariants | kfScoreColNallele | kfScoreColDenom | kfScoreColDosageSum)));
6820 }
6821 const uint32_t output_zst = (flags / kfScoreZs) & 1;
6822 uint32_t* variant_id_htable = nullptr;
6823 uint32_t variant_id_htable_size = 0;
6824 uint32_t* variant_include_cumulative_popcounts = nullptr;
6825 uintptr_t* qsr_include = nullptr;
6826 char** range_names = nullptr;
6827 uintptr_t qsr_ct = 0;
6828 if (multi_input || score_info_ptr->qsr_range_fname) {
6829 // Limit this to ~1/8 of available memory, since memory may be tight.
6830 variant_id_htable_size = GetHtableFastSize(variant_ct);
6831 const uintptr_t htable_size_limit = bigstack_left() / (8 * sizeof(int32_t));
6832 if (variant_id_htable_size > htable_size_limit) {
6833 variant_id_htable_size = htable_size_limit;
6834 const uint32_t htable_size_min = GetHtableMinSize(variant_ct);
6835 if (htable_size_min > variant_id_htable_size) {
6836 variant_id_htable_size = htable_size_min;
6837 }
6838 }
6839 if (unlikely(bigstack_alloc_u32(variant_id_htable_size, &variant_id_htable))) {
6840 goto ScoreReport_ret_NOMEM;
6841 }
6842 reterr = PopulateIdHtableMt(nullptr, variant_include, variant_ids, variant_ct, 0, variant_id_htable_size, max_thread_ct, nullptr, variant_id_htable, nullptr);
6843 if (unlikely(reterr)) {
6844 goto ScoreReport_ret_1;
6845 }
6846 }
6847 if (score_info_ptr->qsr_range_fname) {
6848 // Strictly speaking, textFILE would be more appropriate for the range
6849 // file since it should be tiny, but it doesn't really matter.
6850 // We still reserve bigstack_left() / 8 for the line-buffer since the
6851 // data file usually contains allele codes, and we use TextRetarget()
6852 // below to use the buffer allocated here for the data file too (and for
6853 // the score file later).
6854 reterr = SizeAndInitTextStream(score_info_ptr->qsr_range_fname, bigstack_left() / 8, 1, &score_txs);
6855 if (unlikely(reterr)) {
6856 goto ScoreReport_ret_QSR_RANGE_TSTREAM_FAIL;
6857 }
6858 unsigned char* bigstack_mark2 = g_bigstack_base;
6859 // strlen("<prefix>.<range name>.sscore[.zst]") < kPglFnamesize
6860 const uint32_t max_name_slen = kPglFnamesize - S_CAST(uintptr_t, outname_end - outname) - 9 - output_zst * 4;
6861 ParsedQscoreRange* parsed_qscore_ranges = R_CAST(ParsedQscoreRange*, g_bigstack_base);
6862 unsigned char* tmp_alloc_end = g_bigstack_end;
6863 uintptr_t miss_ct = 0;
6864 while (1) {
6865 ++line_idx;
6866 const char* line_start = TextGet(&score_txs);
6867 if (!line_start) {
6868 if (likely(!TextStreamErrcode2(&score_txs, &reterr))) {
6869 break;
6870 }
6871 goto ScoreReport_ret_QSR_RANGE_TSTREAM_FAIL;
6872 }
6873 // range name, p-value lower bound, p-value upper bound
6874 const char* range_name_end = CurTokenEnd(line_start);
6875 const char* lbound_start = FirstNonTspace(range_name_end);
6876 double lbound;
6877 // PLINK 1.9 documentation promises that lines with too few entries or
6878 // nonnumeric values in the second and third column are ignored.
6879 const char* lbound_end = ScantokDouble(lbound_start, &lbound);
6880 if (!lbound_end) {
6881 continue;
6882 }
6883 const char* ubound_start = FirstNonTspace(lbound_end);
6884 double ubound;
6885 const char* ubound_end = ScantokDouble(ubound_start, &ubound);
6886 if (!ubound_end) {
6887 continue;
6888 }
6889 if (unlikely(lbound > ubound)) {
6890 snprintf(g_logbuf, kLogbufSize, "Error: Upper bound < lower bound on line %" PRIuPTR " of --q-score-range range file.\n", line_idx);
6891 goto ScoreReport_ret_MALFORMED_INPUT_WW;
6892 }
6893 const uint32_t name_slen = range_name_end - line_start;
6894 if (name_slen > max_name_slen) {
6895 snprintf(g_logbuf, kLogbufSize, "Error: Name too long on line %" PRIuPTR " of --q-score-range range file.\n", line_idx);
6896 }
6897 unsigned char* tmp_alloc_base = R_CAST(unsigned char*, &(parsed_qscore_ranges[qsr_ct]));
6898 if (S_CAST(uintptr_t, tmp_alloc_end - tmp_alloc_base) <= name_slen + sizeof(ParsedQscoreRange)) {
6899 goto ScoreReport_ret_NOMEM;
6900 }
6901 tmp_alloc_end -= name_slen + 1;
6902 char* stored_name = R_CAST(char*, tmp_alloc_end);
6903 memcpyx(stored_name, line_start, name_slen, '\0');
6904 parsed_qscore_ranges[qsr_ct].range_name = stored_name;
6905 parsed_qscore_ranges[qsr_ct].lbound = lbound;
6906 parsed_qscore_ranges[qsr_ct].ubound = ubound;
6907 ++qsr_ct;
6908 }
6909 if (unlikely(!qsr_ct)) {
6910 logerrputs("Error: Empty --q-score-range range file.\n");
6911 goto ScoreReport_ret_INCONSISTENT_INPUT;
6912 }
6913 BigstackEndSet(tmp_alloc_end);
6914 if (unlikely(BigstackBaseSetChecked(&(parsed_qscore_ranges[qsr_ct])))) {
6915 goto ScoreReport_ret_NOMEM;
6916 }
6917 #ifndef LAPACK_ILP64
6918 if (unlikely(qsr_ct > (0x7fffffff / kScoreVariantBlockSize))) {
6919 logerrputs("Error: --q-score-range range count too large for this " PROG_NAME_STR " build. If this is\nreally the computation you want, use a " PROG_NAME_STR " build with large-matrix support.\n");
6920 goto ScoreReport_ret_INCONSISTENT_INPUT;
6921 }
6922 # ifndef __LP64__
6923 const uint64_t bit_ct = S_CAST(uint64_t, qsr_ct) * variant_ct;
6924 if (unlikely(bit_ct > 0xffffffffU)) {
6925 goto ScoreReport_ret_NOMEM;
6926 }
6927 # endif
6928 #endif
6929 if (unlikely(bigstack_end_alloc_u32(raw_variant_ctl, &variant_include_cumulative_popcounts) ||
6930 bigstack_end_calloc_w(BitCtToWordCt(S_CAST(uint64_t, qsr_ct) * variant_ct), &qsr_include) ||
6931 bigstack_end_alloc_cp(qsr_ct, &range_names))) {
6932 goto ScoreReport_ret_NOMEM;
6933 }
6934 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
6935 range_names[qsr_idx] = parsed_qscore_ranges[qsr_idx].range_name;
6936 }
6937 const uint32_t variant_ctl = BitCtToWordCt(variant_ct);
6938 uintptr_t* already_seen;
6939 if (unlikely(bigstack_calloc_w(variant_ctl, &already_seen))) {
6940 goto ScoreReport_ret_NOMEM;
6941 }
6942 FillCumulativePopcounts(variant_include, raw_variant_ctl, variant_include_cumulative_popcounts);
6943 reterr = TextRetarget(score_info_ptr->qsr_data_fname, &score_txs);
6944 if (unlikely(reterr)) {
6945 goto ScoreReport_ret_QSR_RANGE_TSTREAM_FAIL;
6946 }
6947 const uint32_t colid_first = (score_info_ptr->qsr_varid_col_p1 < score_info_ptr->qsr_val_col_p1);
6948 uint32_t colmin;
6949 uint32_t coldiff;
6950 if (colid_first) {
6951 colmin = score_info_ptr->qsr_varid_col_p1 - 1;
6952 coldiff = score_info_ptr->qsr_val_col_p1 - score_info_ptr->qsr_varid_col_p1;
6953 } else {
6954 colmin = score_info_ptr->qsr_val_col_p1 - 1;
6955 coldiff = score_info_ptr->qsr_varid_col_p1 - score_info_ptr->qsr_val_col_p1;
6956 }
6957 line_idx = 0;
6958 miss_ct = 0;
6959 if (flags & kfScoreQsrHeader) {
6960 ++line_idx;
6961 if (unlikely(!TextGet(&score_txs))) {
6962 if (!TextStreamErrcode2(&score_txs, &reterr)) {
6963 logerrputs("Error: Empty --q-score-range data file.\n");
6964 goto ScoreReport_ret_MALFORMED_INPUT;
6965 }
6966 goto ScoreReport_ret_QSR_DATA_TSTREAM_FAIL;
6967 }
6968 }
6969 double* min_vals = nullptr;
6970 if (flags & kfScoreQsrMin) {
6971 // something like this is needed to handle --glm output for
6972 // multiallelic variants.
6973 // (possible todo: --glm modifier which requests all-allele joint tests
6974 // for multiallelic variants)
6975 if (unlikely(bigstack_alloc_d(variant_ct, &min_vals))) {
6976 goto ScoreReport_ret_NOMEM;
6977 }
6978 }
6979 while (1) {
6980 ++line_idx;
6981 const char* line_start = TextGet(&score_txs);
6982 if (!line_start) {
6983 if (likely(!TextStreamErrcode2(&score_txs, &reterr))) {
6984 break;
6985 }
6986 goto ScoreReport_ret_QSR_DATA_TSTREAM_FAIL;
6987 }
6988 const char* colid_ptr;
6989 const char* colval_ptr;
6990 if (colid_first) {
6991 colid_ptr = NextTokenMult0(line_start, colmin);
6992 colval_ptr = NextTokenMult(colid_ptr, coldiff);
6993 if (unlikely(!colval_ptr)) {
6994 goto ScoreReport_ret_QSR_DATA_MISSING_TOKENS;
6995 }
6996 } else {
6997 colval_ptr = NextTokenMult0(line_start, colmin);
6998 colid_ptr = NextTokenMult(colval_ptr, coldiff);
6999 if (unlikely(!colid_ptr)) {
7000 goto ScoreReport_ret_QSR_DATA_MISSING_TOKENS;
7001 }
7002 }
7003 const uint32_t varid_slen = strlen_se(colid_ptr);
7004 const uint32_t variant_uidx = VariantIdDupflagHtableFind(colid_ptr, variant_ids, variant_id_htable, varid_slen, variant_id_htable_size, max_variant_id_slen);
7005 if ((variant_uidx >> 31) || (!IsSet(variant_include, variant_uidx))) {
7006 ++miss_ct;
7007 continue;
7008 }
7009 double cur_val;
7010 if (!ScantokDouble(colval_ptr, &cur_val)) {
7011 // Tolerate NA without erroring out. (Could count this as seen, but
7012 // that would force the min_vals logic to be more complicated.)
7013 const char* colval_end = CurTokenEnd(colval_ptr);
7014 if (likely(IsNanStr(colval_ptr, colval_end - colval_ptr))) {
7015 continue;
7016 }
7017 *K_CAST(char*, colval_end) = '\0';
7018 logerrprintfww("Error: Invalid value '%s' on line %" PRIuPTR " of --q-score-range data file.\n", colval_ptr, line_idx);
7019 goto ScoreReport_ret_MALFORMED_INPUT;
7020 }
7021 const uint32_t variant_idx = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx);
7022 const uintptr_t bit_idx_base = variant_idx * qsr_ct;
7023 if (min_vals) {
7024 if (IsSet(already_seen, variant_idx)) {
7025 if (min_vals[variant_idx] <= cur_val) {
7026 continue;
7027 }
7028 ClearBitsNz(bit_idx_base, bit_idx_base + qsr_ct, qsr_include);
7029 }
7030 min_vals[variant_idx] = cur_val;
7031 } else {
7032 if (IsSet(already_seen, variant_idx)) {
7033 logerrprintfww("Error: Duplicate variant ID '%s' in --q-score-range data file. (Add the 'min' modifier if this is a multiallelic variant that you want to use the minimum p-value for.)\n", variant_ids[variant_uidx]);
7034 goto ScoreReport_ret_MALFORMED_INPUT;
7035 }
7036 }
7037 SetBit(variant_idx, already_seen);
7038 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7039 if ((cur_val < parsed_qscore_ranges[qsr_idx].lbound) || (cur_val > parsed_qscore_ranges[qsr_idx].ubound)) {
7040 continue;
7041 }
7042 SetBit(bit_idx_base + qsr_idx, qsr_include);
7043 }
7044 }
7045 const uint32_t qsr_variant_ct = PopcountWords(already_seen, variant_ctl);
7046 if (unlikely(!qsr_variant_ct)) {
7047 logerrputs("Error: No valid entries in --q-score-range data file.\n");
7048 goto ScoreReport_ret_INCONSISTENT_INPUT;
7049 }
7050 logprintf("--q-score-range: %" PRIuPTR " range%s and %u variant%s loaded.\n", qsr_ct, (qsr_ct == 1)? "" : "s", qsr_variant_ct, (qsr_variant_ct == 1)? "" : "s");
7051 if (miss_ct) {
7052 logerrprintf("Warning: %" PRIuPTR " line%s skipped in --q-score-range data file.\n", miss_ct, (miss_ct == 1)? "" : "s");
7053 }
7054 // possible todo: replace variant_include with already_seen, and compact
7055 // qsr_include.
7056 // but for now, we just free already_seen, and in the common use cases
7057 // this should be fine.
7058 reterr = TextRetarget(score_info_ptr->input_fname, &score_txs);
7059 if (unlikely(reterr)) {
7060 cur_input_fname = score_info_ptr->input_fname;
7061 goto ScoreReport_ret_TSTREAM_FAIL;
7062 }
7063 BigstackReset(bigstack_mark2);
7064 line_idx = 0;
7065 } else {
7066 reterr = SizeAndInitTextStream(score_info_ptr->input_fname, bigstack_left() / 8, 1, &score_txs);
7067 if (unlikely(reterr)) {
7068 cur_input_fname = score_info_ptr->input_fname;
7069 goto ScoreReport_ret_TSTREAM_FAIL;
7070 }
7071 }
7072
7073 uint32_t varid_col_idx = score_info_ptr->varid_col_p1 - 1;
7074 uint32_t allele_col_idx = score_info_ptr->allele_col_p1 - 1;
7075 uint32_t relevant_col_idx_end = MAXV(varid_col_idx, allele_col_idx);
7076 uint32_t* score_col_idx_deltas = nullptr;
7077 uintptr_t score_col_ct = 1;
7078 if (!score_info_ptr->input_col_idx_range_list.name_ct) {
7079 // catch edge case
7080 const uint32_t score_col_idx = allele_col_idx + 1;
7081 if (unlikely(score_col_idx == varid_col_idx)) {
7082 logerrprintf("Error: --score%s variant ID column index matches a coefficient column index.\n", multi_input? "-list" : "");
7083 goto ScoreReport_ret_INVALID_CMDLINE;
7084 }
7085 relevant_col_idx_end += (score_col_idx > varid_col_idx);
7086 if (unlikely(bigstack_alloc_u32(1, &score_col_idx_deltas))) {
7087 goto ScoreReport_ret_NOMEM;
7088 }
7089 score_col_idx_deltas[0] = score_col_idx;
7090 } else {
7091 const uint32_t range_list_max = NumericRangeListMax(&(score_info_ptr->input_col_idx_range_list));
7092 if (range_list_max > relevant_col_idx_end) {
7093 relevant_col_idx_end = range_list_max;
7094 }
7095 unsigned char* bigstack_end_mark2 = g_bigstack_end;
7096 const uint32_t last_col_idxl = BitCtToWordCt(relevant_col_idx_end);
7097 uintptr_t* score_col_bitarr;
7098 if (unlikely(bigstack_end_calloc_w(last_col_idxl, &score_col_bitarr))) {
7099 goto ScoreReport_ret_NOMEM;
7100 }
7101 if (unlikely(NumericRangeListToBitarr(&(score_info_ptr->input_col_idx_range_list), relevant_col_idx_end, 1, 0, score_col_bitarr))) {
7102 goto ScoreReport_ret_MISSING_TOKENS;
7103 }
7104 if (unlikely(IsSet(score_col_bitarr, varid_col_idx))) {
7105 logerrprintf("Error: --score%s variant ID column index matches a coefficient column index.\n", multi_input? "-list" : "");
7106 goto ScoreReport_ret_INVALID_CMDLINE;
7107 }
7108 if (unlikely(IsSet(score_col_bitarr, allele_col_idx))) {
7109 logerrprintf("Error: --score%s allele column index matches a coefficient column index.\n", multi_input? "-list" : "");
7110 goto ScoreReport_ret_INVALID_CMDLINE;
7111 }
7112 score_col_ct = PopcountWords(score_col_bitarr, last_col_idxl);
7113 if (unlikely(bigstack_alloc_u32(score_col_ct, &score_col_idx_deltas))) {
7114 goto ScoreReport_ret_NOMEM;
7115 }
7116 uintptr_t col_uidx_base = 0;
7117 uintptr_t score_col_bitarr_bits = score_col_bitarr[0];
7118 for (uintptr_t score_col_idx = 0; score_col_idx != score_col_ct; ++score_col_idx) {
7119 const uint32_t col_uidx = BitIter1(score_col_bitarr, &col_uidx_base, &score_col_bitarr_bits);
7120 score_col_idx_deltas[score_col_idx] = col_uidx;
7121 }
7122 // now convert to deltas
7123 for (uintptr_t score_col_idx = score_col_ct - 1; score_col_idx; --score_col_idx) {
7124 score_col_idx_deltas[score_col_idx] -= score_col_idx_deltas[score_col_idx - 1];
7125 }
7126 BigstackEndReset(bigstack_end_mark2);
7127 }
7128
7129 LlStr* fname_iter = nullptr;
7130 uint32_t infile_ct = 1;
7131 if (multi_input) {
7132 reterr = ScoreListLoad(score_info_ptr->input_fname, &score_txs, &fname_iter, &infile_ct);
7133 if (unlikely(reterr)) {
7134 goto ScoreReport_ret_1;
7135 }
7136 } else {
7137 const uint32_t fname_blen = strlen(score_info_ptr->input_fname) + 1;
7138 if (unlikely(bigstack_alloc_llstr(fname_blen, &fname_iter))) {
7139 goto ScoreReport_ret_NOMEM;
7140 }
7141 fname_iter->next = nullptr;
7142 memcpy(fname_iter->str, score_info_ptr->input_fname, fname_blen);
7143 }
7144
7145 uintptr_t score_final_col_ct = score_col_ct;
7146 if (qsr_ct) {
7147 const uint64_t prod = S_CAST(uint64_t, qsr_ct) * score_col_ct;
7148 if (prod > 0x7fffffff) {
7149 // little point in supporting this even in large-matrix build
7150 logerrputs("Error: <--score[-list] column count> * <--q-score-range range count> too large.\n");
7151 goto ScoreReport_ret_INCONSISTENT_INPUT;
7152 }
7153 #ifndef LAPACK_ILP64
7154 if (unlikely(prod > (0x7fffffff / kScoreVariantBlockSize))) {
7155 logerrputs("Error: <--score[-list] column count> * <--q-score-range range count> too large\nfor this " PROG_NAME_STR " build. If this is really the computation you want, use a\n" PROG_NAME_STR "\nbuild with large-matrix support.\n");
7156 goto ScoreReport_ret_INCONSISTENT_INPUT;
7157 }
7158 #endif
7159 score_final_col_ct = qsr_ct * score_col_ct;
7160 #ifndef LAPACK_ILP64
7161 } else {
7162 if (unlikely(score_final_col_ct > (0x7fffffff / kScoreVariantBlockSize))) {
7163 logerrputs("Error: --score[-list] column count too large for this " PROG_NAME_STR " build. If this is\nreally the computation you want, use a " PROG_NAME_STR " build with large-matrix support.\n");
7164 goto ScoreReport_ret_INCONSISTENT_INPUT;
7165 }
7166 #endif
7167 }
7168 const uint32_t calc_thread_ct = MAXV(1, max_thread_ct - 1);
7169 uint32_t sample_shard_size;
7170 uint32_t sample_shard_ct;
7171 if (sample_ct <= calc_thread_ct * kScoreSampleShardSizeAlign) {
7172 sample_shard_size = kScoreSampleShardSizeAlign;
7173 sample_shard_ct = DivUp(sample_ct, kScoreSampleShardSizeAlign);
7174 } else {
7175 sample_shard_size = kScoreSampleShardSizeAlign * DivUp(sample_ct, calc_thread_ct * kScoreSampleShardSizeAlign);
7176 sample_shard_ct = DivUp(sample_ct, sample_shard_size);
7177 }
7178 #ifndef LAPACK_ILP64
7179 if (unlikely(score_final_col_ct * sample_shard_size > 0x7fffffff)) {
7180 logerrputs("Error: <--score[-list] column count> * <sample count> too large for this " PROG_NAME_STR "\nbuild. If this is really the computation you want, use a " PROG_NAME_STR " build with\nlarge-matrix support.\n");
7181 goto ScoreReport_ret_INCONSISTENT_INPUT;
7182 }
7183 #endif
7184 const uint32_t sample_shard_ct_m1 = sample_shard_ct - 1;
7185 CalcScoreCtx ctx;
7186 ctx.variant_include = qsr_ct? variant_include : nullptr;
7187 ctx.variant_include_cumulative_popcounts = variant_include_cumulative_popcounts;
7188 ctx.qsr_include = qsr_include;
7189 ctx.score_final_col_ct = score_final_col_ct;
7190 ctx.sample_shard_size = sample_shard_size;
7191 ctx.sample_ct = sample_ct;
7192 ctx.flags = flags;
7193 ctx.qsr_ct = qsr_ct;
7194 ctx.cur_variant_batch_size = kScoreVariantBlockSize;
7195 if (unlikely(SetThreadCt(sample_shard_ct, &tg))) {
7196 goto ScoreReport_ret_NOMEM;
7197 }
7198 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
7199 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
7200 const uint32_t sample_ctaw2 = NypCtToAlignedWordCt(sample_ct);
7201 const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct);
7202 const uintptr_t dosage_main_stride = RoundUpPow2(sample_ct, kDosagePerVec);
7203 const uint32_t acc1_vec_ct = BitCtToVecCt(sample_ct);
7204 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
7205 const uint32_t acc8_vec_ct = acc1_vec_ct * 8;
7206 const uint32_t write_score_avgs = (flags / kfScoreColScoreAvgs) & 1;
7207 const uint32_t write_score_sums = (flags / kfScoreColScoreSums) & 1;
7208 if (unlikely(S_CAST(uint64_t, score_col_ct) * infile_ct > 0x7fffff)) {
7209 goto ScoreReport_ret_TOO_MANY_COLUMNS;
7210 }
7211 const uintptr_t global_score_col_ct = score_col_ct * infile_ct;
7212 const uintptr_t overflow_buf_size = RoundUpPow2((global_score_col_ct * (write_score_avgs + write_score_sums) + pheno_ct) * 16 + 3 * kMaxIdSlen + kCompressStreamBlock + 64, kCacheline);
7213 if (unlikely(overflow_buf_size > S_CAST(uintptr_t, kMaxLongLine) + S_CAST(uintptr_t, kCompressStreamBlock))) {
7214 goto ScoreReport_ret_TOO_MANY_COLUMNS;
7215 }
7216 uintptr_t overflow_buf_alloc = overflow_buf_size;
7217 if (flags & (kfScoreZs | kfScoreListVariantsZs)) {
7218 overflow_buf_alloc += CstreamWkspaceReq(overflow_buf_size);
7219 }
7220 uintptr_t raw_allele_ct = 2 * raw_variant_ct;
7221 if (allele_idx_offsets) {
7222 raw_allele_ct = allele_idx_offsets[raw_variant_ct];
7223 }
7224 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
7225 const uintptr_t qsr_ct_nz = qsr_ct + (qsr_ct == 0);
7226 uint32_t* sample_include_cumulative_popcounts = nullptr;
7227 uintptr_t* sex_nonmale_collapsed = nullptr;
7228 VecW* missing_diploid_accx = nullptr;
7229 VecW* missing_haploid_accx = nullptr;
7230 uint32_t* allele_ct_bases;
7231 uint32_t* male_allele_ct_decrs;
7232 uint32_t* nonfemale_allele_ct_incrs;
7233 uint32_t* variant_ct_rems;
7234 uint32_t* variant_hap_ct_rems;
7235 uintptr_t* already_seen_variants;
7236 uintptr_t* already_seen_alleles;
7237 double* tmpfile_buf;
7238 char* overflow_buf = nullptr;
7239 if (unlikely(bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw2, &ctx.genovecs[0]) ||
7240 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw2, &ctx.genovecs[1]) ||
7241 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_bitvecs[0]) ||
7242 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_bitvecs[1]) ||
7243 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_male_bitvecs[0]) ||
7244 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_male_bitvecs[1]) ||
7245 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_nonfemale_bitvecs[0]) ||
7246 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.missing_nonfemale_bitvecs[1]) ||
7247 bigstack_alloc_d(kScoreVariantBlockSize * score_final_col_ct, &(ctx.score_dense_coefs_cmaj[0])) ||
7248 bigstack_alloc_d(kScoreVariantBlockSize * score_final_col_ct, &(ctx.score_dense_coefs_cmaj[1])) ||
7249 bigstack_alloc_dp(sample_shard_ct, &ctx.sharded_final_scores_cmaj) ||
7250 bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) ||
7251 bigstack_alloc_w(sample_ctl, &sex_nonmale_collapsed) ||
7252 bigstack_end_clalloc_v(11 * acc4_vec_ct * qsr_ct_nz, &missing_diploid_accx) ||
7253 bigstack_end_clalloc_v(11 * acc4_vec_ct * qsr_ct_nz, &missing_haploid_accx) ||
7254 bigstack_alloc_u32(qsr_ct_nz, &allele_ct_bases) ||
7255 bigstack_alloc_u32(qsr_ct_nz, &male_allele_ct_decrs) ||
7256 bigstack_alloc_u32(qsr_ct_nz, &nonfemale_allele_ct_incrs) ||
7257 bigstack_alloc_u32(qsr_ct_nz * 2, &variant_ct_rems) ||
7258 bigstack_alloc_u32(qsr_ct_nz * 2, &variant_hap_ct_rems) ||
7259 bigstack_alloc_u64p(sample_shard_ct, &ctx.ddosage_incrs) ||
7260 bigstack_alloc_dp(sample_shard_ct, &ctx.dosages_vmaj) ||
7261 bigstack_alloc_u64(qsr_ct_nz * sample_ct, &ctx.ddosage_sums) ||
7262 bigstack_alloc_w(raw_variant_ctl, &already_seen_variants) ||
7263 bigstack_alloc_w(raw_allele_ctl, &already_seen_alleles) ||
7264 bigstack_end_clalloc_d(score_col_ct, &tmpfile_buf) ||
7265 bigstack_end_clalloc_c(overflow_buf_alloc, &overflow_buf))) {
7266 goto ScoreReport_ret_NOMEM;
7267 }
7268 {
7269 uintptr_t cur_sample_shard_size = sample_shard_size;
7270 for (uint32_t shard_idx = 0; ; ++shard_idx) {
7271 if (shard_idx >= sample_shard_ct_m1) {
7272 if (shard_idx > sample_shard_ct_m1) {
7273 break;
7274 }
7275 cur_sample_shard_size = sample_ct - sample_shard_ct_m1 * sample_shard_size;
7276 }
7277 if (unlikely(bigstack_alloc_d(score_final_col_ct * cur_sample_shard_size, &ctx.sharded_final_scores_cmaj[shard_idx]) ||
7278 bigstack_alloc_u64(cur_sample_shard_size, &ctx.ddosage_incrs[shard_idx]) ||
7279 bigstack_alloc_d(kScoreVariantBlockSize * cur_sample_shard_size, &ctx.dosages_vmaj[shard_idx]))) {
7280 goto ScoreReport_ret_NOMEM;
7281 }
7282 }
7283 }
7284 if (qsr_ct) {
7285 if (unlikely(bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.variant_uidxs[0]) ||
7286 bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.variant_uidxs[1]))) {
7287 goto ScoreReport_ret_NOMEM;
7288 }
7289 } else {
7290 ctx.variant_uidxs[0] = nullptr;
7291 ctx.variant_uidxs[1] = nullptr;
7292 }
7293 if (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) {
7294 // We may want to buffer less than 2x240 variants at a time in this case
7295 // if there are >500k samples...
7296 if (unlikely(bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.dosage_presents[0]) ||
7297 bigstack_alloc_w(kScoreVariantBlockSize * sample_ctaw, &ctx.dosage_presents[1]) ||
7298 bigstack_alloc_dosage(kScoreVariantBlockSize * dosage_main_stride, &ctx.dosage_mains[0]) ||
7299 bigstack_alloc_dosage(kScoreVariantBlockSize * dosage_main_stride, &ctx.dosage_mains[1]) ||
7300 bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.dosage_cts[0]) ||
7301 bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.dosage_cts[1]))) {
7302 goto ScoreReport_ret_NOMEM;
7303 }
7304 } else {
7305 ctx.dosage_presents[0] = nullptr;
7306 ctx.dosage_presents[1] = nullptr;
7307 ctx.dosage_mains[0] = nullptr;
7308 ctx.dosage_mains[1] = nullptr;
7309 ctx.dosage_cts[0] = nullptr;
7310 ctx.dosage_cts[1] = nullptr;
7311 }
7312 const uint32_t domrec = !!(flags & (kfScoreDominant | kfScoreRecessive));
7313 uint32_t* common_geno_sum_incrs = nullptr;
7314 double* common_score_incrs = nullptr;
7315 uint32_t max_returned_difflist_len = 0;
7316 uintptr_t raregeno_stride = 0;
7317 uintptr_t difflist_sample_ids_stride = 0;
7318 if ((!ctx.dosage_presents[0]) && (!domrec)) {
7319 max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
7320 raregeno_stride = NypCtToAlignedWordCt(max_returned_difflist_len);
7321 difflist_sample_ids_stride = RoundUpPow2(max_returned_difflist_len, kInt32PerVec);
7322 if (unlikely(bigstack_alloc_u32(qsr_ct_nz, &common_geno_sum_incrs) ||
7323 bigstack_alloc_d(score_final_col_ct, &common_score_incrs) ||
7324 bigstack_alloc_w(kScoreVariantBlockSize * raregeno_stride, &ctx.raregenos[0]) ||
7325 bigstack_alloc_w(kScoreVariantBlockSize * raregeno_stride, &ctx.raregenos[1]) ||
7326 bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.difflist_lens[0]) ||
7327 bigstack_alloc_u32(kScoreVariantBlockSize, &ctx.difflist_lens[1]) ||
7328 bigstack_alloc_u32(kScoreVariantBlockSize * difflist_sample_ids_stride, &ctx.difflist_sample_ids[0]) ||
7329 bigstack_alloc_u32(kScoreVariantBlockSize * difflist_sample_ids_stride, &ctx.difflist_sample_ids[1]) ||
7330 bigstack_alloc_i8(kScoreVariantBlockSize, &ctx.difflist_common_genos[0]) ||
7331 bigstack_alloc_i8(kScoreVariantBlockSize, &ctx.difflist_common_genos[1]) ||
7332 bigstack_alloc_d(kScoreVariantBlockSize * score_final_col_ct, &ctx.score_sparse_coefs_vmaj[0]) ||
7333 bigstack_alloc_d(kScoreVariantBlockSize * score_final_col_ct, &ctx.score_sparse_coefs_vmaj[1]))) {
7334 goto ScoreReport_ret_NOMEM;
7335 }
7336 } else {
7337 ctx.raregenos[0] = nullptr;
7338 ctx.raregenos[1] = nullptr;
7339 ctx.difflist_lens[0] = nullptr;
7340 ctx.difflist_lens[1] = nullptr;
7341 ctx.difflist_sample_ids[0] = nullptr;
7342 ctx.difflist_sample_ids[1] = nullptr;
7343 ctx.difflist_common_genos[0] = nullptr;
7344 ctx.difflist_common_genos[1] = nullptr;
7345 ctx.score_sparse_coefs_vmaj[0] = nullptr;
7346 ctx.score_sparse_coefs_vmaj[1] = nullptr;
7347 }
7348 ctx.max_returned_difflist_len = max_returned_difflist_len;
7349 if (allele_freqs) {
7350 if (unlikely(bigstack_alloc_d(kScoreVariantBlockSize, &ctx.allele_freqs[0]) ||
7351 bigstack_alloc_d(kScoreVariantBlockSize, &ctx.allele_freqs[1]) ||
7352 bigstack_alloc_d(kScoreVariantBlockSize, &ctx.geno_slopes[0]) ||
7353 bigstack_alloc_d(kScoreVariantBlockSize, &ctx.geno_slopes[1]) ||
7354 bigstack_alloc_d(kScoreVariantBlockSize, &ctx.geno_intercepts[0]) ||
7355 bigstack_alloc_d(kScoreVariantBlockSize, &ctx.geno_intercepts[1]))) {
7356 goto ScoreReport_ret_NOMEM;
7357 }
7358 } else {
7359 ctx.allele_freqs[0] = nullptr;
7360 ctx.allele_freqs[1] = nullptr;
7361 ctx.geno_slopes[0] = nullptr;
7362 ctx.geno_slopes[1] = nullptr;
7363 ctx.geno_intercepts[0] = nullptr;
7364 ctx.geno_intercepts[1] = nullptr;
7365 }
7366 SetThreadFuncAndData(CalcScoreThread, &ctx, &tg);
7367
7368 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
7369 CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_nonmale_collapsed);
7370 AlignedBitarrInvert(sample_ct, sex_nonmale_collapsed);
7371 ctx.sex_nonmale_collapsed = sex_nonmale_collapsed;
7372 const uintptr_t* sex_nonfemale = sex_male;
7373 uintptr_t* sex_female_collapsed = sex_nonmale_collapsed;
7374 if (nosex_ct) {
7375 uintptr_t* sex_female_tmp;
7376 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sex_female_tmp) ||
7377 bigstack_alloc_w(sample_ctl, &sex_female_collapsed))) {
7378 goto ScoreReport_ret_NOMEM;
7379 }
7380 BitvecInvmaskCopy(sex_nm, sex_male, raw_sample_ctl, sex_female_tmp);
7381 CopyBitarrSubset(sex_female_tmp, sample_include, sample_ct, sex_female_collapsed);
7382 // now invert to nonfemale
7383 AlignedBitarrInvert(raw_sample_ct, sex_female_tmp);
7384 sex_nonfemale = sex_female_tmp;
7385 }
7386 ctx.sex_female_collapsed = sex_nonmale_collapsed;
7387
7388 if (!variant_id_htable) {
7389 reterr = AllocAndPopulateIdHtableMt(variant_include, variant_ids, variant_ct, 0, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr);
7390 if (unlikely(reterr)) {
7391 goto ScoreReport_ret_1;
7392 }
7393 }
7394
7395 snprintf(outname_end, kMaxOutfnameExtBlen, ".sscore.tmp");
7396 if (unlikely(fopen_checked(outname, FOPEN_WB, &score_tmpfile))) {
7397 goto ScoreReport_ret_OPEN_FAIL;
7398 }
7399
7400 const uint32_t ignore_dup_ids = (flags / kfScoreIgnoreDupIds) & 1;
7401 const uint32_t list_variants = (flags / kfScoreListVariants) & 1;
7402 if (list_variants) {
7403 const uint32_t list_variants_zst = (flags / kfScoreListVariantsZs) & 1;
7404 OutnameZstSet(".sscore.vars", list_variants_zst, outname_end);
7405 reterr = InitCstream(outname, 0, list_variants_zst, 1, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css);
7406 if (unlikely(reterr)) {
7407 goto ScoreReport_ret_1;
7408 }
7409 cswritep = overflow_buf;
7410 }
7411
7412 char** score_col_names;
7413 if (unlikely(bigstack_end_clalloc_cp(global_score_col_ct, &score_col_names))) {
7414 goto ScoreReport_ret_NOMEM;
7415 }
7416 if (!(flags & kfScoreHeaderRead)) {
7417 // just perform this check once, rather than once per file.
7418 // errored out with "Too many score columns" earlier if LHS > 2^31.
7419 if (global_score_col_ct * 16 > bigstack_left()) {
7420 goto ScoreReport_ret_NOMEM;
7421 }
7422 }
7423
7424 #ifdef USE_MTBLAS
7425 if (sample_shard_ct < calc_thread_ct) {
7426 const uint32_t matrix_multiply_thread_ct = 1 + ((calc_thread_ct - 1) / sample_shard_ct);
7427 BLAS_SET_NUM_THREADS(matrix_multiply_thread_ct);
7428 }
7429 #endif
7430
7431 PgrSampleSubsetIndex pssi;
7432 PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi);
7433 const uint32_t lines_to_skip_p1 = 1 + ((flags / kfScoreHeaderIgnore) & 1);
7434 // Stricter threshold for multi-score since standard matrix-multiply
7435 // workflow is more likely to pay off
7436 const uint32_t max_sparse = (score_final_col_ct == 1)? (sample_ct / 16) : (sample_ct / 32);
7437 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
7438 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
7439 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
7440 const uint32_t variance_standardize = (flags / kfScoreVarianceStandardize) & 1;
7441 const uint32_t center = variance_standardize || (flags & kfScoreCenter);
7442 const uint32_t no_meanimpute = (flags / kfScoreNoMeanimpute) & 1;
7443 const uint32_t y_prohibited = nosex_ct && (!no_meanimpute);
7444 const uint32_t se_mode = (flags / kfScoreSe) & 1;
7445 const uintptr_t tmpfile_buf_byte_ct = score_col_ct * sizeof(double);
7446 // If we're not attempting the sparse-genotype optimization, this is always
7447 // UINT32_MAX.
7448 uint32_t difflist_common_geno = UINT32_MAX;
7449 uint32_t cur_allele_ct = 2;
7450 uint32_t dosage_ct = 0;
7451 double geno_slope = kRecipDosageMax;
7452 double geno_intercept = 0.0;
7453 char* score_name_write_iter = R_CAST(char*, g_bigstack_end);
7454 for (uint32_t file_idx1 = 1; file_idx1 <= infile_ct; ++file_idx1, fname_iter = fname_iter->next) {
7455 cur_input_fname = fname_iter->str;
7456 if (file_idx1 > 1) {
7457 reterr = TextRetarget(cur_input_fname, &score_txs);
7458 if (unlikely(reterr)) {
7459 goto ScoreReport_ret_TSTREAM_FAIL;
7460 }
7461 }
7462 ZeroVecArr(11 * acc4_vec_ct * qsr_ct_nz, missing_diploid_accx);
7463 ZeroVecArr(11 * acc4_vec_ct * qsr_ct_nz, missing_haploid_accx);
7464 ZeroU32Arr(qsr_ct_nz, allele_ct_bases);
7465 ZeroU32Arr(qsr_ct_nz, male_allele_ct_decrs);
7466 ZeroU32Arr(qsr_ct_nz, nonfemale_allele_ct_incrs);
7467 ZeroU64Arr(qsr_ct_nz * sample_ct, ctx.ddosage_sums);
7468 ZeroWArr(raw_variant_ctl, already_seen_variants);
7469 ZeroWArr(raw_allele_ctl, already_seen_alleles);
7470 {
7471 uintptr_t cur_sample_shard_size = sample_shard_size;
7472 for (uint32_t shard_idx = 0; ; ++shard_idx) {
7473 if (shard_idx >= sample_shard_ct_m1) {
7474 if (shard_idx > sample_shard_ct_m1) {
7475 break;
7476 }
7477 cur_sample_shard_size = sample_ct - sample_shard_ct_m1 * sample_shard_size;
7478 }
7479 ZeroDArr(score_final_col_ct * cur_sample_shard_size, ctx.sharded_final_scores_cmaj[shard_idx]);
7480 }
7481 }
7482 if (common_geno_sum_incrs) {
7483 ZeroU32Arr(qsr_ct_nz, common_geno_sum_incrs);
7484 ZeroDArr(score_final_col_ct, common_score_incrs);
7485 }
7486 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct_nz; ++qsr_idx) {
7487 variant_ct_rems[2 * qsr_idx] = 15;
7488 variant_ct_rems[2 * qsr_idx + 1] = 17;
7489 variant_hap_ct_rems[2 * qsr_idx] = 15;
7490 variant_hap_ct_rems[2 * qsr_idx + 1] = 17;
7491 }
7492 ctx.cur_variant_batch_size = kScoreVariantBlockSize;
7493 line_idx = 0;
7494 char* line_start;
7495 for (uint32_t uii = 0; uii != lines_to_skip_p1; ++uii) {
7496 ++line_idx;
7497 line_start = TextGet(&score_txs);
7498 if (unlikely(!line_start)) {
7499 if (!TextStreamErrcode2(&score_txs, &reterr)) {
7500 logerrprintf("Error: --score%s: %s is empty.\n", multi_input? "-list" : "", cur_input_fname);
7501 goto ScoreReport_ret_MALFORMED_INPUT;
7502 }
7503 goto ScoreReport_ret_TSTREAM_FAIL;
7504 }
7505 }
7506 {
7507 const uintptr_t global_score_col_idx_start = (file_idx1 - 1) * score_col_ct;
7508 if (flags & kfScoreHeaderRead) {
7509 char* line_end = TextLineEnd(&score_txs);
7510 if (S_CAST(uintptr_t, line_end - line_start) > bigstack_left()) {
7511 goto ScoreReport_ret_NOMEM;
7512 }
7513 char** cur_score_col_names = &(score_col_names[global_score_col_idx_start]);
7514 char* read_iter = line_start;
7515 for (uintptr_t score_col_idx = 0; score_col_idx != score_col_ct; ++score_col_idx) {
7516 read_iter = NextTokenMult0(read_iter, score_col_idx_deltas[score_col_idx]);
7517 if (unlikely(!read_iter)) {
7518 goto ScoreReport_ret_MISSING_TOKENS;
7519 }
7520 char* token_end = CurTokenEnd(read_iter);
7521 const uint32_t slen = token_end - read_iter;
7522 score_name_write_iter -= 1 + slen;
7523 cur_score_col_names[score_col_idx] = score_name_write_iter;
7524 memcpyx(score_name_write_iter, read_iter, slen, '\0');
7525 }
7526 if (file_idx1 == infile_ct) {
7527 BigstackEndSet(score_name_write_iter);
7528 bigstack_end_clalign();
7529 unsigned char* bigstack_mark2 = g_bigstack_base;
7530 uintptr_t* col_subset_mask;
7531 if (unlikely(bigstack_alloc_w(BitCtToWordCt(score_col_ct), &col_subset_mask))) {
7532 goto ScoreReport_ret_NOMEM;
7533 }
7534 SetAllBits(score_col_ct, col_subset_mask);
7535 uint32_t dup_found;
7536 reterr = CheckIdUniqueness(g_bigstack_base, g_bigstack_end, col_subset_mask, TO_CONSTCPCONSTP(score_col_names), score_col_ct, max_thread_ct, &dup_found);
7537 if (unlikely(reterr)) {
7538 goto ScoreReport_ret_1;
7539 }
7540 if (unlikely(dup_found)) {
7541 logerrprintf("Error: --score%s: Score IDs are not unique.\n", multi_input? "-list" : "");
7542 goto ScoreReport_ret_MALFORMED_INPUT;
7543 }
7544 BigstackReset(bigstack_mark2);
7545 }
7546 } else {
7547 const uintptr_t col_idx_stop = global_score_col_idx_start + score_col_ct;
7548 for (uintptr_t global_score_col_idx = global_score_col_idx_start; global_score_col_idx != col_idx_stop; ++global_score_col_idx) {
7549 const uint32_t str_blen = 6 + UintSlen(global_score_col_idx + 1);
7550 score_name_write_iter -= str_blen;
7551 score_col_names[global_score_col_idx] = score_name_write_iter;
7552 char* tmp_write_iter = strcpya_k(score_name_write_iter, "SCORE");
7553 u32toa_x(global_score_col_idx + 1, '\0', tmp_write_iter);
7554 }
7555 if (file_idx1 == infile_ct) {
7556 BigstackEndSet(score_name_write_iter);
7557 bigstack_end_clalign();
7558 }
7559 }
7560 }
7561
7562 ReinitThreads(&tg);
7563 uint32_t block_vidx = 0;
7564 uint32_t sparse_vidx = 0;
7565 uint32_t parity = 0;
7566 uint32_t prev_variant_uidx = UINT32_MAX;
7567 uintptr_t* genovec_iter = ctx.genovecs[0];
7568 uintptr_t* raregeno_iter = ctx.raregenos[0];
7569 uint32_t* difflist_lens = ctx.difflist_lens[0];
7570 uint32_t* difflist_sample_ids_iter = ctx.difflist_sample_ids[0];
7571 int8_t* difflist_common_genos = ctx.difflist_common_genos[0];
7572 uintptr_t* dosage_present_iter = ctx.dosage_presents[0];
7573 Dosage* dosage_main_iter = ctx.dosage_mains[0];
7574 uint32_t* dosage_cts = ctx.dosage_cts[0];
7575 uintptr_t* missing_bitvec_iter = ctx.missing_bitvecs[0];
7576 uintptr_t* missing_male_bitvec_iter = ctx.missing_male_bitvecs[0];
7577 uintptr_t* missing_nonfemale_bitvec_iter = ctx.missing_nonfemale_bitvecs[0];
7578 double* cur_allele_freqs = ctx.allele_freqs[0];
7579 double* geno_slopes = ctx.geno_slopes[0];
7580 double* geno_intercepts = ctx.geno_intercepts[0];
7581 double* score_dense_coefs_cmaj = ctx.score_dense_coefs_cmaj[0];
7582 double* score_sparse_coefs_vmaj = ctx.score_sparse_coefs_vmaj[0];
7583 uint32_t* variant_uidxs = ctx.variant_uidxs[0];
7584 unsigned char* is_nonx_haploids = &(ctx.is_nonx_haploids[0][0]);
7585 unsigned char* is_relevant_xs = &(ctx.is_relevant_xs[0][0]);
7586 unsigned char* is_ys = &(ctx.is_ys[0][0]);
7587 unsigned char* ploidy_m1s = &(ctx.ploidy_m1s[0][0]);
7588 uint32_t valid_variant_ct = 0;
7589 uint32_t difflist_len = 0;
7590 uintptr_t missing_var_id_ct = 0;
7591 uintptr_t missing_allele_code_ct = 0;
7592 uintptr_t duplicated_var_id_ct = 0;
7593 if (flags & kfScoreHeaderRead) {
7594 ++line_idx;
7595 line_start = TextGet(&score_txs);
7596 }
7597 for (; line_start; ++line_idx, line_start = TextGet(&score_txs)) {
7598 // varid_col_idx and allele_col_idx will almost always be very small
7599 char* variant_id_start = NextTokenMult0(line_start, varid_col_idx);
7600 if (unlikely(!variant_id_start)) {
7601 goto ScoreReport_ret_MISSING_TOKENS;
7602 }
7603 char* variant_id_token_end = CurTokenEnd(variant_id_start);
7604 const uint32_t variant_id_slen = variant_id_token_end - variant_id_start;
7605 uint32_t variant_uidx = VariantIdDupflagHtableFind(variant_id_start, variant_ids, variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen);
7606 if (variant_uidx >> 31) {
7607 ++missing_var_id_ct;
7608 if (variant_uidx != UINT32_MAX) {
7609 if (unlikely(!ignore_dup_ids)) {
7610 snprintf(g_logbuf, kLogbufSize, "Error: --score%s variant ID '%s' appears multiple times in main dataset.\n", multi_input? "-list" : "", variant_ids[variant_uidx & 0x7fffffff]);
7611 goto ScoreReport_ret_INCONSISTENT_INPUT_WW;
7612 }
7613 ++duplicated_var_id_ct;
7614 // subtract this from missing_var_id_ct later
7615 }
7616 continue;
7617 }
7618 char* allele_start = NextTokenMult0(line_start, allele_col_idx);
7619 if (unlikely(!allele_start)) {
7620 goto ScoreReport_ret_MISSING_TOKENS;
7621 }
7622 uintptr_t allele_idx_offset_base;
7623 if (!allele_idx_offsets) {
7624 allele_idx_offset_base = variant_uidx * 2;
7625 } else {
7626 allele_idx_offset_base = allele_idx_offsets[variant_uidx];
7627 cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base;
7628 }
7629 char* allele_end = CurTokenEnd(allele_start);
7630 const char allele_end_char = *allele_end;
7631 *allele_end = '\0';
7632 const uint32_t allele_blen = 1 + S_CAST(uintptr_t, allele_end - allele_start);
7633 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
7634
7635 uint32_t cur_aidx = 0;
7636 for (; cur_aidx != cur_allele_ct; ++cur_aidx) {
7637 if (memequal(allele_start, cur_alleles[cur_aidx], allele_blen)) {
7638 break;
7639 }
7640 }
7641 // compiler is smart enough to avoid repeating this test
7642 if (cur_aidx == cur_allele_ct) {
7643 ++missing_allele_code_ct;
7644 *allele_end = allele_end_char;
7645 continue;
7646 }
7647 const uintptr_t allele_idx = allele_idx_offset_base + cur_aidx;
7648 if (unlikely(IsSet(already_seen_alleles, allele_idx))) {
7649 char* errwrite_iter = strcpya_k(g_logbuf, "Error: --score");
7650 if (multi_input) {
7651 errwrite_iter = strcpya_k(errwrite_iter, "-list");
7652 }
7653 errwrite_iter = strcpya_k(errwrite_iter, ": ");
7654 // Don't write allele code, since it might be too long for the
7655 // buffer.
7656 if (!cur_aidx) {
7657 errwrite_iter = strcpya_k(errwrite_iter, "REF");
7658 } else {
7659 errwrite_iter = strcpya_k(errwrite_iter, "ALT");
7660 errwrite_iter = u32toa(cur_aidx, errwrite_iter);
7661 }
7662 errwrite_iter = strcpya_k(errwrite_iter, " allele for variant '");
7663 errwrite_iter = strcpya(errwrite_iter, variant_ids[variant_uidx]);
7664 errwrite_iter = strcpya_k(errwrite_iter, "' appears multiple times in ");
7665 errwrite_iter = strcpya(errwrite_iter, cur_input_fname);
7666 if (multi_input) {
7667 errwrite_iter = strcpya_k(errwrite_iter, "-list");
7668 }
7669 strcpy_k(errwrite_iter, " file.\n");
7670 goto ScoreReport_ret_MALFORMED_INPUT_WW;
7671 }
7672 SetBit(allele_idx, already_seen_alleles);
7673 const uint32_t is_new_variant = 1 - IsSet(already_seen_variants, variant_uidx);
7674 SetBit(variant_uidx, already_seen_variants);
7675
7676 // okay, the variant and allele are in our dataset.
7677 const uint32_t chr_idx = GetVariantChr(cip, variant_uidx);
7678 uint32_t is_nonx_haploid = IsSet(cip->haploid_mask, chr_idx);
7679 if (unlikely(domrec && is_nonx_haploid)) {
7680 fputs("\n", stdout);
7681 logerrputs("Error: --score[-list] 'dominant' and 'recessive' modifiers cannot be used with\nhaploid chromosomes.\n");
7682 goto ScoreReport_ret_INCONSISTENT_INPUT;
7683 }
7684 uint32_t is_relevant_x = (chr_idx == x_code);
7685 if (unlikely(variance_standardize && (is_relevant_x || (chr_idx == mt_code)))) {
7686 fputs("\n", stdout);
7687 logerrputs("Error: --score[-list] 'variance-standardize' cannot be used with chrX or MT.\n");
7688 goto ScoreReport_ret_INCONSISTENT_INPUT;
7689 }
7690 is_nonx_haploid = (!is_relevant_x) && is_nonx_haploid;
7691
7692 // only if --xchr-model 1 (which is no longer the default)
7693 is_relevant_x = is_relevant_x && xchr_model;
7694
7695 const uint32_t is_y = (chr_idx == y_code);
7696 if (unlikely(is_y && y_prohibited)) {
7697 fputs("\n", stdout);
7698 logerrputs("Error: When both chrY variants and unknown-sex samples are present,\n--score[-list] can only be run with the 'no-mean-imputation' modifier.\n");
7699 goto ScoreReport_ret_INCONSISTENT_INPUT;
7700 }
7701 uint32_t ploidy_m1;
7702 if ((variant_uidx == prev_variant_uidx) && (cur_allele_ct == 2)) {
7703 // Previous record is the exact inverse of what we now want, so just
7704 // copy and invert it.
7705 // This is worth the trouble since PgrGet1D() is usually the main
7706 // bottleneck, and the repeated-variant case definitely comes up from
7707 // at least the recommended PCA-projection workflow.
7708 if (difflist_common_geno != UINT32_MAX) {
7709 memcpy(raregeno_iter, &(raregeno_iter[-S_CAST(intptr_t, raregeno_stride)]), NypCtToWordCt(difflist_len) * sizeof(intptr_t));
7710 memcpy(difflist_sample_ids_iter, &(difflist_sample_ids_iter[-S_CAST(intptr_t, difflist_sample_ids_stride)]), difflist_len * sizeof(int32_t));
7711 GenovecInvertUnsafe(difflist_len, raregeno_iter);
7712 difflist_common_geno = (6 - difflist_common_geno) & 3;
7713 } else {
7714 memcpy(genovec_iter, &(genovec_iter[-S_CAST(intptr_t, sample_ctaw2)]), sample_ctaw2 * sizeof(intptr_t));
7715 GenovecInvertUnsafe(sample_ct, genovec_iter);
7716 if (dosage_present_iter) {
7717 memcpy(dosage_present_iter, &(dosage_present_iter[-S_CAST(intptr_t, sample_ctaw)]), sample_ctaw * sizeof(intptr_t));
7718 dosage_ct = dosage_cts[block_vidx - 1];
7719 memcpy(dosage_main_iter, &(dosage_main_iter[-S_CAST(intptr_t, dosage_main_stride)]), dosage_ct * sizeof(Dosage));
7720 BiallelicDosage16Invert(dosage_ct, dosage_main_iter);
7721 }
7722 }
7723 } else if (dosage_present_iter || (cur_allele_ct > 2) || domrec || is_nonx_haploid || is_relevant_x) {
7724 difflist_common_geno = UINT32_MAX;
7725 reterr = PgrGet1D(sample_include, pssi, sample_ct, variant_uidx, cur_aidx, simple_pgrp, genovec_iter, dosage_present_iter, dosage_main_iter, &dosage_ct);
7726 if (unlikely(reterr)) {
7727 PgenErrPrintNV(reterr, variant_uidx);
7728 goto ScoreReport_ret_1;
7729 }
7730 } else {
7731 // Sparse-genotype optimization. We limit this to the no-dosage,
7732 // all-diploid, biallelic, no 'dominant'/'recessive' case to keep
7733 // code size under control.
7734 reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_sparse, variant_uidx, simple_pgrp, genovec_iter, &difflist_common_geno, raregeno_iter, difflist_sample_ids_iter, &difflist_len);
7735 if (unlikely(reterr)) {
7736 PgenErrPrintNV(reterr, variant_uidx);
7737 goto ScoreReport_ret_1;
7738 }
7739 if (!cur_aidx) {
7740 if (difflist_common_geno == UINT32_MAX) {
7741 GenovecInvertUnsafe(sample_ct, genovec_iter);
7742 } else {
7743 GenovecInvertUnsafe(difflist_len, raregeno_iter);
7744 difflist_common_geno = (6 - difflist_common_geno) & 3;
7745 }
7746 }
7747 }
7748 if (difflist_common_geno != UINT32_MAX) {
7749 ZeroTrailingNyps(difflist_len, raregeno_iter);
7750 if (is_new_variant) {
7751 uint32_t missing_exists = (difflist_common_geno == 3);
7752 if ((!missing_exists) && difflist_len) {
7753 STD_ARRAY_DECL(uint32_t, 4, genocounts);
7754 GenoarrCountFreqsUnsafe(raregeno_iter, difflist_len, genocounts);
7755 missing_exists = (genocounts[3] != 0);
7756 }
7757 // This must be kept in sync with how the main branch processes
7758 // missingness.
7759 if (missing_exists) {
7760 SparseToMissingness(raregeno_iter, difflist_sample_ids_iter, sample_ct, difflist_common_geno, difflist_len, missing_bitvec_iter);
7761 }
7762 if (!qsr_ct) {
7763 allele_ct_bases[0] += 2;
7764 if (missing_exists) {
7765 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, variant_ct_rems, missing_diploid_accx);
7766 }
7767 } else {
7768 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7769 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7770 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7771 allele_ct_bases[qsr_idx] += 2;
7772 if (missing_exists) {
7773 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, &(variant_ct_rems[2 * qsr_idx]), &(missing_diploid_accx[acc4_vec_ct * 11 * qsr_idx]));
7774 }
7775 }
7776 }
7777 }
7778 }
7779 // Enable sparse ddosage_sums update.
7780 if ((difflist_common_geno == 1) || (difflist_common_geno == 2)) {
7781 if (!qsr_ct) {
7782 common_geno_sum_incrs[0] += difflist_common_geno;
7783 } else {
7784 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7785 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7786 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7787 common_geno_sum_incrs[qsr_idx] += difflist_common_geno;
7788 }
7789 }
7790 }
7791 }
7792 ploidy_m1 = 1;
7793 } else {
7794 ZeroTrailingNyps(sample_ct, genovec_iter);
7795 GenoarrToMissingnessUnsafe(genovec_iter, sample_ct, missing_bitvec_iter);
7796 if (dosage_ct) {
7797 BitvecInvmask(dosage_present_iter, sample_ctl, missing_bitvec_iter);
7798 }
7799 if (is_nonx_haploid) {
7800 if (is_y) {
7801 if (is_new_variant) {
7802 if (!qsr_ct) {
7803 nonfemale_allele_ct_incrs[0] += 1;
7804 } else {
7805 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7806 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7807 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7808 nonfemale_allele_ct_incrs[qsr_idx] += 1;
7809 }
7810 }
7811 }
7812 }
7813 BitvecInvmask(sex_female_collapsed, sample_ctl, missing_bitvec_iter);
7814 } else if (is_new_variant) {
7815 if (!qsr_ct) {
7816 allele_ct_bases[0] += 1;
7817 } else {
7818 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7819 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7820 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7821 allele_ct_bases[qsr_idx] += 1;
7822 }
7823 }
7824 }
7825 }
7826 if (is_new_variant) {
7827 if (!qsr_ct) {
7828 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, variant_hap_ct_rems, missing_haploid_accx);
7829 } else {
7830 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7831 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7832 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7833 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, &(variant_ct_rems[2 * qsr_idx]), &(missing_haploid_accx[acc4_vec_ct * 11 * qsr_idx]));
7834 }
7835 }
7836 }
7837 }
7838 if (is_y) {
7839 memcpy(missing_nonfemale_bitvec_iter, missing_bitvec_iter, sample_ctl * sizeof(intptr_t));
7840 BitvecOr(sex_female_collapsed, sample_ctl, missing_bitvec_iter);
7841 }
7842 ploidy_m1 = 0;
7843 } else {
7844 // !is_nonx_haploid
7845 if (is_relevant_x) {
7846 // Handle nonmales first. Remove males from missing_bitvec_iter,
7847 // to be restored at the end of this block.
7848 BitvecInvmaskCopy(missing_bitvec_iter, sex_nonmale_collapsed, sample_ctl, missing_male_bitvec_iter);
7849 BitvecAnd(sex_nonmale_collapsed, sample_ctl, missing_bitvec_iter);
7850 }
7851 if (is_new_variant) {
7852 if (!qsr_ct) {
7853 allele_ct_bases[0] += 2;
7854 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, variant_ct_rems, missing_diploid_accx);
7855 } else {
7856 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7857 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7858 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7859 allele_ct_bases[qsr_idx] += 2;
7860 VerticalCounterUpdate(missing_bitvec_iter, acc1_vec_ct, &(variant_ct_rems[2 * qsr_idx]), &(missing_diploid_accx[acc4_vec_ct * 11 * qsr_idx]));
7861 }
7862 }
7863 }
7864 }
7865 if (is_relevant_x) {
7866 // Now count males.
7867 if (is_new_variant) {
7868 if (!qsr_ct) {
7869 male_allele_ct_decrs[0] += 1;
7870 VerticalCounterUpdate(missing_male_bitvec_iter, acc1_vec_ct, variant_hap_ct_rems, missing_haploid_accx);
7871 } else {
7872 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7873 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7874 if (IsSet(qsr_include, qsr_idx + bit_idx_base)) {
7875 male_allele_ct_decrs[qsr_idx] += 1;
7876 VerticalCounterUpdate(missing_male_bitvec_iter, acc1_vec_ct, &(variant_hap_ct_rems[2 * qsr_idx]), &(missing_haploid_accx[acc4_vec_ct * 11 * qsr_idx]));
7877 }
7878 }
7879 }
7880 }
7881 // Restore missing males to missing_bitvec_iter.
7882 BitvecOr(missing_male_bitvec_iter, sample_ctl, missing_bitvec_iter);
7883 }
7884 ploidy_m1 = domrec? 0 : 1;
7885 }
7886 }
7887 const double ploidy_d = ploidy_m1? 2.0 : 1.0;
7888 if (allele_freqs) {
7889 const double cur_allele_freq = GetAlleleFreq(&(allele_freqs[allele_idx_offset_base - variant_uidx]), cur_aidx, cur_allele_ct);
7890 if (center) {
7891 // Note that we prohibit 'dominant'/'recessive' from being used
7892 // with 'center'/'variance-standardize'.
7893 if (variance_standardize) {
7894 const double variance = ploidy_d * 0.5 * ComputeDiploidMultiallelicVariance(&(allele_freqs[allele_idx_offset_base - variant_uidx]), cur_allele_ct);
7895 if (!(variance > kSmallEpsilon)) {
7896 // ZeroTrailingNyps(sample_ct, genovec_buf);
7897 STD_ARRAY_DECL(uint32_t, 4, genocounts);
7898 if (difflist_common_geno != UINT32_MAX) {
7899 GenoarrCountFreqsUnsafe(raregeno_iter, difflist_len, genocounts);
7900 genocounts[difflist_common_geno] = sample_ct - difflist_len;
7901 } else {
7902 GenoarrCountFreqsUnsafe(genovec_iter, sample_ct, genocounts);
7903 }
7904 if (unlikely(dosage_ct || genocounts[1] || genocounts[2])) {
7905 snprintf(g_logbuf, kLogbufSize, "Error: --score[-list] variance-standardize failure for variant '%s': estimated allele frequency is zero or NaN, but not all dosages are zero. (This is possible when e.g. allele frequencies are estimated from founders, but the allele is only observed in nonfounders.)\n", variant_ids[variant_uidx]);
7906 goto ScoreReport_ret_DEGENERATE_DATA_WW;
7907 }
7908 geno_slope = 0.0;
7909 } else {
7910 geno_slope = kRecipDosageMax / sqrt(variance);
7911 }
7912 }
7913 // (ploidy * cur_allele_freq * kDosageMax) * geno_slope +
7914 // geno_intercept == 0
7915 // bugfix: must use "-1.0 *" instead of - to avoid unsigned int
7916 // wraparound
7917 geno_intercept = (-1.0 * kDosageMax) * ploidy_d * cur_allele_freq * geno_slope;
7918 }
7919 cur_allele_freqs[block_vidx] = cur_allele_freq;
7920 geno_slopes[block_vidx] = geno_slope;
7921 geno_intercepts[block_vidx] = geno_intercept;
7922 }
7923
7924 *allele_end = allele_end_char;
7925 const uint32_t dense_vidx = block_vidx - sparse_vidx;
7926 double* score_coefs_iter = (difflist_common_geno == UINT32_MAX)? (&(score_dense_coefs_cmaj[dense_vidx])) : (&(score_sparse_coefs_vmaj[sparse_vidx * score_final_col_ct]));
7927 double* common_score_incrs_iter = common_score_incrs;
7928 const char* read_iter = line_start;
7929 for (uint32_t score_col_idx = 0; score_col_idx != score_col_ct; ++score_col_idx) {
7930 read_iter = NextTokenMult0(read_iter, score_col_idx_deltas[score_col_idx]);
7931 if (unlikely(!read_iter)) {
7932 goto ScoreReport_ret_MISSING_TOKENS;
7933 }
7934 double raw_coef;
7935 const char* token_end = ScantokDouble(read_iter, &raw_coef);
7936 if (unlikely(!token_end)) {
7937 char* errwrite_iter = strcpya_k(g_logbuf, "Error: --score");
7938 if (multi_input) {
7939 errwrite_iter = strcpya_k(errwrite_iter, "-list");
7940 }
7941 errwrite_iter = strcpya_k(errwrite_iter, ": Invalid coefficient ");
7942 // don't want to write this unconditionally, since it can
7943 // theoretically overflow the buffer.
7944 token_end = CurTokenEnd(read_iter);
7945 const uint32_t token_slen = token_end - read_iter;
7946 if (token_slen <= 77) {
7947 *errwrite_iter++ = '\'';
7948 errwrite_iter = memcpya(errwrite_iter, read_iter, token_slen);
7949 errwrite_iter = strcpya_k(errwrite_iter, "' ");
7950 }
7951 errwrite_iter = strcpya_k(errwrite_iter, "on line ");
7952 errwrite_iter = wtoa(line_idx, errwrite_iter);
7953 errwrite_iter = strcpya_k(errwrite_iter, " of ");
7954 errwrite_iter = strcpya(errwrite_iter, cur_input_fname);
7955 strcpy_k(errwrite_iter, " .\n");
7956 goto ScoreReport_ret_MALFORMED_INPUT_WW;
7957 }
7958 if (difflist_common_geno == UINT32_MAX) {
7959 // dense case: fill column for later matrix-multiply
7960 if (!qsr_ct) {
7961 *score_coefs_iter = raw_coef;
7962 score_coefs_iter = &(score_coefs_iter[kScoreVariantBlockSize]);
7963 } else {
7964 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7965 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7966 double cur_coef = raw_coef * u31tod(IsSet(qsr_include, qsr_idx + bit_idx_base));
7967 *score_coefs_iter = cur_coef;
7968 score_coefs_iter = &(score_coefs_iter[kScoreVariantBlockSize]);
7969 }
7970 }
7971 } else {
7972 // sparse case: use variant-major representation instead
7973 if (!qsr_ct) {
7974 score_coefs_iter[0] = raw_coef;
7975 } else {
7976 const uintptr_t bit_idx_base = RawToSubsettedPos(variant_include, variant_include_cumulative_popcounts, variant_uidx) * qsr_ct;
7977 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct; ++qsr_idx) {
7978 const double cur_coef = raw_coef * u31tod(IsSet(qsr_include, qsr_idx + bit_idx_base));
7979 score_coefs_iter[qsr_idx] = cur_coef;
7980 }
7981 }
7982 double common_dosage = 0.0;
7983 if (difflist_common_geno != 3) {
7984 common_dosage = geno_intercept + kDosageMax * geno_slope * difflist_common_geno;
7985 } else if (!no_meanimpute) {
7986 common_dosage = kDosageMax * 2LL * cur_allele_freqs[block_vidx] * geno_slope;
7987 }
7988 if (!se_mode) {
7989 for (uint32_t uii = 0; uii != qsr_ct_nz; ++uii) {
7990 common_score_incrs_iter[uii] += common_dosage * score_coefs_iter[uii];
7991 }
7992 } else {
7993 for (uint32_t uii = 0; uii != qsr_ct_nz; ++uii) {
7994 score_coefs_iter[uii] *= score_coefs_iter[uii];
7995 }
7996 const double common_dosage_sq = common_dosage * common_dosage;
7997 for (uint32_t uii = 0; uii != qsr_ct_nz; ++uii) {
7998 common_score_incrs_iter[uii] += common_dosage_sq * score_coefs_iter[uii];
7999 }
8000 }
8001 score_coefs_iter = &(score_coefs_iter[qsr_ct_nz]);
8002 common_score_incrs_iter = &(common_score_incrs_iter[qsr_ct_nz]);
8003 }
8004 read_iter = token_end;
8005 }
8006 if (difflist_common_genos) {
8007 difflist_common_genos[block_vidx] = S_CAST(int8_t, difflist_common_geno);
8008 if (difflist_common_geno != UINT32_MAX) {
8009 difflist_lens[sparse_vidx] = difflist_len;
8010 raregeno_iter = &(raregeno_iter[raregeno_stride]);
8011 difflist_sample_ids_iter = &(difflist_sample_ids_iter[difflist_sample_ids_stride]);
8012 ++sparse_vidx;
8013 }
8014 }
8015 if (is_new_variant) {
8016 if (list_variants) {
8017 cswritep = strcpya(cswritep, variant_ids[variant_uidx]);
8018 AppendBinaryEoln(&cswritep);
8019 if (unlikely(Cswrite(&css, &cswritep))) {
8020 goto ScoreReport_ret_WRITE_FAIL;
8021 }
8022 }
8023 ++valid_variant_ct;
8024 if (!(valid_variant_ct % 10000)) {
8025 // Technically still processing a few of these variants, but this
8026 // is less misleading than the previous 'loaded' message.
8027 const uint32_t k_ct = valid_variant_ct / 1000;
8028 if (multi_input) {
8029 printf("\r--score-list file %u/%u: %uk variants processed.", file_idx1, infile_ct, k_ct);
8030 } else {
8031 printf("\r--score: %uk variants processed.", k_ct);
8032 }
8033 fflush(stdout);
8034 }
8035 }
8036 if (variant_uidxs) {
8037 variant_uidxs[block_vidx] = variant_uidx;
8038 }
8039 is_nonx_haploids[block_vidx] = is_nonx_haploid;
8040 is_relevant_xs[block_vidx] = is_relevant_x;
8041 is_ys[block_vidx] = is_y;
8042 ploidy_m1s[block_vidx] = ploidy_m1;
8043 prev_variant_uidx = variant_uidx;
8044 genovec_iter = &(genovec_iter[sample_ctaw2]);
8045 missing_bitvec_iter = &(missing_bitvec_iter[sample_ctaw]);
8046 missing_male_bitvec_iter = &(missing_male_bitvec_iter[sample_ctaw]);
8047 missing_nonfemale_bitvec_iter = &(missing_nonfemale_bitvec_iter[sample_ctaw]);
8048 if (dosage_present_iter) {
8049 dosage_present_iter = &(dosage_present_iter[sample_ctaw]);
8050 dosage_main_iter = &(dosage_main_iter[dosage_main_stride]);
8051 dosage_cts[block_vidx] = dosage_ct;
8052 }
8053 ++block_vidx;
8054 if (block_vidx == kScoreVariantBlockSize) {
8055 if (se_mode) {
8056 const uint32_t dense_ct = block_vidx - sparse_vidx;
8057 if (dense_ct) {
8058 for (uintptr_t score_final_col_idx = 0; score_final_col_idx != score_final_col_ct; ++score_final_col_idx) {
8059 double* score_dense_coefs_row = &(score_dense_coefs_cmaj[score_final_col_idx * kScoreVariantBlockSize]);
8060 for (uint32_t uii = 0; uii != dense_ct; ++uii) {
8061 score_dense_coefs_row[uii] *= score_dense_coefs_row[uii];
8062 }
8063 }
8064 }
8065 for (uintptr_t ulii = 0; ulii != sparse_vidx * score_final_col_ct; ++ulii) {
8066 score_sparse_coefs_vmaj[ulii] *= score_sparse_coefs_vmaj[ulii];
8067 }
8068 }
8069 parity = 1 - parity;
8070 const uint32_t is_not_first_block = ThreadsAreActive(&tg);
8071 if (is_not_first_block) {
8072 JoinThreads(&tg);
8073 // CalcScoreThread() never errors out
8074 }
8075 if (unlikely(SpawnThreads(&tg))) {
8076 goto ScoreReport_ret_THREAD_CREATE_FAIL;
8077 }
8078 // we could instead have prev_genovec, prev_dosage_present, etc.
8079 // pointers, but this should be good enough
8080 prev_variant_uidx = UINT32_MAX;
8081
8082 variant_uidxs = ctx.variant_uidxs[parity];
8083 genovec_iter = ctx.genovecs[parity];
8084 raregeno_iter = ctx.raregenos[parity];
8085 difflist_lens = ctx.difflist_lens[parity];
8086 difflist_sample_ids_iter = ctx.difflist_sample_ids[parity];
8087 difflist_common_genos = ctx.difflist_common_genos[parity];
8088 dosage_present_iter = ctx.dosage_presents[parity];
8089 dosage_main_iter = ctx.dosage_mains[parity];
8090 dosage_cts = ctx.dosage_cts[parity];
8091 missing_bitvec_iter = ctx.missing_bitvecs[parity];
8092 missing_male_bitvec_iter = ctx.missing_male_bitvecs[parity];
8093 missing_nonfemale_bitvec_iter = ctx.missing_nonfemale_bitvecs[parity];
8094 cur_allele_freqs = ctx.allele_freqs[parity];
8095 geno_slopes = ctx.geno_slopes[parity];
8096 geno_intercepts = ctx.geno_intercepts[parity];
8097 score_dense_coefs_cmaj = ctx.score_dense_coefs_cmaj[parity];
8098 score_sparse_coefs_vmaj = ctx.score_sparse_coefs_vmaj[parity];
8099 is_nonx_haploids = &(ctx.is_nonx_haploids[parity][0]);
8100 is_relevant_xs = &(ctx.is_relevant_xs[parity][0]);
8101 is_ys = &(ctx.is_ys[parity][0]);
8102 ploidy_m1s = &(ctx.ploidy_m1s[parity][0]);
8103 block_vidx = 0;
8104 sparse_vidx = 0;
8105 }
8106 }
8107 if (unlikely(TextStreamErrcode2(&score_txs, &reterr))) {
8108 goto ScoreReport_ret_TSTREAM_FAIL;
8109 }
8110 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct_nz; ++qsr_idx) {
8111 VecW* missing_diploid_acc4 = &(missing_diploid_accx[acc4_vec_ct * 11 * qsr_idx]);
8112 VecW* missing_diploid_acc8 = &(missing_diploid_acc4[acc4_vec_ct]);
8113 VecW* missing_diploid_acc32 = &(missing_diploid_acc8[acc8_vec_ct]);
8114 VecW* missing_haploid_acc4 = &(missing_haploid_accx[acc4_vec_ct * 11 * qsr_idx]);
8115 VecW* missing_haploid_acc8 = &(missing_haploid_acc4[acc4_vec_ct]);
8116 VecW* missing_haploid_acc32 = &(missing_haploid_acc8[acc8_vec_ct]);
8117 VcountIncr4To8(missing_diploid_acc4, acc4_vec_ct, missing_diploid_acc8);
8118 VcountIncr8To32(missing_diploid_acc8, acc8_vec_ct, missing_diploid_acc32);
8119 VcountIncr4To8(missing_haploid_acc4, acc4_vec_ct, missing_haploid_acc8);
8120 VcountIncr8To32(missing_haploid_acc8, acc8_vec_ct, missing_haploid_acc32);
8121 }
8122 const uint32_t is_not_first_block = ThreadsAreActive(&tg);
8123 putc_unlocked('\r', stdout);
8124 if (missing_var_id_ct || missing_allele_code_ct || duplicated_var_id_ct) {
8125 missing_var_id_ct -= duplicated_var_id_ct;
8126 if (!missing_var_id_ct) {
8127 if (missing_allele_code_ct) {
8128 if (missing_allele_code_ct == 1) {
8129 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: 1 entry in %s was skipped due to a mismatching allele code.\n", multi_input? "-list" : "", cur_input_fname);
8130 } else {
8131 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: %" PRIuPTR " entries in %s were skipped due to mismatching allele codes.\n", multi_input? "-list" : "", missing_allele_code_ct, cur_input_fname);
8132 }
8133 }
8134 } else if (!missing_allele_code_ct) {
8135 if (missing_var_id_ct == 1) {
8136 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: 1 entry in %s was skipped due to a missing variant ID.\n", multi_input? "-list" : "", cur_input_fname);
8137 } else {
8138 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: %" PRIuPTR " entries in %s were skipped due to missing variant IDs.\n", multi_input? "-list" : "", missing_var_id_ct, cur_input_fname);
8139 }
8140 } else {
8141 char* warning_write_iter = strcpya_k(g_logbuf, "Warning: --score");
8142 if (multi_input) {
8143 warning_write_iter = strcpya_k(warning_write_iter, "-list");
8144 }
8145 warning_write_iter = strcpya_k(warning_write_iter, ": ");
8146 if (missing_var_id_ct == 1) {
8147 warning_write_iter = strcpya_k(warning_write_iter, "1 entry in ");
8148 warning_write_iter = strcpya(warning_write_iter, cur_input_fname);
8149 warning_write_iter = strcpya_k(warning_write_iter," was skipped due to a missing variant ID");
8150 } else {
8151 warning_write_iter = i64toa(missing_var_id_ct, warning_write_iter);
8152 warning_write_iter = strcpya_k(warning_write_iter, " entries in ");
8153 warning_write_iter = strcpya(warning_write_iter, cur_input_fname);
8154 warning_write_iter = strcpya_k(warning_write_iter, " were skipped due to missing variant IDs");
8155 }
8156 warning_write_iter = strcpya_k(warning_write_iter, ", and ");
8157 if (missing_allele_code_ct == 1) {
8158 warning_write_iter = strcpya_k(warning_write_iter, "1 was skipped due to a mismatching allele code");
8159 } else {
8160 warning_write_iter = i64toa(missing_allele_code_ct, warning_write_iter);
8161 warning_write_iter = strcpya_k(warning_write_iter, " were skipped due to mismatching allele codes");
8162 }
8163 strcpy_k(warning_write_iter, ".\n");
8164 }
8165 WordWrapB(0);
8166 logerrputsb();
8167 if (duplicated_var_id_ct) {
8168 if (duplicated_var_id_ct == 1) {
8169 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: 1 entry in %s was skipped since its variant ID appears multiple times in the main dataset.\n", multi_input? "-list" : "", cur_input_fname);
8170 } else {
8171 snprintf(g_logbuf, kLogbufSize, "Warning: --score%s: %" PRIuPTR " entries in %s were skipped since their variant IDs appear multiple times in the main dataset.\n", multi_input? "-list" : "", duplicated_var_id_ct, cur_input_fname);
8172 }
8173 WordWrapB(0);
8174 logerrputsb();
8175 }
8176 if (!list_variants) {
8177 logerrputs("(Add the 'list-variants' modifier to see which variants were actually used for\nscoring.)\n");
8178 }
8179 }
8180 if (block_vidx) {
8181 if (is_not_first_block) {
8182 JoinThreads(&tg);
8183 }
8184 } else if (unlikely(!valid_variant_ct)) {
8185 logerrprintf("Error: --score%s: No valid variants in %s.\n", multi_input? "-list" : "", cur_input_fname);
8186 goto ScoreReport_ret_DEGENERATE_DATA;
8187 } else {
8188 JoinThreads(&tg);
8189 }
8190 DeclareLastThreadBlock(&tg);
8191 ctx.cur_variant_batch_size = block_vidx;
8192 if (se_mode) {
8193 const uint32_t dense_ct = block_vidx - sparse_vidx;
8194 if (dense_ct) {
8195 for (uintptr_t score_final_col_idx = 0; score_final_col_idx != score_final_col_ct; ++score_final_col_idx) {
8196 double* score_dense_coefs_row = &(score_dense_coefs_cmaj[score_final_col_idx * kScoreVariantBlockSize]);
8197 for (uint32_t uii = 0; uii != dense_ct; ++uii) {
8198 score_dense_coefs_row[uii] *= score_dense_coefs_row[uii];
8199 }
8200 }
8201 }
8202 for (uintptr_t ulii = 0; ulii != sparse_vidx * score_final_col_ct; ++ulii) {
8203 score_sparse_coefs_vmaj[ulii] *= score_sparse_coefs_vmaj[ulii];
8204 }
8205 }
8206 if (unlikely(SpawnThreads(&tg))) {
8207 goto ScoreReport_ret_THREAD_CREATE_FAIL;
8208 }
8209 JoinThreads(&tg);
8210 // Sparse-optimization postprocessing.
8211 if (common_geno_sum_incrs) {
8212 uint64_t* ddosage_sums_iter = ctx.ddosage_sums;
8213 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
8214 for (uint32_t qsr_idx = 0; qsr_idx != qsr_ct_nz; ++qsr_idx) {
8215 *ddosage_sums_iter += common_geno_sum_incrs[qsr_idx] * S_CAST(uint64_t, kDosageMax);
8216 ++ddosage_sums_iter;
8217 }
8218 }
8219 uintptr_t cur_sample_shard_size = sample_shard_size;
8220 for (uint32_t shard_idx = 0; ; ++shard_idx) {
8221 if (shard_idx >= sample_shard_ct_m1) {
8222 if (shard_idx > sample_shard_ct_m1) {
8223 break;
8224 }
8225 cur_sample_shard_size = sample_ct - sample_shard_ct_m1 * sample_shard_size;
8226 }
8227 double* shard_final_scores_cmaj_iter = ctx.sharded_final_scores_cmaj[shard_idx];
8228 for (uintptr_t ulii = 0; ulii != score_final_col_ct; ++ulii) {
8229 const double cur_score_incr = common_score_incrs[ulii];
8230 for (uint32_t shard_sample_idx = 0; shard_sample_idx != cur_sample_shard_size; ++shard_sample_idx) {
8231 *shard_final_scores_cmaj_iter += cur_score_incr;
8232 ++shard_final_scores_cmaj_iter;
8233 }
8234 }
8235 }
8236 }
8237 if (se_mode) {
8238 // sample_ct * score_final_col_ct
8239 uintptr_t cur_sample_shard_size = sample_shard_size;
8240 for (uint32_t shard_idx = 0; ; ++shard_idx) {
8241 if (shard_idx >= sample_shard_ct_m1) {
8242 if (shard_idx > sample_shard_ct_m1) {
8243 break;
8244 }
8245 cur_sample_shard_size = sample_ct - sample_shard_ct_m1 * sample_shard_size;
8246 }
8247 double* shard_final_scores_cmaj = ctx.sharded_final_scores_cmaj[shard_idx];
8248 for (uintptr_t ulii = 0; ulii != cur_sample_shard_size * score_final_col_ct; ++ulii) {
8249 shard_final_scores_cmaj[ulii] = sqrt(shard_final_scores_cmaj[ulii]);
8250 }
8251 }
8252 }
8253 // Now compute and spill scores to temporary file.
8254 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct_nz; ++qsr_idx) {
8255 const uint32_t* scrambled_missing_diploid_cts = &(R_CAST(uint32_t*, missing_diploid_accx)[acc4_vec_ct * (3 + 11 * qsr_idx) * kInt32PerVec]);
8256 const uint32_t* scrambled_missing_haploid_cts = &(R_CAST(uint32_t*, missing_haploid_accx)[acc4_vec_ct * (3 + 11 * qsr_idx) * kInt32PerVec]);
8257
8258 uint32_t cur_shard_start = 0;
8259 uintptr_t cur_sample_shard_size = sample_shard_size;
8260 uintptr_t sample_uidx_base = 0;
8261 uintptr_t sample_include_bits = sample_include[0];
8262 for (uint32_t shard_idx = 0; ; ++shard_idx) {
8263 if (shard_idx >= sample_shard_ct_m1) {
8264 if (shard_idx > sample_shard_ct_m1) {
8265 break;
8266 }
8267 cur_sample_shard_size = sample_ct - cur_shard_start;
8268 }
8269 const double* shard_final_scores_cmaj = ctx.sharded_final_scores_cmaj[shard_idx];
8270 for (uint32_t shard_sample_idx = 0; shard_sample_idx != cur_sample_shard_size; ++shard_sample_idx) {
8271 const uint32_t sample_idx = shard_sample_idx + cur_shard_start;
8272 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
8273 const uint32_t scrambled_idx = VcountScramble1(sample_idx);
8274 uint32_t denom = allele_ct_bases[qsr_idx] + IsSet(sex_nonfemale, sample_uidx) * nonfemale_allele_ct_incrs[qsr_idx] - IsSet(sex_male, sample_uidx) * male_allele_ct_decrs[qsr_idx];
8275 if (no_meanimpute) {
8276 const uint32_t nallele = denom - 2 * scrambled_missing_diploid_cts[scrambled_idx] - scrambled_missing_haploid_cts[scrambled_idx];
8277 denom = nallele;
8278 }
8279 const double* final_score_col = &(shard_final_scores_cmaj[shard_sample_idx]);
8280 if (write_score_avgs) {
8281 const double denom_recip = 1.0 / S_CAST(double, denom);
8282 double* tmpfile_write_iter = tmpfile_buf;
8283 for (uintptr_t score_final_col_idx = qsr_idx; score_final_col_idx < score_final_col_ct; score_final_col_idx += qsr_ct_nz) {
8284 *tmpfile_write_iter++ = final_score_col[score_final_col_idx * cur_sample_shard_size] * denom_recip;
8285 }
8286 if (unlikely(fwrite_checked(tmpfile_buf, tmpfile_buf_byte_ct, score_tmpfile))) {
8287 goto ScoreReport_ret_WRITE_FAIL;
8288 }
8289 }
8290 if (write_score_sums) {
8291 double* tmpfile_write_iter = tmpfile_buf;
8292 for (uint32_t score_final_col_idx = qsr_idx; score_final_col_idx < score_final_col_ct; score_final_col_idx += qsr_ct_nz) {
8293 *tmpfile_write_iter++ = final_score_col[score_final_col_idx * cur_sample_shard_size];
8294 }
8295 if (unlikely(fwrite_checked(tmpfile_buf, tmpfile_buf_byte_ct, score_tmpfile))) {
8296 goto ScoreReport_ret_WRITE_FAIL;
8297 }
8298 }
8299 }
8300 cur_shard_start += cur_sample_shard_size;
8301 }
8302 }
8303 if (multi_input) {
8304 logprintf("--score-list file %u/%u: %u variant%s processed.\n", file_idx1, infile_ct, valid_variant_ct, (valid_variant_ct == 1)? "" : "s");
8305 } else {
8306 logprintf("--score: %u variant%s processed.\n", valid_variant_ct, (valid_variant_ct == 1)? "" : "s");
8307 }
8308 }
8309 if (unlikely(fclose_null(&score_tmpfile))) {
8310 goto ScoreReport_ret_WRITE_FAIL;
8311 }
8312 if (list_variants) {
8313 if (unlikely(CswriteCloseNull(&css, cswritep))) {
8314 goto ScoreReport_ret_WRITE_FAIL;
8315 }
8316 cswritep = nullptr;
8317 logprintf("--score: Variant list written to %s .\n", outname);
8318 }
8319
8320 snprintf(outname_end, kMaxOutfnameExtBlen, ".sscore.tmp");
8321 if (unlikely(fopen_checked(outname, FOPEN_RB, &score_tmpfile))) {
8322 goto ScoreReport_ret_OPEN_FAIL;
8323 }
8324
8325 // major: file_idx
8326 // then qsr_idx (out of qsr_ct_nz)
8327 // then sample_idx (out of sample_ct)
8328 // then score_avgs vs. score_sums (out of write_type_ct)
8329 // then score_col_idx within a single input (out of score_col_ct doubles)
8330 const uint32_t write_type_ct = write_score_avgs + write_score_sums;
8331 const uint64_t sample_idx_stride = write_type_ct * score_col_ct;
8332 const uint64_t file_idx_stride = sample_idx_stride * sample_ct * qsr_ct_nz;
8333 const uint32_t* scrambled_missing_diploid_cts = nullptr;
8334 const uint32_t* scrambled_missing_haploid_cts = nullptr;
8335 double* saved_scores = nullptr;
8336 double* cur_saved_scores = tmpfile_buf;
8337 for (uintptr_t qsr_idx = 0; qsr_idx != qsr_ct_nz; ++qsr_idx) {
8338 BigstackReset(bigstack_mark);
8339 char* outname_end2 = outname_end;
8340 if (range_names) {
8341 *outname_end2++ = '.';
8342 outname_end2 = strcpya(outname_end2, range_names[qsr_idx]);
8343 }
8344 OutnameZstSet(".sscore", output_zst, outname_end2);
8345 reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css);
8346 if (unlikely(reterr)) {
8347 goto ScoreReport_ret_1;
8348 }
8349 cswritep = overflow_buf;
8350
8351 if (!qsr_idx) {
8352 const uint64_t saved_scores_byte_ct = S_CAST(uint64_t, score_final_col_ct) * infile_ct * sample_ct * write_type_ct * sizeof(double);
8353 if (saved_scores_byte_ct <= bigstack_left()) {
8354 // Guaranteed to not exhaust memory, since there are no allocations
8355 // after this point, and if qsr_ct > 1 the subsequent InitCstream()
8356 // calls will allocate the same memory as the first one.
8357 saved_scores = S_CAST(double*, bigstack_end_alloc_raw_rd(saved_scores_byte_ct));
8358 if (unlikely(fread_checked(saved_scores, saved_scores_byte_ct, score_tmpfile))) {
8359 goto ScoreReport_ret_READ_TMP_FAIL;
8360 }
8361 }
8362 }
8363 const uint32_t write_fid = FidColIsRequired(siip, flags / kfScoreColMaybefid);
8364 const char* sample_ids = siip->sample_ids;
8365 const char* sids = siip->sids;
8366 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
8367 const uintptr_t max_sid_blen = siip->max_sid_blen;
8368 const uint32_t write_sid = SidColIsRequired(sids, flags / kfScoreColMaybesid);
8369 const uint32_t write_empty_pheno = (flags & kfScoreColPheno1) && (!pheno_ct);
8370 const uint32_t write_phenos = (flags & (kfScoreColPheno1 | kfScoreColPhenos)) && pheno_ct;
8371 if (write_phenos && (!(flags & kfScoreColPhenos))) {
8372 pheno_ct = 1;
8373 }
8374 *cswritep++ = '#';
8375 if (write_fid) {
8376 cswritep = strcpya_k(cswritep, "FID\t");
8377 }
8378 cswritep = strcpya_k(cswritep, "IID");
8379 if (write_sid) {
8380 cswritep = strcpya_k(cswritep, "\tSID");
8381 }
8382 if (write_phenos) {
8383 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
8384 *cswritep++ = '\t';
8385 cswritep = strcpya(cswritep, &(pheno_names[pheno_idx * max_pheno_name_blen]));
8386 if (unlikely(Cswrite(&css, &cswritep))) {
8387 goto ScoreReport_ret_WRITE_FAIL;
8388 }
8389 }
8390 } else if (write_empty_pheno) {
8391 cswritep = strcpya_k(cswritep, "\tPHENO1");
8392 }
8393 const uint32_t write_nallele = (flags / kfScoreColNallele) & 1;
8394 if (write_nallele) {
8395 cswritep = strcpya_k(cswritep, "\tALLELE_CT");
8396 }
8397 const uint32_t write_denom = (flags / kfScoreColDenom) & 1;
8398 if (write_denom) {
8399 cswritep = strcpya_k(cswritep, "\tDENOM");
8400 }
8401 const uint32_t write_dosage_sum = (flags / kfScoreColDosageSum) & 1;
8402 if (write_dosage_sum) {
8403 cswritep = strcpya_k(cswritep, "\tNAMED_ALLELE_DOSAGE_SUM");
8404 }
8405 if (write_score_avgs) {
8406 for (uint32_t global_score_col_idx = 0; global_score_col_idx != global_score_col_ct; ++global_score_col_idx) {
8407 *cswritep++ = '\t';
8408 cswritep = strcpya(cswritep, score_col_names[global_score_col_idx]);
8409 cswritep = strcpya_k(cswritep, "_AVG");
8410 if (unlikely(Cswrite(&css, &cswritep))) {
8411 goto ScoreReport_ret_WRITE_FAIL;
8412 }
8413 }
8414 }
8415 if (write_score_sums) {
8416 for (uint32_t global_score_col_idx = 0; global_score_col_idx != global_score_col_ct; ++global_score_col_idx) {
8417 *cswritep++ = '\t';
8418 cswritep = strcpya(cswritep, score_col_names[global_score_col_idx]);
8419 cswritep = strcpya_k(cswritep, "_SUM");
8420 if (unlikely(Cswrite(&css, &cswritep))) {
8421 goto ScoreReport_ret_WRITE_FAIL;
8422 }
8423 }
8424 }
8425 AppendBinaryEoln(&cswritep);
8426 if (!multi_input) {
8427 scrambled_missing_diploid_cts = &(R_CAST(uint32_t*, missing_diploid_accx)[acc4_vec_ct * (3 + 11 * qsr_idx) * kInt32PerVec]);
8428 scrambled_missing_haploid_cts = &(R_CAST(uint32_t*, missing_haploid_accx)[acc4_vec_ct * (3 + 11 * qsr_idx) * kInt32PerVec]);
8429 }
8430 const uint32_t omp_slen = strlen(output_missing_pheno);
8431
8432 uintptr_t sample_uidx_base = 0;
8433 uintptr_t sample_include_bits = sample_include[0];
8434 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
8435 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
8436 cswritep = AppendXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep);
8437 if (write_phenos) {
8438 // er, this probably belongs in its own function
8439 for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) {
8440 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
8441 const PhenoDtype type_code = cur_pheno_col->type_code;
8442 *cswritep++ = '\t';
8443 if (type_code <= kPhenoDtypeQt) {
8444 if (!IsSet(cur_pheno_col->nonmiss, sample_uidx)) {
8445 cswritep = memcpya(cswritep, output_missing_pheno, omp_slen);
8446 } else if (type_code == kPhenoDtypeCc) {
8447 *cswritep++ = '1' + IsSet(cur_pheno_col->data.cc, sample_uidx);
8448 } else {
8449 cswritep = dtoa_g(cur_pheno_col->data.qt[sample_uidx], cswritep);
8450 }
8451 } else {
8452 // category index guaranteed to be zero for missing values
8453 cswritep = strcpya(cswritep, cur_pheno_col->category_names[cur_pheno_col->data.cat[sample_uidx]]);
8454 if (unlikely(Cswrite(&css, &cswritep))) {
8455 goto ScoreReport_ret_WRITE_FAIL;
8456 }
8457 }
8458 }
8459 } else if (write_empty_pheno) {
8460 *cswritep++ = '\t';
8461 cswritep = memcpya(cswritep, output_missing_pheno, omp_slen);
8462 }
8463
8464 if (!multi_input) {
8465 const uint32_t scrambled_idx = VcountScramble1(sample_idx);
8466 uint32_t denom = allele_ct_bases[qsr_idx] + IsSet(sex_nonfemale, sample_uidx) * nonfemale_allele_ct_incrs[qsr_idx] - IsSet(sex_male, sample_uidx) * male_allele_ct_decrs[qsr_idx];
8467 const uint32_t nallele = denom - 2 * scrambled_missing_diploid_cts[scrambled_idx] - scrambled_missing_haploid_cts[scrambled_idx];
8468 if (write_nallele) {
8469 *cswritep++ = '\t';
8470 cswritep = u32toa(nallele, cswritep);
8471 }
8472 if (no_meanimpute) {
8473 denom = nallele;
8474 }
8475 if (write_denom) {
8476 *cswritep++ = '\t';
8477 cswritep = u32toa(denom, cswritep);
8478 }
8479 if (write_dosage_sum) {
8480 *cswritep++ = '\t';
8481 cswritep = ddosagetoa(ctx.ddosage_sums[sample_idx + qsr_idx * sample_ct], cswritep);
8482 }
8483 }
8484 uint64_t qsr_sample_idx_offset = (qsr_idx * sample_ct + sample_idx) * sample_idx_stride;
8485 for (uint32_t write_type_idx = 0; write_type_idx != write_type_ct; ++write_type_idx) {
8486 if (write_type_idx == 1) {
8487 qsr_sample_idx_offset += score_col_ct;
8488 }
8489 for (uintptr_t file_idx = 0; file_idx != infile_ct; ++file_idx) {
8490 const uint64_t tmp_idx = file_idx * file_idx_stride + qsr_sample_idx_offset;
8491 if (saved_scores) {
8492 cur_saved_scores = &(saved_scores[tmp_idx]);
8493 } else {
8494 if (unlikely(fseeko(score_tmpfile, tmp_idx * sizeof(double), SEEK_SET) ||
8495 fread_checked(cur_saved_scores, tmpfile_buf_byte_ct, score_tmpfile))) {
8496 goto ScoreReport_ret_READ_TMP_FAIL;
8497 }
8498 }
8499 for (uintptr_t score_col_idx = 0; score_col_idx != score_col_ct; ++score_col_idx) {
8500 *cswritep++ = '\t';
8501 cswritep = dtoa_g(cur_saved_scores[score_col_idx], cswritep);
8502 }
8503 }
8504 }
8505 AppendBinaryEoln(&cswritep);
8506 if (unlikely(Cswrite(&css, &cswritep))) {
8507 goto ScoreReport_ret_WRITE_FAIL;
8508 }
8509 }
8510 if (unlikely(CswriteCloseNull(&css, cswritep))) {
8511 goto ScoreReport_ret_WRITE_FAIL;
8512 }
8513 }
8514 if (!qsr_ct) {
8515 logprintfww("--score%s: Results written to %s .\n", multi_input? "-list" : "", outname);
8516 } else {
8517 *outname_end = '\0';
8518 logprintfww("--score%s + --q-score-range: Results written to %s.<range name>.sscore%s .\n", multi_input? "-list" : "", outname, output_zst? ".zst" : "");
8519 }
8520 if (unlikely(fclose_null(&score_tmpfile))) {
8521 goto ScoreReport_ret_READ_TMP_FAIL;
8522 }
8523 snprintf(outname_end, kMaxOutfnameExtBlen, ".sscore.tmp");
8524 if (unlink(outname)) {
8525 logerrprintfww("Error: Failed to delete %s .\n", outname);
8526 goto ScoreReport_ret_WRITE_FAIL;
8527 }
8528 }
8529 while (0) {
8530 ScoreReport_ret_TSTREAM_FAIL:
8531 TextStreamErrPrint(cur_input_fname, &score_txs);
8532 break;
8533 ScoreReport_ret_QSR_RANGE_TSTREAM_FAIL:
8534 TextStreamErrPrint("--q-score-range range file", &score_txs);
8535 break;
8536 ScoreReport_ret_QSR_DATA_TSTREAM_FAIL:
8537 TextStreamErrPrint("--q-score-range data file", &score_txs);
8538 break;
8539 ScoreReport_ret_NOMEM:
8540 reterr = kPglRetNomem;
8541 break;
8542 ScoreReport_ret_OPEN_FAIL:
8543 reterr = kPglRetOpenFail;
8544 break;
8545 ScoreReport_ret_READ_TMP_FAIL:
8546 logerrprintfww(kErrprintfFread, "--score[-list] temporary file", rstrerror(errno));
8547 reterr = kPglRetReadFail;
8548 break;
8549 ScoreReport_ret_WRITE_FAIL:
8550 reterr = kPglRetWriteFail;
8551 break;
8552 ScoreReport_ret_INVALID_CMDLINE:
8553 reterr = kPglRetInvalidCmdline;
8554 break;
8555 ScoreReport_ret_MALFORMED_INPUT_WW:
8556 WordWrapB(0);
8557 fputs("\n", stdout);
8558 logerrputsb();
8559 ScoreReport_ret_MALFORMED_INPUT:
8560 reterr = kPglRetMalformedInput;
8561 break;
8562 ScoreReport_ret_QSR_DATA_MISSING_TOKENS:
8563 logerrprintfww("Error: Line %" PRIuPTR " of --q-score-range data file has fewer tokens than expected.\n", line_idx);
8564 reterr = kPglRetInconsistentInput;
8565 break;
8566 ScoreReport_ret_MISSING_TOKENS:
8567 fputs("\n", stdout);
8568 logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, cur_input_fname);
8569 reterr = kPglRetInconsistentInput;
8570 break;
8571 ScoreReport_ret_INCONSISTENT_INPUT_WW:
8572 WordWrapB(0);
8573 fputs("\n", stdout);
8574 logerrputsb();
8575 ScoreReport_ret_INCONSISTENT_INPUT:
8576 reterr = kPglRetInconsistentInput;
8577 break;
8578 ScoreReport_ret_THREAD_CREATE_FAIL:
8579 reterr = kPglRetThreadCreateFail;
8580 break;
8581 ScoreReport_ret_DEGENERATE_DATA_WW:
8582 WordWrapB(0);
8583 fputs("\n", stdout);
8584 logerrputsb();
8585 ScoreReport_ret_DEGENERATE_DATA:
8586 reterr = kPglRetDegenerateData;
8587 break;
8588 ScoreReport_ret_TOO_MANY_COLUMNS:
8589 logerrprintf("Error: --score%s: Too many score columns.\n", (score_info_ptr->flags & kfScoreMultiInput)? "-list" : "");
8590 reterr = kPglRetNotYetSupported;
8591 break;
8592 }
8593 ScoreReport_ret_1:
8594 fclose_cond(score_tmpfile);
8595 CswriteCloseCond(&css, cswritep);
8596 CleanupThreads(&tg);
8597 BLAS_SET_NUM_THREADS(1);
8598 CleanupTextStream2("--score[-list] file", &score_txs, &reterr);
8599 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
8600 return reterr;
8601 }
8602
8603 typedef struct VscoreCtxStruct {
8604 const uintptr_t* variant_include;
8605 const ChrInfo* cip;
8606 const uintptr_t* allele_idx_offsets;
8607 const double* allele_freqs;
8608 const uintptr_t* sample_include;
8609 const uint32_t* sample_include_cumulative_popcounts;
8610 const uintptr_t* sex_male_collapsed;
8611 const uintptr_t* sex_male_interleaved_vec;
8612 const float* wts_f_smaj;
8613 const double* wts_d_smaj;
8614 uint32_t vscore_ct;
8615 uint32_t sample_ct;
8616 uint32_t male_ct;
8617 uint32_t is_xchr_model_1;
8618
8619 PgenReader** pgr_ptrs;
8620 uintptr_t** genovecs;
8621 uintptr_t** raregenos;
8622 uint32_t** difflist_sample_id_bufs;
8623 uintptr_t** dosage_presents;
8624 Dosage** dosage_mains;
8625 uint32_t* read_variant_uidx_starts;
8626
8627 uint32_t cur_block_size;
8628
8629 float** dosage_f_vmaj_bufs;
8630 float** tmp_f_result_bufs;
8631 double** dosage_d_vmaj_bufs;
8632 double** tmp_d_result_bufs;
8633 #ifdef USE_CUDA
8634 CublasFmultiplier* cfms;
8635 #endif
8636
8637 // variant-major
8638 float* results_f[2];
8639 double* results_d[2];
8640
8641 uint32_t* missing_cts[2];
8642
8643 // high 32 bits = unused for now
8644 // low 32 bits = uint32_t(PglErr)
8645 uint64_t err_info;
8646 } VscoreCtx;
8647
8648 // This setting seems optimal on my Mac (smaller doesn't take full advantage of
8649 // AVX, larger creates cache problems?).
8650 CONSTI32(kVscoreBlockSize, 32);
8651
8652 THREAD_FUNC_DECL VscoreThread(void* raw_arg) {
8653 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
8654 const uintptr_t tidx = arg->tidx;
8655 VscoreCtx* ctx = S_CAST(VscoreCtx*, arg->sharedp->context);
8656
8657 const uintptr_t* variant_include = ctx->variant_include;
8658 const ChrInfo* cip = ctx->cip;
8659 const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets;
8660 const double* allele_freqs = ctx->allele_freqs;
8661 const uintptr_t* sample_include = ctx->sample_include;
8662 const uintptr_t* sex_male = ctx->sex_male_collapsed;
8663 const uintptr_t* sex_male_interleaved_vec = ctx->sex_male_interleaved_vec;
8664 const float* wts_f_smaj = ctx->wts_f_smaj;
8665 const double* wts_d_smaj = ctx->wts_d_smaj;
8666
8667 PgenReader* pgrp = ctx->pgr_ptrs[tidx];
8668 PgrSampleSubsetIndex pssi;
8669 PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi);
8670 uintptr_t* genovec = ctx->genovecs[tidx];
8671 uintptr_t* raregeno = ctx->raregenos[tidx];
8672 uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx];
8673 uintptr_t* dosage_present = nullptr;
8674 Dosage* dosage_main = nullptr;
8675 if (ctx->dosage_presents) {
8676 dosage_present = ctx->dosage_presents[tidx];
8677 dosage_main = ctx->dosage_mains[tidx];
8678 }
8679
8680 const uintptr_t vscore_ct = ctx->vscore_ct;
8681 const uintptr_t sample_ct = ctx->sample_ct;
8682 const uint32_t male_ct = ctx->male_ct;
8683 const uint32_t nonmale_ct = sample_ct - male_ct;
8684 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
8685 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
8686 const uint32_t is_xchr_model_1 = ctx->is_xchr_model_1;
8687 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
8688
8689 const uint32_t single_prec = (wts_f_smaj != nullptr);
8690 #ifdef USE_CUDA
8691 CublasFmultiplier* cfmp = ctx->cfms? &(ctx->cfms[tidx]) : nullptr;
8692 const uint32_t max_sparse = sample_ct / (single_prec? (cfmp? 64 : 32) : 16);
8693 #else
8694 const uint32_t max_sparse = sample_ct / (single_prec? 32 : 16);
8695 #endif
8696
8697 float* tmp_f_result_buf = nullptr;
8698 double* tmp_d_result_buf = nullptr;
8699 uint16_t cur_bidxs[kVscoreBlockSize];
8700
8701 float* dosage_f_vmaj = nullptr;
8702 double* dosage_d_vmaj = nullptr;
8703 if (single_prec) {
8704 tmp_f_result_buf = ctx->tmp_f_result_bufs[tidx];
8705 dosage_f_vmaj = ctx->dosage_f_vmaj_bufs[tidx];
8706 #ifdef USE_CUDA
8707 if (CudaSetDevice(cfmp->device_idx)) {
8708 fputs("unexpected CudaSetDevice() failure in VscoreThread()\n", stderr);
8709 exit(S_CAST(int, kPglRetGpuFail));
8710 }
8711 #endif
8712 } else {
8713 tmp_d_result_buf = ctx->tmp_d_result_bufs[tidx];
8714 dosage_d_vmaj = ctx->dosage_d_vmaj_bufs[tidx];
8715 }
8716
8717 uint32_t is_y = 0;
8718 uint32_t is_x_or_y = 0;
8719 uint32_t is_nonxy_haploid = 0;
8720 uint32_t chr_end = 0;
8721 double slope = 0.0;
8722
8723 uint32_t dosage_ct = 0;
8724
8725 uint32_t parity = 0;
8726 uint64_t new_err_info = 0;
8727 do {
8728 const uintptr_t cur_block_size = ctx->cur_block_size;
8729 const uint32_t bidx_end = ((tidx + 1) * cur_block_size) / calc_thread_ct;
8730 float* cur_results_f = ctx->results_f[parity];
8731 double* cur_results_d = ctx->results_d[parity];
8732 uint32_t* missing_cts = ctx->missing_cts[parity];
8733 uintptr_t row_idx = 0;
8734 uintptr_t variant_uidx_base;
8735 uintptr_t variant_include_bits;
8736 BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
8737 for (uint32_t variant_bidx = (tidx * cur_block_size) / calc_thread_ct; variant_bidx != bidx_end; ++variant_bidx) {
8738 const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
8739 if (variant_uidx >= chr_end) {
8740 const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
8741 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
8742 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
8743 is_y = 0;
8744 is_nonxy_haploid = 0;
8745 if (chr_idx == x_code) {
8746 is_x_or_y = is_xchr_model_1;
8747 } else if (chr_idx == y_code) {
8748 is_x_or_y = 1;
8749 is_y = 1;
8750 } else {
8751 is_x_or_y = 0;
8752 is_nonxy_haploid = IsSet(cip->haploid_mask, chr_idx);
8753 }
8754 slope = (is_nonxy_haploid || is_y)? 0.5 : 1.0;
8755 }
8756 double ref_freq;
8757 if (!allele_idx_offsets) {
8758 ref_freq = allele_freqs[variant_uidx];
8759 } else {
8760 ref_freq = allele_freqs[allele_idx_offsets[variant_uidx] - variant_uidx];
8761 }
8762 const double missing_val = slope * 2 * (1.0 - ref_freq);
8763 if (!dosage_present) {
8764 uint32_t difflist_common_geno;
8765 uint32_t difflist_len;
8766 PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_sparse, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
8767 if (unlikely(reterr)) {
8768 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
8769 goto VscoreThread_err;
8770 }
8771 if (difflist_common_geno != UINT32_MAX) {
8772 if ((!is_x_or_y) && (!difflist_common_geno)) {
8773
8774 float* target_f = nullptr;
8775 double* target_d = nullptr;
8776 if (single_prec) {
8777 target_f = &(cur_results_f[variant_bidx * vscore_ct]);
8778 } else {
8779 target_d = &(cur_results_d[variant_bidx * vscore_ct]);
8780 }
8781 uint32_t missing_ct = 0;
8782 if (!difflist_len) {
8783 if (single_prec) {
8784 ZeroFArr(vscore_ct, target_f);
8785 } else {
8786 ZeroDArr(vscore_ct, target_d);
8787 }
8788 } else {
8789 ZeroTrailingNyps(difflist_len, raregeno);
8790 if (single_prec) {
8791 ZeroFArr(vscore_ct * 3, tmp_f_result_buf);
8792 } else {
8793 ZeroDArr(vscore_ct * 3, tmp_d_result_buf);
8794 }
8795 const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
8796 uint32_t loop_len = kBitsPerWordD2;
8797 for (uint32_t widx = 0; ; ++widx) {
8798 if (widx >= word_ct_m1) {
8799 if (widx > word_ct_m1) {
8800 break;
8801 }
8802 loop_len = ModNz(difflist_len, kBitsPerWordD2);
8803 }
8804 // slightly nicer to work with 2..0 than 1..3 row-indexes
8805 uintptr_t raregeno_word = raregeno[widx];
8806 uintptr_t raregeno_invword = ~raregeno_word;
8807 missing_ct += Popcount01Word(raregeno_word & (raregeno_word >> 1) & kMask5555);
8808 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
8809 if (single_prec) {
8810 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8811 const uintptr_t sample_idx = cur_difflist_sample_ids[uii];
8812 const uint32_t cur_invgeno = raregeno_invword & 3;
8813 const float* incr_src = &(wts_f_smaj[sample_idx * vscore_ct]);
8814 float* incr_dst = &(tmp_f_result_buf[cur_invgeno * vscore_ct]);
8815 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8816 incr_dst[ulii] += incr_src[ulii];
8817 }
8818 raregeno_invword = raregeno_invword >> 2;
8819 }
8820 } else {
8821 for (uint32_t uii = 0; uii != loop_len; ++uii) {
8822 const uintptr_t sample_idx = cur_difflist_sample_ids[uii];
8823 const uint32_t cur_invgeno = raregeno_invword & 3;
8824 const double* incr_src = &(wts_d_smaj[sample_idx * vscore_ct]);
8825 double* incr_dst = &(tmp_d_result_buf[cur_invgeno * vscore_ct]);
8826 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8827 incr_dst[ulii] += incr_src[ulii];
8828 }
8829 raregeno_invword = raregeno_invword >> 2;
8830 }
8831 }
8832 }
8833 if (single_prec) {
8834 if (!is_nonxy_haploid) {
8835 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8836 target_f[ulii] = 2 * tmp_f_result_buf[ulii + vscore_ct] + tmp_f_result_buf[ulii + 2 * vscore_ct];
8837 }
8838 } else {
8839 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8840 target_f[ulii] = tmp_f_result_buf[ulii + vscore_ct] + S_CAST(float, 0.5) * tmp_f_result_buf[ulii + 2 * vscore_ct];
8841 }
8842 }
8843 if (missing_ct) {
8844 const float missing_val_f = S_CAST(float, missing_val);
8845 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8846 target_f[ulii] += missing_val_f * tmp_f_result_buf[ulii];
8847 }
8848 }
8849 } else {
8850 if (!is_nonxy_haploid) {
8851 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8852 target_d[ulii] = 2 * tmp_d_result_buf[ulii + vscore_ct] + tmp_d_result_buf[ulii + 2 * vscore_ct];
8853 }
8854 } else {
8855 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8856 target_d[ulii] = tmp_d_result_buf[ulii + vscore_ct] + 0.5 * tmp_d_result_buf[ulii + 2 * vscore_ct];
8857 }
8858 }
8859 if (missing_ct) {
8860 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8861 target_d[ulii] += missing_val * tmp_d_result_buf[ulii];
8862 }
8863 }
8864 }
8865 }
8866 if (missing_cts) {
8867 missing_cts[variant_bidx] = missing_ct;
8868 }
8869 continue;
8870 }
8871 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, sample_ct, difflist_len, genovec);
8872 }
8873 } else {
8874 PglErr reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
8875 if (unlikely(reterr)) {
8876 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
8877 goto VscoreThread_err;
8878 }
8879 if ((!is_x_or_y) && (dosage_ct <= max_sparse)) {
8880 STD_ARRAY_DECL(uint32_t, 4, genocounts);
8881 ZeroTrailingNyps(sample_ct, genovec);
8882 if (!dosage_ct) {
8883 // dosage_present contains garbage if dosage_ct == 0; might want to
8884 // append 'Unsafe' to PgrGetD and similar function names...
8885 ZeroWArr(BitCtToWordCt(sample_ct), dosage_present);
8886 }
8887 GenoarrCountInvsubsetFreqs2(genovec, dosage_present, sample_ct, sample_ct - dosage_ct, genocounts);
8888 if (genocounts[0] >= sample_ct - max_sparse) {
8889 float* target_f = nullptr;
8890 double* target_d = nullptr;
8891 if (single_prec) {
8892 target_f = &(cur_results_f[variant_bidx * vscore_ct]);
8893 } else {
8894 target_d = &(cur_results_d[variant_bidx * vscore_ct]);
8895 }
8896 if (genocounts[0] == sample_ct) {
8897 if (single_prec) {
8898 ZeroFArr(vscore_ct, target_f);
8899 } else {
8900 ZeroDArr(vscore_ct, target_d);
8901 }
8902 } else {
8903 if (single_prec) {
8904 ZeroFArr(vscore_ct * 3, tmp_f_result_buf);
8905 } else {
8906 ZeroDArr(vscore_ct * 3, tmp_d_result_buf);
8907 }
8908 const Halfword* dosage_present_alias = R_CAST(Halfword*, dosage_present);
8909 const uint32_t sample_ctl2 = DivUp(sample_ct, kBitsPerWordD2);
8910 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
8911 uintptr_t geno_word = genovec[widx];
8912 if (!geno_word) {
8913 continue;
8914 }
8915 const uintptr_t dosage_mask = UnpackHalfwordToWord(dosage_present_alias[widx]);
8916 geno_word = geno_word & (~(dosage_mask * 3));
8917 if (!geno_word) {
8918 continue;
8919 }
8920 if (single_prec) {
8921 const float* cur_wts_smaj = &(wts_f_smaj[widx * kBitsPerWordD2 * vscore_ct]);
8922 do {
8923 const uint32_t shift_ct = ctzw(geno_word) & (~1);
8924 const uintptr_t cur_invgeno = 3 & (~(geno_word >> shift_ct));
8925 const float* incr_src = &(cur_wts_smaj[(shift_ct / 2) * vscore_ct]);
8926 float* incr_dst = &(tmp_f_result_buf[cur_invgeno * vscore_ct]);
8927 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8928 incr_dst[ulii] += incr_src[ulii];
8929 }
8930 geno_word &= ~((3 * k1LU) << shift_ct);
8931 } while (geno_word);
8932 } else {
8933 const double* cur_wts_smaj = &(wts_d_smaj[widx * kBitsPerWordD2 * vscore_ct]);
8934 do {
8935 const uint32_t shift_ct = ctzw(geno_word) & (~1);
8936 const uintptr_t cur_invgeno = 3 & (~(geno_word >> shift_ct));
8937 const double* incr_src = &(cur_wts_smaj[(shift_ct / 2) * vscore_ct]);
8938 double* incr_dst = &(tmp_d_result_buf[cur_invgeno * vscore_ct]);
8939 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8940 incr_dst[ulii] += incr_src[ulii];
8941 }
8942 geno_word &= ~((3 * k1LU) << shift_ct);
8943 } while (geno_word);
8944 }
8945 }
8946 if (single_prec) {
8947 if (!is_nonxy_haploid) {
8948 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8949 target_f[ulii] = 2 * tmp_f_result_buf[ulii + vscore_ct] + tmp_f_result_buf[ulii + 2 * vscore_ct];
8950 }
8951 } else {
8952 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8953 target_f[ulii] = tmp_f_result_buf[ulii + vscore_ct] + S_CAST(float, 0.5) * tmp_f_result_buf[ulii + 2 * vscore_ct];
8954 }
8955 }
8956 if (genocounts[3]) {
8957 const float missing_val_f = S_CAST(float, missing_val);
8958 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8959 target_f[ulii] += missing_val_f * tmp_f_result_buf[ulii];
8960 }
8961 }
8962 } else {
8963 if (!is_nonxy_haploid) {
8964 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8965 target_d[ulii] = 2 * tmp_d_result_buf[ulii + vscore_ct] + tmp_d_result_buf[ulii + 2 * vscore_ct];
8966 }
8967 } else {
8968 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8969 target_d[ulii] = tmp_d_result_buf[ulii + vscore_ct] + 0.5 * tmp_d_result_buf[ulii + 2 * vscore_ct];
8970 }
8971 }
8972 if (genocounts[3]) {
8973 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8974 target_d[ulii] += missing_val * tmp_d_result_buf[ulii];
8975 }
8976 }
8977 }
8978 uintptr_t sample_idx_base = 0;
8979 uintptr_t dosage_present_bits = dosage_present[0];
8980 if (single_prec) {
8981 const float slope_f = S_CAST(float, slope);
8982 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
8983 const uintptr_t sample_idx = BitIter1(dosage_present, &sample_idx_base, &dosage_present_bits);
8984 const float* incr_src = &(wts_f_smaj[sample_idx * vscore_ct]);
8985 const float cur_dosage = slope_f * S_CAST(float, kRecipDosageMid) * u31tof(dosage_main[dosage_idx]);
8986 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8987 target_f[ulii] += cur_dosage * incr_src[ulii];
8988 }
8989 }
8990 } else {
8991 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
8992 const uintptr_t sample_idx = BitIter1(dosage_present, &sample_idx_base, &dosage_present_bits);
8993 const double* incr_src = &(wts_d_smaj[sample_idx * vscore_ct]);
8994 const double cur_dosage = slope * kRecipDosageMid * u31tod(dosage_main[dosage_idx]);
8995 for (uintptr_t ulii = 0; ulii != vscore_ct; ++ulii) {
8996 target_d[ulii] += cur_dosage * incr_src[ulii];
8997 }
8998 }
8999 }
9000 }
9001 if (missing_cts) {
9002 missing_cts[variant_bidx] = genocounts[3];
9003 }
9004 continue;
9005 }
9006 }
9007 }
9008
9009 if (row_idx == kVscoreBlockSize) {
9010 if (single_prec) {
9011 #ifdef USE_CUDA
9012 if (cfmp) {
9013 if (unlikely(CublasFmultiplyRowMajor1(dosage_f_vmaj, cfmp, tmp_f_result_buf))) {
9014 new_err_info = S_CAST(uint32_t, kPglRetGpuFail);
9015 goto VscoreThread_err;
9016 }
9017 } else {
9018 RowMajorFmatrixMultiply(dosage_f_vmaj, wts_f_smaj, kVscoreBlockSize, vscore_ct, sample_ct, tmp_f_result_buf);
9019 }
9020 #else
9021 RowMajorFmatrixMultiply(dosage_f_vmaj, wts_f_smaj, kVscoreBlockSize, vscore_ct, sample_ct, tmp_f_result_buf);
9022 #endif
9023 const float* tmp_f_result_iter = tmp_f_result_buf;
9024 for (uintptr_t ulii = 0; ulii != kVscoreBlockSize; ++ulii) {
9025 const uintptr_t cur_bidx = cur_bidxs[ulii];
9026 memcpy(&(cur_results_f[cur_bidx * vscore_ct]), tmp_f_result_iter, vscore_ct * sizeof(float));
9027 tmp_f_result_iter = &(tmp_f_result_iter[vscore_ct]);
9028 }
9029 } else {
9030 RowMajorMatrixMultiply(dosage_d_vmaj, wts_d_smaj, kVscoreBlockSize, vscore_ct, sample_ct, tmp_d_result_buf);
9031 const double* tmp_d_result_iter = tmp_d_result_buf;
9032 for (uintptr_t ulii = 0; ulii != kVscoreBlockSize; ++ulii) {
9033 const uintptr_t cur_bidx = cur_bidxs[ulii];
9034 memcpy(&(cur_results_d[cur_bidx * vscore_ct]), tmp_d_result_iter, vscore_ct * sizeof(double));
9035 tmp_d_result_iter = &(tmp_d_result_iter[vscore_ct]);
9036 }
9037 }
9038 row_idx = 0;
9039 }
9040 cur_bidxs[row_idx] = variant_bidx;
9041 if (single_prec) {
9042 float* cur_row = &(dosage_f_vmaj[row_idx * sample_ct]);
9043 PopulateRescaledDosageF(genovec, dosage_present, dosage_main, S_CAST(float, slope), S_CAST(float, 0.0), S_CAST(float, missing_val), sample_ct, dosage_ct, cur_row);
9044 if (is_x_or_y) {
9045 // Instead of doing this for every variant, we could precompute
9046 // chrX/chrY weight matrices with male weights halved/nonmale weights
9047 // zeroed out. But the number of chrY variants is typically small
9048 // enough (and how often will --xchr-model 1 be used, anyway?) that I
9049 // don't think it's worth it.
9050 uintptr_t sample_uidx_base = 0;
9051 if (is_y) {
9052 // zero out nonmale values
9053 uintptr_t sex_male_invbits = ~sex_male[0];
9054 for (uint32_t nonmale_idx = 0; nonmale_idx != nonmale_ct; ++nonmale_idx) {
9055 const uintptr_t sample_uidx = BitIter0(sex_male, &sample_uidx_base, &sex_male_invbits);
9056 cur_row[sample_uidx] = S_CAST(float, 0.0);
9057 }
9058 } else {
9059 // xchr_model 1: halve male values
9060 uintptr_t sex_male_bits = sex_male[0];
9061 for (uint32_t male_idx = 0; male_idx != male_ct; ++male_idx) {
9062 const uintptr_t sample_uidx = BitIter1(sex_male, &sample_uidx_base, &sex_male_bits);
9063 cur_row[sample_uidx] *= S_CAST(float, 0.5);
9064 }
9065 }
9066 }
9067 } else {
9068 double* cur_row = &(dosage_d_vmaj[row_idx * sample_ct]);
9069 PopulateRescaledDosage(genovec, dosage_present, dosage_main, slope, 0.0, missing_val, sample_ct, dosage_ct, cur_row);
9070 if (is_x_or_y) {
9071 // Instead of doing this for every variant, we could precompute
9072 // chrX/chrY weight matrices with male weights halved/nonmale weights
9073 // zeroed out. But the number of chrY variants is typically small
9074 // enough (and how often will --xchr-model 1 be used, anyway?) that I
9075 // don't think it's worth it.
9076 uintptr_t sample_uidx_base = 0;
9077 if (is_y) {
9078 // zero out nonmale values
9079 uintptr_t sex_male_invbits = ~sex_male[0];
9080 for (uint32_t nonmale_idx = 0; nonmale_idx != nonmale_ct; ++nonmale_idx) {
9081 const uintptr_t sample_uidx = BitIter0(sex_male, &sample_uidx_base, &sex_male_invbits);
9082 cur_row[sample_uidx] = 0.0;
9083 }
9084 } else {
9085 // xchr_model 1: halve male values
9086 uintptr_t sex_male_bits = sex_male[0];
9087 for (uint32_t male_idx = 0; male_idx != male_ct; ++male_idx) {
9088 const uintptr_t sample_uidx = BitIter1(sex_male, &sample_uidx_base, &sex_male_bits);
9089 cur_row[sample_uidx] *= 0.5;
9090 }
9091 }
9092 }
9093 }
9094 ++row_idx;
9095 if (missing_cts) {
9096 ZeroTrailingNyps(sample_ct, genovec);
9097 uint32_t missing_ct;
9098 if (!dosage_ct) {
9099 if (!is_y) {
9100 missing_ct = GenoarrCountMissingUnsafe(genovec, sample_ct);
9101 } else {
9102 missing_ct = GenoarrCountMissingSubset(genovec, sex_male_interleaved_vec, sample_ct);
9103 }
9104 } else {
9105 if (!is_y) {
9106 missing_ct = GenoarrCountMissingInvsubsetUnsafe(genovec, dosage_present, sample_ct);
9107 } else {
9108 // include males, exclude dosages
9109 const uint32_t fullword_ct = (sample_ct + kBitsPerWordD2 - 1) / kBitsPerWord;
9110 missing_ct = 0;
9111 for (uint32_t widx = 0; widx != fullword_ct; ++widx) {
9112 uintptr_t w1 = genovec[2 * widx];
9113 uintptr_t w2 = genovec[2 * widx + 1];
9114 w1 = w1 & (w1 >> 1);
9115 w2 = w2 & (w2 >> 1);
9116 w1 = PackWordToHalfwordMask5555(w1);
9117 w2 = PackWordToHalfwordMask5555(w2);
9118 const uintptr_t ww = w1 | (w2 << kBitsPerWordD2);
9119 missing_ct += PopcountWord(ww & sex_male[widx] & (~dosage_present[widx]));
9120 }
9121 if (sample_ct > fullword_ct * kBitsPerWord) {
9122 uintptr_t w1 = genovec[2 * fullword_ct];
9123 w1 = w1 & (w1 >> 1);
9124 w1 = PackWordToHalfwordMask5555(w1);
9125 missing_ct += PopcountWord(w1 & sex_male[fullword_ct] & (~dosage_present[fullword_ct]));
9126 }
9127 }
9128 }
9129 missing_cts[variant_bidx] = missing_ct;
9130 }
9131 }
9132 if (row_idx) {
9133 if (single_prec) {
9134 RowMajorFmatrixMultiply(dosage_f_vmaj, wts_f_smaj, row_idx, vscore_ct, sample_ct, tmp_f_result_buf);
9135 const float* tmp_f_result_iter = tmp_f_result_buf;
9136 for (uintptr_t ulii = 0; ulii != row_idx; ++ulii) {
9137 uintptr_t cur_bidx = cur_bidxs[ulii];
9138 memcpy(&(cur_results_f[cur_bidx * vscore_ct]), tmp_f_result_iter, vscore_ct * sizeof(float));
9139 tmp_f_result_iter = &(tmp_f_result_iter[vscore_ct]);
9140 }
9141 } else {
9142 RowMajorMatrixMultiply(dosage_d_vmaj, wts_d_smaj, row_idx, vscore_ct, sample_ct, tmp_d_result_buf);
9143 const double* tmp_d_result_iter = tmp_d_result_buf;
9144 for (uintptr_t ulii = 0; ulii != row_idx; ++ulii) {
9145 uintptr_t cur_bidx = cur_bidxs[ulii];
9146 memcpy(&(cur_results_d[cur_bidx * vscore_ct]), tmp_d_result_iter, vscore_ct * sizeof(double));
9147 tmp_d_result_iter = &(tmp_d_result_iter[vscore_ct]);
9148 }
9149 }
9150 }
9151 parity = 1 - parity;
9152 while (0) {
9153 VscoreThread_err:
9154 UpdateU64IfSmaller(new_err_info, &ctx->err_info);
9155 }
9156 } while (!THREAD_BLOCK_FINISH(arg));
9157 THREAD_RETURN;
9158 }
9159
9160 PglErr Vscore(const uintptr_t* 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* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_male, const double* allele_freqs, const char* in_fname, const RangeList* col_idx_range_listp, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t nosex_ct, uint32_t max_allele_slen, VscoreFlags flags, uint32_t xchr_model, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) {
9161 unsigned char* bigstack_mark = g_bigstack_base;
9162 unsigned char* bigstack_end_mark = g_bigstack_end;
9163 uintptr_t line_idx = 0;
9164 uint32_t calc_thread_ct = max_thread_ct;
9165 char* cswritep = nullptr;
9166 FILE* binfile = nullptr;
9167 PglErr reterr = kPglRetSuccess;
9168 TextStream txs;
9169 ThreadGroup tg;
9170 CompressStreamState css;
9171 VscoreCtx ctx;
9172 PreinitTextStream(&txs);
9173 PreinitThreads(&tg);
9174 PreinitCstream(&css);
9175 #ifdef USE_CUDA
9176 ctx.cfms = nullptr;
9177 #endif
9178 {
9179 // unsurprisingly, lots of overlap with --score
9180 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
9181 if (nosex_ct) {
9182 // forced mean-imputation doesn't mix well with inclusion of chrY
9183 // unknown-sex samples.
9184 if (unlikely(XymtIsNonempty(variant_include, cip, kChrOffsetY))) {
9185 logerrputs("Error: When chrY is present, --variant-score cannot be used with unknown-sex\nsamples.\n");
9186 goto Vscore_ret_INCONSISTENT_INPUT;
9187 }
9188 }
9189 if (!xchr_model) {
9190 uint32_t x_code;
9191 if (XymtExists(cip, kChrOffsetX, &x_code)) {
9192 uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code];
9193 uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx];
9194 uint32_t x_end = cip->chr_fo_vidx_start[x_chr_fo_idx + 1];
9195 if (!AllBitsAreZero(variant_include, x_start, x_end)) {
9196 uintptr_t* variant_include_no_x;
9197 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_no_x))) {
9198 goto Vscore_ret_NOMEM;
9199 }
9200 memcpy(variant_include_no_x, variant_include, raw_variant_ctl * sizeof(intptr_t));
9201 variant_ct -= PopcountBitRange(variant_include, x_start, x_end);
9202 if (!variant_ct) {
9203 logerrputs("Error: No --variant-score variants remaining after --xchr-model 0.\n");
9204 goto Vscore_ret_INCONSISTENT_INPUT;
9205 }
9206 ClearBitsNz(x_start, x_end, variant_include_no_x);
9207 variant_include = variant_include_no_x;
9208 }
9209 }
9210 } else if (xchr_model == 2) {
9211 xchr_model = 0;
9212 }
9213 // now xchr_model is set iff it's 1
9214
9215 // see KeepColMatch() and SampleSortFileMap()
9216 char* line_start;
9217 XidMode xid_mode;
9218 reterr = OpenAndLoadXidHeader(in_fname, "variant-score", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeaderFixedWidth : kfXidHeaderFixedWidthIgnoreSid, kTextStreamBlenFast, &txs, &xid_mode, &line_idx, &line_start);
9219 if (unlikely(reterr)) {
9220 if (reterr == kPglRetEof) {
9221 logerrputs("Error: Empty --variant-score file.\n");
9222 reterr = kPglRetMalformedInput;
9223 }
9224 goto Vscore_ret_1;
9225 }
9226 const uint32_t id_col_ct = GetXidColCt(xid_mode);
9227 const uint32_t col_ct = CountTokens(line_start);
9228 if (unlikely(id_col_ct == col_ct)) {
9229 logerrputs("Error: No score columns in --variant-score file.\n");
9230 goto Vscore_ret_MALFORMED_INPUT;
9231 }
9232 uintptr_t vscore_ct;
9233 uint32_t* col_idx_deltas;
9234 if (!col_idx_range_listp->name_ct) {
9235 vscore_ct = col_ct - id_col_ct;
9236 if (unlikely(bigstack_alloc_u32(vscore_ct, &col_idx_deltas))) {
9237 goto Vscore_ret_NOMEM;
9238 }
9239 for (uint32_t uii = 0; uii != vscore_ct; ++uii) {
9240 col_idx_deltas[uii] = 1;
9241 }
9242 } else {
9243 const uint32_t col_ctl = BitCtToWordCt(col_ct);
9244 uintptr_t* vscore_col_bitarr;
9245 if (unlikely(bigstack_calloc_w(col_ctl, &vscore_col_bitarr))) {
9246 goto Vscore_ret_NOMEM;
9247 }
9248 if (unlikely(NumericRangeListToBitarr(col_idx_range_listp, col_ct, 1, 0, vscore_col_bitarr))) {
9249 goto Vscore_ret_MISSING_TOKENS;
9250 }
9251 if (vscore_col_bitarr[0] & ((1 << id_col_ct) - 1)) {
9252 logerrputs("Error: --vscore-col-nums argument overlaps with ID columns.\n");
9253 goto Vscore_ret_INCONSISTENT_INPUT;
9254 }
9255 vscore_ct = PopcountWords(vscore_col_bitarr, col_ctl);
9256 // since we don't allow overflow, this should be guaranteed to be
9257 // positive
9258 assert(vscore_ct);
9259 if (unlikely(bigstack_alloc_u32(vscore_ct, &col_idx_deltas))) {
9260 goto Vscore_ret_NOMEM;
9261 }
9262 uintptr_t col_uidx_base = 0;
9263 uintptr_t vscore_col_bitarr_bits = vscore_col_bitarr[0];
9264 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9265 const uint32_t col_uidx = BitIter1(vscore_col_bitarr, &col_uidx_base, &vscore_col_bitarr_bits);
9266 col_idx_deltas[vscore_idx] = col_uidx;
9267 }
9268 // now convert to deltas
9269 for (uintptr_t vscore_idx = vscore_ct - 1; vscore_idx; --vscore_idx) {
9270 col_idx_deltas[vscore_idx] -= col_idx_deltas[vscore_idx - 1];
9271 }
9272 col_idx_deltas[0] -= id_col_ct - 1;
9273 }
9274 char** vscore_names;
9275 if (unlikely(bigstack_end_alloc_cp(vscore_ct, &vscore_names))) {
9276 goto Vscore_ret_NOMEM;
9277 }
9278 const uint32_t is_header_line = (line_start[0] == '#');
9279 unsigned char* tmp_alloc_base = g_bigstack_base;
9280 unsigned char* tmp_alloc_end = g_bigstack_end;
9281 if (is_header_line) {
9282 const char* name_iter = NextTokenMult0(line_start, id_col_ct - 1);
9283 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9284 name_iter = NextTokenMult(name_iter, col_idx_deltas[vscore_idx]);
9285 const char* name_end = CurTokenEnd(name_iter);
9286 // don't actually need to enforce unique names, though we could print a
9287 // warning later
9288 const uint32_t cur_slen = name_end - name_iter;
9289 if (cur_slen > kMaxIdSlen) {
9290 snprintf(g_logbuf, kLogbufSize, "Error: Variant-score name in column %" PRIuPTR " of %s is too long.\n", vscore_idx + id_col_ct + 1, in_fname);
9291 goto Vscore_ret_MALFORMED_INPUT_WW;
9292 }
9293 if (StoreStringAtEnd(tmp_alloc_base, name_iter, cur_slen, &tmp_alloc_end, &(vscore_names[vscore_idx]))) {
9294 goto Vscore_ret_NOMEM;
9295 }
9296 name_iter = name_end;
9297 }
9298 ++line_idx;
9299 line_start = TextGet(&txs);
9300 } else {
9301 for (uintptr_t vscore_num = 1; vscore_num <= vscore_ct; ++vscore_num) {
9302 const uint32_t cur_blen = 7 + UintSlen(vscore_num);
9303 if (PtrWSubCk(tmp_alloc_base, cur_blen, &tmp_alloc_end)) {
9304 goto Vscore_ret_NOMEM;
9305 }
9306 char* cur_name_iter = R_CAST(char*, tmp_alloc_end);
9307 vscore_names[vscore_num - 1] = cur_name_iter;
9308 cur_name_iter = strcpya_k(cur_name_iter, "VSCORE");
9309 cur_name_iter = u32toa(vscore_num, cur_name_iter);
9310 *cur_name_iter = '\0';
9311 }
9312 }
9313 BigstackEndSet(tmp_alloc_end);
9314 uint32_t* xid_map;
9315 char* sorted_xidbox;
9316 uintptr_t max_xid_blen;
9317 reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
9318 if (unlikely(reterr)) {
9319 goto Vscore_ret_1;
9320 }
9321 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
9322 char* idbuf;
9323 uint32_t* sample_uidx_order;
9324 if (unlikely(bigstack_alloc_c(siip->max_sample_id_blen, &idbuf) ||
9325 bigstack_alloc_u32(sample_ct, &sample_uidx_order))) {
9326 goto Vscore_ret_NOMEM;
9327 }
9328 const uint32_t single_prec = (flags / kfVscoreSinglePrec) & 1;
9329 double* raw_wts_d = nullptr;
9330 float* raw_wts_f = nullptr;
9331 if (flags & kfVscoreSinglePrec) {
9332 if (unlikely(bigstack_alloc64_f(sample_ct * S_CAST(uint64_t, vscore_ct), &raw_wts_f))) {
9333 goto Vscore_ret_NOMEM;
9334 }
9335 } else {
9336 if (unlikely(bigstack_alloc64_d(sample_ct * S_CAST(uint64_t, vscore_ct), &raw_wts_d))) {
9337 goto Vscore_ret_NOMEM;
9338 }
9339 }
9340 uintptr_t* already_seen;
9341 if (unlikely(bigstack_end_calloc_w(raw_sample_ctl, &already_seen))) {
9342 goto Vscore_ret_NOMEM;
9343 }
9344 uintptr_t miss_ct = 0;
9345 uint32_t hit_ct = 0;
9346
9347 double* raw_wts_d_iter = raw_wts_d;
9348 float* raw_wts_f_iter = raw_wts_f;
9349 for (; line_start; ++line_idx, line_start = TextGet(&txs)) {
9350 if (unlikely(line_start[0] == '#')) {
9351 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --variant-score file starts with a '#'. (This is only permitted before the first nonheader line, and if a #FID/IID header line is present it must denote the end of the header block.)\n", line_idx);
9352 goto Vscore_ret_MALFORMED_INPUT_WW;
9353 }
9354 const char* linebuf_iter = line_start;
9355 uint32_t sample_uidx;
9356 if (SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx, idbuf)) {
9357 if (unlikely(!linebuf_iter)) {
9358 goto Vscore_ret_MISSING_TOKENS;
9359 }
9360 ++miss_ct;
9361 continue;
9362 }
9363 if (unlikely(IsSet(already_seen, sample_uidx))) {
9364 TabsToSpaces(idbuf);
9365 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in --variant-score file.\n", idbuf);
9366 goto Vscore_ret_MALFORMED_INPUT_WW;
9367 }
9368 SetBit(sample_uidx, already_seen);
9369 sample_uidx_order[hit_ct] = sample_uidx;
9370 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9371 linebuf_iter = NextTokenMult(linebuf_iter, col_idx_deltas[vscore_idx]);
9372 if (unlikely(!linebuf_iter)) {
9373 goto Vscore_ret_MISSING_TOKENS;
9374 }
9375 double dxx;
9376 const char* token_end = ScantokDouble(linebuf_iter, &dxx);
9377 if (unlikely((!token_end) || (single_prec && (fabs(dxx) > 3.4028235677973362e38)))) {
9378 token_end = CurTokenEnd(linebuf_iter);
9379 *K_CAST(char*, token_end) = '\0';
9380 snprintf(g_logbuf, kLogbufSize, "Error: Invalid coefficient '%s' on line %" PRIuPTR " of --variant-score file.\n", linebuf_iter, line_idx);
9381 goto Vscore_ret_MALFORMED_INPUT_WW;
9382 }
9383 if (single_prec) {
9384 *raw_wts_f_iter++ = S_CAST(float, dxx);
9385 } else {
9386 *raw_wts_d_iter++ = dxx;
9387 }
9388 linebuf_iter = token_end;
9389 }
9390 ++hit_ct;
9391 }
9392 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
9393 goto Vscore_ret_TSTREAM_FAIL;
9394 }
9395 if (unlikely(CleanupTextStream2(in_fname, &txs, &reterr))) {
9396 goto Vscore_ret_1;
9397 }
9398 if (!hit_ct) {
9399 logerrputs("Error: No valid entries in --variant-score file.\n");
9400 goto Vscore_ret_INCONSISTENT_INPUT;
9401 }
9402 sample_include = already_seen;
9403 sample_ct = hit_ct;
9404 #if defined(__LP64__) && !defined(LAPACK_ILP64)
9405 if (sample_ct * vscore_ct > 0x7fffffff) {
9406 logerrputs("Error: --variant-score input matrix too large for this " PROG_NAME_STR " build. If this\nis really the computation you want, use a " PROG_NAME_STR " build with large-matrix\nsupport.\n");
9407 goto Vscore_ret_INCONSISTENT_INPUT;
9408 }
9409 #endif
9410 ctx.variant_include = variant_include;
9411 ctx.cip = cip;
9412 ctx.allele_idx_offsets = allele_idx_offsets;
9413 ctx.allele_freqs = allele_freqs;
9414 ctx.sample_include = sample_include;
9415 const uint32_t sample_ctl = BitCtToWordCt(sample_ct);
9416 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
9417 uint32_t compress_thread_ct = 1;
9418 const uint32_t output_zst = (flags / kfVscoreZs) & 1;
9419 snprintf(outname_end, kMaxOutfnameExtBlen, ".vscore");
9420 if (flags & (kfVscoreBin | kfVscoreBin4)) {
9421 snprintf(&(outname_end[7]), kMaxOutfnameExtBlen - 7, ".cols");
9422 if (unlikely(fopen_checked(outname, FOPEN_WB, &binfile))) {
9423 goto Vscore_ret_OPEN_FAIL;
9424 }
9425 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9426 fputs(vscore_names[vscore_idx], binfile);
9427 #ifdef _WIN32
9428 putc_unlocked('\r', binfile);
9429 #endif
9430 putc_unlocked('\n', binfile);
9431 }
9432 if (unlikely(fclose_null(&binfile))) {
9433 goto Vscore_ret_WRITE_FAIL;
9434 }
9435 snprintf(&(outname_end[7]), kMaxOutfnameExtBlen - 7, ".bin");
9436 if (unlikely(fopen_checked(outname, FOPEN_WB, &binfile))) {
9437 goto Vscore_ret_OPEN_FAIL;
9438 }
9439 snprintf(&(outname_end[7]), kMaxOutfnameExtBlen - 7, ".vars");
9440 if (output_zst) {
9441 snprintf(&(outname_end[12]), kMaxOutfnameExtBlen - 12, ".zst");
9442 }
9443 } else if (output_zst) {
9444 snprintf(&(outname_end[7]), kMaxOutfnameExtBlen - 7, ".zst");
9445 if (calc_thread_ct > 1) {
9446 // The more samples there are, the higher the compute:compress ratio we
9447 // want, though this is not a linear relationship due to the sparse
9448 // optimization.
9449 // 1:1 split seems to work well for a few thousand samples; I'm
9450 // guessing that ~7:1 is better for hundreds of thousands.
9451 if (sample_ct < 8192) {
9452 compress_thread_ct = calc_thread_ct / 2;
9453 } else {
9454 const uint32_t log2_sample_ct_m10 = bsru32(sample_ct) - 10;
9455 // 3/8, 4/16, 5/24, ...
9456 compress_thread_ct = (calc_thread_ct * log2_sample_ct_m10) / (8 * (log2_sample_ct_m10 - 2));
9457 if (!compress_thread_ct) {
9458 compress_thread_ct = 1;
9459 }
9460 }
9461 calc_thread_ct -= compress_thread_ct;
9462 }
9463 }
9464 {
9465 uint32_t* sample_include_cumulative_popcounts;
9466 if (unlikely(bigstack_end_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts))) {
9467 goto Vscore_ret_NOMEM;
9468 }
9469 float* wts_f_smaj = nullptr;
9470 double* wts_d_smaj = nullptr;
9471 if (single_prec) {
9472 if (unlikely(bigstack_end_alloc_f(sample_ct * vscore_ct, &wts_f_smaj))) {
9473 goto Vscore_ret_NOMEM;
9474 }
9475 } else {
9476 if (unlikely(bigstack_end_alloc_d(sample_ct * vscore_ct, &wts_d_smaj))) {
9477 goto Vscore_ret_NOMEM;
9478 }
9479 }
9480 FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts);
9481 ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts;
9482 logprintfww("--variant-score: %" PRIuPTR " score-vector%s loaded for %u sample%s.\n", vscore_ct, (vscore_ct == 1)? "" : "s", sample_ct, (sample_ct == 1)? "" : "s");
9483 if (miss_ct) {
9484 logerrprintf("Warning: %" PRIuPTR " line%s skipped in --variant-score file.\n", miss_ct, (miss_ct == 1)? "" : "s");
9485 }
9486 if (single_prec) {
9487 const float* wts_read_iter = raw_wts_f;
9488 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
9489 const uint32_t sample_uidx = sample_uidx_order[uii];
9490 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_uidx);
9491 memcpy(&(wts_f_smaj[sample_idx * vscore_ct]), wts_read_iter, vscore_ct * sizeof(float));
9492 wts_read_iter = &(wts_read_iter[vscore_ct]);
9493 }
9494 ctx.wts_f_smaj = wts_f_smaj;
9495 ctx.wts_d_smaj = nullptr;
9496 } else {
9497 const double* wts_read_iter = raw_wts_d;
9498 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
9499 const uint32_t sample_uidx = sample_uidx_order[uii];
9500 const uint32_t sample_idx = RawToSubsettedPos(sample_include, sample_include_cumulative_popcounts, sample_uidx);
9501 memcpy(&(wts_d_smaj[sample_idx * vscore_ct]), wts_read_iter, vscore_ct * sizeof(double));
9502 wts_read_iter = &(wts_read_iter[vscore_ct]);
9503 }
9504 ctx.wts_f_smaj = nullptr;
9505 ctx.wts_d_smaj = wts_d_smaj;
9506 }
9507 BigstackReset(bigstack_mark);
9508 #ifdef USE_CUDA
9509 if (single_prec && (vscore_ct >= 80)) {
9510 const uint32_t device_count = CudaGetDeviceCount();
9511 if (device_count) {
9512 if (unlikely(BIGSTACK_ALLOC_X(CublasFmultiplier, calc_thread_ct, &ctx.cfms))) {
9513 goto Vscore_ret_NOMEM;
9514 }
9515 uint32_t tidx = 0;
9516 CublasFmultiplierPreinit(&ctx.cfms[0]);
9517 for (uint32_t device_idx = 0; device_idx != device_count; ++device_idx) {
9518 if (unlikely(CudaSetDevice(device_idx))) {
9519 reterr = kPglRetGpuFail;
9520 logerrputs("Error: GPU operation failure.\n");
9521 goto Vscore_ret_1;
9522 }
9523 if (CublasFmultiplierRowMajorInit(kVscoreBlockSize, vscore_ct, sample_ct, &ctx.cfms[tidx])) {
9524 // Insufficient memory on this device. Try the next one.
9525 continue;
9526 }
9527 CublasFmultiplierPreloadRowMajor2(ctx.wts_f_smaj, &ctx.cfms[tidx]);
9528 ++tidx;
9529 if (tidx == calc_thread_ct) {
9530 break;
9531 }
9532 CublasFmultiplierPreinit(&ctx.cfms[tidx]);
9533 CublasFmultiplierBorrowRowMajor2(&ctx.cfms[tidx - 1], &ctx.cfms[tidx]);
9534 if (CublasFmultiplierRowMajorInit(kVscoreBlockSize, vscore_ct, sample_ct, &ctx.cfms[tidx])) {
9535 continue;
9536 }
9537 ++tidx;
9538 if (tidx == calc_thread_ct) {
9539 break;
9540 }
9541 CublasFmultiplierPreinit(&ctx.cfms[tidx]);
9542 }
9543 if (!tidx) {
9544 logputs("Note: Not using GPU for --variant-score computation, due to insufficient\ndevice memory. If this is a problem, try providing fewer scores at a time.\n");
9545 ctx.cfms = nullptr;
9546 } else {
9547 calc_thread_ct = tidx;
9548 logprintf("--variant-score: Using %u GPU handle%s.\n", calc_thread_ct, (calc_thread_ct == 1)? "" : "s");
9549 }
9550 }
9551 }
9552 #endif
9553 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
9554 uintptr_t* sex_male_collapsed;
9555 uintptr_t* sex_male_interleaved_vec;
9556 if (unlikely(bigstack_alloc_w(sample_ctl, &sex_male_collapsed) ||
9557 bigstack_alloc_w(sample_ctv * kWordsPerVec, &sex_male_interleaved_vec) ||
9558 bigstack_alloc_wp(calc_thread_ct, &ctx.raregenos) ||
9559 bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs))) {
9560 goto Vscore_ret_NOMEM;
9561 }
9562 if (single_prec) {
9563 if (unlikely(bigstack_alloc_fp(calc_thread_ct, &ctx.dosage_f_vmaj_bufs) ||
9564 bigstack_alloc_fp(calc_thread_ct, &ctx.tmp_f_result_bufs))) {
9565 goto Vscore_ret_NOMEM;
9566 }
9567 ctx.dosage_d_vmaj_bufs = nullptr;
9568 ctx.tmp_d_result_bufs = nullptr;
9569 } else {
9570 if (unlikely(bigstack_alloc_dp(calc_thread_ct, &ctx.dosage_d_vmaj_bufs) ||
9571 bigstack_alloc_dp(calc_thread_ct, &ctx.tmp_d_result_bufs))) {
9572 goto Vscore_ret_NOMEM;
9573 }
9574 ctx.dosage_f_vmaj_bufs = nullptr;
9575 ctx.tmp_f_result_bufs = nullptr;
9576 }
9577 CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed);
9578 // bugfix (18 Oct 2023): forgot to clear trailing words
9579 ZeroTrailingWords(sample_ctl, sex_male_collapsed);
9580 FillInterleavedMaskVec(sex_male_collapsed, sample_ctv, sex_male_interleaved_vec);
9581 ctx.sex_male_collapsed = sex_male_collapsed;
9582 ctx.sex_male_interleaved_vec = sex_male_interleaved_vec;
9583 }
9584 ctx.vscore_ct = vscore_ct;
9585 ctx.sample_ct = sample_ct;
9586 const uint32_t male_ct = PopcountWords(ctx.sex_male_collapsed, sample_ctl);
9587 ctx.male_ct = male_ct;
9588 ctx.is_xchr_model_1 = xchr_model;
9589
9590 const uint32_t chr_col = (flags / kfVscoreColChrom) & 1;
9591 char* chr_buf = nullptr;
9592 uint32_t max_chr_blen = 0;
9593 if (chr_col) {
9594 max_chr_blen = GetMaxChrSlen(cip) + 1;
9595 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
9596 goto Vscore_ret_NOMEM;
9597 }
9598 }
9599 const uint32_t ref_col = (flags / kfVscoreColRef) & 1;
9600 const uint32_t alt1_col = (flags / kfVscoreColAlt1) & 1;
9601 const uint32_t alt_col = (flags / kfVscoreColAlt) & 1;
9602 uintptr_t overflow_buf_size;
9603 if (binfile) {
9604 overflow_buf_size = kCompressStreamBlock + kMaxIdSlen + 16;
9605 } else {
9606 overflow_buf_size = kCompressStreamBlock + max_chr_blen * chr_col + kMaxIdSlen + 128 + (24 * k1LU) * vscore_ct + MAXV(ref_col + alt1_col, alt_col) * max_allele_slen;
9607 }
9608 reterr = InitCstreamAlloc(outname, 0, output_zst, compress_thread_ct, overflow_buf_size, &css, &cswritep);
9609 if (unlikely(reterr)) {
9610 goto Vscore_ret_1;
9611 }
9612 const uintptr_t* nonref_flags = pgfip->nonref_flags;
9613 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
9614 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, flags / kfVscoreColMaybeprovref, raw_variant_ct, all_nonref);
9615 const uint32_t nmiss_col = (flags / kfVscoreColNmiss) & 1;
9616 const uint32_t nobs_col = (flags / kfVscoreColNobs) & 1;
9617 if (!binfile) {
9618 *cswritep++ = '#';
9619 if (chr_col) {
9620 cswritep = strcpya_k(cswritep, "CHROM\t");
9621 }
9622 if (flags & kfVscoreColPos) {
9623 cswritep = strcpya_k(cswritep, "POS\t");
9624 } else {
9625 variant_bps = nullptr;
9626 }
9627 cswritep = strcpya_k(cswritep, "ID");
9628 if (ref_col) {
9629 cswritep = strcpya_k(cswritep, "\tREF");
9630 }
9631 if (alt1_col) {
9632 cswritep = strcpya_k(cswritep, "\tALT1");
9633 }
9634 if (alt_col) {
9635 cswritep = strcpya_k(cswritep, "\tALT");
9636 }
9637 if (provref_col) {
9638 cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
9639 }
9640 if (flags & kfVscoreColAltfreq) {
9641 cswritep = strcpya_k(cswritep, "\tALT_FREQ");
9642 } else {
9643 allele_freqs = nullptr;
9644 }
9645 if (nmiss_col) {
9646 cswritep = strcpya_k(cswritep, "\tMISSING_CT");
9647 }
9648 if (nobs_col) {
9649 cswritep = strcpya_k(cswritep, "\tOBS_CT");
9650 }
9651 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9652 *cswritep++ = '\t';
9653 cswritep = strcpya(cswritep, vscore_names[vscore_idx]);
9654 if (unlikely(Cswrite(&css, &cswritep))) {
9655 goto Vscore_ret_WRITE_FAIL;
9656 }
9657 }
9658 AppendBinaryEoln(&cswritep);
9659 }
9660
9661 if (nmiss_col || nobs_col) {
9662 if (unlikely(bigstack_alloc_u32(kPglVblockSize, &ctx.missing_cts[0]) ||
9663 bigstack_alloc_u32(kPglVblockSize, &ctx.missing_cts[1]))) {
9664 goto Vscore_ret_NOMEM;
9665 }
9666 } else {
9667 ctx.missing_cts[0] = nullptr;
9668 ctx.missing_cts[1] = nullptr;
9669 }
9670
9671 const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
9672 // * Per-thread raregeno buffers must have space for
9673 // max_returned_difflist_len nyps, and difflist_sample_ids buffers need
9674 // space for that many uint32s.
9675 // * Per-thread dosage_vmaj buffers must have space for
9676 // kVscoreBlockSize * sample_ct elements.
9677 // * Per-thread result buffers must have space for kVscoreBlockSize *
9678 // vscore_ct elements.
9679 const uintptr_t thread_xalloc_cacheline_ct = DivUp(max_returned_difflist_len, kNypsPerCacheline) + DivUp(max_returned_difflist_len, kInt32PerCacheline) + DivUp(kVscoreBlockSize * S_CAST(uintptr_t, sample_ct) * sizeof(double), kCacheline) + DivUp(kVscoreBlockSize * vscore_ct * sizeof(double), kCacheline);
9680
9681 // ctx.results must have space for 2 * vscore_ct * read_block_size values.
9682 const uintptr_t per_variant_xalloc_byte_ct = 2 * vscore_ct * ((8 * k1LU) >> single_prec);
9683 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
9684 // defensive
9685 ctx.dosage_presents = nullptr;
9686 ctx.dosage_mains = nullptr;
9687 uint32_t read_block_size;
9688 if (unlikely(PgenMtLoadInit(variant_include, sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, per_variant_xalloc_byte_ct, 0, pgfip, &calc_thread_ct, &ctx.genovecs, nullptr, nullptr, nullptr, dosage_is_present? (&ctx.dosage_presents) : nullptr, dosage_is_present? (&ctx.dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) {
9689 goto Vscore_ret_NOMEM;
9690 }
9691 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
9692 goto Vscore_ret_NOMEM;
9693 }
9694 {
9695 // could vector-align individual allocations and only cacheline-align at
9696 // thread boundaries, but the savings are microscopic
9697 const uintptr_t raregeno_alloc = kCacheline * DivUp(max_returned_difflist_len, kNypsPerCacheline);
9698 const uintptr_t difflist_sample_ids_alloc = RoundUpPow2(max_returned_difflist_len * sizeof(int32_t), kCacheline);
9699 const uintptr_t dosage_vmaj_alloc = RoundUpPow2(kVscoreBlockSize * S_CAST(uintptr_t, sample_ct) * ((8 * k1LU) >> single_prec), kCacheline);
9700 const uintptr_t tmp_result_alloc = RoundUpPow2(kVscoreBlockSize * vscore_ct * ((8 * k1LU) >> single_prec), kCacheline);
9701 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
9702 ctx.raregenos[tidx] = S_CAST(uintptr_t*, bigstack_alloc_raw(raregeno_alloc));
9703 ctx.difflist_sample_id_bufs[tidx] = S_CAST(uint32_t*, bigstack_alloc_raw(difflist_sample_ids_alloc));
9704 if (single_prec) {
9705 ctx.dosage_f_vmaj_bufs[tidx] = S_CAST(float*, bigstack_alloc_raw(dosage_vmaj_alloc));
9706 ctx.tmp_f_result_bufs[tidx] = S_CAST(float*, bigstack_alloc_raw(tmp_result_alloc));
9707 } else {
9708 ctx.dosage_d_vmaj_bufs[tidx] = S_CAST(double*, bigstack_alloc_raw(dosage_vmaj_alloc));
9709 ctx.tmp_d_result_bufs[tidx] = S_CAST(double*, bigstack_alloc_raw(tmp_result_alloc));
9710 }
9711 }
9712 }
9713 const uintptr_t results_byte_ct = RoundUpPow2(per_variant_xalloc_byte_ct * read_block_size, kCacheline);
9714 if (single_prec) {
9715 ctx.results_f[0] = S_CAST(float*, bigstack_alloc_raw(results_byte_ct));
9716 ctx.results_f[1] = S_CAST(float*, bigstack_alloc_raw(results_byte_ct));
9717 ctx.results_d[0] = nullptr;
9718 ctx.results_d[1] = nullptr;
9719 } else {
9720 ctx.results_f[0] = nullptr;
9721 ctx.results_f[1] = nullptr;
9722 ctx.results_d[0] = S_CAST(double*, bigstack_alloc_raw(results_byte_ct));
9723 ctx.results_d[1] = S_CAST(double*, bigstack_alloc_raw(results_byte_ct));
9724 }
9725 assert(g_bigstack_base <= g_bigstack_end);
9726 ctx.err_info = (~0LLU) << 32;
9727 SetThreadFuncAndData(VscoreThread, &ctx, &tg);
9728
9729 fputs("--variant-score: 0%", stdout);
9730 fflush(stdout);
9731
9732 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
9733 // Main workflow:
9734 // 1. Set n=0, load/skip block 0
9735 //
9736 // 2. Spawn threads processing block n
9737 // 3. If n>0, write results for block (n-1)
9738 // 4. Increment n by 1
9739 // 5. Load/skip block n unless eof
9740 // 6. Join threads
9741 // 7. Goto step 2 unless eof
9742 //
9743 // 8. Write results for last block
9744 uintptr_t write_variant_uidx_base = 0;
9745 uintptr_t cur_bits = variant_include[0];
9746 uint32_t prev_block_size = 0;
9747 uint32_t pct = 0;
9748 uint32_t next_print_variant_idx = variant_ct / 100;
9749 uint32_t parity = 0;
9750 uint32_t read_block_idx = 0;
9751 uint32_t chr_fo_idx = UINT32_MAX;
9752 uint32_t chr_end = 0;
9753 uint32_t chr_buf_blen = 0;
9754 uint32_t cur_sample_ct = 0;
9755 uint32_t cur_allele_ct = 2;
9756 for (uint32_t variant_idx = 0; ; ++read_block_idx) {
9757 const uint32_t cur_block_size = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
9758 if (unlikely(reterr)) {
9759 goto Vscore_ret_PGR_FAIL;
9760 }
9761 if (variant_idx) {
9762 JoinThreads(&tg);
9763 reterr = S_CAST(PglErr, ctx.err_info);
9764 if (unlikely(reterr)) {
9765 #ifdef USE_CUDA
9766 if (reterr == kPglRetGpuFail) {
9767 logputs("\n");
9768 logerrputs("Error: GPU operation failure.\n");
9769 goto Vscore_ret_1;
9770 }
9771 #endif
9772 PgenErrPrintNV(reterr, ctx.err_info >> 32);
9773 goto Vscore_ret_1;
9774 }
9775 }
9776 if (!IsLastBlock(&tg)) {
9777 // it may make sense to put this boilerplate into its own function,
9778 // too...
9779 ctx.cur_block_size = cur_block_size;
9780 ComputeUidxStartPartition(variant_include, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts);
9781 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs);
9782 if (variant_idx + cur_block_size == variant_ct) {
9783 DeclareLastThreadBlock(&tg);
9784 }
9785 if (unlikely(SpawnThreads(&tg))) {
9786 goto Vscore_ret_THREAD_CREATE_FAIL;
9787 }
9788 }
9789 parity = 1 - parity;
9790 if (variant_idx) {
9791 // write *previous* block results
9792 const float* cur_results_f_iter = ctx.results_f[parity];
9793 const double* cur_results_d_iter = ctx.results_d[parity];
9794 const uint32_t* cur_missing_cts = ctx.missing_cts[parity];
9795 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_size; ++variant_bidx) {
9796 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
9797 if (write_variant_uidx >= chr_end) {
9798 do {
9799 ++chr_fo_idx;
9800 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
9801 } while (write_variant_uidx >= chr_end);
9802 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
9803 cur_sample_ct = (chr_idx == y_code)? male_ct : sample_ct;
9804 if (chr_buf) {
9805 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
9806 *chr_name_end = '\t';
9807 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
9808 }
9809 }
9810 if (binfile) {
9811 // may as well write variant-ID file in this loop
9812 cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
9813 AppendBinaryEoln(&cswritep);
9814 if (unlikely(Cswrite(&css, &cswritep))) {
9815 goto Vscore_ret_WRITE_FAIL;
9816 }
9817 continue;
9818 }
9819 if (chr_col) {
9820 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
9821 }
9822 if (variant_bps) {
9823 cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep);
9824 }
9825 cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
9826 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
9827 if (allele_idx_offsets) {
9828 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
9829 cur_allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offset_base;
9830 }
9831 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
9832 if (ref_col) {
9833 *cswritep++ = '\t';
9834 cswritep = strcpya(cswritep, cur_alleles[0]);
9835 }
9836 if (alt1_col) {
9837 *cswritep++ = '\t';
9838 cswritep = strcpya(cswritep, cur_alleles[1]);
9839 }
9840 if (alt_col) {
9841 *cswritep++ = '\t';
9842 for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) {
9843 if (unlikely(Cswrite(&css, &cswritep))) {
9844 goto Vscore_ret_WRITE_FAIL;
9845 }
9846 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
9847 }
9848 --cswritep;
9849 }
9850 if (provref_col) {
9851 *cswritep++ = '\t';
9852 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N';
9853 }
9854 if (allele_freqs) {
9855 *cswritep++ = '\t';
9856 cswritep = dtoa_g(1.0 - allele_freqs[allele_idx_offset_base - write_variant_uidx], cswritep);
9857 }
9858 if (nmiss_col) {
9859 *cswritep++ = '\t';
9860 cswritep = u32toa(cur_missing_cts[variant_bidx], cswritep);
9861 }
9862 if (nobs_col) {
9863 *cswritep++ = '\t';
9864 cswritep = u32toa(cur_sample_ct - cur_missing_cts[variant_bidx], cswritep);
9865 }
9866 if (single_prec) {
9867 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9868 *cswritep++ = '\t';
9869 cswritep = ftoa_g(*cur_results_f_iter++, cswritep);
9870 }
9871 } else {
9872 for (uintptr_t vscore_idx = 0; vscore_idx != vscore_ct; ++vscore_idx) {
9873 *cswritep++ = '\t';
9874 cswritep = dtoa_g(*cur_results_d_iter++, cswritep);
9875 }
9876 }
9877 AppendBinaryEoln(&cswritep);
9878 if (unlikely(Cswrite(&css, &cswritep))) {
9879 goto Vscore_ret_WRITE_FAIL;
9880 }
9881 }
9882 if (binfile) {
9883 const uintptr_t entry_ct = vscore_ct * prev_block_size;
9884 if (single_prec) {
9885 // must be bin4
9886 if (unlikely(fwrite_checked(cur_results_f_iter, entry_ct * sizeof(float), binfile))) {
9887 goto Vscore_ret_WRITE_FAIL;
9888 }
9889 } else if (flags & kfVscoreBin) {
9890 if (unlikely(fwrite_checked(cur_results_d_iter, entry_ct * sizeof(double), binfile))) {
9891 goto Vscore_ret_WRITE_FAIL;
9892 }
9893 } else {
9894 const uintptr_t fullgroup_ct = entry_ct / 32768;
9895 float buf[32768];
9896 for (uintptr_t group_idx = 0; group_idx != fullgroup_ct; ++group_idx) {
9897 for (uint32_t uii = 0; uii != 32768; ++uii) {
9898 buf[uii] = S_CAST(float, *cur_results_d_iter++);
9899 }
9900 if (unlikely(fwrite_checked(buf, 32768 * sizeof(float), binfile))) {
9901 goto Vscore_ret_WRITE_FAIL;
9902 }
9903 }
9904 const uint32_t remainder = entry_ct % 32768;
9905 if (remainder) {
9906 for (uint32_t uii = 0; uii != remainder; ++uii) {
9907 buf[uii] = S_CAST(float, *cur_results_d_iter++);
9908 }
9909 if (unlikely(fwrite_checked(buf, remainder * sizeof(float), binfile))) {
9910 goto Vscore_ret_WRITE_FAIL;
9911 }
9912 }
9913 }
9914 }
9915 if (variant_idx == variant_ct) {
9916 break;
9917 }
9918 if (variant_idx >= next_print_variant_idx) {
9919 if (pct > 10) {
9920 putc_unlocked('\b', stdout);
9921 }
9922 pct = (variant_idx * 100LLU) / variant_ct;
9923 printf("\b\b%u%%", pct++);
9924 fflush(stdout);
9925 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
9926 }
9927 }
9928 prev_block_size = cur_block_size;
9929 variant_idx += cur_block_size;
9930 pgfip->block_base = main_loadbufs[parity];
9931 }
9932 if (unlikely(CswriteCloseNull(&css, cswritep))) {
9933 goto Vscore_ret_WRITE_FAIL;
9934 }
9935 putc_unlocked('\r', stdout);
9936 if (!binfile) {
9937 logprintfww("--variant-score: Results written to %s .\n", outname);
9938 } else {
9939 if (unlikely(fclose_null(&binfile))) {
9940 goto Vscore_ret_WRITE_FAIL;
9941 }
9942 outname_end[8] = '\0';
9943 logprintfww("--variant-score: Score matrix written to %sbin , and associated column and variant ID labels written to %scols and %svars%s .\n", outname, outname, outname, output_zst? ".zst" : "");
9944 }
9945 }
9946 while (0) {
9947 Vscore_ret_NOMEM:
9948 reterr = kPglRetNomem;
9949 break;
9950 Vscore_ret_OPEN_FAIL:
9951 reterr = kPglRetOpenFail;
9952 break;
9953 Vscore_ret_TSTREAM_FAIL:
9954 TextStreamErrPrint("--variant-score file", &txs);
9955 break;
9956 Vscore_ret_PGR_FAIL:
9957 PgenErrPrintN(reterr);
9958 break;
9959 Vscore_ret_WRITE_FAIL:
9960 reterr = kPglRetWriteFail;
9961 break;
9962 Vscore_ret_MALFORMED_INPUT_WW:
9963 WordWrapB(0);
9964 logerrputsb();
9965 Vscore_ret_MALFORMED_INPUT:
9966 reterr = kPglRetMalformedInput;
9967 break;
9968 Vscore_ret_MISSING_TOKENS:
9969 logerrprintfww("Error: Line %" PRIuPTR " of --variant-score file has fewer tokens than expected.\n", line_idx);
9970 Vscore_ret_INCONSISTENT_INPUT:
9971 reterr = kPglRetInconsistentInput;
9972 break;
9973 Vscore_ret_THREAD_CREATE_FAIL:
9974 reterr = kPglRetThreadCreateFail;
9975 break;
9976 }
9977 Vscore_ret_1:
9978 #ifdef USE_CUDA
9979 if (ctx.cfms) {
9980 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
9981 if (unlikely(CublasFmultiplierCleanup(&ctx.cfms[tidx]))) {
9982 if (!reterr) {
9983 reterr = kPglRetGpuFail;
9984 }
9985 }
9986 }
9987 }
9988 #endif
9989 fclose_cond(binfile);
9990 CswriteCloseCond(&css, cswritep);
9991 CleanupThreads(&tg);
9992 CleanupTextStream2("--variant-score file", &txs, &reterr);
9993 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
9994 pgfip->block_base = nullptr;
9995 return reterr;
9996 }
9997
9998 #ifndef NOLAPACK
9999 // may need to increase textbuf size if this stops being true
10000 static_assert(kMaxPc < 100000, "PhenoSvd() needs to be updated.");
10001 PglErr PhenoSvd(const PhenoSvdInfo* psip, const uintptr_t* sample_include, const SampleIdInfo* siip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, __attribute__((unused)) uint32_t max_thread_ct, char** pheno_names_ptr, uint32_t* pheno_ct_ptr, uintptr_t* max_pheno_name_blen_ptr, PhenoCol* pheno_cols, char* outname, char* outname_end) {
10002 unsigned char* bigstack_mark = g_bigstack_base;
10003 const uintptr_t orig_pheno_ct = *pheno_ct_ptr;
10004 FILE* outfile = nullptr;
10005 PglErr reterr = kPglRetSuccess;
10006 {
10007 if (unlikely(orig_pheno_ct < 2)) {
10008 logerrprintf("Error: --pheno-svd invoked %s.\n", orig_pheno_ct? "with only 1 phenotype" : "without any phenotypes");
10009 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10010 }
10011 if (unlikely(orig_sample_ct <= 1)) {
10012 assert(orig_sample_ct == 1);
10013 logerrputs("Error: --pheno-svd invoked with only one sample.\n");
10014 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10015 }
10016 const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct);
10017 uintptr_t* sample_intersect;
10018 if (unlikely(bigstack_alloc_w(raw_sample_ctaw, &sample_intersect))) {
10019 goto PhenoSvd_ret_NOMEM;
10020 }
10021 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
10022 memcpy(sample_intersect, sample_include, raw_sample_ctl * sizeof(intptr_t));
10023 ZeroTrailingWords(raw_sample_ctl, sample_intersect);
10024 const uintptr_t orig_max_pheno_name_blen = *max_pheno_name_blen_ptr;
10025 char* orig_pheno_names = *pheno_names_ptr;
10026 for (uintptr_t pheno_idx = 0; pheno_idx != orig_pheno_ct; ++pheno_idx) {
10027 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
10028 if (unlikely(cur_pheno_col->type_code == kPhenoDtypeCat)) {
10029 logerrprintfww("Error: --pheno-svd: phenotype '%s' is categorical; it must be preprocessed with e.g. --split-cat-pheno.\n", &(orig_pheno_names[pheno_idx * orig_max_pheno_name_blen]));
10030 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10031 }
10032 BitvecAnd(cur_pheno_col->nonmiss, raw_sample_ctl, sample_intersect);
10033 }
10034 const uint32_t new_sample_ct = PopcountWords(sample_intersect, raw_sample_ctl);
10035 const PhenoSvdFlags flags = psip->flags;
10036 if (new_sample_ct * 2 < orig_sample_ct) {
10037 if (unlikely(!(flags & kfPhenoSvdForce))) {
10038 logerrprintfww("Error: --pheno-svd: Only %u/%u sample%s have no missing phenotype values. Consider imputing some missing phenotype values, and/or excluding phenotypes with many missing values.\n", new_sample_ct, orig_sample_ct, (new_sample_ct == 1)? "" : "s");
10039 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10040 }
10041 }
10042 const uintptr_t svd_dim = MINV(orig_pheno_ct, new_sample_ct);
10043 uint32_t new_pheno_ct = psip->ct;
10044 if (unlikely(svd_dim < new_pheno_ct)) {
10045 if (svd_dim == orig_pheno_ct) {
10046 logerrprintf("Error: --pheno-svd %u invoked with only %" PRIuPTR " phenotypes.\n", new_pheno_ct, orig_pheno_ct);
10047 } else {
10048 logerrprintf("Error: --pheno-svd %u invoked with only %u samples.\n", new_pheno_ct, new_sample_ct);
10049 }
10050 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10051 }
10052 const uint64_t svd_rect_size = S_CAST(uint64_t, orig_pheno_ct) * new_sample_ct;
10053 __CLPK_integer svd_rect_lwork;
10054 #ifdef LAPACK_ILP64
10055 GetSvdRectLwork(orig_pheno_ct, new_sample_ct, &svd_rect_lwork);
10056 #else
10057 if (unlikely((svd_rect_size > 0x7effffff) ||
10058 GetSvdRectLwork(orig_pheno_ct, new_sample_ct, &svd_rect_lwork))) {
10059 logerrputs("Error: --pheno-svd problem instance too large for this " PROG_NAME_STR " build. If this\nis really the computation you want, use a " PROG_NAME_STR " build with large-matrix support.\n");
10060 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10061 }
10062 #endif
10063 double* matrix; // orig_pheno x new_sample on input, pheno-pheno afterward
10064 double* singular_values;
10065 double* svd_sample_result;
10066 unsigned char* svd_rect_wkspace;
10067 if (unlikely(bigstack_alloc_d(svd_rect_size, &matrix) ||
10068 bigstack_alloc_d(svd_dim, &singular_values) ||
10069 bigstack_alloc_d(svd_rect_size, &svd_sample_result) ||
10070 bigstack_alloc_uc(svd_rect_lwork * sizeof(double), &svd_rect_wkspace))) {
10071 goto PhenoSvd_ret_NOMEM;
10072 }
10073 {
10074 double* dwrite_iter = matrix;
10075 for (uintptr_t pheno_idx = 0; pheno_idx != orig_pheno_ct; ++pheno_idx) {
10076 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]);
10077
10078 uintptr_t sample_uidx_base = 0;
10079 uintptr_t cur_bits = sample_intersect[0];
10080 if (cur_pheno_col->type_code == kPhenoDtypeQt) {
10081 const double* pheno_qt = cur_pheno_col->data.qt;
10082 for (uint32_t sample_idx = 0; sample_idx != new_sample_ct; ++sample_idx) {
10083 const uint32_t sample_uidx = BitIter1(sample_intersect, &sample_uidx_base, &cur_bits);
10084 dwrite_iter[sample_idx] = pheno_qt[sample_uidx];
10085 }
10086 } else {
10087 const uintptr_t* pheno_cc = cur_pheno_col->data.cc;
10088 for (uint32_t sample_idx = 0; sample_idx != new_sample_ct; ++sample_idx) {
10089 const uint32_t sample_uidx = BitIter1(sample_intersect, &sample_uidx_base, &cur_bits);
10090 dwrite_iter[sample_idx] = kSmallDoubles[IsSet(pheno_cc, sample_uidx)];
10091 }
10092 }
10093 dwrite_iter = &(dwrite_iter[new_sample_ct]);
10094 }
10095 }
10096
10097 BLAS_SET_NUM_THREADS(max_thread_ct);
10098 IntErr svd_rect_err = SvdRect(orig_pheno_ct, new_sample_ct, svd_rect_lwork, matrix, singular_values, svd_sample_result, svd_rect_wkspace);
10099 if (unlikely(svd_rect_err)) {
10100 logerrprintf("Error: --pheno-svd: DGESVD failure, info=%d.\n", S_CAST(int32_t, svd_rect_err));
10101 goto PhenoSvd_ret_DEGENERATE_DATA;
10102 }
10103
10104 if (!new_pheno_ct) {
10105 const double min_variance_explained = psip->min_variance_explained;
10106 if (min_variance_explained == 1.0) {
10107 new_pheno_ct = svd_dim;
10108 } else {
10109 double ssq = 0.0;
10110 for (uintptr_t sv_idx = 0; sv_idx != svd_dim; ++sv_idx) {
10111 const double cur_sv = singular_values[sv_idx];
10112 ssq += cur_sv * cur_sv;
10113 }
10114 const double target_ssq = min_variance_explained * ssq;
10115 ssq = 0.0;
10116 do {
10117 const double cur_sv = singular_values[new_pheno_ct];
10118 ssq += cur_sv * cur_sv;
10119 ++new_pheno_ct;
10120 } while (ssq < target_ssq);
10121 assert(new_pheno_ct <= svd_dim);
10122 }
10123 if (unlikely(new_pheno_ct > kMaxPc)) {
10124 logerrprintfww("Error: --pheno-svd variance=%g: Too many new phenotypes (%u; max %u).\n", min_variance_explained, new_pheno_ct, kMaxPc);
10125 goto PhenoSvd_ret_INCONSISTENT_INPUT;
10126 }
10127 logprintf("--pheno-svd variance=%g: %u/%" PRIuPTR " phenotype%s kept.\n", min_variance_explained, new_pheno_ct, svd_dim, (new_pheno_ct == 1)? "" : "s");
10128 }
10129
10130 BigstackReset(svd_rect_wkspace);
10131 const uint32_t textbuf_req = kMaxMediumLine + MAXV(kMaxMediumLine, 3 * kMaxIdBlen + (kMaxDoubleGSlen + 1) * orig_pheno_ct);
10132 char* textbuf;
10133 if (unlikely(bigstack_alloc_c(textbuf_req, &textbuf))) {
10134 goto PhenoSvd_ret_NOMEM;
10135 }
10136 char* textbuf_flush = &(textbuf[kMaxMediumLine]);
10137
10138 snprintf(outname_end, kMaxOutfnameExtBlen, ".svd.pheno");
10139 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
10140 goto PhenoSvd_ret_OPEN_FAIL;
10141 }
10142 char* write_iter = textbuf;
10143 *write_iter++ = '#';
10144 const uint32_t col_fid = FidColIsRequired(siip, flags / kfPhenoSvdScolMaybefid);
10145 if (col_fid) {
10146 write_iter = strcpya_k(write_iter, "FID\t");
10147 }
10148 write_iter = strcpya_k(write_iter, "IID");
10149 const char* sample_ids = siip->sample_ids;
10150 const char* sids = siip->sids;
10151 const uintptr_t max_sample_id_blen = siip->max_sample_id_blen;
10152 const uintptr_t max_sid_blen = siip->max_sid_blen;
10153 const uint32_t col_sid = SidColIsRequired(sids, flags / kfPhenoSvdScolMaybesid);
10154 if (col_sid) {
10155 write_iter = strcpya_k(write_iter, "\tSID");
10156 }
10157 for (uint32_t new_pheno_idx = 0; new_pheno_idx != new_pheno_ct; ++new_pheno_idx) {
10158 write_iter = strcpya_k(write_iter, "\tSVDPHENO");
10159 write_iter = u32toa(1 + new_pheno_idx, write_iter);
10160 }
10161 AppendBinaryEoln(&write_iter);
10162 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
10163 goto PhenoSvd_ret_WRITE_FAIL;
10164 }
10165 {
10166 uintptr_t sample_uidx_base = 0;
10167 uintptr_t cur_bits = sample_intersect[0];
10168 for (uint32_t sample_idx = 0; sample_idx != new_sample_ct; ++sample_idx) {
10169 const uintptr_t sample_uidx = BitIter1(sample_intersect, &sample_uidx_base, &cur_bits);
10170 write_iter = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter);
10171 const double* svd_sample_result_row = &(svd_sample_result[sample_idx * svd_dim]);
10172 for (uint32_t new_pheno_idx = 0; new_pheno_idx != new_pheno_ct; ++new_pheno_idx) {
10173 *write_iter++ = '\t';
10174 write_iter = dtoa_g(svd_sample_result_row[new_pheno_idx], write_iter);
10175 }
10176 AppendBinaryEoln(&write_iter);
10177 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
10178 goto PhenoSvd_ret_WRITE_FAIL;
10179 }
10180 }
10181 }
10182 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
10183 goto PhenoSvd_ret_WRITE_FAIL;
10184 }
10185
10186 snprintf(outname_end, kMaxOutfnameExtBlen, ".svd.pheno_wts");
10187 if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) {
10188 goto PhenoSvd_ret_OPEN_FAIL;
10189 }
10190 write_iter = textbuf;
10191 *write_iter++ = '#';
10192 const uint32_t col_id = (flags / kfPhenoSvdPcolId) & 1;
10193 if (col_id) {
10194 write_iter = strcpya_k(write_iter, "NEW_PHENO_ID\t");
10195 }
10196 const uint32_t col_sv = (flags / kfPhenoSvdPcolSv) & 1;
10197 if (col_sv) {
10198 write_iter = strcpya_k(write_iter, "SINGULAR_VALUE\t");
10199 }
10200 for (uint32_t orig_pheno_idx = 0; orig_pheno_idx != orig_pheno_ct; ++orig_pheno_idx) {
10201 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
10202 goto PhenoSvd_ret_WRITE_FAIL;
10203 }
10204 write_iter = strcpyax(write_iter, &(orig_pheno_names[orig_pheno_idx * orig_max_pheno_name_blen]), '\t');
10205 }
10206 --write_iter;
10207 AppendBinaryEoln(&write_iter);
10208 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
10209 goto PhenoSvd_ret_WRITE_FAIL;
10210 }
10211 for (uint32_t new_pheno_idx = 0; new_pheno_idx != new_pheno_ct; ++new_pheno_idx) {
10212 if (col_id) {
10213 write_iter = strcpya_k(write_iter, "SVDPHENO");
10214 write_iter = u32toa_x(new_pheno_idx + 1, '\t', write_iter);
10215 }
10216 if (col_sv) {
10217 write_iter = dtoa_g(singular_values[new_pheno_idx], write_iter);
10218 *write_iter++ = '\t';
10219 }
10220 const double* matrix_col_iter = &(matrix[new_pheno_idx]);
10221 for (uint32_t orig_pheno_idx = 0; orig_pheno_idx != orig_pheno_ct; ++orig_pheno_idx) {
10222 write_iter = dtoa_g(*matrix_col_iter, write_iter);
10223 *write_iter++ = '\t';
10224 matrix_col_iter = &(matrix_col_iter[svd_dim]);
10225 }
10226 --write_iter;
10227 AppendBinaryEoln(&write_iter);
10228 if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) {
10229 goto PhenoSvd_ret_WRITE_FAIL;
10230 }
10231 }
10232
10233 if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) {
10234 goto PhenoSvd_ret_WRITE_FAIL;
10235 }
10236 outname_end[strlen(".svd.pheno")] = '\0';
10237 logprintfww("--pheno-svd: Results written to %s + %s_wts .\n", outname, outname);
10238
10239 // ensure cleanup works if new phenotype initialization fails in the middle
10240 for (uint32_t pheno_idx = new_pheno_ct; pheno_idx != orig_pheno_ct; ++pheno_idx) {
10241 pheno_cols[pheno_idx].nonmiss = nullptr;
10242 }
10243
10244 const uintptr_t old_pheno_names_size = orig_pheno_ct * orig_max_pheno_name_blen;
10245 const uintptr_t new_max_pheno_name_blen = 9 + UintSlen(new_pheno_ct + 1);
10246 const uintptr_t new_pheno_names_size = new_pheno_ct * new_max_pheno_name_blen;
10247 char* new_pheno_names = orig_pheno_names;
10248 if (new_pheno_names_size > old_pheno_names_size) {
10249 if (unlikely(pgl_malloc(new_pheno_names_size, &new_pheno_names))) {
10250 goto PhenoSvd_ret_NOMEM;
10251 }
10252 *pheno_names_ptr = new_pheno_names;
10253 }
10254 for (uint32_t pheno_idx = 0; pheno_idx != new_pheno_ct; ) {
10255 char* pheno_write_iter = strcpya_k(&(new_pheno_names[pheno_idx * new_max_pheno_name_blen]), "SVDPHENO");
10256 ++pheno_idx;
10257 write_iter = u32toa(pheno_idx, pheno_write_iter);
10258 *write_iter = '\0';
10259 }
10260 const uintptr_t nonmiss_vec_ct = BitCtToVecCt(raw_sample_ct);
10261 const uintptr_t data_vec_ct = DblCtToVecCt(raw_sample_ct);
10262 for (uint32_t pheno_idx = 0; pheno_idx != new_pheno_ct; ++pheno_idx) {
10263 // could try to reuse, but let's keep this a bit simpler for now
10264 vecaligned_free_cond(pheno_cols[pheno_idx].nonmiss);
10265 pheno_cols[pheno_idx].nonmiss = nullptr;
10266 uintptr_t* new_pheno_data_iter;
10267 if (unlikely(vecaligned_malloc((nonmiss_vec_ct + data_vec_ct) * kBytesPerVec, &new_pheno_data_iter))) {
10268 goto PhenoSvd_ret_NOMEM;
10269 }
10270 pheno_cols[pheno_idx].nonmiss = new_pheno_data_iter;
10271 memcpy(new_pheno_data_iter, sample_intersect, raw_sample_ctaw * sizeof(intptr_t));
10272 new_pheno_data_iter = &(new_pheno_data_iter[raw_sample_ctaw]);
10273 double* qt = R_CAST(double*, new_pheno_data_iter);
10274 pheno_cols[pheno_idx].data.qt = qt;
10275
10276 const double* svd_sample_result_col = &(svd_sample_result[pheno_idx]);
10277 uintptr_t sample_uidx_base = 0;
10278 uintptr_t cur_bits = sample_intersect[0];
10279 for (uint32_t sample_idx = 0; sample_idx != new_sample_ct; ++sample_idx) {
10280 const uintptr_t sample_uidx = BitIter1(sample_intersect, &sample_uidx_base, &cur_bits);
10281 qt[sample_uidx] = svd_sample_result_col[sample_idx * svd_dim];
10282 }
10283 }
10284 *pheno_ct_ptr = new_pheno_ct;
10285 *max_pheno_name_blen_ptr = new_max_pheno_name_blen;
10286 }
10287 while (0) {
10288 PhenoSvd_ret_NOMEM:
10289 reterr = kPglRetNomem;
10290 break;
10291 PhenoSvd_ret_OPEN_FAIL:
10292 reterr = kPglRetOpenFail;
10293 break;
10294 PhenoSvd_ret_WRITE_FAIL:
10295 reterr = kPglRetWriteFail;
10296 break;
10297 PhenoSvd_ret_INCONSISTENT_INPUT:
10298 reterr = kPglRetInconsistentInput;
10299 break;
10300 PhenoSvd_ret_DEGENERATE_DATA:
10301 reterr = kPglRetDegenerateData;
10302 break;
10303 }
10304 BLAS_SET_NUM_THREADS(1);
10305 fclose_cond(outfile);
10306 BigstackReset(bigstack_mark);
10307 return reterr;
10308 }
10309 #endif
10310
10311 #ifdef __cplusplus
10312 } // namespace plink2
10313 #endif