Debian Codegraph @

plink_glm.c

raw symbols SCIP
1 // This file is part of PLINK 1.9, copyright (C) 2005-2024 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for 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 "plink_common.h"
19
20 #include "plink_assoc.h"
21 #include "plink_cluster.h"
22 #include "plink_ld.h"
23 #include "plink_matrix.h"
24 #include "plink_perm.h"
25 #include "plink_set.h"
26 #include "plink_stats.h"
27
28 // currently assumed to be no larger than MODEL_BLOCKSIZE
29 // might not want a perfect power of 2 due to cache eviction issues?
30 #define GLM_BLOCKSIZE 512
31
32 // multithread globals
33 static double* g_mperm_save_all;
34
35 // A separated-low-and-high-bit format was tried, and found to not really be
36 // any better than the usual PLINK 2-bit format.
37 static uintptr_t* g_loadbuf;
38
39 #ifndef NOLAPACK
40 static double g_pheno_sum;
41 static double g_pheno_ssq;
42 #endif
43
44 static uint32_t* g_nm_cts;
45
46 // This is *twice* the number of successes, because PLINK 1.07 counts tie as
47 // 0.5. (Actually, it randomizes instead of deterministically adding 0.5; this
48 // randomization just adds noise so we don't replicate it.)
49 static uint32_t* g_perm_2success_ct;
50 static uint32_t* g_perm_attempt_ct;
51 static double* g_maxt_extreme_stat;
52 static double* g_maxt_thread_results;
53
54 // to avoid pathological multithreading issues, this is not a bitset
55 static unsigned char* g_perm_adapt_stop;
56
57 static uint32_t g_adapt_m_table[MODEL_BLOCKSIZE];
58 static uint32_t g_assoc_thread_ct;
59 static uint32_t g_block_diff;
60 static uint32_t g_perms_done;
61 static uint32_t g_first_adapt_check;
62 static double g_adaptive_intercept;
63 static double g_adaptive_slope;
64 static double g_aperm_alpha;
65 static double g_adaptive_ci_zt;
66 static uint32_t g_is_x;
67 static uint32_t g_is_y;
68 static uint32_t g_min_ploidy_1;
69
70 uint32_t glm_init_load_mask(uintptr_t* sample_exclude, uintptr_t* pheno_nm, uintptr_t* covar_nm, uint32_t sample_ct, uintptr_t unfiltered_sample_ctv2, uintptr_t** load_mask_ptr) {
71 uint32_t sample_uidx = 0;
72 uintptr_t* load_mask;
73 uint32_t sample_idx;
74 if (bigstack_calloc_ul(unfiltered_sample_ctv2 / 2, load_mask_ptr)) {
75 return 1;
76 }
77 load_mask = *load_mask_ptr;
78 if (covar_nm) {
79 for (sample_idx = 0; sample_idx < sample_ct; sample_uidx++, sample_idx++) {
80 next_unset_unsafe_ck(sample_exclude, &sample_uidx);
81 if (IS_SET(pheno_nm, sample_uidx) & IS_SET(covar_nm, sample_idx)) {
82 SET_BIT(sample_uidx, load_mask);
83 }
84 }
85 } else {
86 memcpy(load_mask, pheno_nm, unfiltered_sample_ctv2 * (sizeof(intptr_t) / 2));
87 }
88 return 0;
89 }
90
91 int32_t glm_scan_conditions(char* condition_mname, char* condition_fname, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude, uintptr_t marker_ct, char* marker_ids, uintptr_t max_marker_id_len, Chrom_info* chrom_info_ptr, uint32_t hh_or_mt_exists, uintptr_t* loadbuf_raw, FILE* bedfile, uintptr_t bed_offset, uintptr_t unfiltered_sample_ct, uintptr_t* sex_male, uintptr_t* load_mask, uintptr_t* sample_valid_ct_ptr, uintptr_t* condition_ct_ptr, uint32_t** condition_uidxs_ptr, uintptr_t* sample_raw_include2, uintptr_t* sample_raw_male_include2) {
92 // side effects: load_mask and sample_valid_ct potentially updated,
93 // condition_ct should be changed, condition_uidxs should be malloc'd
94 unsigned char* bigstack_mark = g_bigstack_base;
95 FILE* condition_file = nullptr;
96 uint32_t* condition_uidxs = nullptr;
97 uintptr_t marker_ctl = BITCT_TO_WORDCT(marker_ct);
98 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
99 uintptr_t unfiltered_sample_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(unfiltered_sample_ct);
100 uintptr_t sample_valid_ct = *sample_valid_ct_ptr;
101 uintptr_t miss_ct = 0;
102 uintptr_t condition_ct = 0;
103 uintptr_t line_idx = 0;
104 int32_t retval = 0;
105 #ifdef __LP64__
106 __m128i* loadbuf_vptr;
107 __m128i* loadbuf_mask_vptr;
108 __m128i* loadbuf_vend;
109 __m128i vii;
110 #else
111 uintptr_t unfiltered_sample_ctl2 = QUATERCT_TO_WORDCT(unfiltered_sample_ct);
112 uintptr_t* loadbuf_end;
113 #endif
114 uintptr_t* loadbuf_ptr;
115 uintptr_t* loadbuf_mask_ptr;
116 char* sorted_ids;
117 uint32_t* id_map;
118 uintptr_t* already_seen;
119 uintptr_t* loadbuf_mask_orig;
120 uintptr_t* loadbuf_mask;
121 uint32_t* marker_idx_to_uidx;
122 uint32_t* condition_uidxs_tmp;
123 char* bufptr;
124 char* bufptr2;
125 uintptr_t condition_ct_max;
126 uintptr_t condition_idx;
127 uintptr_t sample_uidx_offset;
128 uintptr_t ulii;
129 uintptr_t uljj;
130 uint32_t marker_uidx;
131 uint32_t chrom_idx;
132 uint32_t is_x;
133 uint32_t is_y;
134 int32_t ii;
135 if (condition_mname) {
136 ii = get_uidx_from_unsorted(condition_mname, marker_exclude, marker_ct, marker_ids, max_marker_id_len);
137 if (ii == -1) {
138 LOGERRPRINTFWW("Warning: --condition variant ID '%s' not found.\n", condition_mname);
139 return 0;
140 }
141 condition_ct = 1;
142 condition_uidxs = (uint32_t*)malloc(sizeof(int32_t));
143 condition_uidxs[0] = (uint32_t)ii;
144 } else {
145 if (bigstack_alloc_c(marker_ct * max_marker_id_len, &sorted_ids) ||
146 bigstack_alloc_ui(marker_ct, &id_map) ||
147 bigstack_calloc_ul(marker_ctl, &already_seen) ||
148 bigstack_alloc_ui(marker_ct, &marker_idx_to_uidx)) {
149 goto glm_scan_conditions_ret_NOMEM;
150 }
151 fill_idx_to_uidx(marker_exclude, unfiltered_marker_ct, marker_ct, marker_idx_to_uidx);
152 retval = sort_item_ids_noalloc(unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, 0, 1, strcmp_deref, sorted_ids, id_map);
153 if (retval) {
154 goto glm_scan_conditions_ret_1;
155 }
156 condition_uidxs_tmp = (uint32_t*)g_bigstack_base;
157 condition_ct_max = bigstack_left() / sizeof(int32_t);
158 if (condition_ct_max > marker_ct) {
159 condition_ct_max = marker_ct;
160 }
161 if (fopen_checked(condition_fname, "r", &condition_file)) {
162 goto glm_scan_conditions_ret_OPEN_FAIL;
163 }
164 g_textbuf[MAXLINELEN - 1] = ' ';
165 while (fgets(g_textbuf, MAXLINELEN, condition_file)) {
166 line_idx++;
167 if (!g_textbuf[MAXLINELEN - 1]) {
168 snprintf(g_logbuf, LOGBUFLEN, "Error: Line %" PRIuPTR " of --condition-list file is pathologically long.\n", line_idx);
169 goto glm_scan_conditions_ret_INVALID_FORMAT_2;
170 }
171 bufptr = skip_initial_spaces(g_textbuf);
172 while (!is_eoln_kns(*bufptr)) {
173 bufptr2 = token_endnn(bufptr);
174 ii = bsearch_str(bufptr, (uintptr_t)(bufptr2 - bufptr), sorted_ids, max_marker_id_len, marker_ct);
175 if (ii == -1) {
176 miss_ct++;
177 } else {
178 if (is_set(already_seen, ii)) {
179 LOGERRPRINTFWW("Error: Duplicate variant '%s' in --condition-list file.\n", bufptr);
180 goto glm_scan_conditions_ret_INVALID_FORMAT;
181 }
182 if (condition_ct == condition_ct_max) {
183 goto glm_scan_conditions_ret_NOMEM;
184 }
185 set_bit(ii, already_seen);
186 condition_uidxs_tmp[condition_ct++] = marker_idx_to_uidx[id_map[(uint32_t)ii]];
187 }
188 bufptr = skip_initial_spaces(bufptr2);
189 }
190 }
191 if (!feof(condition_file)) {
192 goto glm_scan_conditions_ret_READ_FAIL;
193 }
194 if (condition_ct) {
195 condition_uidxs = (uint32_t*)malloc(condition_ct * sizeof(int32_t));
196 memcpy(condition_uidxs, condition_uidxs_tmp, condition_ct * sizeof(int32_t));
197 } else if (!miss_ct) {
198 logerrprint("Warning: --condition-list file is empty.\n");
199 goto glm_scan_conditions_ret_1;
200 }
201 if (miss_ct) {
202 snprintf(g_logbuf, LOGBUFLEN, "--condition-list: %" PRIuPTR " of %" PRIuPTR " variant ID%s loaded from %s.\n", condition_ct, condition_ct + miss_ct, (condition_ct + miss_ct == 1)? "" : "s", condition_fname);
203 } else {
204 snprintf(g_logbuf, LOGBUFLEN, "--condition-list: %" PRIuPTR " variant ID%s loaded from %s.\n", condition_ct, (condition_ct == 1)? "" : "s", condition_fname);
205 }
206 logprintb();
207 }
208 if (condition_ct) {
209 if (bigstack_alloc_ul(unfiltered_sample_ctv2, &loadbuf_mask_orig) ||
210 bigstack_alloc_ul(unfiltered_sample_ctv2, &loadbuf_mask)) {
211 goto glm_scan_conditions_ret_NOMEM;
212 }
213 init_quaterarr_from_bitarr(load_mask, unfiltered_sample_ct, loadbuf_mask_orig);
214 memcpy(loadbuf_mask, loadbuf_mask_orig, unfiltered_sample_ctv2 * sizeof(intptr_t));
215 #ifdef __LP64__
216 loadbuf_vend = (__m128i*)(&(loadbuf_raw[unfiltered_sample_ctv2]));
217 #else
218 loadbuf_end = &(loadbuf_raw[unfiltered_sample_ctl2]);
219 #endif
220 for (condition_idx = 0; condition_idx < condition_ct; condition_idx++) {
221 // scan for missing values to update sample_valid_ct
222 marker_uidx = condition_uidxs[condition_idx];
223 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
224 goto glm_scan_conditions_ret_READ_FAIL;
225 }
226 // don't use load_and_collapse since collapse bitmask not finalized
227 if (load_raw(unfiltered_sample_ct4, bedfile, loadbuf_raw)) {
228 goto glm_scan_conditions_ret_READ_FAIL;
229 }
230 chrom_idx = get_variant_chrom(chrom_info_ptr, marker_uidx);
231 if (IS_SET(chrom_info_ptr->haploid_mask, chrom_idx) || (chrom_idx == (uint32_t)chrom_info_ptr->xymt_codes[MT_OFFSET])) {
232 is_x = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[X_OFFSET]);
233 is_y = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[Y_OFFSET]);
234 haploid_fix(hh_or_mt_exists, sample_raw_include2, sample_raw_male_include2, unfiltered_sample_ct, is_x, is_y, (unsigned char*)loadbuf_raw);
235 }
236 // clear loadbuf_mask bits where loadbuf is 01.
237 #ifdef __LP64__
238 loadbuf_vptr = (__m128i*)loadbuf_raw;
239 loadbuf_mask_vptr = (__m128i*)loadbuf_mask;
240 do {
241 vii = *loadbuf_vptr++;
242 vii = _mm_andnot_si128(_mm_srli_epi64(vii, 1), vii);
243 *loadbuf_mask_vptr = _mm_andnot_si128(vii, *loadbuf_mask_vptr);
244 loadbuf_mask_vptr++;
245 } while (loadbuf_vptr < loadbuf_vend);
246 #else
247 loadbuf_ptr = loadbuf_raw;
248 loadbuf_mask_ptr = loadbuf_mask;
249 do {
250 ulii = *loadbuf_ptr++;
251 ulii = ((~ulii) >> 1) & ulii;
252 *loadbuf_mask_ptr &= ~ulii;
253 loadbuf_mask_ptr++;
254 } while (loadbuf_ptr < loadbuf_end);
255 #endif
256 }
257 loadbuf_ptr = loadbuf_mask_orig;
258 loadbuf_mask_ptr = loadbuf_mask;
259 for (sample_uidx_offset = 0; sample_uidx_offset < unfiltered_sample_ct; sample_uidx_offset += BITCT2) {
260 ulii = (*loadbuf_ptr++) & (~(*loadbuf_mask_ptr++));
261 while (ulii) {
262 uljj = CTZLU(ulii);
263 clear_bit_ul(sample_uidx_offset + (uljj / 2), load_mask);
264 sample_valid_ct--;
265 ulii &= ulii - 1;
266 }
267 }
268 *condition_uidxs_ptr = condition_uidxs;
269 }
270 *condition_ct_ptr = condition_ct;
271 *sample_valid_ct_ptr = sample_valid_ct;
272 while (0) {
273 glm_scan_conditions_ret_NOMEM:
274 retval = RET_NOMEM;
275 break;
276 glm_scan_conditions_ret_OPEN_FAIL:
277 retval = RET_OPEN_FAIL;
278 break;
279 glm_scan_conditions_ret_READ_FAIL:
280 retval = RET_READ_FAIL;
281 break;
282 glm_scan_conditions_ret_INVALID_FORMAT_2:
283 logerrprintb();
284 glm_scan_conditions_ret_INVALID_FORMAT:
285 retval = RET_INVALID_FORMAT;
286 break;
287 }
288 glm_scan_conditions_ret_1:
289 bigstack_reset(bigstack_mark);
290 fclose_cond(condition_file);
291 return retval;
292 }
293
294 uint32_t glm_loadbuf_to_doubles(uintptr_t* loadbuf_collapsed, uint32_t sample_valid_ct, double* covar_row, double* geno_map, uintptr_t* cur_missing) {
295 // ok for cur_missing to be nullptr if there can't possibly be any missing
296 uintptr_t* ulptr_end = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
297 uint32_t cur_missing_ct = 0;
298 uint32_t sample_idx = 0;
299 uint32_t sample_idx_stop = BITCT2;
300 uintptr_t cur_word;
301 uintptr_t cur_genotype;
302 while (1) {
303 while (loadbuf_collapsed < ulptr_end) {
304 cur_word = *loadbuf_collapsed++;
305 for (; sample_idx < sample_idx_stop; sample_idx++, covar_row++, cur_word >>= 2) {
306 cur_genotype = cur_word & 3;
307 if (cur_genotype != 1) {
308 *covar_row = geno_map[cur_genotype];
309 } else {
310 SET_BIT(sample_idx, cur_missing);
311 }
312 }
313 sample_idx_stop += BITCT2;
314 }
315 if (sample_idx == sample_valid_ct) {
316 return cur_missing_ct;
317 }
318 ulptr_end++;
319 sample_idx_stop = sample_valid_ct;
320 }
321 }
322
323 uint32_t glm_loadbuf_to_doubles_x(uintptr_t* loadbuf_collapsed, uintptr_t* sex_male_collapsed, uint32_t sample_valid_ct, double* covar_row, double* geno_map, uintptr_t* cur_missing) {
324 uintptr_t* ulptr_end = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
325 uint32_t cur_missing_ct = 0;
326 uint32_t sample_idx = 0;
327 uint32_t sample_idx_stop = BITCT2;
328 uintptr_t cur_word;
329 uintptr_t cur_genotype;
330 while (1) {
331 while (loadbuf_collapsed < ulptr_end) {
332 cur_word = *loadbuf_collapsed++;
333 for (; sample_idx < sample_idx_stop; sample_idx++, covar_row++, cur_word >>= 2) {
334 cur_genotype = cur_word & 3;
335 if (cur_genotype != 1) {
336 *covar_row = geno_map[cur_genotype + 4 * IS_SET(sex_male_collapsed, sample_idx)];
337 } else {
338 SET_BIT(sample_idx, cur_missing);
339 }
340 }
341 sample_idx_stop += BITCT2;
342 }
343 if (sample_idx == sample_valid_ct) {
344 return cur_missing_ct;
345 }
346 ulptr_end++;
347 sample_idx_stop = sample_valid_ct;
348 }
349 }
350
351 uint32_t glm_loadbuf_to_floats(uintptr_t* loadbuf_collapsed, uint32_t sample_valid_ct, float* covar_row, float* geno_map, uintptr_t* cur_missing) {
352 // ok for cur_missing to be nullptr if there can't possibly be any missing
353 uintptr_t* ulptr_end = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
354 uint32_t cur_missing_ct = 0;
355 uint32_t sample_idx = 0;
356 uint32_t sample_idx_stop = BITCT2;
357 uintptr_t cur_word;
358 uintptr_t cur_genotype;
359 while (1) {
360 while (loadbuf_collapsed < ulptr_end) {
361 cur_word = *loadbuf_collapsed++;
362 for (; sample_idx < sample_idx_stop; sample_idx++, covar_row++, cur_word >>= 2) {
363 cur_genotype = cur_word & 3;
364 if (cur_genotype != 1) {
365 *covar_row = geno_map[cur_genotype];
366 } else {
367 SET_BIT(sample_idx, cur_missing);
368 }
369 }
370 sample_idx_stop += BITCT2;
371 }
372 if (sample_idx == sample_valid_ct) {
373 return cur_missing_ct;
374 }
375 ulptr_end++;
376 sample_idx_stop = sample_valid_ct;
377 }
378 }
379
380 uint32_t glm_loadbuf_to_floats_x(uintptr_t* loadbuf_collapsed, uintptr_t* sex_male_collapsed, uint32_t sample_valid_ct, float* covar_row, float* geno_map, uintptr_t* cur_missing) {
381 uintptr_t* ulptr_end = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
382 uint32_t cur_missing_ct = 0;
383 uint32_t sample_idx = 0;
384 uint32_t sample_idx_stop = BITCT2;
385 uintptr_t cur_word;
386 uintptr_t cur_genotype;
387 while (1) {
388 while (loadbuf_collapsed < ulptr_end) {
389 cur_word = *loadbuf_collapsed++;
390 for (; sample_idx < sample_idx_stop; sample_idx++, covar_row++, cur_word >>= 2) {
391 cur_genotype = cur_word & 3;
392 if (cur_genotype != 1) {
393 *covar_row = geno_map[cur_genotype + 4 * IS_SET(sex_male_collapsed, sample_idx)];
394 } else {
395 SET_BIT(sample_idx, cur_missing);
396 }
397 }
398 sample_idx_stop += BITCT2;
399 }
400 if (sample_idx == sample_valid_ct) {
401 return cur_missing_ct;
402 }
403 ulptr_end++;
404 sample_idx_stop = sample_valid_ct;
405 }
406 }
407
408 int32_t glm_check_vif(double vif_thresh, uintptr_t param_ct, uintptr_t sample_valid_ct, double* covars_collapsed, double* param_2d_buf, MATRIX_INVERT_BUF1_TYPE* mi_buf, double* param_2d_buf2) {
409 __CLPK_integer dim = ((uint32_t)param_ct) - 1;
410 uintptr_t param_ct_m1 = param_ct - 1;
411 double sample_ct_d = (double)((intptr_t)sample_valid_ct);
412 double sample_ct_recip = 1.0 / sample_ct_d;
413 double sample_ct_m1_recip = 1.0 / ((double)((intptr_t)(sample_valid_ct - 1)));
414 double* dptr;
415 double* dptr2;
416 double* dptr3;
417 uintptr_t param_idx;
418 uintptr_t param_idx2;
419 uintptr_t sample_idx;
420 double dxx;
421 double dyy;
422 for (param_idx = 1; param_idx < param_ct; param_idx++) {
423 dyy = 0; // sum
424 dptr = &(covars_collapsed[param_idx * sample_valid_ct]);
425 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
426 dxx = *dptr++;
427 dyy += dxx;
428 }
429 param_2d_buf2[param_idx] = dyy * sample_ct_recip;
430 }
431 for (param_idx = 1; param_idx < param_ct; param_idx++) {
432 dptr = &(param_2d_buf[(param_idx - 1) * param_ct]);
433 dyy = param_2d_buf2[param_idx] * sample_ct_d;
434 for (param_idx2 = param_idx; param_idx2 < param_ct; param_idx2++) {
435 dxx = 0;
436 dptr2 = &(covars_collapsed[param_idx * sample_valid_ct]);
437 dptr3 = &(covars_collapsed[param_idx2 * sample_valid_ct]);
438 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
439 dxx += (*dptr2++) * (*dptr3++);
440 }
441 dxx -= dyy * param_2d_buf2[param_idx2];
442 *dptr++ = dxx * sample_ct_m1_recip;
443 }
444 }
445 for (param_idx = 0; param_idx < param_ct_m1; param_idx++) {
446 dxx = param_2d_buf[param_idx * param_ct]; // diagonal element
447 if ((dxx == 0) || (!realnum(dxx))) {
448 return 1;
449 }
450 param_2d_buf2[param_idx] = 1.0 / sqrt(dxx); // now inverse sqrt of diagonal
451 }
452 for (param_idx = 1; param_idx < param_ct_m1; param_idx++) {
453 dyy = param_2d_buf2[param_idx];
454 dptr = &(param_2d_buf[param_idx * param_ct_m1]);
455 dptr3 = param_2d_buf2;
456 for (param_idx2 = 0; param_idx2 < param_idx; param_idx2++) {
457 dptr2 = &(param_2d_buf[param_idx2 * param_ct_m1 + param_idx]);
458 dxx = (*dptr2) * dyy * (*dptr3++);
459 if (dxx > 0.999) {
460 return 1;
461 }
462 *dptr2 = dxx;
463 *dptr++ = dxx;
464 }
465 }
466 for (param_idx = 0; param_idx < param_ct_m1; param_idx++) {
467 param_2d_buf[param_idx * param_ct] = 1;
468 }
469
470 if (invert_matrix(dim, param_2d_buf, mi_buf, param_2d_buf2)) {
471 return 1;
472 }
473 for (param_idx = 0; param_idx < param_ct_m1; param_idx++) {
474 if (param_2d_buf[param_idx * param_ct] > vif_thresh) {
475 return 1;
476 }
477 }
478 return 0;
479 }
480
481 uint32_t glm_linear(uintptr_t cur_batch_size, uintptr_t param_ct, uintptr_t sample_valid_ct, uint32_t missing_ct, uintptr_t* loadbuf, uint32_t standard_beta, double pheno_sum_base, double pheno_ssq_base, double* covars_cov_major, double* covars_sample_major, double* perm_pmajor, double* coef, double* param_2d_buf, MATRIX_INVERT_BUF1_TYPE* mi_buf, double* param_2d_buf2, double* linear_results, uintptr_t constraint_ct, double* constraints_con_major, double* param_df_buf, double* param_df_buf2, double* df_df_buf, double* df_buf, uint32_t* perm_fail_ct_ptr, uintptr_t* perm_fails) {
482 // See the second half of PLINK 1.07 linear.cpp fitLM(), and
483 // validParameters(). The HuberWhite() logic is, unfortunately, buggy so
484 // it's been removed (if you want to try to fix it, pull the 1 Aug 2014
485 // version of this file from git).
486 // Diagonals of the final covariance matrices (not including the intercept
487 // element) are saved to linear_results[(perm_idx * (param_ct - 1))..
488 // ((perm_idx + 1) * (param_ct - 1) - 1)].
489 // If not all permutations yield valid results, bits in perm_fails[] are set.
490 // A return value of 1 reports that ALL permutations failed. In this case,
491 // perm_fails is not necessarily updated.
492 uintptr_t param_ct_p1 = param_ct + 1; // diagonals of param * param matrix
493 uintptr_t joint_test_requested = (constraints_con_major? 1 : 0);
494 uintptr_t param_ctx = param_ct + joint_test_requested;
495 uintptr_t param_ctx_m1 = param_ctx - 1;
496 uintptr_t cur_word = 0;
497 uint32_t perm_fail_ct = 0;
498 double* dptr;
499 double* dptr2;
500 double* dptr3;
501 uintptr_t* ulptr;
502 double* pheno_ptr;
503 double partial;
504 double min_sigma;
505 double pheno_sum;
506 double pheno_ssq;
507 uintptr_t sample_uidx;
508 uintptr_t sample_idx;
509 uintptr_t param_idx;
510 uintptr_t param_idx2;
511 uintptr_t perm_idx;
512
513 double dxx;
514 double dyy;
515 double dzz;
516 fill_ulong_zero(BITCT_TO_WORDCT(cur_batch_size), perm_fails);
517 col_major_matrix_multiply((uint32_t)param_ct, (uint32_t)param_ct, (uint32_t)sample_valid_ct, covars_sample_major, covars_cov_major, param_2d_buf);
518 if (invert_matrix((uint32_t)param_ct, param_2d_buf, mi_buf, param_2d_buf2)) {
519 return 1;
520 }
521
522 // only need to perform S[i][j] / sqrt(S[i][i] * S[j][j]) check once, since
523 // it's independent of sigma
524
525 // may as well cache square roots
526 for (param_idx = 0; param_idx < param_ct; param_idx++) {
527 param_2d_buf2[param_idx] = sqrt(param_2d_buf[param_idx * param_ct_p1]);
528 }
529 for (param_idx = 1; param_idx < param_ct; param_idx++) {
530 dxx = 0.99999 * param_2d_buf2[param_idx];
531 dptr = &(param_2d_buf[param_idx * param_ct]); // S[i][j]
532 dptr2 = param_2d_buf2; // sqrt(S[j][j])
533 for (param_idx2 = 0; param_idx2 < param_idx; param_idx2++) {
534 // S[i][j] / sqrt(S[i][i] * S[j][j]) > 0.99999
535 // -> S[i][j] > 0.99999 * sqrt(S[i][i]) * sqrt(S[j][j])
536 if ((*dptr++) > dxx * (*dptr2++)) {
537 return 1;
538 }
539 }
540 }
541 // now determine min(S[i][i]), i >= 1
542 min_sigma = param_2d_buf[param_ct_p1];
543 for (param_idx = 2; param_idx < param_ct; param_idx++) {
544 dxx = param_2d_buf[param_idx * param_ct_p1];
545 if (min_sigma > dxx) {
546 min_sigma = dxx;
547 }
548 }
549 if (min_sigma <= 0) {
550 return 1;
551 }
552 // S[i][i] * sigma < 1e-20 iff sigma < 1e-20 / S[i][i]
553 min_sigma = 1e-20 / min_sigma;
554
555 // now temporarily save sigmas in linear_results[perm_idx * param_ctx_m1]
556 pheno_ptr = perm_pmajor;
557 dyy = 1;
558 dzz = 0;
559 for (perm_idx = 0; perm_idx < cur_batch_size; perm_idx++) {
560 // not coef[perm_idx * param_ct] due to how dgels() works
561 dptr = &(coef[perm_idx * sample_valid_ct]);
562
563 dptr2 = covars_sample_major;
564 dxx = 0;
565 if (!missing_ct) {
566 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
567 partial = 0;
568 dptr3 = dptr;
569 for (param_idx = 0; param_idx < param_ct; param_idx++) {
570 partial += (*dptr2++) * (*dptr3++);
571 }
572 partial -= *pheno_ptr++;
573 dxx += partial * partial;
574 }
575 } else {
576 if (standard_beta) {
577 pheno_sum = pheno_sum_base;
578 pheno_ssq = pheno_ssq_base;
579 ulptr = loadbuf;
580 for (sample_uidx = 0; sample_uidx < sample_valid_ct; sample_uidx += BITCT2) {
581 cur_word = *ulptr++;
582 cur_word = cur_word & (~(cur_word >> 1)) & FIVEMASK;
583 while (cur_word) {
584 dyy = pheno_ptr[sample_uidx + (CTZLU(cur_word) / 2)];
585 pheno_sum -= dyy;
586 pheno_ssq -= dyy * dyy;
587 cur_word &= cur_word - 1;
588 }
589 }
590 dzz = pheno_sum / ((double)((intptr_t)sample_valid_ct));
591 dyy = sqrt(((double)((intptr_t)(sample_valid_ct - 1))) / (pheno_ssq - pheno_sum * dzz));
592 }
593 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
594 partial = 0;
595 dptr3 = dptr;
596 for (param_idx = 0; param_idx < param_ct; param_idx++) {
597 partial += (*dptr2++) * (*dptr3++);
598 }
599 while (1) {
600 if (sample_uidx % BITCT2) {
601 cur_word >>= 2;
602 } else {
603 cur_word = loadbuf[sample_uidx / BITCT2];
604 cur_word = cur_word & (~(cur_word >> 1)) & FIVEMASK;
605 }
606 if (!(cur_word & 1)) {
607 break;
608 }
609 sample_uidx++;
610 }
611 partial -= (pheno_ptr[sample_uidx] - dzz) * dyy;
612 dxx += partial * partial;
613 }
614 pheno_ptr = &(pheno_ptr[sample_valid_ct + missing_ct]);
615 }
616 linear_results[perm_idx * param_ctx_m1] = dxx;
617 }
618 dxx = 1.0 / ((double)((intptr_t)(sample_valid_ct - param_ct)));
619 if (!constraint_ct) {
620 // only need diagonal of S
621 dptr2 = param_2d_buf2;
622 for (param_idx = 1; param_idx < param_ct; param_idx++) {
623 *dptr2++ = param_2d_buf[param_idx * param_ct_p1]; // S0[i][i]
624 }
625 }
626 dptr = linear_results;
627 for (perm_idx = 0; perm_idx < cur_batch_size; perm_idx++) {
628 dyy = dxx * (*dptr); // sigma = (previous sigma) / (nind-np)
629 if (dyy < min_sigma) {
630 dyy = 0;
631 perm_fail_ct++;
632 dptr = &(dptr[param_ctx_m1]);
633 SET_BIT(perm_idx, perm_fails);
634 } else {
635 dptr2 = param_2d_buf2;
636 if (!joint_test_requested) {
637 for (param_idx = 1; param_idx < param_ct; param_idx++) {
638 *dptr++ = (*dptr2++) * dyy; // S[i][i] = S0[i][i] * sigma
639 }
640 } else if (constraint_ct) {
641 // need all of S for linear_hypothesis_chisq()
642 dptr3 = param_2d_buf;
643 param_idx2 = param_ct * param_ct;
644 for (param_idx = 0; param_idx < param_idx2; param_idx++) {
645 *dptr2++ = (*dptr3++) * dyy;
646 }
647 for (param_idx = 1; param_idx < param_ct; param_idx++) {
648 *dptr++ = param_2d_buf2[param_idx * param_ct_p1];
649 }
650 if (!linear_hypothesis_chisq(constraint_ct, param_ct, constraints_con_major, &(coef[perm_idx * sample_valid_ct]), param_2d_buf2, param_df_buf, param_df_buf2, df_df_buf, mi_buf, df_buf, &dyy)) {
651 *dptr++ = dyy;
652 } else {
653 // joint test failure does not make the entire permutation count
654 // as failed
655 *dptr++ = -9;
656 }
657 } else {
658 *dptr++ = -9;
659 }
660 }
661 }
662 *perm_fail_ct_ptr = perm_fail_ct;
663 return 0;
664 }
665
666 // #####
667 // The following code is based on the winning submissino of Pascal Pons in the
668 // "GWASSpeedup" contest run in April 2013 by Babbage Analytics & Innovation
669 // and TopCoder, who have donated the results to be used in PLINK. The contest
670 // was designed by Po-Ru Loh; subsequent analysis and code preparation were
671 // performed by Andrew Hill, Ragu Bharadwaj, and Scott Jelinsky. A manuscript
672 // is in preparation by these authors and Iain Kilty, Kevin Boudreau, Karim
673 // Lakhani and Eva Guinan.
674 // #####
675
676 #ifdef __LP64__
677 // exp_ps is a C port of Shigeo Mitsunari's fast math library posted at
678 // http://homepage1.nifty.com/herumi/ . License is
679 // http://opensource.org/licenses/BSD-3-Clause .
680
681 // programmatically generated by:
682 // typedef union {
683 // float f4;
684 // uint32_t u4;
685 // } __uni4;
686 //
687 // __uni4 u4;
688 // int32_t ii;
689 // for (ii = 0; ii < 1024; ii++) {
690 // u4.f4 = pow(2.0f, ((float)ii) / 1024.0);
691 // printf("0x%08x", u4.u4 & 0x7fffff);
692 // if (ii % 4 != 3) {
693 // printf(", ");
694 // } else {
695 // printf(",\n");
696 // }
697 // }
698 const uint32_t float_exp_lookup_int[] __attribute__((aligned(16))) = {
699 0x00000000, 0x00001630, 0x00002c64, 0x0000429c,
700 0x000058d8, 0x00006f17, 0x0000855b, 0x00009ba2,
701 0x0000b1ed, 0x0000c83c, 0x0000de8f, 0x0000f4e6,
702 0x00010b41, 0x0001219f, 0x00013802, 0x00014e68,
703 0x000164d2, 0x00017b40, 0x000191b2, 0x0001a828,
704 0x0001bea1, 0x0001d51f, 0x0001eba1, 0x00020226,
705 0x000218af, 0x00022f3c, 0x000245ce, 0x00025c63,
706 0x000272fc, 0x00028998, 0x0002a039, 0x0002b6de,
707 0x0002cd87, 0x0002e433, 0x0002fae4, 0x00031198,
708 0x00032850, 0x00033f0d, 0x000355cd, 0x00036c91,
709 0x00038359, 0x00039a25, 0x0003b0f5, 0x0003c7c9,
710 0x0003dea1, 0x0003f57d, 0x00040c5d, 0x00042341,
711 0x00043a29, 0x00045115, 0x00046804, 0x00047ef8,
712 0x000495f0, 0x0004aceb, 0x0004c3eb, 0x0004daef,
713 0x0004f1f6, 0x00050902, 0x00052012, 0x00053725,
714 0x00054e3d, 0x00056558, 0x00057c78, 0x0005939c,
715 0x0005aac3, 0x0005c1ef, 0x0005d91f, 0x0005f052,
716 0x0006078a, 0x00061ec6, 0x00063606, 0x00064d4a,
717 0x00066491, 0x00067bdd, 0x0006932d, 0x0006aa81,
718 0x0006c1d9, 0x0006d935, 0x0006f095, 0x000707f9,
719 0x00071f62, 0x000736ce, 0x00074e3e, 0x000765b3,
720 0x00077d2b, 0x000794a8, 0x0007ac28, 0x0007c3ad,
721 0x0007db35, 0x0007f2c2, 0x00080a53, 0x000821e8,
722 0x00083981, 0x0008511e, 0x000868c0, 0x00088065,
723 0x0008980f, 0x0008afbc, 0x0008c76e, 0x0008df23,
724 0x0008f6dd, 0x00090e9b, 0x0009265d, 0x00093e24,
725 0x000955ee, 0x00096dbc, 0x0009858f, 0x00099d66,
726 0x0009b541, 0x0009cd20, 0x0009e503, 0x0009fcea,
727 0x000a14d5, 0x000a2cc5, 0x000a44b9, 0x000a5cb1,
728 0x000a74ad, 0x000a8cad, 0x000aa4b1, 0x000abcba,
729 0x000ad4c6, 0x000aecd7, 0x000b04ec, 0x000b1d05,
730 0x000b3523, 0x000b4d44, 0x000b656a, 0x000b7d94,
731 0x000b95c2, 0x000badf4, 0x000bc62b, 0x000bde65,
732 0x000bf6a4, 0x000c0ee7, 0x000c272f, 0x000c3f7a,
733 0x000c57ca, 0x000c701e, 0x000c8876, 0x000ca0d2,
734 0x000cb933, 0x000cd198, 0x000cea01, 0x000d026e,
735 0x000d1adf, 0x000d3355, 0x000d4bcf, 0x000d644d,
736 0x000d7cd0, 0x000d9556, 0x000dade1, 0x000dc671,
737 0x000ddf04, 0x000df79c, 0x000e1038, 0x000e28d8,
738 0x000e417d, 0x000e5a25, 0x000e72d3, 0x000e8b84,
739 0x000ea43a, 0x000ebcf3, 0x000ed5b2, 0x000eee74,
740 0x000f073b, 0x000f2006, 0x000f38d5, 0x000f51a9,
741 0x000f6a81, 0x000f835d, 0x000f9c3e, 0x000fb523,
742 0x000fce0c, 0x000fe6fa, 0x000fffec, 0x001018e2,
743 0x001031dc, 0x00104adb, 0x001063de, 0x00107ce6,
744 0x001095f2, 0x0010af02, 0x0010c816, 0x0010e12f,
745 0x0010fa4d, 0x0011136e, 0x00112c94, 0x001145be,
746 0x00115eed, 0x00117820, 0x00119158, 0x0011aa93,
747 0x0011c3d3, 0x0011dd18, 0x0011f661, 0x00120fae,
748 0x00122900, 0x00124256, 0x00125bb0, 0x0012750f,
749 0x00128e72, 0x0012a7da, 0x0012c146, 0x0012dab7,
750 0x0012f42c, 0x00130da5, 0x00132723, 0x001340a5,
751 0x00135a2b, 0x001373b6, 0x00138d46, 0x0013a6d9,
752 0x0013c072, 0x0013da0e, 0x0013f3af, 0x00140d55,
753 0x001426ff, 0x001440ae, 0x00145a60, 0x00147418,
754 0x00148dd4, 0x0014a794, 0x0014c159, 0x0014db22,
755 0x0014f4f0, 0x00150ec2, 0x00152898, 0x00154274,
756 0x00155c53, 0x00157637, 0x00159020, 0x0015aa0d,
757 0x0015c3ff, 0x0015ddf5, 0x0015f7ef, 0x001611ee,
758 0x00162bf2, 0x001645fa, 0x00166006, 0x00167a18,
759 0x0016942d, 0x0016ae47, 0x0016c866, 0x0016e289,
760 0x0016fcb1, 0x001716dd, 0x0017310e, 0x00174b43,
761 0x0017657d, 0x00177fbc, 0x001799ff, 0x0017b446,
762 0x0017ce92, 0x0017e8e3, 0x00180338, 0x00181d92,
763 0x001837f0, 0x00185253, 0x00186cbb, 0x00188727,
764 0x0018a197, 0x0018bc0d, 0x0018d686, 0x0018f105,
765 0x00190b88, 0x0019260f, 0x0019409c, 0x00195b2c,
766 0x001975c2, 0x0019905c, 0x0019aafa, 0x0019c59e,
767 0x0019e046, 0x0019faf2, 0x001a15a3, 0x001a3059,
768 0x001a4b13, 0x001a65d2, 0x001a8096, 0x001a9b5e,
769 0x001ab62b, 0x001ad0fd, 0x001aebd3, 0x001b06ae,
770 0x001b218d, 0x001b3c71, 0x001b575a, 0x001b7248,
771 0x001b8d3a, 0x001ba831, 0x001bc32c, 0x001bde2c,
772 0x001bf931, 0x001c143b, 0x001c2f49, 0x001c4a5c,
773 0x001c6573, 0x001c8090, 0x001c9bb1, 0x001cb6d6,
774 0x001cd201, 0x001ced30, 0x001d0864, 0x001d239c,
775 0x001d3eda, 0x001d5a1c, 0x001d7562, 0x001d90ae,
776 0x001dabfe, 0x001dc753, 0x001de2ad, 0x001dfe0b,
777 0x001e196e, 0x001e34d6, 0x001e5043, 0x001e6bb4,
778 0x001e872a, 0x001ea2a5, 0x001ebe25, 0x001ed9a9,
779 0x001ef532, 0x001f10c0, 0x001f2c53, 0x001f47eb,
780 0x001f6387, 0x001f7f28, 0x001f9ace, 0x001fb679,
781 0x001fd228, 0x001feddc, 0x00200996, 0x00202553,
782 0x00204116, 0x00205cde, 0x002078aa, 0x0020947b,
783 0x0020b051, 0x0020cc2c, 0x0020e80b, 0x002103f0,
784 0x00211fd9, 0x00213bc7, 0x002157ba, 0x002173b2,
785 0x00218faf, 0x0021abb0, 0x0021c7b7, 0x0021e3c2,
786 0x0021ffd2, 0x00221be7, 0x00223801, 0x0022541f,
787 0x00227043, 0x00228c6b, 0x0022a899, 0x0022c4cb,
788 0x0022e102, 0x0022fd3e, 0x0023197f, 0x002335c5,
789 0x0023520f, 0x00236e5f, 0x00238ab3, 0x0023a70d,
790 0x0023c36b, 0x0023dfce, 0x0023fc37, 0x002418a4,
791 0x00243516, 0x0024518d, 0x00246e08, 0x00248a89,
792 0x0024a70f, 0x0024c39a, 0x0024e029, 0x0024fcbe,
793 0x00251958, 0x002535f6, 0x00255299, 0x00256f42,
794 0x00258bef, 0x0025a8a2, 0x0025c559, 0x0025e215,
795 0x0025fed7, 0x00261b9d, 0x00263868, 0x00265538,
796 0x0026720e, 0x00268ee8, 0x0026abc7, 0x0026c8ac,
797 0x0026e595, 0x00270283, 0x00271f76, 0x00273c6f,
798 0x0027596c, 0x0027766e, 0x00279376, 0x0027b082,
799 0x0027cd94, 0x0027eaaa, 0x002807c6, 0x002824e6,
800 0x0028420c, 0x00285f37, 0x00287c66, 0x0028999b,
801 0x0028b6d5, 0x0028d414, 0x0028f158, 0x00290ea1,
802 0x00292bef, 0x00294942, 0x0029669b, 0x002983f8,
803 0x0029a15b, 0x0029bec2, 0x0029dc2f, 0x0029f9a1,
804 0x002a1718, 0x002a3494, 0x002a5215, 0x002a6f9b,
805 0x002a8d26, 0x002aaab7, 0x002ac84c, 0x002ae5e7,
806 0x002b0387, 0x002b212c, 0x002b3ed6, 0x002b5c85,
807 0x002b7a3a, 0x002b97f3, 0x002bb5b2, 0x002bd376,
808 0x002bf13f, 0x002c0f0d, 0x002c2ce0, 0x002c4ab9,
809 0x002c6897, 0x002c867a, 0x002ca462, 0x002cc24f,
810 0x002ce041, 0x002cfe39, 0x002d1c36, 0x002d3a38,
811 0x002d583f, 0x002d764b, 0x002d945d, 0x002db274,
812 0x002dd090, 0x002deeb1, 0x002e0cd8, 0x002e2b03,
813 0x002e4934, 0x002e676b, 0x002e85a6, 0x002ea3e7,
814 0x002ec22d, 0x002ee078, 0x002efec8, 0x002f1d1e,
815 0x002f3b79, 0x002f59d9, 0x002f783e, 0x002f96a9,
816 0x002fb519, 0x002fd38e, 0x002ff209, 0x00301089,
817 0x00302f0e, 0x00304d98, 0x00306c28, 0x00308abd,
818 0x0030a957, 0x0030c7f7, 0x0030e69c, 0x00310546,
819 0x003123f6, 0x003142aa, 0x00316165, 0x00318024,
820 0x00319ee9, 0x0031bdb3, 0x0031dc83, 0x0031fb57,
821 0x00321a32, 0x00323911, 0x003257f6, 0x003276e0,
822 0x003295d0, 0x0032b4c5, 0x0032d3bf, 0x0032f2bf,
823 0x003311c4, 0x003330cf, 0x00334fde, 0x00336ef4,
824 0x00338e0e, 0x0033ad2e, 0x0033cc54, 0x0033eb7e,
825 0x00340aaf, 0x003429e4, 0x0034491f, 0x00346860,
826 0x003487a6, 0x0034a6f1, 0x0034c642, 0x0034e598,
827 0x003504f3, 0x00352454, 0x003543bb, 0x00356327,
828 0x00358298, 0x0035a20f, 0x0035c18b, 0x0035e10d,
829 0x00360094, 0x00362020, 0x00363fb2, 0x00365f4a,
830 0x00367ee7, 0x00369e89, 0x0036be31, 0x0036dddf,
831 0x0036fd92, 0x00371d4a, 0x00373d08, 0x00375ccc,
832 0x00377c95, 0x00379c63, 0x0037bc37, 0x0037dc11,
833 0x0037fbf0, 0x00381bd4, 0x00383bbe, 0x00385bae,
834 0x00387ba3, 0x00389b9e, 0x0038bb9e, 0x0038dba4,
835 0x0038fbaf, 0x00391bc0, 0x00393bd7, 0x00395bf3,
836 0x00397c14, 0x00399c3b, 0x0039bc68, 0x0039dc9a,
837 0x0039fcd2, 0x003a1d10, 0x003a3d53, 0x003a5d9b,
838 0x003a7dea, 0x003a9e3e, 0x003abe97, 0x003adef6,
839 0x003aff5b, 0x003b1fc5, 0x003b4035, 0x003b60aa,
840 0x003b8126, 0x003ba1a6, 0x003bc22d, 0x003be2b9,
841 0x003c034a, 0x003c23e2, 0x003c447f, 0x003c6521,
842 0x003c85ca, 0x003ca678, 0x003cc72b, 0x003ce7e5,
843 0x003d08a4, 0x003d2968, 0x003d4a33, 0x003d6b03,
844 0x003d8bd8, 0x003dacb4, 0x003dcd95, 0x003dee7c,
845 0x003e0f68, 0x003e305a, 0x003e5152, 0x003e7250,
846 0x003e9353, 0x003eb45c, 0x003ed56b, 0x003ef67f,
847 0x003f179a, 0x003f38ba, 0x003f59df, 0x003f7b0b,
848 0x003f9c3c, 0x003fbd73, 0x003fdeb0, 0x003ffff2,
849 0x0040213b, 0x00404289, 0x004063dc, 0x00408536,
850 0x0040a695, 0x0040c7fb, 0x0040e966, 0x00410ad6,
851 0x00412c4d, 0x00414dc9, 0x00416f4b, 0x004190d3,
852 0x0041b261, 0x0041d3f5, 0x0041f58e, 0x0042172d,
853 0x004238d2, 0x00425a7d, 0x00427c2e, 0x00429de4,
854 0x0042bfa1, 0x0042e163, 0x0043032b, 0x004324f9,
855 0x004346cd, 0x004368a7, 0x00438a86, 0x0043ac6b,
856 0x0043ce57, 0x0043f048, 0x0044123f, 0x0044343c,
857 0x0044563f, 0x00447848, 0x00449a56, 0x0044bc6b,
858 0x0044de85, 0x004500a5, 0x004522cc, 0x004544f8,
859 0x0045672a, 0x00458962, 0x0045aba0, 0x0045cde4,
860 0x0045f02e, 0x0046127e, 0x004634d3, 0x0046572f,
861 0x00467991, 0x00469bf8, 0x0046be66, 0x0046e0d9,
862 0x00470353, 0x004725d2, 0x00474858, 0x00476ae3,
863 0x00478d75, 0x0047b00c, 0x0047d2aa, 0x0047f54d,
864 0x004817f7, 0x00483aa6, 0x00485d5b, 0x00488017,
865 0x0048a2d8, 0x0048c5a0, 0x0048e86d, 0x00490b41,
866 0x00492e1b, 0x004950fa, 0x004973e0, 0x004996cc,
867 0x0049b9be, 0x0049dcb5, 0x0049ffb3, 0x004a22b7,
868 0x004a45c1, 0x004a68d1, 0x004a8be8, 0x004aaf04,
869 0x004ad226, 0x004af54f, 0x004b187d, 0x004b3bb2,
870 0x004b5eed, 0x004b822e, 0x004ba575, 0x004bc8c2,
871 0x004bec15, 0x004c0f6e, 0x004c32ce, 0x004c5633,
872 0x004c799f, 0x004c9d11, 0x004cc089, 0x004ce407,
873 0x004d078c, 0x004d2b16, 0x004d4ea7, 0x004d723d,
874 0x004d95da, 0x004db97e, 0x004ddd27, 0x004e00d6,
875 0x004e248c, 0x004e4848, 0x004e6c0a, 0x004e8fd2,
876 0x004eb3a1, 0x004ed775, 0x004efb50, 0x004f1f31,
877 0x004f4319, 0x004f6706, 0x004f8afa, 0x004faef4,
878 0x004fd2f4, 0x004ff6fb, 0x00501b08, 0x00503f1b,
879 0x00506334, 0x00508753, 0x0050ab79, 0x0050cfa5,
880 0x0050f3d7, 0x00511810, 0x00513c4f, 0x00516094,
881 0x005184df, 0x0051a931, 0x0051cd89, 0x0051f1e7,
882 0x0052164c, 0x00523ab7, 0x00525f28, 0x005283a0,
883 0x0052a81e, 0x0052cca2, 0x0052f12c, 0x005315bd,
884 0x00533a54, 0x00535ef2, 0x00538396, 0x0053a840,
885 0x0053ccf1, 0x0053f1a8, 0x00541665, 0x00543b29,
886 0x00545ff3, 0x005484c3, 0x0054a99a, 0x0054ce77,
887 0x0054f35b, 0x00551845, 0x00553d35, 0x0055622c,
888 0x00558729, 0x0055ac2d, 0x0055d137, 0x0055f647,
889 0x00561b5e, 0x0056407b, 0x0056659f, 0x00568ac9,
890 0x0056affa, 0x0056d531, 0x0056fa6e, 0x00571fb2,
891 0x005744fd, 0x00576a4e, 0x00578fa5, 0x0057b503,
892 0x0057da67, 0x0057ffd2, 0x00582543, 0x00584abb,
893 0x00587039, 0x005895be, 0x0058bb49, 0x0058e0db,
894 0x00590673, 0x00592c12, 0x005951b8, 0x00597763,
895 0x00599d16, 0x0059c2cf, 0x0059e88e, 0x005a0e54,
896 0x005a3421, 0x005a59f4, 0x005a7fcd, 0x005aa5ae,
897 0x005acb94, 0x005af182, 0x005b1776, 0x005b3d70,
898 0x005b6371, 0x005b8979, 0x005baf87, 0x005bd59c,
899 0x005bfbb8, 0x005c21da, 0x005c4802, 0x005c6e32,
900 0x005c9468, 0x005cbaa4, 0x005ce0e7, 0x005d0731,
901 0x005d2d82, 0x005d53d9, 0x005d7a36, 0x005da09b,
902 0x005dc706, 0x005ded77, 0x005e13f0, 0x005e3a6f,
903 0x005e60f5, 0x005e8781, 0x005eae14, 0x005ed4ae,
904 0x005efb4e, 0x005f21f5, 0x005f48a3, 0x005f6f58,
905 0x005f9613, 0x005fbcd5, 0x005fe39e, 0x00600a6d,
906 0x00603143, 0x00605820, 0x00607f03, 0x0060a5ee,
907 0x0060ccdf, 0x0060f3d7, 0x00611ad5, 0x006141db,
908 0x006168e7, 0x00618ffa, 0x0061b713, 0x0061de34,
909 0x0062055b, 0x00622c89, 0x006253be, 0x00627af9,
910 0x0062a23c, 0x0062c985, 0x0062f0d5, 0x0063182c,
911 0x00633f89, 0x006366ee, 0x00638e59, 0x0063b5cb,
912 0x0063dd44, 0x006404c4, 0x00642c4b, 0x006453d8,
913 0x00647b6d, 0x0064a308, 0x0064caaa, 0x0064f253,
914 0x00651a03, 0x006541b9, 0x00656977, 0x0065913c,
915 0x0065b907, 0x0065e0d9, 0x006608b2, 0x00663092,
916 0x00665879, 0x00668067, 0x0066a85c, 0x0066d058,
917 0x0066f85b, 0x00672064, 0x00674875, 0x0067708c,
918 0x006798ab, 0x0067c0d0, 0x0067e8fd, 0x00681130,
919 0x0068396a, 0x006861ac, 0x006889f4, 0x0068b243,
920 0x0068da99, 0x006902f7, 0x00692b5b, 0x006953c6,
921 0x00697c38, 0x0069a4b1, 0x0069cd32, 0x0069f5b9,
922 0x006a1e47, 0x006a46dd, 0x006a6f79, 0x006a981c,
923 0x006ac0c7, 0x006ae978, 0x006b1231, 0x006b3af1,
924 0x006b63b7, 0x006b8c85, 0x006bb55a, 0x006bde36,
925 0x006c0719, 0x006c3003, 0x006c58f4, 0x006c81ec,
926 0x006caaec, 0x006cd3f2, 0x006cfd00, 0x006d2614,
927 0x006d4f30, 0x006d7853, 0x006da17d, 0x006dcaae,
928 0x006df3e7, 0x006e1d26, 0x006e466d, 0x006e6fbb,
929 0x006e9910, 0x006ec26c, 0x006eebcf, 0x006f1539,
930 0x006f3eab, 0x006f6824, 0x006f91a4, 0x006fbb2b,
931 0x006fe4ba, 0x00700e4f, 0x007037ec, 0x00706190,
932 0x00708b3b, 0x0070b4ee, 0x0070dea8, 0x00710868,
933 0x00713231, 0x00715c00, 0x007185d7, 0x0071afb5,
934 0x0071d99a, 0x00720386, 0x00722d7a, 0x00725775,
935 0x00728177, 0x0072ab81, 0x0072d592, 0x0072ffaa,
936 0x007329c9, 0x007353f0, 0x00737e1e, 0x0073a853,
937 0x0073d290, 0x0073fcd4, 0x0074271f, 0x00745172,
938 0x00747bcc, 0x0074a62d, 0x0074d096, 0x0074fb06,
939 0x0075257d, 0x00754ffc, 0x00757a82, 0x0075a50f,
940 0x0075cfa4, 0x0075fa40, 0x007624e4, 0x00764f8f,
941 0x00767a41, 0x0076a4fb, 0x0076cfbc, 0x0076fa85,
942 0x00772555, 0x0077502d, 0x00777b0b, 0x0077a5f2,
943 0x0077d0df, 0x0077fbd5, 0x007826d1, 0x007851d5,
944 0x00787ce1, 0x0078a7f4, 0x0078d30e, 0x0078fe30,
945 0x0079295a, 0x0079548b, 0x00797fc3, 0x0079ab03,
946 0x0079d64a, 0x007a0199, 0x007a2cf0, 0x007a584d,
947 0x007a83b3, 0x007aaf20, 0x007ada94, 0x007b0610,
948 0x007b3194, 0x007b5d1f, 0x007b88b2, 0x007bb44c,
949 0x007bdfed, 0x007c0b97, 0x007c3748, 0x007c6300,
950 0x007c8ec0, 0x007cba88, 0x007ce657, 0x007d122e,
951 0x007d3e0c, 0x007d69f2, 0x007d95e0, 0x007dc1d5,
952 0x007dedd2, 0x007e19d6, 0x007e45e2, 0x007e71f6,
953 0x007e9e11, 0x007eca34, 0x007ef65f, 0x007f2291,
954 0x007f4ecb, 0x007f7b0d, 0x007fa756, 0x007fd3a7
955 };
956
957 const float* const float_exp_lookup = (const float*)float_exp_lookup_int;
958
959 static inline __m128 fmath_exp_ps(__m128 xx) {
960 const __m128i mask7ff = {0x7fffffff7fffffffLLU, 0x7fffffff7fffffffLLU};
961
962 // 88
963 const __m128i max_x = {0x42b0000042b00000LLU, 0x42b0000042b00000LLU};
964 // -88
965 // more sensible 0xc2b00000... not used here due to "narrowing conversion"
966 // warning
967 const __m128i min_x = {-0x3d4fffff3d500000LL, -0x3d4fffff3d500000LL};
968 // 2^10 / log(2)
969 const __m128i const_aa = {0x44b8aa3b44b8aa3bLLU, 0x44b8aa3b44b8aa3bLLU};
970 // log(2) / 2^10
971 const __m128i const_bb = {0x3a3172183a317218LLU, 0x3a3172183a317218LLU};
972
973 const __m128i f1 = {0x3f8000003f800000LLU, 0x3f8000003f800000LLU};
974 const __m128i mask_s = {0x3ff000003ffLLU, 0x3ff000003ffLLU};
975 const __m128i i127s = {0x1fc000001fc00LLU, 0x1fc000001fc00LLU};
976 __m128i limit = _mm_castps_si128(_mm_and_ps(xx, (__m128)mask7ff));
977 int32_t over = _mm_movemask_epi8(_mm_cmpgt_epi32(limit, max_x));
978 if (over) {
979 xx = _mm_min_ps(xx, (__m128)max_x);
980 xx = _mm_max_ps(xx, (__m128)min_x);
981 }
982 __m128i rr = _mm_cvtps_epi32(_mm_mul_ps(xx, (__m128)const_aa));
983 __m128 tt = _mm_sub_ps(xx, _mm_mul_ps(_mm_cvtepi32_ps(rr), (__m128)const_bb));
984 tt = _mm_add_ps(tt, (__m128)f1);
985 __m128i v4 = _mm_and_si128(rr, mask_s);
986 __m128i u4 = _mm_add_epi32(rr, i127s);
987 u4 = _mm_srli_epi32(u4, 10);
988 u4 = _mm_slli_epi32(u4, 23);
989 uint32_t v0 = _mm_cvtsi128_si32(v4);
990 // uint32_t v1 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(2)));
991 // uint32_t v2 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(4)));
992 // uint32_t v3 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(6)));
993 // make this work with LLVM
994 uint32_t v1 = _mm_extract_epi16(((__m128i)(v4)), ((int32_t)(2)));
995 uint32_t v2 = _mm_extract_epi16(((__m128i)(v4)), ((int32_t)(4)));
996 uint32_t v3 = _mm_extract_epi16(((__m128i)(v4)), ((int32_t)(6)));
997
998 __m128 t0 = _mm_set_ss(float_exp_lookup[v0]);
999 __m128 t1 = _mm_set_ss(float_exp_lookup[v1]);
1000 __m128 t2 = _mm_set_ss(float_exp_lookup[v2]);
1001 __m128 t3 = _mm_set_ss(float_exp_lookup[v3]);
1002 t1 = _mm_movelh_ps(t1, t3);
1003 t1 = _mm_castsi128_ps(_mm_slli_epi64(_mm_castps_si128(t1), 32));
1004 t0 = _mm_movelh_ps(t0, t2);
1005 t0 = _mm_or_ps(t0, t1);
1006 t0 = _mm_or_ps(t0, _mm_castsi128_ps(u4));
1007 tt = _mm_mul_ps(tt, t0);
1008 return tt;
1009 }
1010
1011 // For equivalent "normal" C/C++ code, see the non-__LP64__ versions of these
1012 // functions.
1013 static inline void logistic_sse(float* vect, uint32_t nn) {
1014 __m128 zero = _mm_setzero_ps();
1015 __m128 one = _mm_set1_ps(1.0);
1016 uint32_t uii;
1017 for (uii = 0; uii < nn; uii += 4) {
1018 __m128 aa = _mm_load_ps(&(vect[uii]));
1019 aa = _mm_sub_ps(zero, aa);
1020 aa = fmath_exp_ps(aa);
1021 aa = _mm_add_ps(aa, one);
1022 aa = _mm_div_ps(one, aa);
1023 _mm_store_ps(&(vect[uii]), aa);
1024 }
1025 }
1026
1027 static inline void compute_v_and_p_minus_y(float* pp, float* vv, const float* yy, uint32_t nn) {
1028 __m128 one = _mm_set1_ps(1.0);
1029 uint32_t uii;
1030 for (uii = 0; uii < nn; uii += 4) {
1031 __m128 ptmp = _mm_load_ps(&(pp[uii]));
1032 __m128 one_minus_ptmp = _mm_sub_ps(one, ptmp);
1033 _mm_store_ps(&(vv[uii]), _mm_mul_ps(ptmp, one_minus_ptmp));
1034 __m128 ytmp = _mm_load_ps(&(yy[uii]));
1035 _mm_store_ps(&(pp[uii]), _mm_sub_ps(ptmp, ytmp));
1036 }
1037 }
1038
1039 static inline void mult_tmatrix_nxd_vect_d(const float* tm, const float* vect, float* dest, uint32_t col_ct, uint32_t row_ct) {
1040 // tm is row-major, cols are packed to 16-byte alignment
1041 // "col_cta4" = col_ct, aligned to multiple of 4. Since 16-byte blocks
1042 // contain 4 floats each, this is the actual length (in floats) of each tm
1043 // row. (Yes, I need to standardize a zillion other variable names of this
1044 // sort...)
1045 __m128 w1;
1046 __m128 w2;
1047 __m128 w3;
1048 __m128 w4;
1049 __m128 r1;
1050 __m128 r2;
1051 __m128 r3;
1052 __m128 r4;
1053 uintptr_t col_cta4 = round_up_pow2(col_ct, 4);
1054 uint32_t row_idx = 0;
1055 uint32_t row_ctm3;
1056 uint32_t col_idx;
1057 if (row_ct < 4) {
1058 memset(dest, 0, col_cta4 * sizeof(float));
1059 } else {
1060 w1 = _mm_load1_ps(vect);
1061 w2 = _mm_load1_ps(&(vect[1]));
1062 w3 = _mm_load1_ps(&(vect[2]));
1063 w4 = _mm_load1_ps(&(vect[3]));
1064 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1065 r1 = _mm_load_ps(&(tm[col_idx]));
1066 r2 = _mm_load_ps(&(tm[col_idx + col_cta4]));
1067 r3 = _mm_load_ps(&(tm[col_idx + 2 * col_cta4]));
1068 r4 = _mm_load_ps(&(tm[col_idx + 3 * col_cta4]));
1069 r1 = _mm_mul_ps(r1, w1);
1070 r2 = _mm_mul_ps(r2, w2);
1071 r3 = _mm_mul_ps(r3, w3);
1072 r4 = _mm_mul_ps(r4, w4);
1073 r1 = _mm_add_ps(r1, r2);
1074 r3 = _mm_add_ps(r3, r4);
1075 r1 = _mm_add_ps(r1, r3);
1076 _mm_store_ps(&(dest[col_idx]), r1);
1077 }
1078 row_ctm3 = row_ct - 3;
1079 for (row_idx = 4; row_idx < row_ctm3; row_idx += 4) {
1080 w1 = _mm_load1_ps(&(vect[row_idx]));
1081 w2 = _mm_load1_ps(&(vect[row_idx + 1]));
1082 w3 = _mm_load1_ps(&(vect[row_idx + 2]));
1083 w4 = _mm_load1_ps(&(vect[row_idx + 3]));
1084 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1085 r1 = _mm_load_ps(&(tm[col_idx + row_idx * col_cta4]));
1086 r2 = _mm_load_ps(&(tm[col_idx + (row_idx + 1) * col_cta4]));
1087 r3 = _mm_load_ps(&(tm[col_idx + (row_idx + 2) * col_cta4]));
1088 r4 = _mm_load_ps(&(tm[col_idx + (row_idx + 3) * col_cta4]));
1089 r1 = _mm_mul_ps(r1, w1);
1090 r2 = _mm_mul_ps(r2, w2);
1091 r3 = _mm_mul_ps(r3, w3);
1092 r4 = _mm_mul_ps(r4, w4);
1093 r1 = _mm_add_ps(r1, r2);
1094 r3 = _mm_add_ps(r3, r4);
1095 r1 = _mm_add_ps(r1, r3);
1096 r1 = _mm_add_ps(r1, _mm_load_ps(&(dest[col_idx])));
1097 _mm_store_ps(&(dest[col_idx]), r1);
1098 }
1099 }
1100 }
1101 switch(row_ct % 4) {
1102 case 3:
1103 w1 = _mm_load1_ps(&(vect[row_idx]));
1104 w2 = _mm_load1_ps(&(vect[row_idx + 1]));
1105 w3 = _mm_load1_ps(&(vect[row_idx + 2]));
1106 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1107 r1 = _mm_load_ps(&(tm[col_idx + row_idx * col_cta4]));
1108 r2 = _mm_load_ps(&(tm[col_idx + (row_idx + 1) * col_cta4]));
1109 r3 = _mm_load_ps(&(tm[col_idx + (row_idx + 2) * col_cta4]));
1110 r1 = _mm_mul_ps(r1, w1);
1111 r2 = _mm_mul_ps(r2, w2);
1112 r3 = _mm_mul_ps(r3, w3);
1113 r1 = _mm_add_ps(r1, r2);
1114 r3 = _mm_add_ps(r3, _mm_load_ps(&(dest[col_idx])));
1115 r1 = _mm_add_ps(r1, r3);
1116 _mm_store_ps(&(dest[col_idx]), r1);
1117 }
1118 break;
1119 case 2:
1120 w1 = _mm_load1_ps(&(vect[row_idx]));
1121 w2 = _mm_load1_ps(&(vect[row_idx + 1]));
1122 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1123 r1 = _mm_load_ps(&(tm[col_idx + row_idx * col_cta4]));
1124 r2 = _mm_load_ps(&(tm[col_idx + (row_idx + 1) * col_cta4]));
1125 r1 = _mm_mul_ps(r1, w1);
1126 r2 = _mm_mul_ps(r2, w2);
1127 r1 = _mm_add_ps(r1, r2);
1128 r1 = _mm_add_ps(r1, _mm_load_ps(&(dest[col_idx])));
1129 _mm_store_ps(&(dest[col_idx]), r1);
1130 }
1131 break;
1132 case 1:
1133 w1 = _mm_load1_ps(&(vect[row_idx]));
1134 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1135 r1 = _mm_load_ps(&(tm[col_idx + row_idx * col_cta4]));
1136 r1 = _mm_mul_ps(r1, w1);
1137 r1 = _mm_add_ps(r1, _mm_load_ps(&(dest[col_idx])));
1138 _mm_store_ps(&(dest[col_idx]), r1);
1139 }
1140 }
1141 }
1142
1143 // N.B. This requires all mm[] rows to be zero-padded at the end, and there
1144 // can't be nan values at the end of vect[]. (The other way around works too.)
1145 static inline void mult_matrix_dxn_vect_n(const float* mm, const float* vect, float* dest, uint32_t col_ct, uint32_t row_ct) {
1146 uintptr_t col_cta4 = round_up_pow2(col_ct, 4);
1147 uint32_t row_idx = 0;
1148 const float* mm_ptr;
1149 __m128 s1;
1150 __m128 s2;
1151 __m128 s3;
1152 __m128 s4;
1153 __m128 vv;
1154 __m128 a1;
1155 __m128 a2;
1156 __m128 a3;
1157 __m128 a4;
1158 __univec uvec;
1159 uint32_t row_ctm3;
1160 uint32_t col_idx;
1161 if (row_ct > 3) {
1162 row_ctm3 = row_ct - 3;
1163 for (; row_idx < row_ctm3; row_idx += 4) {
1164 s1 = _mm_setzero_ps();
1165 s2 = _mm_setzero_ps();
1166 s3 = _mm_setzero_ps();
1167 s4 = _mm_setzero_ps();
1168 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1169 mm_ptr = &(mm[row_idx * col_cta4 + col_idx]);
1170 vv = _mm_load_ps(&(vect[col_idx]));
1171 a1 = _mm_load_ps(mm_ptr);
1172 a2 = _mm_load_ps(&(mm_ptr[col_cta4]));
1173 a3 = _mm_load_ps(&(mm_ptr[2 * col_cta4]));
1174 a4 = _mm_load_ps(&(mm_ptr[3 * col_cta4]));
1175 // want to switch this to fused multiply-add...
1176 a1 = _mm_mul_ps(a1, vv);
1177 a2 = _mm_mul_ps(a2, vv);
1178 a3 = _mm_mul_ps(a3, vv);
1179 a4 = _mm_mul_ps(a4, vv);
1180 s1 = _mm_add_ps(s1, a1);
1181 s2 = _mm_add_ps(s2, a2);
1182 s3 = _mm_add_ps(s3, a3);
1183 s4 = _mm_add_ps(s4, a4);
1184 }
1185 // refrain from using SSE3 _mm_hadd_ps() for now
1186 uvec.vf = s1;
1187 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1188 uvec.vf = s2;
1189 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1190 uvec.vf = s3;
1191 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1192 uvec.vf = s4;
1193 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1194 }
1195 }
1196 s1 = _mm_setzero_ps();
1197 s2 = _mm_setzero_ps();
1198 s3 = _mm_setzero_ps();
1199 switch (row_ct % 4) {
1200 case 3:
1201 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1202 mm_ptr = &(mm[row_idx * col_cta4 + col_idx]);
1203 vv = _mm_load_ps(&(vect[col_idx]));
1204 a1 = _mm_load_ps(mm_ptr);
1205 a2 = _mm_load_ps(&(mm_ptr[col_cta4]));
1206 a3 = _mm_load_ps(&(mm_ptr[2 * col_cta4]));
1207 a1 = _mm_mul_ps(a1, vv);
1208 a2 = _mm_mul_ps(a2, vv);
1209 a3 = _mm_mul_ps(a3, vv);
1210 s1 = _mm_add_ps(s1, a1);
1211 s2 = _mm_add_ps(s2, a2);
1212 s3 = _mm_add_ps(s3, a3);
1213 }
1214 uvec.vf = s1;
1215 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1216 uvec.vf = s2;
1217 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1218 uvec.vf = s3;
1219 *dest = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1220 break;
1221 case 2:
1222 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1223 mm_ptr = &(mm[row_idx * col_cta4 + col_idx]);
1224 vv = _mm_load_ps(&(vect[col_idx]));
1225 a1 = _mm_load_ps(mm_ptr);
1226 a2 = _mm_load_ps(&(mm_ptr[col_cta4]));
1227 a1 = _mm_mul_ps(a1, vv);
1228 a2 = _mm_mul_ps(a2, vv);
1229 s1 = _mm_add_ps(s1, a1);
1230 s2 = _mm_add_ps(s2, a2);
1231 }
1232 uvec.vf = s1;
1233 *dest++ = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1234 uvec.vf = s2;
1235 *dest = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1236 break;
1237 case 1:
1238 for (col_idx = 0; col_idx < col_ct; col_idx += 4) {
1239 vv = _mm_load_ps(&(vect[col_idx]));
1240 a1 = _mm_load_ps(&(mm[row_idx * col_cta4 + col_idx]));
1241 a1 = _mm_mul_ps(a1, vv);
1242 s1 = _mm_add_ps(s1, a1);
1243 }
1244 uvec.vf = s1;
1245 *dest = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1246 break;
1247 }
1248 }
1249
1250 static inline float triple_product(const float* v1, const float* v2, const float* v3, uint32_t nn) {
1251 __m128 sum = _mm_setzero_ps();
1252 __m128 aa;
1253 __m128 bb;
1254 __m128 cc;
1255 __univec uvec;
1256 uint32_t uii;
1257 for (uii = 0; uii < nn; uii += 4) {
1258 aa = _mm_load_ps(&(v1[uii]));
1259 bb = _mm_load_ps(&(v2[uii]));
1260 cc = _mm_load_ps(&(v3[uii]));
1261 sum = _mm_add_ps(sum, _mm_mul_ps(_mm_mul_ps(aa, bb), cc));
1262 }
1263 uvec.vf = sum;
1264 return uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1265 }
1266
1267 static inline void compute_two_diag_triple_product(const float* aa, const float* bb, const float* vv, float* raa_ptr, float* rab_ptr, float* rbb_ptr, uint32_t nn) {
1268 __m128 saa = _mm_setzero_ps();
1269 __m128 sab = _mm_setzero_ps();
1270 __m128 sbb = _mm_setzero_ps();
1271 __m128 vtmp;
1272 __m128 atmp;
1273 __m128 btmp;
1274 __m128 av;
1275 __m128 bv;
1276 __univec uvec;
1277 uint32_t uii;
1278 for (uii = 0; uii < nn; uii += 4) {
1279 vtmp = _mm_load_ps(&(vv[uii]));
1280 atmp = _mm_load_ps(&(aa[uii]));
1281 btmp = _mm_load_ps(&(bb[uii]));
1282 av = _mm_mul_ps(atmp, vtmp);
1283 bv = _mm_mul_ps(btmp, vtmp);
1284 saa = _mm_add_ps(saa, _mm_mul_ps(atmp, av));
1285 sab = _mm_add_ps(sab, _mm_mul_ps(atmp, bv));
1286 sbb = _mm_add_ps(sbb, _mm_mul_ps(btmp, bv));
1287 }
1288 uvec.vf = saa;
1289 *raa_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1290 uvec.vf = sab;
1291 *rab_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1292 uvec.vf = sbb;
1293 *rbb_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1294 }
1295
1296 static inline void compute_three_triple_product(const float* bb, const float* a1, const float* a2, const float* a3, const float* vv, float* r1_ptr, float* r2_ptr, float* r3_ptr, uint32_t nn) {
1297 __m128 s1 = _mm_setzero_ps();
1298 __m128 s2 = _mm_setzero_ps();
1299 __m128 s3 = _mm_setzero_ps();
1300 __m128 a1tmp;
1301 __m128 a2tmp;
1302 __m128 a3tmp;
1303 __m128 vtmp;
1304 __m128 btmp;
1305 __univec uvec;
1306 uint32_t uii;
1307 for (uii = 0; uii < nn; uii += 4) {
1308 a1tmp = _mm_load_ps(&(a1[uii]));
1309 a2tmp = _mm_load_ps(&(a2[uii]));
1310 a3tmp = _mm_load_ps(&(a3[uii]));
1311 vtmp = _mm_load_ps(&(vv[uii]));
1312 btmp = _mm_load_ps(&(bb[uii]));
1313 btmp = _mm_mul_ps(btmp, vtmp);
1314 s1 = _mm_add_ps(s1, _mm_mul_ps(a1tmp, btmp));
1315 s2 = _mm_add_ps(s2, _mm_mul_ps(a2tmp, btmp));
1316 s3 = _mm_add_ps(s3, _mm_mul_ps(a3tmp, btmp));
1317 }
1318 uvec.vf = s1;
1319 *r1_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1320 uvec.vf = s2;
1321 *r2_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1322 uvec.vf = s3;
1323 *r3_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1324 }
1325
1326 static inline void compute_two_plus_one_triple_product(const float* bb, const float* a1, const float* a2, const float* vv, float* r1_ptr, float* r2_ptr, float* r3_ptr, uint32_t nn) {
1327 __m128 s1 = _mm_setzero_ps();
1328 __m128 s2 = _mm_setzero_ps();
1329 __m128 s3 = _mm_setzero_ps();
1330 __m128 a1tmp;
1331 __m128 a2tmp;
1332 __m128 btmp;
1333 __m128 vtmp;
1334 __m128 bv;
1335 __univec uvec;
1336 uint32_t uii;
1337 for (uii = 0; uii < nn; uii += 4) {
1338 a1tmp = _mm_load_ps(&(a1[uii]));
1339 a2tmp = _mm_load_ps(&(a2[uii]));
1340 btmp = _mm_load_ps(&(bb[uii]));
1341 vtmp = _mm_load_ps(&(vv[uii]));
1342 bv = _mm_mul_ps(btmp, vtmp);
1343 s1 = _mm_add_ps(s1, _mm_mul_ps(btmp, bv));
1344 s2 = _mm_add_ps(s2, _mm_mul_ps(a1tmp, bv));
1345 s3 = _mm_add_ps(s3, _mm_mul_ps(a2tmp, bv));
1346 }
1347 uvec.vf = s1;
1348 *r1_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1349 uvec.vf = s2;
1350 *r2_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1351 uvec.vf = s3;
1352 *r3_ptr = uvec.f4[0] + uvec.f4[1] + uvec.f4[2] + uvec.f4[3];
1353 }
1354 #else // no __LP64__ (and hence, unsafe to assume presence of SSE2)
1355 static inline void logistic_sse(float* vect, uint32_t nn) {
1356 uint32_t uii;
1357 for (uii = 0; uii < nn; uii++) {
1358 vect[uii] = 1.0 / (1 + exp(-vect[uii]));
1359 }
1360 }
1361
1362 static inline void compute_v_and_p_minus_y(float* pp, float* vv, const float* yy, uint32_t nn) {
1363 uint32_t uii;
1364 for (uii = 0; uii < nn; uii++) {
1365 vv[uii] = pp[uii] * (1.0 - pp[uii]);
1366 pp[uii] -= yy[uii];
1367 }
1368 }
1369
1370 static inline void mult_tmatrix_nxd_vect_d(const float* tm, const float* vect, float* dest, uint32_t col_ct, uint32_t row_ct) {
1371 uintptr_t col_cta4 = round_up_pow2(col_ct, 4);
1372 const float* tm_ptr;
1373 float vect_val;
1374 uint32_t col_idx;
1375 uint32_t row_idx;
1376 fill_float_zero(col_ct, dest);
1377 for (row_idx = 0; row_idx < row_ct; row_idx++) {
1378 vect_val = vect[row_idx];
1379 tm_ptr = &(tm[row_idx * col_cta4]);
1380 for (col_idx = 0; col_idx < col_ct; col_idx++) {
1381 dest[col_idx] += (*tm_ptr++) * vect_val;
1382 }
1383 }
1384 }
1385
1386 static inline void mult_matrix_dxn_vect_n(const float* mm, const float* vect, float* dest, uint32_t col_ct, uint32_t row_ct) {
1387 uintptr_t col_cta4 = round_up_pow2(col_ct, 4);
1388 const float* mm_ptr;
1389 const float* vect_ptr;
1390 uint32_t row_idx;
1391 uint32_t col_idx;
1392 float fxx;
1393 for (row_idx = 0; row_idx < row_ct; row_idx++) {
1394 fxx = 0.0;
1395 vect_ptr = vect;
1396 mm_ptr = &(mm[row_idx * col_cta4]);
1397 for (col_idx = 0; col_idx < col_ct; col_idx++) {
1398 fxx += (*mm_ptr++) * (*vect_ptr++);
1399 }
1400 *dest++ = fxx;
1401 }
1402 }
1403
1404 static inline float triple_product(const float* v1, const float* v2, const float* v3, uint32_t nn) {
1405 float fxx = 0.0;
1406 uint32_t uii;
1407 for (uii = 0; uii < nn; uii++) {
1408 fxx += (*v1++) * (*v2++) * (*v3++);
1409 }
1410 return fxx;
1411 }
1412
1413 static inline void compute_two_diag_triple_product(const float* aa, const float* bb, const float* vv, float* raa_ptr, float* rab_ptr, float* rbb_ptr, uint32_t nn) {
1414 float raa = 0.0;
1415 float rab = 0.0;
1416 float rbb = 0.0;
1417 uint32_t uii;
1418 float fxx;
1419 float fyy;
1420 float fzz;
1421 for (uii = 0; uii < nn; uii++) {
1422 fxx = (*aa++);
1423 fyy = (*bb++);
1424 fzz = (*vv++);
1425 raa += fxx * fxx * fzz;
1426 fzz *= fyy;
1427 rab += fxx * fzz;
1428 rbb += fyy * fzz;
1429 }
1430 *raa_ptr = raa;
1431 *rab_ptr = rab;
1432 *rbb_ptr = rbb;
1433 }
1434
1435 static inline void compute_three_triple_product(const float* bb, const float* a1, const float* a2, const float* a3, const float* vv, float* r1_ptr, float* r2_ptr, float* r3_ptr, uint32_t nn) {
1436 float r1 = 0.0;
1437 float r2 = 0.0;
1438 float r3 = 0.0;
1439 uint32_t uii;
1440 float fxx;
1441 for (uii = 0; uii < nn; uii++) {
1442 fxx = (*bb++) * (*vv++);
1443 r1 += (*a1++) * fxx;
1444 r2 += (*a2++) * fxx;
1445 r3 += (*a3++) * fxx;
1446 }
1447 *r1_ptr = r1;
1448 *r2_ptr = r2;
1449 *r3_ptr = r3;
1450 }
1451
1452 static inline void compute_two_plus_one_triple_product(const float* bb, const float* a1, const float* a2, const float* vv, float* r1_ptr, float* r2_ptr, float* r3_ptr, uint32_t nn) {
1453 float r1 = 0.0;
1454 float r2 = 0.0;
1455 float r3 = 0.0;
1456 uint32_t uii;
1457 float fxx;
1458 float fyy;
1459 for (uii = 0; uii < nn; uii++) {
1460 fxx = (*bb++);
1461 fyy = fxx * (*vv++);
1462 r1 += fxx * fyy;
1463 r2 += (*a1++) * fyy;
1464 r3 += (*a2++) * fyy;
1465 }
1466 *r1_ptr = r1;
1467 *r2_ptr = r2;
1468 *r3_ptr = r3;
1469 }
1470 #endif
1471
1472 static inline void compute_hessian(const float* mm, const float* vv, float* dest, uint32_t col_ct, uint32_t row_ct) {
1473 uintptr_t col_cta4 = round_up_pow2(col_ct, 4);
1474 uintptr_t row_cta4 = round_up_pow2(row_ct, 4);
1475 uintptr_t row_cta4p1 = row_cta4 + 1;
1476 const float* mm_cur;
1477 uint32_t row_ctm3;
1478 uint32_t row_idx;
1479 uint32_t row_idx2;
1480 if (row_ct > 3) {
1481 row_ctm3 = row_ct - 3;
1482 for (row_idx = 0; row_idx < row_ctm3; row_idx += 3) {
1483 mm_cur = &(mm[row_idx * col_cta4]);
1484 compute_two_diag_triple_product(mm_cur, &(mm_cur[col_cta4]), vv, &(dest[row_idx * row_cta4p1]), &(dest[(row_idx + 1) * row_cta4p1 - 1]), &(dest[(row_idx + 1) * row_cta4p1]), col_ct);
1485 compute_two_plus_one_triple_product(&(mm_cur[2 * col_cta4]), &(mm_cur[col_cta4]), mm_cur, vv, &(dest[(row_idx + 2) * row_cta4p1]), &(dest[(row_idx + 2) * row_cta4p1 - 1]), &(dest[(row_idx + 2) * row_cta4p1 - 2]), col_ct);
1486 for (row_idx2 = row_idx + 3; row_idx2 < row_ct; row_idx2++) {
1487 compute_three_triple_product(&(mm[row_idx2 * col_cta4]), mm_cur, &(mm_cur[col_cta4]), &(mm_cur[2 * col_cta4]), vv, &(dest[row_idx2 * row_cta4 + row_idx]), &(dest[row_idx2 * row_cta4 + row_idx + 1]), &(dest[row_idx2 * row_cta4 + row_idx + 2]), col_ct);
1488 }
1489 }
1490 }
1491 switch (row_ct % 3) {
1492 case 0:
1493 compute_two_plus_one_triple_product(&(mm[(row_ct - 3) * col_cta4]), &(mm[(row_ct - 2) * col_cta4]), &(mm[(row_ct - 1) * col_cta4]), vv, &(dest[(row_ct - 3) * row_cta4p1]), &(dest[(row_ct - 2) * row_cta4p1 - 1]), &(dest[(row_ct - 1) * row_cta4p1 - 2]), col_ct);
1494 // fall through
1495 case 2:
1496 compute_two_diag_triple_product(&(mm[(row_ct - 2) * col_cta4]), &(mm[(row_ct - 1) * col_cta4]), vv, &(dest[(row_ct - 2) * row_cta4p1]), &(dest[(row_ct - 1) * row_cta4p1 - 1]), &(dest[(row_ct - 1) * row_cta4p1]), col_ct);
1497 break;
1498 case 1:
1499 dest[(row_ct - 1) * row_cta4p1] = triple_product(&(mm[(row_ct - 1) * col_cta4]), &(mm[(row_ct - 1) * col_cta4]), vv, col_ct);
1500 }
1501 }
1502
1503 void solve_linear_system(const float* ll, const float* yy, float* xx, uint32_t dd) {
1504 // might want to use this in NOLAPACK case only, since we can now produce
1505 // 32-bit Linux builds with statically linked LAPACK
1506 uintptr_t dim_cta4 = round_up_pow2(dd, 4);
1507 const float* ll_ptr;
1508 float* xx_ptr;
1509 uint32_t row_idx;
1510 uint32_t col_idx;
1511 float fxx;
1512 for (row_idx = 0; row_idx < dd; row_idx++) {
1513 fxx = yy[row_idx];
1514 ll_ptr = &(ll[row_idx * dim_cta4]);
1515 xx_ptr = xx;
1516 for (col_idx = 0; col_idx < row_idx; col_idx++) {
1517 fxx -= (*ll_ptr++) * (*xx_ptr++);
1518 }
1519 *xx_ptr = fxx / (*ll_ptr);
1520 }
1521 for (col_idx = dd; col_idx;) {
1522 fxx = xx[--col_idx];
1523 xx_ptr = &(xx[dd - 1]);
1524 for (row_idx = dd - 1; row_idx > col_idx; row_idx--) {
1525 fxx -= ll[row_idx * dim_cta4 + col_idx] * (*xx_ptr--);
1526 }
1527 *xx_ptr = fxx / ll[row_idx * (dim_cta4 + 1)];
1528 }
1529 }
1530
1531 float compute_wald(const float* ll, uint32_t dd, float* xbuf) {
1532 uintptr_t dim_cta4 = round_up_pow2(dd, 4);
1533 uint32_t row_idx = 0;
1534 const float* ll_ptr;
1535 float* xbuf_ptr;
1536 uint32_t col_idx;
1537 float fxx;
1538 float fyy;
1539 while (1) {
1540 fxx = 0.0;
1541 ll_ptr = &(ll[row_idx * dim_cta4]);
1542 xbuf_ptr = xbuf;
1543 for (col_idx = 0; col_idx < row_idx; col_idx++) {
1544 fxx -= (*ll_ptr++) * (*xbuf_ptr++);
1545 }
1546 if (++row_idx == dd) {
1547 fyy = (*ll_ptr);
1548 return (fxx + 1.0) / (fyy * fyy);
1549 }
1550 *xbuf_ptr = fxx / (*ll_ptr);
1551 }
1552 }
1553
1554 void cholesky_decomposition(const float* aa, float* ll, uint32_t dd) {
1555 uintptr_t dim_cta4 = round_up_pow2(dd, 4);
1556 uintptr_t dim_cta4p1 = dim_cta4 + 1;
1557 float* ll_ptr;
1558 float* ll_ptr2;
1559 uint32_t row_idx;
1560 uint32_t row_idx2;
1561 uint32_t col_idx;
1562 float fxx;
1563 float fyy;
1564 for (row_idx = 0; row_idx < dd; row_idx++) {
1565 fxx = aa[row_idx * dim_cta4p1];
1566 ll_ptr = &(ll[row_idx * dim_cta4]);
1567 for (col_idx = 0; col_idx < row_idx; col_idx++) {
1568 fyy = (*ll_ptr++);
1569 fxx -= fyy * fyy;
1570 }
1571 if (fxx >= 0.0) {
1572 fyy = sqrt(fxx);
1573 } else {
1574 fyy = 1e-6;
1575 }
1576 ll[row_idx * dim_cta4p1] = fyy;
1577 fyy = 1.0 / fyy; // now 1.0 / L[j][j]
1578 for (row_idx2 = row_idx + 1; row_idx2 < dd; row_idx2++) {
1579 fxx = aa[row_idx2 * dim_cta4 + row_idx];
1580 ll_ptr = &(ll[row_idx * dim_cta4]);
1581 ll_ptr2 = &(ll[row_idx2 * dim_cta4]);
1582 for (col_idx = 0; col_idx < row_idx; col_idx++) {
1583 fxx -= (*ll_ptr++) * (*ll_ptr2++);
1584 }
1585 ll[row_idx2 * dim_cta4 + row_idx] = fxx * fyy;
1586 }
1587 }
1588 }
1589
1590 uint32_t logistic_regression(uint32_t sample_ct, uint32_t param_ct, float* vv, float* hh, float* grad, float* ll, float* dcoef, const float* xx, const float* yy, float* coef, float* pp) {
1591 // Similar to first part of logistic.cpp fitLM(), but incorporates changes
1592 // from Pascal Pons et al.'s TopCoder code.
1593 //
1594 // Preallocated buffers (initial contents irrelevant):
1595 // vv = sample variance buffer
1596 // hh = hessian matrix buffer, param_ct x param_ct, rows 16-byte aligned
1597 // grad = gradient buffer (length param_ct)
1598 // ll = linear system buffer, param_ct x param_ct, rows 16-byte aligned
1599 // dcoef = current coefficient change buffer (length param_ct)
1600 //
1601 // Inputs:
1602 // xx = covariate (and usually genotype) matrix, covariate-major, rows are
1603 // 16-byte aligned, trailing row elements must be zeroed out
1604 // yy = case/control phenotype; trailing elements must be zeroed out
1605 //
1606 // Input/output:
1607 // coef = starting point, overwritten with logistic regression result. Must
1608 // be 16-byte aligned.
1609 //
1610 // Output:
1611 // pp = final likelihoods minus Y[]
1612 //
1613 // Returns 0 on success, 1 on convergence failure.
1614 uintptr_t param_cta4 = round_up_pow2(param_ct, 4);
1615 uint32_t iteration = 0;
1616 float min_delta_coef = 1e9;
1617 float delta_coef;
1618 float fxx;
1619 uint32_t param_idx;
1620
1621 fill_float_zero(param_ct * param_cta4, ll);
1622 while (1) {
1623 iteration++;
1624
1625 // P[i] = \sum_j coef[j] * X[i][j];
1626 mult_tmatrix_nxd_vect_d(xx, coef, pp, sample_ct, param_ct);
1627
1628 // P[i] = 1 / (1 + exp(-P[i]));
1629 logistic_sse(pp, sample_ct);
1630
1631 // V[i] = P[i] * (1 - P[i]);
1632 // P[i] -= Y[i];
1633 compute_v_and_p_minus_y(pp, vv, yy, sample_ct);
1634
1635 compute_hessian(xx, vv, hh, sample_ct, param_ct);
1636
1637 mult_matrix_dxn_vect_n(xx, pp, grad, sample_ct, param_ct);
1638
1639 cholesky_decomposition(hh, ll, param_ct);
1640
1641 fill_float_zero(param_ct, dcoef);
1642 solve_linear_system(ll, grad, dcoef, param_ct);
1643
1644 delta_coef = 0.0;
1645 for (param_idx = 0; param_idx < param_ct; param_idx++) {
1646 fxx = dcoef[param_idx];
1647 delta_coef += fabsf(fxx);
1648 coef[param_idx] -= fxx;
1649 }
1650 if (delta_coef < min_delta_coef) {
1651 min_delta_coef = delta_coef;
1652 }
1653 if (delta_coef != delta_coef) {
1654 return 1;
1655 }
1656 if (iteration > 4) {
1657 if (((delta_coef > 20.0) && (delta_coef > 2 * min_delta_coef)) || ((iteration >= 8) && fabsf(1.0f - delta_coef) < 1e-3)) {
1658 return 1;
1659 }
1660 if (iteration >= 15) {
1661 // quasi-bugfix (11 Sep 2018): if fabsf(any coefficient) > 8e3, this is
1662 // almost certainly a form of convergence failure that didn't get
1663 // caught by the (delta_coef > 20.0) check due to a precision quirk.
1664 // (8e3 threshold ~= 1e-4 * 2^23, since floats have 23 bits of
1665 // precision)
1666 for (param_idx = 0; param_idx < param_ct; param_idx++) {
1667 if (fabsf(coef[param_idx]) > 8e3) {
1668 return 1;
1669 }
1670 }
1671 return 0;
1672 }
1673 }
1674 // Pons reported that 1.1e-3 was dangerous, so I agree with the decision to
1675 // tighten this threshold from 1e-3 to 1e-4.
1676 if (delta_coef < 1e-4) {
1677 // Be more conservative in throwing out results when we don't hit the
1678 // iteration limit.
1679 for (param_idx = 0; param_idx < param_ct; param_idx++) {
1680 if (fabsf(coef[param_idx]) > 6e4) {
1681 return 1;
1682 }
1683 }
1684 return 0;
1685 }
1686 }
1687 }
1688
1689 uint32_t glm_logistic(uintptr_t cur_batch_size, uintptr_t param_ct, uintptr_t sample_valid_ct, uint32_t missing_ct, uint32_t skip_intercept, uintptr_t* loadbuf, float* covars_cov_major, uintptr_t* perm_vecs, float* coef, float* pp, float* sample_1d_buf, float* pheno_buf, float* param_1d_buf, float* param_1d_buf2, float* param_2d_buf, float* param_2d_buf2, float* logistic_results, uintptr_t constraint_ct, double* constraints_con_major, double* param_1d_dbuf, double* param_2d_dbuf, double* param_2d_dbuf2, double* param_df_dbuf, double* df_df_dbuf, MATRIX_INVERT_BUF1_TYPE* mi_buf, double* df_dbuf, uintptr_t* perm_fails) {
1690 // Similar to logistic.cpp fitLM(), but incorporates changes from the
1691 // postprocessed TopCoder contest code.
1692 // * coef is now assumed to be initialized with a good starting point for
1693 // each permutation. The initializer must remove columns corresponding to
1694 // missing genotypes. (Todo: figure out when/whether we actually want to
1695 // take advantage of this with a nonzero starting point. If we do, we'll
1696 // also need to add restart logic.)
1697 // * covars_cov_major must now have 16-byte aligned rows.
1698 // Returns number of regression failures.
1699 uintptr_t param_cta4 = round_up_pow2(param_ct, 4);
1700 uintptr_t param_ct_p1 = param_ct + 1;
1701 uintptr_t param_ct_msi = param_ct - skip_intercept;
1702 uintptr_t joint_test_requested = (constraints_con_major? 1 : 0);
1703 uintptr_t param_ctx = param_ct + joint_test_requested;
1704 uintptr_t param_ctx_msi = param_ctx - skip_intercept;
1705 uintptr_t sample_validx_ctaw = BITCT_TO_ALIGNED_WORDCT(sample_valid_ct + missing_ct);
1706 uintptr_t perm_fail_ct = 0;
1707 uintptr_t cur_word = 0;
1708 uintptr_t perm_idx;
1709 uintptr_t sample_uidx;
1710 uintptr_t sample_idx;
1711 uintptr_t param_idx;
1712 uintptr_t param_idx2;
1713 float* fptr;
1714 float* fptr2;
1715 double dxx;
1716 float fxx;
1717 fill_ulong_zero(BITCT_TO_WORDCT(cur_batch_size), perm_fails);
1718 for (perm_idx = 0; perm_idx < cur_batch_size; perm_idx++) {
1719 fptr = pheno_buf;
1720 if (!missing_ct) {
1721 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
1722 *fptr++ = (float)((int32_t)is_set_ul(perm_vecs, sample_idx));
1723 }
1724 } else {
1725 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
1726 while (1) {
1727 if (sample_uidx % BITCT2) {
1728 cur_word >>= 2;
1729 } else {
1730 cur_word = loadbuf[sample_uidx / BITCT2];
1731 cur_word = cur_word & (~(cur_word >> 1)) & FIVEMASK;
1732 }
1733 if (!(cur_word & 1)) {
1734 break;
1735 }
1736 sample_uidx++;
1737 }
1738 *fptr++ = (float)((int32_t)is_set_ul(perm_vecs, sample_uidx));
1739 }
1740 }
1741 // bugfix (13 Oct 2017): must guarantee trailing phenotype values are valid
1742 // (exact contents don't matter since they are multipled by zero, but they
1743 // can't be nan)
1744 const uint32_t trail_ct = (-sample_valid_ct) & 3;
1745 fill_float_zero(trail_ct, fptr);
1746 if (logistic_regression(sample_valid_ct, param_ct, sample_1d_buf, param_2d_buf, param_1d_buf, param_2d_buf2, param_1d_buf2, covars_cov_major, pheno_buf, coef, pp)) {
1747 goto glm_logistic_fail;
1748 }
1749
1750 // compute S
1751 // param_2d_buf = S, param_1d_buf = y, param_1d_buf2 = x
1752 for (param_idx = 0; param_idx < param_ct; param_idx++) {
1753 fill_float_zero(param_ct, param_1d_buf);
1754 param_1d_buf[param_idx] = 1.0;
1755 solve_linear_system(param_2d_buf2, param_1d_buf, param_1d_buf2, param_ct);
1756 // S does *not* currently have 16-byte aligned rows
1757 memcpy(&(param_2d_buf[param_idx * param_ct]), param_1d_buf2, param_ct * sizeof(float));
1758 }
1759
1760 // validParameters() check
1761 for (param_idx = 1; param_idx < param_ct; param_idx++) {
1762 fxx = param_2d_buf[param_idx * param_ct_p1];
1763 if ((fxx < 1e-20) || (!realnum(fxx))) {
1764 goto glm_logistic_fail;
1765 }
1766 param_2d_buf2[param_idx] = sqrtf(fxx);
1767 }
1768 param_2d_buf2[0] = sqrtf(param_2d_buf[0]);
1769 for (param_idx = 1; param_idx < param_ct; param_idx++) {
1770 fxx = 0.99999 * param_2d_buf2[param_idx];
1771 fptr = &(param_2d_buf[param_idx * param_ct]);
1772 fptr2 = param_2d_buf2;
1773 for (param_idx2 = 0; param_idx2 < param_idx; param_idx2++) {
1774 if ((*fptr++) > fxx * (*fptr2++)) {
1775 goto glm_logistic_fail;
1776 }
1777 }
1778 }
1779 fptr = &(logistic_results[perm_idx * param_ctx_msi]);
1780 for (param_idx = skip_intercept; param_idx < param_ct; param_idx++) {
1781 *fptr++ = param_2d_buf[param_idx * param_ct_p1];
1782 }
1783 if (joint_test_requested) {
1784 // ugly to do this with doubles while doing everything else with floats,
1785 // but unless I need to write a float matrix inversion later for some
1786 // other reason, it's probably still the least-bad approach
1787 if (!constraint_ct) {
1788 *fptr++ = -9;
1789 } else {
1790 for (param_idx = 0; param_idx < param_ct; param_idx++) {
1791 param_1d_dbuf[param_idx] = (double)coef[param_idx];
1792 }
1793 param_idx2 = param_ct * param_ct;
1794 for (param_idx = 0; param_idx < param_idx2; param_idx++) {
1795 param_2d_dbuf[param_idx] = (double)(param_2d_buf[param_idx]);
1796 }
1797 if (!linear_hypothesis_chisq(constraint_ct, param_ct, constraints_con_major, param_1d_dbuf, param_2d_dbuf, param_2d_dbuf2, param_df_dbuf, df_df_dbuf, mi_buf, df_dbuf, &dxx)) {
1798 *fptr++ = (float)dxx;
1799 } else {
1800 *fptr++ = -9;
1801 }
1802 }
1803 }
1804 if (0) {
1805 glm_logistic_fail:
1806 fill_float_zero(param_ct_msi, &(logistic_results[perm_idx * param_ctx_msi]));
1807 SET_BIT(perm_idx, perm_fails);
1808 perm_fail_ct++;
1809 if (joint_test_requested) {
1810 logistic_results[perm_idx * param_ctx_msi + param_ct_msi] = -9;
1811 }
1812 }
1813 coef = &(coef[param_cta4]);
1814 perm_vecs = &(perm_vecs[sample_validx_ctaw]);
1815 }
1816 return perm_fail_ct;
1817 }
1818
1819 uint32_t glm_fill_design(uintptr_t* loadbuf_collapsed, double* fixed_covars_cov_major, uintptr_t sample_valid_ct, uint32_t cur_param_ct, uint32_t coding_flags, uintptr_t condition_list_start_idx, uintptr_t interaction_start_idx, uintptr_t sex_start_idx, uintptr_t* active_params, uintptr_t* haploid_params, uint32_t include_sex, uint32_t male_x_01, uintptr_t* sex_male_collapsed, uint32_t is_nonx_haploid, double* cur_covars_cov_major, double* cur_covars_sample_major, uint32_t standard_beta) {
1820 double* dptr = cur_covars_cov_major;
1821 uintptr_t* ulptr_end_init = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
1822 uintptr_t fixed_covar_nonsex_ct = interaction_start_idx - condition_list_start_idx;
1823 uintptr_t interactions_present = sex_start_idx - interaction_start_idx;
1824 uint32_t genotypic_or_hethom = condition_list_start_idx - 2;
1825 uint32_t missing_ct = 0;
1826 double* dptr2;
1827 uintptr_t* ulptr;
1828 uintptr_t* ulptr_end;
1829 uintptr_t fixed_covar_idx;
1830 uintptr_t cur_sample_valid_ct;
1831 uintptr_t sample_idx;
1832 uintptr_t sample_idx_stop;
1833 uintptr_t cur_word;
1834 uintptr_t cur_genotype;
1835 uintptr_t param_idx;
1836 double dxx;
1837 double dyy;
1838 double dzz;
1839 // don't need to recompute this during permutations, but it's so cheap that
1840 // it hardly matters
1841 missing_ct = count_01(loadbuf_collapsed, QUATERCT_TO_WORDCT(sample_valid_ct));
1842 if (missing_ct >= sample_valid_ct - 1) {
1843 // regression will be skipped in this case
1844 return missing_ct;
1845 }
1846 cur_sample_valid_ct = sample_valid_ct - missing_ct;
1847 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
1848 *dptr++ = 1;
1849 }
1850 if (IS_SET(active_params, 1)) {
1851 ulptr = loadbuf_collapsed;
1852 ulptr_end = ulptr_end_init;
1853 sample_idx = 0;
1854 sample_idx_stop = BITCT2;
1855 if (coding_flags & GLM_DOMINANT) {
1856 while (1) {
1857 while (ulptr < ulptr_end) {
1858 cur_word = *ulptr++;
1859 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1860 cur_genotype = cur_word & 3;
1861 if (cur_genotype != 1) {
1862 // 0/1/1, i.e.
1863 // 3 = hom A2 -> 0
1864 // 2 = het -> 1
1865 // 0 = hom A1 -> 1
1866
1867 // Alexandrescu states that non-branching comparisons are
1868 // actually *lower*-strength than arithmetic operations, so I'll
1869 // try this...
1870 *dptr++ = (double)(cur_genotype != 3);
1871 }
1872 }
1873 sample_idx_stop += BITCT2;
1874 }
1875 if (sample_idx == sample_valid_ct) {
1876 break;
1877 }
1878 ulptr_end++;
1879 sample_idx_stop = sample_valid_ct;
1880 }
1881 } else if ((!(coding_flags & (GLM_HETHOM | GLM_RECESSIVE))) && (!is_nonx_haploid)) {
1882 if (!male_x_01) {
1883 while (1) {
1884 while (ulptr < ulptr_end) {
1885 cur_word = *ulptr++;
1886 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1887 cur_genotype = cur_word & 3;
1888 if (cur_genotype != 1) {
1889 // 0/1/2, i.e.
1890 // 3 = hom A2 -> 0
1891 // 2 = het -> 1
1892 // 0 = hom A1 -> 2
1893 *dptr++ = (double)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype));
1894 }
1895 }
1896 sample_idx_stop += BITCT2;
1897 }
1898 if (sample_idx == sample_valid_ct) {
1899 break;
1900 }
1901 ulptr_end++;
1902 sample_idx_stop = sample_valid_ct;
1903 }
1904 } else {
1905 while (1) {
1906 while (ulptr < ulptr_end) {
1907 cur_word = *ulptr++;
1908 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1909 cur_genotype = cur_word & 3;
1910 if (cur_genotype != 1) {
1911 // 0/1/2, but downshifted for males
1912 *dptr++ = (double)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)));
1913 }
1914 }
1915 sample_idx_stop += BITCT2;
1916 }
1917 if (sample_idx == sample_valid_ct) {
1918 break;
1919 }
1920 ulptr_end++;
1921 sample_idx_stop = sample_valid_ct;
1922 }
1923 }
1924 } else {
1925 while (1) {
1926 while (ulptr < ulptr_end) {
1927 cur_word = *ulptr++;
1928 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1929 cur_genotype = cur_word & 3;
1930 if (cur_genotype != 1) {
1931 // 0/0/1
1932 *dptr++ = (double)(cur_genotype == 0);
1933 }
1934 }
1935 sample_idx_stop += BITCT2;
1936 }
1937 if (sample_idx == sample_valid_ct) {
1938 break;
1939 }
1940 ulptr_end++;
1941 sample_idx_stop = sample_valid_ct;
1942 }
1943 }
1944 }
1945 if (genotypic_or_hethom && (!is_nonx_haploid) && IS_SET(active_params, 2)) {
1946 ulptr = loadbuf_collapsed;
1947 ulptr_end = ulptr_end_init;
1948 sample_idx = 0;
1949 sample_idx_stop = BITCT2;
1950 while (1) {
1951 while (ulptr < ulptr_end) {
1952 cur_word = *ulptr++;
1953 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1954 cur_genotype = cur_word & 3;
1955 if (cur_genotype != 1) {
1956 // 0/1/0
1957 *dptr++ = (double)(cur_genotype == 2);
1958 }
1959 }
1960 sample_idx_stop += BITCT2;
1961 }
1962 if (sample_idx == sample_valid_ct) {
1963 break;
1964 }
1965 ulptr_end++;
1966 sample_idx_stop = sample_valid_ct;
1967 }
1968 }
1969 for (fixed_covar_idx = 0; fixed_covar_idx < fixed_covar_nonsex_ct; fixed_covar_idx++) {
1970 if (!is_set(active_params, fixed_covar_idx + condition_list_start_idx)) {
1971 continue;
1972 }
1973 copy_when_nonmissing(loadbuf_collapsed, (char*)(&(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct])), sizeof(double), sample_valid_ct, missing_ct, (char*)dptr);
1974 dptr = &(dptr[cur_sample_valid_ct]);
1975 }
1976 if (interactions_present) {
1977 param_idx = interaction_start_idx;
1978 for (fixed_covar_idx = 0; fixed_covar_idx < fixed_covar_nonsex_ct; fixed_covar_idx++, param_idx++) {
1979 if (IS_SET(active_params, param_idx)) {
1980 ulptr = loadbuf_collapsed;
1981 ulptr_end = ulptr_end_init;
1982 sample_idx = 0;
1983 sample_idx_stop = BITCT2;
1984 dptr2 = &(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct]);
1985 if (coding_flags & GLM_DOMINANT) {
1986 while (1) {
1987 while (ulptr < ulptr_end) {
1988 cur_word = *ulptr++;
1989 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
1990 cur_genotype = cur_word & 3;
1991 if (cur_genotype != 1) {
1992 // 0/1/1
1993 *dptr++ = ((double)(cur_genotype != 3)) * (*dptr2);
1994 }
1995 dptr2++;
1996 }
1997 sample_idx_stop += BITCT2;
1998 }
1999 if (sample_idx == sample_valid_ct) {
2000 break;
2001 }
2002 ulptr_end++;
2003 sample_idx_stop = sample_valid_ct;
2004 }
2005 } else if (!(coding_flags & (GLM_HETHOM | GLM_RECESSIVE))) {
2006 if (!male_x_01) {
2007 while (1) {
2008 while (ulptr < ulptr_end) {
2009 cur_word = *ulptr++;
2010 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2011 cur_genotype = cur_word & 3;
2012 if (cur_genotype != 1) {
2013 // 0/1/2
2014 *dptr++ = ((double)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype))) * (*dptr2);
2015 }
2016 dptr2++;
2017 }
2018 sample_idx_stop += BITCT2;
2019 }
2020 if (sample_idx == sample_valid_ct) {
2021 break;
2022 }
2023 ulptr_end++;
2024 sample_idx_stop = sample_valid_ct;
2025 }
2026 } else {
2027 while (1) {
2028 while (ulptr < ulptr_end) {
2029 cur_word = *ulptr++;
2030 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2031 cur_genotype = cur_word & 3;
2032 if (cur_genotype != 1) {
2033 // 0/1/2
2034 *dptr++ = ((double)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)))) * (*dptr2);
2035 }
2036 dptr2++;
2037 }
2038 sample_idx_stop += BITCT2;
2039 }
2040 if (sample_idx == sample_valid_ct) {
2041 break;
2042 }
2043 ulptr_end++;
2044 sample_idx_stop = sample_valid_ct;
2045 }
2046 }
2047 } else {
2048 while (1) {
2049 while (ulptr < ulptr_end) {
2050 cur_word = *ulptr++;
2051 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2052 cur_genotype = cur_word & 3;
2053 if (cur_genotype != 1) {
2054 // 0/0/1
2055 *dptr++ = ((double)(cur_genotype == 0)) * (*dptr2);
2056 }
2057 dptr2++;
2058 }
2059 sample_idx_stop += BITCT2;
2060 }
2061 if (sample_idx == sample_valid_ct) {
2062 break;
2063 }
2064 ulptr_end++;
2065 sample_idx_stop = sample_valid_ct;
2066 }
2067 }
2068 }
2069 if (genotypic_or_hethom) {
2070 param_idx++;
2071 if ((!is_nonx_haploid) && IS_SET(active_params, param_idx)) {
2072 ulptr = loadbuf_collapsed;
2073 ulptr_end = ulptr_end_init;
2074 sample_idx = 0;
2075 sample_idx_stop = BITCT2;
2076 dptr2 = &(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct]);
2077 while (1) {
2078 while (ulptr < ulptr_end) {
2079 cur_word = *ulptr++;
2080 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2081 cur_genotype = cur_word & 3;
2082 if (cur_genotype != 1) {
2083 // 0/1/0
2084 *dptr++ = ((double)(cur_genotype == 2)) * (*dptr2);
2085 }
2086 dptr2++;
2087 }
2088 sample_idx_stop += BITCT2;
2089 }
2090 if (sample_idx == sample_valid_ct) {
2091 break;
2092 }
2093 ulptr_end++;
2094 sample_idx_stop = sample_valid_ct;
2095 }
2096 }
2097 }
2098 }
2099 }
2100 if (include_sex) {
2101 if (IS_SET(active_params, sex_start_idx)) {
2102 copy_when_nonmissing(loadbuf_collapsed, (char*)(&(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct])), sizeof(double), sample_valid_ct, missing_ct, (char*)dptr);
2103 dptr = &(dptr[cur_sample_valid_ct]);
2104 }
2105 // bugfix (21 May 2017): if no covariates, interactions_present is false
2106 // even in "--linear sex interaction" case. so we always check
2107 // active_params[] (allocating the necessary extra bits even when
2108 // 'interaction' was not specified).
2109 if (is_set(active_params, sex_start_idx + 1)) {
2110 ulptr = loadbuf_collapsed;
2111 ulptr_end = ulptr_end_init;
2112 sample_idx = 0;
2113 sample_idx_stop = BITCT2;
2114 dptr2 = &(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct]);
2115 if (!(coding_flags & GLM_HETHOM)) {
2116 if (!male_x_01) {
2117 while (1) {
2118 while (ulptr < ulptr_end) {
2119 cur_word = *ulptr++;
2120 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2121 cur_genotype = cur_word & 3;
2122 if (cur_genotype != 1) {
2123 // 0/1/2
2124 *dptr++ = ((double)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype))) * (*dptr2);
2125 }
2126 dptr2++;
2127 }
2128 sample_idx_stop += BITCT2;
2129 }
2130 if (sample_idx == sample_valid_ct) {
2131 break;
2132 }
2133 ulptr_end++;
2134 sample_idx_stop = sample_valid_ct;
2135 }
2136 } else {
2137 while (1) {
2138 while (ulptr < ulptr_end) {
2139 cur_word = *ulptr++;
2140 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2141 cur_genotype = cur_word & 3;
2142 if (cur_genotype != 1) {
2143 // 0/1/2
2144 *dptr++ = ((double)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)))) * (*dptr2);
2145 }
2146 dptr2++;
2147 }
2148 sample_idx_stop += BITCT2;
2149 }
2150 if (sample_idx == sample_valid_ct) {
2151 break;
2152 }
2153 ulptr_end++;
2154 sample_idx_stop = sample_valid_ct;
2155 }
2156 }
2157 } else {
2158 while (1) {
2159 while (ulptr < ulptr_end) {
2160 cur_word = *ulptr++;
2161 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2162 cur_genotype = cur_word & 3;
2163 if (cur_genotype != 1) {
2164 // 0/0/1
2165 *dptr++ = ((double)(cur_genotype == 0)) * (*dptr2);
2166 }
2167 dptr2++;
2168 }
2169 sample_idx_stop += BITCT2;
2170 }
2171 if (sample_idx == sample_valid_ct) {
2172 break;
2173 }
2174 ulptr_end++;
2175 sample_idx_stop = sample_valid_ct;
2176 }
2177 }
2178 }
2179 if (genotypic_or_hethom && (!is_nonx_haploid) && is_set(active_params, sex_start_idx + 2)) {
2180 ulptr = loadbuf_collapsed;
2181 ulptr_end = ulptr_end_init;
2182 sample_idx = 0;
2183 sample_idx_stop = BITCT2;
2184 dptr2 = &(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct]);
2185 while (1) {
2186 while (ulptr < ulptr_end) {
2187 cur_word = *ulptr++;
2188 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2189 cur_genotype = cur_word & 3;
2190 if (cur_genotype != 1) {
2191 // 0/1/0
2192 *dptr++ = ((double)(cur_genotype == 2)) * (*dptr2);
2193 }
2194 dptr2++;
2195 }
2196 sample_idx_stop += BITCT2;
2197 }
2198 if (sample_idx == sample_valid_ct) {
2199 break;
2200 }
2201 ulptr_end++;
2202 sample_idx_stop = sample_valid_ct;
2203 }
2204 }
2205 }
2206 // if (dptr != &(cur_covars_cov_major[cur_param_ct * cur_sample_valid_ct])) {
2207 // printf("assert failure:\n cur_param_ct = %u\n cur_sample_valid_ct = %" PRIuPTR "\n dptr - cur_covars_cov_major = %" PRIuPTR "\n", cur_param_ct, cur_sample_valid_ct, (uintptr_t)(dptr - cur_covars_cov_major));
2208 // exit(1);
2209 // }
2210 if (standard_beta) {
2211 for (param_idx = 1; param_idx < cur_param_ct; param_idx++) {
2212 dxx = 0; // sum
2213 dyy = 0; // ssq
2214 dptr = &(cur_covars_cov_major[param_idx * cur_sample_valid_ct]);
2215 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
2216 dzz = *dptr++;
2217 dxx += dzz;
2218 dyy += dzz * dzz;
2219 }
2220 dptr = &(cur_covars_cov_major[param_idx * cur_sample_valid_ct]);
2221 dzz = dxx / ((double)((intptr_t)cur_sample_valid_ct));
2222 dyy = sqrt((dyy - dxx * dzz) / ((double)((intptr_t)(cur_sample_valid_ct - 1))));
2223 if (dyy == 0) {
2224 fill_double_zero(cur_sample_valid_ct, dptr);
2225 } else {
2226 dyy = 1.0 / dyy;
2227 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
2228 *dptr = ((*dptr) - dzz) * dyy;
2229 dptr++;
2230 }
2231 }
2232 }
2233 }
2234
2235 transpose_copy(cur_param_ct, cur_sample_valid_ct, cur_covars_cov_major, cur_covars_sample_major);
2236 return missing_ct;
2237 }
2238
2239 uint32_t glm_fill_design_float(uintptr_t* loadbuf_collapsed, float* fixed_covars_cov_major, uintptr_t sample_valid_ct, uint32_t cur_param_ct, uint32_t coding_flags, uintptr_t condition_list_start_idx, uintptr_t interaction_start_idx, uintptr_t sex_start_idx, uintptr_t* active_params, uintptr_t* haploid_params, uint32_t include_sex, uint32_t male_x_01, uintptr_t* sex_male_collapsed, uint32_t is_nonx_haploid, float* cur_covars_cov_major) {
2240 // rows of cur_covars_cov_major must be 16-byte aligned
2241 float* fptr = cur_covars_cov_major;
2242 uintptr_t* ulptr_end_init = &(loadbuf_collapsed[sample_valid_ct / BITCT2]);
2243 uintptr_t fixed_covar_nonsex_ct = interaction_start_idx - condition_list_start_idx;
2244 uintptr_t interactions_present = sex_start_idx - interaction_start_idx;
2245 uint32_t genotypic_or_hethom = condition_list_start_idx - 2;
2246 uint32_t missing_ct = 0;
2247 float* fptr2;
2248 uintptr_t* ulptr;
2249 uintptr_t* ulptr_end;
2250 uintptr_t fixed_covar_idx;
2251 uintptr_t cur_sample_valid_ct;
2252 uintptr_t cur_sample_valid_cta4;
2253 uintptr_t sample_idx;
2254 uintptr_t sample_idx_stop;
2255 uintptr_t cur_word;
2256 uintptr_t cur_genotype;
2257 uintptr_t param_idx;
2258 uint32_t align_skip;
2259 // don't need to recompute this during permutations, but it's so cheap that
2260 // it hardly matters
2261 missing_ct = count_01(loadbuf_collapsed, QUATERCT_TO_WORDCT(sample_valid_ct));
2262 if (missing_ct >= sample_valid_ct - 1) {
2263 // regression will be skipped in this case
2264 return missing_ct;
2265 }
2266 cur_sample_valid_ct = sample_valid_ct - missing_ct;
2267 cur_sample_valid_cta4 = round_up_pow2(cur_sample_valid_ct, 4);
2268 align_skip = cur_sample_valid_cta4 - cur_sample_valid_ct;
2269 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
2270 *fptr++ = 1;
2271 }
2272 fill_float_zero(align_skip, fptr);
2273 fptr = &(fptr[align_skip]);
2274 if (IS_SET(active_params, 1)) {
2275 ulptr = loadbuf_collapsed;
2276 ulptr_end = ulptr_end_init;
2277 sample_idx = 0;
2278 sample_idx_stop = BITCT2;
2279 if (coding_flags & GLM_DOMINANT) {
2280 while (1) {
2281 while (ulptr < ulptr_end) {
2282 cur_word = *ulptr++;
2283 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2284 cur_genotype = cur_word & 3;
2285 if (cur_genotype != 1) {
2286 // 0/1/1, i.e.
2287 // 3 = hom A2 -> 0
2288 // 2 = het -> 1
2289 // 0 = hom A1 -> 1
2290 *fptr++ = (float)(cur_genotype != 3);
2291 }
2292 }
2293 sample_idx_stop += BITCT2;
2294 }
2295 if (sample_idx == sample_valid_ct) {
2296 break;
2297 }
2298 ulptr_end++;
2299 sample_idx_stop = sample_valid_ct;
2300 }
2301 } else if ((!(coding_flags & (GLM_HETHOM | GLM_RECESSIVE))) && (!is_nonx_haploid)) {
2302 if (!male_x_01) {
2303 while (1) {
2304 while (ulptr < ulptr_end) {
2305 cur_word = *ulptr++;
2306 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2307 cur_genotype = cur_word & 3;
2308 if (cur_genotype != 1) {
2309 // 0/1/2, i.e.
2310 // 3 = hom A2 -> 0
2311 // 2 = het -> 1
2312 // 0 = hom A1 -> 2
2313 *fptr++ = (float)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype));
2314 }
2315 }
2316 sample_idx_stop += BITCT2;
2317 }
2318 if (sample_idx == sample_valid_ct) {
2319 break;
2320 }
2321 ulptr_end++;
2322 sample_idx_stop = sample_valid_ct;
2323 }
2324 } else {
2325 while (1) {
2326 while (ulptr < ulptr_end) {
2327 cur_word = *ulptr++;
2328 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2329 cur_genotype = cur_word & 3;
2330 if (cur_genotype != 1) {
2331 // 0/1/2, but downshifted for males
2332 *fptr++ = (float)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)));
2333 }
2334 }
2335 sample_idx_stop += BITCT2;
2336 }
2337 if (sample_idx == sample_valid_ct) {
2338 break;
2339 }
2340 ulptr_end++;
2341 sample_idx_stop = sample_valid_ct;
2342 }
2343 }
2344 } else {
2345 while (1) {
2346 while (ulptr < ulptr_end) {
2347 cur_word = *ulptr++;
2348 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2349 cur_genotype = cur_word & 3;
2350 if (cur_genotype != 1) {
2351 // 0/0/1
2352 *fptr++ = (float)(cur_genotype == 0);
2353 }
2354 }
2355 sample_idx_stop += BITCT2;
2356 }
2357 if (sample_idx == sample_valid_ct) {
2358 break;
2359 }
2360 ulptr_end++;
2361 sample_idx_stop = sample_valid_ct;
2362 }
2363 }
2364 fill_float_zero(align_skip, fptr);
2365 fptr = &(fptr[align_skip]);
2366 }
2367 if (genotypic_or_hethom && (!is_nonx_haploid) && IS_SET(active_params, 2)) {
2368 ulptr = loadbuf_collapsed;
2369 ulptr_end = ulptr_end_init;
2370 sample_idx = 0;
2371 sample_idx_stop = BITCT2;
2372 while (1) {
2373 while (ulptr < ulptr_end) {
2374 cur_word = *ulptr++;
2375 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2376 cur_genotype = cur_word & 3;
2377 if (cur_genotype != 1) {
2378 // 0/1/0
2379 *fptr++ = (float)(cur_genotype == 2);
2380 }
2381 }
2382 sample_idx_stop += BITCT2;
2383 }
2384 if (sample_idx == sample_valid_ct) {
2385 break;
2386 }
2387 ulptr_end++;
2388 sample_idx_stop = sample_valid_ct;
2389 }
2390 fill_float_zero(align_skip, fptr);
2391 fptr = &(fptr[align_skip]);
2392 }
2393 for (fixed_covar_idx = 0; fixed_covar_idx < fixed_covar_nonsex_ct; fixed_covar_idx++) {
2394 if (!is_set(active_params, fixed_covar_idx + condition_list_start_idx)) {
2395 continue;
2396 }
2397 copy_when_nonmissing(loadbuf_collapsed, (char*)(&(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct])), sizeof(float), sample_valid_ct, missing_ct, (char*)fptr);
2398 fill_float_zero(align_skip, &(fptr[cur_sample_valid_ct]));
2399 fptr = &(fptr[cur_sample_valid_cta4]);
2400 }
2401 if (interactions_present) {
2402 param_idx = interaction_start_idx;
2403 for (fixed_covar_idx = 0; fixed_covar_idx < fixed_covar_nonsex_ct; fixed_covar_idx++, param_idx++) {
2404 if (IS_SET(active_params, param_idx)) {
2405 ulptr = loadbuf_collapsed;
2406 ulptr_end = ulptr_end_init;
2407 sample_idx = 0;
2408 sample_idx_stop = BITCT2;
2409 fptr2 = &(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct]);
2410 if (coding_flags & GLM_DOMINANT) {
2411 while (1) {
2412 while (ulptr < ulptr_end) {
2413 cur_word = *ulptr++;
2414 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2415 cur_genotype = cur_word & 3;
2416 if (cur_genotype != 1) {
2417 // 0/1/1
2418 *fptr++ = ((float)(cur_genotype != 3)) * (*fptr2);
2419 }
2420 fptr2++;
2421 }
2422 sample_idx_stop += BITCT2;
2423 }
2424 if (sample_idx == sample_valid_ct) {
2425 break;
2426 }
2427 ulptr_end++;
2428 sample_idx_stop = sample_valid_ct;
2429 }
2430 } else if (!(coding_flags & (GLM_HETHOM | GLM_RECESSIVE))) {
2431 if (!male_x_01) {
2432 while (1) {
2433 while (ulptr < ulptr_end) {
2434 cur_word = *ulptr++;
2435 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2436 cur_genotype = cur_word & 3;
2437 if (cur_genotype != 1) {
2438 // 0/1/2
2439 *fptr++ = ((float)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype))) * (*fptr2);
2440 }
2441 fptr2++;
2442 }
2443 sample_idx_stop += BITCT2;
2444 }
2445 if (sample_idx == sample_valid_ct) {
2446 break;
2447 }
2448 ulptr_end++;
2449 sample_idx_stop = sample_valid_ct;
2450 }
2451 } else {
2452 while (1) {
2453 while (ulptr < ulptr_end) {
2454 cur_word = *ulptr++;
2455 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2456 cur_genotype = cur_word & 3;
2457 if (cur_genotype != 1) {
2458 // 0/1/2
2459 *fptr++ = ((float)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)))) * (*fptr2);
2460 }
2461 fptr2++;
2462 }
2463 sample_idx_stop += BITCT2;
2464 }
2465 if (sample_idx == sample_valid_ct) {
2466 break;
2467 }
2468 ulptr_end++;
2469 sample_idx_stop = sample_valid_ct;
2470 }
2471 }
2472 } else {
2473 while (1) {
2474 while (ulptr < ulptr_end) {
2475 cur_word = *ulptr++;
2476 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2477 cur_genotype = cur_word & 3;
2478 if (cur_genotype != 1) {
2479 // 0/0/1
2480 *fptr++ = ((float)(cur_genotype == 0)) * (*fptr2);
2481 }
2482 fptr2++;
2483 }
2484 sample_idx_stop += BITCT2;
2485 }
2486 if (sample_idx == sample_valid_ct) {
2487 break;
2488 }
2489 ulptr_end++;
2490 sample_idx_stop = sample_valid_ct;
2491 }
2492 }
2493 fill_float_zero(align_skip, fptr);
2494 fptr = &(fptr[align_skip]);
2495 }
2496 if (genotypic_or_hethom) {
2497 param_idx++;
2498 if ((!is_nonx_haploid) && IS_SET(active_params, param_idx)) {
2499 ulptr = loadbuf_collapsed;
2500 ulptr_end = ulptr_end_init;
2501 sample_idx = 0;
2502 sample_idx_stop = BITCT2;
2503 fptr2 = &(fixed_covars_cov_major[fixed_covar_idx * sample_valid_ct]);
2504 while (1) {
2505 while (ulptr < ulptr_end) {
2506 cur_word = *ulptr++;
2507 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2508 cur_genotype = cur_word & 3;
2509 if (cur_genotype != 1) {
2510 // 0/1/0
2511 *fptr++ = ((float)(cur_genotype == 2)) * (*fptr2);
2512 }
2513 fptr2++;
2514 }
2515 sample_idx_stop += BITCT2;
2516 }
2517 if (sample_idx == sample_valid_ct) {
2518 break;
2519 }
2520 ulptr_end++;
2521 sample_idx_stop = sample_valid_ct;
2522 }
2523 fill_float_zero(align_skip, fptr);
2524 fptr = &(fptr[align_skip]);
2525 }
2526 }
2527 }
2528 }
2529 if (include_sex) {
2530 if (IS_SET(active_params, sex_start_idx)) {
2531 copy_when_nonmissing(loadbuf_collapsed, (char*)(&(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct])), sizeof(float), sample_valid_ct, missing_ct, (char*)fptr);
2532 fill_float_zero(align_skip, &(fptr[cur_sample_valid_ct]));
2533 fptr = &(fptr[cur_sample_valid_cta4]);
2534 }
2535 if (is_set(active_params, sex_start_idx + 1)) {
2536 ulptr = loadbuf_collapsed;
2537 ulptr_end = ulptr_end_init;
2538 sample_idx = 0;
2539 sample_idx_stop = BITCT2;
2540 fptr2 = &(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct]);
2541 if (coding_flags & GLM_DOMINANT) {
2542 while (1) {
2543 while (ulptr < ulptr_end) {
2544 cur_word = *ulptr++;
2545 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2546 cur_genotype = cur_word & 3;
2547 if (cur_genotype != 1) {
2548 // 0/1/1
2549 *fptr++ = ((float)(cur_genotype != 3)) * (*fptr2);
2550 }
2551 fptr2++;
2552 }
2553 sample_idx_stop += BITCT2;
2554 }
2555 if (sample_idx == sample_valid_ct) {
2556 break;
2557 }
2558 ulptr_end++;
2559 sample_idx_stop = sample_valid_ct;
2560 }
2561 } else if (!(coding_flags & (GLM_HETHOM | GLM_RECESSIVE))) {
2562 if (!male_x_01) {
2563 while (1) {
2564 while (ulptr < ulptr_end) {
2565 cur_word = *ulptr++;
2566 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2567 cur_genotype = cur_word & 3;
2568 if (cur_genotype != 1) {
2569 // 0/1/2
2570 *fptr++ = ((float)((intptr_t)(2 + (cur_genotype / 2) - cur_genotype))) * (*fptr2);
2571 }
2572 fptr2++;
2573 }
2574 sample_idx_stop += BITCT2;
2575 }
2576 if (sample_idx == sample_valid_ct) {
2577 break;
2578 }
2579 ulptr_end++;
2580 sample_idx_stop = sample_valid_ct;
2581 }
2582 } else {
2583 while (1) {
2584 while (ulptr < ulptr_end) {
2585 cur_word = *ulptr++;
2586 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2587 cur_genotype = cur_word & 3;
2588 if (cur_genotype != 1) {
2589 // 0/1/2
2590 *fptr++ = ((float)((intptr_t)((2 + (cur_genotype / 2) - cur_genotype) >> IS_SET(sex_male_collapsed, sample_idx)))) * (*fptr2);
2591 }
2592 fptr2++;
2593 }
2594 sample_idx_stop += BITCT2;
2595 }
2596 if (sample_idx == sample_valid_ct) {
2597 break;
2598 }
2599 ulptr_end++;
2600 sample_idx_stop = sample_valid_ct;
2601 }
2602 }
2603 } else {
2604 while (1) {
2605 while (ulptr < ulptr_end) {
2606 cur_word = *ulptr++;
2607 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2608 cur_genotype = cur_word & 3;
2609 if (cur_genotype != 1) {
2610 // 0/0/1
2611 *fptr++ = ((float)(cur_genotype == 0)) * (*fptr2);
2612 }
2613 fptr2++;
2614 }
2615 sample_idx_stop += BITCT2;
2616 }
2617 if (sample_idx == sample_valid_ct) {
2618 break;
2619 }
2620 ulptr_end++;
2621 sample_idx_stop = sample_valid_ct;
2622 }
2623 }
2624 fill_float_zero(align_skip, fptr);
2625 fptr = &(fptr[align_skip]);
2626 }
2627 if (genotypic_or_hethom && (!is_nonx_haploid) && is_set(active_params, sex_start_idx + 2)) {
2628 ulptr = loadbuf_collapsed;
2629 ulptr_end = ulptr_end_init;
2630 sample_idx = 0;
2631 sample_idx_stop = BITCT2;
2632 fptr2 = &(fixed_covars_cov_major[fixed_covar_nonsex_ct * sample_valid_ct]);
2633 while (1) {
2634 while (ulptr < ulptr_end) {
2635 cur_word = *ulptr++;
2636 for (; sample_idx < sample_idx_stop; sample_idx++, cur_word >>= 2) {
2637 cur_genotype = cur_word & 3;
2638 if (cur_genotype != 1) {
2639 // 0/1/0
2640 *fptr++ = ((float)(cur_genotype == 2)) * (*fptr2);
2641 }
2642 fptr2++;
2643 }
2644 sample_idx_stop += BITCT2;
2645 }
2646 if (sample_idx == sample_valid_ct) {
2647 break;
2648 }
2649 ulptr_end++;
2650 sample_idx_stop = sample_valid_ct;
2651 }
2652 fill_float_zero(align_skip, fptr);
2653 fptr = &(fptr[align_skip]);
2654 }
2655 }
2656 // if (fptr != &(cur_covars_cov_major[cur_param_ct * cur_sample_valid_cta4])) {
2657 // printf("assert failure:\n cur_param_ct = %u\n cur_sample_valid_cta4 = %" PRIuPTR "\n fptr - cur_covars_cov_major = %" PRIuPTR "\nsample_valid_ct = %" PRIuPTR "\nalign_skip = %u\n", cur_param_ct, cur_sample_valid_cta4, (uintptr_t)(fptr - cur_covars_cov_major), sample_valid_ct, align_skip);
2658 // exit(1);
2659 // }
2660 return missing_ct;
2661 }
2662
2663 // glm main loop-specific multithread globals
2664
2665 #ifndef NOLAPACK
2666 typedef struct linear_multithread_struct {
2667 double* param_2d_buf;
2668 double* param_2d_buf2;
2669 MATRIX_INVERT_BUF1_TYPE* mi_buf;
2670 double* df_df_buf;
2671 double* df_buf;
2672 double* cur_covars_cov_major;
2673 double* cur_covars_sample_major;
2674 uintptr_t* perm_fails;
2675 double* dgels_a;
2676 double* dgels_b;
2677 double* dgels_work;
2678 double* param_df_buf;
2679 double* param_df_buf2;
2680 double* regression_results;
2681 } Linear_multithread;
2682
2683 static Linear_multithread* g_linear_mt;
2684 #endif
2685
2686 typedef struct logistic_multithread_struct {
2687 float* cur_covars_cov_major;
2688 float* coef;
2689 float* pp;
2690 float* sample_1d_buf;
2691 float* pheno_buf;
2692 float* param_1d_buf;
2693 float* param_1d_buf2;
2694 float* param_2d_buf;
2695 float* param_2d_buf2;
2696 float* regression_results;
2697 double* param_1d_dbuf;
2698 double* param_2d_dbuf;
2699 double* param_2d_dbuf2;
2700 double* param_df_dbuf;
2701 double* df_df_dbuf;
2702 MATRIX_INVERT_BUF1_TYPE* mi_buf;
2703 double* df_dbuf;
2704 uintptr_t* perm_fails;
2705 } Logistic_multithread;
2706
2707 static Logistic_multithread* g_logistic_mt;
2708 static uintptr_t* g_joint_test_params;
2709 static double* g_orig_stats;
2710 #ifndef NOLAPACK
2711 static double* g_fixed_covars_cov_major;
2712 #endif
2713 static uintptr_t g_cur_param_ct;
2714 static uintptr_t g_cur_constraint_ct;
2715 static uint32_t g_standard_beta;
2716 static uint32_t g_coding_flags;
2717 static uintptr_t g_condition_list_start_idx;
2718 static uintptr_t g_interaction_start_idx;
2719 static uintptr_t g_sex_start_idx;
2720 static uintptr_t* g_active_params;
2721 static uintptr_t* g_haploid_params;
2722 static uint32_t g_include_sex;
2723 static uint32_t g_male_x_01;
2724 static uintptr_t* g_sex_male_collapsed;
2725 #ifndef NOLAPACK
2726 static __CLPK_integer g_dgels_lwork;
2727 #endif
2728 static double* g_constraints_con_major;
2729 static uint32_t g_perm_batch_max;
2730 static float* g_fixed_covars_cov_major_f;
2731
2732 static const char glm_main_effects[] = "REC\0DOM\0HOM\0ADD";
2733
2734 #ifndef NOLAPACK
2735 THREAD_RET_TYPE glm_linear_adapt_thread(void* arg) {
2736 uintptr_t tidx = (uintptr_t)arg;
2737 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
2738 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
2739 uintptr_t perm_vec_ct = g_perm_vec_ct;
2740 // unlike the other permutation loops, g_perms_done is not preincremented
2741 // here
2742 uint32_t pidx_offset = g_perms_done;
2743 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
2744 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
2745 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
2746 uint32_t first_adapt_check = g_first_adapt_check;
2747 uintptr_t* loadbuf = g_loadbuf;
2748 uint32_t* adapt_m_table = &(g_adapt_m_table[marker_bidx]);
2749 double* perm_pmajor = g_perm_pmajor;
2750 unsigned char* __restrict__ perm_adapt_stop = g_perm_adapt_stop;
2751 uint32_t* __restrict__ perm_attempt_ct = g_perm_attempt_ct;
2752 uint32_t* __restrict__ perm_2success_ct = g_perm_2success_ct;
2753 uintptr_t* joint_test_params = g_joint_test_params;
2754 double* __restrict__ orig_stats = g_orig_stats;
2755 double adaptive_intercept = g_adaptive_intercept;
2756 double adaptive_slope = g_adaptive_slope;
2757 double adaptive_ci_zt = g_adaptive_ci_zt;
2758 double aperm_alpha = g_aperm_alpha;
2759 double pheno_sum_base = g_pheno_sum;
2760 double pheno_ssq_base = g_pheno_ssq;
2761 uintptr_t cur_param_ct = g_cur_param_ct;
2762 uintptr_t cur_constraint_ct = g_cur_constraint_ct;
2763 char dgels_trans = 'N';
2764 __CLPK_integer dgels_n = (int32_t)((uint32_t)cur_param_ct);
2765 __CLPK_integer dgels_lwork = g_dgels_lwork;
2766 uint32_t standard_beta = g_standard_beta;
2767 uint32_t coding_flags = g_coding_flags;
2768 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
2769 uintptr_t interaction_start_idx = g_interaction_start_idx;
2770 uintptr_t sex_start_idx = g_sex_start_idx;
2771 uintptr_t* active_params = g_active_params;
2772 uintptr_t* haploid_params = g_haploid_params;
2773 uint32_t include_sex = g_include_sex;
2774 uint32_t male_x_01 = g_male_x_01;
2775 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
2776 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
2777 double* fixed_covars_cov_major = g_fixed_covars_cov_major;
2778 double* constraints_con_major = g_constraints_con_major;
2779 double* param_2d_buf = g_linear_mt[tidx].param_2d_buf;
2780 double* param_2d_buf2 = g_linear_mt[tidx].param_2d_buf2;
2781 MATRIX_INVERT_BUF1_TYPE* mi_buf = g_linear_mt[tidx].mi_buf;
2782 double* df_df_buf = g_linear_mt[tidx].df_df_buf;
2783 double* df_buf = g_linear_mt[tidx].df_buf;
2784 double* cur_covars_cov_major = g_linear_mt[tidx].cur_covars_cov_major;
2785 double* cur_covars_sample_major = g_linear_mt[tidx].cur_covars_sample_major;
2786 uintptr_t* perm_fails = g_linear_mt[tidx].perm_fails;
2787 double* dgels_a = g_linear_mt[tidx].dgels_a;
2788 double* dgels_b = g_linear_mt[tidx].dgels_b;
2789 double* dgels_work = g_linear_mt[tidx].dgels_work;
2790 double* param_df_buf = g_linear_mt[tidx].param_df_buf;
2791 double* param_df_buf2 = g_linear_mt[tidx].param_df_buf2;
2792 double* regression_results = g_linear_mt[tidx].regression_results;
2793 double* dptr;
2794 uintptr_t* loadbuf_ptr;
2795 uintptr_t cur_missing_ct;
2796 uintptr_t cur_sample_valid_ct;
2797 uintptr_t pidx;
2798 uintptr_t sample_idx;
2799 uintptr_t param_ctx_m1;
2800 uint32_t marker_idx;
2801 uint32_t next_adapt_check;
2802 uint32_t success_2start;
2803 uint32_t success_2incr;
2804 uint32_t attempts;
2805 uint32_t cur_attempts;
2806 uint32_t perm_fail_ct;
2807 uint32_t cur_fail_ct;
2808 __CLPK_integer dgels_m;
2809 __CLPK_integer dgels_nrhs;
2810 __CLPK_integer dgels_ldb;
2811 __CLPK_integer dgels_info;
2812 double stat_high;
2813 double stat_low;
2814 double pval;
2815 double dxx;
2816 double dyy;
2817 double dzz;
2818 if (cur_constraint_ct) {
2819 param_ctx_m1 = cur_param_ct;
2820 } else {
2821 param_ctx_m1 = cur_param_ct - 1;
2822 }
2823 if (tidx + 1 == g_assoc_thread_ct) {
2824 marker_bceil = g_block_diff;
2825 }
2826 for (; marker_bidx < marker_bceil; marker_bidx++) {
2827 marker_idx = *adapt_m_table++;
2828 if (perm_adapt_stop[marker_idx]) {
2829 continue;
2830 }
2831 success_2start = perm_2success_ct[marker_idx];
2832 attempts = perm_attempt_ct[marker_idx];
2833 next_adapt_check = first_adapt_check;
2834 stat_high = orig_stats[marker_idx] + EPSILON;
2835 stat_low = orig_stats[marker_idx] - EPSILON;
2836 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
2837 cur_missing_ct = glm_fill_design(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major, cur_covars_sample_major, standard_beta);
2838 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
2839 dgels_m = (int32_t)((uint32_t)cur_sample_valid_ct);
2840 dgels_ldb = dgels_m;
2841 dptr = dgels_b;
2842 success_2incr = 0;
2843 cur_fail_ct = 0;
2844 memcpy(dgels_a, cur_covars_cov_major, cur_param_ct * cur_sample_valid_ct * sizeof(double));
2845 if (!cur_missing_ct) {
2846 memcpy(dgels_b, perm_pmajor, perm_vec_ct * sample_valid_ct * sizeof(double));
2847 } else {
2848 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
2849 copy_when_nonmissing(loadbuf_ptr, (char*)(&(perm_pmajor[pidx * sample_valid_ct])), sizeof(double), sample_valid_ct, cur_missing_ct, (char*)(&(dgels_b[pidx * cur_sample_valid_ct])));
2850 if (standard_beta) {
2851 dxx = 0;
2852 dyy = 0;
2853 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
2854 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
2855 dzz = *dptr++;
2856 dxx += dzz;
2857 dyy += dzz * dzz;
2858 }
2859 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
2860 dzz = dxx / ((double)((intptr_t)cur_sample_valid_ct));
2861 dyy = sqrt(((double)((intptr_t)(cur_sample_valid_ct - 1))) / (dyy - dxx * dzz));
2862 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
2863 *dptr = ((*dptr) - dzz) * dyy;
2864 dptr++;
2865 }
2866 }
2867 }
2868 }
2869 dgels_nrhs = (int32_t)((uint32_t)perm_vec_ct);
2870 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
2871 glm_linear(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, loadbuf_ptr, standard_beta, pheno_sum_base, pheno_ssq_base, cur_covars_cov_major, cur_covars_sample_major, perm_pmajor, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, cur_constraint_ct, constraints_con_major, param_df_buf, param_df_buf2, df_df_buf, df_buf, &perm_fail_ct, perm_fails);
2872 for (pidx = 0; pidx < perm_vec_ct;) {
2873 if (!IS_SET(perm_fails, pidx)) {
2874 if (!joint_test_params) {
2875 dxx = dgels_b[pidx * cur_sample_valid_ct + 1];
2876 dyy = sqrt(regression_results[pidx * param_ctx_m1]);
2877 dxx = fabs(dxx / dyy);
2878 if (dxx > stat_high) {
2879 success_2incr += 2;
2880 } else if (dxx > stat_low) {
2881 success_2incr++;
2882 }
2883 } else {
2884 dxx = regression_results[(pidx + 1) * param_ctx_m1 - 1];
2885 if (dxx > stat_high) {
2886 success_2incr += 2;
2887 } else if (dxx > stat_low) {
2888 success_2incr++;
2889 } else if (dxx == -9) {
2890 cur_fail_ct++;
2891 }
2892 }
2893 } else {
2894 cur_fail_ct++;
2895 }
2896 if (++pidx == next_adapt_check - pidx_offset) {
2897 if (success_2start + success_2incr) {
2898 cur_attempts = attempts + pidx - cur_fail_ct;
2899 pval = ((double)((int32_t)(success_2start + success_2incr + 2))) / ((double)(2 * ((int32_t)(cur_attempts + 1))));
2900 dxx = adaptive_ci_zt * sqrt(pval * (1 - pval) / ((int32_t)cur_attempts));
2901 dyy = pval - dxx; // lower bound
2902 dzz = pval + dxx; // upper bound
2903 if ((dyy > aperm_alpha) || (dzz < aperm_alpha)) {
2904 perm_adapt_stop[marker_idx] = 1;
2905 goto glm_linear_adapt_thread_done;
2906 }
2907 }
2908 next_adapt_check += (int32_t)(adaptive_intercept + ((int32_t)next_adapt_check) * adaptive_slope);
2909 }
2910 }
2911 cur_attempts = attempts + perm_vec_ct - cur_fail_ct;
2912 glm_linear_adapt_thread_done:
2913 perm_2success_ct[marker_idx] = success_2start + success_2incr;
2914 perm_attempt_ct[marker_idx] = cur_attempts;
2915 }
2916 THREAD_RETURN;
2917 }
2918 #endif
2919
2920 THREAD_RET_TYPE glm_logistic_adapt_thread(void* arg) {
2921 uintptr_t tidx = (uintptr_t)arg;
2922 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
2923 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
2924 uintptr_t perm_vec_ct = g_perm_vec_ct;
2925 uint32_t pidx_offset = g_perms_done;
2926 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
2927 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
2928 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
2929 uint32_t first_adapt_check = g_first_adapt_check;
2930 uintptr_t* loadbuf = g_loadbuf;
2931 uint32_t* adapt_m_table = &(g_adapt_m_table[marker_bidx]);
2932 uintptr_t* perm_vecs = g_perm_vecs;
2933 unsigned char* __restrict__ perm_adapt_stop = g_perm_adapt_stop;
2934 uint32_t* __restrict__ perm_attempt_ct = g_perm_attempt_ct;
2935 uint32_t* __restrict__ perm_2success_ct = g_perm_2success_ct;
2936 uintptr_t* joint_test_params = g_joint_test_params;
2937 double* __restrict__ orig_stats = g_orig_stats;
2938 double adaptive_intercept = g_adaptive_intercept;
2939 double adaptive_slope = g_adaptive_slope;
2940 double adaptive_ci_zt = g_adaptive_ci_zt;
2941 double aperm_alpha = g_aperm_alpha;
2942 uintptr_t cur_param_ct = g_cur_param_ct;
2943 uintptr_t cur_param_cta4 = round_up_pow2(cur_param_ct, 4);
2944 uintptr_t cur_constraint_ct = g_cur_constraint_ct;
2945 uint32_t coding_flags = g_coding_flags;
2946 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
2947 uintptr_t interaction_start_idx = g_interaction_start_idx;
2948 uintptr_t sex_start_idx = g_sex_start_idx;
2949 uintptr_t* active_params = g_active_params;
2950 uintptr_t* haploid_params = g_haploid_params;
2951 uint32_t include_sex = g_include_sex;
2952 uint32_t male_x_01 = g_male_x_01;
2953 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
2954 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
2955 float* fixed_covars_cov_major = g_fixed_covars_cov_major_f;
2956 double* constraints_con_major = g_constraints_con_major;
2957 float* cur_covars_cov_major = g_logistic_mt[tidx].cur_covars_cov_major;
2958 float* coef = g_logistic_mt[tidx].coef;
2959 float* pp = g_logistic_mt[tidx].pp;
2960 float* sample_1d_buf = g_logistic_mt[tidx].sample_1d_buf;
2961 float* pheno_buf = g_logistic_mt[tidx].pheno_buf;
2962 float* param_1d_buf = g_logistic_mt[tidx].param_1d_buf;
2963 float* param_1d_buf2 = g_logistic_mt[tidx].param_1d_buf2;
2964 float* param_2d_buf = g_logistic_mt[tidx].param_2d_buf;
2965 float* param_2d_buf2 = g_logistic_mt[tidx].param_2d_buf2;
2966 float* regression_results = g_logistic_mt[tidx].regression_results;
2967 double* param_1d_dbuf = g_logistic_mt[tidx].param_1d_dbuf;
2968 double* param_2d_dbuf = g_logistic_mt[tidx].param_2d_dbuf;
2969 double* param_2d_dbuf2 = g_logistic_mt[tidx].param_2d_dbuf2;
2970 double* param_df_dbuf = g_logistic_mt[tidx].param_df_dbuf;
2971 MATRIX_INVERT_BUF1_TYPE* mi_buf = g_logistic_mt[tidx].mi_buf;
2972 double* df_df_dbuf = g_logistic_mt[tidx].df_df_dbuf;
2973 double* df_dbuf = g_logistic_mt[tidx].df_dbuf;
2974 uintptr_t* perm_fails = g_logistic_mt[tidx].perm_fails;
2975 uintptr_t* loadbuf_ptr;
2976 uintptr_t cur_missing_ct;
2977 uintptr_t cur_sample_valid_ct;
2978 uintptr_t pidx;
2979 uintptr_t param_ctx_m1;
2980 uint32_t marker_idx;
2981 uint32_t next_adapt_check;
2982 uint32_t success_2start;
2983 uint32_t success_2incr;
2984 uint32_t attempts;
2985 uint32_t cur_attempts;
2986 uint32_t cur_fail_ct;
2987 double stat_high;
2988 double stat_low;
2989 double pval;
2990 double dxx;
2991 double dyy;
2992 double dzz;
2993 if (cur_constraint_ct) {
2994 param_ctx_m1 = cur_param_ct;
2995 } else {
2996 param_ctx_m1 = cur_param_ct - 1;
2997 }
2998 if (tidx + 1 == g_assoc_thread_ct) {
2999 marker_bceil = g_block_diff;
3000 }
3001 for (; marker_bidx < marker_bceil; marker_bidx++) {
3002 marker_idx = *adapt_m_table++;
3003 if (perm_adapt_stop[marker_idx]) {
3004 continue;
3005 }
3006 success_2start = perm_2success_ct[marker_idx];
3007 attempts = perm_attempt_ct[marker_idx];
3008 next_adapt_check = first_adapt_check;
3009 stat_high = orig_stats[marker_idx] + EPSILON;
3010 stat_low = orig_stats[marker_idx] - EPSILON;
3011 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
3012 cur_missing_ct = glm_fill_design_float(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major);
3013 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
3014 success_2incr = 0;
3015 cur_fail_ct = 0;
3016 // todo: try better starting position
3017 fill_float_zero(cur_param_cta4 * perm_vec_ct, coef);
3018 glm_logistic(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, 1, loadbuf_ptr, cur_covars_cov_major, perm_vecs, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, cur_constraint_ct, constraints_con_major, param_1d_dbuf, param_2d_dbuf, param_2d_dbuf2, param_df_dbuf, df_df_dbuf, mi_buf, df_dbuf, perm_fails);
3019 for (pidx = 0; pidx < perm_vec_ct;) {
3020 if (!IS_SET(perm_fails, pidx)) {
3021 if (!joint_test_params) {
3022 dxx = (double)coef[pidx * cur_param_cta4 + 1]; // bugfix, forgot a4
3023 dxx *= dxx;
3024 dxx /= (double)regression_results[pidx * param_ctx_m1];
3025 if (dxx > stat_high) {
3026 success_2incr += 2;
3027 } else if (dxx > stat_low) {
3028 success_2incr++;
3029 }
3030 } else {
3031 dxx = (double)regression_results[(pidx + 1) * param_ctx_m1 - 1];
3032 if (dxx > stat_high) {
3033 success_2incr += 2;
3034 } else if (dxx > stat_low) {
3035 success_2incr++;
3036 } else if (dxx == -9) {
3037 cur_fail_ct++;
3038 }
3039 }
3040 } else {
3041 cur_fail_ct++;
3042 }
3043 if (++pidx == next_adapt_check - pidx_offset) {
3044 if (success_2start + success_2incr) {
3045 cur_attempts = attempts + pidx - cur_fail_ct;
3046 pval = ((double)((int32_t)(success_2start + success_2incr + 2))) / ((double)(2 * ((int32_t)(cur_attempts + 1))));
3047 dxx = adaptive_ci_zt * sqrt(pval * (1 - pval) / ((int32_t)cur_attempts));
3048 dyy = pval - dxx; // lower bound
3049 dzz = pval + dxx; // upper bound
3050 if ((dyy > aperm_alpha) || (dzz < aperm_alpha)) {
3051 perm_adapt_stop[marker_idx] = 1;
3052 goto glm_logistic_adapt_thread_done;
3053 }
3054 }
3055 next_adapt_check += (int32_t)(adaptive_intercept + ((int32_t)next_adapt_check) * adaptive_slope);
3056 }
3057 }
3058 cur_attempts = attempts + perm_vec_ct - cur_fail_ct;
3059 glm_logistic_adapt_thread_done:
3060 perm_2success_ct[marker_idx] = success_2start + success_2incr;
3061 perm_attempt_ct[marker_idx] = cur_attempts;
3062 }
3063 THREAD_RETURN;
3064 }
3065
3066 #ifndef NOLAPACK
3067 THREAD_RET_TYPE glm_linear_maxt_thread(void* arg) {
3068 // todo: either switch to spawn_threads2 interface, or document why that
3069 // isn't a good idea
3070 uintptr_t tidx = (uintptr_t)arg;
3071 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
3072 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
3073 uintptr_t perm_vec_ct = g_perm_vec_ct;
3074 uint32_t pidx_offset = g_perms_done;
3075 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
3076 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
3077 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
3078 uintptr_t* loadbuf = g_loadbuf;
3079 uint32_t* adapt_m_table = &(g_adapt_m_table[marker_bidx]);
3080 double* perm_pmajor = g_perm_pmajor;
3081 uintptr_t perm_vec_ctcl8m = round_up_pow2(perm_vec_ct, CACHELINE_DBL);
3082 double* __restrict__ results = &(g_maxt_thread_results[perm_vec_ctcl8m * tidx]);
3083 unsigned char* __restrict__ perm_adapt_stop = g_perm_adapt_stop;
3084 uint32_t* __restrict__ perm_fail_cts = g_perm_attempt_ct;
3085 uint32_t* __restrict__ perm_2success_ct = g_perm_2success_ct;
3086 uintptr_t* joint_test_params = g_joint_test_params;
3087 double* __restrict__ orig_stats = g_orig_stats;
3088 double pheno_sum_base = g_pheno_sum;
3089 double pheno_ssq_base = g_pheno_ssq;
3090 uintptr_t cur_param_ct = g_cur_param_ct;
3091 uintptr_t cur_constraint_ct = g_cur_constraint_ct;
3092 char dgels_trans = 'N';
3093 __CLPK_integer dgels_n = (int32_t)((uint32_t)cur_param_ct);
3094 __CLPK_integer dgels_lwork = g_dgels_lwork;
3095 uint32_t standard_beta = g_standard_beta;
3096 uint32_t coding_flags = g_coding_flags;
3097 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
3098 uintptr_t interaction_start_idx = g_interaction_start_idx;
3099 uintptr_t sex_start_idx = g_sex_start_idx;
3100 uintptr_t* active_params = g_active_params;
3101 uintptr_t* haploid_params = g_haploid_params;
3102 uint32_t include_sex = g_include_sex;
3103 uint32_t male_x_01 = g_male_x_01;
3104 uintptr_t perm_batch_max = g_perm_batch_max;
3105 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
3106 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
3107 double* fixed_covars_cov_major = g_fixed_covars_cov_major;
3108 double* constraints_con_major = g_constraints_con_major;
3109 double* msa_ptr = nullptr;
3110 double* param_2d_buf = g_linear_mt[tidx].param_2d_buf;
3111 double* param_2d_buf2 = g_linear_mt[tidx].param_2d_buf2;
3112 MATRIX_INVERT_BUF1_TYPE* mi_buf = g_linear_mt[tidx].mi_buf;
3113 double* df_df_buf = g_linear_mt[tidx].df_df_buf;
3114 double* df_buf = g_linear_mt[tidx].df_buf;
3115 double* cur_covars_cov_major = g_linear_mt[tidx].cur_covars_cov_major;
3116 double* cur_covars_sample_major = g_linear_mt[tidx].cur_covars_sample_major;
3117 uintptr_t* perm_fails = g_linear_mt[tidx].perm_fails;
3118 double* dgels_a = g_linear_mt[tidx].dgels_a;
3119 double* dgels_b = g_linear_mt[tidx].dgels_b;
3120 double* dgels_work = g_linear_mt[tidx].dgels_work;
3121 double* param_df_buf = g_linear_mt[tidx].param_df_buf;
3122 double* param_df_buf2 = g_linear_mt[tidx].param_df_buf2;
3123 double* regression_results = g_linear_mt[tidx].regression_results;
3124 double* dptr;
3125 uintptr_t* loadbuf_ptr;
3126 uintptr_t cur_missing_ct;
3127 uintptr_t cur_sample_valid_ct;
3128 uintptr_t pidx;
3129 uintptr_t sample_idx;
3130 uintptr_t param_ctx_m1;
3131 uint32_t marker_idx;
3132 uint32_t success_2incr;
3133 uint32_t perm_fail_ct;
3134 __CLPK_integer dgels_m;
3135 __CLPK_integer dgels_nrhs;
3136 __CLPK_integer dgels_ldb;
3137 __CLPK_integer dgels_info;
3138 double stat_high;
3139 double stat_low;
3140 double dxx;
3141 double dyy;
3142 double dzz;
3143 if (cur_constraint_ct) {
3144 param_ctx_m1 = cur_param_ct;
3145 } else {
3146 param_ctx_m1 = cur_param_ct - 1;
3147 }
3148 if (tidx + 1 == g_assoc_thread_ct) {
3149 marker_bceil = g_block_diff;
3150 }
3151 memcpy(results, &(g_maxt_extreme_stat[pidx_offset]), perm_vec_ct * sizeof(double));
3152 for (; marker_bidx < marker_bceil; marker_bidx++) {
3153 marker_idx = *adapt_m_table++;
3154 if (perm_adapt_stop[marker_idx]) {
3155 if (g_mperm_save_all && (perm_batch_max != perm_vec_ct)) {
3156 msa_ptr = &(g_mperm_save_all[marker_idx * perm_vec_ct]);
3157 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3158 *msa_ptr++ = -9;
3159 }
3160 }
3161 continue;
3162 }
3163 if (g_mperm_save_all) {
3164 msa_ptr = &(g_mperm_save_all[marker_idx * perm_vec_ct]);
3165 }
3166 stat_high = orig_stats[marker_idx] + EPSILON;
3167 stat_low = orig_stats[marker_idx] - EPSILON;
3168 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
3169 cur_missing_ct = glm_fill_design(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major, cur_covars_sample_major, standard_beta);
3170 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
3171 dgels_m = (int32_t)((uint32_t)cur_sample_valid_ct);
3172 dgels_ldb = dgels_m;
3173 dptr = dgels_b;
3174 success_2incr = 0;
3175 memcpy(dgels_a, cur_covars_cov_major, cur_param_ct * cur_sample_valid_ct * sizeof(double));
3176 if (!cur_missing_ct) {
3177 memcpy(dgels_b, perm_pmajor, perm_vec_ct * sample_valid_ct * sizeof(double));
3178 } else {
3179 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3180 copy_when_nonmissing(loadbuf_ptr, (char*)(&(perm_pmajor[pidx * sample_valid_ct])), sizeof(double), sample_valid_ct, cur_missing_ct, (char*)(&(dgels_b[pidx * cur_sample_valid_ct])));
3181 if (standard_beta) {
3182 dxx = 0;
3183 dyy = 0;
3184 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
3185 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
3186 dzz = *dptr++;
3187 dxx += dzz;
3188 dyy += dzz * dzz;
3189 }
3190 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
3191 dzz = dxx / ((double)((intptr_t)cur_sample_valid_ct));
3192 dyy = sqrt(((double)((intptr_t)(cur_sample_valid_ct - 1))) / (dyy - dxx * dzz));
3193 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
3194 *dptr = ((*dptr) - dzz) * dyy;
3195 dptr++;
3196 }
3197 }
3198 }
3199 }
3200 dgels_nrhs = (int32_t)((uint32_t)perm_vec_ct);
3201 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
3202 glm_linear(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, loadbuf_ptr, standard_beta, pheno_sum_base, pheno_ssq_base, cur_covars_cov_major, cur_covars_sample_major, perm_pmajor, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, cur_constraint_ct, constraints_con_major, param_df_buf, param_df_buf2, df_df_buf, df_buf, &perm_fail_ct, perm_fails);
3203 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3204 if (!IS_SET(perm_fails, pidx)) {
3205 if (!joint_test_params) {
3206 dxx = dgels_b[pidx * cur_sample_valid_ct + 1];
3207 dyy = sqrt(regression_results[pidx * param_ctx_m1]);
3208 dxx = fabs(dxx / dyy);
3209 if (dxx > stat_high) {
3210 success_2incr += 2;
3211 } else if (dxx > stat_low) {
3212 success_2incr++;
3213 }
3214 } else {
3215 dxx = regression_results[(pidx + 1) * param_ctx_m1 - 1];
3216 if (dxx > stat_high) {
3217 success_2incr += 2;
3218 } else if (dxx > stat_low) {
3219 success_2incr++;
3220 } else if (dxx == -9) {
3221 perm_fail_ct++;
3222 }
3223 }
3224 if (results[pidx] < dxx) {
3225 results[pidx] = dxx;
3226 }
3227 if (msa_ptr) {
3228 *msa_ptr++ = dxx;
3229 }
3230 } else if (msa_ptr) {
3231 *msa_ptr++ = -9;
3232 }
3233 }
3234 perm_2success_ct[marker_idx] += success_2incr;
3235 if (perm_fail_ct) {
3236 perm_fail_cts[marker_idx] += perm_fail_ct;
3237 }
3238 }
3239 THREAD_RETURN;
3240 }
3241 #endif
3242
3243 THREAD_RET_TYPE glm_logistic_maxt_thread(void* arg) {
3244 uintptr_t tidx = (uintptr_t)arg;
3245 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
3246 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
3247 uintptr_t perm_vec_ct = g_perm_vec_ct;
3248 uint32_t pidx_offset = g_perms_done;
3249 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
3250 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
3251 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
3252 uintptr_t* loadbuf = g_loadbuf;
3253 uint32_t* adapt_m_table = &(g_adapt_m_table[marker_bidx]);
3254 uintptr_t* perm_vecs = g_perm_vecs;
3255 uintptr_t perm_vec_ctcl8m = round_up_pow2(perm_vec_ct, CACHELINE_DBL);
3256 double* __restrict__ results = &(g_maxt_thread_results[perm_vec_ctcl8m * tidx]);
3257 unsigned char* __restrict__ perm_adapt_stop = g_perm_adapt_stop;
3258 uint32_t* __restrict__ perm_fail_cts = g_perm_attempt_ct;
3259 uint32_t* __restrict__ perm_2success_ct = g_perm_2success_ct;
3260 uintptr_t* joint_test_params = g_joint_test_params;
3261 double* __restrict__ orig_stats = g_orig_stats;
3262 uintptr_t cur_param_ct = g_cur_param_ct;
3263 uintptr_t cur_param_cta4 = round_up_pow2(cur_param_ct, 4);
3264 uintptr_t cur_constraint_ct = g_cur_constraint_ct;
3265 uint32_t coding_flags = g_coding_flags;
3266 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
3267 uintptr_t interaction_start_idx = g_interaction_start_idx;
3268 uintptr_t sex_start_idx = g_sex_start_idx;
3269 uintptr_t* active_params = g_active_params;
3270 uintptr_t* haploid_params = g_haploid_params;
3271 uint32_t include_sex = g_include_sex;
3272 uint32_t male_x_01 = g_male_x_01;
3273 uintptr_t perm_batch_max = g_perm_batch_max;
3274 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
3275 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
3276 float* fixed_covars_cov_major = g_fixed_covars_cov_major_f;
3277 double* constraints_con_major = g_constraints_con_major;
3278 double* msa_ptr = nullptr;
3279 float* cur_covars_cov_major = g_logistic_mt[tidx].cur_covars_cov_major;
3280 float* coef = g_logistic_mt[tidx].coef;
3281 float* pp = g_logistic_mt[tidx].pp;
3282 float* sample_1d_buf = g_logistic_mt[tidx].sample_1d_buf;
3283 float* pheno_buf = g_logistic_mt[tidx].pheno_buf;
3284 float* param_1d_buf = g_logistic_mt[tidx].param_1d_buf;
3285 float* param_1d_buf2 = g_logistic_mt[tidx].param_1d_buf2;
3286 float* param_2d_buf = g_logistic_mt[tidx].param_2d_buf;
3287 float* param_2d_buf2 = g_logistic_mt[tidx].param_2d_buf2;
3288 float* regression_results = g_logistic_mt[tidx].regression_results;
3289 double* param_1d_dbuf = g_logistic_mt[tidx].param_1d_dbuf;
3290 double* param_2d_dbuf = g_logistic_mt[tidx].param_2d_dbuf;
3291 double* param_2d_dbuf2 = g_logistic_mt[tidx].param_2d_dbuf2;
3292 double* param_df_dbuf = g_logistic_mt[tidx].param_df_dbuf;
3293 MATRIX_INVERT_BUF1_TYPE* mi_buf = g_logistic_mt[tidx].mi_buf;
3294 double* df_df_dbuf = g_logistic_mt[tidx].df_df_dbuf;
3295 double* df_dbuf = g_logistic_mt[tidx].df_dbuf;
3296 uintptr_t* perm_fails = g_logistic_mt[tidx].perm_fails;
3297 uintptr_t* loadbuf_ptr;
3298 uintptr_t cur_missing_ct;
3299 uintptr_t cur_sample_valid_ct;
3300 uintptr_t pidx;
3301 uintptr_t param_ctx_m1;
3302 uint32_t marker_idx;
3303 uint32_t success_2incr;
3304 uint32_t perm_fail_ct;
3305 double stat_high;
3306 double stat_low;
3307 double dxx;
3308 if (cur_constraint_ct) {
3309 param_ctx_m1 = cur_param_ct;
3310 } else {
3311 param_ctx_m1 = cur_param_ct - 1;
3312 }
3313 if (tidx + 1 == g_assoc_thread_ct) {
3314 marker_bceil = g_block_diff;
3315 }
3316 memcpy(results, &(g_maxt_extreme_stat[pidx_offset]), perm_vec_ct * sizeof(double));
3317 for (; marker_bidx < marker_bceil; marker_bidx++) {
3318 marker_idx = *adapt_m_table++;
3319 if (perm_adapt_stop[marker_idx]) {
3320 if (g_mperm_save_all && (perm_batch_max != perm_vec_ct)) {
3321 msa_ptr = &(g_mperm_save_all[marker_idx * perm_vec_ct]);
3322 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3323 *msa_ptr++ = -9;
3324 }
3325 }
3326 continue;
3327 }
3328 if (g_mperm_save_all) {
3329 msa_ptr = &(g_mperm_save_all[marker_idx * perm_vec_ct]);
3330 }
3331 stat_high = orig_stats[marker_idx] + EPSILON;
3332 stat_low = orig_stats[marker_idx] - EPSILON;
3333 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
3334 cur_missing_ct = glm_fill_design_float(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major);
3335 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
3336 success_2incr = 0;
3337 // todo: try better starting position
3338 fill_float_zero(cur_param_cta4 * perm_vec_ct, coef);
3339 perm_fail_ct = glm_logistic(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, 1, loadbuf_ptr, cur_covars_cov_major, perm_vecs, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, cur_constraint_ct, constraints_con_major, param_1d_dbuf, param_2d_dbuf, param_2d_dbuf2, param_df_dbuf, df_df_dbuf, mi_buf, df_dbuf, perm_fails);
3340 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3341 if (!IS_SET(perm_fails, pidx)) {
3342 if (!joint_test_params) {
3343 dxx = (double)coef[pidx * cur_param_cta4 + 1];
3344 dxx *= dxx;
3345 dxx /= (double)regression_results[pidx * param_ctx_m1];
3346 printf("coef: %g denom: %g stat: %g\n", coef[pidx * cur_param_cta4 + 1], regression_results[pidx * param_ctx_m1], dxx);
3347 if (dxx > stat_high) {
3348 success_2incr += 2;
3349 } else if (dxx > stat_low) {
3350 success_2incr++;
3351 }
3352 } else {
3353 dxx = (double)regression_results[(pidx + 1) * param_ctx_m1 - 1];
3354 if (dxx > stat_high) {
3355 success_2incr += 2;
3356 } else if (dxx > stat_low) {
3357 success_2incr++;
3358 } else if (dxx == -9) {
3359 perm_fail_ct++;
3360 }
3361 }
3362 if (results[pidx] < dxx) {
3363 results[pidx] = dxx;
3364 }
3365 if (msa_ptr) {
3366 *msa_ptr++ = dxx;
3367 }
3368 } else if (msa_ptr) {
3369 *msa_ptr++ = -9;
3370 }
3371 }
3372 perm_2success_ct[marker_idx] += success_2incr;
3373 if (perm_fail_ct) {
3374 perm_fail_cts[marker_idx] += perm_fail_ct;
3375 }
3376 }
3377 THREAD_RETURN;
3378 }
3379
3380 #ifndef NOLAPACK
3381 THREAD_RET_TYPE glm_linear_set_thread(void* arg) {
3382 // Simplified version of what glm_linear_maxt_thread() does.
3383 uintptr_t tidx = (uintptr_t)arg;
3384 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
3385 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
3386 uintptr_t perm_vec_ct = g_perm_vec_ct;
3387 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
3388 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
3389 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
3390 uintptr_t* loadbuf = g_loadbuf;
3391 double* perm_pmajor = g_perm_pmajor;
3392 double pheno_sum_base = g_pheno_sum;
3393 double pheno_ssq_base = g_pheno_ssq;
3394 uintptr_t cur_param_ct = g_cur_param_ct;
3395 uintptr_t param_ct_m1 = cur_param_ct - 1;
3396 char dgels_trans = 'N';
3397 __CLPK_integer dgels_n = (int32_t)((uint32_t)cur_param_ct);
3398 __CLPK_integer dgels_lwork = g_dgels_lwork;
3399 uint32_t standard_beta = g_standard_beta;
3400 uint32_t coding_flags = g_coding_flags;
3401 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
3402 uintptr_t interaction_start_idx = g_interaction_start_idx;
3403 uintptr_t sex_start_idx = g_sex_start_idx;
3404 uintptr_t* active_params = g_active_params;
3405 uintptr_t* haploid_params = g_haploid_params;
3406 uint32_t include_sex = g_include_sex;
3407 uint32_t male_x_01 = g_male_x_01;
3408 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
3409 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
3410 double* fixed_covars_cov_major = g_fixed_covars_cov_major;
3411 double* param_2d_buf = g_linear_mt[tidx].param_2d_buf;
3412 double* param_2d_buf2 = g_linear_mt[tidx].param_2d_buf2;
3413 MATRIX_INVERT_BUF1_TYPE* mi_buf = g_linear_mt[tidx].mi_buf;
3414 double* cur_covars_cov_major = g_linear_mt[tidx].cur_covars_cov_major;
3415 double* cur_covars_sample_major = g_linear_mt[tidx].cur_covars_sample_major;
3416 uintptr_t* perm_fails = g_linear_mt[tidx].perm_fails;
3417 double* dgels_a = g_linear_mt[tidx].dgels_a;
3418 double* dgels_b = g_linear_mt[tidx].dgels_b;
3419 double* dgels_work = g_linear_mt[tidx].dgels_work;
3420 double* regression_results = g_linear_mt[tidx].regression_results;
3421 double* msa_ptr;
3422 double* dptr;
3423 uintptr_t* loadbuf_ptr;
3424 uintptr_t cur_missing_ct;
3425 uintptr_t cur_sample_valid_ct;
3426 uintptr_t pidx;
3427 uintptr_t sample_idx;
3428 uint32_t perm_fail_ct;
3429 __CLPK_integer dgels_m;
3430 __CLPK_integer dgels_nrhs;
3431 __CLPK_integer dgels_ldb;
3432 __CLPK_integer dgels_info;
3433 double dxx;
3434 double dyy;
3435 double dzz;
3436 if (tidx + 1 == g_assoc_thread_ct) {
3437 marker_bceil = g_block_diff;
3438 }
3439 for (; marker_bidx < marker_bceil; marker_bidx++) {
3440 msa_ptr = &(g_mperm_save_all[marker_bidx * perm_vec_ct]);
3441 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
3442 cur_missing_ct = glm_fill_design(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major, cur_covars_sample_major, standard_beta);
3443 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
3444 dgels_m = (int32_t)((uint32_t)cur_sample_valid_ct);
3445 dgels_ldb = dgels_m;
3446 dptr = dgels_b;
3447 memcpy(dgels_a, cur_covars_cov_major, cur_param_ct * cur_sample_valid_ct * sizeof(double));
3448 if (!cur_missing_ct) {
3449 memcpy(dgels_b, perm_pmajor, perm_vec_ct * sample_valid_ct * sizeof(double));
3450 } else {
3451 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3452 copy_when_nonmissing(loadbuf_ptr, (char*)(&(perm_pmajor[pidx * sample_valid_ct])), sizeof(double), sample_valid_ct, cur_missing_ct, (char*)(&(dgels_b[pidx * cur_sample_valid_ct])));
3453 if (standard_beta) {
3454 dxx = 0;
3455 dyy = 0;
3456 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
3457 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
3458 dzz = *dptr++;
3459 dxx += dzz;
3460 dyy += dzz * dzz;
3461 }
3462 dptr = &(dgels_b[pidx * cur_sample_valid_ct]);
3463 dzz = dxx / ((double)((intptr_t)cur_sample_valid_ct));
3464 dyy = sqrt(((double)((intptr_t)(cur_sample_valid_ct - 1))) / (dyy - dxx * dzz));
3465 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
3466 *dptr = ((*dptr) - dzz) * dyy;
3467 dptr++;
3468 }
3469 }
3470 }
3471 }
3472 dgels_nrhs = (int32_t)((uint32_t)perm_vec_ct);
3473 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
3474 glm_linear(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, loadbuf_ptr, standard_beta, pheno_sum_base, pheno_ssq_base, cur_covars_cov_major, cur_covars_sample_major, perm_pmajor, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, 0, nullptr, nullptr, nullptr, nullptr, nullptr, &perm_fail_ct, perm_fails);
3475 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3476 if (!IS_SET(perm_fails, pidx)) {
3477 dxx = fabs(dgels_b[pidx * cur_sample_valid_ct + 1] / sqrt(regression_results[pidx * param_ct_m1]));
3478 } else {
3479 dxx = -9;
3480 }
3481 *msa_ptr++ = dxx;
3482 }
3483 }
3484 THREAD_RETURN;
3485 }
3486 #endif
3487
3488 THREAD_RET_TYPE glm_logistic_set_thread(void* arg) {
3489 // Simplified version of what glm_logistic_maxt_thread() does.
3490 uintptr_t tidx = (uintptr_t)arg;
3491 uintptr_t sample_valid_ct = g_perm_pheno_nm_ct;
3492 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
3493 uintptr_t perm_vec_ct = g_perm_vec_ct;
3494 uintptr_t marker_blocks = g_block_diff / CACHELINE_INT32;
3495 uint32_t marker_bidx = CACHELINE_INT32 * ((((uint64_t)tidx) * marker_blocks) / g_assoc_thread_ct);
3496 uint32_t marker_bceil = CACHELINE_INT32 * ((((uint64_t)(tidx + 1)) * marker_blocks) / g_assoc_thread_ct);
3497 uintptr_t* loadbuf = g_loadbuf;
3498 uintptr_t* perm_vecs = g_perm_vecs;
3499 uintptr_t cur_param_ct = g_cur_param_ct;
3500 uintptr_t param_ct_m1 = cur_param_ct - 1;
3501 uintptr_t cur_param_cta4 = round_up_pow2(cur_param_ct, 4);
3502 uint32_t coding_flags = g_coding_flags;
3503 uintptr_t condition_list_start_idx = g_condition_list_start_idx;
3504 uintptr_t interaction_start_idx = g_interaction_start_idx;
3505 uintptr_t sex_start_idx = g_sex_start_idx;
3506 uintptr_t* active_params = g_active_params;
3507 uintptr_t* haploid_params = g_haploid_params;
3508 uint32_t include_sex = g_include_sex;
3509 uint32_t male_x_01 = g_male_x_01;
3510 uintptr_t* sex_male_collapsed = g_sex_male_collapsed;
3511 uint32_t is_nonx_haploid = g_min_ploidy_1 && (!g_is_x);
3512 float* fixed_covars_cov_major = g_fixed_covars_cov_major_f;
3513 float* cur_covars_cov_major = g_logistic_mt[tidx].cur_covars_cov_major;
3514 float* coef = g_logistic_mt[tidx].coef;
3515 float* pp = g_logistic_mt[tidx].pp;
3516 float* sample_1d_buf = g_logistic_mt[tidx].sample_1d_buf;
3517 float* pheno_buf = g_logistic_mt[tidx].pheno_buf;
3518 float* param_1d_buf = g_logistic_mt[tidx].param_1d_buf;
3519 float* param_1d_buf2 = g_logistic_mt[tidx].param_1d_buf2;
3520 float* param_2d_buf = g_logistic_mt[tidx].param_2d_buf;
3521 float* param_2d_buf2 = g_logistic_mt[tidx].param_2d_buf2;
3522 float* regression_results = g_logistic_mt[tidx].regression_results;
3523 uintptr_t* perm_fails = g_logistic_mt[tidx].perm_fails;
3524 uintptr_t* loadbuf_ptr;
3525 double* msa_ptr;
3526 uintptr_t cur_missing_ct;
3527 uintptr_t cur_sample_valid_ct;
3528 uintptr_t pidx;
3529 double dxx;
3530 if (tidx + 1 == g_assoc_thread_ct) {
3531 marker_bceil = g_block_diff;
3532 }
3533 for (; marker_bidx < marker_bceil; marker_bidx++) {
3534 msa_ptr = &(g_mperm_save_all[marker_bidx * perm_vec_ct]);
3535 loadbuf_ptr = &(loadbuf[marker_bidx * sample_valid_ctv2]);
3536 cur_missing_ct = glm_fill_design_float(loadbuf_ptr, fixed_covars_cov_major, sample_valid_ct, cur_param_ct, coding_flags, condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, include_sex, male_x_01, sex_male_collapsed, is_nonx_haploid, cur_covars_cov_major);
3537 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
3538 // todo: try better starting position
3539 fill_float_zero(cur_param_cta4 * perm_vec_ct, coef);
3540 glm_logistic(perm_vec_ct, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, 1, loadbuf_ptr, cur_covars_cov_major, perm_vecs, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, perm_fails);
3541 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
3542 if (!IS_SET(perm_fails, pidx)) {
3543 dxx = (double)coef[pidx * cur_param_cta4 + 1];
3544 dxx *= dxx;
3545 dxx /= (double)regression_results[pidx * param_ct_m1];
3546 } else {
3547 dxx = -9;
3548 }
3549 *msa_ptr++ = dxx;
3550 }
3551 }
3552 THREAD_RETURN;
3553 }
3554
3555 int32_t glm_common_init(FILE* bedfile, uintptr_t bed_offset, uint32_t glm_modifier, uint32_t standard_beta, uint32_t glm_xchr_model, Range_list* parameters_range_list_ptr, Range_list* tests_range_list_ptr, uint32_t mtest_adjust, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude, uintptr_t marker_ct, char* marker_ids, uintptr_t max_marker_id_len, uintptr_t max_marker_allele_len, uintptr_t* marker_reverse, char* condition_mname, char* condition_fname, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t sample_ct, uintptr_t* sample_exclude, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, uintptr_t covar_ct, char* covar_names, uintptr_t max_covar_name_len, uintptr_t* covar_nm, double* covar_d, uintptr_t* sex_nm, uintptr_t* sex_male, uint32_t hh_or_mt_exists, uint32_t do_perms, uint32_t is_set_test, uint32_t* perm_batch_size_ptr, uintptr_t* max_param_name_len_ptr, uintptr_t* np_diploid_ptr, uintptr_t* condition_ct_ptr, uintptr_t* np_sex_ptr, uint32_t* marker_initial_ct_ptr, uint32_t* sex_covar_everywhere_ptr, uint32_t* variation_in_sex_ptr, uint32_t* x_sex_interaction_ptr, uintptr_t* constraint_ct_max_ptr, uintptr_t* param_idx_end_ptr, uintptr_t** loadbuf_raw_ptr, uintptr_t** load_mask_ptr, uintptr_t** sex_male_collapsed_ptr, uintptr_t** sample_include2_ptr, uintptr_t** sample_male_include2_ptr, uintptr_t** active_params_ptr, uintptr_t** haploid_params_ptr, uint32_t** condition_uidxs_ptr, char** writebuf_ptr, uintptr_t* sample_valid_ct_ptr, uintptr_t* param_ctx_max_ptr, uintptr_t* param_ctl_max_ptr, uintptr_t* condition_list_start_idx_ptr, uintptr_t* covar_start_idx_ptr, uintptr_t* interaction_start_idx_ptr, uintptr_t* sex_start_idx_ptr, uintptr_t* np_base_ptr, uintptr_t* param_ct_max_ptr) {
3556 unsigned char* bigstack_end_mark = g_bigstack_end;
3557 uintptr_t unfiltered_sample_ctl = BITCT_TO_WORDCT(unfiltered_sample_ct);
3558 uintptr_t unfiltered_sample_ctv2 = 2 * unfiltered_sample_ctl;
3559 uintptr_t sample_uidx = 0;
3560 uintptr_t max_param_name_len = 2;
3561 uintptr_t np_base_raw = 2; // intercept, additive effect
3562 uintptr_t np_diploid_raw = 0; // genotypic, hethom
3563 uintptr_t np_sex_raw = 0; // X-only sex covariate, sex-dosage interaction
3564 uintptr_t np_diploid = 0;
3565 uintptr_t constraint_ct_max = 0;
3566 uintptr_t condition_ct = 0;
3567 uintptr_t np_sex = 0;
3568 uintptr_t param_idx_end = 2;
3569 uintptr_t* load_mask = nullptr;
3570 uintptr_t* sample_include2 = nullptr;
3571 uintptr_t* sample_male_include2 = nullptr;
3572 uint32_t* condition_uidxs = nullptr;
3573 uint32_t covar_interactions = (glm_modifier / GLM_INTERACTION) & 1;
3574 uint32_t genotypic = glm_modifier & GLM_GENOTYPIC;
3575 uint32_t genotypic_or_hethom = (glm_modifier & (GLM_GENOTYPIC | GLM_HETHOM))? 1 : 0;
3576 uint32_t marker_initial_ct = marker_ct;
3577 uint32_t slen_add = 0;
3578 uint32_t sex_covar_everywhere = glm_modifier & GLM_SEX;
3579 uint32_t x_sex_interaction = (glm_xchr_model == 3);
3580 uint32_t x_present = (chrom_info_ptr->xymt_codes[X_OFFSET] != -2) && is_set(chrom_info_ptr->chrom_mask, chrom_info_ptr->xymt_codes[X_OFFSET]);
3581 uint32_t hide_covar = glm_modifier & GLM_HIDE_COVAR;
3582 uint32_t variation_in_sex = 0; // zero if no-x-sex specified
3583 int32_t retval = 0;
3584 uintptr_t* loadbuf_raw;
3585 uintptr_t* sex_male_collapsed;
3586 uintptr_t* active_params;
3587 uintptr_t* haploid_params;
3588 uintptr_t sample_valid_ct;
3589 uintptr_t sample_valid_ctv2;
3590 uintptr_t sample_uidx_stop;
3591 uintptr_t sample_idx;
3592 uintptr_t param_raw_ct_max;
3593 uintptr_t param_raw_ctp2l; // two extra bits for '--linear sex interaction'
3594 uintptr_t param_ctx_max;
3595 uintptr_t param_ctl_max;
3596 uintptr_t condition_list_start_idx;
3597 uintptr_t covar_start_idx;
3598 uintptr_t interaction_start_idx;
3599 uintptr_t sex_start_idx;
3600 uintptr_t np_base;
3601 uintptr_t param_ct_max;
3602 uintptr_t param_idx;
3603 uint32_t slen;
3604 uint32_t uii;
3605 uint32_t ujj;
3606 g_joint_test_params = nullptr;
3607 if (max_marker_allele_len > MAXLINELEN) {
3608 if (bigstack_alloc_c(max_marker_allele_len + MAXLINELEN, writebuf_ptr)) {
3609 goto glm_common_init_ret_NOMEM;
3610 }
3611 } else {
3612 *writebuf_ptr = g_textbuf;
3613 }
3614 g_standard_beta = standard_beta;
3615 g_coding_flags = glm_modifier & (GLM_HETHOM | GLM_DOMINANT | GLM_RECESSIVE);
3616 g_include_sex = 0;
3617 g_male_x_01 = 0;
3618 if (!glm_xchr_model) {
3619 if (is_set(chrom_info_ptr->haploid_mask, 0)) {
3620 logerrprint("Error: --xchr-model 0 cannot be used with haploid genomes.\n");
3621 goto glm_common_init_ret_INVALID_CMDLINE;
3622 }
3623 uii = count_non_autosomal_markers(chrom_info_ptr, marker_exclude, 1, 1);
3624 if (uii) {
3625 if (is_set_test) {
3626 logerrprint("Error: --linear/--logistic set-test cannot be used with --xchr-model 0.\n");
3627 goto glm_common_init_ret_INVALID_CMDLINE;
3628 }
3629 LOGPRINTF("Excluding %u nonautosomal variant%s from --linear/--logistic analysis\n(--xchr-model 0).\n", uii, (uii == 1)? "" : "s");
3630 marker_initial_ct -= uii;
3631 if (!marker_initial_ct) {
3632 logerrprint("Error: No variants remaining for --linear/--logistic analysis.\n");
3633 goto glm_common_init_ret_INVALID_CMDLINE;
3634 }
3635 }
3636 }
3637 if (glm_init_load_mask(sample_exclude, pheno_nm, covar_nm, sample_ct, unfiltered_sample_ctv2, &load_mask)) {
3638 goto glm_common_init_ret_NOMEM;
3639 }
3640 if (bigstack_alloc_ul(unfiltered_sample_ctv2, &loadbuf_raw)) {
3641 goto glm_common_init_ret_NOMEM;
3642 }
3643 loadbuf_raw[unfiltered_sample_ctv2 - 2] = 0;
3644 loadbuf_raw[unfiltered_sample_ctv2 - 1] = 0;
3645 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
3646 if (condition_mname || condition_fname) {
3647 // temporary allocation of unfiltered sample_include2 and
3648 // sample_male_include2 for glm_scan_conditions()
3649 if (hh_or_mt_exists & (Y_FIX_NEEDED | NXMHH_EXISTS)) {
3650 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_include2)) {
3651 goto glm_common_init_ret_NOMEM;
3652 }
3653 fill_quatervec_55(unfiltered_sample_ct, sample_include2);
3654 }
3655 if (hh_or_mt_exists & (XMHH_EXISTS | Y_FIX_NEEDED)) {
3656 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_male_include2)) {
3657 goto glm_common_init_ret_NOMEM;
3658 }
3659 init_quaterarr_from_bitarr(sex_male, unfiltered_sample_ct, sample_male_include2);
3660 }
3661 retval = glm_scan_conditions(condition_mname, condition_fname, unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, chrom_info_ptr, hh_or_mt_exists, loadbuf_raw, bedfile, bed_offset, unfiltered_sample_ct, sex_male, load_mask, &sample_valid_ct, &condition_ct, &condition_uidxs, sample_include2, sample_male_include2);
3662 if (retval) {
3663 goto glm_common_init_ret_1;
3664 }
3665 bigstack_end_reset(bigstack_end_mark);
3666
3667 // need to set to null for next alloc_collapsed_haploid_filters() call to
3668 // work properly
3669 sample_include2 = nullptr;
3670 sample_male_include2 = nullptr;
3671 np_base_raw += condition_ct * (1 + covar_interactions);
3672 }
3673 np_base_raw += covar_ct * (1 + covar_interactions);
3674 if (!((glm_modifier & GLM_NO_X_SEX) || ((!sex_covar_everywhere) && (!x_present)))) {
3675 sample_uidx = 0;
3676 sample_idx = 0;
3677 uii = 2;
3678 // slight change from PLINK 1.07: missing sex no longer counts as female
3679 // when both --allow-no-sex and --sex are active (--linear/--logistic
3680 // normally throws out all samples missing a covariate, so we shouldn't
3681 // make an exception for sex; --allow-no-sex may still have an effect on
3682 // other analyses in the current run)
3683 //
3684 // todo: implement this change for --allow-no-sex without --sex as well.
3685 do {
3686 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
3687 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
3688 sample_idx += sample_uidx_stop - sample_uidx;
3689 do {
3690 if (IS_SET(sex_nm, sample_uidx)) {
3691 ujj = is_set(sex_male, sample_uidx);
3692 if (uii == ujj) {
3693 variation_in_sex = 1;
3694 sample_idx = sample_valid_ct;
3695 break;
3696 }
3697 uii = 1 - ujj;
3698 }
3699 } while (++sample_uidx < sample_uidx_stop);
3700 } while (sample_idx < sample_valid_ct);
3701 if (variation_in_sex) {
3702 if (sex_covar_everywhere) {
3703 np_base_raw += 1 + covar_interactions;
3704 if (covar_interactions) {
3705 np_diploid_raw = genotypic_or_hethom;
3706 }
3707 bitvec_and(sex_nm, unfiltered_sample_ctl, load_mask);
3708 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
3709 } else {
3710 np_sex_raw = 1;
3711 if (covar_interactions) {
3712 np_sex_raw += 1 + genotypic_or_hethom;
3713 }
3714 }
3715 if (x_sex_interaction) {
3716 if (covar_interactions) {
3717 logprint("Note: Ignoring --xchr-model 3 since it's redundant with --linear\n'interaction' modifier.\n");
3718 x_sex_interaction = 0;
3719 } else {
3720 np_sex_raw++;
3721 }
3722 }
3723 } else {
3724 if (sex_covar_everywhere) {
3725 LOGERRPRINTFWW("Warning: Ignoring --linear/--logistic 'sex' modifier%s since sex is%cinvariant.\n", x_sex_interaction? " and --xchr-model 3" : "", x_sex_interaction? '\n' : ' ');
3726 sex_covar_everywhere = 0;
3727 } else if (x_sex_interaction) {
3728 logerrprint("Warning: Ignoring --xchr-model 3 since sex is invariant.\n");
3729 }
3730 x_sex_interaction = 0;
3731 }
3732 }
3733 if (genotypic_or_hethom) {
3734 np_diploid_raw++;
3735 if (covar_interactions) {
3736 np_diploid_raw += condition_ct + covar_ct;
3737 }
3738 }
3739
3740 sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
3741 if (alloc_collapsed_haploid_filters(load_mask, sex_male, unfiltered_sample_ct, sample_valid_ct, hh_or_mt_exists, 1, &sample_include2, &sample_male_include2)) {
3742 goto glm_common_init_ret_NOMEM;
3743 }
3744 if (bigstack_alloc_ul(GLM_BLOCKSIZE * sample_valid_ctv2, &g_loadbuf) ||
3745 bigstack_alloc_ul(sample_valid_ctv2, &sex_male_collapsed)) {
3746 goto glm_common_init_ret_NOMEM;
3747 }
3748 for (uii = 1; uii <= GLM_BLOCKSIZE; uii++) {
3749 g_loadbuf[uii * sample_valid_ctv2 - 2] = 0;
3750 g_loadbuf[uii * sample_valid_ctv2 - 1] = 0;
3751 }
3752 copy_bitarr_subset(sex_male, load_mask, unfiltered_sample_ct, sample_valid_ct, sex_male_collapsed);
3753 param_raw_ct_max = np_base_raw + np_diploid_raw + np_sex_raw;
3754 param_raw_ctp2l = BITCT_TO_WORDCT(param_raw_ct_max + 2);
3755 if (bigstack_alloc_ul(param_raw_ctp2l, &active_params)) {
3756 goto glm_common_init_ret_NOMEM;
3757 }
3758 condition_list_start_idx = 2 + genotypic_or_hethom;
3759 covar_start_idx = condition_list_start_idx + condition_ct;
3760 interaction_start_idx = covar_start_idx + covar_ct;
3761 if (!covar_interactions) {
3762 sex_start_idx = interaction_start_idx;
3763 } else {
3764 if (genotypic_or_hethom) {
3765 sex_start_idx = interaction_start_idx * 3 - 6;
3766 } else {
3767 sex_start_idx = interaction_start_idx * 2 - 2;
3768 }
3769 }
3770 g_condition_list_start_idx = condition_list_start_idx;
3771 g_interaction_start_idx = interaction_start_idx;
3772 g_sex_start_idx = sex_start_idx;
3773 g_active_params = active_params;
3774 g_sex_male_collapsed = sex_male_collapsed;
3775
3776 if (parameters_range_list_ptr->name_ct) {
3777 fill_ulong_zero(param_raw_ctp2l, active_params);
3778 active_params[0] = 1;
3779 numeric_range_list_to_bitarr(parameters_range_list_ptr, param_raw_ct_max, 0, 1, active_params);
3780 if ((!(active_params[0] & 2)) && ((!np_diploid_raw) || (!(active_params[0] & 4))) && ((!covar_interactions) || ((!popcount_bit_idx(active_params, interaction_start_idx, sex_start_idx)) && ((!variation_in_sex) || (!popcount_bit_idx(active_params, sex_start_idx + 1, param_raw_ct_max)))))) {
3781 // force the user to explicitly use no-snp if that's their intention
3782 logerrprint("Error: --parameters must retain at least one dosage-dependent variable. To\nperform one-off regression(s), use the --linear 'no-snp' modifier instead.\n");
3783 goto glm_common_init_ret_INVALID_CMDLINE;
3784 }
3785 param_ct_max = popcount_longs(active_params, param_raw_ctp2l);
3786 if (np_diploid_raw) {
3787 np_diploid = IS_SET(active_params, 2);
3788 if (covar_interactions) {
3789 for (param_idx = interaction_start_idx + 1; param_idx < sex_start_idx; param_idx += 2) {
3790 np_diploid += IS_SET(active_params, param_idx);
3791 }
3792 }
3793 }
3794 np_base = param_ct_max - np_diploid;
3795 if (!sex_covar_everywhere) {
3796 np_sex = popcount_bit_idx(active_params, sex_start_idx, param_raw_ct_max);
3797 np_base -= np_sex;
3798 if (!np_sex) {
3799 variation_in_sex = 0;
3800 }
3801 }
3802 } else {
3803 fill_all_bits(param_raw_ct_max, active_params);
3804 param_ct_max = param_raw_ct_max;
3805 np_base = np_base_raw;
3806 np_diploid = np_diploid_raw;
3807 np_sex = np_sex_raw;
3808 }
3809 // parameter sequence:
3810 // 1. intercept
3811 // 2. allelic dosage
3812 // 3. dominance deviation
3813 // 4. --condition-list
3814 // 5. --covar
3815 // 6. interactions (if DOMDEV is present, both interactions with first
3816 // covariate occur before either interaction with the second covariate,
3817 // etc.
3818 // 7. sex
3819 // 8. sex interactions
3820 if (IS_SET(active_params, 1)) {
3821 max_param_name_len = 4;
3822 } else if (mtest_adjust) {
3823 logerrprint("Error: --adjust cannot be used when --parameters excludes the main effect.\n");
3824 goto glm_common_init_ret_INVALID_CMDLINE;
3825 }
3826 if (hide_covar) {
3827 if (genotypic_or_hethom && IS_SET(active_params, 2)) {
3828 if (IS_SET(active_params, 1)) {
3829 param_idx_end = 3;
3830 }
3831 } else if (!IS_SET(active_params, 1)) {
3832 if (tests_range_list_ptr->name_ct || (glm_modifier & GLM_TEST_ALL)) {
3833 param_idx_end = 1;
3834 } else {
3835 logerrprint("Error: 'hide-covar' modifier suppresses all output due to --parameters setting.\n");
3836 goto glm_common_init_ret_INVALID_CMDLINE;
3837 }
3838 }
3839 }
3840
3841 if (genotypic_or_hethom) {
3842 if (genotypic) {
3843 slen_add = 8; // "DOMDEVx"...
3844 } else {
3845 slen_add = 5; // "HETx"...
3846 }
3847 if (IS_SET(active_params, 2)) {
3848 max_param_name_len = slen_add - 1;
3849 }
3850 }
3851 for (uii = 0; uii < condition_ct; uii++) {
3852 if (is_set(active_params, uii + condition_list_start_idx)) {
3853 slen = strlen(&(marker_ids[condition_uidxs[uii] * max_marker_id_len]));
3854 if (max_param_name_len <= slen) {
3855 max_param_name_len = slen + 1;
3856 }
3857 }
3858 if (covar_interactions) {
3859 // ugh, special case
3860 // "CSNP"+int2str(c+1)
3861 slen = 4 + intlen(uii + 1);
3862 if (!genotypic_or_hethom) {
3863 if (is_set(active_params, interaction_start_idx + uii)) {
3864 if (max_param_name_len < slen + 5) {
3865 max_param_name_len = slen + 5;
3866 }
3867 }
3868 } else {
3869 if (is_set(active_params, interaction_start_idx + 2 * uii)) {
3870 if (max_param_name_len < slen + 5) {
3871 max_param_name_len = slen + 5;
3872 }
3873 }
3874 if (is_set(active_params, interaction_start_idx + 2 * uii + 1)) {
3875 if (max_param_name_len < slen + slen_add) {
3876 max_param_name_len = slen + slen_add;
3877 }
3878 }
3879 }
3880 }
3881 }
3882 for (uii = 0; uii < covar_ct; uii++) {
3883 slen = strlen(&(covar_names[uii * max_covar_name_len]));
3884 if (is_set(active_params, uii + covar_start_idx)) {
3885 if (max_param_name_len <= slen) {
3886 max_param_name_len = slen + 1;
3887 }
3888 }
3889 if (covar_interactions) {
3890 if (!genotypic_or_hethom) {
3891 if (is_set(active_params, interaction_start_idx + uii + condition_ct)) {
3892 if (max_param_name_len < slen + 5) {
3893 max_param_name_len = slen + 5;
3894 }
3895 }
3896 } else {
3897 if (is_set(active_params, interaction_start_idx + 2 * (uii + condition_ct))) {
3898 if (max_param_name_len < slen + 5) {
3899 max_param_name_len = slen + 5;
3900 }
3901 }
3902 if (is_set(active_params, interaction_start_idx + 2 * (uii + condition_ct) + 1)) {
3903 if (max_param_name_len < slen + slen_add) {
3904 max_param_name_len = slen + slen_add;
3905 }
3906 }
3907 }
3908 }
3909 }
3910 if (variation_in_sex) {
3911 if (is_set(active_params, sex_start_idx)) {
3912 if (max_param_name_len < 4) {
3913 max_param_name_len = 4;
3914 }
3915 }
3916 if (covar_interactions) {
3917 if (is_set(active_params, sex_start_idx + 1)) {
3918 if (max_param_name_len < 8) {
3919 max_param_name_len = 8; // "ADDxSEX", etc.
3920 }
3921 }
3922 if (genotypic_or_hethom) {
3923 if (is_set(active_params, sex_start_idx + 2)) {
3924 if (max_param_name_len < 3 + slen_add) {
3925 max_param_name_len = 3 + slen_add; // "DOMDEVxSEX", "HETxSEX"
3926 }
3927 }
3928 }
3929 } else if (x_sex_interaction) {
3930 // --xchr-model 3, use "XxSEX" name instead
3931 if (is_set(active_params, sex_start_idx + 1)) {
3932 if (max_param_name_len < 6) {
3933 max_param_name_len = 6;
3934 }
3935 } else {
3936 x_sex_interaction = 0;
3937 }
3938 }
3939 }
3940 param_ctx_max = param_ct_max;
3941 param_ctl_max = BITCT_TO_WORDCT(param_ct_max);
3942 if (bigstack_alloc_ul(param_ctl_max, &haploid_params)) {
3943 goto glm_common_init_ret_NOMEM;
3944 }
3945 g_haploid_params = haploid_params;
3946 if (genotypic_or_hethom) {
3947 fill_ulong_zero(param_ctl_max, haploid_params);
3948 ujj = np_base;
3949 for (uii = 0, param_idx = 0; uii < ujj; uii++, param_idx++) {
3950 next_set_unsafe_ck(active_params, &uii);
3951 if ((uii != 2) && ((uii < interaction_start_idx) || (!((uii - interaction_start_idx) & 1)))) {
3952 SET_BIT(param_idx, haploid_params);
3953 }
3954 }
3955 } else {
3956 fill_all_bits(param_ct_max - np_sex, haploid_params);
3957 }
3958 uii = 0;
3959 if ((genotypic_or_hethom && ((active_params[0] & 6) == 6)) || tests_range_list_ptr->name_ct || (glm_modifier & GLM_TEST_ALL)) {
3960 if (bigstack_alloc_ul(param_ctl_max, &g_joint_test_params)) {
3961 goto glm_common_init_ret_NOMEM;
3962 }
3963 fill_ulong_zero(param_ctl_max, g_joint_test_params);
3964 if (tests_range_list_ptr->name_ct) {
3965 numeric_range_list_to_bitarr(tests_range_list_ptr, param_ct_max - 1, 1, 1, g_joint_test_params);
3966 constraint_ct_max = popcount_longs(g_joint_test_params, param_ctl_max);
3967 } else if (glm_modifier & GLM_TEST_ALL) {
3968 constraint_ct_max = param_ct_max - 1;
3969 fill_bits(0, constraint_ct_max, g_joint_test_params);
3970 } else {
3971 // genotypic/hethom, neither of first two terms excluded by --parameters,
3972 // no --tests
3973 constraint_ct_max = 2;
3974 g_joint_test_params[0] = 3;
3975 uii = 1; // flag this to prevent 'interaction' permutation test
3976 }
3977 if ((constraint_ct_max > 1) || ((constraint_ct_max == 1) && (hide_covar || (covar_interactions && do_perms)))) {
3978 // "USER_2DF", etc.
3979 // Allow 1df if:
3980 // - 'hide-covar' is in effect (so only this covariate is reported on)
3981 // - and/or 'interaction' is being used with a permutation test
3982 // In the latter case, we don't stop the user from shooting themselves in
3983 // the foot with an inappropriate permutation test target; forcing them
3984 // to use --tests should prevent enough mistakes.
3985 slen = 8 + intlen(constraint_ct_max);
3986 if (max_param_name_len < slen) {
3987 max_param_name_len = slen;
3988 }
3989 param_ctx_max++;
3990 } else {
3991 bigstack_reset(g_joint_test_params);
3992 g_joint_test_params = nullptr;
3993 constraint_ct_max = 0;
3994 logerrprint("Warning: Ignoring --tests since too few parameter indices are in range.\n");
3995 }
3996 }
3997 if (covar_interactions && do_perms && ((!constraint_ct_max) || uii)) {
3998 logerrprint("Error: --linear/--logistic 'interaction' modifier cannot be used with\npermutation except with --tests.\n");
3999 goto glm_common_init_ret_INVALID_CMDLINE;
4000 }
4001 if (do_perms && (!IS_SET(active_params, 1)) && (!constraint_ct_max)) {
4002 logerrprint("Error: --linear/--logistic permutation test cannot occur when --parameters\nexcludes the main effect and no joint test is active.\n");
4003 goto glm_common_init_ret_INVALID_CMDLINE;
4004 }
4005
4006 g_perm_cluster_ct = 0;
4007 g_perm_pheno_nm_ct = sample_valid_ct;
4008 g_perms_done = 0;
4009 g_mperm_save_all = nullptr;
4010 if ((!do_perms) || is_set_test) {
4011 *perm_batch_size_ptr = 1;
4012 }
4013 *loadbuf_raw_ptr = loadbuf_raw;
4014 *load_mask_ptr = load_mask;
4015 *sex_male_collapsed_ptr = sex_male_collapsed;
4016 *constraint_ct_max_ptr = constraint_ct_max;
4017 *max_param_name_len_ptr = max_param_name_len;
4018 *np_diploid_ptr = np_diploid;
4019 *condition_ct_ptr = condition_ct;
4020 *np_sex_ptr = np_sex;
4021 *param_idx_end_ptr = param_idx_end;
4022 *marker_initial_ct_ptr = marker_initial_ct;
4023 *sex_covar_everywhere_ptr = sex_covar_everywhere;
4024 *variation_in_sex_ptr = variation_in_sex;
4025 *x_sex_interaction_ptr = x_sex_interaction;
4026 *sample_valid_ct_ptr = sample_valid_ct;
4027 *sample_include2_ptr = sample_include2;
4028 *sample_male_include2_ptr = sample_male_include2;
4029 *active_params_ptr = active_params;
4030 *haploid_params_ptr = haploid_params;
4031 *condition_uidxs_ptr = condition_uidxs;
4032 *param_ctx_max_ptr = param_ctx_max;
4033 *param_ctl_max_ptr = param_ctl_max;
4034 *condition_list_start_idx_ptr = condition_list_start_idx;
4035 *covar_start_idx_ptr = covar_start_idx;
4036 *interaction_start_idx_ptr = interaction_start_idx;
4037 *sex_start_idx_ptr = sex_start_idx;
4038 *np_base_ptr = np_base;
4039 *param_ct_max_ptr = param_ct_max;
4040 while (0) {
4041 glm_common_init_ret_NOMEM:
4042 retval = RET_NOMEM;
4043 break;
4044 glm_common_init_ret_INVALID_CMDLINE:
4045 retval = RET_INVALID_CMDLINE;
4046 break;
4047 }
4048 glm_common_init_ret_1:
4049 bigstack_end_reset(bigstack_end_mark);
4050 return retval;
4051 }
4052
4053 #ifndef NOLAPACK
4054 int32_t glm_linear_assoc_set_test(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, uint32_t glm_xchr_model, uint32_t glm_mperm_val, double pfilter, double output_min_p, uint32_t mtest_adjust, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude_orig, uintptr_t marker_ct_orig, uintptr_t* marker_exclude_mid, uintptr_t marker_ct_mid, char* marker_ids, uintptr_t max_marker_id_len, uintptr_t* marker_reverse, uintptr_t* regression_skip, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t* sex_male, Aperm_info* apip, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, uintptr_t* founder_pnm, uintptr_t* load_mask, uintptr_t* sample_include2, uintptr_t* sample_male_include2, uint32_t ld_ignore_x, uint32_t hh_exists, uint32_t hh_or_mt_exists, uint32_t perm_batch_size, Set_info* sip, uint32_t* tcnt, uintptr_t* loadbuf_raw, uintptr_t param_ct_max, uintptr_t np_base, uintptr_t np_diploid, uintptr_t np_sex, uintptr_t sample_valid_ct, uint32_t sex_covar_everywhere) {
4055 // Side effect: t-statistics in g_orig_stats[] are clobbered and replaced
4056 // with same-p-value 1df chi-square statistics. Something of this sort is
4057 // required to get the set test to work at all for --linear.
4058 // We could apply a similar procedure to xdf joint test p-values, but I'll
4059 // refrain until/unless methods developers say that's actually a worthwhile
4060 // procedure.
4061 unsigned char* bigstack_mark = g_bigstack_base;
4062 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
4063 uintptr_t cur_param_ct = 0;
4064 uintptr_t* marker_exclude = marker_exclude_mid;
4065 uintptr_t* unstopped_markers = nullptr;
4066 uintptr_t* loadbuf = g_loadbuf;
4067 uintptr_t* perm_adapt_set_unstopped = nullptr;
4068 double* orig_stats = g_orig_stats;
4069 double* sorted_chisq_buf = nullptr;
4070 uint32_t* marker_idx_to_uidx = nullptr;
4071 uint32_t* sorted_marker_idx_buf = nullptr;
4072 uint32_t* proxy_arr = nullptr;
4073 uint32_t* perm_2success_ct = nullptr;
4074 uint32_t* perm_attempt_ct = nullptr;
4075 uintptr_t marker_ct = marker_ct_mid;
4076 uintptr_t set_ct = 0;
4077 uintptr_t final_mask = get_final_mask(pheno_nm_ct);
4078 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
4079 double adaptive_ci_zt = 0.0;
4080 uint32_t max_thread_ct = g_thread_ct;
4081 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
4082 uint32_t perms_done = 0;
4083 int32_t retval = 0;
4084 unsigned char* bigstack_mark2;
4085 uintptr_t* set_incl;
4086 uintptr_t* loadbuf_ptr;
4087 double* orig_set_scores;
4088 double* chisq_pmajor;
4089 double* read_dptr;
4090 double* write_dptr;
4091 uint32_t** setdefs;
4092 uint32_t** ld_map;
4093 uintptr_t marker_ctl;
4094 uintptr_t marker_midx;
4095 uintptr_t set_idx;
4096 uintptr_t perm_vec_ct;
4097 uintptr_t pidx;
4098 uintptr_t ulii;
4099 double chisq_threshold;
4100 double dxx;
4101 double dyy;
4102 uint32_t perms_total;
4103 uint32_t max_sigset_size;
4104 uint32_t marker_unstopped_ct;
4105 uint32_t chrom_fo_idx;
4106 uint32_t chrom_end;
4107 uint32_t block_size;
4108 uint32_t block_end;
4109 uint32_t first_adapt_check;
4110 uint32_t marker_uidx;
4111 uint32_t marker_idx;
4112 uint32_t marker_idx2;
4113 uint32_t marker_bidx;
4114 uint32_t skip_ct;
4115 uint32_t uii;
4116 if (sip->set_test_lambda > 1.0) {
4117 dxx = 1.0 / sip->set_test_lambda;
4118 } else {
4119 dxx = 1.0;
4120 }
4121 for (marker_midx = 0; marker_midx < marker_ct; marker_midx++) {
4122 dyy = calc_tprob(orig_stats[marker_midx], tcnt[marker_midx]);
4123 if (dyy == 0.0) {
4124 dyy = MAX_INVERSE_CHIPROB_1DF * dxx;
4125 } else {
4126 orig_stats[marker_midx] = inverse_chiprob(dyy, 1) * dxx;
4127 }
4128 }
4129 retval = set_test_common_init(threads, bedfile, bed_offset, outname, outname_end, unfiltered_marker_ct, marker_exclude_orig, marker_ct_orig, marker_ids, max_marker_id_len, marker_reverse, orig_stats, sip, chrom_info_ptr, unfiltered_sample_ct, sex_male, founder_pnm, ld_ignore_x, hh_exists, "--linear", &marker_ct, &marker_exclude, &set_incl, &marker_idx_to_uidx, &setdefs, &set_ct, &max_sigset_size, &ld_map, &chisq_threshold, &orig_set_scores, &sorted_chisq_buf, &sorted_marker_idx_buf, &proxy_arr, &perm_adapt_set_unstopped, &perm_2success_ct, &perm_attempt_ct, &unstopped_markers);
4130 if (retval) {
4131 goto glm_linear_assoc_set_test_ret_1;
4132 }
4133 if (!set_ct) {
4134 goto glm_linear_assoc_set_test_write;
4135 }
4136 marker_ctl = BITCT_TO_WORDCT(marker_ct);
4137 if (marker_ct_mid != marker_ct) {
4138 inplace_delta_collapse_arr((char*)tcnt, sizeof(int32_t), marker_ct_mid, marker_ct, marker_exclude_mid, marker_exclude);
4139 inplace_delta_collapse_bitfield(regression_skip, marker_ct, marker_exclude_mid, marker_exclude);
4140 }
4141 if (glm_modifier & GLM_PERM) {
4142 perms_total = apip->max;
4143 first_adapt_check = (apip->min < apip->init_interval)? ((int32_t)apip->init_interval) : apip->min;
4144 adaptive_ci_zt = ltqnorm(1 - apip->beta / (2.0 * ((intptr_t)set_ct)));
4145 } else {
4146 perms_total = glm_mperm_val;
4147 first_adapt_check = perms_total + 1;
4148 }
4149 for (uii = 0; uii < set_ct; uii++) {
4150 perm_attempt_ct[uii] = perms_total;
4151 }
4152 if (max_thread_ct > perms_total) {
4153 max_thread_ct = perms_total;
4154 }
4155 if (bigstack_init_sfmtp(max_thread_ct)) {
4156 goto glm_linear_assoc_set_test_ret_NOMEM;
4157 }
4158
4159 bigstack_mark2 = g_bigstack_base;
4160 glm_linear_assoc_set_test_more_perms:
4161 bitvec_and(unstopped_markers, marker_ctl, regression_skip);
4162 bitvec_andnot(regression_skip, marker_ctl, unstopped_markers);
4163 skip_ct = popcount_longs(regression_skip, marker_ctl);
4164 marker_unstopped_ct = popcount_longs(unstopped_markers, marker_ctl);
4165
4166 if (perms_done) {
4167 uii = apip->init_interval;
4168 while (first_adapt_check <= perms_done) {
4169 first_adapt_check += (int32_t)(uii + ((int32_t)first_adapt_check) * apip->interval_slope);
4170 }
4171 }
4172 perm_vec_ct = perm_batch_size;
4173 // possible todo: split first batch to reduce adaptive overshoot
4174 if (perm_vec_ct > perms_total - perms_done) {
4175 perm_vec_ct = perms_total - perms_done;
4176 }
4177 g_perm_vec_ct = perm_vec_ct;
4178 if (perm_vec_ct >= CACHELINE_INT32 * max_thread_ct) {
4179 g_perm_generation_thread_ct = max_thread_ct;
4180 } else {
4181 g_perm_generation_thread_ct = MAXV(perm_vec_ct / CACHELINE_INT32, 1);
4182 }
4183 ulii = 0;
4184 if (!g_perm_cluster_ct) {
4185 if (spawn_threads(threads, &generate_qt_perms_pmajor_thread, g_perm_generation_thread_ct)) {
4186 goto glm_linear_assoc_set_test_ret_THREAD_CREATE_FAIL;
4187 }
4188 generate_qt_perms_pmajor_thread((void*)ulii);
4189 } else {
4190 if (spawn_threads(threads, &generate_qt_cluster_perms_pmajor_thread, g_perm_generation_thread_ct)) {
4191 goto glm_linear_assoc_set_test_ret_THREAD_CREATE_FAIL;
4192 }
4193 generate_qt_cluster_perms_pmajor_thread((void*)ulii);
4194 }
4195 join_threads(threads, g_perm_generation_thread_ct);
4196 if (bigstack_alloc_d(MODEL_BLOCKSIZE * perm_vec_ct, &g_mperm_save_all) ||
4197 bigstack_alloc_d(marker_ct * perm_vec_ct, &chisq_pmajor)) {
4198 goto glm_linear_assoc_set_test_ret_NOMEM;
4199 }
4200 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
4201 write_dptr = &(chisq_pmajor[pidx * marker_ct]);
4202 for (marker_idx = 0, marker_idx2 = 0; marker_idx < skip_ct; marker_idx++, marker_idx2++) {
4203 next_set_unsafe_ck(regression_skip, &marker_idx2);
4204 write_dptr[marker_idx2] = -9;
4205 }
4206 }
4207 chrom_fo_idx = 0xffffffffU;
4208 marker_uidx = next_unset_unsafe(marker_exclude, 0);
4209 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
4210 goto glm_linear_assoc_set_test_ret_READ_FAIL;
4211 }
4212 marker_idx = 0;
4213 marker_idx2 = 0;
4214 chrom_end = 0;
4215 do {
4216 if (marker_uidx >= chrom_end) {
4217 // exploit overflow
4218 chrom_fo_idx++;
4219 refresh_chrom_info(chrom_info_ptr, marker_uidx, &chrom_end, &chrom_fo_idx, &g_is_x, &g_is_y, &uii, &g_min_ploidy_1);
4220 g_min_ploidy_1 |= uii;
4221 g_male_x_01 = 0;
4222 if (g_is_x) {
4223 cur_param_ct = param_ct_max;
4224 if (glm_xchr_model != 2) {
4225 g_male_x_01 = 1;
4226 }
4227 } else {
4228 cur_param_ct = np_base + np_diploid;
4229 }
4230 g_cur_param_ct = cur_param_ct;
4231 g_include_sex = sex_covar_everywhere || (g_is_x && np_sex);
4232 }
4233 block_size = 0;
4234 block_end = marker_unstopped_ct - marker_idx;
4235 if (block_end > GLM_BLOCKSIZE) {
4236 block_end = GLM_BLOCKSIZE;
4237 }
4238 do {
4239 if (!IS_SET(unstopped_markers, marker_idx2)) {
4240 do {
4241 marker_uidx++;
4242 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
4243 marker_idx2++;
4244 } while ((marker_uidx < chrom_end) && (!IS_SET(unstopped_markers, marker_idx2)));
4245 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
4246 goto glm_linear_assoc_set_test_ret_READ_FAIL;
4247 }
4248 if (marker_uidx >= chrom_end) {
4249 break;
4250 }
4251 }
4252 loadbuf_ptr = &(loadbuf[block_size * sample_valid_ctv2]);
4253 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_ptr)) {
4254 goto glm_linear_assoc_set_test_ret_READ_FAIL;
4255 }
4256 if (g_min_ploidy_1 && hh_or_mt_exists) {
4257 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)loadbuf_ptr);
4258 }
4259 g_adapt_m_table[block_size] = marker_idx2++;
4260 block_size++;
4261 if (marker_idx + block_size == marker_unstopped_ct) {
4262 break;
4263 }
4264 marker_uidx++;
4265 if (IS_SET(marker_exclude, marker_uidx)) {
4266 marker_uidx = next_unset_unsafe(marker_exclude, marker_uidx);
4267 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
4268 goto glm_linear_assoc_set_test_ret_READ_FAIL;
4269 }
4270 }
4271 } while ((block_size < block_end) && (marker_uidx < chrom_end));
4272 if (!block_size) {
4273 continue;
4274 }
4275 g_block_diff = block_size;
4276
4277 g_assoc_thread_ct = block_size / CACHELINE_INT32;
4278 if (g_assoc_thread_ct > max_thread_ct) {
4279 g_assoc_thread_ct = max_thread_ct;
4280 } else if (!g_assoc_thread_ct) {
4281 g_assoc_thread_ct = 1;
4282 }
4283 ulii = 0;
4284
4285 if (spawn_threads(threads, &glm_linear_set_thread, g_assoc_thread_ct)) {
4286 goto glm_linear_assoc_set_test_ret_THREAD_CREATE_FAIL;
4287 }
4288 glm_linear_set_thread((void*)ulii);
4289 join_threads(threads, g_assoc_thread_ct);
4290
4291 // convert to equivalent chi-square stats and transpose
4292 // (conversion has to be done here since dcdflib is not thread-safe)
4293 read_dptr = g_mperm_save_all;
4294 for (marker_bidx = 0; marker_bidx < block_size; marker_bidx++) {
4295 uii = g_adapt_m_table[marker_bidx];
4296 write_dptr = &(chisq_pmajor[uii]);
4297 uii = tcnt[uii];
4298 dyy = inverse_tprob(sip->set_p, uii);
4299 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
4300 dxx = *read_dptr++;
4301 if (dxx < dyy) {
4302 dxx = -9;
4303 } else {
4304 dxx = calc_tprob(dxx, uii);
4305 if (dxx == 0.0) {
4306 dxx = MAX_INVERSE_CHIPROB_1DF;
4307 } else {
4308 dxx = inverse_chiprob(dxx, 1);
4309 }
4310 }
4311 // this is cache-unfriendly, may want to update in-place instead and
4312 // separate out the transpose
4313 write_dptr[pidx * marker_ct] = dxx;
4314 }
4315 }
4316 marker_idx += block_size;
4317 } while (marker_idx < marker_unstopped_ct);
4318 perms_done += perm_vec_ct;
4319 compute_set_scores(marker_ct, perm_vec_ct, set_ct, chisq_pmajor, orig_set_scores, sorted_chisq_buf, sorted_marker_idx_buf, proxy_arr, setdefs, ld_map, apip, chisq_threshold, adaptive_ci_zt, first_adapt_check, perms_done, sip->set_max, perm_adapt_set_unstopped, perm_2success_ct, perm_attempt_ct);
4320 bigstack_reset(bigstack_mark2);
4321 if (perms_done < perms_total) {
4322 if (glm_modifier & GLM_PERM) {
4323 if (!extract_set_union(setdefs, set_ct, perm_adapt_set_unstopped, unstopped_markers, marker_ct)) {
4324 perms_done = 0;
4325 for (set_idx = 0; set_idx < set_ct; set_idx++) {
4326 if (perms_done < perm_attempt_ct[set_idx]) {
4327 perms_done = perm_attempt_ct[set_idx];
4328 }
4329 }
4330 goto glm_linear_assoc_set_test_perms_done;
4331 }
4332 }
4333 printf("\r%u permutation%s complete.", perms_done, (perms_done != 1)? "s" : "");
4334 fflush(stdout);
4335 goto glm_linear_assoc_set_test_more_perms;
4336 }
4337 glm_linear_assoc_set_test_perms_done:
4338 putc_unlocked('\r', stdout);
4339 LOGPRINTF("%u permutation%s complete.\n", perms_done, (perms_done != 1)? "s" : "");
4340 glm_linear_assoc_set_test_write:
4341 if (glm_modifier & GLM_PERM) {
4342 memcpy(outname_end, ".assoc.linear.set.perm", 23);
4343 } else {
4344 memcpy(outname_end, ".assoc.linear.set.mperm", 24);
4345 }
4346 retval = write_set_test_results(outname, &(outname_end[17]), sip, ld_map, setdefs, set_incl, set_ct, marker_ct_orig, marker_ct, marker_idx_to_uidx, marker_ids, max_marker_id_len, perm_2success_ct, perm_attempt_ct, mtest_adjust, perm_count, pfilter, output_min_p, chisq_threshold, orig_stats, sorted_chisq_buf, sorted_marker_idx_buf, proxy_arr);
4347 while (0) {
4348 glm_linear_assoc_set_test_ret_NOMEM:
4349 retval = RET_NOMEM;
4350 break;
4351 glm_linear_assoc_set_test_ret_READ_FAIL:
4352 retval = RET_READ_FAIL;
4353 break;
4354 glm_linear_assoc_set_test_ret_THREAD_CREATE_FAIL:
4355 retval = RET_THREAD_CREATE_FAIL;
4356 break;
4357 }
4358 glm_linear_assoc_set_test_ret_1:
4359 bigstack_reset(bigstack_mark);
4360 return retval;
4361 }
4362
4363 int32_t glm_linear_assoc(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, double glm_vif_thresh, uint32_t glm_xchr_model, uint32_t glm_mperm_val, Range_list* parameters_range_list_ptr, Range_list* tests_range_list_ptr, double ci_size, double ci_zt, double pfilter, double output_min_p, uint32_t mtest_adjust, double adjust_lambda, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude_orig, uintptr_t marker_ct_orig, char* marker_ids, uintptr_t max_marker_id_len, uint32_t plink_maxsnp, uint32_t* marker_pos, char** marker_allele_ptrs, uintptr_t max_marker_allele_len, uintptr_t* marker_reverse, char* condition_mname, char* condition_fname, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t sample_ct, uintptr_t* sample_exclude, uint32_t cluster_ct, uint32_t* cluster_map, uint32_t* cluster_starts, Aperm_info* apip, uint32_t mperm_save, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, double* pheno_d, uintptr_t covar_ct, char* covar_names, uintptr_t max_covar_name_len, uintptr_t* covar_nm, double* covar_d, uintptr_t* founder_info, uintptr_t* sex_nm, uintptr_t* sex_male, uint32_t ld_ignore_x, uint32_t hh_exists, uint32_t orig_perm_batch_size, Set_info* sip) {
4364 // todo: investigate pre-orthogonalization of covariates
4365 unsigned char* bigstack_mark = g_bigstack_base;
4366 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
4367 uintptr_t unfiltered_sample_ctl = BITCT_TO_WORDCT(unfiltered_sample_ct);
4368 FILE* outfile = nullptr;
4369 FILE* outfile_msa = nullptr;
4370 uintptr_t marker_ct = marker_ct_orig;
4371 uintptr_t sample_uidx = 0;
4372 uintptr_t cur_constraint_ct = 0;
4373 uintptr_t cur_param_ct = 0;
4374 uintptr_t cur_param_ctx = 0;
4375 uint32_t perms_total = 0;
4376 uint32_t is_set_test = glm_modifier & GLM_SET_TEST;
4377 uint32_t perm_adapt_nst = (glm_modifier & GLM_PERM) && (!is_set_test);
4378 uint32_t perm_maxt_nst = (glm_modifier & GLM_MPERM) && (!is_set_test);
4379 uint32_t covar_interactions = (glm_modifier / GLM_INTERACTION) & 1;
4380 uint32_t hethom = glm_modifier & GLM_HETHOM;
4381 uint32_t standard_beta = glm_modifier & GLM_STANDARD_BETA;
4382 uint32_t genotypic_or_hethom = (glm_modifier & (GLM_GENOTYPIC | GLM_HETHOM))? 1 : 0;
4383 uint32_t do_perms = glm_modifier & (GLM_PERM | GLM_MPERM);
4384 uint32_t do_perms_nst = do_perms && (!is_set_test);
4385 uint32_t perm_batch_size = orig_perm_batch_size;
4386 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
4387 uint32_t hide_covar = glm_modifier & GLM_HIDE_COVAR;
4388 uint32_t fill_orig_chiabs = do_perms || mtest_adjust;
4389 uint32_t display_ci = (ci_size > 0);
4390 uint32_t perm_pass_idx = 0;
4391 uint32_t perm_fail_ct = 0;
4392 uint32_t pct = 0;
4393 // not useful to have more than 2 threads due to memory bus bottleneck? need
4394 // to test this, and some other multithreaded routines, on quad-core system.
4395 // if this value is changed, glm_linear_assoc_set_test value also needs to be
4396 // changed.
4397 uint32_t max_thread_ct = g_thread_ct;
4398 uint32_t hh_or_mt_exists = hh_exists;
4399 uint32_t report_intercept = glm_modifier & GLM_INTERCEPT;
4400 int32_t retval = 0;
4401 char dgels_trans = 'N';
4402 __CLPK_integer dgels_m = 0;
4403 __CLPK_integer dgels_n = 0;
4404 __CLPK_integer dgels_nrhs = 0;
4405 __CLPK_integer dgels_ldb = 0;
4406 uintptr_t* marker_exclude = marker_exclude_orig;
4407 uintptr_t* founder_pnm = nullptr;
4408 uintptr_t* regression_skip = nullptr;
4409 double* constraints_con_major = nullptr;
4410 double* orig_pvals = nullptr;
4411 uint32_t* condition_uidxs = nullptr;
4412 uint32_t* marker_idx_to_uidx = nullptr;
4413 uint32_t* tcnt = nullptr;
4414 char* cur_param_names = nullptr;
4415 char* haploid_param_names = nullptr;
4416 char* wptr_start = nullptr;
4417 double geno_map[12];
4418 uint32_t mu_table[GLM_BLOCKSIZE];
4419 char numbuf[16];
4420 uintptr_t* ulptr;
4421 double* dptr3;
4422 uintptr_t cur_word;
4423 __CLPK_integer dgels_info;
4424 double* geno_map_ptr;
4425 char* writebuf;
4426 char* param_names;
4427 const char* main_effect;
4428
4429 // linear: pval = calc_tprob(g_orig_stats[i], sample_valid_ct - param_ct)
4430 double* orig_stats_ptr;
4431
4432 char* outname_end2;
4433 char* wptr;
4434 char* wptr_start2;
4435 char* cptr;
4436 double* dptr;
4437 double* dptr2;
4438 uintptr_t* loadbuf_raw;
4439 uintptr_t* load_mask;
4440 uintptr_t* sex_male_collapsed;
4441 uintptr_t* sample_include2;
4442 uintptr_t* sample_male_include2;
4443 uintptr_t* active_params;
4444 uintptr_t* haploid_params;
4445 uintptr_t* loadbuf_ptr;
4446 uintptr_t max_param_name_len;
4447 uintptr_t np_diploid;
4448 uintptr_t condition_ct;
4449 uintptr_t constraint_ct_max;
4450 uintptr_t np_sex;
4451 uintptr_t param_idx_end;
4452 uintptr_t sample_valid_ct;
4453 uintptr_t sample_valid_ctv2;
4454 uintptr_t sample_uidx_stop;
4455 uintptr_t sample_idx;
4456 uintptr_t param_ctx_max;
4457 uintptr_t param_ctl_max;
4458 uintptr_t param_ctx_max_m1;
4459 uintptr_t condition_list_start_idx;
4460 uintptr_t covar_start_idx;
4461 uintptr_t interaction_start_idx;
4462 uintptr_t sex_start_idx;
4463 uintptr_t np_base;
4464 uintptr_t param_ct_max;
4465 uintptr_t cur_missing_ct;
4466 uintptr_t cur_sample_valid_ct;
4467 uintptr_t param_idx;
4468 uintptr_t param_idx_fixed;
4469 uintptr_t constraint_idx;
4470 uintptr_t final_mask;
4471 uintptr_t ulii;
4472 uintptr_t uljj;
4473 double* msa_ptr;
4474 double se;
4475 double zval;
4476 double pval;
4477 double dxx;
4478 double dyy;
4479 double dzz;
4480 uint32_t mperm_save_all;
4481 uint32_t marker_initial_ct;
4482 uint32_t sex_covar_everywhere;
4483 uint32_t variation_in_sex;
4484 uint32_t x_sex_interaction;
4485 uint32_t marker_unstopped_ct;
4486 uint32_t chrom_fo_idx;
4487 uint32_t chrom_end;
4488 uint32_t block_size;
4489 uint32_t block_end;
4490 uint32_t tidx;
4491 uint32_t perm_idx;
4492 uint32_t marker_uidx;
4493 uint32_t marker_uidx2;
4494 uint32_t marker_idx;
4495 uint32_t marker_idx2;
4496 uint32_t marker_idx3;
4497 uint32_t marker_bidx;
4498 uint32_t chrom_idx;
4499 uint32_t loop_end;
4500 uint32_t regression_fail;
4501 uint32_t uii;
4502 uint32_t ujj;
4503 uint32_t ukk;
4504 numbuf[0] = ' ';
4505 if ((chrom_info_ptr->xymt_codes[MT_OFFSET] != -2) && is_set(chrom_info_ptr->chrom_mask, chrom_info_ptr->xymt_codes[MT_OFFSET])) {
4506 hh_or_mt_exists |= NXMHH_EXISTS;
4507 }
4508 if (is_set_test) {
4509 if (bigstack_alloc_ul(unfiltered_sample_ctl, &founder_pnm)) {
4510 goto glm_linear_assoc_ret_NOMEM;
4511 }
4512 memcpy(founder_pnm, pheno_nm, unfiltered_sample_ctl * sizeof(intptr_t));
4513 bitvec_and(founder_info, unfiltered_sample_ctl, founder_pnm);
4514 if (extract_set_union_unfiltered(sip, nullptr, unfiltered_marker_ct, marker_exclude_orig, &marker_exclude, &marker_ct)) {
4515 goto glm_linear_assoc_ret_NOMEM;
4516 }
4517 if (glm_modifier & GLM_PERM) {
4518 if (orig_perm_batch_size > apip->max) {
4519 orig_perm_batch_size = apip->max;
4520 }
4521 } else {
4522 if (orig_perm_batch_size > glm_mperm_val) {
4523 orig_perm_batch_size = glm_mperm_val;
4524 }
4525 }
4526 }
4527 retval = glm_common_init(bedfile, bed_offset, glm_modifier, standard_beta, glm_xchr_model, parameters_range_list_ptr, tests_range_list_ptr, mtest_adjust, unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, max_marker_allele_len, marker_reverse, condition_mname, condition_fname, chrom_info_ptr, unfiltered_sample_ct, sample_ct, sample_exclude, pheno_nm_ct, pheno_nm, covar_ct, covar_names, max_covar_name_len, covar_nm, covar_d, sex_nm, sex_male, hh_or_mt_exists, do_perms, is_set_test, &perm_batch_size, &max_param_name_len, &np_diploid, &condition_ct, &np_sex, &marker_initial_ct, &sex_covar_everywhere, &variation_in_sex, &x_sex_interaction, &constraint_ct_max, &param_idx_end, &loadbuf_raw, &load_mask, &sex_male_collapsed, &sample_include2, &sample_male_include2, &active_params, &haploid_params, &condition_uidxs, &writebuf, &sample_valid_ct, &param_ctx_max, &param_ctl_max, &condition_list_start_idx, &covar_start_idx, &interaction_start_idx, &sex_start_idx, &np_base, &param_ct_max);
4528 if (retval) {
4529 goto glm_linear_assoc_ret_1;
4530 }
4531 if (sample_valid_ct <= param_ct_max) {
4532 logerrprint("Warning: Skipping --linear since # variables >= # samples.\n");
4533 if (pheno_nm_ct > param_ct_max) {
4534 logerrprint("(Check your covariates--all samples with at least one missing covariate are\nexcluded from this analysis.)\n");
4535 }
4536 goto glm_linear_assoc_ret_1;
4537 }
4538 sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
4539 final_mask = get_final_mask(sample_valid_ct);
4540 param_ctx_max_m1 = param_ctx_max - 1;
4541 if (bigstack_alloc_d(marker_initial_ct, &g_orig_stats) ||
4542 bigstack_alloc_c(param_ctx_max * max_param_name_len, &param_names) ||
4543 bigstack_alloc_d((variation_in_sex + interaction_start_idx - condition_list_start_idx) * sample_valid_ct, &g_fixed_covars_cov_major) ||
4544 bigstack_alloc_ui(marker_initial_ct, &g_nm_cts)) {
4545 goto glm_linear_assoc_ret_NOMEM;
4546 }
4547 if (!is_set_test) {
4548 // use this array to track regression failures even in max(T) case
4549 if (bigstack_calloc_uc(round_up_pow2(marker_initial_ct, BYTECT), &g_perm_adapt_stop)) {
4550 goto glm_linear_assoc_ret_NOMEM;
4551 }
4552 } else {
4553 g_perm_adapt_stop = nullptr;
4554 if (bigstack_calloc_ul(BITCT_TO_WORDCT(marker_initial_ct), &regression_skip)) {
4555 goto glm_linear_assoc_ret_NOMEM;
4556 }
4557 }
4558
4559 param_idx = 1;
4560 if (glm_modifier & GLM_RECESSIVE) {
4561 main_effect = glm_main_effects;
4562 } else if (glm_modifier & GLM_DOMINANT) {
4563 main_effect = &(glm_main_effects[4]);
4564 } else if (hethom) {
4565 main_effect = &(glm_main_effects[8]);
4566 } else {
4567 main_effect = &(glm_main_effects[12]);
4568 }
4569 if (IS_SET(active_params, 1)) {
4570 memcpy(&(param_names[max_param_name_len]), main_effect, 4);
4571 param_idx++;
4572 }
4573 if (genotypic_or_hethom && IS_SET(active_params, 2)) {
4574 if (hethom) {
4575 memcpy(&(param_names[param_idx * max_param_name_len]), "HET", 4);
4576 } else {
4577 memcpy(&(param_names[param_idx * max_param_name_len]), "DOMDEV", 7);
4578 }
4579 param_idx++;
4580 }
4581 // 0..3: diploid chromosomes, X chromosome female
4582 // 4..7: X chromosome male
4583 // 8..11: haploid
4584 fill_double_zero(12, geno_map);
4585 geno_map[0] = 1;
4586 geno_map[2] = 1;
4587 geno_map[4] = 1;
4588 geno_map[8] = 1;
4589 if (glm_modifier & GLM_CONDITION_RECESSIVE) {
4590 geno_map[2] = 0;
4591 } else if (!(glm_modifier & GLM_CONDITION_DOMINANT)) {
4592 geno_map[0] = 2;
4593 if (glm_xchr_model == 2) {
4594 geno_map[4] = 2;
4595 }
4596 }
4597 for (param_idx_fixed = 0; param_idx_fixed < condition_ct; param_idx_fixed++) {
4598 marker_uidx = condition_uidxs[param_idx_fixed];
4599 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
4600 goto glm_linear_assoc_ret_READ_FAIL;
4601 }
4602 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, g_loadbuf)) {
4603 goto glm_linear_assoc_ret_READ_FAIL;
4604 }
4605 chrom_idx = get_variant_chrom(chrom_info_ptr, marker_uidx);
4606 geno_map_ptr = geno_map;
4607 if ((IS_SET(chrom_info_ptr->haploid_mask, chrom_idx)) || (chrom_idx == (uint32_t)chrom_info_ptr->xymt_codes[MT_OFFSET])) {
4608 g_is_x = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[X_OFFSET]);
4609 g_is_y = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[Y_OFFSET]);
4610 if (hh_or_mt_exists) {
4611 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)g_loadbuf);
4612 }
4613 if (!g_is_x) {
4614 geno_map_ptr = &(geno_map[8]);
4615 }
4616 } else {
4617 g_is_x = 0;
4618 }
4619 if (!g_is_x) {
4620 glm_loadbuf_to_doubles(g_loadbuf, sample_valid_ct, &(g_fixed_covars_cov_major[param_idx_fixed * sample_valid_ct]), geno_map_ptr, nullptr);
4621 } else {
4622 glm_loadbuf_to_doubles_x(g_loadbuf, sex_male_collapsed, sample_valid_ct, &(g_fixed_covars_cov_major[param_idx_fixed * sample_valid_ct]), geno_map_ptr, nullptr);
4623 }
4624 if (is_set(active_params, param_idx_fixed + condition_list_start_idx)) {
4625 strcpy(&(param_names[param_idx * max_param_name_len]), &(marker_ids[marker_uidx * max_marker_id_len]));
4626 param_idx++;
4627 }
4628 }
4629 for (uii = 0; uii < covar_ct; param_idx_fixed++, uii++) {
4630 // sample-major to covariate-major
4631 sample_uidx = 0;
4632 dptr = &(g_fixed_covars_cov_major[param_idx_fixed * sample_valid_ct]);
4633 dptr2 = &(covar_d[uii]);
4634 for (sample_idx = 0; sample_idx < sample_ct; sample_uidx++, sample_idx++) {
4635 next_unset_ul_unsafe_ck(sample_exclude, &sample_uidx);
4636 if (IS_SET(load_mask, sample_uidx)) {
4637 *dptr++ = dptr2[sample_idx * covar_ct];
4638 }
4639 }
4640 }
4641 for (uii = 0; uii < covar_ct; uii++) {
4642 if (is_set(active_params, uii + covar_start_idx)) {
4643 strcpy(&(param_names[param_idx * max_param_name_len]), &(covar_names[uii * max_covar_name_len]));
4644 param_idx++;
4645 }
4646 }
4647 if (covar_interactions) {
4648 ujj = interaction_start_idx;
4649 for (uii = 0; uii < condition_ct; uii++) {
4650 if (is_set(active_params, ujj++)) {
4651 wptr = memcpyl3a(&(param_names[param_idx * max_param_name_len]), main_effect);
4652 wptr = memcpya(wptr, "xCSNP", 5);
4653 uint32toa_x(uii + 1, '\0', wptr);
4654 param_idx++;
4655 }
4656 if (genotypic_or_hethom) {
4657 if (is_set(active_params, ujj++)) {
4658 wptr = &(param_names[param_idx * max_param_name_len]);
4659 if (hethom) {
4660 wptr = memcpya(wptr, "HETxCSNP", 8);
4661 } else {
4662 wptr = memcpya(wptr, "DOMDEVxCSNP", 11);
4663 }
4664 uint32toa_x(uii + 1, '\0', wptr);
4665 param_idx++;
4666 }
4667 }
4668 }
4669 for (uii = 0; uii < covar_ct; uii++) {
4670 if (is_set(active_params, ujj++)) {
4671 wptr = memcpya(&(param_names[param_idx * max_param_name_len]), main_effect, 3);
4672 *wptr++ = 'x';
4673 strcpy(wptr, &(covar_names[uii * max_covar_name_len]));
4674 param_idx++;
4675 }
4676 if (genotypic_or_hethom) {
4677 if (is_set(active_params, ujj++)) {
4678 wptr = &(param_names[param_idx * max_param_name_len]);
4679 if (hethom) {
4680 wptr = memcpya(wptr, "HETx", 4);
4681 } else {
4682 wptr = memcpya(wptr, "DOMDEVx", 7);
4683 }
4684 strcpy(wptr, &(covar_names[uii * max_covar_name_len]));
4685 param_idx++;
4686 }
4687 }
4688 }
4689 }
4690 if (variation_in_sex) {
4691 dptr = &(g_fixed_covars_cov_major[param_idx_fixed * sample_valid_ct]);
4692 fill_double_zero(sample_valid_ct, dptr);
4693 sample_idx = 0;
4694 while (1) {
4695 next_set_ul_ck(sex_male_collapsed, sample_valid_ct, &sample_idx);
4696 if (sample_idx == sample_valid_ct) {
4697 break;
4698 }
4699 dptr[sample_idx++] = 1;
4700 }
4701 if (IS_SET(active_params, sex_start_idx)) {
4702 memcpy(&(param_names[param_idx * max_param_name_len]), "SEX", 4);
4703 param_idx++;
4704 }
4705 if (covar_interactions) {
4706 if (is_set(active_params, sex_start_idx + 1)) {
4707 wptr = memcpyl3a(&(param_names[param_idx * max_param_name_len]), main_effect);
4708 memcpy(wptr, "xSEX", 5);
4709 param_idx++;
4710 }
4711 if (genotypic_or_hethom && is_set(active_params, sex_start_idx + 2)) {
4712 wptr = &(param_names[param_idx * max_param_name_len]);
4713 if (hethom) {
4714 memcpy(wptr, "HETxSEX", 8);
4715 } else {
4716 memcpy(wptr, "DOMDEVxSEX", 11);
4717 }
4718 param_idx++;
4719 }
4720 } else if (x_sex_interaction) {
4721 // active_params bit must be set
4722 memcpy(&(param_names[param_idx * max_param_name_len]), "XxSEX", 6);
4723 param_idx++;
4724 }
4725 }
4726 if (genotypic_or_hethom) {
4727 if (bigstack_alloc_c(np_base * max_param_name_len, &haploid_param_names)) {
4728 goto glm_linear_assoc_ret_NOMEM;
4729 }
4730 uii = 1;
4731 for (param_idx = 1; param_idx < np_base; uii++, param_idx++) {
4732 next_set_unsafe_ck(haploid_params, &uii);
4733 strcpy(&(haploid_param_names[param_idx * max_param_name_len]), &(param_names[uii * max_param_name_len]));
4734 }
4735 }
4736
4737 if (constraint_ct_max) {
4738 if (bigstack_alloc_d(constraint_ct_max * param_ct_max, &constraints_con_major)) {
4739 goto glm_linear_assoc_ret_NOMEM;
4740 }
4741 // special case: df may vary between chromosomes, so refill suffix at
4742 // beginning of each chromosome
4743 wptr = &(param_names[param_ct_max * max_param_name_len]);
4744 if (tests_range_list_ptr->name_ct) {
4745 memcpy(wptr, "USER_", 6);
4746 } else if (glm_modifier & GLM_TEST_ALL) {
4747 memcpy(wptr, "FULL_", 6);
4748 } else {
4749 memcpy(wptr, "GENO_", 6);
4750 }
4751 }
4752 g_constraints_con_major = constraints_con_major;
4753 if (!perm_maxt_nst) {
4754 g_aperm_alpha = apip->alpha;
4755 mperm_save = 0;
4756 }
4757 mperm_save_all = mperm_save & MPERM_DUMP_ALL;
4758 if (fill_orig_chiabs) {
4759 if (mtest_adjust || is_set_test) {
4760 if (constraint_ct_max) {
4761 if (bigstack_alloc_d(marker_initial_ct, &orig_pvals)) {
4762 goto glm_linear_assoc_ret_NOMEM;
4763 }
4764 }
4765 if ((!constraint_ct_max) || is_set_test) {
4766 if (bigstack_calloc_ui(marker_initial_ct, &tcnt)) {
4767 goto glm_linear_assoc_ret_NOMEM;
4768 }
4769 }
4770 if (!is_set_test) {
4771 if (bigstack_alloc_ui(marker_initial_ct, &marker_idx_to_uidx)) {
4772 goto glm_linear_assoc_ret_NOMEM;
4773 }
4774 }
4775 }
4776 if (do_perms_nst) {
4777 // need this for max(T) now since we need to track permutation failures
4778 // bugfix: g_perm_2success_ct was uninitialized.
4779 if (bigstack_calloc_ui(marker_initial_ct, &g_perm_2success_ct) ||
4780 bigstack_calloc_ui(marker_initial_ct, &g_perm_attempt_ct)) {
4781 goto glm_linear_assoc_ret_NOMEM;
4782 }
4783 perms_total = perm_adapt_nst? apip->max : glm_mperm_val;
4784 if (perms_total < orig_perm_batch_size) {
4785 orig_perm_batch_size = perms_total;
4786 }
4787 perm_batch_size = orig_perm_batch_size;
4788 uii = perm_batch_size / CACHELINE_INT32;
4789 if (!uii) {
4790 uii = 1;
4791 } else if (uii > GLM_BLOCKSIZE / CACHELINE_INT32) {
4792 uii = GLM_BLOCKSIZE / CACHELINE_INT32;
4793 }
4794 if (max_thread_ct > uii) {
4795 max_thread_ct = uii;
4796 }
4797 if (!perm_adapt_nst) {
4798 if (bigstack_alloc_d(round_up_pow2(perm_batch_size, CACHELINE_DBL) * max_thread_ct, &g_maxt_thread_results) ||
4799 bigstack_calloc_d(perms_total, &g_maxt_extreme_stat)) {
4800 goto glm_linear_assoc_ret_NOMEM;
4801 }
4802 if (mperm_save_all) {
4803 if (bigstack_alloc_d(((uintptr_t)marker_initial_ct) * perm_batch_size, &g_mperm_save_all)) {
4804 goto glm_linear_assoc_ret_NOMEM;
4805 }
4806 memcpy(outname_end, ".mperm.dump.all", 16);
4807 if (fopen_checked(outname, "w", &outfile_msa)) {
4808 goto glm_linear_assoc_ret_OPEN_FAIL;
4809 }
4810 if (putc_checked('0', outfile_msa)) {
4811 goto glm_linear_assoc_ret_WRITE_FAIL;
4812 }
4813 LOGPRINTF("Dumping all permutation %s to %s .\n", (!constraint_ct_max)? "absolute t-stats" : "chi-square values", outname);
4814 }
4815 }
4816 g_perm_batch_max = perm_batch_size;
4817 }
4818 }
4819 if (do_perms) {
4820 if (cluster_starts) {
4821 // Pointless to include size-1 clusters in permutation.
4822 retval = cluster_include_and_reindex(unfiltered_sample_ct, load_mask, 1, nullptr, sample_valid_ct, 0, cluster_ct, cluster_map, cluster_starts, &g_perm_cluster_ct, &g_perm_cluster_map, &g_perm_cluster_starts, nullptr, nullptr);
4823 if (retval) {
4824 goto glm_linear_assoc_ret_1;
4825 }
4826 if (!g_perm_cluster_ct) {
4827 goto glm_linear_assoc_ret_NO_PERMUTATION_CLUSTERS;
4828 }
4829 if (bigstack_alloc_ui(max_thread_ct * round_up_pow2(g_perm_cluster_ct, CACHELINE_INT32), &g_perm_qt_cluster_thread_wkspace) ||
4830 bigstack_alloc_ui(sample_valid_ct, &g_perm_sample_to_cluster)) {
4831 goto glm_linear_assoc_ret_NOMEM;
4832 }
4833 fill_unfiltered_sample_to_cluster(sample_valid_ct, g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, g_perm_sample_to_cluster);
4834 }
4835 if (!is_set_test) {
4836 if (bigstack_init_sfmtp(max_thread_ct)) {
4837 goto glm_linear_assoc_ret_NOMEM;
4838 }
4839 }
4840 } else {
4841 orig_perm_batch_size = 1;
4842 }
4843 if (bigstack_alloc_d(sample_valid_ct, &g_perm_pheno_d2)) {
4844 goto glm_linear_assoc_ret_NOMEM;
4845 }
4846 g_linear_mt = (Linear_multithread*)bigstack_alloc(max_thread_ct * sizeof(Linear_multithread));
4847 if (!g_linear_mt) {
4848 goto glm_linear_assoc_ret_NOMEM;
4849 }
4850 ulii = BITCT_TO_WORDCT(orig_perm_batch_size);
4851 for (tidx = 0; tidx < max_thread_ct; tidx++) {
4852 if (bigstack_alloc_d(param_ct_max * sample_valid_ct, &(g_linear_mt[tidx].cur_covars_cov_major)) ||
4853 bigstack_alloc_d(param_ct_max * sample_valid_ct, &(g_linear_mt[tidx].cur_covars_sample_major)) ||
4854 bigstack_alloc_ul(ulii, &(g_linear_mt[tidx].perm_fails)) ||
4855 bigstack_alloc_d(param_ct_max * param_ct_max, &(g_linear_mt[tidx].param_2d_buf)) ||
4856 bigstack_alloc_d(param_ct_max * param_ct_max, &(g_linear_mt[tidx].param_2d_buf2)) ||
4857 bigstack_alloc_d(orig_perm_batch_size * param_ctx_max_m1, &(g_linear_mt[tidx].regression_results))) {
4858 goto glm_linear_assoc_ret_NOMEM;
4859 }
4860
4861 g_linear_mt[tidx].mi_buf = (MATRIX_INVERT_BUF1_TYPE*)bigstack_alloc(param_ct_max * MATRIX_INVERT_BUF1_ELEM_ALLOC);
4862 if (!(g_linear_mt[tidx].mi_buf)) {
4863 goto glm_linear_assoc_ret_NOMEM;
4864 }
4865 if (constraint_ct_max) {
4866 if (bigstack_alloc_d(constraint_ct_max * constraint_ct_max, &(g_linear_mt[tidx].df_df_buf)) ||
4867 bigstack_alloc_d(constraint_ct_max, &(g_linear_mt[tidx].df_buf)) ||
4868 bigstack_alloc_d(constraint_ct_max * param_ct_max, &(g_linear_mt[tidx].param_df_buf)) ||
4869 bigstack_alloc_d(constraint_ct_max * param_ct_max, &(g_linear_mt[tidx].param_df_buf2))) {
4870 goto glm_linear_assoc_ret_NOMEM;
4871 }
4872 }
4873 if (bigstack_alloc_d(param_ct_max * sample_valid_ct, &(g_linear_mt[tidx].dgels_a)) ||
4874 bigstack_alloc_d(orig_perm_batch_size * sample_valid_ct, &(g_linear_mt[tidx].dgels_b))) {
4875 goto glm_linear_assoc_ret_NOMEM;
4876 }
4877 if (!tidx) {
4878 dgels_m = (int32_t)((uint32_t)sample_valid_ct);
4879 dgels_n = (int32_t)((uint32_t)param_ct_max);
4880 dgels_nrhs = orig_perm_batch_size;
4881 dgels_ldb = dgels_m;
4882 g_dgels_lwork = -1;
4883 // no other parameters are needed for workspace query
4884 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, g_linear_mt[0].dgels_a, &dgels_m, g_linear_mt[0].dgels_b, &dgels_ldb, &dxx, &g_dgels_lwork, &dgels_info);
4885 // todo: support linking to 64-bit LAPACK on Linux
4886 if (dxx > 2147483647.0) {
4887 logerrprint("Error: Multiple linear regression problem too large for current LAPACK version.\n");
4888 retval = RET_CALC_NOT_YET_SUPPORTED;
4889 goto glm_linear_assoc_ret_1;
4890 }
4891 g_dgels_lwork = (int32_t)dxx;
4892 }
4893 if (bigstack_alloc_d(g_dgels_lwork, &(g_linear_mt[tidx].dgels_work))) {
4894 goto glm_linear_assoc_ret_NOMEM;
4895 }
4896 }
4897
4898 dptr = g_perm_pheno_d2;
4899 g_pheno_sum = 0;
4900 g_pheno_ssq = 0;
4901 sample_uidx = 0;
4902 sample_idx = 0;
4903 do {
4904 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
4905 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
4906 sample_idx += sample_uidx_stop - sample_uidx;
4907 dptr2 = &(pheno_d[sample_uidx]);
4908 sample_uidx = sample_uidx_stop;
4909 dptr3 = &(pheno_d[sample_uidx_stop]);
4910 do {
4911 dxx = *dptr2++;
4912 *dptr++ = dxx;
4913 g_pheno_sum += dxx;
4914 g_pheno_ssq += dxx * dxx;
4915 } while (dptr2 < dptr3);
4916 } while (sample_idx < sample_valid_ct);
4917 if (g_pheno_ssq * ((double)((intptr_t)sample_valid_ct)) == g_pheno_sum * g_pheno_sum) {
4918 goto glm_linear_assoc_ret_PHENO_CONSTANT;
4919 }
4920 if (standard_beta) {
4921 dxx = g_pheno_sum / ((double)((intptr_t)sample_valid_ct));
4922 dyy = sqrt(((double)((intptr_t)(sample_valid_ct - 1))) / (g_pheno_ssq - g_pheno_sum * dxx));
4923 dptr = g_perm_pheno_d2;
4924 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
4925 *dptr = ((*dptr) - dxx) * dyy;
4926 dptr++;
4927 }
4928 g_pheno_sum = 0;
4929 g_pheno_ssq = (double)((intptr_t)(sample_valid_ct - 1));
4930 }
4931 if (do_perms) {
4932 if (bigstack_alloc_ui(sample_valid_ct - 1, &g_perm_precomputed_mods) ||
4933 bigstack_alloc_d(orig_perm_batch_size * sample_valid_ct, &g_perm_pmajor)) {
4934 goto glm_linear_assoc_ret_NOMEM;
4935 }
4936 precompute_mods(sample_valid_ct, g_perm_precomputed_mods);
4937 }
4938
4939 outname_end2 = memcpyb(outname_end, ".assoc.linear", 14);
4940 if (fopen_checked(outname, "w", &outfile)) {
4941 goto glm_linear_assoc_ret_OPEN_FAIL;
4942 }
4943 LOGPRINTFWW5("Writing linear model association results to %s ... ", outname);
4944 fflush(stdout);
4945 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us BP A1 TEST NMISS BETA ", plink_maxsnp);
4946 fprintf(outfile, g_textbuf, "SNP");
4947 if (display_ci) {
4948 uii = (uint32_t)((int32_t)(ci_size * (100 + EPSILON)));
4949 if (uii >= 10) {
4950 fprintf(outfile, " SE L%u U%u ", uii, uii);
4951 } else {
4952 fprintf(outfile, " SE L%u U%u ", uii, uii);
4953 }
4954 }
4955 fputs(" STAT P \n", outfile);
4956 loop_end = marker_initial_ct / 100;
4957 marker_unstopped_ct = marker_initial_ct;
4958 g_adaptive_ci_zt = ltqnorm(1 - apip->beta / (2.0 * ((int32_t)marker_initial_ct)));
4959
4960 // ----- begin main loop -----
4961 glm_linear_assoc_more_perms:
4962 if (do_perms_nst) {
4963 if (perm_adapt_nst) {
4964 if (perm_pass_idx) {
4965 while (g_first_adapt_check <= g_perms_done) {
4966 g_first_adapt_check += (int32_t)(apip->init_interval + ((int32_t)g_first_adapt_check) * apip->interval_slope);
4967 }
4968 } else {
4969 if (apip->min < apip->init_interval) {
4970 g_first_adapt_check = (int32_t)(apip->init_interval);
4971 } else {
4972 g_first_adapt_check = apip->min;
4973 }
4974 g_adaptive_intercept = apip->init_interval;
4975 g_adaptive_slope = apip->interval_slope;
4976 }
4977 }
4978 g_perm_vec_ct = perm_batch_size;
4979 if (perm_adapt_nst && (g_perms_done < perm_batch_size)) {
4980 // special case: split first batch to reduce adaptive overshoot
4981 ulii = perm_batch_size;
4982 uljj = (intptr_t)(apip->init_interval);
4983 uljj = MAXV(uljj, apip->min);
4984 uljj *= 2;
4985 uljj = MAXV(64, uljj);
4986 while (ulii >= (uljj << perm_pass_idx)) {
4987 ulii >>= 1;
4988 }
4989 g_perm_vec_ct = ulii - g_perms_done;
4990 }
4991 if (g_perm_vec_ct > perms_total - g_perms_done) {
4992 g_perm_vec_ct = perms_total - g_perms_done;
4993 }
4994 if (g_perm_vec_ct >= CACHELINE_INT32 * max_thread_ct) {
4995 g_perm_generation_thread_ct = max_thread_ct;
4996 } else {
4997 g_perm_generation_thread_ct = MAXV(g_perm_vec_ct / CACHELINE_INT32, 1);
4998 }
4999 ulii = 0;
5000 if (!g_perm_cluster_ct) {
5001 if (spawn_threads(threads, &generate_qt_perms_pmajor_thread, g_perm_generation_thread_ct)) {
5002 goto glm_linear_assoc_ret_THREAD_CREATE_FAIL;
5003 }
5004 generate_qt_perms_pmajor_thread((void*)ulii);
5005 } else {
5006 if (spawn_threads(threads, &generate_qt_cluster_perms_pmajor_thread, g_perm_generation_thread_ct)) {
5007 goto glm_linear_assoc_ret_THREAD_CREATE_FAIL;
5008 }
5009 generate_qt_cluster_perms_pmajor_thread((void*)ulii);
5010 }
5011 join_threads(threads, g_perm_generation_thread_ct);
5012 }
5013 chrom_fo_idx = 0xffffffffU;
5014 marker_uidx = next_unset_unsafe(marker_exclude, 0);
5015 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5016 goto glm_linear_assoc_ret_READ_FAIL;
5017 }
5018 if (!perm_pass_idx) {
5019 fputs("0%", stdout);
5020 fflush(stdout);
5021 }
5022 marker_idx = 0;
5023 marker_idx2 = 0;
5024 chrom_end = 0;
5025 do {
5026 if (marker_uidx >= chrom_end) {
5027 // exploit overflow
5028 do {
5029 chrom_fo_idx++;
5030 refresh_chrom_info(chrom_info_ptr, marker_uidx, &chrom_end, &chrom_fo_idx, &g_is_x, &g_is_y, &uii, &g_min_ploidy_1);
5031 g_min_ploidy_1 |= uii;
5032 } while ((!glm_xchr_model) && g_min_ploidy_1);
5033 uii = chrom_info_ptr->chrom_file_order[chrom_fo_idx];
5034 wptr_start = width_force(4, writebuf, chrom_name_write(chrom_info_ptr, uii, writebuf));
5035 *wptr_start++ = ' ';
5036 fill_double_zero(constraint_ct_max * param_ct_max, constraints_con_major);
5037 g_male_x_01 = 0;
5038 if (g_is_x) {
5039 cur_param_ct = param_ct_max;
5040 cur_constraint_ct = constraint_ct_max;
5041 cur_param_names = param_names;
5042 if (glm_xchr_model != 2) {
5043 g_male_x_01 = 1;
5044 }
5045 } else if ((!g_min_ploidy_1) || (!genotypic_or_hethom)) {
5046 cur_param_ct = np_base + np_diploid;
5047 if (constraint_ct_max) {
5048 // bugfix: this incorrectly had constraint_ct_max as last parameter
5049 // bugfix (4 Mar 2019): also need to subtract 1 from cur_param_ct,
5050 // since g_joint_test_params has ADD rather than INTERCEPT in bit 0,
5051 // etc.
5052 cur_constraint_ct = popcount_bit_idx(g_joint_test_params, 0, cur_param_ct - 1);
5053 } else {
5054 cur_constraint_ct = 0;
5055 }
5056 cur_param_names = param_names;
5057 } else {
5058 // er, is this still reachable with forced --xchr-model 0? should it
5059 // be reachable?
5060 cur_param_ct = np_base;
5061 cur_constraint_ct = 0;
5062 if (constraint_ct_max) {
5063 for (ulii = 0; ulii < param_ctl_max; ulii++) {
5064 uljj = g_joint_test_params[ulii] & haploid_params[ulii];
5065 while (uljj) {
5066 uii = CTZLU(uljj) + ulii * BITCT;
5067 constraints_con_major[cur_constraint_ct * cur_param_ct + uii + 1] = 1;
5068 cur_constraint_ct++;
5069 uljj &= uljj - 1;
5070 }
5071 }
5072 }
5073 cur_param_names = haploid_param_names;
5074 }
5075 g_cur_param_ct = cur_param_ct;
5076 g_cur_constraint_ct = cur_constraint_ct;
5077 if (!hide_covar) {
5078 param_idx_end = cur_param_ct;
5079 }
5080 cur_param_ctx = cur_param_ct;
5081 g_include_sex = sex_covar_everywhere || (g_is_x && np_sex);
5082 if (cur_constraint_ct) {
5083 cur_param_ctx++;
5084 // bugfix (9 May 2017): constraints_con_major wasn't being initialized
5085 // in some haploid cases
5086 if (g_is_x || (!g_min_ploidy_1) || (!genotypic_or_hethom)) {
5087 ulii = 0;
5088 for (constraint_idx = 0; constraint_idx < cur_constraint_ct; ulii++, constraint_idx++) {
5089 next_set_ul_unsafe_ck(g_joint_test_params, &ulii);
5090 constraints_con_major[constraint_idx * cur_param_ct + ulii + 1] = 1;
5091 }
5092 }
5093 wptr = uint32toa(cur_constraint_ct, &(param_names[param_ct_max * max_param_name_len + 5]));
5094 memcpy(wptr, "DF", 3);
5095 }
5096 }
5097 block_size = 0;
5098 block_end = marker_unstopped_ct - marker_idx;
5099 if (block_end > GLM_BLOCKSIZE) {
5100 block_end = GLM_BLOCKSIZE;
5101 }
5102 do {
5103 if (g_perm_adapt_stop && g_perm_adapt_stop[marker_idx2]) {
5104 do {
5105 marker_uidx++;
5106 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
5107 marker_idx2++;
5108 } while ((marker_uidx < chrom_end) && g_perm_adapt_stop[marker_idx2]);
5109 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5110 goto glm_linear_assoc_ret_READ_FAIL;
5111 }
5112 if (marker_uidx >= chrom_end) {
5113 break;
5114 }
5115 }
5116 loadbuf_ptr = &(g_loadbuf[block_size * sample_valid_ctv2]);
5117 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_ptr)) {
5118 goto glm_linear_assoc_ret_READ_FAIL;
5119 }
5120 if (g_min_ploidy_1 && hh_or_mt_exists) {
5121 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)loadbuf_ptr);
5122 }
5123 g_adapt_m_table[block_size] = marker_idx2++;
5124 mu_table[block_size++] = marker_uidx;
5125 if (marker_idx + block_size == marker_unstopped_ct) {
5126 break;
5127 }
5128 marker_uidx++;
5129 if (IS_SET(marker_exclude, marker_uidx)) {
5130 marker_uidx = next_unset_unsafe(marker_exclude, marker_uidx);
5131 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5132 goto glm_linear_assoc_ret_READ_FAIL;
5133 }
5134 }
5135 } while ((block_size < block_end) && (marker_uidx < chrom_end));
5136 if (!block_size) {
5137 continue;
5138 }
5139 g_block_diff = block_size;
5140 if (!perm_pass_idx) {
5141 #ifndef NOLAPACK
5142 dgels_nrhs = 1;
5143 #endif
5144 for (marker_bidx = 0; marker_bidx < block_size; marker_bidx++) {
5145 // 1. fill design matrix and make transposed copy; fill g_nm_cts[] in
5146 // the process
5147 // 2. 'standard-beta' adjustment if necessary
5148 // 3. linear/logistic regression, set g_perm_adapt_stop byte on failure
5149 // 4. write basic report to disk
5150 marker_uidx2 = mu_table[marker_bidx];
5151 loadbuf_ptr = &(g_loadbuf[marker_bidx * sample_valid_ctv2]);
5152 marker_idx3 = g_adapt_m_table[marker_bidx];
5153 if (marker_idx_to_uidx) {
5154 marker_idx_to_uidx[marker_idx3] = marker_uidx2;
5155 }
5156 cur_missing_ct = glm_fill_design(loadbuf_ptr, g_fixed_covars_cov_major, sample_valid_ct, cur_param_ct, glm_modifier & (GLM_HETHOM | GLM_DOMINANT | GLM_RECESSIVE), condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, g_include_sex, g_male_x_01, sex_male_collapsed, g_min_ploidy_1 && (!g_is_x), g_linear_mt[0].cur_covars_cov_major, g_linear_mt[0].cur_covars_sample_major, standard_beta);
5157 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
5158 g_nm_cts[marker_idx3] = cur_sample_valid_ct;
5159 if ((cur_sample_valid_ct > cur_param_ct) && (!glm_check_vif(glm_vif_thresh, cur_param_ct, cur_sample_valid_ct, g_linear_mt[0].cur_covars_cov_major, g_linear_mt[0].param_2d_buf, g_linear_mt[0].mi_buf, g_linear_mt[0].param_2d_buf2))) {
5160 regression_fail = 0;
5161 memcpy(g_linear_mt[0].dgels_a, g_linear_mt[0].cur_covars_cov_major, cur_param_ct * cur_sample_valid_ct * sizeof(double));
5162 copy_when_nonmissing(loadbuf_ptr, (char*)g_perm_pheno_d2, sizeof(double), sample_valid_ct, cur_missing_ct, (char*)(g_linear_mt[0].dgels_b));
5163 if (standard_beta && cur_missing_ct) {
5164 dxx = g_pheno_sum;
5165 dyy = g_pheno_ssq;
5166 ulptr = loadbuf_ptr;
5167 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx += BITCT2) {
5168 cur_word = *ulptr++;
5169 cur_word = cur_word & (~(cur_word >> 1)) & FIVEMASK;
5170 while (cur_word) {
5171 dzz = g_perm_pheno_d2[sample_idx + (CTZLU(cur_word) / 2)];
5172 dxx -= dzz;
5173 dyy -= dzz * dzz;
5174 cur_word &= cur_word - 1;
5175 }
5176 }
5177 dzz = dxx / ((double)((intptr_t)cur_sample_valid_ct));
5178 dyy = sqrt(((double)((intptr_t)(cur_sample_valid_ct - 1))) / (dyy - dxx * dzz));
5179 dptr = g_linear_mt[0].dgels_b;
5180 for (sample_idx = 0; sample_idx < cur_sample_valid_ct; sample_idx++) {
5181 *dptr = ((*dptr) - dzz) * dyy;
5182 dptr++;
5183 }
5184 }
5185 dgels_m = (int32_t)((uint32_t)cur_sample_valid_ct);
5186 dgels_n = (int32_t)((uint32_t)cur_param_ct);
5187 dgels_ldb = dgels_m;
5188
5189 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, g_linear_mt[0].dgels_a, &dgels_m, g_linear_mt[0].dgels_b, &dgels_ldb, g_linear_mt[0].dgels_work, &g_dgels_lwork, &dgels_info);
5190 if (glm_linear(1, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, loadbuf_ptr, standard_beta, g_pheno_sum, g_pheno_ssq, g_linear_mt[0].cur_covars_cov_major, g_linear_mt[0].cur_covars_sample_major, g_perm_pheno_d2, g_linear_mt[0].dgels_b, g_linear_mt[0].param_2d_buf, g_linear_mt[0].mi_buf, g_linear_mt[0].param_2d_buf2, g_linear_mt[0].regression_results, cur_constraint_ct, constraints_con_major, g_linear_mt[0].param_df_buf, g_linear_mt[0].param_df_buf2, g_linear_mt[0].df_df_buf, g_linear_mt[0].df_buf, &perm_fail_ct, g_linear_mt[0].perm_fails) || perm_fail_ct) {
5191 regression_fail = 1;
5192 if (is_set_test && is_monomorphic(loadbuf_ptr, sample_valid_ct)) {
5193 set_bit(marker_idx3, regression_skip);
5194 }
5195 }
5196 } else {
5197 regression_fail = 1;
5198 if (is_set_test) {
5199 set_bit(marker_idx3, regression_skip);
5200 }
5201 }
5202 wptr_start2 = fw_strcpy(plink_maxsnp, &(marker_ids[marker_uidx2 * max_marker_id_len]), wptr_start);
5203 *wptr_start2++ = ' ';
5204 wptr_start2 = uint32toa_w10x(marker_pos[marker_uidx2], ' ', wptr_start2);
5205 wptr_start2 = fw_strcpy(4, marker_allele_ptrs[marker_uidx2 * 2], wptr_start2);
5206 *wptr_start2++ = ' ';
5207 orig_stats_ptr = &(g_orig_stats[marker_idx3]);
5208 if (!regression_fail) {
5209 for (param_idx = 1; param_idx < cur_param_ct; param_idx++) {
5210 dxx = g_linear_mt[0].dgels_b[param_idx]; // coef[p]
5211 se = sqrt(g_linear_mt[0].regression_results[param_idx - 1]);
5212 zval = dxx / se;
5213 pval = calc_tprob(zval, cur_sample_valid_ct - cur_param_ct);
5214 if (param_idx == 1) {
5215 if (mperm_save_all) {
5216 dtoa_gx(fabs(zval), '\0', &(numbuf[1]));
5217 fputs(numbuf, outfile_msa);
5218 }
5219 if (!constraint_ct_max) {
5220 *orig_stats_ptr = fabs(zval);
5221 if (orig_pvals) {
5222 orig_pvals[marker_idx3] = pval;
5223 }
5224 if (tcnt) {
5225 tcnt[marker_idx3] = cur_sample_valid_ct - cur_param_ct;
5226 }
5227 }
5228 }
5229 if ((param_idx < param_idx_end) && ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0)))) {
5230 wptr = fw_strcpy(10, &(cur_param_names[param_idx * max_param_name_len]), wptr_start2);
5231 *wptr++ = ' ';
5232 wptr = uint32toa_w8x((uint32_t)cur_sample_valid_ct, ' ', wptr);
5233 wptr = dtoa_g_wxp4x(dxx, 10, ' ', wptr);
5234 if (display_ci) {
5235 dyy = ci_zt * se;
5236 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
5237 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
5238 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
5239 }
5240 wptr = dtoa_g_wxp4x(zval, 12, ' ', wptr);
5241 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
5242 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
5243 goto glm_linear_assoc_ret_WRITE_FAIL;
5244 }
5245 }
5246 }
5247 if (report_intercept) {
5248 dxx = g_linear_mt[0].dgels_b[0];
5249 wptr = memcpya(wptr_start2, " INTERCEPT ", 11);
5250 wptr = uint32toa_w8x((uint32_t)cur_sample_valid_ct, ' ', wptr);
5251 wptr = dtoa_g_wxp4x(dxx, 10, ' ', wptr);
5252 if (display_ci) {
5253 // okay, this should be made more maintainable...
5254 se = sqrt(g_linear_mt[0].param_2d_buf2[0]);
5255 dyy = ci_zt * se;
5256 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
5257 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
5258 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
5259 }
5260 wptr = memcpya(wptr, " NA NA\n", 26);
5261 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
5262 goto glm_linear_assoc_ret_WRITE_FAIL;
5263 }
5264 }
5265 if (cur_constraint_ct) {
5266 dxx = g_linear_mt[0].regression_results[cur_param_ct - 1];
5267 *orig_stats_ptr = dxx;
5268 pval = chiprob_p(dxx, cur_constraint_ct);
5269 if (orig_pvals) {
5270 orig_pvals[marker_idx3] = pval;
5271 }
5272 if ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0))) {
5273 wptr = fw_strcpy(10, &(param_names[param_ct_max * max_param_name_len]), wptr_start2);
5274 *wptr++ = ' ';
5275 wptr = uint32toa_w8((uint32_t)cur_sample_valid_ct, wptr);
5276 wptr = memcpya(wptr, " NA ", 12);
5277 if (display_ci) {
5278 wptr = memcpya(wptr, " NA NA NA ", 27);
5279 }
5280 wptr = dtoa_g_wxp4x(dxx, 12, ' ', wptr);
5281 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
5282 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
5283 goto glm_linear_assoc_ret_WRITE_FAIL;
5284 }
5285 }
5286 } else if (orig_pvals && constraint_ct_max) {
5287 orig_pvals[marker_idx3] = -9;
5288 }
5289 } else {
5290 if (!is_set_test) {
5291 g_perm_adapt_stop[marker_idx3] = 1;
5292 }
5293 if (orig_pvals) {
5294 orig_pvals[marker_idx3] = -9;
5295 }
5296 *orig_stats_ptr = -9;
5297 if (mperm_save_all) {
5298 fputs(" NA", outfile_msa);
5299 msa_ptr = &(g_mperm_save_all[marker_idx3 * perm_batch_size]);
5300 for (perm_idx = 0; perm_idx < perm_batch_size; perm_idx++) {
5301 *msa_ptr++ = -9;
5302 }
5303 }
5304 if (pfilter == 2.0) {
5305 for (param_idx = 1; param_idx < cur_param_ctx; param_idx++) {
5306 if ((param_idx < param_idx_end) || (param_idx == cur_param_ct)) {
5307 if (!(param_idx == cur_param_ct)) {
5308 wptr = fw_strcpy(10, &(cur_param_names[param_idx * max_param_name_len]), wptr_start2);
5309 } else {
5310 wptr = fw_strcpy(10, &(param_names[param_ct_max * max_param_name_len]), wptr_start2);
5311 }
5312 *wptr++ = ' ';
5313 wptr = uint32toa_w8((uint32_t)cur_sample_valid_ct, wptr);
5314 wptr = memcpya(wptr, " NA ", 12);
5315 if (display_ci) {
5316 wptr = memcpya(wptr, " NA NA NA ", 27);
5317 }
5318 wptr = memcpya(wptr, " NA NA\n", 26);
5319 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
5320 goto glm_linear_assoc_ret_WRITE_FAIL;
5321 }
5322 }
5323 }
5324 }
5325 }
5326 }
5327 }
5328 if (do_perms_nst) {
5329 // split loaded markers evenly between threads. each thread does the
5330 // following for every marker in its set:
5331 // 1. fill design matrix and make transposed copy, do this more
5332 // efficiently if g_nm_cts[] indicates there are no missing genotypes
5333 // 2. 'standard-beta' adjustment if necessary (these first two steps
5334 // should go into another function since they're mostly duplicated)
5335 // 3. linear/logistic regression on permutations, handle adaptive logic,
5336 // --mperm-save[-all], etc.
5337 g_assoc_thread_ct = block_size / CACHELINE_INT32;
5338 if (g_assoc_thread_ct > max_thread_ct) {
5339 g_assoc_thread_ct = max_thread_ct;
5340 } else if (!g_assoc_thread_ct) {
5341 g_assoc_thread_ct = 1;
5342 }
5343 ulii = 0;
5344 if (perm_adapt_nst) {
5345 if (spawn_threads(threads, &glm_linear_adapt_thread, g_assoc_thread_ct)) {
5346 goto glm_linear_assoc_ret_THREAD_CREATE_FAIL;
5347 }
5348 glm_linear_adapt_thread((void*)ulii);
5349 join_threads(threads, g_assoc_thread_ct);
5350 } else {
5351 if (spawn_threads(threads, &glm_linear_maxt_thread, g_assoc_thread_ct)) {
5352 goto glm_linear_assoc_ret_THREAD_CREATE_FAIL;
5353 }
5354 glm_linear_maxt_thread((void*)ulii);
5355 join_threads(threads, g_assoc_thread_ct);
5356 ulii = round_up_pow2(g_perm_vec_ct, CACHELINE_DBL);
5357 ukk = g_perms_done + g_perm_vec_ct;
5358 for (uii = 0; uii < g_assoc_thread_ct; uii++) {
5359 dptr = &(g_maxt_thread_results[uii * ulii]);
5360 for (ujj = g_perms_done; ujj < ukk; ujj++) {
5361 dxx = *dptr++;
5362 if (dxx > g_maxt_extreme_stat[ujj]) {
5363 g_maxt_extreme_stat[ujj] = dxx;
5364 }
5365 }
5366 }
5367 }
5368 }
5369 marker_idx += block_size;
5370 if ((!perm_pass_idx) && (marker_idx >= loop_end)) {
5371 if (marker_idx < marker_initial_ct) {
5372 if (pct >= 10) {
5373 putc_unlocked('\b', stdout);
5374 }
5375 pct = (marker_idx * 100LLU) / marker_initial_ct;
5376 printf("\b\b%u%%", pct);
5377 fflush(stdout);
5378 loop_end = (((uint64_t)pct + 1LLU) * marker_initial_ct) / 100;
5379 }
5380 }
5381 } while (marker_idx < marker_unstopped_ct);
5382 // if more permutations, reevaluate marker_unstopped_ct, etc.
5383 if (!perm_pass_idx) {
5384 if (pct >= 10) {
5385 putc_unlocked('\b', stdout);
5386 }
5387 fputs("\b\b", stdout);
5388 logprint("done.\n");
5389 if (fclose_null(&outfile)) {
5390 goto glm_linear_assoc_ret_WRITE_FAIL;
5391 }
5392 if (!is_set_test) {
5393 if (mtest_adjust) {
5394 retval = multcomp(outname, outname_end, marker_idx_to_uidx, marker_initial_ct, marker_ids, max_marker_id_len, plink_maxsnp, chrom_info_ptr, constraint_ct_max? nullptr : g_orig_stats, pfilter, output_min_p, mtest_adjust, constraint_ct_max, adjust_lambda, constraint_ct_max? nullptr : tcnt, constraint_ct_max? orig_pvals : nullptr);
5395 if (retval) {
5396 goto glm_linear_assoc_ret_1;
5397 }
5398 }
5399 if (mperm_save_all) {
5400 if (putc_checked('\n', outfile_msa)) {
5401 goto glm_linear_assoc_ret_WRITE_FAIL;
5402 }
5403 }
5404 } else {
5405 retval = glm_linear_assoc_set_test(threads, bedfile, bed_offset, outname, outname_end, glm_modifier, glm_xchr_model, glm_mperm_val, pfilter, output_min_p, mtest_adjust, unfiltered_marker_ct, marker_exclude_orig, marker_ct_orig, marker_exclude, marker_ct, marker_ids, max_marker_id_len, marker_reverse, regression_skip, chrom_info_ptr, unfiltered_sample_ct, sex_male, apip, pheno_nm_ct, pheno_nm, founder_pnm, load_mask, sample_include2, sample_male_include2, ld_ignore_x, hh_exists, hh_or_mt_exists, orig_perm_batch_size, sip, tcnt, loadbuf_raw, param_ct_max, np_base, np_diploid, np_sex, sample_valid_ct, sex_covar_everywhere);
5406 if (retval) {
5407 goto glm_linear_assoc_ret_1;
5408 }
5409 }
5410 }
5411 if (do_perms_nst) {
5412 if (mperm_save_all) {
5413 if (perm_pass_idx) {
5414 putc_unlocked(' ', stdout);
5415 }
5416 fputs("[dumping stats]", stdout);
5417 fflush(stdout);
5418 ulii = g_perm_vec_ct;
5419 ujj = 1 + g_perms_done;
5420 wptr = g_textbuf;
5421 cptr = &(g_textbuf[MAXLINELEN]);
5422 for (uii = 0; uii < ulii; uii++) {
5423 wptr = uint32toa(uii + ujj, wptr);
5424 dptr = &(g_mperm_save_all[uii]);
5425 for (ukk = 0; ukk < marker_ct; ukk++) {
5426 *wptr++ = ' ';
5427 dxx = dptr[ukk * ulii];
5428 if (dxx >= 0) {
5429 wptr = dtoa_g(dxx, wptr);
5430 } else {
5431 wptr = memcpya(wptr, "NA", 2);
5432 }
5433 if (wptr >= cptr) {
5434 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile_msa)) {
5435 goto glm_linear_assoc_ret_WRITE_FAIL;
5436 }
5437 wptr = g_textbuf;
5438 }
5439 }
5440 *wptr++ = '\n';
5441 }
5442 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile_msa)) {
5443 goto glm_linear_assoc_ret_WRITE_FAIL;
5444 }
5445 fputs("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b ", stdout);
5446 }
5447 g_perms_done += g_perm_vec_ct;
5448 if (g_perms_done < perms_total) {
5449 if (perm_adapt_nst || (!perm_pass_idx)) {
5450 marker_unstopped_ct = marker_initial_ct - popcount01_longs((uintptr_t*)g_perm_adapt_stop, (marker_initial_ct + sizeof(intptr_t) - 1) / sizeof(intptr_t));
5451 if (!marker_unstopped_ct) {
5452 goto glm_linear_assoc_perm_count;
5453 }
5454 }
5455 printf("\r%u permutation%s complete.", g_perms_done, (g_perms_done != 1)? "s" : "");
5456 fflush(stdout);
5457 perm_pass_idx++;
5458 goto glm_linear_assoc_more_perms;
5459 }
5460 glm_linear_assoc_perm_count:
5461 if (perm_adapt_nst) {
5462 g_perms_done = 0;
5463 for (uii = 0; uii < marker_initial_ct; uii++) {
5464 if (g_perm_attempt_ct[uii] > g_perms_done) {
5465 g_perms_done = g_perm_attempt_ct[uii];
5466 if (g_perms_done == perms_total) {
5467 break;
5468 }
5469 }
5470 }
5471 }
5472 putc_unlocked('\r', stdout);
5473 LOGPRINTF("%u %s permutation%s complete.\n", g_perms_done, perm_maxt_nst? "max(T)" : "(adaptive)", (g_perms_done != 1)? "s" : "");
5474
5475 if (perm_adapt_nst) {
5476 memcpy(outname_end2, ".perm", 6);
5477 } else {
5478 if (mperm_save & MPERM_DUMP_BEST) {
5479 memcpy(outname_end, ".mperm.dump.best", 17);
5480 LOGPRINTFWW("Dumping best permutation %s to %s .\n", (!constraint_ct_max)? "absolute t-stats" : "chi-square values", outname);
5481 if (fopen_checked(outname, "w", &outfile)) {
5482 goto glm_linear_assoc_ret_OPEN_FAIL;
5483 }
5484 dxx = 0;
5485 for (marker_idx = 0; marker_idx < marker_initial_ct; marker_idx++) {
5486 if (g_orig_stats[marker_idx] > dxx) {
5487 dxx = g_orig_stats[marker_idx];
5488 }
5489 }
5490 memcpy(g_textbuf, "0 ", 2);
5491 wptr = dtoa_gx(dxx, '\n', &(g_textbuf[2]));
5492 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile)) {
5493 goto glm_linear_assoc_ret_WRITE_FAIL;
5494 }
5495 for (uii = 0; uii < perms_total; uii++) {
5496 wptr = uint32toa_x(uii + 1, ' ', g_textbuf);
5497 wptr = dtoa_gx(g_maxt_extreme_stat[uii], '\n', wptr);
5498 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile)) {
5499 goto glm_linear_assoc_ret_WRITE_FAIL;
5500 }
5501 }
5502 if (fclose_null(&outfile)) {
5503 goto glm_linear_assoc_ret_WRITE_FAIL;
5504 }
5505 memcpy(outname_end, ".assoc.linear", 13);
5506 }
5507 memcpy(outname_end2, ".mperm", 7);
5508 }
5509 if (fopen_checked(outname, "w", &outfile)) {
5510 goto glm_linear_assoc_ret_OPEN_FAIL;
5511 }
5512 if (perm_adapt_nst) {
5513 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us EMP1 NP \n", plink_maxsnp);
5514 } else {
5515 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us EMP1 EMP2 \n", plink_maxsnp);
5516 #ifdef __cplusplus
5517 std::sort(g_maxt_extreme_stat, &(g_maxt_extreme_stat[perms_total]));
5518 #else
5519 qsort(g_maxt_extreme_stat, perms_total, sizeof(double), double_cmp);
5520 #endif
5521 // (debugging)
5522 // printf("extreme stats: %g %g %g\n", g_maxt_extreme_stat[0], g_maxt_extreme_stat[(perms_total - 1) / 2], g_maxt_extreme_stat[perms_total - 1]);
5523
5524 for (marker_idx = 0; marker_idx < marker_initial_ct; marker_idx++) {
5525 g_perm_attempt_ct[marker_idx] = perms_total - g_perm_attempt_ct[marker_idx];
5526 }
5527 }
5528 fprintf(outfile, g_textbuf, "SNP");
5529 chrom_fo_idx = 0xffffffffU;
5530 marker_uidx = next_unset_unsafe(marker_exclude, 0);
5531 marker_idx = 0;
5532 while (1) {
5533 do {
5534 chrom_end = chrom_info_ptr->chrom_fo_vidx_start[(++chrom_fo_idx) + 1];
5535 } while (marker_uidx >= chrom_end);
5536 uii = chrom_info_ptr->chrom_file_order[chrom_fo_idx];
5537 wptr_start = width_force(4, g_textbuf, chrom_name_write(chrom_info_ptr, uii, g_textbuf));
5538 *wptr_start++ = ' ';
5539 wptr_start[plink_maxsnp] = ' ';
5540 for (; marker_uidx < chrom_end;) {
5541 pval = ((double)(g_perm_2success_ct[marker_idx] + 2)) / ((double)(2 * (g_perm_attempt_ct[marker_idx] + 1)));
5542 if (pval <= pfilter) {
5543 fw_strcpy(plink_maxsnp, &(marker_ids[marker_uidx * max_marker_id_len]), wptr_start);
5544 wptr = &(wptr_start[1 + plink_maxsnp]);
5545 if (g_orig_stats[marker_idx] == -9) {
5546 wptr = memcpya(wptr, " NA NA", 25);
5547 } else {
5548 if (!perm_count) {
5549 wptr = dtoa_g_wxp4x(pval, 12, ' ', wptr);
5550 } else {
5551 wptr = dtoa_g_wxp4x(((double)g_perm_2success_ct[marker_idx]) * 0.5, 12, ' ', wptr);
5552 }
5553 if (perm_adapt_nst) {
5554 wptr = memseta(wptr, 32, 2);
5555 wptr = uint32toa_w10(g_perm_attempt_ct[marker_idx], wptr);
5556 } else {
5557 dzz = (int32_t)(perms_total - doublearr_greater_than(g_maxt_extreme_stat, perms_total, g_orig_stats[marker_idx] - EPSILON) + 1);
5558 if (!perm_count) {
5559 wptr = dtoa_g_wxp4(dzz / ((double)((int32_t)perms_total + 1)), 12, wptr);
5560 } else {
5561 wptr = dtoa_g_wxp4(dzz - 1, 12, wptr);
5562 }
5563 }
5564 }
5565 wptr = memcpya(wptr, " \n", 2);
5566 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
5567 goto glm_linear_assoc_ret_WRITE_FAIL;
5568 }
5569 }
5570 if (++marker_idx == marker_ct) {
5571 goto glm_linear_assoc_loop_end;
5572 }
5573 marker_uidx++;
5574 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
5575 }
5576 }
5577 glm_linear_assoc_loop_end:
5578 if (fclose_null(&outfile)) {
5579 goto glm_linear_assoc_ret_WRITE_FAIL;
5580 }
5581 LOGPRINTFWW("Permutation test report written to %s .\n", outname);
5582 }
5583
5584 while (0) {
5585 glm_linear_assoc_ret_NOMEM:
5586 retval = RET_NOMEM;
5587 break;
5588 glm_linear_assoc_ret_OPEN_FAIL:
5589 retval = RET_OPEN_FAIL;
5590 break;
5591 glm_linear_assoc_ret_READ_FAIL:
5592 retval = RET_READ_FAIL;
5593 break;
5594 glm_linear_assoc_ret_WRITE_FAIL:
5595 retval = RET_WRITE_FAIL;
5596 break;
5597 glm_linear_assoc_ret_NO_PERMUTATION_CLUSTERS:
5598 logerrprint("Error: No size 2+ clusters for permutation test.\n");
5599 retval = RET_INVALID_CMDLINE;
5600 break;
5601 glm_linear_assoc_ret_PHENO_CONSTANT:
5602 logerrprint("Warning: Skipping --linear since phenotype is constant.\n");
5603 break;
5604 glm_linear_assoc_ret_THREAD_CREATE_FAIL:
5605 retval = RET_THREAD_CREATE_FAIL;
5606 break;
5607 }
5608 glm_linear_assoc_ret_1:
5609 bigstack_reset(bigstack_mark);
5610 fclose_cond(outfile);
5611 fclose_cond(outfile_msa);
5612 free_cond(condition_uidxs);
5613 return retval;
5614 }
5615 #endif
5616
5617 int32_t glm_logistic_assoc_set_test(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, uint32_t glm_xchr_model, uint32_t glm_mperm_val, double pfilter, double output_min_p, uint32_t mtest_adjust, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude_orig, uintptr_t marker_ct_orig, uintptr_t* marker_exclude_mid, uintptr_t marker_ct_mid, char* marker_ids, uintptr_t max_marker_id_len, uintptr_t* marker_reverse, uintptr_t* regression_skip, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t* sex_male, Aperm_info* apip, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, uintptr_t* founder_pnm, uintptr_t* load_mask, uintptr_t* sample_include2, uintptr_t* sample_male_include2, uint32_t ld_ignore_x, uint32_t hh_exists, uint32_t hh_or_mt_exists, uint32_t perm_batch_size, Set_info* sip, uintptr_t* loadbuf_raw, uintptr_t param_ct_max, uintptr_t np_base, uintptr_t np_diploid, uintptr_t np_sex, uintptr_t sample_valid_ct, uint32_t sex_covar_everywhere) {
5618 // Very similar to glm_linear_assoc_set_test(); could merge them.
5619 unsigned char* bigstack_mark = g_bigstack_base;
5620 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
5621 uintptr_t cur_param_ct = 0;
5622 uintptr_t* marker_exclude = marker_exclude_mid;
5623 uintptr_t* unstopped_markers = nullptr;
5624 uintptr_t* loadbuf = g_loadbuf;
5625 uintptr_t* perm_adapt_set_unstopped = nullptr;
5626 double* orig_stats = g_orig_stats;
5627 double* sorted_chisq_buf = nullptr;
5628 uint32_t* marker_idx_to_uidx = nullptr;
5629 uint32_t* sorted_marker_idx_buf = nullptr;
5630 uint32_t* proxy_arr = nullptr;
5631 uint32_t* perm_2success_ct = nullptr;
5632 uint32_t* perm_attempt_ct = nullptr;
5633 uintptr_t marker_ct = marker_ct_mid;
5634 uintptr_t set_ct = 0;
5635 uintptr_t final_mask = get_final_mask(pheno_nm_ct);
5636 uintptr_t sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
5637 double adaptive_ci_zt = 0.0;
5638 uint32_t max_thread_ct = g_thread_ct;
5639 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
5640 uint32_t perms_done = 0;
5641 int32_t retval = 0;
5642 unsigned char* bigstack_mark2;
5643 uintptr_t* set_incl;
5644 uintptr_t* loadbuf_ptr;
5645 double* orig_set_scores;
5646 double* chisq_pmajor;
5647 double* read_dptr;
5648 double* write_dptr;
5649 uint32_t** setdefs;
5650 uint32_t** ld_map;
5651 uintptr_t marker_ctl;
5652 uintptr_t marker_midx;
5653 uintptr_t set_idx;
5654 uintptr_t perm_vec_ct;
5655 uintptr_t pidx;
5656 uintptr_t ulii;
5657 double chisq_threshold;
5658 double dxx;
5659 uint32_t perms_total;
5660 uint32_t max_sigset_size;
5661 uint32_t marker_unstopped_ct;
5662 uint32_t chrom_fo_idx;
5663 uint32_t chrom_end;
5664 uint32_t block_size;
5665 uint32_t block_end;
5666 uint32_t first_adapt_check;
5667 uint32_t marker_uidx;
5668 uint32_t marker_idx;
5669 uint32_t marker_idx2;
5670 uint32_t marker_bidx;
5671 uint32_t skip_ct;
5672 uint32_t uii;
5673 if (sip->set_test_lambda > 1.0) {
5674 dxx = 1.0 / sip->set_test_lambda;
5675 read_dptr = orig_stats;
5676 for (marker_midx = 0; marker_midx < marker_ct; marker_midx++) {
5677 *read_dptr *= dxx;
5678 read_dptr++;
5679 }
5680 }
5681 retval = set_test_common_init(threads, bedfile, bed_offset, outname, outname_end, unfiltered_marker_ct, marker_exclude_orig, marker_ct_orig, marker_ids, max_marker_id_len, marker_reverse, orig_stats, sip, chrom_info_ptr, unfiltered_sample_ct, sex_male, founder_pnm, ld_ignore_x, hh_exists, "--logistic", &marker_ct, &marker_exclude, &set_incl, &marker_idx_to_uidx, &setdefs, &set_ct, &max_sigset_size, &ld_map, &chisq_threshold, &orig_set_scores, &sorted_chisq_buf, &sorted_marker_idx_buf, &proxy_arr, &perm_adapt_set_unstopped, &perm_2success_ct, &perm_attempt_ct, &unstopped_markers);
5682 if (retval) {
5683 goto glm_logistic_assoc_set_test_ret_1;
5684 }
5685 if (!set_ct) {
5686 goto glm_logistic_assoc_set_test_write;
5687 }
5688 marker_ctl = BITCT_TO_WORDCT(marker_ct);
5689 if (marker_ct_mid != marker_ct) {
5690 inplace_delta_collapse_bitfield(regression_skip, marker_ct, marker_exclude_mid, marker_exclude);
5691 }
5692 if (glm_modifier & GLM_PERM) {
5693 perms_total = apip->max;
5694 first_adapt_check = (apip->min < apip->init_interval)? ((int32_t)apip->init_interval) : apip->min;
5695 adaptive_ci_zt = ltqnorm(1 - apip->beta / (2.0 * ((intptr_t)set_ct)));
5696 } else {
5697 perms_total = glm_mperm_val;
5698 first_adapt_check = perms_total + 1;
5699 }
5700 for (uii = 0; uii < set_ct; uii++) {
5701 perm_attempt_ct[uii] = perms_total;
5702 }
5703 if (max_thread_ct > perms_total) {
5704 max_thread_ct = perms_total;
5705 }
5706 if (bigstack_init_sfmtp(max_thread_ct)) {
5707 goto glm_logistic_assoc_set_test_ret_NOMEM;
5708 }
5709
5710 bigstack_mark2 = g_bigstack_base;
5711 glm_logistic_assoc_set_test_more_perms:
5712 bitvec_and(unstopped_markers, marker_ctl, regression_skip);
5713 bitvec_andnot(regression_skip, marker_ctl, unstopped_markers);
5714 skip_ct = popcount_longs(regression_skip, marker_ctl);
5715 marker_unstopped_ct = popcount_longs(unstopped_markers, marker_ctl);
5716
5717 if (perms_done) {
5718 uii = apip->init_interval;
5719 while (first_adapt_check <= perms_done) {
5720 first_adapt_check += (int32_t)(uii + ((int32_t)first_adapt_check) * apip->interval_slope);
5721 }
5722 }
5723 perm_vec_ct = perm_batch_size;
5724 // possible todo: split first batch to reduce adaptive overshoot
5725 if (perm_vec_ct > perms_total - perms_done) {
5726 perm_vec_ct = perms_total - perms_done;
5727 }
5728 g_perm_vec_ct = perm_vec_ct;
5729 if (perm_vec_ct >= CACHELINE_INT32 * max_thread_ct) {
5730 g_perm_generation_thread_ct = max_thread_ct;
5731 } else {
5732 g_perm_generation_thread_ct = MAXV(perm_vec_ct / CACHELINE_INT32, 1);
5733 }
5734 ulii = 0;
5735 if (!g_perm_cluster_ct) {
5736 if (spawn_threads(threads, &generate_cc_perms_thread, g_perm_generation_thread_ct)) {
5737 goto glm_logistic_assoc_set_test_ret_THREAD_CREATE_FAIL;
5738 }
5739 generate_cc_perms_thread((void*)ulii);
5740 } else {
5741 if (spawn_threads(threads, &generate_cc_cluster_perms_thread, g_perm_generation_thread_ct)) {
5742 goto glm_logistic_assoc_set_test_ret_THREAD_CREATE_FAIL;
5743 }
5744 generate_cc_cluster_perms_thread((void*)ulii);
5745 }
5746 join_threads(threads, g_perm_generation_thread_ct);
5747 if (bigstack_alloc_d(MODEL_BLOCKSIZE * perm_vec_ct, &g_mperm_save_all) ||
5748 bigstack_alloc_d(marker_ct * perm_vec_ct, &chisq_pmajor)) {
5749 goto glm_logistic_assoc_set_test_ret_NOMEM;
5750 }
5751 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
5752 write_dptr = &(chisq_pmajor[pidx * marker_ct]);
5753 for (marker_idx = 0, marker_idx2 = 0; marker_idx < skip_ct; marker_idx++, marker_idx2++) {
5754 next_set_unsafe_ck(regression_skip, &marker_idx2);
5755 write_dptr[marker_idx2] = -9;
5756 }
5757 }
5758 chrom_fo_idx = 0xffffffffU;
5759 marker_uidx = next_unset_unsafe(marker_exclude, 0);
5760 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5761 goto glm_logistic_assoc_set_test_ret_READ_FAIL;
5762 }
5763 marker_idx = 0;
5764 marker_idx2 = 0;
5765 chrom_end = 0;
5766 do {
5767 if (marker_uidx >= chrom_end) {
5768 // exploit overflow
5769 chrom_fo_idx++;
5770 refresh_chrom_info(chrom_info_ptr, marker_uidx, &chrom_end, &chrom_fo_idx, &g_is_x, &g_is_y, &uii, &g_min_ploidy_1);
5771 g_min_ploidy_1 |= uii;
5772 g_male_x_01 = 0;
5773 if (g_is_x) {
5774 cur_param_ct = param_ct_max;
5775 if (glm_xchr_model != 2) {
5776 g_male_x_01 = 1;
5777 }
5778 } else {
5779 cur_param_ct = np_base + np_diploid;
5780 }
5781 g_cur_param_ct = cur_param_ct;
5782 g_include_sex = sex_covar_everywhere || (g_is_x && np_sex);
5783 }
5784 block_size = 0;
5785 block_end = marker_unstopped_ct - marker_idx;
5786 if (block_end > GLM_BLOCKSIZE) {
5787 block_end = GLM_BLOCKSIZE;
5788 }
5789 do {
5790 if (!IS_SET(unstopped_markers, marker_idx2)) {
5791 do {
5792 marker_uidx++;
5793 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
5794 marker_idx2++;
5795 } while ((marker_uidx < chrom_end) && (!IS_SET(unstopped_markers, marker_idx2)));
5796 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5797 goto glm_logistic_assoc_set_test_ret_READ_FAIL;
5798 }
5799 if (marker_uidx >= chrom_end) {
5800 break;
5801 }
5802 }
5803 loadbuf_ptr = &(loadbuf[block_size * sample_valid_ctv2]);
5804 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_ptr)) {
5805 goto glm_logistic_assoc_set_test_ret_READ_FAIL;
5806 }
5807 if (g_min_ploidy_1 && hh_or_mt_exists) {
5808 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)loadbuf_ptr);
5809 }
5810 g_adapt_m_table[block_size] = marker_idx2++;
5811 block_size++;
5812 if (marker_idx + block_size == marker_unstopped_ct) {
5813 break;
5814 }
5815 marker_uidx++;
5816 if (IS_SET(marker_exclude, marker_uidx)) {
5817 marker_uidx = next_unset_unsafe(marker_exclude, marker_uidx);
5818 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
5819 goto glm_logistic_assoc_set_test_ret_READ_FAIL;
5820 }
5821 }
5822 } while ((block_size < block_end) && (marker_uidx < chrom_end));
5823 if (!block_size) {
5824 continue;
5825 }
5826 g_block_diff = block_size;
5827
5828 g_assoc_thread_ct = block_size / CACHELINE_INT32;
5829 if (g_assoc_thread_ct > max_thread_ct) {
5830 g_assoc_thread_ct = max_thread_ct;
5831 } else if (!g_assoc_thread_ct) {
5832 g_assoc_thread_ct = 1;
5833 }
5834 ulii = 0;
5835
5836 if (spawn_threads(threads, &glm_logistic_set_thread, g_assoc_thread_ct)) {
5837 goto glm_logistic_assoc_set_test_ret_THREAD_CREATE_FAIL;
5838 }
5839 glm_logistic_set_thread((void*)ulii);
5840 join_threads(threads, g_assoc_thread_ct);
5841
5842 for (pidx = 0; pidx < perm_vec_ct; pidx++) {
5843 // transpose
5844 read_dptr = &(g_mperm_save_all[pidx]);
5845 write_dptr = &(chisq_pmajor[pidx * marker_ct]);
5846 for (marker_bidx = 0; marker_bidx < block_size; marker_bidx++) {
5847 write_dptr[g_adapt_m_table[marker_bidx]] = read_dptr[marker_bidx * perm_vec_ct];
5848 }
5849 }
5850 marker_idx += block_size;
5851 } while (marker_idx < marker_unstopped_ct);
5852 perms_done += perm_vec_ct;
5853 compute_set_scores(marker_ct, perm_vec_ct, set_ct, chisq_pmajor, orig_set_scores, sorted_chisq_buf, sorted_marker_idx_buf, proxy_arr, setdefs, ld_map, apip, chisq_threshold, adaptive_ci_zt, first_adapt_check, perms_done, sip->set_max, perm_adapt_set_unstopped, perm_2success_ct, perm_attempt_ct);
5854 bigstack_reset(bigstack_mark2);
5855 if (perms_done < perms_total) {
5856 if (glm_modifier & GLM_PERM) {
5857 if (!extract_set_union(setdefs, set_ct, perm_adapt_set_unstopped, unstopped_markers, marker_ct)) {
5858 perms_done = 0;
5859 for (set_idx = 0; set_idx < set_ct; set_idx++) {
5860 if (perms_done < perm_attempt_ct[set_idx]) {
5861 perms_done = perm_attempt_ct[set_idx];
5862 }
5863 }
5864 goto glm_logistic_assoc_set_test_perms_done;
5865 }
5866 }
5867 printf("\r%u permutation%s complete.", perms_done, (perms_done != 1)? "s" : "");
5868 fflush(stdout);
5869 goto glm_logistic_assoc_set_test_more_perms;
5870 }
5871 glm_logistic_assoc_set_test_perms_done:
5872 putc_unlocked('\r', stdout);
5873 LOGPRINTF("%u permutation%s complete.\n", perms_done, (perms_done != 1)? "s" : "");
5874 glm_logistic_assoc_set_test_write:
5875 if (glm_modifier & GLM_PERM) {
5876 memcpy(outname_end, ".assoc.logistic.set.perm", 25);
5877 } else {
5878 memcpy(outname_end, ".assoc.logistic.set.mperm", 26);
5879 }
5880 retval = write_set_test_results(outname, &(outname_end[19]), sip, ld_map, setdefs, set_incl, set_ct, marker_ct_orig, marker_ct, marker_idx_to_uidx, marker_ids, max_marker_id_len, perm_2success_ct, perm_attempt_ct, mtest_adjust, perm_count, pfilter, output_min_p, chisq_threshold, orig_stats, sorted_chisq_buf, sorted_marker_idx_buf, proxy_arr);
5881 while (0) {
5882 glm_logistic_assoc_set_test_ret_NOMEM:
5883 retval = RET_NOMEM;
5884 break;
5885 glm_logistic_assoc_set_test_ret_READ_FAIL:
5886 retval = RET_READ_FAIL;
5887 break;
5888 glm_logistic_assoc_set_test_ret_THREAD_CREATE_FAIL:
5889 retval = RET_THREAD_CREATE_FAIL;
5890 break;
5891 }
5892 glm_logistic_assoc_set_test_ret_1:
5893 bigstack_reset(bigstack_mark);
5894 return retval;
5895 }
5896
5897 int32_t glm_logistic_assoc(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, double glm_vif_thresh, uint32_t glm_xchr_model, uint32_t glm_mperm_val, Range_list* parameters_range_list_ptr, Range_list* tests_range_list_ptr, double ci_size, double ci_zt, double pfilter, double output_min_p, uint32_t mtest_adjust, double adjust_lambda, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude_orig, uintptr_t marker_ct_orig, char* marker_ids, uintptr_t max_marker_id_len, uint32_t plink_maxsnp, uint32_t* marker_pos, char** marker_allele_ptrs, uintptr_t max_marker_allele_len, uintptr_t* marker_reverse, char* condition_mname, char* condition_fname, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t sample_ct, uintptr_t* sample_exclude, uint32_t cluster_ct, uint32_t* cluster_map, uint32_t* cluster_starts, Aperm_info* apip, uint32_t mperm_save, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, uintptr_t* pheno_c, uintptr_t covar_ct, char* covar_names, uintptr_t max_covar_name_len, uintptr_t* covar_nm, double* covar_d, uintptr_t* founder_info, uintptr_t* sex_nm, uintptr_t* sex_male, uint32_t ld_ignore_x, uint32_t hh_exists, uint32_t orig_perm_batch_size, Set_info* sip) {
5898 unsigned char* bigstack_mark = g_bigstack_base;
5899 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
5900 uintptr_t unfiltered_sample_ctl = BITCT_TO_WORDCT(unfiltered_sample_ct);
5901 FILE* outfile = nullptr;
5902 FILE* outfile_msa = nullptr;
5903 uintptr_t marker_ct = marker_ct_orig;
5904 uintptr_t sample_uidx = 0;
5905 uintptr_t cur_constraint_ct = 0;
5906 uintptr_t cur_param_ct = 0;
5907 uintptr_t cur_param_ctx = 0;
5908 uint32_t perms_total = 0;
5909 uint32_t is_set_test = glm_modifier & GLM_SET_TEST;
5910 uint32_t perm_adapt_nst = (glm_modifier & GLM_PERM) && (!is_set_test);
5911 uint32_t perm_maxt_nst = (glm_modifier & GLM_MPERM) && (!is_set_test);
5912 uint32_t covar_interactions = (glm_modifier / GLM_INTERACTION) & 1;
5913 uint32_t hethom = glm_modifier & GLM_HETHOM;
5914 uint32_t genotypic_or_hethom = (glm_modifier & (GLM_GENOTYPIC | GLM_HETHOM))? 1 : 0;
5915 uint32_t do_perms = glm_modifier & (GLM_PERM | GLM_MPERM);
5916 uint32_t do_perms_nst = do_perms && (!is_set_test);
5917 uint32_t perm_batch_size = orig_perm_batch_size;
5918 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
5919 uint32_t hide_covar = glm_modifier & GLM_HIDE_COVAR;
5920 uint32_t report_odds = !(glm_modifier & GLM_BETA);
5921
5922 // do_perms guarantees this is true for set test
5923 uint32_t fill_orig_chiabs = do_perms || mtest_adjust;
5924
5925 uint32_t display_ci = (ci_size > 0);
5926 uint32_t perm_pass_idx = 0;
5927 uint32_t pct = 0;
5928 uint32_t max_thread_ct = g_thread_ct;
5929 uint32_t hh_or_mt_exists = hh_exists;
5930 uint32_t skip_intercept = !(glm_modifier & GLM_INTERCEPT);
5931 int32_t retval = 0;
5932 double* constraints_con_major = nullptr;
5933 double* orig_pvals = nullptr;
5934 uintptr_t* marker_exclude = marker_exclude_orig;
5935 uintptr_t* founder_pnm = nullptr;
5936 uintptr_t* regression_skip = nullptr;
5937 uintptr_t* pheno_c_collapsed = nullptr;
5938 uint32_t* condition_uidxs = nullptr;
5939 uint32_t* marker_idx_to_uidx = nullptr;
5940 char* cur_param_names = nullptr;
5941 char* haploid_param_names = nullptr;
5942 char* wptr_start = nullptr;
5943 float geno_map[12];
5944 uint32_t mu_table[GLM_BLOCKSIZE];
5945 char numbuf[16];
5946 float* geno_map_ptr;
5947 char* writebuf;
5948 char* param_names;
5949 const char* main_effect;
5950
5951 // logistic: pval = chiprob_p(g_orig_stats[i] * g_orig_stats[i], 1);
5952 double* orig_stats_ptr;
5953
5954 char* outname_end2;
5955 char* wptr;
5956 char* wptr_start2;
5957 char* cptr;
5958 float* fptr;
5959 double* dptr;
5960 uintptr_t* loadbuf_raw;
5961 uintptr_t* load_mask;
5962 uintptr_t* sex_male_collapsed;
5963 uintptr_t* sample_include2;
5964 uintptr_t* sample_male_include2;
5965 uintptr_t* active_params;
5966 uintptr_t* haploid_params;
5967 uintptr_t* loadbuf_ptr;
5968 uintptr_t max_param_name_len;
5969 uintptr_t np_diploid;
5970 uintptr_t condition_ct;
5971 uintptr_t constraint_ct_max;
5972 uintptr_t np_sex;
5973 uintptr_t param_idx_end;
5974 uintptr_t sample_valid_ct;
5975 uintptr_t sample_valid_cta4;
5976 uintptr_t sample_valid_ctaw;
5977 uintptr_t sample_valid_ctv2;
5978 uintptr_t sample_idx;
5979 uintptr_t param_ctx_max;
5980 uintptr_t param_ctl_max;
5981 uintptr_t condition_list_start_idx;
5982 uintptr_t covar_start_idx;
5983 uintptr_t interaction_start_idx;
5984 uintptr_t sex_start_idx;
5985 uintptr_t np_base;
5986 uintptr_t param_ct_max;
5987 uintptr_t param_ct_maxa4;
5988 uintptr_t cur_missing_ct;
5989 uintptr_t cur_sample_valid_ct;
5990 uintptr_t param_idx;
5991 uintptr_t param_idx_fixed;
5992 uintptr_t constraint_idx;
5993 uintptr_t final_mask;
5994 uintptr_t ulii;
5995 uintptr_t uljj;
5996 double* msa_ptr;
5997 double se;
5998 double zval;
5999 double pval;
6000 double dxx;
6001 double dyy;
6002 double dzz;
6003 uint32_t mperm_save_all;
6004 uint32_t marker_initial_ct;
6005 uint32_t sex_covar_everywhere;
6006 uint32_t variation_in_sex;
6007 uint32_t x_sex_interaction;
6008 uint32_t marker_unstopped_ct;
6009 uint32_t chrom_fo_idx;
6010 uint32_t chrom_end;
6011 uint32_t block_size;
6012 uint32_t block_end;
6013 uint32_t tidx;
6014 uint32_t perm_idx;
6015 uint32_t marker_uidx;
6016 uint32_t marker_uidx2;
6017 uint32_t marker_idx;
6018 uint32_t marker_idx2;
6019 uint32_t marker_idx3;
6020 uint32_t marker_bidx;
6021 uint32_t chrom_idx;
6022 uint32_t loop_end;
6023 uint32_t regression_fail;
6024 uint32_t uii;
6025 uint32_t ujj;
6026 uint32_t ukk;
6027 numbuf[0] = ' ';
6028 if (pheno_nm_ct < 2) {
6029 logerrprint("Warning: Skipping --logistic since less than two phenotypes are present.\n");
6030 goto glm_logistic_assoc_ret_1;
6031 }
6032 if ((chrom_info_ptr->xymt_codes[MT_OFFSET] != -2) && is_set(chrom_info_ptr->chrom_mask, chrom_info_ptr->xymt_codes[MT_OFFSET])) {
6033 hh_or_mt_exists |= NXMHH_EXISTS;
6034 }
6035 if (is_set_test) {
6036 if (bigstack_alloc_ul(unfiltered_sample_ctl, &founder_pnm)) {
6037 goto glm_logistic_assoc_ret_NOMEM;
6038 }
6039 memcpy(founder_pnm, pheno_nm, unfiltered_sample_ctl * sizeof(intptr_t));
6040 bitvec_and(founder_info, unfiltered_sample_ctl, founder_pnm);
6041 if (extract_set_union_unfiltered(sip, nullptr, unfiltered_marker_ct, marker_exclude_orig, &marker_exclude, &marker_ct)) {
6042 goto glm_logistic_assoc_ret_NOMEM;
6043 }
6044 if (glm_modifier & GLM_PERM) {
6045 if (orig_perm_batch_size > apip->max) {
6046 orig_perm_batch_size = apip->max;
6047 }
6048 } else {
6049 if (orig_perm_batch_size > glm_mperm_val) {
6050 orig_perm_batch_size = glm_mperm_val;
6051 }
6052 }
6053 }
6054 retval = glm_common_init(bedfile, bed_offset, glm_modifier, 0, glm_xchr_model, parameters_range_list_ptr, tests_range_list_ptr, mtest_adjust, unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, max_marker_allele_len, marker_reverse, condition_mname, condition_fname, chrom_info_ptr, unfiltered_sample_ct, sample_ct, sample_exclude, pheno_nm_ct, pheno_nm, covar_ct, covar_names, max_covar_name_len, covar_nm, covar_d, sex_nm, sex_male, hh_or_mt_exists, do_perms, is_set_test, &perm_batch_size, &max_param_name_len, &np_diploid, &condition_ct, &np_sex, &marker_initial_ct, &sex_covar_everywhere, &variation_in_sex, &x_sex_interaction, &constraint_ct_max, &param_idx_end, &loadbuf_raw, &load_mask, &sex_male_collapsed, &sample_include2, &sample_male_include2, &active_params, &haploid_params, &condition_uidxs, &writebuf, &sample_valid_ct, &param_ctx_max, &param_ctl_max, &condition_list_start_idx, &covar_start_idx, &interaction_start_idx, &sex_start_idx, &np_base, &param_ct_max);
6055 if (retval) {
6056 goto glm_logistic_assoc_ret_1;
6057 }
6058 if (sample_valid_ct <= param_ct_max) {
6059 logerrprint("Warning: Skipping --logistic since # variables >= # samples.\n");
6060 if (pheno_nm_ct > param_ct_max) {
6061 logerrprint("(Check your covariates--all samples with at least one missing covariate are\nexcluded from this analysis.)\n");
6062 }
6063 goto glm_logistic_assoc_ret_1;
6064 }
6065 sample_valid_cta4 = round_up_pow2(sample_valid_ct, 4);
6066 sample_valid_ctaw = BITCT_TO_ALIGNED_WORDCT(sample_valid_ct);
6067 sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
6068 final_mask = get_final_mask(sample_valid_ct);
6069 param_ct_maxa4 = round_up_pow2(param_ct_max, 4);
6070 if (bigstack_alloc_d(marker_initial_ct, &g_orig_stats) ||
6071 bigstack_alloc_c(param_ctx_max * max_param_name_len, &param_names) ||
6072 bigstack_alloc_f((variation_in_sex + interaction_start_idx - condition_list_start_idx) * sample_valid_ct, &g_fixed_covars_cov_major_f) ||
6073 bigstack_alloc_ui(marker_initial_ct, &g_nm_cts)) {
6074 goto glm_logistic_assoc_ret_NOMEM;
6075 }
6076 if (!is_set_test) {
6077 // use this array to track regression failures even in max(T) case
6078 if (bigstack_calloc_uc(round_up_pow2(marker_initial_ct, BYTECT), &g_perm_adapt_stop)) {
6079 goto glm_logistic_assoc_ret_NOMEM;
6080 }
6081 } else {
6082 g_perm_adapt_stop = nullptr;
6083 if (bigstack_calloc_ul(BITCT_TO_WORDCT(marker_initial_ct), &regression_skip)) {
6084 goto glm_logistic_assoc_ret_NOMEM;
6085 }
6086 }
6087
6088 param_idx = 1;
6089 if (glm_modifier & GLM_RECESSIVE) {
6090 main_effect = glm_main_effects;
6091 } else if (glm_modifier & GLM_DOMINANT) {
6092 main_effect = &(glm_main_effects[4]);
6093 } else if (hethom) {
6094 main_effect = &(glm_main_effects[8]);
6095 } else {
6096 main_effect = &(glm_main_effects[12]);
6097 }
6098 if (IS_SET(active_params, 1)) {
6099 memcpy(&(param_names[max_param_name_len]), main_effect, 4);
6100 param_idx++;
6101 }
6102 if (genotypic_or_hethom && IS_SET(active_params, 2)) {
6103 if (hethom) {
6104 memcpy(&(param_names[param_idx * max_param_name_len]), "HET", 4);
6105 } else {
6106 memcpy(&(param_names[param_idx * max_param_name_len]), "DOMDEV", 7);
6107 }
6108 param_idx++;
6109 }
6110 // 0..3: diploid chromosomes, X chromosome female
6111 // 4..7: X chromosome male
6112 // 8..11: haploid
6113 fill_float_zero(12, geno_map);
6114 geno_map[0] = 1;
6115 geno_map[2] = 1;
6116 geno_map[4] = 1;
6117 geno_map[8] = 1;
6118 if (glm_modifier & GLM_CONDITION_RECESSIVE) {
6119 geno_map[2] = 0;
6120 } else if (!(glm_modifier & GLM_CONDITION_DOMINANT)) {
6121 geno_map[0] = 2;
6122 if (glm_xchr_model == 2) {
6123 geno_map[4] = 2;
6124 }
6125 }
6126 for (param_idx_fixed = 0; param_idx_fixed < condition_ct; param_idx_fixed++) {
6127 marker_uidx = condition_uidxs[param_idx_fixed];
6128 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
6129 goto glm_logistic_assoc_ret_READ_FAIL;
6130 }
6131 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, g_loadbuf)) {
6132 goto glm_logistic_assoc_ret_READ_FAIL;
6133 }
6134 chrom_idx = get_variant_chrom(chrom_info_ptr, marker_uidx);
6135 geno_map_ptr = geno_map;
6136 if (IS_SET(chrom_info_ptr->haploid_mask, chrom_idx) || (chrom_idx == (uint32_t)chrom_info_ptr->xymt_codes[MT_OFFSET])) {
6137 g_is_x = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[X_OFFSET]);
6138 g_is_y = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[Y_OFFSET]);
6139 if (hh_or_mt_exists) {
6140 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)g_loadbuf);
6141 }
6142 if (!g_is_x) {
6143 geno_map_ptr = &(geno_map[8]);
6144 }
6145 } else {
6146 g_is_x = 0;
6147 }
6148 if (!g_is_x) {
6149 glm_loadbuf_to_floats(g_loadbuf, sample_valid_ct, &(g_fixed_covars_cov_major_f[param_idx_fixed * sample_valid_ct]), geno_map_ptr, nullptr);
6150 } else {
6151 glm_loadbuf_to_floats_x(g_loadbuf, sex_male_collapsed, sample_valid_ct, &(g_fixed_covars_cov_major_f[param_idx_fixed * sample_valid_ct]), geno_map_ptr, nullptr);
6152 }
6153 if (is_set(active_params, param_idx_fixed + condition_list_start_idx)) {
6154 strcpy(&(param_names[param_idx * max_param_name_len]), &(marker_ids[marker_uidx * max_marker_id_len]));
6155 param_idx++;
6156 }
6157 }
6158 for (uii = 0; uii < covar_ct; param_idx_fixed++, uii++) {
6159 // sample-major to covariate-major
6160 fptr = &(g_fixed_covars_cov_major_f[param_idx_fixed * sample_valid_ct]);
6161 dptr = &(covar_d[uii]);
6162 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_ct; sample_uidx++, sample_idx++) {
6163 next_unset_ul_unsafe_ck(sample_exclude, &sample_uidx);
6164 if (IS_SET(load_mask, sample_uidx)) {
6165 *fptr++ = (float)dptr[sample_idx * covar_ct];
6166 }
6167 }
6168 }
6169 for (uii = 0; uii < covar_ct; uii++) {
6170 if (is_set(active_params, uii + covar_start_idx)) {
6171 strcpy(&(param_names[param_idx * max_param_name_len]), &(covar_names[uii * max_covar_name_len]));
6172 param_idx++;
6173 }
6174 }
6175 if (covar_interactions) {
6176 ujj = interaction_start_idx;
6177 for (uii = 0; uii < condition_ct; uii++) {
6178 if (is_set(active_params, ujj++)) {
6179 wptr = memcpyl3a(&(param_names[param_idx * max_param_name_len]), main_effect);
6180 wptr = memcpya(wptr, "xCSNP", 5);
6181 uint32toa_x(uii + 1, '\0', wptr);
6182 param_idx++;
6183 }
6184 if (genotypic_or_hethom) {
6185 if (is_set(active_params, ujj++)) {
6186 wptr = &(param_names[param_idx * max_param_name_len]);
6187 if (hethom) {
6188 wptr = memcpya(wptr, "HETxCSNP", 8);
6189 } else {
6190 wptr = memcpya(wptr, "DOMDEVxCSNP", 11);
6191 }
6192 uint32toa_x(uii + 1, '\0', wptr);
6193 param_idx++;
6194 }
6195 }
6196 }
6197 for (uii = 0; uii < covar_ct; uii++) {
6198 if (is_set(active_params, ujj++)) {
6199 wptr = memcpyl3a(&(param_names[param_idx * max_param_name_len]), main_effect);
6200 *wptr++ = 'x';
6201 strcpy(wptr, &(covar_names[uii * max_covar_name_len]));
6202 param_idx++;
6203 }
6204 if (genotypic_or_hethom) {
6205 if (is_set(active_params, ujj++)) {
6206 wptr = &(param_names[param_idx * max_param_name_len]);
6207 if (hethom) {
6208 wptr = memcpya(wptr, "HETx", 4);
6209 } else {
6210 wptr = memcpya(wptr, "DOMDEVx", 7);
6211 }
6212 strcpy(wptr, &(covar_names[uii * max_covar_name_len]));
6213 param_idx++;
6214 }
6215 }
6216 }
6217 }
6218 if (variation_in_sex) {
6219 fptr = &(g_fixed_covars_cov_major_f[param_idx_fixed * sample_valid_ct]);
6220 fill_float_zero(sample_valid_ct, fptr);
6221 sample_idx = 0;
6222 while (1) {
6223 next_set_ul_ck(sex_male_collapsed, sample_valid_ct, &sample_idx);
6224 if (sample_idx == sample_valid_ct) {
6225 break;
6226 }
6227 fptr[sample_idx++] = 1;
6228 }
6229 if (IS_SET(active_params, sex_start_idx)) {
6230 memcpy(&(param_names[param_idx * max_param_name_len]), "SEX", 4);
6231 param_idx++;
6232 }
6233 if (covar_interactions) {
6234 if (is_set(active_params, sex_start_idx + 1)) {
6235 wptr = memcpyl3a(&(param_names[param_idx * max_param_name_len]), main_effect);
6236 memcpy(wptr, "xSEX", 5);
6237 param_idx++;
6238 }
6239 if (genotypic_or_hethom && is_set(active_params, sex_start_idx + 2)) {
6240 wptr = &(param_names[param_idx * max_param_name_len]);
6241 if (hethom) {
6242 memcpy(wptr, "HETxSEX", 8);
6243 } else {
6244 memcpy(wptr, "DOMDEVxSEX", 11);
6245 }
6246 param_idx++;
6247 }
6248 } else if (x_sex_interaction) {
6249 // active_params bit must be set
6250 memcpy(&(param_names[param_idx * max_param_name_len]), "XxSEX", 6);
6251 param_idx++;
6252 }
6253 }
6254 if (genotypic_or_hethom) {
6255 if (bigstack_alloc_c(np_base * max_param_name_len, &haploid_param_names)) {
6256 goto glm_logistic_assoc_ret_NOMEM;
6257 }
6258 for (uii = 1, param_idx = 1; param_idx < np_base; uii++, param_idx++) {
6259 next_set_unsafe_ck(haploid_params, &uii);
6260 strcpy(&(haploid_param_names[param_idx * max_param_name_len]), &(param_names[uii * max_param_name_len]));
6261 }
6262 }
6263
6264 if (constraint_ct_max) {
6265 if (bigstack_alloc_d(constraint_ct_max * param_ct_max, &constraints_con_major)) {
6266 goto glm_logistic_assoc_ret_NOMEM;
6267 }
6268 // special case: df may vary between chromosomes, so refill suffix at
6269 // beginning of each chromosome
6270 wptr = &(param_names[param_ct_max * max_param_name_len]);
6271 if (tests_range_list_ptr->name_ct) {
6272 memcpy(wptr, "USER_", 6);
6273 } else if (glm_modifier & GLM_TEST_ALL) {
6274 memcpy(wptr, "FULL_", 6);
6275 } else {
6276 memcpy(wptr, "GENO_", 6);
6277 }
6278 }
6279 g_constraints_con_major = constraints_con_major;
6280 if (!perm_maxt_nst) {
6281 g_aperm_alpha = apip->alpha;
6282 mperm_save = 0;
6283 }
6284 mperm_save_all = mperm_save & MPERM_DUMP_ALL;
6285 if (fill_orig_chiabs) {
6286 if (mtest_adjust && (!is_set_test)) {
6287 if (bigstack_alloc_d(marker_initial_ct, &orig_pvals) ||
6288 bigstack_alloc_ui(marker_initial_ct, &marker_idx_to_uidx)) {
6289 goto glm_logistic_assoc_ret_NOMEM;
6290 }
6291 }
6292 if (do_perms_nst) {
6293 // need this for max(T) now since we need to track permutation failures
6294 if (bigstack_calloc_ui(marker_initial_ct, &g_perm_2success_ct) ||
6295 bigstack_calloc_ui(marker_initial_ct, &g_perm_attempt_ct)) {
6296 goto glm_logistic_assoc_ret_NOMEM;
6297 }
6298 perms_total = perm_adapt_nst? apip->max : glm_mperm_val;
6299 if (perms_total < orig_perm_batch_size) {
6300 orig_perm_batch_size = perms_total;
6301 }
6302 perm_batch_size = orig_perm_batch_size;
6303 uii = perm_batch_size;
6304 if (uii > GLM_BLOCKSIZE / CACHELINE_INT32) {
6305 uii = GLM_BLOCKSIZE / CACHELINE_INT32;
6306 }
6307 if (max_thread_ct > uii) {
6308 max_thread_ct = uii;
6309 }
6310 if (!perm_adapt_nst) {
6311 if (bigstack_alloc_d(round_up_pow2(perm_batch_size, CACHELINE_DBL) * max_thread_ct, &g_maxt_thread_results) ||
6312 bigstack_calloc_d(perms_total, &g_maxt_extreme_stat)) {
6313 goto glm_logistic_assoc_ret_NOMEM;
6314 }
6315 if (mperm_save_all) {
6316 if (bigstack_alloc_d(((uintptr_t)marker_initial_ct) * perm_batch_size, &g_mperm_save_all)) {
6317 goto glm_logistic_assoc_ret_NOMEM;
6318 }
6319 memcpy(outname_end, ".mperm.dump.all", 16);
6320 if (fopen_checked(outname, "w", &outfile_msa)) {
6321 goto glm_logistic_assoc_ret_OPEN_FAIL;
6322 }
6323 if (putc_checked('0', outfile_msa)) {
6324 goto glm_logistic_assoc_ret_WRITE_FAIL;
6325 }
6326 LOGPRINTFWW("Dumping all permutation chi-square values to %s .\n", outname);
6327 }
6328 }
6329 g_perm_batch_max = perm_batch_size;
6330 }
6331 }
6332 if (do_perms) {
6333 if (cluster_starts) {
6334 retval = cluster_include_and_reindex(unfiltered_sample_ct, load_mask, 1, pheno_c, sample_valid_ct, 0, cluster_ct, cluster_map, cluster_starts, &g_perm_cluster_ct, &g_perm_cluster_map, &g_perm_cluster_starts, &g_perm_cluster_case_cts, &g_perm_cluster_cc_preimage);
6335 if (retval) {
6336 goto glm_logistic_assoc_ret_1;
6337 }
6338 if (!g_perm_cluster_ct) {
6339 goto glm_logistic_assoc_ret_NO_PERMUTATION_CLUSTERS;
6340 }
6341 if (cluster_alloc_and_populate_magic_nums(g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, &g_perm_tot_quotients, &g_perm_totq_magics, &g_perm_totq_preshifts, &g_perm_totq_postshifts, &g_perm_totq_incrs)) {
6342 goto glm_logistic_assoc_ret_NOMEM;
6343 }
6344 if (bigstack_alloc_ui(sample_valid_ct, &g_perm_sample_to_cluster)) {
6345 goto glm_logistic_assoc_ret_NOMEM;
6346 }
6347 fill_unfiltered_sample_to_cluster(sample_valid_ct, g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, g_perm_sample_to_cluster);
6348 }
6349 g_perm_tot_quotient = 0x100000000LLU / sample_valid_ct;
6350 magic_num(g_perm_tot_quotient, &g_perm_totq_magic, &g_perm_totq_preshift, &g_perm_totq_postshift, &g_perm_totq_incr);
6351 if (!is_set_test) {
6352 if (bigstack_init_sfmtp(max_thread_ct)) {
6353 goto glm_logistic_assoc_ret_NOMEM;
6354 }
6355 }
6356 } else {
6357 orig_perm_batch_size = 1;
6358 }
6359 g_logistic_mt = (Logistic_multithread*)bigstack_alloc(max_thread_ct * sizeof(Logistic_multithread));
6360 if (!g_logistic_mt) {
6361 goto glm_logistic_assoc_ret_NOMEM;
6362 }
6363 for (tidx = 0; tidx < max_thread_ct; tidx++) {
6364 // covars_cov_major, param_2d_buf, param_2d_buf2 matrices must have 16-byte
6365 // aligned rows
6366 // (no need to worry about 1D 16-byte alignment requirements since
6367 // bigstack_alloc actually forces 64-byte alignment, and allocation sizes
6368 // are automatically rounded up)
6369 uii = (tidx || (orig_perm_batch_size > 1) || skip_intercept)? 1 : 0;
6370 if (bigstack_alloc_f(param_ct_max * sample_valid_cta4, &(g_logistic_mt[tidx].cur_covars_cov_major)) ||
6371 bigstack_alloc_f(param_ct_maxa4 * orig_perm_batch_size, &(g_logistic_mt[tidx].coef)) ||
6372 bigstack_alloc_f(sample_valid_cta4, &(g_logistic_mt[tidx].pp)) ||
6373 bigstack_alloc_f(sample_valid_ct, &(g_logistic_mt[tidx].sample_1d_buf)) ||
6374 bigstack_alloc_f(sample_valid_ct, &(g_logistic_mt[tidx].pheno_buf)) ||
6375 bigstack_alloc_f(param_ct_max, &(g_logistic_mt[tidx].param_1d_buf)) ||
6376 bigstack_alloc_f(param_ct_max, &(g_logistic_mt[tidx].param_1d_buf2)) ||
6377 bigstack_alloc_f(param_ct_max * param_ct_maxa4, &(g_logistic_mt[tidx].param_2d_buf)) ||
6378 bigstack_alloc_f(param_ct_max * param_ct_maxa4, &(g_logistic_mt[tidx].param_2d_buf2)) ||
6379 bigstack_alloc_f(orig_perm_batch_size * (param_ctx_max - uii), &(g_logistic_mt[tidx].regression_results)) ||
6380 bigstack_alloc_ul(BITCT_TO_WORDCT(orig_perm_batch_size), &(g_logistic_mt[tidx].perm_fails))) {
6381 goto glm_logistic_assoc_ret_NOMEM;
6382 }
6383 if (constraint_ct_max) {
6384 g_logistic_mt[tidx].mi_buf = (MATRIX_INVERT_BUF1_TYPE*)bigstack_alloc(param_ct_max * MATRIX_INVERT_BUF1_ELEM_ALLOC);
6385 if (!(g_logistic_mt[tidx].mi_buf)) {
6386 goto glm_logistic_assoc_ret_NOMEM;
6387 }
6388 if (bigstack_alloc_d(param_ct_max, &(g_logistic_mt[tidx].param_1d_dbuf)) ||
6389 bigstack_alloc_d(param_ct_max * param_ct_max, &(g_logistic_mt[tidx].param_2d_dbuf)) ||
6390 bigstack_alloc_d(param_ct_max * param_ct_max, &(g_logistic_mt[tidx].param_2d_dbuf2)) ||
6391 bigstack_alloc_d(param_ct_max * constraint_ct_max, &(g_logistic_mt[tidx].param_df_dbuf)) ||
6392 bigstack_alloc_d(constraint_ct_max * constraint_ct_max, &(g_logistic_mt[tidx].df_df_dbuf)) ||
6393 bigstack_alloc_d(constraint_ct_max, &(g_logistic_mt[tidx].df_dbuf))) {
6394 goto glm_logistic_assoc_ret_NOMEM;
6395 }
6396 } else {
6397 g_logistic_mt[tidx].mi_buf = nullptr;
6398 g_logistic_mt[tidx].param_1d_dbuf = nullptr;
6399 g_logistic_mt[tidx].param_2d_dbuf = nullptr;
6400 g_logistic_mt[tidx].param_2d_dbuf2 = nullptr;
6401 g_logistic_mt[tidx].param_df_dbuf = nullptr;
6402 g_logistic_mt[tidx].df_df_dbuf = nullptr;
6403 g_logistic_mt[tidx].df_dbuf = nullptr;
6404 }
6405 }
6406
6407 if (bigstack_alloc_ul(sample_valid_ctaw, &pheno_c_collapsed)) {
6408 goto glm_logistic_assoc_ret_NOMEM;
6409 }
6410 // bugfix (21 Sep 2020): trailing word not guaranteed to be zero
6411 pheno_c_collapsed[sample_valid_ctaw - 1] = 0;
6412 copy_bitarr_subset(pheno_c, load_mask, unfiltered_sample_ct, sample_valid_ct, pheno_c_collapsed);
6413 g_perm_case_ct = popcount_longs(pheno_c_collapsed, sample_valid_ctaw);
6414 if ((!g_perm_case_ct) || (g_perm_case_ct == sample_valid_ct)) {
6415 goto glm_logistic_assoc_ret_PHENO_CONSTANT;
6416 }
6417 if (do_perms) {
6418 if (bigstack_alloc_ul(orig_perm_batch_size * sample_valid_ctaw, &g_perm_vecs)) {
6419 goto glm_logistic_assoc_ret_NOMEM;
6420 }
6421 g_perm_is_1bit = 1;
6422 }
6423
6424 outname_end2 = memcpyb(outname_end, ".assoc.logistic", 16);
6425 if (fopen_checked(outname, "w", &outfile)) {
6426 goto glm_logistic_assoc_ret_OPEN_FAIL;
6427 }
6428 LOGPRINTFWW5("Writing logistic model association results to %s ... ", outname);
6429 fflush(stdout);
6430 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us BP A1 TEST NMISS %s ", plink_maxsnp, report_odds? " OR" : "BETA");
6431 fprintf(outfile, g_textbuf, "SNP");
6432 if (display_ci) {
6433 uii = (uint32_t)((int32_t)(ci_size * (100 + EPSILON)));
6434 if (uii >= 10) {
6435 fprintf(outfile, " SE L%u U%u ", uii, uii);
6436 } else {
6437 fprintf(outfile, " SE L%u U%u ", uii, uii);
6438 }
6439 }
6440 fputs(" STAT P \n", outfile);
6441 loop_end = marker_initial_ct / 100;
6442 marker_unstopped_ct = marker_initial_ct;
6443 g_adaptive_ci_zt = ltqnorm(1 - apip->beta / (2.0 * ((int32_t)marker_initial_ct)));
6444
6445 // ----- begin main loop -----
6446 glm_logistic_assoc_more_perms:
6447 if (do_perms_nst) {
6448 if (perm_adapt_nst) {
6449 if (perm_pass_idx) {
6450 while (g_first_adapt_check <= g_perms_done) {
6451 g_first_adapt_check += (int32_t)(apip->init_interval + ((int32_t)g_first_adapt_check) * apip->interval_slope);
6452 }
6453 } else {
6454 if (apip->min < apip->init_interval) {
6455 g_first_adapt_check = (int32_t)(apip->init_interval);
6456 } else {
6457 g_first_adapt_check = apip->min;
6458 }
6459 g_adaptive_intercept = apip->init_interval;
6460 g_adaptive_slope = apip->interval_slope;
6461 }
6462 }
6463 g_perm_vec_ct = perm_batch_size;
6464 if (perm_adapt_nst && (g_perms_done < perm_batch_size)) {
6465 // special case: split first batch to reduce adaptive overshoot
6466 ulii = perm_batch_size;
6467 uljj = (intptr_t)(apip->init_interval);
6468 uljj = MAXV(uljj, apip->min);
6469 uljj *= 2;
6470 uljj = MAXV(64, uljj);
6471 while (ulii >= (uljj << perm_pass_idx)) {
6472 ulii >>= 1;
6473 }
6474 g_perm_vec_ct = ulii - g_perms_done;
6475 }
6476 if (g_perm_vec_ct > perms_total - g_perms_done) {
6477 g_perm_vec_ct = perms_total - g_perms_done;
6478 }
6479 ulii = 0;
6480 g_perm_generation_thread_ct = MINV(max_thread_ct, g_perm_vec_ct);
6481 if (!g_perm_cluster_ct) {
6482 if (spawn_threads(threads, &generate_cc_perms_thread, g_perm_generation_thread_ct)) {
6483 goto glm_logistic_assoc_ret_THREAD_CREATE_FAIL;
6484 }
6485 generate_cc_perms_thread((void*)ulii);
6486 } else {
6487 if (spawn_threads(threads, &generate_cc_cluster_perms_thread, g_perm_generation_thread_ct)) {
6488 goto glm_logistic_assoc_ret_THREAD_CREATE_FAIL;
6489 }
6490 generate_cc_cluster_perms_thread((void*)ulii);
6491 }
6492 join_threads(threads, g_perm_generation_thread_ct);
6493 }
6494 chrom_fo_idx = 0xffffffffU;
6495 marker_uidx = next_unset_unsafe(marker_exclude, 0);
6496 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
6497 goto glm_logistic_assoc_ret_READ_FAIL;
6498 }
6499 if (!perm_pass_idx) {
6500 fputs("0%", stdout);
6501 fflush(stdout);
6502 }
6503 marker_idx = 0;
6504 marker_idx2 = 0;
6505 chrom_end = 0;
6506 do {
6507 if (marker_uidx >= chrom_end) {
6508 // exploit overflow
6509 do {
6510 chrom_fo_idx++;
6511 refresh_chrom_info(chrom_info_ptr, marker_uidx, &chrom_end, &chrom_fo_idx, &g_is_x, &g_is_y, &uii, &g_min_ploidy_1);
6512 g_min_ploidy_1 |= uii;
6513 } while ((!glm_xchr_model) && g_min_ploidy_1);
6514 uii = chrom_info_ptr->chrom_file_order[chrom_fo_idx];
6515 wptr_start = width_force(4, writebuf, chrom_name_write(chrom_info_ptr, uii, writebuf));
6516 *wptr_start++ = ' ';
6517 fill_double_zero(constraint_ct_max * param_ct_max, constraints_con_major);
6518 g_male_x_01 = 0;
6519 if (g_is_x) {
6520 cur_param_ct = param_ct_max;
6521 cur_constraint_ct = constraint_ct_max;
6522 cur_param_names = param_names;
6523 if (glm_xchr_model != 2) {
6524 g_male_x_01 = 1;
6525 }
6526 } else if ((!g_min_ploidy_1) || (!genotypic_or_hethom)) {
6527 cur_param_ct = np_base + np_diploid;
6528 if (constraint_ct_max) {
6529 cur_constraint_ct = popcount_bit_idx(g_joint_test_params, 0, cur_param_ct - 1);
6530 } else {
6531 cur_constraint_ct = 0;
6532 }
6533 cur_param_names = param_names;
6534 } else {
6535 cur_param_ct = np_base;
6536 cur_constraint_ct = 0;
6537 if (constraint_ct_max) {
6538 for (ulii = 0; ulii < param_ctl_max; ulii++) {
6539 uljj = g_joint_test_params[ulii] & haploid_params[ulii];
6540 while (uljj) {
6541 uii = CTZLU(uljj) + ulii * BITCT;
6542 constraints_con_major[cur_constraint_ct * cur_param_ct + uii + 1] = 1;
6543 cur_constraint_ct++;
6544 uljj &= uljj - 1;
6545 }
6546 }
6547 }
6548 cur_param_names = haploid_param_names;
6549 }
6550 g_cur_param_ct = cur_param_ct;
6551 g_cur_constraint_ct = cur_constraint_ct;
6552 if (!hide_covar) {
6553 param_idx_end = cur_param_ct;
6554 }
6555 cur_param_ctx = cur_param_ct;
6556 g_include_sex = sex_covar_everywhere || (g_is_x && np_sex);
6557 if (cur_constraint_ct) {
6558 cur_param_ctx++;
6559 if (g_is_x || (!g_min_ploidy_1) || (!genotypic_or_hethom)) {
6560 ulii = 0;
6561 for (constraint_idx = 0; constraint_idx < cur_constraint_ct; ulii++, constraint_idx++) {
6562 next_set_ul_unsafe_ck(g_joint_test_params, &ulii);
6563 constraints_con_major[constraint_idx * cur_param_ct + ulii + 1] = 1;
6564 }
6565 }
6566 wptr = uint32toa(cur_constraint_ct, &(param_names[param_ct_max * max_param_name_len + 5]));
6567 memcpy(wptr, "DF", 3);
6568 }
6569 }
6570 block_size = 0;
6571 block_end = marker_unstopped_ct - marker_idx;
6572 if (block_end > GLM_BLOCKSIZE) {
6573 block_end = GLM_BLOCKSIZE;
6574 }
6575 do {
6576 if (g_perm_adapt_stop && g_perm_adapt_stop[marker_idx2]) {
6577 do {
6578 marker_uidx++;
6579 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
6580 marker_idx2++;
6581 } while ((marker_uidx < chrom_end) && g_perm_adapt_stop[marker_idx2]);
6582 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
6583 goto glm_logistic_assoc_ret_READ_FAIL;
6584 }
6585 if (marker_uidx >= chrom_end) {
6586 break;
6587 }
6588 }
6589 loadbuf_ptr = &(g_loadbuf[block_size * sample_valid_ctv2]);
6590 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_ptr)) {
6591 goto glm_logistic_assoc_ret_READ_FAIL;
6592 }
6593 if (g_min_ploidy_1 && hh_or_mt_exists) {
6594 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, g_is_x, g_is_y, (unsigned char*)loadbuf_ptr);
6595 }
6596 g_adapt_m_table[block_size] = marker_idx2++;
6597 mu_table[block_size++] = marker_uidx;
6598 if (marker_idx + block_size == marker_unstopped_ct) {
6599 break;
6600 }
6601 marker_uidx++;
6602 if (IS_SET(marker_exclude, marker_uidx)) {
6603 marker_uidx = next_unset_unsafe(marker_exclude, marker_uidx);
6604 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
6605 goto glm_logistic_assoc_ret_READ_FAIL;
6606 }
6607 }
6608 } while ((block_size < block_end) && (marker_uidx < chrom_end));
6609 if (!block_size) {
6610 continue;
6611 }
6612 g_block_diff = block_size;
6613 if (!perm_pass_idx) {
6614 for (marker_bidx = 0; marker_bidx < block_size; marker_bidx++) {
6615 // 1. fill design matrix and make transposed copy; fill g_nm_cts[] in
6616 // the process
6617 // 2. logistic regression, set g_perm_adapt_stop byte on failure
6618 // 3. write basic report to disk
6619 marker_uidx2 = mu_table[marker_bidx];
6620 loadbuf_ptr = &(g_loadbuf[marker_bidx * sample_valid_ctv2]);
6621 marker_idx3 = g_adapt_m_table[marker_bidx];
6622 if (marker_idx_to_uidx) {
6623 marker_idx_to_uidx[marker_idx3] = marker_uidx2;
6624 }
6625 cur_missing_ct = glm_fill_design_float(loadbuf_ptr, g_fixed_covars_cov_major_f, sample_valid_ct, cur_param_ct, glm_modifier & (GLM_HETHOM | GLM_DOMINANT | GLM_RECESSIVE), condition_list_start_idx, interaction_start_idx, sex_start_idx, active_params, haploid_params, g_include_sex, g_male_x_01, sex_male_collapsed, g_min_ploidy_1 && (!g_is_x), g_logistic_mt[0].cur_covars_cov_major);
6626 cur_sample_valid_ct = sample_valid_ct - cur_missing_ct;
6627 g_nm_cts[marker_idx3] = cur_sample_valid_ct;
6628 if (cur_sample_valid_ct > cur_param_ct) {
6629 // todo: try better starting position
6630 fill_float_zero(round_up_pow2(cur_param_ct, 4), g_logistic_mt[0].coef);
6631 regression_fail = glm_logistic(1, cur_param_ct, cur_sample_valid_ct, cur_missing_ct, skip_intercept, loadbuf_ptr, g_logistic_mt[0].cur_covars_cov_major, pheno_c_collapsed, g_logistic_mt[0].coef, g_logistic_mt[0].pp, g_logistic_mt[0].sample_1d_buf, g_logistic_mt[0].pheno_buf, g_logistic_mt[0].param_1d_buf, g_logistic_mt[0].param_1d_buf2, g_logistic_mt[0].param_2d_buf, g_logistic_mt[0].param_2d_buf2, g_logistic_mt[0].regression_results, cur_constraint_ct, constraints_con_major, g_logistic_mt[0].param_1d_dbuf, g_logistic_mt[0].param_2d_dbuf, g_logistic_mt[0].param_2d_dbuf2, g_logistic_mt[0].param_df_dbuf, g_logistic_mt[0].df_df_dbuf, g_logistic_mt[0].mi_buf, g_logistic_mt[0].df_dbuf, g_logistic_mt[0].perm_fails);
6632 } else {
6633 regression_fail = 1;
6634 }
6635 wptr_start2 = fw_strcpy(plink_maxsnp, &(marker_ids[marker_uidx2 * max_marker_id_len]), wptr_start);
6636 *wptr_start2++ = ' ';
6637 wptr_start2 = uint32toa_w10x(marker_pos[marker_uidx2], ' ', wptr_start2);
6638 wptr_start2 = fw_strcpy(4, marker_allele_ptrs[marker_uidx2 * 2], wptr_start2);
6639 *wptr_start2++ = ' ';
6640 orig_stats_ptr = &(g_orig_stats[marker_idx3]);
6641 if (!regression_fail) {
6642 for (param_idx = 1; param_idx < cur_param_ct; param_idx++) {
6643 dxx = (double)g_logistic_mt[0].coef[param_idx];
6644 se = sqrt((double)g_logistic_mt[0].regression_results[param_idx - skip_intercept]);
6645 zval = dxx / se;
6646 pval = chiprob_p(zval * zval, 1);
6647 if (param_idx == 1) {
6648 if (mperm_save_all) {
6649 dtoa_gx(zval * zval, '\0', &(numbuf[1]));
6650 fputs(numbuf, outfile_msa);
6651 }
6652 if (!constraint_ct_max) {
6653 *orig_stats_ptr = zval * zval;
6654 if (orig_pvals) {
6655 orig_pvals[marker_idx3] = pval;
6656 }
6657 }
6658 }
6659 if ((param_idx < param_idx_end) && ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0)))) {
6660 wptr = fw_strcpy(10, &(cur_param_names[param_idx * max_param_name_len]), wptr_start2);
6661 *wptr++ = ' ';
6662 wptr = uint32toa_w8x((uint32_t)cur_sample_valid_ct, ' ', wptr);
6663 wptr = dtoa_g_wxp4x(report_odds? exp(dxx) : dxx, 10, ' ', wptr);
6664 if (display_ci) {
6665 dyy = ci_zt * se;
6666 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
6667 if (report_odds) {
6668 wptr = dtoa_g_wxp4x(exp(dxx - dyy), 8, ' ', wptr);
6669 wptr = dtoa_g_wxp4x(exp(dxx + dyy), 8, ' ', wptr);
6670 } else {
6671 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
6672 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
6673 }
6674 }
6675 wptr = dtoa_g_wxp4x(zval, 12, ' ', wptr);
6676 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
6677 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
6678 goto glm_logistic_assoc_ret_WRITE_FAIL;
6679 }
6680 }
6681 }
6682 if (!skip_intercept) {
6683 dxx = (double)g_logistic_mt[0].coef[0];
6684 wptr = memcpya(wptr_start2, " INTERCEPT ", 11);
6685 wptr = uint32toa_w8x((uint32_t)cur_sample_valid_ct, ' ', wptr);
6686 // bugfix (15 Feb 2019): forgot report_odds here
6687 wptr = dtoa_g_wxp4x(report_odds? exp(dxx) : dxx, 10, ' ', wptr);
6688 if (display_ci) {
6689 se = sqrt((double)g_logistic_mt[0].regression_results[0]);
6690 dyy = ci_zt * se;
6691 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
6692 if (report_odds) {
6693 wptr = dtoa_g_wxp4x(exp(dxx - dyy), 8, ' ', wptr);
6694 wptr = dtoa_g_wxp4x(exp(dxx + dyy), 8, ' ', wptr);
6695 } else {
6696 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
6697 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
6698 }
6699 }
6700 wptr = memcpya(wptr, " NA NA\n", 26);
6701 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
6702 goto glm_logistic_assoc_ret_WRITE_FAIL;
6703 }
6704 }
6705 if (cur_constraint_ct) {
6706 dxx = (double)g_logistic_mt[0].regression_results[cur_param_ct - skip_intercept];
6707 *orig_stats_ptr = dxx;
6708 pval = chiprob_p(dxx, cur_constraint_ct);
6709 if (orig_pvals) {
6710 orig_pvals[marker_idx3] = pval;
6711 }
6712 if ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0))) {
6713 wptr = fw_strcpy(10, &(param_names[param_ct_max * max_param_name_len]), wptr_start2);
6714 *wptr++ = ' ';
6715 wptr = uint32toa_w8((uint32_t)cur_sample_valid_ct, wptr);
6716 wptr = memcpya(wptr, " NA ", 12);
6717 if (display_ci) {
6718 wptr = memcpya(wptr, " NA NA NA ", 27);
6719 }
6720 wptr = dtoa_g_wxp4x(dxx, 12, ' ', wptr);
6721 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
6722 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
6723 goto glm_logistic_assoc_ret_WRITE_FAIL;
6724 }
6725 }
6726 } else if (orig_pvals && constraint_ct_max) {
6727 orig_pvals[marker_idx3] = -9;
6728 }
6729 } else {
6730 if (!is_set_test) {
6731 g_perm_adapt_stop[marker_idx3] = 1;
6732 }
6733 if (orig_pvals) {
6734 orig_pvals[marker_idx3] = -9;
6735 }
6736 *orig_stats_ptr = -9;
6737 if (mperm_save_all) {
6738 fputs(" NA", outfile_msa);
6739 msa_ptr = &(g_mperm_save_all[marker_idx3 * perm_batch_size]);
6740 for (perm_idx = 0; perm_idx < perm_batch_size; perm_idx++) {
6741 *msa_ptr++ = -9;
6742 }
6743 }
6744 if (pfilter == 2.0) {
6745 for (param_idx = 1; param_idx < cur_param_ctx; param_idx++) {
6746 if ((param_idx < param_idx_end) || (param_idx == cur_param_ct)) {
6747 if (!(param_idx == cur_param_ct)) {
6748 wptr = fw_strcpy(10, &(cur_param_names[param_idx * max_param_name_len]), wptr_start2);
6749 } else {
6750 wptr = fw_strcpy(10, &(param_names[param_ct_max * max_param_name_len]), wptr_start2);
6751 }
6752 *wptr++ = ' ';
6753 wptr = uint32toa_w8((uint32_t)cur_sample_valid_ct, wptr);
6754 wptr = memcpya(wptr, " NA ", 12);
6755 if (display_ci) {
6756 wptr = memcpya(wptr, " NA NA NA ", 27);
6757 }
6758 wptr = memcpya(wptr, " NA NA\n", 26);
6759 if (fwrite_checked(writebuf, wptr - writebuf, outfile)) {
6760 goto glm_logistic_assoc_ret_WRITE_FAIL;
6761 }
6762 }
6763 }
6764 }
6765 }
6766 }
6767 }
6768 if (do_perms_nst) {
6769 // split loaded markers evenly between threads. each thread does the
6770 // following for every marker in its set:
6771 // 1. fill design matrix and make transposed copy, do this more
6772 // efficiently if g_nm_cts[] indicates there are no missing genotypes
6773 // 2. logistic regression on permutations, handle adaptive logic,
6774 // --mperm-save[-all], etc.
6775 g_assoc_thread_ct = block_size / CACHELINE_INT32;
6776 if (g_assoc_thread_ct > max_thread_ct) {
6777 g_assoc_thread_ct = max_thread_ct;
6778 } else if (!g_assoc_thread_ct) {
6779 g_assoc_thread_ct = 1;
6780 }
6781 ulii = 0;
6782 if (perm_adapt_nst) {
6783 if (spawn_threads(threads, &glm_logistic_adapt_thread, g_assoc_thread_ct)) {
6784 goto glm_logistic_assoc_ret_THREAD_CREATE_FAIL;
6785 }
6786 glm_logistic_adapt_thread((void*)ulii);
6787 join_threads(threads, g_assoc_thread_ct);
6788 } else {
6789 if (spawn_threads(threads, &glm_logistic_maxt_thread, g_assoc_thread_ct)) {
6790 goto glm_logistic_assoc_ret_THREAD_CREATE_FAIL;
6791 }
6792 glm_logistic_maxt_thread((void*)ulii);
6793 join_threads(threads, g_assoc_thread_ct);
6794 ulii = round_up_pow2(g_perm_vec_ct, CACHELINE_DBL);
6795 ukk = g_perms_done + g_perm_vec_ct;
6796 for (uii = 0; uii < g_assoc_thread_ct; uii++) {
6797 dptr = &(g_maxt_thread_results[uii * ulii]);
6798 for (ujj = g_perms_done; ujj < ukk; ujj++) {
6799 dxx = *dptr++;
6800 if (dxx > g_maxt_extreme_stat[ujj]) {
6801 g_maxt_extreme_stat[ujj] = dxx;
6802 }
6803 }
6804 }
6805 }
6806 }
6807 marker_idx += block_size;
6808 if ((!perm_pass_idx) && (marker_idx >= loop_end)) {
6809 if (marker_idx < marker_initial_ct) {
6810 if (pct >= 10) {
6811 putc_unlocked('\b', stdout);
6812 }
6813 pct = (marker_idx * 100LLU) / marker_initial_ct;
6814 printf("\b\b%u%%", pct);
6815 fflush(stdout);
6816 loop_end = (((uint64_t)pct + 1LLU) * marker_initial_ct) / 100;
6817 }
6818 }
6819 } while (marker_idx < marker_unstopped_ct);
6820 // if more permutations, reevaluate marker_unstopped_ct, etc.
6821 if (!perm_pass_idx) {
6822 if (pct >= 10) {
6823 putc_unlocked('\b', stdout);
6824 }
6825 fputs("\b\b", stdout);
6826 logprint("done.\n");
6827 if (fclose_null(&outfile)) {
6828 goto glm_logistic_assoc_ret_WRITE_FAIL;
6829 }
6830 if (!is_set_test) {
6831 if (mtest_adjust) {
6832 retval = multcomp(outname, outname_end, marker_idx_to_uidx, marker_initial_ct, marker_ids, max_marker_id_len, plink_maxsnp, chrom_info_ptr, nullptr, pfilter, output_min_p, mtest_adjust, constraint_ct_max, adjust_lambda, nullptr, orig_pvals);
6833 if (retval) {
6834 goto glm_logistic_assoc_ret_1;
6835 }
6836 }
6837 if (mperm_save_all) {
6838 if (putc_checked('\n', outfile_msa)) {
6839 goto glm_logistic_assoc_ret_WRITE_FAIL;
6840 }
6841 }
6842 } else {
6843 retval = glm_logistic_assoc_set_test(threads, bedfile, bed_offset, outname, outname_end, glm_modifier, glm_xchr_model, glm_mperm_val, pfilter, output_min_p, mtest_adjust, unfiltered_marker_ct, marker_exclude_orig, marker_ct_orig, marker_exclude, marker_ct, marker_ids, max_marker_id_len, marker_reverse, regression_skip, chrom_info_ptr, unfiltered_sample_ct, sex_male, apip, pheno_nm_ct, pheno_nm, founder_pnm, load_mask, sample_include2, sample_male_include2, ld_ignore_x, hh_exists, hh_or_mt_exists, orig_perm_batch_size, sip, loadbuf_raw, param_ct_max, np_base, np_diploid, np_sex, sample_valid_ct, sex_covar_everywhere);
6844 if (retval) {
6845 goto glm_logistic_assoc_ret_1;
6846 }
6847 }
6848 }
6849 if (do_perms_nst) {
6850 if (mperm_save_all) {
6851 if (perm_pass_idx) {
6852 putc_unlocked(' ', stdout);
6853 }
6854 fputs("[dumping stats]", stdout);
6855 fflush(stdout);
6856 ulii = g_perm_vec_ct;
6857 ujj = 1 + g_perms_done;
6858 wptr = g_textbuf;
6859 cptr = &(g_textbuf[MAXLINELEN]);
6860 for (uii = 0; uii < ulii; uii++) {
6861 wptr = uint32toa(uii + ujj, wptr);
6862 dptr = &(g_mperm_save_all[uii]);
6863 for (ukk = 0; ukk < marker_ct; ukk++) {
6864 *wptr++ = ' ';
6865 dxx = dptr[ukk * ulii];
6866 if (dxx >= 0) {
6867 wptr = dtoa_g(dxx, wptr);
6868 } else {
6869 wptr = memcpya(wptr, "NA", 2);
6870 }
6871 if (wptr >= cptr) {
6872 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile_msa)) {
6873 goto glm_logistic_assoc_ret_WRITE_FAIL;
6874 }
6875 wptr = g_textbuf;
6876 }
6877 }
6878 *wptr++ = '\n';
6879 }
6880 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile_msa)) {
6881 goto glm_logistic_assoc_ret_WRITE_FAIL;
6882 }
6883 fputs("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b ", stdout);
6884 }
6885 g_perms_done += g_perm_vec_ct;
6886 if (g_perms_done < perms_total) {
6887 if (perm_adapt_nst || (!perm_pass_idx)) {
6888 marker_unstopped_ct = marker_initial_ct - popcount01_longs((uintptr_t*)g_perm_adapt_stop, (marker_initial_ct + sizeof(intptr_t) - 1) / sizeof(intptr_t));
6889 if (!marker_unstopped_ct) {
6890 goto glm_logistic_assoc_perm_count;
6891 }
6892 }
6893 printf("\r%u permutation%s complete.", g_perms_done, (g_perms_done != 1)? "s" : "");
6894 fflush(stdout);
6895 perm_pass_idx++;
6896 goto glm_logistic_assoc_more_perms;
6897 }
6898 glm_logistic_assoc_perm_count:
6899 if (perm_adapt_nst) {
6900 g_perms_done = 0;
6901 for (uii = 0; uii < marker_initial_ct; uii++) {
6902 if (g_perm_attempt_ct[uii] > g_perms_done) {
6903 g_perms_done = g_perm_attempt_ct[uii];
6904 if (g_perms_done == perms_total) {
6905 break;
6906 }
6907 }
6908 }
6909 }
6910 putc_unlocked('\r', stdout);
6911 LOGPRINTF("%u %s permutation%s complete.\n", g_perms_done, perm_maxt_nst? "max(T)" : "(adaptive)", (g_perms_done != 1)? "s" : "");
6912
6913 if (perm_adapt_nst) {
6914 memcpy(outname_end2, ".perm", 6);
6915 } else {
6916 if (mperm_save & MPERM_DUMP_BEST) {
6917 memcpy(outname_end, ".mperm.dump.best", 17);
6918 LOGPRINTF("Dumping best permutation chi-square values to %s .\n", outname);
6919 if (fopen_checked(outname, "w", &outfile)) {
6920 goto glm_logistic_assoc_ret_OPEN_FAIL;
6921 }
6922 dxx = 0;
6923 for (marker_idx = 0; marker_idx < marker_initial_ct; marker_idx++) {
6924 if (g_orig_stats[marker_idx] > dxx) {
6925 dxx = g_orig_stats[marker_idx];
6926 }
6927 }
6928 memcpy(g_textbuf, "0 ", 2);
6929 wptr = dtoa_gx(dxx, '\n', &(g_textbuf[2]));
6930 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile)) {
6931 goto glm_logistic_assoc_ret_WRITE_FAIL;
6932 }
6933 for (uii = 0; uii < perms_total; uii++) {
6934 wptr = uint32toa_x(uii + 1, ' ', g_textbuf);
6935 wptr = dtoa_gx(g_maxt_extreme_stat[uii], '\n', wptr);
6936 if (fwrite_checked(g_textbuf, (uintptr_t)(wptr - g_textbuf), outfile)) {
6937 goto glm_logistic_assoc_ret_WRITE_FAIL;
6938 }
6939 }
6940 if (fclose_null(&outfile)) {
6941 goto glm_logistic_assoc_ret_WRITE_FAIL;
6942 }
6943 memcpy(outname_end, ".assoc.logistic", 15);
6944 }
6945 memcpy(outname_end2, ".mperm", 7);
6946 }
6947 if (fopen_checked(outname, "w", &outfile)) {
6948 goto glm_logistic_assoc_ret_OPEN_FAIL;
6949 }
6950 if (perm_adapt_nst) {
6951 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us EMP1 NP \n", plink_maxsnp);
6952 } else {
6953 snprintf(g_textbuf, TEXTBUF_SIZE, " CHR %%%us EMP1 EMP2 \n", plink_maxsnp);
6954 #ifdef __cplusplus
6955 std::sort(g_maxt_extreme_stat, &(g_maxt_extreme_stat[perms_total]));
6956 #else
6957 qsort(g_maxt_extreme_stat, perms_total, sizeof(double), double_cmp);
6958 #endif
6959 // (debugging)
6960 // printf("extreme stats: %g %g %g\n", g_maxt_extreme_stat[0], g_maxt_extreme_stat[(perms_total - 1) / 2], g_maxt_extreme_stat[perms_total - 1]);
6961
6962 for (marker_idx = 0; marker_idx < marker_initial_ct; marker_idx++) {
6963 g_perm_attempt_ct[marker_idx] = perms_total - g_perm_attempt_ct[marker_idx];
6964 }
6965 }
6966 fprintf(outfile, g_textbuf, "SNP");
6967 chrom_fo_idx = 0xffffffffU;
6968 marker_uidx = next_unset_unsafe(marker_exclude, 0);
6969 marker_idx = 0;
6970 while (1) {
6971 do {
6972 chrom_end = chrom_info_ptr->chrom_fo_vidx_start[(++chrom_fo_idx) + 1];
6973 } while (marker_uidx >= chrom_end);
6974 uii = chrom_info_ptr->chrom_file_order[chrom_fo_idx];
6975 wptr_start = width_force(4, g_textbuf, chrom_name_write(chrom_info_ptr, uii, g_textbuf));
6976 *wptr_start++ = ' ';
6977 wptr_start[plink_maxsnp] = ' ';
6978 for (; marker_uidx < chrom_end;) {
6979 pval = ((double)(g_perm_2success_ct[marker_idx] + 2)) / ((double)(2 * (g_perm_attempt_ct[marker_idx] + 1)));
6980 if (pval <= pfilter) {
6981 fw_strcpy(plink_maxsnp, &(marker_ids[marker_uidx * max_marker_id_len]), wptr_start);
6982 wptr = &(wptr_start[1 + plink_maxsnp]);
6983 if (g_orig_stats[marker_idx] == -9) {
6984 wptr = memcpya(wptr, " NA NA", 25);
6985 } else {
6986 if (!perm_count) {
6987 wptr = dtoa_g_wxp4x(pval, 12, ' ', wptr);
6988 } else {
6989 wptr = dtoa_g_wxp4x(((double)g_perm_2success_ct[marker_idx]) * 0.5, 12, ' ', wptr);
6990 }
6991 if (perm_adapt_nst) {
6992 wptr = memseta(wptr, 32, 2);
6993 wptr = uint32toa_w10(g_perm_attempt_ct[marker_idx], wptr);
6994 } else {
6995 dzz = (int32_t)(perms_total - doublearr_greater_than(g_maxt_extreme_stat, perms_total, g_orig_stats[marker_idx] - EPSILON) + 1);
6996 if (!perm_count) {
6997 wptr = dtoa_g_wxp4(dzz / ((double)((int32_t)perms_total + 1)), 12, wptr);
6998 } else {
6999 wptr = dtoa_g_wxp4(dzz - 1, 12, wptr);
7000 }
7001 }
7002 }
7003 wptr = memcpya(wptr, " \n", 2);
7004 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7005 goto glm_logistic_assoc_ret_WRITE_FAIL;
7006 }
7007 }
7008 if (++marker_idx == marker_ct) {
7009 goto glm_logistic_assoc_loop_end;
7010 }
7011 marker_uidx++;
7012 next_unset_unsafe_ck(marker_exclude, &marker_uidx);
7013 }
7014 }
7015 glm_logistic_assoc_loop_end:
7016 if (fclose_null(&outfile)) {
7017 goto glm_logistic_assoc_ret_WRITE_FAIL;
7018 }
7019 LOGPRINTF("Permutation test report written to %s .\n", outname);
7020 }
7021
7022 while (0) {
7023 glm_logistic_assoc_ret_NOMEM:
7024 retval = RET_NOMEM;
7025 break;
7026 glm_logistic_assoc_ret_OPEN_FAIL:
7027 retval = RET_OPEN_FAIL;
7028 break;
7029 glm_logistic_assoc_ret_READ_FAIL:
7030 retval = RET_READ_FAIL;
7031 break;
7032 glm_logistic_assoc_ret_WRITE_FAIL:
7033 retval = RET_WRITE_FAIL;
7034 break;
7035 glm_logistic_assoc_ret_NO_PERMUTATION_CLUSTERS:
7036 logerrprint("Error: No size 2+ clusters for permutation test.\n");
7037 retval = RET_INVALID_CMDLINE;
7038 break;
7039 glm_logistic_assoc_ret_PHENO_CONSTANT:
7040 logerrprint("Warning: Skipping --linear/--logistic since phenotype is constant.\n");
7041 break;
7042 glm_logistic_assoc_ret_THREAD_CREATE_FAIL:
7043 retval = RET_THREAD_CREATE_FAIL;
7044 break;
7045 }
7046 glm_logistic_assoc_ret_1:
7047 bigstack_reset(bigstack_mark);
7048 fclose_cond(outfile);
7049 fclose_cond(outfile_msa);
7050 free_cond(condition_uidxs);
7051 return retval;
7052 }
7053
7054 #ifndef NOLAPACK
7055 int32_t glm_linear_nosnp(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, double glm_vif_thresh, uint32_t glm_xchr_model, uint32_t glm_mperm_val, Range_list* parameters_range_list_ptr, Range_list* tests_range_list_ptr, double ci_size, double ci_zt, double pfilter, double output_min_p, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude, uintptr_t marker_ct, char* marker_ids, uintptr_t max_marker_id_len, uintptr_t* marker_reverse, char* condition_mname, char* condition_fname, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t sample_ct, uintptr_t* sample_exclude, uint32_t cluster_ct, uint32_t* cluster_map, uint32_t* cluster_starts, uint32_t mperm_save, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, double* pheno_d, uintptr_t covar_ct, char* covar_names, uintptr_t max_covar_name_len, uintptr_t* covar_nm, double* covar_d, uintptr_t* sex_nm, uintptr_t* sex_male, uint32_t hh_or_mt_exists, uint32_t perm_batch_size, Set_info* sip) {
7056 unsigned char* bigstack_mark = g_bigstack_base;
7057 unsigned char* bigstack_end_mark = g_bigstack_end;
7058 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
7059 uintptr_t unfiltered_sample_ctl = BITCT_TO_WORDCT(unfiltered_sample_ct);
7060 uintptr_t unfiltered_sample_ctv2 = 2 * unfiltered_sample_ctl;
7061 FILE* outfile = nullptr;
7062 uintptr_t sample_uidx = 0;
7063 uintptr_t max_param_name_len = 2;
7064 uintptr_t param_raw_ct = 1;
7065 uintptr_t condition_ct = 0;
7066 uintptr_t constraint_ct = 0;
7067 uintptr_t ulii = 0;
7068 uint32_t cur_batch_size = 1;
7069 uint32_t do_perms = (glm_modifier / GLM_MPERM) & 1;
7070 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
7071 uint32_t hide_covar = glm_modifier & GLM_HIDE_COVAR;
7072 uint32_t display_ci = (ci_size > 0);
7073 uint32_t variation_in_sex = 0; // no need to initialize if no-x-sex specified
7074 uint32_t perms_done = 0;
7075 uint32_t perm_fail_total = 0;
7076 uint32_t joint_perm_fail_extra = 0;
7077 uint32_t perm_fail_ct = 0;
7078 uint32_t max_thread_ct = g_thread_ct;
7079 int32_t retval = 0;
7080 uint32_t report_intercept = glm_modifier & GLM_INTERCEPT;
7081 char dgels_trans = 'N';
7082 __CLPK_integer dgels_m = 0;
7083 __CLPK_integer dgels_n = 0;
7084 __CLPK_integer dgels_nrhs = 0;
7085 double* dgels_a = nullptr;
7086 double* dgels_b = nullptr;
7087 double* dgels_work = nullptr;
7088 double* param_df_buf = nullptr;
7089 double* param_df_buf2 = nullptr;
7090 __CLPK_integer dgels_ldb = 0;
7091 __CLPK_integer dgels_lwork = -1;
7092 __CLPK_integer dgels_info;
7093 double dzz;
7094 double* regression_results = nullptr;
7095 double* mperm_save_stats = nullptr;
7096 double* constraints_con_major = nullptr;
7097 double* df_df_buf = nullptr;
7098 double* df_buf = nullptr;
7099 uintptr_t* loadbuf_raw = nullptr;
7100 uintptr_t* loadbuf_collapsed = nullptr;
7101 uintptr_t* load_mask = nullptr;
7102 uintptr_t* sex_male_collapsed = nullptr;
7103 uintptr_t* sample_include2 = nullptr;
7104 uintptr_t* sample_male_include2 = nullptr;
7105 uintptr_t* active_params = nullptr;
7106 uintptr_t* joint_test_params = nullptr;
7107 uintptr_t* perm_fails = nullptr;
7108 uint32_t* perm_2success_ct = nullptr;
7109 uint32_t* condition_uidxs = nullptr;
7110 double geno_map[12];
7111 double* geno_map_ptr;
7112 double* param_2d_buf;
7113 double* param_2d_buf2;
7114 MATRIX_INVERT_BUF1_TYPE* mi_buf;
7115 char* param_names;
7116 double* covars_cov_major;
7117 double* covars_sample_major;
7118 double* orig_stats;
7119 char* outname_end2;
7120 char* wptr;
7121 char* wptr2;
7122 double* dptr;
7123 double* dptr2;
7124 uintptr_t sample_valid_ct;
7125 uintptr_t sample_valid_ctv2;
7126 uintptr_t sample_uidx_stop;
7127 uintptr_t sample_idx;
7128 uintptr_t param_raw_ctp2l;
7129 uintptr_t param_ct;
7130 uintptr_t param_ctx; // param_ct + 1 if joint test needed, param_ct otherwise
7131 uintptr_t param_idx;
7132 uintptr_t constraint_idx;
7133 uintptr_t final_mask;
7134 uintptr_t uljj;
7135 double* msa_ptr;
7136 double* dptr3;
7137 double se;
7138 double zval;
7139 double pval;
7140 double dxx;
7141 double dyy;
7142 uint32_t perm_idx;
7143 uint32_t marker_uidx;
7144 uint32_t chrom_idx;
7145 uint32_t is_x;
7146 uint32_t is_y;
7147 uint32_t uii;
7148 uint32_t ujj;
7149 uint32_t slen;
7150 int32_t ii;
7151 if (hide_covar && (!tests_range_list_ptr->name_ct) && (!(glm_modifier & GLM_TEST_ALL))) {
7152 logerrprint("Error: --linear hide-covar no-snp produces no output.\n");
7153 goto glm_linear_nosnp_ret_INVALID_CMDLINE;
7154 }
7155 if (glm_init_load_mask(sample_exclude, pheno_nm, covar_nm, sample_ct, unfiltered_sample_ctv2, &load_mask)) {
7156 goto glm_linear_nosnp_ret_NOMEM;
7157 }
7158 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
7159 if ((chrom_info_ptr->xymt_codes[MT_OFFSET] != -2) && is_set(chrom_info_ptr->chrom_mask, chrom_info_ptr->xymt_codes[MT_OFFSET])) {
7160 hh_or_mt_exists |= NXMHH_EXISTS;
7161 }
7162 if (condition_mname || condition_fname) {
7163 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &loadbuf_raw)) {
7164 goto glm_linear_nosnp_ret_NOMEM;
7165 }
7166 loadbuf_raw[unfiltered_sample_ctv2 - 2] = 0;
7167 loadbuf_raw[unfiltered_sample_ctv2 - 1] = 0;
7168
7169 if (hh_or_mt_exists & (Y_FIX_NEEDED | NXMHH_EXISTS)) {
7170 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_include2)) {
7171 goto glm_linear_nosnp_ret_NOMEM;
7172 }
7173 fill_quatervec_55(unfiltered_sample_ct, sample_include2); // harmless
7174 }
7175 if (hh_or_mt_exists & (XMHH_EXISTS | Y_FIX_NEEDED)) {
7176 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_male_include2)) {
7177 goto glm_linear_nosnp_ret_NOMEM;
7178 }
7179 init_quaterarr_from_bitarr(sex_male, unfiltered_sample_ct, sample_male_include2);
7180 }
7181 retval = glm_scan_conditions(condition_mname, condition_fname, unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, chrom_info_ptr, hh_or_mt_exists, loadbuf_raw, bedfile, bed_offset, unfiltered_sample_ct, sex_male, load_mask, &sample_valid_ct, &condition_ct, &condition_uidxs, sample_include2, sample_male_include2);
7182 if (retval) {
7183 goto glm_linear_nosnp_ret_1;
7184 }
7185 // deallocate temporary sample[_male]_include2
7186 bigstack_end_reset(loadbuf_raw);
7187 param_raw_ct += condition_ct;
7188 }
7189 param_raw_ct += covar_ct;
7190 if (glm_modifier & GLM_SEX) {
7191 sample_uidx = 0;
7192 sample_idx = 0;
7193 uii = 2;
7194 do {
7195 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
7196 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
7197 sample_idx += sample_uidx_stop - sample_uidx;
7198 do {
7199 if (IS_SET(sex_nm, sample_uidx)) {
7200 ujj = is_set(sex_male, sample_uidx);
7201 if (uii == ujj) {
7202 variation_in_sex = 1;
7203 sample_idx = sample_valid_ct;
7204 break;
7205 }
7206 uii = 1 - ujj;
7207 }
7208 } while (++sample_uidx < sample_uidx_stop);
7209 } while (sample_idx < sample_valid_ct);
7210 if (variation_in_sex) {
7211 param_raw_ct++;
7212 bitvec_and(sex_nm, unfiltered_sample_ctl, load_mask);
7213 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
7214 } else {
7215 logerrprint("Warning: Ignoring --linear 'sex' modifier since sex is invariant.\n");
7216 }
7217 }
7218 sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
7219
7220 if (condition_mname || condition_fname) {
7221 // now that we've determined which samples will be in the regression,
7222 // initialize collapsed sample_include2, sample_male_include2, sex_male
7223 if (hh_or_mt_exists & (Y_FIX_NEEDED | NXMHH_EXISTS)) {
7224 bigstack_end_alloc_ul(sample_valid_ctv2, &sample_include2);
7225 fill_quatervec_55(sample_valid_ct, sample_include2);
7226 }
7227 if (hh_or_mt_exists & (XMHH_EXISTS | Y_FIX_NEEDED)) {
7228 bigstack_end_alloc_ul(sample_valid_ctv2, &sample_male_include2);
7229 alloc_collapsed_haploid_filters(load_mask, sex_male, unfiltered_sample_ct, sample_valid_ct, hh_or_mt_exists, 1, &sample_include2, &sample_male_include2);
7230 }
7231 if (bigstack_end_alloc_ul(sample_valid_ctv2, &loadbuf_collapsed) ||
7232 bigstack_end_alloc_ul(sample_valid_ctv2 / 2, &sex_male_collapsed)) {
7233 goto glm_linear_nosnp_ret_NOMEM;
7234 }
7235 loadbuf_collapsed[sample_valid_ctv2 - 2] = 0;
7236 loadbuf_collapsed[sample_valid_ctv2 - 1] = 0;
7237 copy_bitarr_subset(sex_male, load_mask, unfiltered_sample_ct, sample_valid_ct, sex_male_collapsed);
7238 }
7239 param_raw_ctp2l = BITCT_TO_WORDCT(param_raw_ct + 2);
7240 if (aligned_malloc(param_raw_ctp2l * sizeof(intptr_t), &active_params)) {
7241 goto glm_linear_nosnp_ret_NOMEM;
7242 }
7243 if (parameters_range_list_ptr->name_ct) {
7244 fill_ulong_zero(param_raw_ctp2l, active_params);
7245 active_params[0] = 1;
7246 numeric_range_list_to_bitarr(parameters_range_list_ptr, param_raw_ct, 0, 1, active_params);
7247 param_ct = popcount_longs(active_params, param_raw_ctp2l);
7248 } else {
7249 fill_all_bits(param_raw_ct, active_params);
7250 param_ct = param_raw_ct;
7251 }
7252 if (param_ct == 1) {
7253 logerrprint("Warning: Skipping --linear since the intercept is the only variable.\n");
7254 goto glm_linear_nosnp_ret_1;
7255 } else if (sample_valid_ct <= param_ct) {
7256 logerrprint("Warning: Skipping --linear since # variables >= # samples.\n");
7257 if (pheno_nm_ct > param_ct) {
7258 logerrprint("(Check your covariates--all samples with at least one missing covariate are\nexcluded from this analysis.)\n");
7259 }
7260 goto glm_linear_nosnp_ret_1;
7261 }
7262 // parameter sequence:
7263 // 1. intercept
7264 // 2. --condition-list (1 to condition_ct in raw list)
7265 // 3. --covar (condition_ct + 1 to condition_ct + covar_ct in raw list)
7266 // 4. sex (condition_ct + covar_ct + 1 in raw list)
7267 for (uii = 0; uii < condition_ct; uii++) {
7268 if (is_set(active_params, uii + 1)) {
7269 slen = strlen(&(marker_ids[condition_uidxs[uii] * max_marker_id_len]));
7270 if (max_param_name_len <= slen) {
7271 max_param_name_len = slen + 1;
7272 }
7273 }
7274 }
7275 uii = condition_ct + 1;
7276 for (ujj = 0; ujj < covar_ct; ujj++) {
7277 if (is_set(active_params, ujj + uii)) {
7278 slen = strlen(&(covar_names[ujj * max_covar_name_len]));
7279 if (max_param_name_len <= slen) {
7280 max_param_name_len = slen + 1;
7281 }
7282 }
7283 }
7284 param_ctx = param_ct;
7285 if (tests_range_list_ptr->name_ct || (glm_modifier & GLM_TEST_ALL)) {
7286 ulii = BITCT_TO_WORDCT(param_ct);
7287 if (aligned_malloc(ulii * sizeof(intptr_t), &joint_test_params)) {
7288 goto glm_linear_nosnp_ret_NOMEM;
7289 }
7290 fill_ulong_zero(ulii, joint_test_params);
7291 if (tests_range_list_ptr->name_ct) {
7292 numeric_range_list_to_bitarr(tests_range_list_ptr, param_ct - 1, 1, 1, joint_test_params);
7293 constraint_ct = popcount_longs(joint_test_params, ulii);
7294 } else {
7295 constraint_ct = param_ct - 1;
7296 fill_bits(0, constraint_ct, joint_test_params);
7297 }
7298 if ((constraint_ct > 1) || (hide_covar && (constraint_ct == 1))) {
7299 // permit hide-covar + single --tests parameter combination
7300 slen = 8 + intlen((uint32_t)constraint_ct);
7301 if (max_param_name_len < slen) {
7302 max_param_name_len = slen;
7303 }
7304 param_ctx++;
7305 } else {
7306 constraint_ct = 0;
7307 aligned_free_null(&joint_test_params);
7308 logerrprint("Warning: Ignoring --tests since fewer than two parameter indices are in range.\n");
7309 }
7310 }
7311
7312 ulii = condition_ct + covar_ct + 1;
7313 if (variation_in_sex && IS_SET(active_params, ulii)) {
7314 if (max_param_name_len < 4) {
7315 max_param_name_len = 4;
7316 }
7317 }
7318 if (bigstack_alloc_c(param_ctx * max_param_name_len, &param_names) ||
7319 bigstack_alloc_d(param_ct * sample_valid_ct, &covars_cov_major)) {
7320 goto glm_linear_nosnp_ret_NOMEM;
7321 }
7322 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
7323 covars_cov_major[sample_idx] = 1;
7324 }
7325 param_idx = 1;
7326 fill_double_zero(12, geno_map);
7327 geno_map[0] = 1;
7328 geno_map[2] = 1;
7329 geno_map[4] = 1;
7330 geno_map[8] = 1;
7331 if (glm_modifier & GLM_CONDITION_RECESSIVE) {
7332 geno_map[2] = 0;
7333 } else if (!(glm_modifier & GLM_CONDITION_DOMINANT)) {
7334 geno_map[0] = 2;
7335 if (glm_xchr_model == 2) {
7336 geno_map[4] = 2;
7337 }
7338 }
7339 final_mask = get_final_mask(sample_valid_ct);
7340 for (uii = 0; uii < condition_ct; uii++) {
7341 if (is_set(active_params, uii + 1)) {
7342 marker_uidx = condition_uidxs[uii];
7343 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
7344 goto glm_linear_nosnp_ret_READ_FAIL;
7345 }
7346 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_collapsed)) {
7347 goto glm_linear_nosnp_ret_READ_FAIL;
7348 }
7349 chrom_idx = get_variant_chrom(chrom_info_ptr, marker_uidx);
7350 geno_map_ptr = geno_map;
7351 if (IS_SET(chrom_info_ptr->haploid_mask, chrom_idx) || (chrom_idx == (uint32_t)chrom_info_ptr->xymt_codes[MT_OFFSET])) {
7352 is_x = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[X_OFFSET]);
7353 is_y = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[Y_OFFSET]);
7354 if (hh_or_mt_exists) {
7355 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, is_x, is_y, (unsigned char*)loadbuf_collapsed);
7356 }
7357 if (!is_x) {
7358 geno_map_ptr = &(geno_map[8]);
7359 }
7360 } else {
7361 is_x = 0;
7362 }
7363 if (!is_x) {
7364 glm_loadbuf_to_doubles(loadbuf_collapsed, sample_valid_ct, &(covars_cov_major[param_idx * sample_valid_ct]), geno_map_ptr, nullptr);
7365 } else {
7366 glm_loadbuf_to_doubles_x(loadbuf_collapsed, sex_male_collapsed, sample_valid_ct, &(covars_cov_major[param_idx * sample_valid_ct]), geno_map_ptr, nullptr);
7367 }
7368 strcpy(&(param_names[param_idx * max_param_name_len]), &(marker_ids[marker_uidx * max_marker_id_len]));
7369 param_idx++;
7370 }
7371 }
7372 bigstack_end_reset(bigstack_end_mark);
7373 if (constraint_ct) {
7374 if (bigstack_calloc_d(constraint_ct * param_ct, &constraints_con_major) ||
7375 bigstack_alloc_d(constraint_ct * constraint_ct, &df_df_buf) ||
7376 bigstack_alloc_d(constraint_ct, &df_buf) ||
7377 bigstack_alloc_d(constraint_ct * param_ct, &param_df_buf) ||
7378 bigstack_alloc_d(constraint_ct * param_ct, &param_df_buf2)) {
7379 goto glm_linear_nosnp_ret_NOMEM;
7380 }
7381 uljj = 0;
7382 for (constraint_idx = 0; constraint_idx < constraint_ct; uljj++, constraint_idx++) {
7383 next_set_ul_unsafe_ck(joint_test_params, &uljj);
7384 constraints_con_major[constraint_idx * param_ct + uljj + 1] = 1;
7385 }
7386 wptr = memcpya(&(param_names[param_ct * max_param_name_len]), (glm_modifier & GLM_TEST_ALL)? "FULL" : "USER", 4);
7387 *wptr++ = '_';
7388 wptr = uint32toa(constraint_ct, wptr);
7389 memcpy(wptr, "DF", 3);
7390 }
7391 if (bigstack_alloc_d(param_ct * sample_valid_ct, &covars_sample_major) ||
7392 bigstack_calloc_ui(param_ctx - 1, &perm_2success_ct) ||
7393 bigstack_alloc_d(param_ctx - 1, &orig_stats) ||
7394 bigstack_alloc_d(param_ct * param_ct, &param_2d_buf) ||
7395 bigstack_alloc_d(param_ct * param_ct, &param_2d_buf2)) {
7396 goto glm_linear_nosnp_ret_NOMEM;
7397 }
7398 mi_buf = (MATRIX_INVERT_BUF1_TYPE*)bigstack_alloc(param_ct * MATRIX_INVERT_BUF1_ELEM_ALLOC);
7399 if (!mi_buf) {
7400 goto glm_linear_nosnp_ret_NOMEM;
7401 }
7402 sample_uidx = 0;
7403 sample_idx = 0;
7404 if (bigstack_alloc_d(sample_valid_ct, &g_perm_pheno_d2)) {
7405 goto glm_linear_nosnp_ret_NOMEM;
7406 }
7407 dptr = g_perm_pheno_d2;
7408 g_pheno_sum = 0;
7409 g_pheno_ssq = 0;
7410 do {
7411 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
7412 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
7413 sample_idx += sample_uidx_stop - sample_uidx;
7414 dptr2 = &(pheno_d[sample_uidx]);
7415 sample_uidx = sample_uidx_stop;
7416 dptr3 = &(pheno_d[sample_uidx_stop]);
7417 do {
7418 dxx = *dptr2++;
7419 *dptr++ = dxx;
7420 g_pheno_sum += dxx;
7421 g_pheno_ssq += dxx * dxx;
7422 } while (dptr2 < dptr3);
7423 } while (sample_idx < sample_valid_ct);
7424 if (g_pheno_ssq * ((double)((intptr_t)sample_valid_ct)) == g_pheno_sum * g_pheno_sum) {
7425 goto glm_linear_nosnp_ret_PHENO_CONSTANT;
7426 }
7427 uii = condition_ct + 1;
7428 for (ujj = 0; ujj < covar_ct; ujj++) {
7429 if (is_set(active_params, ujj + uii)) {
7430 // sample-major to covariate-major
7431 sample_uidx = 0;
7432 dptr = &(covars_cov_major[param_idx * sample_valid_ct]);
7433 dptr2 = &(covar_d[ujj]);
7434 for (sample_idx = 0; sample_idx < sample_ct; sample_uidx++, sample_idx++) {
7435 next_unset_ul_unsafe_ck(sample_exclude, &sample_uidx);
7436 if (IS_SET(load_mask, sample_uidx)) {
7437 *dptr++ = dptr2[sample_idx * covar_ct];
7438 }
7439 }
7440 strcpy(&(param_names[param_idx * max_param_name_len]), &(covar_names[ujj * max_covar_name_len]));
7441 param_idx++;
7442 }
7443 }
7444 if (variation_in_sex && IS_SET(active_params, ulii)) {
7445 sample_uidx = 0;
7446 dptr = &(covars_cov_major[param_idx * sample_valid_ct]);
7447 dptr2 = &(dptr[sample_valid_ct]);
7448 do {
7449 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
7450 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
7451 do {
7452 *dptr++ = (double)((intptr_t)is_set_ul(sex_male, sample_uidx));
7453 } while (++sample_uidx < sample_uidx_stop);
7454 } while (dptr < dptr2);
7455 memcpy(&(param_names[param_idx * max_param_name_len]), "SEX", 4);
7456 }
7457 if (glm_modifier & GLM_STANDARD_BETA) {
7458 // with no SNPs, only need to do this once
7459 dzz = g_pheno_sum / ((double)((intptr_t)sample_valid_ct)); // mean
7460 dyy = sqrt(((double)((intptr_t)(sample_valid_ct - 1))) / (g_pheno_ssq - g_pheno_sum * dzz)); // 1/stdev
7461 dptr = g_perm_pheno_d2;
7462 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
7463 *dptr = ((*dptr) - dzz) * dyy;
7464 dptr++;
7465 }
7466 for (param_idx = 1; param_idx < param_ct; param_idx++) {
7467 dxx = 0; // sum
7468 dyy = 0; // ssq
7469 dptr = &(covars_cov_major[param_idx * sample_valid_ct]);
7470 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
7471 dzz = *dptr++;
7472 dxx += dzz;
7473 dyy += dzz * dzz;
7474 }
7475 dptr = &(covars_cov_major[param_idx * sample_valid_ct]);
7476 dzz = dxx / ((double)((intptr_t)sample_valid_ct));
7477 dyy = sqrt((dyy - dxx * dzz) / ((double)((intptr_t)(sample_valid_ct - 1))));
7478 if (dyy == 0) {
7479 fill_double_zero(sample_valid_ct, dptr);
7480 } else {
7481 dyy = 1.0 / dyy;
7482 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
7483 *dptr = ((*dptr) - dzz) * dyy;
7484 dptr++;
7485 }
7486 }
7487 }
7488 }
7489 ii = glm_check_vif(glm_vif_thresh, param_ct, sample_valid_ct, covars_cov_major, param_2d_buf, mi_buf, param_2d_buf2);
7490 if (ii == -1) {
7491 goto glm_linear_nosnp_ret_NOMEM;
7492 } else if (ii == 1) {
7493 logerrprint("Warning: Skipping --linear no-snp since VIF check failed.\n");
7494 goto glm_linear_nosnp_ret_1;
7495 }
7496
7497 // required for multithreaded permutation generation
7498 g_perm_cluster_ct = 0;
7499 g_perm_pheno_nm_ct = sample_valid_ct;
7500
7501 perms_done = 0;
7502
7503 if (do_perms) {
7504 // not actually max(T), just fixed permutation count.
7505 if (perm_batch_size > glm_mperm_val) {
7506 perm_batch_size = glm_mperm_val;
7507 }
7508 } else {
7509 perm_batch_size = 1;
7510 mperm_save = 0;
7511 }
7512 if (bigstack_alloc_ul(BITCT_TO_WORDCT(perm_batch_size), &perm_fails) ||
7513 bigstack_alloc_d(perm_batch_size * (param_ctx - 1), &regression_results)) {
7514 goto glm_linear_nosnp_ret_NOMEM;
7515 }
7516
7517 if (do_perms) {
7518 if (bigstack_alloc_ui(sample_valid_ct - 1, &g_perm_precomputed_mods)) {
7519 goto glm_linear_nosnp_ret_NOMEM;
7520 }
7521 precompute_mods(sample_valid_ct, g_perm_precomputed_mods);
7522 }
7523 // may want to put a multiple linear regression wrapper function in
7524 // plink_matrix, perhaps with the PLINK 1.07 svdcmp/svbksb no-LAPACK
7525 // fallback
7526
7527 // multiple linear regression-specific allocations and preprocessing
7528 dgels_m = (int32_t)((uint32_t)sample_valid_ct);
7529 dgels_n = (int32_t)((uint32_t)param_ct);
7530 dgels_nrhs = perm_batch_size;
7531 dgels_ldb = dgels_m;
7532 if (bigstack_alloc_d(perm_batch_size * sample_valid_ct, &g_perm_pmajor) ||
7533 bigstack_alloc_d(param_ct * sample_valid_ct, &dgels_a) ||
7534 bigstack_alloc_d(perm_batch_size * sample_valid_ct, &dgels_b)) {
7535 goto glm_linear_nosnp_ret_NOMEM;
7536 }
7537 fill_double_zero(param_ctx - 1, regression_results);
7538 memcpy(dgels_a, covars_cov_major, param_ct * sample_valid_ct * sizeof(double));
7539 memcpy(dgels_b, g_perm_pheno_d2, sample_valid_ct * sizeof(double));
7540 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, &dxx, &dgels_lwork, &dgels_info);
7541 if (dxx > 2147483647.0) {
7542 // maybe this can't actually happen, but just in case...
7543 // (todo: update this, and all the other matrix logic, once LAPACK can
7544 // handle 64-bit integers; currently that's on their wishlist)
7545 logerrprint("Error: Multiple linear regression problem too large for current LAPACK version.\n");
7546 retval = RET_CALC_NOT_YET_SUPPORTED;
7547 goto glm_linear_nosnp_ret_1;
7548 }
7549 dgels_lwork = (int32_t)dxx;
7550 if (bigstack_alloc_d(dgels_lwork, &dgels_work)) {
7551 goto glm_linear_nosnp_ret_NOMEM;
7552 }
7553 dgels_nrhs = 1;
7554
7555 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
7556 if (dgels_info) {
7557 logerrprint("Warning: Skipping --linear no-snp since regression failed.\n");
7558 goto glm_linear_nosnp_ret_1;
7559 }
7560
7561 uii = perm_batch_size / CACHELINE_INT32;
7562 if (!uii) {
7563 uii = 1;
7564 }
7565 if (max_thread_ct > uii) {
7566 max_thread_ct = uii;
7567 }
7568 if (cluster_starts && do_perms) {
7569 retval = cluster_include_and_reindex(unfiltered_sample_ct, load_mask, 1, nullptr, sample_valid_ct, 0, cluster_ct, cluster_map, cluster_starts, &g_perm_cluster_ct, &g_perm_cluster_map, &g_perm_cluster_starts, nullptr, nullptr);
7570 if (retval) {
7571 goto glm_linear_nosnp_ret_1;
7572 }
7573 if (!g_perm_cluster_ct) {
7574 goto glm_linear_nosnp_ret_NO_PERMUTATION_CLUSTERS;
7575 }
7576 if (bigstack_alloc_ui(max_thread_ct * round_up_pow2(g_perm_cluster_ct, CACHELINE_INT32), &g_perm_qt_cluster_thread_wkspace)) {
7577 goto glm_linear_nosnp_ret_NOMEM;
7578 }
7579 if (bigstack_alloc_ui(sample_valid_ct, &g_perm_sample_to_cluster)) {
7580 goto glm_linear_nosnp_ret_NOMEM;
7581 }
7582 fill_unfiltered_sample_to_cluster(sample_valid_ct, g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, g_perm_sample_to_cluster);
7583 }
7584 if (do_perms) {
7585 // Note that, for now, the main nosnp regression loop is not multithreaded;
7586 // only the permutation generation process is.
7587 if (bigstack_init_sfmtp(max_thread_ct)) {
7588 goto glm_linear_nosnp_ret_NOMEM;
7589 }
7590 }
7591
7592 transpose_copy(param_ct, sample_valid_ct, covars_cov_major, covars_sample_major);
7593 if (glm_linear(1, param_ct, sample_valid_ct, 0, nullptr, 0, 0, 0, covars_cov_major, covars_sample_major, g_perm_pheno_d2, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, constraint_ct, constraints_con_major, param_df_buf, param_df_buf2, df_df_buf, df_buf, &perm_fail_ct, perm_fails) || perm_fail_ct) {
7594 logerrprint("Warning: Skipping --linear no-snp due to multicollinearity.\n");
7595 goto glm_linear_nosnp_ret_1;
7596 }
7597 if (constraint_ct && (regression_results[param_ct - 1] == -9)) {
7598 logerrprint("Warning: Ignoring --tests due to regression failure.\n");
7599 constraint_ct = 0;
7600 }
7601
7602 if (mperm_save) {
7603 // --mperm-save prevented during command-line parsing, so must be
7604 // --mperm-save-all
7605 if (bigstack_alloc_d(glm_mperm_val * (param_ctx - 1), &mperm_save_stats)) {
7606 goto glm_linear_nosnp_ret_NOMEM;
7607 }
7608 *outname_end = '\0';
7609 LOGPREPRINTFWW("Dumping all permutation absolute t-stats to %s.[testID].mperm.dump.all.\n", outname);
7610 fputs(g_logbuf, stdout);
7611 if (constraint_ct) {
7612 logprint("(exception: chi-square values will be dumped for joint test)\n");
7613 }
7614 }
7615 outname_end2 = memcpyb(outname_end, ".assoc.linear", 14);
7616 if (fopen_checked(outname, "w", &outfile)) {
7617 goto glm_linear_nosnp_ret_OPEN_FAIL;
7618 }
7619 LOGPRINTFWW5("Writing linear model association results to %s ... ", outname);
7620 fflush(stdout);
7621 fputs(" TEST NMISS BETA ", outfile);
7622 if (display_ci) {
7623 uii = (uint32_t)((int32_t)(ci_size * (100 + EPSILON)));
7624 if (uii >= 10) {
7625 fprintf(outfile, " SE L%u U%u ", uii, uii);
7626 } else {
7627 fprintf(outfile, " SE L%u U%u ", uii, uii);
7628 }
7629 }
7630 if (fputs_checked(" STAT P \n", outfile)) {
7631 goto glm_linear_nosnp_ret_WRITE_FAIL;
7632 }
7633
7634 for (param_idx = 1; param_idx < param_ct; param_idx++) {
7635 dxx = dgels_b[param_idx]; // coef[p]
7636 se = sqrt(regression_results[param_idx - 1]);
7637 zval = dxx / se;
7638 orig_stats[param_idx - 1] = fabs(zval);
7639 pval = calc_tprob(zval, sample_valid_ct - param_ct);
7640 if ((!hide_covar) && ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0)))) {
7641 wptr = fw_strcpy(10, &(param_names[param_idx * max_param_name_len]), g_textbuf);
7642 *wptr++ = ' ';
7643 wptr = uint32toa_w8x((uint32_t)sample_valid_ct, ' ', wptr);
7644 wptr = dtoa_g_wxp4x(dxx, 10, ' ', wptr);
7645 if (display_ci) {
7646 dyy = ci_zt * se;
7647 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
7648 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
7649 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
7650 }
7651 wptr = dtoa_g_wxp4x(zval, 12, ' ', wptr);
7652 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
7653 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7654 goto glm_linear_nosnp_ret_WRITE_FAIL;
7655 }
7656 }
7657 }
7658 if (report_intercept) {
7659 wptr = memcpya(g_textbuf, " INTERCEPT ", 11);
7660 wptr = uint32toa_w8x((uint32_t)sample_valid_ct, ' ', wptr);
7661 wptr = dtoa_g_wxp4x(dgels_b[0], 10, ' ', wptr);
7662 if (display_ci) {
7663 se = sqrt(param_2d_buf2[0]);
7664 dyy = ci_zt * se;
7665 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
7666 wptr = dtoa_g_wxp4x(dgels_b[0] - dyy, 8, ' ', wptr);
7667 wptr = dtoa_g_wxp4x(dgels_b[0] + dyy, 8, ' ', wptr);
7668 }
7669 wptr = memcpya(wptr, " NA NA\n", 26);
7670 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7671 goto glm_linear_nosnp_ret_WRITE_FAIL;
7672 }
7673 }
7674 if (constraint_ct) {
7675 dxx = regression_results[param_ct - 1];
7676 orig_stats[param_ct - 1] = dxx;
7677 pval = chiprob_p(dxx, constraint_ct);
7678 if ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0))) {
7679 wptr = fw_strcpy(10, &(param_names[param_ct * max_param_name_len]), g_textbuf);
7680 *wptr++ = ' ';
7681 wptr = uint32toa_w8((uint32_t)sample_valid_ct, wptr);
7682 wptr = memcpya(wptr, " NA ", 12);
7683 if (display_ci) {
7684 wptr = memcpya(wptr, " NA NA NA ", 27);
7685 }
7686 wptr = dtoa_g_wxp4x(dxx, 12, ' ', wptr);
7687 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
7688 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7689 goto glm_linear_nosnp_ret_WRITE_FAIL;
7690 }
7691 }
7692 }
7693 if (fclose_null(&outfile)) {
7694 goto glm_linear_nosnp_ret_WRITE_FAIL;
7695 }
7696 logprint("done.\n");
7697
7698 msa_ptr = mperm_save_stats;
7699 while (perms_done < glm_mperm_val) {
7700 cur_batch_size = perm_batch_size;
7701 if (cur_batch_size > glm_mperm_val - perms_done) {
7702 cur_batch_size = glm_mperm_val - perms_done;
7703 }
7704 g_perm_vec_ct = cur_batch_size;
7705 ulii = 0;
7706
7707 if (cur_batch_size >= CACHELINE_INT32 * max_thread_ct) {
7708 g_perm_generation_thread_ct = max_thread_ct;
7709 } else {
7710 g_perm_generation_thread_ct = MAXV(cur_batch_size / CACHELINE_INT32, 1);
7711 }
7712 if (!g_perm_cluster_ct) {
7713 if (spawn_threads(threads, &generate_qt_perms_pmajor_thread, g_perm_generation_thread_ct)) {
7714 goto glm_linear_nosnp_ret_THREAD_CREATE_FAIL;
7715 }
7716 generate_qt_perms_pmajor_thread((void*)ulii);
7717 } else {
7718 if (spawn_threads(threads, &generate_qt_cluster_perms_pmajor_thread, g_perm_generation_thread_ct)) {
7719 goto glm_linear_nosnp_ret_THREAD_CREATE_FAIL;
7720 }
7721 generate_qt_cluster_perms_pmajor_thread((void*)ulii);
7722 }
7723 join_threads(threads, g_perm_generation_thread_ct);
7724 dgels_nrhs = cur_batch_size;
7725 fill_double_zero((param_ctx - 1) * cur_batch_size, regression_results);
7726 memcpy(dgels_a, covars_cov_major, param_ct * sample_valid_ct * sizeof(double));
7727 memcpy(dgels_b, g_perm_pmajor, cur_batch_size * sample_valid_ct * sizeof(double));
7728 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
7729 if (glm_linear(cur_batch_size, param_ct, sample_valid_ct, 0, nullptr, 0, 0, 0, covars_cov_major, covars_sample_major, g_perm_pmajor, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, constraint_ct, constraints_con_major, param_df_buf, param_df_buf2, df_df_buf, df_buf, &perm_fail_ct, perm_fails)) {
7730 perm_fail_ct = cur_batch_size;
7731 fill_bits(0, cur_batch_size, perm_fails);
7732 }
7733 perm_fail_total += perm_fail_ct;
7734 ulii = param_ct - 1;
7735 uljj = param_ctx - 1;
7736 for (perm_idx = 0; perm_idx < cur_batch_size; perm_idx++) {
7737 if (IS_SET(perm_fails, perm_idx)) {
7738 if (mperm_save) {
7739 for (param_idx = 0; param_idx < uljj; param_idx++) {
7740 *msa_ptr++ = -9;
7741 }
7742 }
7743 continue;
7744 }
7745 // permutation-major regression coefficients
7746 dptr = &(dgels_b[perm_idx * sample_valid_ct + 1]);
7747 // permutation-major variances
7748 dptr2 = &(regression_results[perm_idx * uljj]);
7749 dptr3 = orig_stats;
7750 for (param_idx = 0; param_idx < ulii; param_idx++) {
7751 dxx = *dptr++;
7752 se = sqrt(*dptr2++);
7753 zval = fabs(dxx / se);
7754 dyy = *dptr3++;
7755 if (zval > dyy + EPSILON) {
7756 perm_2success_ct[param_idx] += 2;
7757 } else if (zval > dyy - EPSILON) {
7758 perm_2success_ct[param_idx] += 1;
7759 }
7760 if (mperm_save) {
7761 *msa_ptr++ = zval;
7762 }
7763 }
7764 if (joint_test_params) {
7765 if (constraint_ct) {
7766 dxx = *dptr2;
7767 dyy = *dptr3;
7768 if (dxx > dyy + EPSILON) {
7769 perm_2success_ct[ulii] += 2;
7770 } else if (dxx > dyy - EPSILON) {
7771 perm_2success_ct[ulii] += 1;
7772 }
7773 if (mperm_save) {
7774 *msa_ptr++ = dxx;
7775 }
7776 if (dxx == -9) {
7777 joint_perm_fail_extra++;
7778 }
7779 } else if (mperm_save) {
7780 msa_ptr++;
7781 }
7782 }
7783 }
7784 perms_done += cur_batch_size;
7785 putc_unlocked('\r', stdout);
7786 LOGPRINTF("%u permutation%s complete.", perms_done, (perms_done != 1)? "s" : "");
7787 fflush(stdout);
7788 }
7789 if (do_perms) {
7790 putc_unlocked('\n', stdout);
7791 memcpy(outname_end2, ".mperm", 7);
7792 if (fopen_checked(outname, "w", &outfile)) {
7793 goto glm_linear_nosnp_ret_OPEN_FAIL;
7794 }
7795 if (fputs_checked(" TEST EMP1 NP \n", outfile)) {
7796 goto glm_linear_nosnp_ret_WRITE_FAIL;
7797 }
7798 dxx = 0.5 / ((double)((int32_t)(glm_mperm_val - perm_fail_total) + 1));
7799 for (param_idx = 1; param_idx < param_ct; param_idx++) {
7800 wptr = fw_strcpy(10, &(param_names[param_idx * max_param_name_len]), g_textbuf);
7801 *wptr++ = ' ';
7802 pval = ((double)(perm_2success_ct[param_idx - 1] + 2)) * dxx;
7803 if (pval <= pfilter) {
7804 if (!perm_count) {
7805 wptr = dtoa_g_wxp4(pval, 12, wptr);
7806 } else {
7807 wptr = dtoa_g_wxp4(((double)perm_2success_ct[param_idx - 1]) * 0.5, 12, wptr);
7808 }
7809 wptr = memseta(wptr, 32, 3);
7810 wptr = uint32toa_w10(glm_mperm_val - perm_fail_total, wptr);
7811 wptr = memcpya(wptr, " \n", 2);
7812 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7813 goto glm_linear_nosnp_ret_WRITE_FAIL;
7814 }
7815 }
7816 }
7817 if (constraint_ct) {
7818 wptr = fw_strcpy(10, &(param_names[param_ct * max_param_name_len]), g_textbuf);
7819 *wptr++ = ' ';
7820 pval = ((double)(perm_2success_ct[param_ct - 1] + 2)) * 0.5 / ((double)((int32_t)(glm_mperm_val - perm_fail_total - joint_perm_fail_extra) + 1));
7821 if (pval <= pfilter) {
7822 if (!perm_count) {
7823 wptr = dtoa_g_wxp4(pval, 12, wptr);
7824 } else {
7825 wptr = dtoa_g_wxp4(((double)perm_2success_ct[param_ct - 1]) * 0.5, 12, wptr);
7826 }
7827 wptr = memseta(wptr, 32, 3);
7828 wptr = uint32toa_w10(glm_mperm_val - perm_fail_total - joint_perm_fail_extra, wptr);
7829 wptr = memcpya(wptr, " \n", 2);
7830 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7831 goto glm_linear_nosnp_ret_WRITE_FAIL;
7832 }
7833 }
7834 }
7835 if (fclose_null(&outfile)) {
7836 goto glm_linear_nosnp_ret_WRITE_FAIL;
7837 }
7838 LOGPRINTFWW("Permutation test report written to %s .\n", outname);
7839 if (mperm_save) {
7840 *outname_end = '.';
7841 if ((param_ct != param_ctx) && constraint_ct) {
7842 // need to distinguish between --tests being cancelled due to inversion
7843 // failure, vs. normal completion
7844 param_ct++;
7845 }
7846 for (param_idx = 1; param_idx < param_ct; param_idx++) {
7847 wptr = strcpya(&(outname_end[1]), &(param_names[param_idx * max_param_name_len]));
7848 memcpy(wptr, ".mperm.dump.all", 16);
7849 if (fopen_checked(outname, "w", &outfile)) {
7850 goto glm_linear_nosnp_ret_OPEN_FAIL;
7851 }
7852 ulii = param_ctx - 1;
7853 wptr = memcpya(g_textbuf, "0 ", 2);
7854 wptr = dtoa_gx(orig_stats[param_idx - 1], '\n', wptr);
7855 wptr2 = &(g_textbuf[MAXLINELEN]);
7856 dptr = &(mperm_save_stats[param_idx - 1]);
7857 for (perm_idx = 0; perm_idx < glm_mperm_val; perm_idx++) {
7858 wptr = uint32toa_x(perm_idx + 1, ' ', wptr);
7859 dxx = dptr[perm_idx * ulii];
7860 if (dxx >= 0) {
7861 wptr = dtoa_gx(dxx, '\n', wptr);
7862 } else {
7863 wptr = memcpyl3a(wptr, "NA\n");
7864 }
7865 if (wptr >= wptr2) {
7866 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7867 goto glm_linear_nosnp_ret_WRITE_FAIL;
7868 }
7869 wptr = g_textbuf;
7870 }
7871 }
7872 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
7873 goto glm_linear_nosnp_ret_WRITE_FAIL;
7874 }
7875 if (fclose_null(&outfile)) {
7876 goto glm_linear_nosnp_ret_WRITE_FAIL;
7877 }
7878 LOGPREPRINTFWW("%s written.\n", outname);
7879 logstr(g_logbuf);
7880 }
7881 }
7882 }
7883 while (0) {
7884 glm_linear_nosnp_ret_NOMEM:
7885 retval = RET_NOMEM;
7886 break;
7887 glm_linear_nosnp_ret_OPEN_FAIL:
7888 retval = RET_OPEN_FAIL;
7889 break;
7890 glm_linear_nosnp_ret_READ_FAIL:
7891 retval = RET_READ_FAIL;
7892 break;
7893 glm_linear_nosnp_ret_WRITE_FAIL:
7894 retval = RET_WRITE_FAIL;
7895 break;
7896 glm_linear_nosnp_ret_THREAD_CREATE_FAIL:
7897 retval = RET_THREAD_CREATE_FAIL;
7898 break;
7899 glm_linear_nosnp_ret_NO_PERMUTATION_CLUSTERS:
7900 logerrprint("Error: No size 2+ clusters for permutation test.\n");
7901 glm_linear_nosnp_ret_INVALID_CMDLINE:
7902 retval = RET_INVALID_CMDLINE;
7903 break;
7904 glm_linear_nosnp_ret_PHENO_CONSTANT:
7905 logerrprint("Warning: Skipping --linear since phenotype is constant.\n");
7906 break;
7907 }
7908 glm_linear_nosnp_ret_1:
7909 bigstack_double_reset(bigstack_mark, bigstack_end_mark);
7910 fclose_cond(outfile);
7911 aligned_free_cond(active_params);
7912 aligned_free_cond(joint_test_params);
7913 free_cond(condition_uidxs);
7914 return retval;
7915 }
7916 #endif
7917
7918 int32_t glm_logistic_nosnp(pthread_t* threads, FILE* bedfile, uintptr_t bed_offset, char* outname, char* outname_end, uint32_t glm_modifier, double glm_vif_thresh, uint32_t glm_xchr_model, uint32_t glm_mperm_val, Range_list* parameters_range_list_ptr, Range_list* tests_range_list_ptr, double ci_size, double ci_zt, double pfilter, double output_min_p, uintptr_t unfiltered_marker_ct, uintptr_t* marker_exclude, uintptr_t marker_ct, char* marker_ids, uintptr_t max_marker_id_len, uintptr_t* marker_reverse, char* condition_mname, char* condition_fname, Chrom_info* chrom_info_ptr, uintptr_t unfiltered_sample_ct, uintptr_t sample_ct, uintptr_t* sample_exclude, uint32_t cluster_ct, uint32_t* cluster_map, uint32_t* cluster_starts, uint32_t mperm_save, uint32_t pheno_nm_ct, uintptr_t* pheno_nm, uintptr_t* pheno_c, uintptr_t covar_ct, char* covar_names, uintptr_t max_covar_name_len, uintptr_t* covar_nm, double* covar_d, uintptr_t* sex_nm, uintptr_t* sex_male, uint32_t hh_or_mt_exists, uint32_t perm_batch_size, Set_info* sip) {
7919 unsigned char* bigstack_mark = g_bigstack_base;
7920 unsigned char* bigstack_end_mark = g_bigstack_end;
7921 uintptr_t unfiltered_sample_ct4 = (unfiltered_sample_ct + 3) / 4;
7922 uintptr_t unfiltered_sample_ctl = BITCT_TO_WORDCT(unfiltered_sample_ct);
7923 uintptr_t unfiltered_sample_ctv2 = 2 * unfiltered_sample_ctl;
7924 FILE* outfile = nullptr;
7925 uintptr_t sample_uidx = 0;
7926 uintptr_t max_param_name_len = 2;
7927 uintptr_t param_raw_ct = 1;
7928 uintptr_t condition_ct = 0;
7929 uintptr_t constraint_ct = 0;
7930 uintptr_t ulii = 0;
7931 uint32_t cur_batch_size = 1;
7932 uint32_t do_perms = (glm_modifier / GLM_MPERM) & 1;
7933 uint32_t perm_count = glm_modifier & GLM_PERM_COUNT;
7934 uint32_t hide_covar = glm_modifier & GLM_HIDE_COVAR;
7935 uint32_t report_odds = !(glm_modifier & GLM_BETA);
7936 uint32_t display_ci = (ci_size > 0);
7937 uint32_t variation_in_sex = 0; // no need to initialize if no-x-sex specified
7938 uint32_t perms_done = 0;
7939 uint32_t perm_fail_total = 0;
7940 uint32_t joint_perm_fail_extra = 0;
7941 uint32_t max_thread_ct = g_thread_ct;
7942 uint32_t skip_intercept = !(glm_modifier & GLM_INTERCEPT);
7943 int32_t retval = 0;
7944 uintptr_t* loadbuf_raw = nullptr;
7945 uintptr_t* loadbuf_collapsed = nullptr;
7946 uintptr_t* load_mask = nullptr;
7947 uintptr_t* sex_male_collapsed = nullptr;
7948 uintptr_t* sample_include2 = nullptr;
7949 uintptr_t* sample_male_include2 = nullptr;
7950 uintptr_t* active_params = nullptr;
7951 uintptr_t* joint_test_params = nullptr;
7952 double* mperm_save_stats = nullptr;
7953 double* constraints_con_major = nullptr;
7954 double* param_1d_dbuf = nullptr;
7955 double* param_2d_dbuf = nullptr;
7956 double* param_2d_dbuf2 = nullptr;
7957 double* param_df_dbuf = nullptr;
7958 double* df_df_dbuf = nullptr;
7959 MATRIX_INVERT_BUF1_TYPE* mi_buf = nullptr;
7960 double* df_dbuf = nullptr;
7961 uintptr_t* perm_fails = nullptr;
7962 uint32_t* perm_2success_ct = nullptr;
7963 uint32_t* condition_uidxs = nullptr;
7964 float geno_map[12];
7965 float* geno_map_ptr;
7966 char* param_names;
7967 float* covars_cov_major;
7968 float* coef;
7969 float* pp;
7970 float* sample_1d_buf;
7971 float* pheno_buf;
7972 float* param_1d_buf;
7973 float* param_1d_buf2;
7974 float* param_2d_buf;
7975 float* param_2d_buf2;
7976 float* regression_results;
7977 double* orig_stats;
7978 char* outname_end2;
7979 char* wptr;
7980 char* wptr2;
7981 float* fptr;
7982 float* fptr2;
7983 double* dptr;
7984 uintptr_t sample_valid_ct;
7985 uintptr_t sample_valid_cta4;
7986 uintptr_t sample_valid_ctaw;
7987 uintptr_t sample_valid_ctv2;
7988 uintptr_t sample_uidx_stop;
7989 uintptr_t sample_idx;
7990 uintptr_t param_raw_ctp2l;
7991 uintptr_t param_ct;
7992 uintptr_t param_cta4;
7993 uintptr_t param_ctx; // param_ct + 1 if joint test needed, param_ct otherwise
7994 uintptr_t param_idx;
7995 uintptr_t constraint_idx;
7996 uintptr_t final_mask;
7997 uintptr_t uljj;
7998 double* msa_ptr;
7999 double se;
8000 double zval;
8001 double pval;
8002 double dxx;
8003 double dyy;
8004 uint32_t perm_idx;
8005 uint32_t marker_uidx;
8006 uint32_t chrom_idx;
8007 uint32_t is_x;
8008 uint32_t is_y;
8009 uint32_t uii;
8010 uint32_t ujj;
8011 uint32_t slen;
8012 if (hide_covar && (!tests_range_list_ptr->name_ct) && (!(glm_modifier & GLM_TEST_ALL))) {
8013 logerrprint("Error: --logistic hide-covar no-snp produces no output.\n");
8014 goto glm_logistic_nosnp_ret_INVALID_CMDLINE;
8015 }
8016 if (glm_init_load_mask(sample_exclude, pheno_nm, covar_nm, sample_ct, unfiltered_sample_ctv2, &load_mask)) {
8017 goto glm_logistic_nosnp_ret_NOMEM;
8018 }
8019 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
8020 if ((chrom_info_ptr->xymt_codes[MT_OFFSET] != -2) && is_set(chrom_info_ptr->chrom_mask, chrom_info_ptr->xymt_codes[MT_OFFSET])) {
8021 hh_or_mt_exists |= NXMHH_EXISTS;
8022 }
8023 if (condition_mname || condition_fname) {
8024 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &loadbuf_raw)) {
8025 goto glm_logistic_nosnp_ret_NOMEM;
8026 }
8027 loadbuf_raw[unfiltered_sample_ctv2 - 2] = 0;
8028 loadbuf_raw[unfiltered_sample_ctv2 - 1] = 0;
8029
8030 if (hh_or_mt_exists & (Y_FIX_NEEDED | NXMHH_EXISTS)) {
8031 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_include2)) {
8032 goto glm_logistic_nosnp_ret_NOMEM;
8033 }
8034 fill_quatervec_55(unfiltered_sample_ct, sample_include2); // harmless
8035 }
8036 if (hh_or_mt_exists & (XMHH_EXISTS | Y_FIX_NEEDED)) {
8037 if (bigstack_end_alloc_ul(unfiltered_sample_ctv2, &sample_male_include2)) {
8038 goto glm_logistic_nosnp_ret_NOMEM;
8039 }
8040 init_quaterarr_from_bitarr(sex_male, unfiltered_sample_ct, sample_male_include2);
8041 }
8042 retval = glm_scan_conditions(condition_mname, condition_fname, unfiltered_marker_ct, marker_exclude, marker_ct, marker_ids, max_marker_id_len, chrom_info_ptr, hh_or_mt_exists, loadbuf_raw, bedfile, bed_offset, unfiltered_sample_ct, sex_male, load_mask, &sample_valid_ct, &condition_ct, &condition_uidxs, sample_include2, sample_male_include2);
8043 if (retval) {
8044 goto glm_logistic_nosnp_ret_1;
8045 }
8046 // deallocate temporary sample[_male]_include2
8047 bigstack_end_reset(loadbuf_raw);
8048 param_raw_ct += condition_ct;
8049 }
8050 param_raw_ct += covar_ct;
8051 if (glm_modifier & GLM_SEX) {
8052 sample_uidx = 0;
8053 sample_idx = 0;
8054 uii = 2;
8055 do {
8056 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
8057 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
8058 sample_idx += sample_uidx_stop - sample_uidx;
8059 do {
8060 if (IS_SET(sex_nm, sample_uidx)) {
8061 ujj = is_set(sex_male, sample_uidx);
8062 if (uii == ujj) {
8063 variation_in_sex = 1;
8064 sample_idx = sample_valid_ct;
8065 break;
8066 }
8067 uii = 1 - ujj;
8068 }
8069 } while (++sample_uidx < sample_uidx_stop);
8070 } while (sample_idx < sample_valid_ct);
8071 if (variation_in_sex) {
8072 param_raw_ct++;
8073 bitvec_and(sex_nm, unfiltered_sample_ctl, load_mask);
8074 sample_valid_ct = popcount_longs(load_mask, unfiltered_sample_ctl);
8075 } else {
8076 logerrprint("Warning: Ignoring --logistic 'sex' modifier since sex is invariant.\n");
8077 }
8078 }
8079 sample_valid_cta4 = round_up_pow2(sample_valid_ct, 4);
8080 sample_valid_ctaw = BITCT_TO_ALIGNED_WORDCT(sample_valid_ct);
8081 sample_valid_ctv2 = QUATERCT_TO_ALIGNED_WORDCT(sample_valid_ct);
8082
8083 if (condition_mname || condition_fname) {
8084 // now that we've determined which samples will be in the regression,
8085 // initialize collapsed sample_include2, sample_male_include2, sex_male
8086 if (hh_or_mt_exists & (Y_FIX_NEEDED | NXMHH_EXISTS)) {
8087 bigstack_end_alloc_ul(sample_valid_ctv2, &sample_include2);
8088 fill_quatervec_55(sample_valid_ct, sample_include2);
8089 }
8090 if (hh_or_mt_exists & (XMHH_EXISTS | Y_FIX_NEEDED)) {
8091 bigstack_end_alloc_ul(sample_valid_ctv2, &sample_male_include2);
8092 alloc_collapsed_haploid_filters(load_mask, sex_male, unfiltered_sample_ct, sample_valid_ct, hh_or_mt_exists, 1, &sample_include2, &sample_male_include2);
8093 }
8094 if (bigstack_end_alloc_ul(sample_valid_ctv2, &loadbuf_collapsed) ||
8095 bigstack_end_alloc_ul(sample_valid_ctv2 / 2, &sex_male_collapsed)) {
8096 goto glm_logistic_nosnp_ret_NOMEM;
8097 }
8098 loadbuf_collapsed[sample_valid_ctv2 - 2] = 0;
8099 loadbuf_collapsed[sample_valid_ctv2 - 1] = 0;
8100 copy_bitarr_subset(sex_male, load_mask, unfiltered_sample_ct, sample_valid_ct, sex_male_collapsed);
8101 }
8102 param_raw_ctp2l = BITCT_TO_WORDCT(param_raw_ct + 2);
8103 if (aligned_malloc(param_raw_ctp2l * sizeof(intptr_t), &active_params)) {
8104 goto glm_logistic_nosnp_ret_NOMEM;
8105 }
8106 if (parameters_range_list_ptr->name_ct) {
8107 fill_ulong_zero(param_raw_ctp2l, active_params);
8108 active_params[0] = 1;
8109 numeric_range_list_to_bitarr(parameters_range_list_ptr, param_raw_ct, 0, 1, active_params);
8110 param_ct = popcount_longs(active_params, param_raw_ctp2l);
8111 } else {
8112 fill_all_bits(param_raw_ct, active_params);
8113 param_ct = param_raw_ct;
8114 }
8115 param_cta4 = round_up_pow2(param_ct, 4);
8116 if (param_ct == 1) {
8117 logerrprint("Warning: Skipping --logistic since the intercept is the only variable.\n");
8118 goto glm_logistic_nosnp_ret_1;
8119 } else if (sample_valid_ct <= param_ct) {
8120 logerrprint("Warning: Skipping --logistic since # variables >= # samples.\n");
8121 if (pheno_nm_ct > param_ct) {
8122 logerrprint("(Check your covariates--all samples with at least one missing covariate are\nexcluded from this analysis.)\n");
8123 }
8124 goto glm_logistic_nosnp_ret_1;
8125 }
8126 // parameter sequence:
8127 // 1. intercept
8128 // 2. --condition-list (1 to condition_ct in raw list)
8129 // 3. --covar (condition_ct + 1 to condition_ct + covar_ct in raw list)
8130 // 4. sex (condition_ct + covar_ct + 1 in raw list)
8131 for (uii = 0; uii < condition_ct; uii++) {
8132 if (is_set(active_params, uii + 1)) {
8133 slen = strlen(&(marker_ids[condition_uidxs[uii] * max_marker_id_len]));
8134 if (max_param_name_len <= slen) {
8135 max_param_name_len = slen + 1;
8136 }
8137 }
8138 }
8139 uii = condition_ct + 1;
8140 for (ujj = 0; ujj < covar_ct; ujj++) {
8141 if (is_set(active_params, ujj + uii)) {
8142 slen = strlen(&(covar_names[ujj * max_covar_name_len]));
8143 if (max_param_name_len <= slen) {
8144 max_param_name_len = slen + 1;
8145 }
8146 }
8147 }
8148 param_ctx = param_ct;
8149 if (tests_range_list_ptr->name_ct || (glm_modifier & GLM_TEST_ALL)) {
8150 ulii = BITCT_TO_WORDCT(param_ct);
8151 if (aligned_malloc(ulii * sizeof(intptr_t), &joint_test_params)) {
8152 goto glm_logistic_nosnp_ret_NOMEM;
8153 }
8154 fill_ulong_zero(ulii, joint_test_params);
8155 if (tests_range_list_ptr->name_ct) {
8156 numeric_range_list_to_bitarr(tests_range_list_ptr, param_ct - 1, 1, 1, joint_test_params);
8157 constraint_ct = popcount_longs(joint_test_params, ulii);
8158 } else {
8159 constraint_ct = param_ct - 1;
8160 fill_bits(0, constraint_ct, joint_test_params);
8161 }
8162 if ((constraint_ct > 1) || (hide_covar && (constraint_ct == 1))) {
8163 // permit hide-covar + single --tests parameter combination
8164 slen = 8 + intlen((uint32_t)constraint_ct);
8165 if (max_param_name_len < slen) {
8166 max_param_name_len = slen;
8167 }
8168 param_ctx++;
8169 } else {
8170 constraint_ct = 0;
8171 aligned_free_null(&joint_test_params);
8172 logerrprint("Warning: Ignoring --tests since fewer than two parameter indices are in range.\n");
8173 }
8174 }
8175
8176 ulii = condition_ct + covar_ct + 1;
8177 if (variation_in_sex && IS_SET(active_params, ulii)) {
8178 if (max_param_name_len < 4) {
8179 max_param_name_len = 4;
8180 }
8181 }
8182 if (bigstack_alloc_c(param_ctx * max_param_name_len, &param_names) ||
8183 bigstack_alloc_f(param_ct * sample_valid_cta4, &covars_cov_major)) {
8184 goto glm_logistic_nosnp_ret_NOMEM;
8185 }
8186 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
8187 covars_cov_major[sample_idx] = 1;
8188 }
8189 if (sample_valid_ct % 4) {
8190 // need to zero out end of every row
8191 uii = sample_valid_cta4 - sample_valid_ct;
8192 for (param_idx = 0; param_idx < param_ct; param_idx++) {
8193 fill_float_zero(uii, &(covars_cov_major[param_idx * sample_valid_cta4 + sample_valid_ct]));
8194 }
8195 }
8196 param_idx = 1;
8197 fill_float_zero(12, geno_map);
8198 geno_map[0] = 1;
8199 geno_map[2] = 1;
8200 geno_map[4] = 1;
8201 geno_map[8] = 1;
8202 if (glm_modifier & GLM_CONDITION_RECESSIVE) {
8203 geno_map[2] = 0;
8204 } else if (!(glm_modifier & GLM_CONDITION_DOMINANT)) {
8205 geno_map[0] = 2;
8206 if (glm_xchr_model == 2) {
8207 geno_map[4] = 2;
8208 }
8209 }
8210 final_mask = get_final_mask(sample_valid_ct);
8211 for (uii = 0; uii < condition_ct; uii++) {
8212 if (is_set(active_params, uii + 1)) {
8213 marker_uidx = condition_uidxs[uii];
8214 if (fseeko(bedfile, bed_offset + ((uint64_t)marker_uidx) * unfiltered_sample_ct4, SEEK_SET)) {
8215 goto glm_logistic_nosnp_ret_READ_FAIL;
8216 }
8217 if (load_and_collapse_incl(unfiltered_sample_ct, sample_valid_ct, load_mask, final_mask, IS_SET(marker_reverse, marker_uidx), bedfile, loadbuf_raw, loadbuf_collapsed)) {
8218 goto glm_logistic_nosnp_ret_READ_FAIL;
8219 }
8220 chrom_idx = get_variant_chrom(chrom_info_ptr, marker_uidx);
8221 geno_map_ptr = geno_map;
8222 if (IS_SET(chrom_info_ptr->haploid_mask, chrom_idx) || (chrom_idx == (uint32_t)chrom_info_ptr->xymt_codes[MT_OFFSET])) {
8223 is_x = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[X_OFFSET]);
8224 is_y = ((int32_t)chrom_idx == chrom_info_ptr->xymt_codes[Y_OFFSET]);
8225 if (hh_or_mt_exists) {
8226 haploid_fix(hh_or_mt_exists, sample_include2, sample_male_include2, sample_valid_ct, is_x, is_y, (unsigned char*)loadbuf_collapsed);
8227 }
8228 if (!is_x) {
8229 geno_map_ptr = &(geno_map[8]);
8230 }
8231 } else {
8232 is_x = 0;
8233 }
8234 if (!is_x) {
8235 glm_loadbuf_to_floats(loadbuf_collapsed, sample_valid_ct, &(covars_cov_major[param_idx * sample_valid_cta4]), geno_map_ptr, nullptr);
8236 } else {
8237 glm_loadbuf_to_floats_x(loadbuf_collapsed, sex_male_collapsed, sample_valid_ct, &(covars_cov_major[param_idx * sample_valid_cta4]), geno_map_ptr, nullptr);
8238 }
8239 strcpy(&(param_names[param_idx * max_param_name_len]), &(marker_ids[marker_uidx * max_marker_id_len]));
8240 param_idx++;
8241 }
8242 }
8243 bigstack_end_reset(bigstack_end_mark);
8244 if (bigstack_alloc_ui(param_ctx - 1, &perm_2success_ct) ||
8245 bigstack_alloc_d(param_ctx - 1, &orig_stats)) {
8246 goto glm_logistic_nosnp_ret_NOMEM;
8247 }
8248
8249 if (constraint_ct) {
8250 if (bigstack_calloc_d(constraint_ct * param_ct, &constraints_con_major)) {
8251 goto glm_logistic_nosnp_ret_NOMEM;
8252 }
8253 uljj = 0;
8254 for (constraint_idx = 0; constraint_idx < constraint_ct; uljj++, constraint_idx++) {
8255 next_set_ul_unsafe_ck(joint_test_params, &uljj);
8256 constraints_con_major[constraint_idx * param_ct + uljj + 1] = 1;
8257 }
8258 wptr = memcpya(&(param_names[param_ct * max_param_name_len]), (glm_modifier & GLM_TEST_ALL)? "FULL" : "USER", 4);
8259 *wptr++ = '_';
8260 wptr = uint32toa(constraint_ct, wptr);
8261 memcpy(wptr, "DF", 3);
8262 }
8263 fill_uint_zero(param_ctx - 1, perm_2success_ct);
8264 sample_uidx = 0;
8265 sample_idx = 0;
8266 uii = condition_ct + 1;
8267 for (ujj = 0; ujj < covar_ct; ujj++) {
8268 if (is_set(active_params, ujj + uii)) {
8269 // sample-major to covariate-major
8270 sample_uidx = 0;
8271 fptr = &(covars_cov_major[param_idx * sample_valid_cta4]);
8272 dptr = &(covar_d[ujj]);
8273 for (sample_idx = 0; sample_idx < sample_ct; sample_uidx++, sample_idx++) {
8274 next_unset_ul_unsafe_ck(sample_exclude, &sample_uidx);
8275 if (IS_SET(load_mask, sample_uidx)) {
8276 *fptr++ = (float)dptr[sample_idx * covar_ct];
8277 }
8278 }
8279 strcpy(&(param_names[param_idx * max_param_name_len]), &(covar_names[ujj * max_covar_name_len]));
8280 param_idx++;
8281 }
8282 }
8283 if (variation_in_sex && IS_SET(active_params, ulii)) {
8284 sample_uidx = 0;
8285 fptr = &(covars_cov_major[param_idx * sample_valid_cta4]);
8286 fptr2 = &(fptr[sample_valid_ct]);
8287 do {
8288 sample_uidx = next_set_ul_unsafe(load_mask, sample_uidx);
8289 sample_uidx_stop = next_unset_ul(load_mask, sample_uidx, unfiltered_sample_ct);
8290 do {
8291 *fptr++ = (float)((intptr_t)is_set_ul(sex_male, sample_uidx));
8292 } while (++sample_uidx < sample_uidx_stop);
8293 } while (fptr < fptr2);
8294 memcpy(&(param_names[param_idx * max_param_name_len]), "SEX", 4);
8295 }
8296 // no more VIF check
8297
8298 // required for multithreaded permutation generation
8299 g_perm_cluster_ct = 0;
8300 g_perm_pheno_nm_ct = sample_valid_ct;
8301
8302 perms_done = 0;
8303
8304 if (do_perms) {
8305 // not actually max(T), just fixed permutation count.
8306 if (perm_batch_size > glm_mperm_val) {
8307 perm_batch_size = glm_mperm_val;
8308 }
8309 } else {
8310 perm_batch_size = 1;
8311 mperm_save = 0;
8312 }
8313 uii = ((perm_batch_size > 1) || skip_intercept)? 1 : 0;
8314 if (bigstack_alloc_f(param_cta4 * perm_batch_size, &coef) ||
8315 bigstack_alloc_f(sample_valid_cta4, &pp) ||
8316 bigstack_alloc_f(sample_valid_ct, &sample_1d_buf) ||
8317 bigstack_alloc_f(sample_valid_ct, &pheno_buf) ||
8318 bigstack_alloc_f(param_ct, &param_1d_buf) ||
8319 bigstack_alloc_f(param_ct, &param_1d_buf2) ||
8320 bigstack_alloc_f(param_ct * param_cta4, &param_2d_buf) ||
8321 bigstack_alloc_f(param_ct * param_cta4, &param_2d_buf2) ||
8322 bigstack_alloc_f(perm_batch_size * (param_ctx - uii), &regression_results) ||
8323 bigstack_alloc_ul(BITCT_TO_WORDCT(perm_batch_size), &perm_fails) ||
8324 bigstack_alloc_ul(perm_batch_size * sample_valid_ctaw, &g_perm_vecs)) {
8325 goto glm_logistic_nosnp_ret_NOMEM;
8326 }
8327 g_perm_vecs[sample_valid_ctaw - 1] = 0;
8328 copy_bitarr_subset(pheno_c, load_mask, unfiltered_sample_ct, sample_valid_ct, g_perm_vecs);
8329 g_perm_case_ct = popcount_longs(g_perm_vecs, sample_valid_ctaw);
8330 if ((!g_perm_case_ct) || (g_perm_case_ct == sample_valid_ct)) {
8331 goto glm_logistic_nosnp_ret_PHENO_CONSTANT;
8332 }
8333
8334 uii = perm_batch_size;
8335 if (max_thread_ct > uii) {
8336 max_thread_ct = uii;
8337 }
8338 if (cluster_starts && do_perms) {
8339 retval = cluster_include_and_reindex(unfiltered_sample_ct, load_mask, 1, pheno_c, sample_valid_ct, 0, cluster_ct, cluster_map, cluster_starts, &g_perm_cluster_ct, &g_perm_cluster_map, &g_perm_cluster_starts, &g_perm_cluster_case_cts, &g_perm_cluster_cc_preimage);
8340 if (retval) {
8341 goto glm_logistic_nosnp_ret_1;
8342 }
8343 if (!g_perm_cluster_ct) {
8344 goto glm_logistic_nosnp_ret_NO_PERMUTATION_CLUSTERS;
8345 }
8346 if (cluster_alloc_and_populate_magic_nums(g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, &g_perm_tot_quotients, &g_perm_totq_magics, &g_perm_totq_preshifts, &g_perm_totq_postshifts, &g_perm_totq_incrs)) {
8347 goto glm_logistic_nosnp_ret_NOMEM;
8348 }
8349 if (bigstack_alloc_ui(sample_valid_ct, &g_perm_sample_to_cluster)) {
8350 goto glm_logistic_nosnp_ret_NOMEM;
8351 }
8352 fill_unfiltered_sample_to_cluster(sample_valid_ct, g_perm_cluster_ct, g_perm_cluster_map, g_perm_cluster_starts, g_perm_sample_to_cluster);
8353 }
8354 if (constraint_ct) {
8355 mi_buf = (MATRIX_INVERT_BUF1_TYPE*)bigstack_alloc(param_ct * MATRIX_INVERT_BUF1_ELEM_ALLOC);
8356 if (!mi_buf) {
8357 goto glm_logistic_nosnp_ret_NOMEM;
8358 }
8359 if (bigstack_alloc_d(param_ct, &param_1d_dbuf) ||
8360 bigstack_alloc_d(param_ct * param_ct, &param_2d_dbuf) ||
8361 bigstack_alloc_d(param_ct * param_ct, &param_2d_dbuf2) ||
8362 bigstack_alloc_d(param_ct * constraint_ct, &param_df_dbuf) ||
8363 bigstack_alloc_d(constraint_ct * constraint_ct, &df_df_dbuf) ||
8364 bigstack_alloc_d(constraint_ct, &df_dbuf)) {
8365 goto glm_logistic_nosnp_ret_NOMEM;
8366 }
8367 }
8368 if (do_perms) {
8369 g_perm_tot_quotient = 0x100000000LLU / sample_valid_ct;
8370 magic_num(g_perm_tot_quotient, &g_perm_totq_magic, &g_perm_totq_preshift, &g_perm_totq_postshift, &g_perm_totq_incr);
8371 // Note that, for now, the main nosnp regression loop is not multithreaded;
8372 // only the permutation generation process is.
8373 if (bigstack_init_sfmtp(max_thread_ct)) {
8374 goto glm_logistic_nosnp_ret_NOMEM;
8375 }
8376 g_perm_is_1bit = 1;
8377 }
8378
8379 fill_float_zero(param_cta4, coef);
8380 if (glm_logistic(1, param_ct, sample_valid_ct, 0, skip_intercept, nullptr, covars_cov_major, g_perm_vecs, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, constraint_ct, constraints_con_major, param_1d_dbuf, param_2d_dbuf, param_2d_dbuf2, param_df_dbuf, df_df_dbuf, mi_buf, df_dbuf, perm_fails)) {
8381 logerrprint("Warning: Skipping --logistic no-snp due to multicollinearity.\n");
8382 goto glm_logistic_nosnp_ret_1;
8383 }
8384 if (constraint_ct && (regression_results[param_ct - skip_intercept] == -9)) {
8385 logerrprint("Warning: Ignoring --tests due to regression failure.\n");
8386 constraint_ct = 0;
8387 }
8388
8389 if (mperm_save) {
8390 // --mperm-save prevented during command-line parsing, so must be
8391 // --mperm-save-all
8392 if (bigstack_alloc_d(glm_mperm_val * (param_ctx - 1), &mperm_save_stats)) {
8393 goto glm_logistic_nosnp_ret_NOMEM;
8394 }
8395 *outname_end = '\0';
8396 LOGPREPRINTFWW("Dumping all permutation chi-square values to %s.[testID].mperm.dump.all.\n", outname);
8397 fputs(g_logbuf, stdout);
8398 }
8399 outname_end2 = memcpyb(outname_end, ".assoc.logistic", 16);
8400 if (fopen_checked(outname, "w", &outfile)) {
8401 goto glm_logistic_nosnp_ret_OPEN_FAIL;
8402 }
8403 LOGPRINTFWW5("Writing logistic model association results to %s ... ", outname);
8404 fflush(stdout);
8405 fprintf(outfile, " TEST NMISS %s ", report_odds? " OR" : "BETA");
8406 if (display_ci) {
8407 uii = (uint32_t)((int32_t)(ci_size * (100 + EPSILON)));
8408 if (uii >= 10) {
8409 fprintf(outfile, " SE L%u U%u ", uii, uii);
8410 } else {
8411 fprintf(outfile, " SE L%u U%u ", uii, uii);
8412 }
8413 }
8414 if (fputs_checked(" STAT P \n", outfile)) {
8415 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8416 }
8417
8418 for (param_idx = 1; param_idx < param_ct; param_idx++) {
8419 dxx = (double)coef[param_idx];
8420 se = sqrt((double)regression_results[param_idx - skip_intercept]);
8421 zval = dxx / se;
8422 orig_stats[param_idx - 1] = zval * zval;
8423 pval = chiprob_p(zval * zval, 1);
8424 if ((!hide_covar) && ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0)))) {
8425 wptr = fw_strcpy(10, &(param_names[param_idx * max_param_name_len]), g_textbuf);
8426 *wptr++ = ' ';
8427 wptr = uint32toa_w8x((uint32_t)sample_valid_ct, ' ', wptr);
8428 wptr = dtoa_g_wxp4x(report_odds? exp(dxx) : dxx, 10, ' ', wptr);
8429 if (display_ci) {
8430 dyy = ci_zt * se;
8431 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
8432 if (report_odds) {
8433 wptr = dtoa_g_wxp4x(exp(dxx - dyy), 8, ' ', wptr);
8434 wptr = dtoa_g_wxp4x(exp(dxx + dyy), 8, ' ', wptr);
8435 } else {
8436 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
8437 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
8438 }
8439 }
8440 wptr = dtoa_g_wxp4x(zval, 12, ' ', wptr);
8441 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
8442 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8443 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8444 }
8445 }
8446 }
8447 if (!skip_intercept) {
8448 dxx = (double)coef[0];
8449 wptr = memcpya(g_textbuf, " INTERCEPT ", 11);
8450 wptr = uint32toa_w8x((uint32_t)sample_valid_ct, ' ', wptr);
8451 wptr = dtoa_g_wxp4x(report_odds? exp(dxx) : dxx, 10, ' ', wptr);
8452 if (display_ci) {
8453 se = sqrt((double)regression_results[0]);
8454 dyy = ci_zt * se;
8455 wptr = dtoa_g_wxp4x(se, 8, ' ', wptr);
8456 if (report_odds) {
8457 wptr = dtoa_g_wxp4x(exp(dxx - dyy), 8, ' ', wptr);
8458 wptr = dtoa_g_wxp4x(exp(dxx + dyy), 8, ' ', wptr);
8459 } else {
8460 wptr = dtoa_g_wxp4x(dxx - dyy, 8, ' ', wptr);
8461 wptr = dtoa_g_wxp4x(dxx + dyy, 8, ' ', wptr);
8462 }
8463 }
8464 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8465 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8466 }
8467 }
8468 if (constraint_ct) {
8469 dxx = (double)regression_results[param_ct - skip_intercept];
8470 orig_stats[param_ct - 1] = dxx;
8471 pval = chiprob_p(dxx, constraint_ct);
8472 if ((pfilter == 2.0) || ((pval <= pfilter) && (pval >= 0.0))) {
8473 wptr = fw_strcpy(10, &(param_names[param_ct * max_param_name_len]), g_textbuf);
8474 *wptr++ = ' ';
8475 wptr = uint32toa_w8((uint32_t)sample_valid_ct, wptr);
8476 wptr = memcpya(wptr, " NA ", 12);
8477 if (display_ci) {
8478 wptr = memcpya(wptr, " NA NA NA ", 27);
8479 }
8480 wptr = dtoa_g_wxp4x(dxx, 12, ' ', wptr);
8481 wptr = dtoa_g_wxp4x(MAXV(pval, output_min_p), 12, '\n', wptr);
8482 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8483 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8484 }
8485 }
8486 }
8487 if (fclose_null(&outfile)) {
8488 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8489 }
8490 logprint("done.\n");
8491
8492 msa_ptr = mperm_save_stats;
8493 while (perms_done < glm_mperm_val) {
8494 cur_batch_size = perm_batch_size;
8495 if (cur_batch_size > glm_mperm_val - perms_done) {
8496 cur_batch_size = glm_mperm_val - perms_done;
8497 }
8498 g_perm_vec_ct = cur_batch_size;
8499 ulii = 0;
8500
8501 if (cur_batch_size > max_thread_ct) {
8502 g_perm_generation_thread_ct = max_thread_ct;
8503 } else {
8504 g_perm_generation_thread_ct = g_perm_vec_ct;
8505 }
8506 if (!g_perm_cluster_ct) {
8507 if (spawn_threads(threads, &generate_cc_perms_thread, g_perm_generation_thread_ct)) {
8508 goto glm_logistic_nosnp_ret_THREAD_CREATE_FAIL;
8509 }
8510 generate_cc_perms_thread((void*)ulii);
8511 } else {
8512 if (spawn_threads(threads, &generate_cc_cluster_perms_thread, g_perm_generation_thread_ct)) {
8513 goto glm_logistic_nosnp_ret_THREAD_CREATE_FAIL;
8514 }
8515 generate_cc_cluster_perms_thread((void*)ulii);
8516 }
8517 join_threads(threads, g_perm_generation_thread_ct);
8518 fill_float_zero(cur_batch_size * param_cta4, coef);
8519 perm_fail_total += glm_logistic(cur_batch_size, param_ct, sample_valid_ct, 0, 1, nullptr, covars_cov_major, g_perm_vecs, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, constraint_ct, constraints_con_major, param_1d_dbuf, param_2d_dbuf, param_2d_dbuf2, param_df_dbuf, df_df_dbuf, mi_buf, df_dbuf, perm_fails);
8520 ulii = param_ct - 1;
8521 uljj = param_ctx - 1;
8522 for (perm_idx = 0; perm_idx < cur_batch_size; perm_idx++) {
8523 if (IS_SET(perm_fails, perm_idx)) {
8524 if (mperm_save) {
8525 for (param_idx = 0; param_idx < uljj; param_idx++) {
8526 *msa_ptr++ = -9;
8527 }
8528 }
8529 continue;
8530 }
8531 fptr = &(coef[perm_idx * param_ct + 1]);
8532 fptr2 = &(regression_results[perm_idx * uljj]);
8533 dptr = orig_stats;
8534 for (param_idx = 0; param_idx < ulii; param_idx++) {
8535 dxx = (double)(*fptr++);
8536 se = sqrt((double)(*fptr2++));
8537 zval = fabs(dxx / se);
8538 dyy = *dptr++;
8539 zval *= zval;
8540 if (zval > dyy + EPSILON) {
8541 perm_2success_ct[param_idx] += 2;
8542 } else if (zval > dyy - EPSILON) {
8543 perm_2success_ct[param_idx] += 1;
8544 }
8545 if (mperm_save) {
8546 *msa_ptr++ = zval;
8547 }
8548 }
8549 if (joint_test_params) {
8550 if (constraint_ct) {
8551 dxx = (double)(*fptr2);
8552 dyy = *dptr;
8553 if (dxx > dyy + EPSILON) {
8554 perm_2success_ct[ulii] += 2;
8555 } else if (dxx > dyy - EPSILON) {
8556 perm_2success_ct[ulii] += 1;
8557 }
8558 if (mperm_save) {
8559 *msa_ptr++ = dxx;
8560 }
8561 if (dxx == -9) {
8562 joint_perm_fail_extra++;
8563 }
8564 } else if (mperm_save) {
8565 msa_ptr++;
8566 }
8567 }
8568 }
8569 perms_done += cur_batch_size;
8570 putc_unlocked('\r', stdout);
8571 LOGPRINTF("%u permutation%s complete.", perms_done, (perms_done != 1)? "s" : "");
8572 fflush(stdout);
8573 }
8574 if (do_perms) {
8575 putc_unlocked('\n', stdout);
8576 memcpy(outname_end2, ".mperm", 7);
8577 if (fopen_checked(outname, "w", &outfile)) {
8578 goto glm_logistic_nosnp_ret_OPEN_FAIL;
8579 }
8580 if (fputs_checked(" TEST EMP1 NP \n", outfile)) {
8581 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8582 }
8583 dxx = 0.5 / ((double)((int32_t)(glm_mperm_val - perm_fail_total) + 1));
8584 for (param_idx = 1; param_idx < param_ct; param_idx++) {
8585 wptr = fw_strcpy(10, &(param_names[param_idx * max_param_name_len]), g_textbuf);
8586 *wptr++ = ' ';
8587 pval = ((double)(perm_2success_ct[param_idx - 1] + 2)) * dxx;
8588 if (pval <= pfilter) {
8589 if (!perm_count) {
8590 wptr = dtoa_g_wxp4(pval, 12, wptr);
8591 } else {
8592 wptr = dtoa_g_wxp4(((double)perm_2success_ct[param_idx - 1]) * 0.5, 12, wptr);
8593 }
8594 wptr = memseta(wptr, 32, 3);
8595 wptr = uint32toa_w10(glm_mperm_val - perm_fail_total, wptr);
8596 wptr = memcpya(wptr, " \n", 2);
8597 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8598 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8599 }
8600 }
8601 }
8602 if (constraint_ct) {
8603 wptr = fw_strcpy(10, &(param_names[param_ct * max_param_name_len]), g_textbuf);
8604 *wptr++ = ' ';
8605 pval = ((double)(perm_2success_ct[param_ct - 1] + 2)) * 0.5 / ((double)((int32_t)(glm_mperm_val - perm_fail_total - joint_perm_fail_extra) + 1));
8606 if (pval <= pfilter) {
8607 if (!perm_count) {
8608 wptr = dtoa_g_wxp4(pval, 12, wptr);
8609 } else {
8610 wptr = dtoa_g_wxp4(((double)perm_2success_ct[param_ct - 1]) * 0.5, 12, wptr);
8611 }
8612 wptr = memseta(wptr, 32, 3);
8613 wptr = uint32toa_w10(glm_mperm_val - perm_fail_total - joint_perm_fail_extra, wptr);
8614 wptr = memcpya(wptr, " \n", 2);
8615 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8616 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8617 }
8618 }
8619 }
8620 if (fclose_null(&outfile)) {
8621 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8622 }
8623 LOGPRINTFWW("Permutation test report written to %s .\n", outname);
8624 if (mperm_save) {
8625 *outname_end = '.';
8626 if ((param_ct != param_ctx) && constraint_ct) {
8627 // need to distinguish between --tests being cancelled due to inversion
8628 // failure, vs. normal completion
8629 param_ct++;
8630 }
8631 for (param_idx = 1; param_idx < param_ct; param_idx++) {
8632 wptr = strcpya(&(outname_end[1]), &(param_names[param_idx * max_param_name_len]));
8633 memcpy(wptr, ".mperm.dump.all", 16);
8634 if (fopen_checked(outname, "w", &outfile)) {
8635 goto glm_logistic_nosnp_ret_OPEN_FAIL;
8636 }
8637 ulii = param_ctx - 1;
8638 wptr = memcpya(g_textbuf, "0 ", 2);
8639 wptr = dtoa_gx(orig_stats[param_idx - 1], '\n', wptr);
8640 wptr2 = &(g_textbuf[MAXLINELEN]);
8641 dptr = &(mperm_save_stats[param_idx - 1]);
8642 for (perm_idx = 0; perm_idx < glm_mperm_val; perm_idx++) {
8643 wptr = uint32toa_x(perm_idx + 1, ' ', wptr);
8644 dxx = dptr[perm_idx * ulii];
8645 if (dxx >= 0) {
8646 wptr = dtoa_gx(dxx, '\n', wptr);
8647 } else {
8648 wptr = memcpyl3a(wptr, "NA\n");
8649 }
8650 if (wptr >= wptr2) {
8651 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8652 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8653 }
8654 wptr = g_textbuf;
8655 }
8656 }
8657 if (fwrite_checked(g_textbuf, wptr - g_textbuf, outfile)) {
8658 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8659 }
8660 if (fclose_null(&outfile)) {
8661 goto glm_logistic_nosnp_ret_WRITE_FAIL;
8662 }
8663 LOGPREPRINTFWW("%s written.\n", outname);
8664 logstr(g_logbuf);
8665 }
8666 }
8667 }
8668 while (0) {
8669 glm_logistic_nosnp_ret_NOMEM:
8670 retval = RET_NOMEM;
8671 break;
8672 glm_logistic_nosnp_ret_OPEN_FAIL:
8673 retval = RET_OPEN_FAIL;
8674 break;
8675 glm_logistic_nosnp_ret_READ_FAIL:
8676 retval = RET_READ_FAIL;
8677 break;
8678 glm_logistic_nosnp_ret_WRITE_FAIL:
8679 retval = RET_WRITE_FAIL;
8680 break;
8681 glm_logistic_nosnp_ret_THREAD_CREATE_FAIL:
8682 retval = RET_THREAD_CREATE_FAIL;
8683 break;
8684 glm_logistic_nosnp_ret_NO_PERMUTATION_CLUSTERS:
8685 logerrprint("Error: No size 2+ clusters for permutation test.\n");
8686 glm_logistic_nosnp_ret_INVALID_CMDLINE:
8687 retval = RET_INVALID_CMDLINE;
8688 break;
8689 glm_logistic_nosnp_ret_PHENO_CONSTANT:
8690 logerrprint("Warning: Skipping --logistic since phenotype is constant.\n");
8691 break;
8692 }
8693 glm_logistic_nosnp_ret_1:
8694 bigstack_double_reset(bigstack_mark, bigstack_end_mark);
8695 fclose_cond(outfile);
8696 aligned_free_cond(active_params);
8697 aligned_free_cond(joint_test_params);
8698 free_cond(condition_uidxs);
8699 return retval;
8700 }
8701
8702 #ifndef NOLAPACK
8703 uint32_t glm_linear_dosage(uintptr_t sample_ct, uintptr_t* cur_samples, uintptr_t sample_valid_ct, uintptr_t* pheno_nm, double* pheno_d, uintptr_t* perm_fails, uintptr_t covar_ct, double* covar_d, double* cur_dosages, double* pheno_d2, double* covars_cov_major, double* covars_sample_major, double* param_2d_buf, MATRIX_INVERT_BUF1_TYPE* mi_buf, double* param_2d_buf2, double* regression_results, double* dgels_a, double* dgels_b, double* dgels_work, __CLPK_integer dgels_lwork, uint32_t standard_beta, double vif_thresh, double* beta_ptr, double* se_ptr, double* pval_ptr) {
8704 uintptr_t param_ct = covar_ct + 2;
8705 if (sample_valid_ct <= param_ct) {
8706 return 0;
8707 }
8708 double* dptr = pheno_d2;
8709 __CLPK_integer dgels_m = (int32_t)((uint32_t)sample_valid_ct);
8710 __CLPK_integer dgels_n = (int32_t)((uint32_t)param_ct);
8711 __CLPK_integer dgels_nrhs = 1;
8712 __CLPK_integer dgels_ldb = dgels_m;
8713 char dgels_trans = 'N';
8714 double* dptr2;
8715 uintptr_t sample_uidx;
8716 uintptr_t sample_idx;
8717 uintptr_t covar_idx;
8718 double dxx;
8719 double dyy;
8720 double dzz;
8721 __CLPK_integer dgels_info;
8722 uint32_t perm_fail_ct;
8723 int32_t ii;
8724 if (!standard_beta) {
8725 dptr2 = covars_sample_major;
8726 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8727 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8728 *dptr++ = pheno_d[sample_uidx];
8729 *dptr2++ = 1.0;
8730 *dptr2++ = cur_dosages[sample_uidx];
8731 if (covar_ct) {
8732 memcpy(dptr2, &(covar_d[sample_uidx * covar_ct]), covar_ct * sizeof(double));
8733 dptr2 = &(dptr2[covar_ct]);
8734 }
8735 }
8736 transpose_copy(sample_valid_ct, param_ct, covars_sample_major, covars_cov_major);
8737 } else {
8738 // kind of silly that this flag makes us switch from sample-major ->
8739 // cov-major to cov-major -> sample-major initialization, but what can you
8740 // do.
8741 dxx = 0; // sum
8742 dyy = 0; // ssq
8743 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8744 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8745 dzz = pheno_d[sample_uidx];
8746 *dptr++ = dzz;
8747 dxx += dzz;
8748 dyy += dzz * dzz;
8749 }
8750 dzz = dxx / ((double)((intptr_t)sample_valid_ct)); // mean
8751 dyy = sqrt(((double)((intptr_t)(sample_valid_ct - 1))) / (dyy - dxx * dzz)); // 1/stdev
8752 dptr = pheno_d2;
8753 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
8754 *dptr = ((*dptr) - dzz) * dyy;
8755 dptr++;
8756 }
8757 dptr = covars_cov_major;
8758 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
8759 *dptr++ = 1;
8760 }
8761 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8762 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8763 *dptr++ = cur_dosages[sample_uidx];
8764 }
8765 for (covar_idx = 0; covar_idx < covar_ct; covar_idx++) {
8766 dxx = 0;
8767 dyy = 0;
8768 dptr2 = dptr;
8769 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8770 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8771 dzz = covar_d[sample_uidx * covar_ct];
8772 *dptr2++ = dzz;
8773 dxx += dzz;
8774 dyy += dzz * dzz;
8775 }
8776 dzz = dxx / ((double)((intptr_t)sample_valid_ct));
8777 dyy = sqrt(((double)((intptr_t)(sample_valid_ct - 1))) / (dyy - dxx * dzz));
8778 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
8779 *dptr = ((*dptr) - dzz) * dyy;
8780 dptr++;
8781 }
8782 // "destructive" populate, we don't need covar_d again in this function
8783 // call
8784 covar_d++;
8785 }
8786 transpose_copy(param_ct, sample_valid_ct, covars_cov_major, covars_sample_major);
8787 }
8788 ii = glm_check_vif(vif_thresh, param_ct, sample_valid_ct, covars_cov_major, param_2d_buf, mi_buf, param_2d_buf2);
8789 if (ii == -1) {
8790 // kludge, might be better to calculate maximum VIF check memory usage
8791 // and verify that much workspace is free ahead of time
8792 return 2;
8793 } else if (ii == 1) {
8794 return 0;
8795 }
8796 transpose_copy(param_ct, sample_valid_ct, covars_cov_major, covars_sample_major);
8797 fill_double_zero(param_ct - 1, regression_results);
8798 memcpy(dgels_a, covars_cov_major, param_ct * sample_valid_ct * sizeof(double));
8799 memcpy(dgels_b, pheno_d2, sample_valid_ct * sizeof(double));
8800 dgels_(&dgels_trans, &dgels_m, &dgels_n, &dgels_nrhs, dgels_a, &dgels_m, dgels_b, &dgels_ldb, dgels_work, &dgels_lwork, &dgels_info);
8801 glm_linear(1, param_ct, sample_valid_ct, 0, nullptr, 0, 0, 0, covars_cov_major, covars_sample_major, pheno_d2, dgels_b, param_2d_buf, mi_buf, param_2d_buf2, regression_results, 0, nullptr, nullptr, nullptr, nullptr, nullptr, &perm_fail_ct, perm_fails);
8802 if (perm_fail_ct) {
8803 return 0;
8804 }
8805 dxx = dgels_b[1];
8806 dyy = sqrt(regression_results[0]);
8807 *beta_ptr = dxx;
8808 *se_ptr = dyy;
8809 *pval_ptr = calc_tprob(dxx / dyy, sample_valid_ct - param_ct);
8810 return 1;
8811 }
8812 #endif
8813
8814 uint32_t glm_logistic_dosage(uintptr_t sample_ct, uintptr_t* cur_samples, uintptr_t sample_valid_ct, uintptr_t* pheno_nm, uintptr_t* pheno_c, uintptr_t* perm_vec, uintptr_t* perm_fails, uintptr_t covar_ct, float* covar_f, double* cur_dosages, float* coef, float* pp, float* pheno_buf, float* covars_cov_major, float* param_1d_buf, float* param_1d_buf2, float* param_2d_buf, float* param_2d_buf2, float* regression_results, float* sample_1d_buf, double* beta_ptr, double* se_ptr, double* pval_ptr) {
8815 uintptr_t param_ct = covar_ct + 2;
8816 if (sample_valid_ct <= param_ct) {
8817 return 0;
8818 }
8819 uintptr_t sample_valid_cta4 = round_up_pow2(sample_valid_ct, 4);
8820 uintptr_t sample_valid_ctaw = BITCT_TO_ALIGNED_WORDCT(sample_valid_ct);
8821 uintptr_t param_cta4 = round_up_pow2(param_ct, 4);
8822 float* fptr = covars_cov_major;
8823 uintptr_t case_ct;
8824 uintptr_t sample_uidx;
8825 uintptr_t sample_idx;
8826 uintptr_t covar_idx;
8827 double dxx;
8828 double dyy;
8829 perm_vec[sample_valid_ctaw - 1] = 0;
8830 copy_bitarr_subset(pheno_c, cur_samples, sample_ct, sample_valid_ct, perm_vec);
8831 case_ct = popcount_longs(perm_vec, sample_valid_ctaw);
8832 if ((!case_ct) || (case_ct == sample_valid_ct)) {
8833 return 0;
8834 }
8835 for (sample_idx = 0; sample_idx < sample_valid_ct; sample_idx++) {
8836 *fptr++ = 1;
8837 }
8838 for (; sample_idx < sample_valid_cta4; sample_idx++) {
8839 *fptr++ = 0;
8840 }
8841 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8842 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8843 *fptr++ = (float)cur_dosages[sample_uidx];
8844 }
8845 for (; sample_idx < sample_valid_cta4; sample_idx++) {
8846 *fptr++ = 0;
8847 }
8848 for (covar_idx = 0; covar_idx < covar_ct; covar_idx++) {
8849 for (sample_uidx = 0, sample_idx = 0; sample_idx < sample_valid_ct; sample_uidx++, sample_idx++) {
8850 next_set_ul_unsafe_ck(cur_samples, &sample_uidx);
8851 *fptr++ = covar_f[sample_uidx * covar_ct];
8852 }
8853 for (; sample_idx < sample_valid_cta4; sample_idx++) {
8854 *fptr++ = 0;
8855 }
8856 covar_f++;
8857 }
8858 fill_float_zero(param_cta4, coef);
8859 if (glm_logistic(1, param_ct, sample_valid_ct, 0, 1, nullptr, covars_cov_major, perm_vec, coef, pp, sample_1d_buf, pheno_buf, param_1d_buf, param_1d_buf2, param_2d_buf, param_2d_buf2, regression_results, 0, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, perm_fails) || perm_fails[0]) {
8860 return 0;
8861 }
8862 dxx = (double)coef[1];
8863 dyy = sqrt((double)regression_results[0]);
8864 *beta_ptr = dxx;
8865 *se_ptr = dyy;
8866 dxx /= dyy;
8867 *pval_ptr = chiprob_p(dxx * dxx, 1);
8868 return 1;
8869 }