Debian Codegraph @

plink2_glm_linear.cc

raw
1 // This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This program is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option)
7 // any later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 // more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 #include "include/plink2_stats.h"
18 #include "plink2_compress_stream.h"
19 #include "plink2_glm_linear.h"
20
21 #ifdef __cplusplus
22 namespace plink2 {
23 #endif
24
25 // xtx_state 0: either interactions or local covariates present, no xtx_image
26 // xtx_state 1: only additive effect
27 // xtx_state 2: additive and domdev effects
28 // Note that the immediate return value only corresponds to out-of-memory.
29 // Other errors are indicated by glm_err_ptr on a *false* return
30 // value, due to how the caller is expected to handle them.
31 BoolErr GlmAllocFillAndTestCovarsQt(const uintptr_t* sample_include, const uintptr_t* covar_include, const PhenoCol* covar_cols, const char* covar_names, uintptr_t sample_ct, uintptr_t covar_ct, uint32_t local_covar_ct, uint32_t covar_max_nonnull_cat_ct, uintptr_t extra_cat_ct, uintptr_t max_covar_name_blen, double max_corr, double vif_thresh, uintptr_t xtx_state, RegressionNmPrecomp** nm_precomp_ptr, double** covars_cmaj_d_ptr, const char*** cur_covar_names_ptr, GlmErr* glm_err_ptr) {
32 const uintptr_t new_covar_ct = covar_ct + extra_cat_ct;
33 const uintptr_t new_nonlocal_covar_ct = new_covar_ct - local_covar_ct;
34 if (unlikely(bigstack_alloc_kcp(new_covar_ct, cur_covar_names_ptr) ||
35 bigstack_alloc_d(new_nonlocal_covar_ct * sample_ct, covars_cmaj_d_ptr))) {
36 return 1;
37 }
38 double* corr_buf = nullptr;
39 unsigned char* bigstack_mark = g_bigstack_base;
40 *nm_precomp_ptr = nullptr;
41 if (xtx_state) {
42 assert(!local_covar_ct);
43 if (unlikely(BIGSTACK_ALLOC_X(RegressionNmPrecomp, 1, nm_precomp_ptr))) {
44 return 1;
45 }
46 // x^2 + (2*xtx_state + 2)x + (5*xtx_state - 1)
47 // 2x^2 + (2*xtx_state + 4)x + (5*xtx_state)
48 // 3x^2 + (2*xtx_state + 4)x + (5*xtx_state)
49 // 4x^2 + (4*xtx_state + 4)x + (8*xtx_state - 2)
50 // 4x^2 + (4*xtx_state + 5)x + (8*xtx_state - 2)
51 //
52 // xt_y_image: (1 + xtx_state + x) elements per phenotype in subbatch;
53 // now allocated later
54 if (unlikely(bigstack_alloc_d(8 * xtx_state - 2 +
55 new_covar_ct * (5 + 4 * xtx_state + 4 * new_covar_ct),
56 &((*nm_precomp_ptr)->xtx_image)) ||
57 bigstack_alloc_d(new_covar_ct * (new_covar_ct + 1), &corr_buf))) {
58 return 1;
59 }
60 (*nm_precomp_ptr)->covarx_dotprod_inv = &((*nm_precomp_ptr)->xtx_image[(new_covar_ct + xtx_state + 1) * (new_covar_ct + xtx_state + 1)]);
61 (*nm_precomp_ptr)->corr_inv = &((*nm_precomp_ptr)->covarx_dotprod_inv[(new_covar_ct + 1) * (new_covar_ct + 1)]);
62 (*nm_precomp_ptr)->corr_image = &((*nm_precomp_ptr)->corr_inv[new_covar_ct * new_covar_ct]);
63 (*nm_precomp_ptr)->corr_inv_sqrts = &((*nm_precomp_ptr)->corr_image[(new_covar_ct + xtx_state) * (new_covar_ct + xtx_state)]);
64 (*nm_precomp_ptr)->xt_y_image = nullptr; // defensive
65 bigstack_mark = R_CAST(unsigned char*, corr_buf);
66 }
67 double* covar_dotprod;
68 double* inverse_corr_buf;
69 if (unlikely(bigstack_alloc_d(new_nonlocal_covar_ct * new_nonlocal_covar_ct, &covar_dotprod) ||
70 bigstack_alloc_d(new_nonlocal_covar_ct * new_nonlocal_covar_ct, &inverse_corr_buf))) {
71 return 1;
72 }
73 PglErr reterr = GlmFillAndTestCovars(sample_include, covar_include, covar_cols, covar_names, sample_ct, covar_ct, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct, max_covar_name_blen, max_corr, vif_thresh, covar_dotprod, corr_buf, inverse_corr_buf, *covars_cmaj_d_ptr, *cur_covar_names_ptr, glm_err_ptr);
74 if (unlikely(reterr)) {
75 return (reterr == kPglRetNomem);
76 }
77 if (xtx_state) {
78 if (InitNmPrecomp(*covars_cmaj_d_ptr, covar_dotprod, corr_buf, inverse_corr_buf, sample_ct, 1, new_covar_ct, xtx_state, *nm_precomp_ptr)) {
79 *glm_err_ptr = SetGlmErr0(kGlmErrcodeVifInfinite);
80 return 0; // not out-of-memory error
81 }
82 }
83 BigstackReset(bigstack_mark);
84 return 0;
85 }
86
87 void FillPhenoAndXtY(const uintptr_t* sample_include, const double* __restrict pheno_qt, const double* __restrict covars_cmaj_d, uintptr_t sample_ct, uintptr_t domdev_present_p1, uintptr_t covar_ct, double* xt_y_image, double* __restrict pheno_d) {
88 double* pheno_d_iter = pheno_d;
89 uintptr_t sample_uidx_base = 0;
90 uintptr_t cur_bits = sample_include[0];
91 double pheno_sum = 0.0;
92 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
93 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits);
94 const double cur_pheno = pheno_qt[sample_uidx];
95 *pheno_d_iter++ = cur_pheno;
96 pheno_sum += cur_pheno;
97 }
98 if (!xt_y_image) {
99 return;
100 }
101 xt_y_image[0] = pheno_sum;
102 ZeroDArr(domdev_present_p1, &(xt_y_image[1]));
103 ColMajorVectorMatrixMultiplyStrided(pheno_d, covars_cmaj_d, sample_ct, sample_ct, covar_ct, &(xt_y_image[1 + domdev_present_p1]));
104 }
105
106 uintptr_t GetResidualizedPhenoAndXtYWorkspaceSize(uintptr_t sample_ct, uintptr_t covar_ct) {
107 const uintptr_t pred_ct = covar_ct + 1;
108 uintptr_t workspace_size = RoundUpPow2(pred_ct * kMatrixInvertBuf1CheckedAlloc, kCacheline);
109 workspace_size += RoundUpPow2(sample_ct * sizeof(double), kCacheline);
110 workspace_size += RoundUpPow2(sample_ct * pred_ct * sizeof(double), kCacheline);
111 workspace_size += RoundUpPow2(pred_ct * pred_ct * sizeof(double), kCacheline);
112 workspace_size += 2 * RoundUpPow2(pred_ct * sizeof(double), kCacheline);
113 workspace_size += RoundUpPow2(pred_ct * MAXV(pred_ct, 7) * sizeof(double), kCacheline);
114 return workspace_size;
115 }
116
117 // xt_y_image may be a nm_precomp component
118 BoolErr FillResidualizedPhenoAndXtY(const uintptr_t* sample_include, const double* __restrict pheno_qt, const double* __restrict covars_cmaj_d, uintptr_t sample_ct, uintptr_t domdev_present_p1, uintptr_t covar_ct, double* xt_y_image, double* __restrict pheno_d) {
119 unsigned char* bigstack_mark = g_bigstack_base;
120 const uintptr_t pred_ct = covar_ct + 1;
121 double* orig_pheno_d;
122 double* predictors_pmaj;
123 double* xtx_inv;
124 double* fitted_coefs;
125 double* xt_y_tmp;
126 double* dbl_2d_buf;
127 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, bigstack_alloc(pred_ct * kMatrixInvertBuf1CheckedAlloc));
128 if (unlikely((!inv_1d_buf) ||
129 bigstack_alloc_d(sample_ct, &orig_pheno_d) ||
130 bigstack_alloc_d(sample_ct * pred_ct, &predictors_pmaj) ||
131 bigstack_alloc_d(pred_ct * pred_ct, &xtx_inv) ||
132 bigstack_alloc_d(pred_ct, &fitted_coefs) ||
133 bigstack_alloc_d(pred_ct, &xt_y_tmp) ||
134 bigstack_alloc_d(pred_ct * MAXV(pred_ct, 7), &dbl_2d_buf))) {
135 return 1;
136 }
137 assert(S_CAST(uintptr_t, g_bigstack_base - bigstack_mark) == GetResidualizedPhenoAndXtYWorkspaceSize(sample_ct, covar_ct));
138 FillPhenoAndXtY(sample_include, pheno_qt, covars_cmaj_d, sample_ct, domdev_present_p1, covar_ct, xt_y_tmp, orig_pheno_d);
139 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
140 predictors_pmaj[uii] = 1.0;
141 }
142 memcpy(&(predictors_pmaj[sample_ct]), covars_cmaj_d, sample_ct * covar_ct * sizeof(double));
143 // We duplicate some work here, but not a big deal.
144 MultiplySelfTranspose(predictors_pmaj, pred_ct, sample_ct, xtx_inv);
145 LinearRegressionInv(orig_pheno_d, predictors_pmaj, pred_ct, sample_ct, 1, xtx_inv, fitted_coefs, xt_y_tmp, inv_1d_buf, dbl_2d_buf);
146 ColMajorMatrixVectorMultiplyStrided(predictors_pmaj, fitted_coefs, sample_ct, sample_ct, pred_ct, pheno_d);
147 double pheno_sum = 0.0;
148 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
149 const double new_pheno_val = orig_pheno_d[uii] - pheno_d[uii];
150 pheno_d[uii] = new_pheno_val;
151 pheno_sum += new_pheno_val;
152 }
153 xt_y_image[0] = pheno_sum;
154 ZeroDArr(domdev_present_p1, &(xt_y_image[1]));
155 BigstackReset(bigstack_mark);
156 return 0;
157 }
158
159 void ClearNmPrecompCovars(uintptr_t sample_ct, uintptr_t domdev_present_p1, RegressionNmPrecomp* nm_precomp) {
160 const uintptr_t stride = 1 + domdev_present_p1;
161 ZeroDArr(stride * stride - 1, &(nm_precomp->xtx_image[1]));
162 nm_precomp->covarx_dotprod_inv[0] = 1.0 / u31tod(sample_ct);
163 ZeroDArr(domdev_present_p1 * domdev_present_p1, nm_precomp->corr_image);
164 }
165
166 BoolErr GlmAllocFillAndTestPhenoCovarsQt(const uintptr_t* sample_include, const double* pheno_qt, const uintptr_t* covar_include, const PhenoCol* covar_cols, const char* covar_names, uintptr_t sample_ct, uint32_t is_qt_residualize, uintptr_t covar_ct, uint32_t local_covar_ct, uint32_t covar_max_nonnull_cat_ct, uintptr_t extra_cat_ct, uintptr_t max_covar_name_blen, double max_corr, double vif_thresh, uintptr_t xtx_state, double** pheno_d_ptr, RegressionNmPrecomp** nm_precomp_ptr, double** covars_cmaj_d_ptr, const char*** cur_covar_names_ptr, GlmErr* glm_err_ptr) {
167 if (unlikely(GlmAllocFillAndTestCovarsQt(sample_include, covar_include, covar_cols, covar_names, sample_ct, covar_ct, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct, max_covar_name_blen, max_corr, vif_thresh, xtx_state, nm_precomp_ptr, covars_cmaj_d_ptr, cur_covar_names_ptr, glm_err_ptr))) {
168 return 1;
169 }
170 if (*glm_err_ptr) {
171 // this is a bit messy
172 return 0;
173 }
174 if (unlikely(bigstack_alloc_d(sample_ct, pheno_d_ptr))) {
175 return 1;
176 }
177 const uintptr_t new_covar_ct = covar_ct + extra_cat_ct;
178 double* xt_y_image = nullptr;
179 if (xtx_state) {
180 if (unlikely(bigstack_alloc_d(1 + xtx_state + new_covar_ct, &xt_y_image))) {
181 return 1;
182 }
183 (*nm_precomp_ptr)->xt_y_image = xt_y_image;
184 }
185 if (!is_qt_residualize) {
186 FillPhenoAndXtY(sample_include, pheno_qt, *covars_cmaj_d_ptr, sample_ct, xtx_state, new_covar_ct, xt_y_image, *pheno_d_ptr);
187 return 0;
188 }
189 if (unlikely(FillResidualizedPhenoAndXtY(sample_include, pheno_qt, *covars_cmaj_d_ptr, sample_ct, xtx_state, new_covar_ct, (*nm_precomp_ptr)->xt_y_image, *pheno_d_ptr))) {
190 return 1;
191 }
192 ClearNmPrecompCovars(sample_ct, xtx_state, *nm_precomp_ptr);
193 return 0;
194 }
195
196 uintptr_t GetLinearWorkspaceSize(uint32_t sample_ct, uint32_t biallelic_predictor_ct, uint32_t max_extra_allele_ct, uint32_t constraint_ct, uint32_t xmain_ct, uint32_t max_returned_difflist_len) {
197 // sample_ct * max_predictor_ct < 2^31, and max_predictor_ct < sqrt(2^31), so
198 // no overflows
199
200 // sample_nm, tmp_nm = sample_ctl words
201 uintptr_t workspace_size = 2 * RoundUpPow2(BitCtToWordCt(sample_ct) * sizeof(intptr_t), kCacheline);
202
203 // nm_pheno_buf = sample_ct doubles
204 workspace_size += RoundUpPow2(sample_ct * sizeof(double), kCacheline);
205
206 const uint32_t max_predictor_ct = biallelic_predictor_ct + max_extra_allele_ct;
207 // predictors_pmaj = (max_predictor_ct + main_mutated + main_omitted) * sample_ct
208 // doubles
209 workspace_size += RoundUpPow2((max_predictor_ct + xmain_ct) * sample_ct * sizeof(double), kCacheline);
210
211 // xtx_inv = max_predictor_ct * max_predictor_ct doubles
212 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ct * sizeof(double), kCacheline);
213
214 // dbl_2d_buf = max_predictor_ct * max(max_predictor_ct, 7) doubles
215 workspace_size += RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
216
217 // inverse_corr_buf = (max_predictor_ct - 1) * max(max_predictor_ct - 1, 4)
218 // doubles
219 workspace_size += RoundUpPow2((max_predictor_ct - 1) * MAXV((max_predictor_ct - 1), 4) * sizeof(double), kCacheline);
220
221 // semicomputed_biallelic_corr_matrix = (max_predictor_ct - 1)^2 doubles
222 workspace_size += RoundUpPow2((biallelic_predictor_ct - 1) * (biallelic_predictor_ct - 1) * sizeof(double), kCacheline);
223
224 // semicomputed_biallelic_inv_corr_sqrts = biallelic_predictor_ct doubles
225 workspace_size += RoundUpPow2(biallelic_predictor_ct * sizeof(double), kCacheline);
226
227 // fitted_coefs, xt_y = max_predictor_ct doubles
228 workspace_size += 2 * RoundUpPow2(max_predictor_ct * sizeof(double), kCacheline);
229
230 // inv_1d_buf
231 workspace_size += RoundUpPow2(MAXV(max_predictor_ct, constraint_ct) * kMatrixInvertBuf1CheckedAlloc, kCacheline);
232
233 // machr2_dosage_sums, machr2_dosage_ssqs
234 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(uint64_t) * 2, kCacheline);
235
236 // raregeno
237 workspace_size += DivUp(max_returned_difflist_len, kNypsPerCacheline) * kCacheline;
238
239 // difflist_sample_ids
240 workspace_size += DivUp(max_returned_difflist_len, kInt32PerCacheline) * kCacheline;
241
242 if (constraint_ct) {
243 // tmphxs_buf, h_transpose_buf = constraint_ct * max_predictor_ct doubles
244 workspace_size += 2 * RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(double), kCacheline);
245
246 // inner_buf = constraint_ct * constraint_ct
247 workspace_size += RoundUpPow2(constraint_ct * constraint_ct * sizeof(double), kCacheline);
248
249 // cur_constraints_con_major = constraint_ct * max_predictor_ct doubles
250 workspace_size += RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(double), kCacheline);
251 }
252 return workspace_size;
253 }
254
255 // possible todo: delete this, and GlmLinear(), if GlmLinearBatchThread is good
256 // enough at the same job.
257 THREAD_FUNC_DECL GlmLinearThread(void* raw_arg) {
258 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
259 const uintptr_t tidx = arg->tidx;
260 GlmLinearCtx* ctx = S_CAST(GlmLinearCtx*, arg->sharedp->context);
261 GlmCtx* common = ctx->common;
262
263 PgenReader* pgrp = common->pgr_ptrs[tidx];
264 PgenVariant pgv;
265 pgv.genovec = common->genovecs[tidx];
266 pgv.dosage_present = nullptr;
267 pgv.dosage_main = nullptr;
268 // bugfix (22 Jan 2025): this could be uninitialized when
269 // PgrGetDifflistOrGenovec was used
270 pgv.dosage_ct = 0;
271 if (common->dosage_presents) {
272 pgv.dosage_present = common->dosage_presents[tidx];
273 pgv.dosage_main = common->dosage_mains[tidx];
274 }
275 unsigned char* workspace_buf = common->workspace_bufs[tidx];
276 const uintptr_t* variant_include = common->variant_include;
277 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
278 const AlleleCode* omitted_alleles = common->omitted_alleles;
279 const uintptr_t* sex_male_collapsed = common->sex_male_collapsed;
280 const ChrInfo* cip = common->cip;
281 const uint32_t* subset_chr_fo_vidx_start = common->subset_chr_fo_vidx_start;
282 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
283 const GlmFlags glm_flags = common->glm_flags;
284 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
285 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
286 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
287 const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
288 const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
289 const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
290 const uint32_t joint_genotypic = (glm_flags / kfGlmGenotypic) & 1;
291 const uint32_t joint_hethom = (glm_flags / kfGlmHethom) & 1;
292 const uint32_t domdev_present = joint_genotypic || joint_hethom;
293 const uint32_t domdev_present_p1 = domdev_present + 1;
294 const uint32_t reported_pred_uidx_start = 1 - include_intercept;
295 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
296 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
297 const uint32_t is_xchr_model_1 = common->is_xchr_model_1;
298 const double max_corr = common->max_corr;
299 const double vif_thresh = common->vif_thresh;
300 const uintptr_t max_reported_test_ct = common->max_reported_test_ct;
301 const uintptr_t local_covar_ct = common->local_covar_ct;
302 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
303 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!model_dominant) && (!model_recessive) && (!model_hetonly) && (!common->tests_flag) && (!add_interactions);
304 uintptr_t max_sample_ct = MAXV(common->sample_ct, common->sample_ct_x);
305 if (max_sample_ct < common->sample_ct_y) {
306 max_sample_ct = common->sample_ct_y;
307 }
308 pgv.patch_01_set = nullptr;
309 pgv.patch_01_vals = nullptr;
310 pgv.patch_10_set = nullptr;
311 pgv.patch_10_vals = nullptr;
312 if (common->thread_mhc) {
313 const uint32_t max_sample_ctl = BitCtToWordCt(max_sample_ct);
314 pgv.patch_01_set = common->thread_mhc[tidx];
315 pgv.patch_01_vals = R_CAST(AlleleCode*, &(pgv.patch_01_set[max_sample_ctl]));
316 AlleleCode* patch_01_vals_end = &(pgv.patch_01_vals[max_sample_ct]);
317 AlignACToVec(&patch_01_vals_end);
318 pgv.patch_10_set = R_CAST(uintptr_t*, patch_01_vals_end);
319 pgv.patch_10_vals = R_CAST(AlleleCode*, &(pgv.patch_10_set[max_sample_ctl]));
320 }
321 pgv.patch_01_ct = 0;
322 pgv.patch_10_ct = 0;
323 pgv.multidosage_sample_ct = 0;
324 uint32_t variant_idx_offset = 0;
325 uint32_t allele_ct = 2;
326 uint32_t omitted_allele_idx = 0;
327 uint32_t extra_regression_ct = 0;
328 double main_dosage_sum = 0.0;
329 double main_dosage_ssq = 0.0;
330 double covarless_inverse_buf[9];
331 for (uint32_t uii = 1; uii != 9; ++uii) {
332 covarless_inverse_buf[uii] = 0.0;
333 }
334 uint32_t max_sparse = 0;
335 uint32_t difflist_len = 0;
336 uint32_t parity = 0;
337 uint64_t new_err_info = 0;
338 do {
339 const uintptr_t cur_block_variant_ct = common->cur_block_variant_ct;
340 uint32_t variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct;
341 const uint32_t variant_bidx_end = ((tidx + 1) * cur_block_variant_ct) / calc_thread_ct;
342 uintptr_t variant_uidx_base;
343 uintptr_t variant_include_bits;
344 BitIter1Start(variant_include, common->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
345
346 uintptr_t allele_bidx = variant_bidx;
347 if (max_extra_allele_ct) {
348 allele_bidx = variant_bidx + CountExtraAlleles(variant_include, allele_idx_offsets, common->read_variant_uidx_starts[0], common->read_variant_uidx_starts[tidx], 0);
349 }
350 double* beta_se_iter = common->block_beta_se;
351 if (beta_se_multiallelic_fused) {
352 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * variant_bidx]);
353 } else {
354 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * allele_bidx]);
355 }
356
357 LinearAuxResult* block_aux_iter = &(ctx->block_aux[allele_bidx]);
358 const double* local_covars_iter = nullptr;
359 if (local_covar_ct) {
360 // &(nullptr[0]) is okay in C++, but undefined in C
361 local_covars_iter = &(ctx->local_covars_vcmaj_d[parity][variant_bidx * max_sample_ct * local_covar_ct]);
362 }
363 while (variant_bidx < variant_bidx_end) {
364 const uint32_t variant_idx = variant_bidx + variant_idx_offset;
365 const uint32_t chr_fo_idx = LastLeqU32(subset_chr_fo_vidx_start, 0, cip->chr_ct, variant_idx);
366 // const uint32_t chr_fo_idx = LowerBoundNonemptyU32(&(subset_chr_fo_vidx_start[1]), cip->chr_ct, variant_idx + 1);
367 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
368 uint32_t cur_variant_bidx_end = subset_chr_fo_vidx_start[chr_fo_idx + 1] - variant_idx_offset;
369 if (cur_variant_bidx_end > variant_bidx_end) {
370 cur_variant_bidx_end = variant_bidx_end;
371 }
372 const uint32_t is_haploid = IsSet(cip->haploid_mask, chr_idx);
373 const uint32_t is_regular_x = is_haploid && (chr_idx == x_code);
374 const uint32_t is_y = (chr_idx == y_code);
375 const uint32_t is_nonx_haploid = is_haploid && (!is_regular_x);
376 const uintptr_t* cur_sample_include;
377 const uint32_t* cur_sample_include_cumulative_popcounts;
378 const double* cur_pheno;
379 const RegressionNmPrecomp* nm_precomp;
380 const double* cur_covars_cmaj;
381 const uintptr_t* cur_parameter_subset;
382 const uintptr_t* cur_joint_test_params;
383 uint32_t cur_sample_ct;
384 uint32_t cur_covar_ct;
385 uint32_t cur_constraint_ct;
386 if (is_y && common->sample_include_y) {
387 cur_sample_include = common->sample_include_y;
388 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
389 cur_pheno = ctx->pheno_y_d;
390 nm_precomp = common->nm_precomp_y;
391 cur_covars_cmaj = ctx->covars_cmaj_y_d;
392 cur_parameter_subset = common->parameter_subset_y;
393 cur_joint_test_params = common->joint_test_params_y;
394 cur_sample_ct = common->sample_ct_y;
395 cur_covar_ct = common->covar_ct_y;
396 cur_constraint_ct = common->constraint_ct_y;
397 } else if (is_regular_x && common->sample_include_x) {
398 cur_sample_include = common->sample_include_x;
399 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
400 cur_pheno = ctx->pheno_x_d;
401 nm_precomp = common->nm_precomp_x;
402 cur_covars_cmaj = ctx->covars_cmaj_x_d;
403 cur_parameter_subset = common->parameter_subset_x;
404 cur_joint_test_params = common->joint_test_params_x;
405 cur_sample_ct = common->sample_ct_x;
406 cur_covar_ct = common->covar_ct_x;
407 cur_constraint_ct = common->constraint_ct_x;
408 } else {
409 cur_sample_include = common->sample_include;
410 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
411 cur_pheno = ctx->pheno_d;
412 nm_precomp = common->nm_precomp;
413 cur_covars_cmaj = ctx->covars_cmaj_d;
414 cur_parameter_subset = common->parameter_subset;
415 cur_joint_test_params = common->joint_test_params;
416 cur_sample_ct = common->sample_ct;
417 cur_covar_ct = common->covar_ct;
418 cur_constraint_ct = common->constraint_ct;
419 }
420 const uint32_t sample_ctl = BitCtToWordCt(cur_sample_ct);
421 const uint32_t sample_ctl2 = NypCtToWordCt(cur_sample_ct);
422 const uint32_t cur_biallelic_predictor_ct_base = 2 + domdev_present + cur_covar_ct * (1 + add_interactions * domdev_present_p1);
423 uint32_t cur_biallelic_predictor_ct = cur_biallelic_predictor_ct_base;
424 uint32_t literal_covar_ct = cur_covar_ct;
425 if (cur_parameter_subset) {
426 cur_biallelic_predictor_ct = PopcountWords(cur_parameter_subset, BitCtToWordCt(cur_biallelic_predictor_ct_base));
427 literal_covar_ct = PopcountBitRange(cur_parameter_subset, 2 + domdev_present, 2 + domdev_present + cur_covar_ct);
428 }
429 const uint32_t max_predictor_ct = cur_biallelic_predictor_ct + max_extra_allele_ct;
430 uint32_t reported_pred_uidx_biallelic_end;
431 if (hide_covar) {
432 if (!cur_parameter_subset) {
433 reported_pred_uidx_biallelic_end = 2 + domdev_present;
434 } else {
435 reported_pred_uidx_biallelic_end = IsSet(cur_parameter_subset, 1) + domdev_present_p1;
436 }
437 } else {
438 reported_pred_uidx_biallelic_end = cur_biallelic_predictor_ct;
439 }
440 // nm_predictors_pmaj_buf may require up to two extra columns omitted
441 // from the main regression.
442 // 1. In the multiallelic dominant/recessive/hetonly/hethom cases, the
443 // original genotype column does not appear in the regression, and
444 // we'd rather not reconstruct it from genovec, etc. when we need to
445 // swap it out for another allele, so we keep the original genotype in
446 // an extra column.
447 // To reduce code bloat, we now handle the biallelic cases in the same
448 // way; this is one of the more peripheral code paths so adding more
449 // complexity to speed it up is less justifiable.
450 // 2. If --parameters excludes the main (possibly
451 // dominant/recessive/hetonly) genotype column but does care about an
452 // interaction, we want a copy of what the main genotype column's
453 // contents would have been to refer to.
454 const uint32_t main_omitted = cur_parameter_subset && (!IsSet(cur_parameter_subset, 1));
455 const uint32_t main_mutated = model_dominant || model_recessive || model_hetonly || joint_hethom;
456 unsigned char* workspace_iter = workspace_buf;
457 uintptr_t* sample_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
458 uintptr_t* tmp_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
459 double* nm_pheno_buf = S_CAST(double*, arena_alloc_raw_rd(cur_sample_ct * sizeof(double), &workspace_iter));
460 double* nm_predictors_pmaj_buf = S_CAST(double*, arena_alloc_raw_rd((max_predictor_ct + main_mutated + main_omitted) * cur_sample_ct * sizeof(double), &workspace_iter));
461 double* xtx_inv = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ct * sizeof(double), &workspace_iter));
462 double* fitted_coefs = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * sizeof(double), &workspace_iter));
463 double* xt_y = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * sizeof(double), &workspace_iter));
464 double* semicomputed_biallelic_corr_matrix = S_CAST(double*, arena_alloc_raw_rd((cur_biallelic_predictor_ct - 1) * (cur_biallelic_predictor_ct - 1) * sizeof(double), &workspace_iter));
465 double* semicomputed_biallelic_inv_corr_sqrts = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
466 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, arena_alloc_raw_rd(MAXV(max_predictor_ct, cur_constraint_ct) * kMatrixInvertBuf1CheckedAlloc, &workspace_iter));
467 double* dbl_2d_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), &workspace_iter));
468 uint64_t* machr2_dosage_sums = S_CAST(uint64_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(uint64_t) * 2, &workspace_iter));
469 uint64_t* machr2_dosage_ssqs = &(machr2_dosage_sums[max_extra_allele_ct + 2]);
470
471 // could technically have this overlap fitted_coefs/xt_y, but that sets
472 // the stage for future bugs
473 double* inverse_corr_buf = S_CAST(double*, arena_alloc_raw_rd((max_predictor_ct - 1) * MAXV((max_predictor_ct - 1), 4) * sizeof(double), &workspace_iter));
474
475 const uint32_t sparse_optimization_eligible = (!is_regular_x) && nm_precomp;
476 // Only try to load difflist in no-covariate no-dosage biallelic case,
477 // where sparse_optimization is guaranteed to be true.
478 const uint32_t difflist_eligible = sparse_optimization_eligible && (!pgv.dosage_present) && (!cur_covar_ct);
479 uintptr_t* raregeno = nullptr;
480 uint32_t* difflist_sample_ids = nullptr;
481 if (difflist_eligible) {
482 max_sparse = cur_sample_ct / kPglMaxDifflistLenDivisor;
483 const uint32_t max_returned_difflist_len = ctx->max_returned_difflist_len;
484 raregeno = S_CAST(uintptr_t*, arena_alloc_raw(DivUp(max_returned_difflist_len, kNypsPerCacheline) * kCacheline, &workspace_iter));
485 difflist_sample_ids = S_CAST(uint32_t*, arena_alloc_raw(DivUp(max_returned_difflist_len, kInt32PerCacheline) * kCacheline, &workspace_iter));
486 }
487
488 // joint test only
489 double* tmphxs_buf = nullptr;
490 double* h_transpose_buf = nullptr;
491 double* inner_buf = nullptr;
492 double* cur_constraints_con_major = nullptr;
493 if (cur_constraint_ct) {
494 tmphxs_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
495 h_transpose_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
496 inner_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * cur_constraint_ct * sizeof(double), &workspace_iter));
497 cur_constraints_con_major = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
498 ZeroDArr(cur_constraint_ct * max_predictor_ct, cur_constraints_con_major);
499 const uint32_t first_joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
500 cur_constraints_con_major[first_joint_test_idx] = 1.0;
501 // Rest of this matrix must be updated later, since cur_predictor_ct
502 // changes at multiallelic variants.
503 }
504 // <= instead of == since WorkspaceSize doesn't exclude difflist space on
505 // chrX
506 assert(S_CAST(uintptr_t, workspace_iter - workspace_buf) <= GetLinearWorkspaceSize(cur_sample_ct, cur_biallelic_predictor_ct, max_extra_allele_ct, cur_constraint_ct, main_mutated + main_omitted, ctx->max_returned_difflist_len));
507 const double pheno_ssq_base = DotprodD(cur_pheno, cur_pheno, cur_sample_ct);
508 const double cur_sample_ct_recip = 1.0 / u31tod(cur_sample_ct);
509 const double cur_sample_ct_m1_recip = 1.0 / u31tod(cur_sample_ct - 1);
510 double geno_d_lookup[2];
511 if (sparse_optimization_eligible) {
512 if (model_hetonly) {
513 geno_d_lookup[0] = 1.0;
514 geno_d_lookup[1] = 0.0;
515 } else {
516 geno_d_lookup[1] = 1.0;
517 if (is_nonx_haploid) {
518 geno_d_lookup[0] = 0.5;
519 } else if (model_recessive || joint_hethom) {
520 geno_d_lookup[0] = 0.0;
521 } else {
522 geno_d_lookup[0] = 1.0;
523 if (!model_dominant) {
524 geno_d_lookup[1] = 2.0;
525 }
526 }
527 }
528 }
529 const double* xtx_image = nullptr;
530 const double* covarx_dotprod_inv = nullptr;
531 const double* corr_inv = nullptr;
532 const double* xt_y_image = nullptr;
533 if (nm_precomp) {
534 xtx_image = nm_precomp->xtx_image;
535 covarx_dotprod_inv = nm_precomp->covarx_dotprod_inv;
536 corr_inv = nm_precomp->corr_inv;
537 const uintptr_t nongeno_pred_ct = cur_biallelic_predictor_ct - domdev_present - 2;
538 const uintptr_t nonintercept_biallelic_pred_ct = cur_biallelic_predictor_ct - 1;
539 memcpy(semicomputed_biallelic_corr_matrix, nm_precomp->corr_image, nonintercept_biallelic_pred_ct * nonintercept_biallelic_pred_ct * sizeof(double));
540 memcpy(&(semicomputed_biallelic_inv_corr_sqrts[domdev_present_p1]), nm_precomp->corr_inv_sqrts, nongeno_pred_ct * sizeof(double));
541 xt_y_image = nm_precomp->xt_y_image;
542 }
543 PgrSampleSubsetIndex pssi;
544 PgrSetSampleSubsetIndex(cur_sample_include_cumulative_popcounts, pgrp, &pssi);
545 // when this is set, the last fully-processed variant had no missing
546 // genotypes, and if the current variant also has no missing genotypes we
547 // may be able to skip reinitialization of most of
548 // nm_predictors_pmaj_buf.
549 uint32_t prev_nm = 0;
550 uint32_t prev_nm_sample_ct = 0;
551
552 STD_ARRAY_DECL(uint32_t, 4, genocounts);
553 for (; variant_bidx != cur_variant_bidx_end; ++variant_bidx) {
554 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
555 // DPrintf("\nWorker thread %" PRIuPTR " starting unfiltered variant %u", tidx, variant_uidx);
556 if (allele_idx_offsets) {
557 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
558 if (!beta_se_multiallelic_fused) {
559 extra_regression_ct = allele_ct - 2;
560 }
561 }
562 const uint32_t allele_ct_m2 = allele_ct - 2;
563 const uint32_t expected_predictor_ct = cur_biallelic_predictor_ct + allele_ct_m2;
564 uint32_t difflist_common_geno = UINT32_MAX;
565 PglErr reterr;
566 if (!allele_ct_m2) {
567 if (difflist_eligible) {
568 reterr = PgrGetDifflistOrGenovec(cur_sample_include, pssi, cur_sample_ct, max_sparse, variant_uidx, pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
569 } else {
570 reterr = PgrGetD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
571 }
572 } else {
573 reterr = PgrGetMD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, &pgv);
574 // todo: proper multiallelic dosage support
575 }
576 if (unlikely(reterr)) {
577 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
578 goto GlmLinearThread_err;
579 }
580 if (omitted_alleles) {
581 omitted_allele_idx = omitted_alleles[variant_uidx];
582 }
583 uint32_t missing_ct;
584 if (difflist_common_geno == 2 * omitted_allele_idx) {
585 ZeroTrailingNyps(difflist_len, raregeno);
586 GenoarrCountFreqsUnsafe(raregeno, difflist_len, genocounts);
587 genocounts[difflist_common_geno] = cur_sample_ct - difflist_len;
588 missing_ct = genocounts[3];
589 // no need to set sample_nm
590 } else {
591 // bugfix (20 Jan 2025): difflist_common_geno == 3 was not handled
592 // properly
593 if (difflist_common_geno != UINT32_MAX) {
594 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, cur_sample_ct, difflist_len, pgv.genovec);
595 difflist_common_geno = UINT32_MAX;
596 }
597 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
598 GenoarrCountFreqsUnsafe(pgv.genovec, cur_sample_ct, genocounts);
599 missing_ct = genocounts[3];
600 if (!missing_ct) {
601 SetAllBits(cur_sample_ct, sample_nm);
602 } else {
603 GenoarrToNonmissing(pgv.genovec, cur_sample_ct, sample_nm);
604 if (pgv.dosage_ct) {
605 BitvecOr(pgv.dosage_present, sample_ctl, sample_nm);
606 missing_ct = cur_sample_ct - PopcountWords(sample_nm, sample_ctl);
607 }
608 }
609 }
610 uintptr_t const_alleles[DivUp(kPglMaxAlleleCt, kBitsPerWord)];
611 const uint32_t allele_ctl = DivUp(allele_ct, kBitsPerWord);
612 ZeroWArr(allele_ctl, const_alleles);
613 const uint32_t nm_sample_ct = cur_sample_ct - missing_ct;
614 const uint32_t nm_sample_ctl = BitCtToWordCt(nm_sample_ct);
615 // first predictor column: intercept
616 if (!prev_nm) {
617 assert((!prev_nm_sample_ct) || (nm_predictors_pmaj_buf[prev_nm_sample_ct - 1] == 1.0));
618 for (uint32_t sample_idx = prev_nm_sample_ct; sample_idx < nm_sample_ct; ++sample_idx) {
619 nm_predictors_pmaj_buf[sample_idx] = 1.0;
620 }
621 }
622 prev_nm_sample_ct = nm_sample_ct;
623 // second predictor column: main genotype
624 double* genotype_vals = &(nm_predictors_pmaj_buf[nm_sample_ct]);
625 if (main_mutated || main_omitted) {
626 genotype_vals = &(nm_predictors_pmaj_buf[expected_predictor_ct * nm_sample_ct]);
627 }
628 double cur_pheno_ssq = pheno_ssq_base;
629 if (missing_ct) {
630 if (difflist_common_geno != UINT32_MAX) {
631 const uint32_t raregeno_word_ct = NypCtToWordCt(difflist_len);
632 for (uint32_t widx = 0; widx != raregeno_word_ct; ++widx) {
633 uintptr_t missing_word = raregeno[widx];
634 missing_word = missing_word & (missing_word >> 1) & kMask5555;
635 if (!missing_word) {
636 continue;
637 }
638 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
639 do {
640 const uint32_t difflist_idx = ctzw(missing_word) / 2;
641 const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx];
642 cur_pheno_ssq -= cur_pheno[sample_idx] * cur_pheno[sample_idx];
643 missing_word &= missing_word - 1;
644 } while (missing_word);
645 }
646 } else {
647 uintptr_t sample_midx_base = 0;
648 uintptr_t sample_nm_inv_bits = ~sample_nm[0];
649 for (uint32_t missing_idx = 0; missing_idx != missing_ct; ++missing_idx) {
650 const uintptr_t sample_midx = BitIter0(sample_nm, &sample_midx_base, &sample_nm_inv_bits);
651 cur_pheno_ssq -= cur_pheno[sample_midx] * cur_pheno[sample_midx];
652 }
653 }
654 }
655 uint32_t sparse_optimization = 0;
656 double* multi_start = nullptr;
657 if (!allele_ct_m2) {
658 // When there are no dosages, and either:
659 // prev_nm is set and missing_ct is zero, or
660 // there are no covariates,
661 // we don't need to call MultiplySelfTranspose() on
662 // nm_predictors_pmaj_buf to get all the predictor x predictor dot
663 // products; instead we patch in the genotype x predictor dot
664 // products that may change, copying the rest from xtx_image.
665 // As a side effect, it is no longer strictly necessary to fill the
666 // genotype row of nm_predictors_pmaj_buf. sparse_optimization
667 // indicates that plink 1.9's QT --assoc sparse dot product algorithm
668 // will be used instead.
669 // probable todos: allow a few dosages to be present, cover chrX
670 // case.
671 if (omitted_allele_idx) {
672 if (difflist_common_geno != UINT32_MAX) {
673 assert(difflist_common_geno == 2);
674 GenovecInvertUnsafe(difflist_len, raregeno);
675 ZeroTrailingNyps(difflist_len, raregeno);
676 difflist_common_geno = 0;
677 } else {
678 GenovecInvertUnsafe(cur_sample_ct, pgv.genovec);
679 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
680 if (pgv.dosage_ct) {
681 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
682 }
683 }
684 const uint32_t uii = genocounts[0];
685 genocounts[0] = genocounts[2];
686 genocounts[2] = uii;
687 }
688 uint64_t dosage_sum = (genocounts[1] + 2 * genocounts[2]) * 0x4000LLU;
689 uint64_t dosage_ssq = (genocounts[1] + 4LLU * genocounts[2]) * 0x10000000LLU;
690 if (!missing_ct) {
691 // originally had genocounts[0] > 0.875 * nm_sample_ct threshold,
692 // but then tried this on high-MAF data and it was still
693 // substantially faster
694 sparse_optimization = sparse_optimization_eligible && (!pgv.dosage_ct) && (prev_nm || (!cur_covar_ct));
695 if (!sparse_optimization) {
696 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, genotype_vals);
697 if (pgv.dosage_ct) {
698 uintptr_t sample_idx_base = 0;
699 uintptr_t dosage_present_bits = pgv.dosage_present[0];
700 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
701 const uintptr_t sample_idx = BitIter1(pgv.dosage_present, &sample_idx_base, &dosage_present_bits);
702 const uintptr_t dosage_val = pgv.dosage_main[dosage_idx];
703 // 32768 -> 2, 16384 -> 1, 0 -> 0
704 genotype_vals[sample_idx] = kRecipDosageMid * swtod(dosage_val);
705 dosage_sum += dosage_val;
706 dosage_ssq += dosage_val * dosage_val;
707 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_idx);
708 if (cur_geno && (cur_geno != 3)) {
709 const uintptr_t prev_val = cur_geno * kDosageMid;
710 dosage_sum -= prev_val;
711 dosage_ssq -= prev_val * prev_val;
712 }
713 }
714 }
715 }
716 } else {
717 if (!pgv.dosage_ct) {
718 sparse_optimization = sparse_optimization_eligible && (!cur_covar_ct);
719 if (!sparse_optimization) {
720 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, genotype_vals);
721 }
722 } else {
723 uintptr_t sample_midx_base = 0;
724 uintptr_t sample_nm_bits = sample_nm[0];
725 uint32_t dosage_idx = 0;
726 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
727 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
728 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_midx);
729 double cur_val;
730 if (IsSet(pgv.dosage_present, sample_midx)) {
731 const uintptr_t dosage_val = pgv.dosage_main[dosage_idx++];
732 cur_val = kRecipDosageMid * swtod(dosage_val);
733 dosage_sum += dosage_val;
734 dosage_ssq += dosage_val * dosage_val;
735 if (cur_geno && (cur_geno != 3)) {
736 const uintptr_t prev_val = cur_geno * kDosageMid;
737 dosage_sum -= prev_val;
738 dosage_ssq -= prev_val * prev_val;
739 }
740 } else {
741 cur_val = kSmallDoubles[cur_geno];
742 }
743 genotype_vals[sample_idx] = cur_val;
744 }
745 }
746 }
747 // Check for constant genotype column.
748 // (Technically, we should recheck later in the chrX no-sex-covariate
749 // --xchr-model 1 corner case.)
750 if (!pgv.dosage_ct) {
751 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
752 const_alleles[0] = 3;
753 }
754 } else if (pgv.dosage_ct == nm_sample_ct) {
755 if (DosageIsConstant(dosage_sum, dosage_ssq, nm_sample_ct)) {
756 const_alleles[0] = 3;
757 }
758 }
759 machr2_dosage_sums[1 - omitted_allele_idx] = dosage_sum;
760 machr2_dosage_ssqs[1 - omitted_allele_idx] = dosage_ssq;
761 machr2_dosage_sums[omitted_allele_idx] = kDosageMax * S_CAST(uint64_t, nm_sample_ct) - dosage_sum;
762 machr2_dosage_ssqs[omitted_allele_idx] = kDosageMax * (kDosageMax * S_CAST(uint64_t, nm_sample_ct) - 2 * dosage_sum) + dosage_ssq;
763 } else {
764 // multiallelic.
765 // If some but not all alleles have constant dosages, we remove just
766 // those alleles from the regressions; trim-alts is not necessary to
767 // see what's going on with the other alleles. To reduce parsing
768 // complexity, the number of output lines is not affected by this;
769 // the ones corresponding to the constant alleles have NA values.
770 // Punt on sparse_optimization for now; may be worth revisiting after
771 // multiallelic dosage implemented.
772 // dosage_ct == 0 temporarily guaranteed if we reach here.
773 assert(!pgv.dosage_ct);
774 multi_start = &(nm_predictors_pmaj_buf[(expected_predictor_ct - allele_ct_m2) * nm_sample_ct]);
775 ZeroU64Arr(allele_ct, machr2_dosage_sums);
776 ZeroU64Arr(allele_ct, machr2_dosage_ssqs);
777 // postpone multiply for now, since no multiallelic dosages
778 machr2_dosage_sums[0] = genocounts[1] + 2 * genocounts[0];
779 machr2_dosage_ssqs[0] = genocounts[1] + 4LLU * genocounts[0];
780 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
781 SetBit(0, const_alleles);
782 }
783 if (omitted_allele_idx) {
784 // Main genotype column starts as REF.
785 if (!missing_ct) {
786 GenoarrLookup16x8bx2(pgv.genovec, kSmallInvDoublePairs, nm_sample_ct, genotype_vals);
787 } else {
788 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallInvDoubles, cur_sample_ct, genotype_vals);
789 }
790 }
791 uint32_t rare_allele_ct = allele_ct_m2;
792 double* alt1_start = nullptr;
793 double* rarealt_start = multi_start;
794 if (omitted_allele_idx != 1) {
795 if (omitted_allele_idx) {
796 alt1_start = multi_start;
797 rarealt_start = &(rarealt_start[nm_sample_ct]);
798 --rare_allele_ct;
799 } else {
800 alt1_start = genotype_vals;
801 }
802 if (!missing_ct) {
803 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, alt1_start);
804 } else {
805 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, alt1_start);
806 }
807 }
808 ZeroDArr(rare_allele_ct * nm_sample_ct, rarealt_start);
809 // Use sums as ones[] and ssqs as twos[] for rarealts; transform to
810 // actual sums/ssqs later.
811 if (pgv.patch_01_ct) {
812 const uintptr_t* patch_set_nm = pgv.patch_01_set;
813 if (missing_ct) {
814 CopyBitarrSubset(pgv.patch_01_set, sample_nm, nm_sample_ct, tmp_nm);
815 patch_set_nm = tmp_nm;
816 }
817 uintptr_t sample_idx_base = 0;
818 uintptr_t cur_bits = patch_set_nm[0];
819 if (!omitted_allele_idx) {
820 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
821 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
822 const uint32_t allele_code = pgv.patch_01_vals[uii];
823 rarealt_start[(allele_code - 2) * nm_sample_ct + sample_idx] = 1.0;
824 alt1_start[sample_idx] = 0.0;
825 machr2_dosage_sums[allele_code] += 1;
826 }
827 } else if (omitted_allele_idx == 1) {
828 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
829 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
830 const uint32_t allele_code = pgv.patch_01_vals[uii];
831 rarealt_start[(allele_code - 2) * nm_sample_ct + sample_idx] = 1.0;
832 machr2_dosage_sums[allele_code] += 1;
833 }
834 } else {
835 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
836 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
837 alt1_start[sample_idx] = 0.0;
838 const uint32_t allele_code = pgv.patch_01_vals[uii];
839 machr2_dosage_sums[allele_code] += 1;
840 if (allele_code == omitted_allele_idx) {
841 continue;
842 }
843 const uint32_t cur_col = allele_code - 2 - (allele_code > omitted_allele_idx);
844 rarealt_start[cur_col * nm_sample_ct + sample_idx] = 1.0;
845 }
846 }
847 }
848 uintptr_t alt1_het_ct = genocounts[1] - pgv.patch_01_ct;
849 if (pgv.patch_10_ct) {
850 const uintptr_t* patch_set_nm = pgv.patch_10_set;
851 if (missing_ct) {
852 CopyBitarrSubset(pgv.patch_10_set, sample_nm, nm_sample_ct, tmp_nm);
853 patch_set_nm = tmp_nm;
854 }
855 uintptr_t sample_idx_base = 0;
856 uintptr_t cur_bits = patch_set_nm[0];
857 if (!omitted_allele_idx) {
858 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
859 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
860 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
861 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
862 if (ac0 == ac1) {
863 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] = 2.0;
864 alt1_start[sample_idx] = 0.0;
865 machr2_dosage_ssqs[ac0] += 1;
866 } else {
867 rarealt_start[(ac1 - 2) * nm_sample_ct + sample_idx] = 1.0;
868 machr2_dosage_sums[ac1] += 1;
869 if (ac0 == 1) {
870 ++alt1_het_ct;
871 alt1_start[sample_idx] = 1.0;
872 } else {
873 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] += 1.0;
874 alt1_start[sample_idx] = 0.0;
875 machr2_dosage_sums[ac0] += 1;
876 }
877 }
878 }
879 } else if (omitted_allele_idx == 1) {
880 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
881 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
882 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
883 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
884 if (ac0 == ac1) {
885 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] = 2.0;
886 machr2_dosage_ssqs[ac0] += 1;
887 } else {
888 rarealt_start[(ac1 - 2) * nm_sample_ct + sample_idx] = 1.0;
889 machr2_dosage_sums[ac1] += 1;
890 if (ac0 == 1) {
891 ++alt1_het_ct;
892 } else {
893 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] += 1.0;
894 machr2_dosage_sums[ac0] += 1;
895 }
896 }
897 }
898 } else {
899 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
900 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
901 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
902 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
903 if (ac0 == ac1) {
904 machr2_dosage_ssqs[ac0] += 1;
905 alt1_start[sample_idx] = 0.0;
906 if (ac0 != omitted_allele_idx) {
907 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
908 rarealt_start[ac0_col * nm_sample_ct + sample_idx] = 2.0;
909 }
910 } else {
911 machr2_dosage_sums[ac1] += 1;
912 if (ac1 != omitted_allele_idx) {
913 const uint32_t ac1_col = ac1 - 2 - (ac1 > omitted_allele_idx);
914 rarealt_start[ac1_col * nm_sample_ct + sample_idx] = 1.0;
915 }
916 if (ac0 == 1) {
917 ++alt1_het_ct;
918 alt1_start[sample_idx] = 1.0;
919 } else {
920 machr2_dosage_sums[ac0] += 1;
921 alt1_start[sample_idx] = 0.0;
922 if (ac0 != omitted_allele_idx) {
923 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
924 rarealt_start[ac0_col * nm_sample_ct + sample_idx] += 1.0;
925 }
926 }
927 }
928 }
929 }
930 }
931 for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) {
932 const uintptr_t one_ct = machr2_dosage_sums[allele_idx];
933 const uintptr_t two_ct = machr2_dosage_ssqs[allele_idx];
934 machr2_dosage_sums[allele_idx] = one_ct + 2 * two_ct;
935 machr2_dosage_ssqs[allele_idx] = one_ct + 4LLU * two_ct;
936 if ((one_ct == nm_sample_ct) || (two_ct == nm_sample_ct) || ((!one_ct) && (!two_ct))) {
937 SetBit(allele_idx, const_alleles);
938 }
939 }
940 const uintptr_t alt1_hom_ct = genocounts[2] - pgv.patch_10_ct;
941 machr2_dosage_sums[1] = alt1_het_ct + 2 * alt1_hom_ct;
942 machr2_dosage_ssqs[1] = alt1_het_ct + 4LLU * alt1_hom_ct;
943 if ((alt1_het_ct == nm_sample_ct) || (alt1_hom_ct == nm_sample_ct) || ((!alt1_het_ct) && (!alt1_hom_ct))) {
944 SetBit(1, const_alleles);
945 }
946 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
947 machr2_dosage_sums[allele_idx] *= 0x4000LLU;
948 machr2_dosage_ssqs[allele_idx] *= 0x10000000LLU;
949 }
950 }
951 // usually need to save some of {sample_obs_ct, allele_obs_ct,
952 // a1_dosage, mach_r2 even for skipped variants
953 // compute them all for now, could conditionally skip later
954 uint32_t allele_obs_ct = nm_sample_ct * 2;
955 if (!is_regular_x) {
956 if (is_nonx_haploid) {
957 allele_obs_ct = nm_sample_ct;
958 // everything is on 0..1 scale, not 0..2
959 if (!sparse_optimization) {
960 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
961 genotype_vals[sample_idx] *= 0.5;
962 }
963 const uint32_t high_ct = nm_sample_ct * allele_ct_m2;
964 for (uint32_t uii = 0; uii != high_ct; ++uii) {
965 multi_start[uii] *= 0.5;
966 }
967 }
968 }
969 } else {
970 CopyBitarrSubset(sex_male_collapsed, sample_nm, nm_sample_ct, tmp_nm);
971 const uintptr_t* male_nm = tmp_nm;
972 const uint32_t nm_male_ct = PopcountWords(male_nm, nm_sample_ctl);
973 if (is_xchr_model_1) {
974 // special case: multiply male values by 0.5
975 uintptr_t sample_idx_base = 0;
976 uintptr_t male_nm_bits = male_nm[0];
977 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
978 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
979 genotype_vals[sample_idx] *= 0.5;
980 // could insert multiallelic loop here instead, but I'm guessing
981 // that's worse due to locality of writes?
982 }
983 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
984 double* cur_start = &(multi_start[extra_allele_idx * nm_sample_ct]);
985 sample_idx_base = 0;
986 male_nm_bits = male_nm[0];
987 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
988 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
989 cur_start[sample_idx] *= 0.5;
990 }
991 }
992 allele_obs_ct -= nm_male_ct;
993 }
994 }
995 const double mach_r2 = MultiallelicDiploidMachR2(machr2_dosage_sums, machr2_dosage_ssqs, nm_sample_ct, allele_ct);
996 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
997 if (allele_idx == omitted_allele_idx) {
998 continue;
999 }
1000 block_aux_iter->sample_obs_ct = nm_sample_ct;
1001 block_aux_iter->allele_obs_ct = allele_obs_ct;
1002 double a1_dosage = u63tod(machr2_dosage_sums[allele_idx]) * kRecipDosageMid;
1003 if (is_xchr_model_1) {
1004 // ugh.
1005 double* geno_col = genotype_vals;
1006 if (allele_idx > (!omitted_allele_idx)) {
1007 geno_col = &(nm_predictors_pmaj_buf[(expected_predictor_ct - (allele_ct - allele_idx) + (allele_idx < omitted_allele_idx)) * nm_sample_ct]);
1008 }
1009 a1_dosage = 0.0;
1010 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1011 a1_dosage += geno_col[sample_idx];
1012 }
1013 if (!allele_ct_m2) {
1014 main_dosage_sum = a1_dosage;
1015 main_dosage_ssq = 0.0;
1016 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1017 const double cur_dosage = geno_col[sample_idx];
1018 main_dosage_ssq += cur_dosage * cur_dosage;
1019 }
1020 }
1021 } else {
1022 if (is_nonx_haploid) {
1023 a1_dosage *= 0.5;
1024 }
1025 if (!allele_ct_m2) {
1026 main_dosage_sum = a1_dosage;
1027 main_dosage_ssq = u63tod(machr2_dosage_ssqs[allele_idx]) * kRecipDosageMidSq;
1028 if (is_nonx_haploid) {
1029 main_dosage_ssq *= 0.25;
1030 }
1031 }
1032 }
1033 block_aux_iter->a1_dosage = a1_dosage;
1034 block_aux_iter->mach_r2 = mach_r2;
1035 ++block_aux_iter;
1036 }
1037 // now free to skip the actual regression if there are too few samples,
1038 // or there's a zero-variance genotype column
1039 GlmErr glm_err = 0;
1040 if (nm_sample_ct <= expected_predictor_ct) {
1041 glm_err = SetGlmErr0(kGlmErrcodeSampleCtLtePredictorCt);
1042 } else if (IsSet(const_alleles, omitted_allele_idx)) {
1043 glm_err = SetGlmErr0(kGlmErrcodeConstOmittedAllele);
1044 }
1045 if (glm_err) {
1046 if (missing_ct) {
1047 // covariates have not been copied yet, so we can't usually change
1048 // prev_nm from 0 to 1 when missing_ct == 0 (and there's little
1049 // reason to optimize the zero-covariate case).
1050 prev_nm = 0;
1051 }
1052 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
1053 if (beta_se_multiallelic_fused || (!hide_covar)) {
1054 reported_ct += allele_ct_m2;
1055 }
1056 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
1057 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
1058 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
1059 beta_se_iter[uii * 2 + 1] = -9.0;
1060 }
1061 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
1062 }
1063 } else {
1064 uint32_t parameter_uidx = 2 + domdev_present;
1065 double* nm_predictors_pmaj_istart = nullptr;
1066 if (!sparse_optimization) {
1067 // only need to do this part once per variant in multiallelic case
1068 double* nm_predictors_pmaj_iter = &(nm_predictors_pmaj_buf[nm_sample_ct * (parameter_uidx - main_omitted)]);
1069 if (missing_ct || (!prev_nm)) {
1070 // fill phenotype
1071 {
1072 uintptr_t sample_midx_base = 0;
1073 uintptr_t sample_nm_bits = sample_nm[0];
1074 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1075 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1076 nm_pheno_buf[sample_idx] = cur_pheno[sample_midx];
1077 }
1078 }
1079
1080 // fill covariates
1081 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx, ++parameter_uidx) {
1082 // strictly speaking, we don't need cur_covars_cmaj to be
1083 // vector-aligned
1084 if (cur_parameter_subset && (!IsSet(cur_parameter_subset, parameter_uidx))) {
1085 continue;
1086 }
1087 const double* cur_covar_col;
1088 if (covar_idx < local_covar_ct) {
1089 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
1090 } else {
1091 cur_covar_col = &(cur_covars_cmaj[(covar_idx - local_covar_ct) * cur_sample_ct]);
1092 }
1093 uintptr_t sample_midx_base = 0;
1094 uintptr_t sample_nm_bits = sample_nm[0];
1095 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1096 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1097 *nm_predictors_pmaj_iter++ = cur_covar_col[sample_midx];
1098 }
1099 }
1100 nm_predictors_pmaj_istart = nm_predictors_pmaj_iter;
1101 prev_nm = !(missing_ct || local_covar_ct);
1102 } else {
1103 // bugfix (15 Aug 2018): this was not handling --parameters
1104 // correctly when a covariate was only needed as part of an
1105 // interaction
1106 parameter_uidx += cur_covar_ct;
1107 nm_predictors_pmaj_istart = &(nm_predictors_pmaj_iter[literal_covar_ct * nm_sample_ct]);
1108 }
1109 }
1110 const uint32_t const_allele_ct = PopcountWords(const_alleles, allele_ctl);
1111 if (const_allele_ct) {
1112 // Must delete constant-allele columns from nm_predictors_pmaj, and
1113 // shift later columns back.
1114 double* read_iter = genotype_vals;
1115 double* write_iter = genotype_vals;
1116 for (uint32_t read_allele_idx = 0; read_allele_idx != allele_ct; ++read_allele_idx) {
1117 if (read_allele_idx == omitted_allele_idx) {
1118 continue;
1119 }
1120 if (!IsSet(const_alleles, read_allele_idx)) {
1121 if (write_iter != read_iter) {
1122 memcpy(write_iter, read_iter, nm_sample_ct * sizeof(double));
1123 }
1124 if (write_iter == genotype_vals) {
1125 write_iter = multi_start;
1126 } else {
1127 write_iter = &(write_iter[nm_sample_ct]);
1128 }
1129 }
1130 if (read_iter == genotype_vals) {
1131 read_iter = multi_start;
1132 } else {
1133 read_iter = &(read_iter[nm_sample_ct]);
1134 }
1135 }
1136 }
1137 const uint32_t cur_predictor_ct = expected_predictor_ct - const_allele_ct;
1138 uint32_t nonconst_extra_regression_idx = UINT32_MAX; // deliberate overflow
1139 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
1140 if (extra_regression_ct) {
1141 if (IsSet(const_alleles, extra_regression_idx + (extra_regression_idx >= omitted_allele_idx))) {
1142 glm_err = SetGlmErr0(kGlmErrcodeConstAllele);
1143 goto GlmLinearThread_skip_regression;
1144 }
1145 ++nonconst_extra_regression_idx;
1146 if (nonconst_extra_regression_idx) {
1147 double* swap_target = &(multi_start[(nonconst_extra_regression_idx - 1) * nm_sample_ct]);
1148 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
1149 double dxx = genotype_vals[uii];
1150 genotype_vals[uii] = swap_target[uii];
1151 swap_target[uii] = dxx;
1152 }
1153 }
1154 }
1155 if (!sparse_optimization) {
1156 double* main_vals = &(nm_predictors_pmaj_buf[nm_sample_ct]);
1157 double* domdev_vals = nullptr;
1158 if (main_omitted) {
1159 // if main_mutated, this will be filled below
1160 // if not, this aliases genotype_vals
1161 main_vals = &(nm_predictors_pmaj_buf[(cur_predictor_ct + main_mutated) * nm_sample_ct]);
1162 } else if (joint_genotypic || joint_hethom) {
1163 domdev_vals = &(main_vals[nm_sample_ct]);
1164 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1165 double cur_genotype_val = genotype_vals[sample_idx];
1166 if (cur_genotype_val > 1.0) {
1167 cur_genotype_val = 2.0 - cur_genotype_val;
1168 }
1169 domdev_vals[sample_idx] = cur_genotype_val;
1170 }
1171 }
1172 if (model_dominant) {
1173 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1174 double cur_genotype_val = genotype_vals[sample_idx];
1175 // 0..1..1
1176 if (cur_genotype_val > 1.0) {
1177 cur_genotype_val = 1.0;
1178 }
1179 main_vals[sample_idx] = cur_genotype_val;
1180 }
1181 } else if (model_recessive || joint_hethom) {
1182 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1183 double cur_genotype_val = genotype_vals[sample_idx];
1184 // 0..0..1
1185 if (cur_genotype_val < 1.0) {
1186 cur_genotype_val = 0.0;
1187 } else {
1188 cur_genotype_val -= 1.0;
1189 }
1190 main_vals[sample_idx] = cur_genotype_val;
1191 }
1192 } else if (model_hetonly) {
1193 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1194 double cur_genotype_val = genotype_vals[sample_idx];
1195 // 0..1..0
1196 if (cur_genotype_val > 1.0) {
1197 cur_genotype_val = 2.0 - cur_genotype_val;
1198 }
1199 main_vals[sample_idx] = cur_genotype_val;
1200 }
1201 }
1202
1203 // fill interaction terms
1204 if (add_interactions) {
1205 double* nm_predictors_pmaj_iter = nm_predictors_pmaj_istart;
1206 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx) {
1207 const double* cur_covar_col;
1208 if (covar_idx < local_covar_ct) {
1209 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
1210 } else {
1211 cur_covar_col = &(cur_covars_cmaj[covar_idx * cur_sample_ct]);
1212 }
1213 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
1214 uintptr_t sample_midx_base = 0;
1215 uintptr_t sample_nm_bits = sample_nm[0];
1216 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1217 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1218 *nm_predictors_pmaj_iter++ = main_vals[sample_idx] * cur_covar_col[sample_midx];
1219 }
1220 }
1221 ++parameter_uidx;
1222 if (domdev_present) {
1223 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
1224 uintptr_t sample_midx_base = 0;
1225 uintptr_t sample_nm_bits = sample_nm[0];
1226 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1227 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1228 *nm_predictors_pmaj_iter++ = domdev_vals[sample_idx] * cur_covar_col[sample_midx];
1229 }
1230 }
1231 ++parameter_uidx;
1232 }
1233 }
1234 }
1235 }
1236
1237 // bugfix (12 Sep 2017): forgot to implement per-variant VIF and
1238 // max-corr checks
1239 // DPrintf("\nWorker thread %" PRIuPTR " starting main regression for %u", tidx, variant_uidx);
1240 if (xtx_image && (sparse_optimization || (prev_nm && (!allele_ct_m2)))) {
1241 // only need to fill in additive and possibly domdev dot
1242 // products
1243 memcpy(xtx_inv, xtx_image, cur_predictor_ct * cur_predictor_ct * sizeof(double));
1244 memcpy(xt_y, xt_y_image, cur_predictor_ct * sizeof(double));
1245 if (sparse_optimization) {
1246 // currently does not handle chrX
1247 double geno_pheno_prod = 0.0;
1248 double domdev_pheno_prod = 0.0;
1249 double domdev_geno_prod = 0.0;
1250 if (!cur_covar_ct) {
1251 // missing genotypes may be present
1252 double pheno_sum = xt_y[0];
1253 if (!difflist_common_geno) {
1254 if (difflist_len) {
1255 const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
1256 uint32_t loop_len = kBitsPerWordD2;
1257 for (uint32_t widx = 0; ; ++widx) {
1258 if (widx >= word_ct_m1) {
1259 if (widx > word_ct_m1) {
1260 break;
1261 }
1262 loop_len = ModNz(difflist_len, kBitsPerWordD2);
1263 }
1264 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
1265 uintptr_t raregeno_word = raregeno[widx];
1266 for (uint32_t uii = 0; uii != loop_len; ++uii) {
1267 const uintptr_t cur_geno = raregeno_word & 3;
1268 const uint32_t sample_midx = cur_difflist_sample_ids[uii];
1269 const double cur_pheno_val = cur_pheno[sample_midx];
1270 if (cur_geno == 3) {
1271 pheno_sum -= cur_pheno[sample_midx];
1272 } else {
1273 const uint32_t cur_geno_m1 = cur_geno - 1;
1274 const double geno_d = geno_d_lookup[cur_geno_m1];
1275 geno_pheno_prod += geno_d * cur_pheno_val;
1276 if (domdev_present && (!cur_geno_m1)) {
1277 // domdev = 1
1278 domdev_pheno_prod += cur_pheno_val;
1279 domdev_geno_prod += geno_d;
1280 }
1281 }
1282 raregeno_word = raregeno_word >> 2;
1283 }
1284 }
1285 }
1286 } else {
1287 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
1288 uintptr_t geno_word = pgv.genovec[widx];
1289 if (!geno_word) {
1290 continue;
1291 }
1292 const uint32_t sample_midx_base = widx * kBitsPerWordD2;
1293 uintptr_t missing_word = geno_word & (geno_word >> 1) & kMask5555;
1294 if (missing_word) {
1295 geno_word ^= missing_word * 3;
1296 while (missing_word) {
1297 const uint32_t sample_midx_lowbits = ctzw(missing_word) / 2;
1298 const uint32_t sample_midx = sample_midx_base + sample_midx_lowbits;
1299 pheno_sum -= cur_pheno[sample_midx];
1300 missing_word &= missing_word - 1;
1301 }
1302 }
1303 while (geno_word) {
1304 const uint32_t lowest_set_bit = ctzw(geno_word);
1305 const uint32_t sample_midx = sample_midx_base + (lowest_set_bit / 2);
1306 const double geno_d = geno_d_lookup[lowest_set_bit & 1];
1307 const double cur_pheno_val = cur_pheno[sample_midx];
1308 geno_pheno_prod += geno_d * cur_pheno_val;
1309 if (domdev_present && (!(lowest_set_bit & 1))) {
1310 // domdev = 1
1311 domdev_pheno_prod += cur_pheno_val;
1312 domdev_geno_prod += geno_d;
1313 }
1314 geno_word &= geno_word - 1;
1315 }
1316 }
1317 }
1318 xt_y[0] = pheno_sum;
1319 xtx_inv[0] = u31tod(nm_sample_ct);
1320 } else {
1321 double* geno_dotprod_row = &(xtx_inv[cur_predictor_ct]);
1322 double* domdev_dotprod_row = &(xtx_inv[2 * cur_predictor_ct]);
1323 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
1324 uintptr_t geno_word = pgv.genovec[widx];
1325 if (geno_word) {
1326 const uint32_t sample_idx_base = widx * kBitsPerWordD2;
1327 do {
1328 const uint32_t lowest_set_bit = ctzw(geno_word);
1329 // since there are no missing values, we have a het if
1330 // (lowest_set_bit & 1) is zero, and a hom-alt when
1331 // it's one.
1332 const uint32_t sample_idx = sample_idx_base + (lowest_set_bit / 2);
1333 const double geno_d = geno_d_lookup[lowest_set_bit & 1];
1334 const double cur_pheno_val = nm_pheno_buf[sample_idx];
1335 geno_pheno_prod += geno_d * cur_pheno_val;
1336 for (uintptr_t pred_idx = domdev_present + 2; pred_idx != cur_predictor_ct; ++pred_idx) {
1337 geno_dotprod_row[pred_idx] += geno_d * nm_predictors_pmaj_buf[pred_idx * nm_sample_ct + sample_idx];
1338 }
1339 // can have a separate categorical loop here
1340
1341 if (domdev_present && (!(lowest_set_bit & 1))) {
1342 // domdev = 1
1343 domdev_pheno_prod += cur_pheno_val;
1344 domdev_geno_prod += geno_d;
1345 for (uintptr_t pred_idx = 3; pred_idx != cur_predictor_ct; ++pred_idx) {
1346 domdev_dotprod_row[pred_idx] += nm_predictors_pmaj_buf[pred_idx * nm_sample_ct + sample_idx];
1347 }
1348 // categorical optimization possible here
1349 }
1350 geno_word &= geno_word - 1;
1351 } while (geno_word);
1352 }
1353 }
1354 }
1355 xt_y[1] = geno_pheno_prod;
1356 const double het_ctd = u31tod(genocounts[1]);
1357 const double homalt_ctd = u31tod(genocounts[2]);
1358 xtx_inv[cur_predictor_ct] = het_ctd * geno_d_lookup[0] + homalt_ctd * geno_d_lookup[1];
1359 xtx_inv[cur_predictor_ct + 1] = het_ctd * geno_d_lookup[0] * geno_d_lookup[0] + homalt_ctd * geno_d_lookup[1] * geno_d_lookup[1];
1360 if (domdev_present) {
1361 xt_y[2] = domdev_pheno_prod;
1362 xtx_inv[cur_predictor_ct + 2] = domdev_geno_prod;
1363 xtx_inv[2 * cur_predictor_ct] = het_ctd;
1364 xtx_inv[2 * cur_predictor_ct + 2] = het_ctd;
1365 }
1366 } else {
1367 // !sparse_optimization
1368 xt_y[1] = DotprodD(&(nm_predictors_pmaj_buf[nm_sample_ct]), nm_pheno_buf, nm_sample_ct);
1369 uintptr_t start_pred_idx = 0;
1370 if (!(model_dominant || model_recessive || model_hetonly || joint_hethom)) {
1371 start_pred_idx = domdev_present + 2;
1372 xtx_inv[cur_predictor_ct] = main_dosage_sum;
1373 xtx_inv[cur_predictor_ct + 1] = main_dosage_ssq;
1374 }
1375 if (cur_predictor_ct > start_pred_idx) {
1376 // categorical optimization possible here
1377 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[nm_sample_ct]), &(nm_predictors_pmaj_buf[start_pred_idx * nm_sample_ct]), nm_sample_ct, nm_sample_ct, cur_predictor_ct - start_pred_idx, &(xtx_inv[cur_predictor_ct + start_pred_idx]));
1378 }
1379 if (domdev_present) {
1380 xt_y[2] = DotprodD(&(nm_predictors_pmaj_buf[2 * nm_sample_ct]), nm_pheno_buf, nm_sample_ct);
1381 // categorical optimization possible here
1382 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[2 * nm_sample_ct]), nm_predictors_pmaj_buf, nm_sample_ct, nm_sample_ct, cur_predictor_ct, &(xtx_inv[2 * cur_predictor_ct]));
1383 xtx_inv[cur_predictor_ct + 2] = xtx_inv[2 * cur_predictor_ct + 1];
1384 }
1385 }
1386 const double* covarxx_dotprod_inv = covarx_dotprod_inv;
1387 if (!missing_ct) {
1388 glm_err = CheckMaxCorrAndVifNm(xtx_inv, corr_inv, cur_predictor_ct, domdev_present_p1, cur_sample_ct_recip, cur_sample_ct_m1_recip, max_corr, vif_thresh, semicomputed_biallelic_corr_matrix, semicomputed_biallelic_inv_corr_sqrts, dbl_2d_buf, &(dbl_2d_buf[2 * cur_predictor_ct]), &(dbl_2d_buf[3 * cur_predictor_ct]));
1389 } else {
1390 for (uint32_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
1391 dbl_2d_buf[pred_idx] = xtx_inv[pred_idx * cur_predictor_ct];
1392 }
1393 glm_err = CheckMaxCorrAndVif(xtx_inv, 1, cur_predictor_ct, nm_sample_ct, max_corr, vif_thresh, dbl_2d_buf, nullptr, inverse_corr_buf, inv_1d_buf);
1394 covarless_inverse_buf[0] = 1.0 / u31tod(nm_sample_ct);
1395 covarxx_dotprod_inv = covarless_inverse_buf;
1396 }
1397 if (glm_err) {
1398 goto GlmLinearThread_skip_regression;
1399 }
1400 const double geno_ssq = xtx_inv[1 + cur_predictor_ct];
1401 if (!domdev_present) {
1402 xtx_inv[1 + cur_predictor_ct] = xtx_inv[cur_predictor_ct];
1403 if (InvertRank1Symm(covarxx_dotprod_inv, &(xtx_inv[1 + cur_predictor_ct]), cur_predictor_ct - 1, 1, geno_ssq, dbl_2d_buf, inverse_corr_buf)) {
1404 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
1405 goto GlmLinearThread_skip_regression;
1406 }
1407 } else {
1408 const double domdev_geno_prod = xtx_inv[2 + cur_predictor_ct];
1409 const double domdev_ssq = xtx_inv[2 + 2 * cur_predictor_ct];
1410 xtx_inv[2 + cur_predictor_ct] = xtx_inv[cur_predictor_ct];
1411 xtx_inv[2 + 2 * cur_predictor_ct] = xtx_inv[2 * cur_predictor_ct];
1412 if (InvertRank2Symm(covarxx_dotprod_inv, &(xtx_inv[2 + cur_predictor_ct]), cur_predictor_ct - 2, cur_predictor_ct, 1, geno_ssq, domdev_geno_prod, domdev_ssq, dbl_2d_buf, inverse_corr_buf, &(inverse_corr_buf[2 * (cur_predictor_ct - 2)]))) {
1413 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
1414 goto GlmLinearThread_skip_regression;
1415 }
1416 }
1417 // need to make sure xtx_inv remains reflected in NOLAPACK case
1418 memcpy(xtx_inv, dbl_2d_buf, cur_predictor_ct * cur_predictor_ct * sizeof(double));
1419 ReflectMatrix(cur_predictor_ct, xtx_inv);
1420 ColMajorVectorMatrixMultiplyStrided(xt_y, xtx_inv, cur_predictor_ct, cur_predictor_ct, cur_predictor_ct, fitted_coefs);
1421 } else {
1422 // generic case
1423 // major categorical optimization possible here, some
1424 // multiallelic optimizations possible
1425 MultiplySelfTranspose(nm_predictors_pmaj_buf, cur_predictor_ct, nm_sample_ct, xtx_inv);
1426 for (uint32_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
1427 dbl_2d_buf[pred_idx] = xtx_inv[pred_idx * cur_predictor_ct];
1428 }
1429 glm_err = CheckMaxCorrAndVif(xtx_inv, 1, cur_predictor_ct, nm_sample_ct, max_corr, vif_thresh, dbl_2d_buf, nullptr, inverse_corr_buf, inv_1d_buf);
1430 if (glm_err) {
1431 goto GlmLinearThread_skip_regression;
1432 }
1433 if (LinearRegressionInv(nm_pheno_buf, nm_predictors_pmaj_buf, cur_predictor_ct, nm_sample_ct, 1, xtx_inv, fitted_coefs, xt_y, inv_1d_buf, dbl_2d_buf)) {
1434 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
1435 goto GlmLinearThread_skip_regression;
1436 }
1437 }
1438 {
1439 // DPrintf("\nWorker thread %" PRIuPTR " finished main regression for %u", tidx, variant_uidx);
1440 // RSS = y^T y - y^T X (X^T X)^{-1} X^T y
1441 // = cur_pheno_ssq - xt_y * fitted_coefs
1442 // s^2 = RSS / df
1443 // possible todo: improve numerical stability of this computation
1444 // in non-mean-centered phenotype case
1445 const double sigma = (cur_pheno_ssq - DotprodxD(xt_y, fitted_coefs, cur_predictor_ct)) / u31tod(nm_sample_ct - cur_predictor_ct);
1446 for (uint32_t uii = 0; uii != cur_predictor_ct; ++uii) {
1447 double* s_iter = &(xtx_inv[uii * cur_predictor_ct]);
1448 #ifdef NOLAPACK
1449 for (uint32_t ujj = 0; ujj != cur_predictor_ct; ++ujj) {
1450 s_iter[ujj] *= sigma;
1451 }
1452 #else
1453 for (uint32_t ujj = 0; ujj <= uii; ++ujj) {
1454 s_iter[ujj] *= sigma;
1455 }
1456 #endif
1457 }
1458 // validParameters() check
1459 for (uint32_t pred_uidx = 1; pred_uidx != cur_predictor_ct; ++pred_uidx) {
1460 const double xtx_inv_diag_element = xtx_inv[pred_uidx * (cur_predictor_ct + 1)];
1461 if (xtx_inv_diag_element < 1e-20) {
1462 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
1463 goto GlmLinearThread_skip_regression;
1464 }
1465 // use dbl_2d_buf[] to store diagonal square roots
1466 dbl_2d_buf[pred_uidx] = sqrt(xtx_inv_diag_element);
1467 }
1468 dbl_2d_buf[0] = sqrt(xtx_inv[0]);
1469 for (uint32_t pred_uidx = 1; pred_uidx != cur_predictor_ct; ++pred_uidx) {
1470 const double cur_xtx_inv_diag_sqrt = 0.99999 * dbl_2d_buf[pred_uidx];
1471 const double* xtx_inv_row = &(xtx_inv[pred_uidx * cur_predictor_ct]);
1472 for (uint32_t pred_uidx2 = 0; pred_uidx2 != pred_uidx; ++pred_uidx2) {
1473 if (xtx_inv_row[pred_uidx2] > cur_xtx_inv_diag_sqrt * dbl_2d_buf[pred_uidx2]) {
1474 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
1475 goto GlmLinearThread_skip_regression;
1476 }
1477 }
1478 }
1479 double* beta_se_iter2 = beta_se_iter;
1480 for (uint32_t pred_uidx = reported_pred_uidx_start; pred_uidx != reported_pred_uidx_biallelic_end; ++pred_uidx) {
1481 // In the multiallelic-fused case, if the first allele is
1482 // constant, this writes the beta/se values for the first
1483 // nonconstant, non-omitted allele where the results for the
1484 // first allele belong. We correct that below.
1485 *beta_se_iter2++ = fitted_coefs[pred_uidx];
1486 *beta_se_iter2++ = dbl_2d_buf[pred_uidx];
1487 }
1488 // move this up since dbl_2d_buf may be clobbered
1489 if (cur_constraint_ct) {
1490 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeRankDeficient);
1491 memcpy(beta_se_iter2, &glm_err2, 8);
1492 ++beta_se_iter2;
1493 *beta_se_iter2++ = -9.0;
1494 }
1495 if (!const_allele_ct) {
1496 if (beta_se_multiallelic_fused || (!hide_covar)) {
1497 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
1498 beta_se_iter2[2 * extra_allele_idx] = fitted_coefs[cur_biallelic_predictor_ct + extra_allele_idx];
1499 beta_se_iter2[2 * extra_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + extra_allele_idx];
1500 }
1501 }
1502 } else if (!beta_se_multiallelic_fused) {
1503 if (!hide_covar) {
1504 // Need to insert some {CONST_ALLELE, -9} entries.
1505 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
1506 const uint32_t cur_raw_allele_idx = extra_regression_idx + (extra_regression_idx >= omitted_allele_idx);
1507 uint32_t extra_read_allele_idx = 0;
1508 uint32_t extra_write_allele_idx = 0;
1509 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
1510 if ((allele_idx == omitted_allele_idx) || (allele_idx == cur_raw_allele_idx)) {
1511 continue;
1512 }
1513 if (IsSet(const_alleles, allele_idx)) {
1514 memcpy(&(beta_se_iter2[2 * extra_write_allele_idx]), &glm_err2, 8);
1515 beta_se_iter2[2 * extra_write_allele_idx + 1] = -9.0;
1516 } else {
1517 beta_se_iter2[2 * extra_write_allele_idx] = fitted_coefs[cur_biallelic_predictor_ct + extra_read_allele_idx];
1518 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + extra_read_allele_idx];
1519 ++extra_read_allele_idx;
1520 }
1521 ++extra_write_allele_idx;
1522 }
1523 }
1524 } else {
1525 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
1526 // Special-case first nonconst allele since it's positioned
1527 // discontinuously, and its BETA/SE may already be correctly
1528 // filled.
1529 uint32_t allele_idx = omitted_allele_idx? 0 : 1;
1530 uint32_t extra_write_allele_idx = 0;
1531 if (IsSet(const_alleles, allele_idx)) {
1532 memcpy(&(beta_se_iter[2 * include_intercept]), &glm_err2, 8);
1533 beta_se_iter[2 * include_intercept + 1] = -9.0;
1534 allele_idx = AdvTo0Bit(const_alleles, 1);
1535 if (allele_idx == omitted_allele_idx) {
1536 allele_idx = AdvTo0Bit(const_alleles, omitted_allele_idx + 1);
1537 }
1538 extra_write_allele_idx = allele_idx - 1 - (allele_idx > omitted_allele_idx);
1539 for (uint32_t uii = 0; uii != extra_write_allele_idx; ++uii) {
1540 memcpy(&(beta_se_iter2[2 * uii]), &glm_err2, 8);
1541 beta_se_iter2[2 * uii + 1] = -9.0;
1542 }
1543 beta_se_iter2[2 * extra_write_allele_idx] = fitted_coefs[1];
1544 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[1];
1545 ++extra_write_allele_idx;
1546 }
1547 ++allele_idx;
1548 uint32_t nonconst_allele_idx_m1 = 0;
1549 for (; allele_idx != allele_ct; ++allele_idx) {
1550 if (allele_idx == omitted_allele_idx) {
1551 continue;
1552 }
1553 if (!IsSet(const_alleles, allele_idx)) {
1554 beta_se_iter2[2 * extra_write_allele_idx] = fitted_coefs[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
1555 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
1556 ++nonconst_allele_idx_m1;
1557 } else {
1558 memcpy(&(beta_se_iter2[2 * extra_write_allele_idx]), &glm_err2, 8);
1559 beta_se_iter2[2 * extra_write_allele_idx + 1] = -9.0;
1560 }
1561 ++extra_write_allele_idx;
1562 }
1563 }
1564 if (cur_constraint_ct) {
1565 uint32_t joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
1566 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
1567 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
1568 cur_constraints_con_major[uii * cur_predictor_ct + joint_test_idx] = 1.0;
1569 }
1570 #ifndef NOLAPACK
1571 // xtx_inv upper triangle was not filled
1572 ReflectMatrix(cur_predictor_ct, xtx_inv);
1573 #endif
1574 double chisq;
1575 if (!LinearHypothesisChisq(fitted_coefs, cur_constraints_con_major, xtx_inv, cur_constraint_ct, cur_predictor_ct, cur_predictor_ct, &chisq, tmphxs_buf, h_transpose_buf, inner_buf, inv_1d_buf, dbl_2d_buf)) {
1576 beta_se_iter2[-1] = chisq;
1577 }
1578 // next test may have different alt allele count
1579 joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
1580 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
1581 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
1582 cur_constraints_con_major[uii * cur_predictor_ct + joint_test_idx] = 0.0;
1583 }
1584 }
1585 }
1586 while (0) {
1587 GlmLinearThread_skip_regression:
1588 {
1589 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
1590 if (beta_se_multiallelic_fused || (!hide_covar)) {
1591 reported_ct += allele_ct_m2;
1592 }
1593 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
1594 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
1595 beta_se_iter[uii * 2 + 1] = -9.0;
1596 }
1597 }
1598 }
1599 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
1600 }
1601 }
1602 // bugfix (1 Apr 2019): this needs to execute when regression is
1603 // skipped
1604 if (local_covars_iter) {
1605 local_covars_iter = &(local_covars_iter[local_covar_ct * max_sample_ct]);
1606 }
1607 }
1608 }
1609 parity = 1 - parity;
1610 variant_idx_offset += cur_block_variant_ct;
1611 while (0) {
1612 GlmLinearThread_err:
1613 UpdateU64IfSmaller(new_err_info, &common->err_info);
1614 }
1615 } while (!THREAD_BLOCK_FINISH(arg));
1616 THREAD_RETURN;
1617 }
1618
1619 PglErr GlmLinear(const char* cur_pheno_name, const char* const* test_names, const char* const* test_names_x, const char* const* test_names_y, const uint32_t* variant_bps, const char* const* variant_ids, const char* const* allele_storage, const GlmInfo* glm_info_ptr, const uint32_t* local_sample_uidx_order, const uintptr_t* local_variant_include, const char* outname, uint32_t raw_variant_ct, uint32_t max_chr_blen, double ci_size, double ln_pfilter, double output_min_ln, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, uintptr_t overflow_buf_size, uint32_t local_sample_ct, PgenFileInfo* pgfip, GlmLinearCtx* ctx, TextStream* local_covar_txsp, LlStr** outfnames_ll_ptr, uintptr_t* valid_variants, uintptr_t* valid_alleles, double* orig_ln_pvals, uintptr_t* valid_allele_ct_ptr) {
1620 unsigned char* bigstack_mark = g_bigstack_base;
1621 char* cswritep = nullptr;
1622 PglErr reterr = kPglRetSuccess;
1623 CompressStreamState css;
1624 ThreadGroup tg;
1625 PreinitCstream(&css);
1626 PreinitThreads(&tg);
1627 {
1628 GlmCtx* common = ctx->common;
1629 const uintptr_t* variant_include = common->variant_include;
1630 const ChrInfo* cip = common->cip;
1631 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
1632 const AlleleCode* omitted_alleles = common->omitted_alleles;
1633
1634 const uint32_t sample_ct = common->sample_ct;
1635 const uint32_t sample_ct_x = common->sample_ct_x;
1636 const uint32_t sample_ct_y = common->sample_ct_y;
1637 const uint32_t covar_ct = common->covar_ct;
1638 const uintptr_t local_covar_ct = common->local_covar_ct;
1639 const uint32_t covar_ct_x = common->covar_ct_x;
1640 const uint32_t covar_ct_y = common->covar_ct_y;
1641
1642 uint32_t max_sample_ct = MAXV(sample_ct, sample_ct_x);
1643 if (max_sample_ct < sample_ct_y) {
1644 max_sample_ct = sample_ct_y;
1645 }
1646 uint32_t* local_sample_idx_order = nullptr;
1647 uint32_t local_line_idx = 0;
1648 uint32_t local_xy = 0; // 1 = chrX, 2 = chrY
1649
1650 const char* local_line_iter = nullptr;
1651 uint32_t local_prev_chr_code = UINT32_MAX;
1652 uint32_t local_chr_code = UINT32_MAX;
1653 uint32_t local_bp = UINT32_MAX;
1654 uint32_t local_skip_chr = 1;
1655 if (local_covar_ct) {
1656 reterr = TextRewind(local_covar_txsp);
1657 if (unlikely(reterr)) {
1658 goto GlmLinear_ret_TSTREAM_FAIL;
1659 }
1660 local_line_idx = glm_info_ptr->local_header_line_ct;
1661 reterr = TextSkip(local_line_idx, local_covar_txsp);
1662 if (unlikely(reterr)) {
1663 goto GlmLinear_ret_TSTREAM_FAIL;
1664 }
1665 if (unlikely(bigstack_alloc_u32(local_sample_ct, &local_sample_idx_order))) {
1666 goto GlmLinear_ret_NOMEM;
1667 }
1668 for (uint32_t uii = 0; uii != local_sample_ct; ++uii) {
1669 const uint32_t cur_uidx = local_sample_uidx_order[uii];
1670 uint32_t cur_idx = UINT32_MAX;
1671 if ((cur_uidx != UINT32_MAX) && IsSet(common->sample_include, cur_uidx)) {
1672 cur_idx = RawToSubsettedPos(common->sample_include, common->sample_include_cumulative_popcounts, cur_uidx);
1673 }
1674 local_sample_idx_order[uii] = cur_idx;
1675 }
1676 }
1677
1678 const uint32_t variant_ct = common->variant_ct;
1679
1680 const GlmFlags glm_flags = glm_info_ptr->flags;
1681 const uint32_t output_zst = (glm_flags / kfGlmZs) & 1;
1682 // forced-singlethreaded
1683 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &css, &cswritep);
1684 if (unlikely(reterr)) {
1685 goto GlmLinear_ret_1;
1686 }
1687 if (outfnames_ll_ptr) {
1688 if (unlikely(PushLlStr(outname, outfnames_ll_ptr))) {
1689 goto GlmLinear_ret_NOMEM;
1690 }
1691 }
1692 const uint32_t report_neglog10p = (glm_flags / kfGlmLog10) & 1;
1693 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
1694 const uint32_t domdev_present = (glm_flags & (kfGlmGenotypic | kfGlmHethom))? 1 : 0;
1695 const uint32_t domdev_present_p1 = domdev_present + 1;
1696
1697 const uint32_t constraint_ct = common->constraint_ct;
1698 const uint32_t constraint_ct_x = common->constraint_ct_x;
1699 const uint32_t constraint_ct_y = common->constraint_ct_y;
1700
1701 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
1702 uint32_t biallelic_predictor_ct = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
1703 uint32_t biallelic_predictor_ct_x = 2 + covar_ct_x * (1 + add_interactions);
1704 uint32_t biallelic_predictor_ct_y = 2 + covar_ct_y * (1 + add_interactions);
1705 const uintptr_t* parameter_subset = common->parameter_subset;
1706 const uintptr_t* parameter_subset_x = common->parameter_subset_x;
1707 const uintptr_t* parameter_subset_y = common->parameter_subset_y;
1708 if (parameter_subset) {
1709 biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct));
1710 if (sample_ct_x) {
1711 biallelic_predictor_ct_x = PopcountWords(parameter_subset_x, BitCtToWordCt(biallelic_predictor_ct_x));
1712 } else {
1713 biallelic_predictor_ct_x = 0;
1714 }
1715 if (sample_ct_y) {
1716 // bugfix (7 Feb 2018): had biallelic_predictor_ct_x on right side
1717 // here, oops
1718 biallelic_predictor_ct_y = PopcountWords(parameter_subset_y, BitCtToWordCt(biallelic_predictor_ct_y));
1719 } else {
1720 biallelic_predictor_ct_y = 0;
1721 }
1722 }
1723 uint32_t biallelic_reported_test_ct = GetBiallelicReportedTestCt(parameter_subset, glm_flags, covar_ct, common->tests_flag);
1724 uintptr_t max_reported_test_ct = biallelic_reported_test_ct;
1725 uint32_t biallelic_reported_test_ct_x = 0;
1726 if (sample_ct_x) {
1727 biallelic_reported_test_ct_x = GetBiallelicReportedTestCt(parameter_subset_x, glm_flags, covar_ct_x, common->tests_flag);
1728 if (biallelic_reported_test_ct_x > max_reported_test_ct) {
1729 max_reported_test_ct = biallelic_reported_test_ct_x;
1730 }
1731 }
1732 uint32_t biallelic_reported_test_ct_y = 0;
1733 if (sample_ct_y) {
1734 biallelic_reported_test_ct_y = GetBiallelicReportedTestCt(parameter_subset_y, glm_flags, covar_ct_y, common->tests_flag);
1735 if (biallelic_reported_test_ct_y > max_reported_test_ct) {
1736 max_reported_test_ct = biallelic_reported_test_ct_y;
1737 }
1738 }
1739 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
1740 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
1741 const GlmColFlags glm_cols = glm_info_ptr->cols;
1742 const uint32_t test_col = glm_cols & kfGlmColTest;
1743 if (unlikely((!test_col) && (max_reported_test_ct > 1))) {
1744 // this is okay in plain multiallelic case due to A1 column
1745 logerrputs("Error: --glm's 'test' column cannot be omitted when results for multiple\npredictors are reported. (Did you forget 'hide-covar'?)\n");
1746 goto GlmLinear_ret_INCONSISTENT_INPUT;
1747 }
1748 const uint32_t main_mutated = ((glm_flags & (kfGlmDominant | kfGlmRecessive | kfGlmHetonly | kfGlmHethom)) != kfGlm0);
1749 // bugfix (4 Mar 2019): forgot to update this for --tests
1750 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!main_mutated) && (!common->tests_flag) && (!add_interactions);
1751 if (beta_se_multiallelic_fused || (!hide_covar)) {
1752 max_reported_test_ct += max_extra_allele_ct;
1753 }
1754 common->max_reported_test_ct = max_reported_test_ct;
1755
1756 uint32_t x_code = UINT32_MAXM1;
1757 uint32_t x_start = 0;
1758 uint32_t x_end = 0;
1759 if (sample_ct_x) {
1760 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetX, &x_code, &x_start, &x_end);
1761 }
1762 uint32_t y_code = UINT32_MAXM1;
1763 uint32_t y_start = 0;
1764 uint32_t y_end = 0;
1765 if (sample_ct_y) {
1766 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetY, &y_code, &y_start, &y_end);
1767 }
1768 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
1769 const uint32_t chr_col = glm_cols & kfGlmColChrom;
1770
1771 // includes trailing tab
1772 char* chr_buf = nullptr;
1773 if (chr_col) {
1774 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
1775 goto GlmLinear_ret_NOMEM;
1776 }
1777 }
1778
1779 uint32_t calc_thread_ct = (max_thread_ct > 8)? (max_thread_ct - 1) : max_thread_ct;
1780 if (calc_thread_ct > variant_ct) {
1781 calc_thread_ct = variant_ct;
1782 }
1783
1784 const uint32_t main_omitted = (parameter_subset && (!IsSet(parameter_subset, 1)));
1785 const uint32_t xmain_ct = main_mutated + main_omitted;
1786 const uint32_t max_returned_difflist_len = ctx->max_returned_difflist_len;
1787 uintptr_t workspace_alloc = GetLinearWorkspaceSize(sample_ct, biallelic_predictor_ct, max_extra_allele_ct, constraint_ct, xmain_ct, max_returned_difflist_len);
1788 if (sample_ct_x) {
1789 const uintptr_t workspace_alloc_x = GetLinearWorkspaceSize(sample_ct_x, biallelic_predictor_ct_x, max_extra_allele_ct, constraint_ct_x, xmain_ct, max_returned_difflist_len);
1790 if (workspace_alloc_x > workspace_alloc) {
1791 workspace_alloc = workspace_alloc_x;
1792 }
1793 }
1794 if (sample_ct_y) {
1795 const uintptr_t workspace_alloc_y = GetLinearWorkspaceSize(sample_ct_y, biallelic_predictor_ct_y, max_extra_allele_ct, constraint_ct_y, xmain_ct, max_returned_difflist_len);
1796 if (workspace_alloc_y > workspace_alloc) {
1797 workspace_alloc = workspace_alloc_y;
1798 }
1799 }
1800 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
1801 // +1 is for top-level common->workspace_bufs
1802 uintptr_t thread_xalloc_cacheline_ct = (workspace_alloc / kCacheline) + 1;
1803
1804 uintptr_t per_variant_xalloc_byte_ct = max_sample_ct * local_covar_ct * sizeof(double);
1805 uintptr_t per_alt_allele_xalloc_byte_ct = sizeof(LinearAuxResult);
1806 if (beta_se_multiallelic_fused) {
1807 per_variant_xalloc_byte_ct += 2 * max_reported_test_ct * sizeof(double);
1808 } else {
1809 per_alt_allele_xalloc_byte_ct += 2 * max_reported_test_ct * sizeof(double);
1810 }
1811 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
1812 common->thread_mhc = nullptr;
1813 common->dosage_presents = nullptr;
1814 common->dosage_mains = nullptr;
1815 uint32_t read_block_size;
1816 uintptr_t max_alt_allele_block_size;
1817 if (unlikely(PgenMtLoadInit(variant_include, max_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, per_variant_xalloc_byte_ct, per_alt_allele_xalloc_byte_ct, pgfip, &calc_thread_ct, &common->genovecs, max_extra_allele_ct? (&common->thread_mhc) : nullptr, nullptr, nullptr, dosage_is_present? (&common->dosage_presents) : nullptr, dosage_is_present? (&common->dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, &max_alt_allele_block_size, main_loadbufs, &common->pgr_ptrs, &common->read_variant_uidx_starts))) {
1818 goto GlmLinear_ret_NOMEM;
1819 }
1820 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
1821 goto GlmLinear_ret_NOMEM;
1822 }
1823 LinearAuxResult* linear_block_aux_bufs[2];
1824 double* block_beta_se_bufs[2];
1825
1826 for (uint32_t uii = 0; uii != 2; ++uii) {
1827 if (unlikely(BIGSTACK_ALLOC_X(LinearAuxResult, max_alt_allele_block_size, &(linear_block_aux_bufs[uii])))) {
1828 // shouldn't be possible for these to fail?
1829 goto GlmLinear_ret_NOMEM;
1830 }
1831 if (beta_se_multiallelic_fused) {
1832 if (unlikely(bigstack_alloc_d(read_block_size * 2 * max_reported_test_ct, &(block_beta_se_bufs[uii])))) {
1833 goto GlmLinear_ret_NOMEM;
1834 }
1835 } else {
1836 if (unlikely(bigstack_alloc_d(max_alt_allele_block_size * 2 * max_reported_test_ct, &(block_beta_se_bufs[uii])))) {
1837 goto GlmLinear_ret_NOMEM;
1838 }
1839 }
1840 if (local_covar_ct) {
1841 // bugfix (5 Mar 2018): don't want sizeof(double) here
1842 if (unlikely(bigstack_alloc_d(read_block_size * max_sample_ct * local_covar_ct, &(ctx->local_covars_vcmaj_d[uii])))) {
1843 goto GlmLinear_ret_NOMEM;
1844 }
1845 } else {
1846 ctx->local_covars_vcmaj_d[uii] = nullptr;
1847 }
1848 }
1849
1850 common->workspace_bufs = S_CAST(unsigned char**, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(intptr_t)));
1851 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
1852 common->workspace_bufs[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(workspace_alloc));
1853 }
1854 common->err_info = (~0LLU) << 32;
1855 SetThreadFuncAndData(GlmLinearThread, ctx, &tg);
1856
1857 const uint32_t ref_col = glm_cols & kfGlmColRef;
1858 const uint32_t alt1_col = glm_cols & kfGlmColAlt1;
1859 const uint32_t alt_col = glm_cols & kfGlmColAlt;
1860 const uintptr_t* nonref_flags = pgfip->nonref_flags;
1861 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
1862 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, glm_cols / kfGlmColMaybeprovref, raw_variant_ct, all_nonref);
1863 const uint32_t omitted_col = glm_cols & kfGlmColOmitted;
1864 const uint32_t ax_col = glm_cols & kfGlmColAx;
1865 const uint32_t a1_ct_col = glm_cols & kfGlmColA1count;
1866 const uint32_t tot_allele_col = glm_cols & kfGlmColTotallele;
1867 const uint32_t a1_freq_col = glm_cols & kfGlmColA1freq;
1868 const uint32_t mach_r2_col = glm_cols & kfGlmColMachR2;
1869 const uint32_t nobs_col = glm_cols & kfGlmColNobs;
1870 const uint32_t beta_col = glm_cols & (kfGlmColBeta | kfGlmColOrbeta);
1871 const uint32_t se_col = glm_cols & kfGlmColSe;
1872 const uint32_t ci_col = (ci_size != 0.0) && (glm_cols & kfGlmColCi);
1873 const uint32_t t_col = glm_cols & kfGlmColTz;
1874 const uint32_t p_col = glm_cols & kfGlmColP;
1875 const uint32_t err_col = glm_cols & kfGlmColErr;
1876 *cswritep++ = '#';
1877 if (chr_col) {
1878 cswritep = strcpya_k(cswritep, "CHROM\t");
1879 }
1880 if (variant_bps) {
1881 cswritep = strcpya_k(cswritep, "POS\t");
1882 }
1883 cswritep = strcpya_k(cswritep, "ID");
1884 if (ref_col) {
1885 cswritep = strcpya_k(cswritep, "\tREF");
1886 }
1887 if (alt1_col) {
1888 cswritep = strcpya_k(cswritep, "\tALT1");
1889 }
1890 if (alt_col) {
1891 cswritep = strcpya_k(cswritep, "\tALT");
1892 }
1893 if (provref_col) {
1894 cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
1895 }
1896 cswritep = strcpya_k(cswritep, "\tA1");
1897 if (omitted_col) {
1898 cswritep = strcpya_k(cswritep, "\tOMITTED");
1899 }
1900 if (ax_col) {
1901 cswritep = strcpya_k(cswritep, "\tAX");
1902 }
1903 if (a1_ct_col) {
1904 cswritep = strcpya_k(cswritep, "\tA1_CT");
1905 }
1906 if (tot_allele_col) {
1907 cswritep = strcpya_k(cswritep, "\tALLELE_CT");
1908 }
1909 if (a1_freq_col) {
1910 cswritep = strcpya_k(cswritep, "\tA1_FREQ");
1911 }
1912 if (mach_r2_col) {
1913 cswritep = strcpya_k(cswritep, "\tMACH_R2");
1914 }
1915 if (test_col) {
1916 cswritep = strcpya_k(cswritep, "\tTEST");
1917 }
1918 if (nobs_col) {
1919 cswritep = strcpya_k(cswritep, "\tOBS_CT");
1920 }
1921 if (beta_col) {
1922 cswritep = strcpya_k(cswritep, "\tBETA");
1923 }
1924 if (se_col) {
1925 cswritep = strcpya_k(cswritep, "\tSE");
1926 }
1927 double ci_zt = 0.0;
1928 if (ci_col) {
1929 cswritep = strcpya_k(cswritep, "\tL");
1930 cswritep = dtoa_g(ci_size * 100, cswritep);
1931 cswritep = strcpya_k(cswritep, "\tU");
1932 cswritep = dtoa_g(ci_size * 100, cswritep);
1933 ci_zt = QuantileToZscore((ci_size + 1.0) * 0.5);
1934 }
1935 if (t_col) {
1936 if (!constraint_ct) {
1937 cswritep = strcpya_k(cswritep, "\tT_STAT");
1938 } else {
1939 // F-statistic for joint tests.
1940 cswritep = strcpya_k(cswritep, "\tT_OR_F_STAT");
1941 }
1942 }
1943 if (p_col) {
1944 if (report_neglog10p) {
1945 cswritep = strcpya_k(cswritep, "\tNEG_LOG10_P");
1946 } else {
1947 cswritep = strcpya_k(cswritep, "\tP");
1948 }
1949 }
1950 if (err_col) {
1951 cswritep = strcpya_k(cswritep, "\tERRCODE");
1952 }
1953 AppendBinaryEoln(&cswritep);
1954
1955 // Main workflow:
1956 // 1. Set n=0, load/skip block 0
1957 //
1958 // 2. Spawn threads processing block n
1959 // 3. If n>0, write results for block (n-1)
1960 // 4. Increment n by 1
1961 // 5. Load/skip block n unless eof
1962 // 6. Join threads
1963 // 7. Goto step 2 unless eof
1964 //
1965 // 8, Write results for last block
1966 uintptr_t write_variant_uidx_base = 0;
1967 uintptr_t cur_bits = variant_include[0];
1968 uint32_t parity = 0;
1969 uint32_t read_block_idx = 0;
1970 uint32_t chr_fo_idx = UINT32_MAX;
1971 uint32_t chr_end = 0;
1972 uint32_t chr_buf_blen = 0;
1973 uint32_t suppress_mach_r2 = 0;
1974
1975 uint32_t cur_biallelic_reported_test_ct = 0;
1976 uint32_t primary_reported_test_idx = include_intercept;
1977 uint32_t cur_biallelic_predictor_ct = 0;
1978 uint32_t cur_constraint_ct = 0;
1979
1980 const char* const* cur_test_names = nullptr;
1981 uint32_t prev_block_variant_ct = 0;
1982 uint32_t pct = 0;
1983 uint32_t next_print_variant_idx = variant_ct / 100;
1984 uint32_t allele_ct = 2;
1985 uint32_t omitted_allele_idx = 0;
1986 uintptr_t valid_allele_ct = 0;
1987 logprintfww5("--glm linear regression on phenotype '%s': ", cur_pheno_name);
1988 fputs("0%", stdout);
1989 fflush(stdout);
1990 for (uint32_t variant_idx = 0; ; ) {
1991 const uint32_t cur_block_variant_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
1992 if (unlikely(reterr)) {
1993 goto GlmLinear_ret_PGR_FAIL;
1994 }
1995 if (local_covar_ct && cur_block_variant_ct) {
1996 const uint32_t uidx_start = read_block_idx * read_block_size;
1997 const uint32_t uidx_end = MINV(raw_variant_ct, uidx_start + read_block_size);
1998 if (local_variant_include) {
1999 reterr = ReadLocalCovarBlock(common, local_sample_uidx_order, local_variant_include, uidx_start, uidx_end, cur_block_variant_ct, local_sample_ct, glm_info_ptr->local_cat_ct, local_covar_txsp, &local_line_idx, &local_xy, nullptr, ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
2000 } else {
2001 double* prev_local_covar_row_d = nullptr;
2002 if (variant_idx) {
2003 prev_local_covar_row_d = &(ctx->local_covars_vcmaj_d[1 - parity][S_CAST(uintptr_t, read_block_size - 1) * max_sample_ct * local_covar_ct]);
2004 }
2005 reterr = ReadRfmix2Block(common, variant_bps, local_sample_uidx_order, nullptr, prev_local_covar_row_d, uidx_start, uidx_end, cur_block_variant_ct, local_sample_ct, glm_info_ptr->local_cat_ct, glm_info_ptr->local_chrom_col, glm_info_ptr->local_bp_col, glm_info_ptr->local_first_covar_col, local_covar_txsp, &local_line_iter, &local_line_idx, &local_prev_chr_code, &local_chr_code, &local_bp, &local_skip_chr, nullptr, ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
2006 /*
2007 for (uint32_t uii = 0; uii < max_sample_ct; ++uii) {
2008 printf("%g ", ctx->local_covars_vcmaj_d[parity][uii]);
2009 }
2010 printf("\n");
2011 exit(1);
2012 */
2013 }
2014 if (unlikely(reterr)) {
2015 goto GlmLinear_ret_1;
2016 }
2017 }
2018 if (variant_idx) {
2019 // DPrintf("\nWaiting for worker threads up to filtered variant %u", variant_idx);
2020 JoinThreads(&tg);
2021 reterr = S_CAST(PglErr, common->err_info);
2022 if (unlikely(reterr)) {
2023 PgenErrPrintNV(reterr, common->err_info >> 32);
2024 goto GlmLinear_ret_1;
2025 }
2026 }
2027 if (!IsLastBlock(&tg)) {
2028 common->cur_block_variant_ct = cur_block_variant_ct;
2029 const uint32_t uidx_start = read_block_idx * read_block_size;
2030 ComputeUidxStartPartition(variant_include, cur_block_variant_ct, calc_thread_ct, uidx_start, common->read_variant_uidx_starts);
2031 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, common->pgr_ptrs);
2032 ctx->block_aux = linear_block_aux_bufs[parity];
2033 common->block_beta_se = block_beta_se_bufs[parity];
2034 if (variant_idx + cur_block_variant_ct == variant_ct) {
2035 DeclareLastThreadBlock(&tg);
2036 }
2037 // DPrintf("\nLaunching worker threads for filtered variants [%u,%u)", variant_idx, variant_idx + cur_block_variant_ct);
2038 if (unlikely(SpawnThreads(&tg))) {
2039 goto GlmLinear_ret_THREAD_CREATE_FAIL;
2040 }
2041 }
2042 parity = 1 - parity;
2043 if (variant_idx) {
2044 // write *previous* block results
2045 const double* beta_se_iter = block_beta_se_bufs[parity];
2046 const LinearAuxResult* cur_block_aux = linear_block_aux_bufs[parity];
2047 uintptr_t allele_bidx = 0;
2048 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_variant_ct; ++variant_bidx) {
2049 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
2050 if (write_variant_uidx >= chr_end) {
2051 do {
2052 ++chr_fo_idx;
2053 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2054 } while (write_variant_uidx >= chr_end);
2055 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
2056 if ((chr_idx == x_code) && sample_ct_x) {
2057 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_x;
2058 cur_biallelic_predictor_ct = biallelic_predictor_ct_x;
2059 cur_constraint_ct = constraint_ct_x;
2060 cur_test_names = test_names_x;
2061 } else if ((chr_idx == y_code) && sample_ct_y) {
2062 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_y;
2063 cur_biallelic_predictor_ct = biallelic_predictor_ct_y;
2064 cur_constraint_ct = constraint_ct_y;
2065 cur_test_names = test_names_y;
2066 } else {
2067 cur_biallelic_reported_test_ct = biallelic_reported_test_ct;
2068 cur_biallelic_predictor_ct = biallelic_predictor_ct;
2069 cur_constraint_ct = constraint_ct;
2070 cur_test_names = test_names;
2071 }
2072 suppress_mach_r2 = (chr_idx == x_code) || (chr_idx == mt_code);
2073 if (cur_constraint_ct) {
2074 primary_reported_test_idx = cur_biallelic_reported_test_ct - 1;
2075 }
2076 if (chr_col) {
2077 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
2078 *chr_name_end = '\t';
2079 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
2080 }
2081 }
2082 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
2083 if (allele_idx_offsets) {
2084 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
2085 allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offsets[write_variant_uidx];
2086 }
2087 const uint32_t allele_ct_m1 = allele_ct - 1;
2088 const uint32_t extra_allele_ct = allele_ct - 2;
2089 if (omitted_alleles) {
2090 omitted_allele_idx = omitted_alleles[write_variant_uidx];
2091 }
2092 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
2093 uint32_t variant_is_valid = 0;
2094 uint32_t a1_allele_idx = 0;
2095 for (uint32_t nonomitted_allele_idx = 0; nonomitted_allele_idx != allele_ct_m1; ++nonomitted_allele_idx, ++a1_allele_idx) {
2096 if (beta_se_multiallelic_fused) {
2097 if (!nonomitted_allele_idx) {
2098 primary_reported_test_idx = include_intercept;
2099 } else {
2100 primary_reported_test_idx = cur_biallelic_reported_test_ct + nonomitted_allele_idx - 1;
2101 }
2102 }
2103 if (nonomitted_allele_idx == omitted_allele_idx) {
2104 ++a1_allele_idx;
2105 }
2106 const double primary_beta = beta_se_iter[primary_reported_test_idx * 2];
2107 const double primary_se = beta_se_iter[primary_reported_test_idx * 2 + 1];
2108 const uint32_t allele_is_valid = (primary_se != -9.0);
2109 variant_is_valid |= allele_is_valid;
2110 {
2111 const LinearAuxResult* auxp = &(cur_block_aux[allele_bidx]);
2112 if (ln_pfilter <= 0.0) {
2113 if (!allele_is_valid) {
2114 goto GlmLinear_allele_iterate;
2115 }
2116 double primary_ln_pval;
2117 if (!cur_constraint_ct) {
2118 if (primary_beta == 0.0) {
2119 primary_ln_pval = 0.0;
2120 } else if (primary_se == 0.0) {
2121 primary_ln_pval = -DBL_MAX;
2122 } else {
2123 const double primary_tstat = primary_beta / primary_se;
2124 primary_ln_pval = TstatToLnP(primary_tstat, auxp->sample_obs_ct - cur_biallelic_predictor_ct - extra_allele_ct);
2125 }
2126 } else {
2127 primary_ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
2128 }
2129 if (primary_ln_pval > ln_pfilter) {
2130 if (orig_ln_pvals) {
2131 orig_ln_pvals[valid_allele_ct] = primary_ln_pval;
2132 }
2133 goto GlmLinear_allele_iterate;
2134 }
2135 }
2136 uint32_t inner_reported_test_ct = cur_biallelic_reported_test_ct;
2137 if (extra_allele_ct) {
2138 if (beta_se_multiallelic_fused) {
2139 if (!nonomitted_allele_idx) {
2140 inner_reported_test_ct = 1 + include_intercept;
2141 } else if (nonomitted_allele_idx == extra_allele_ct) {
2142 inner_reported_test_ct -= include_intercept;
2143 } else {
2144 inner_reported_test_ct = 1;
2145 }
2146 } else if (!hide_covar) {
2147 inner_reported_test_ct += extra_allele_ct;
2148 }
2149 }
2150 // possible todo: make number-to-string operations, strlen(),
2151 // etc. happen only once per variant.
2152 for (uint32_t allele_test_idx = 0; allele_test_idx != inner_reported_test_ct; ++allele_test_idx) {
2153 uint32_t test_idx = allele_test_idx;
2154 if (beta_se_multiallelic_fused && nonomitted_allele_idx) {
2155 if (!allele_test_idx) {
2156 test_idx = primary_reported_test_idx;
2157 } else {
2158 // bugfix (26 Jun 2019): only correct to add 1 here in
2159 // include_intercept case
2160 test_idx += include_intercept;
2161 }
2162 }
2163 if (chr_col) {
2164 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
2165 }
2166 if (variant_bps) {
2167 cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep);
2168 }
2169 cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
2170 if (ref_col) {
2171 *cswritep++ = '\t';
2172 cswritep = strcpya(cswritep, cur_alleles[0]);
2173 }
2174 if (alt1_col) {
2175 *cswritep++ = '\t';
2176 cswritep = strcpya(cswritep, cur_alleles[1]);
2177 }
2178 if (alt_col) {
2179 *cswritep++ = '\t';
2180 for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
2181 if (unlikely(Cswrite(&css, &cswritep))) {
2182 goto GlmLinear_ret_WRITE_FAIL;
2183 }
2184 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
2185 }
2186 --cswritep;
2187 }
2188 *cswritep++ = '\t';
2189 if (provref_col) {
2190 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N';
2191 *cswritep++ = '\t';
2192 }
2193 const uint32_t multi_a1 = extra_allele_ct && beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx);
2194 if (multi_a1) {
2195 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
2196 if (allele_idx == omitted_allele_idx) {
2197 continue;
2198 }
2199 if (unlikely(Cswrite(&css, &cswritep))) {
2200 goto GlmLinear_ret_WRITE_FAIL;
2201 }
2202 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
2203 }
2204 --cswritep;
2205 } else {
2206 cswritep = strcpya(cswritep, cur_alleles[a1_allele_idx]);
2207 }
2208 if (omitted_col) {
2209 *cswritep++ = '\t';
2210 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
2211 }
2212 if (ax_col) {
2213 *cswritep++ = '\t';
2214 if (beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx)) {
2215 if (unlikely(Cswrite(&css, &cswritep))) {
2216 goto GlmLinear_ret_WRITE_FAIL;
2217 }
2218 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
2219 } else {
2220 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
2221 if (allele_idx == a1_allele_idx) {
2222 continue;
2223 }
2224 if (unlikely(Cswrite(&css, &cswritep))) {
2225 goto GlmLinear_ret_WRITE_FAIL;
2226 }
2227 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
2228 }
2229 --cswritep;
2230 }
2231 }
2232 if (a1_ct_col) {
2233 *cswritep++ = '\t';
2234 if (!multi_a1) {
2235 cswritep = dtoa_g(auxp->a1_dosage, cswritep);
2236 } else {
2237 cswritep = strcpya_k(cswritep, "NA");
2238 }
2239 }
2240 if (tot_allele_col) {
2241 *cswritep++ = '\t';
2242 cswritep = u32toa(auxp->allele_obs_ct, cswritep);
2243 }
2244 if (a1_freq_col) {
2245 *cswritep++ = '\t';
2246 if (!multi_a1) {
2247 cswritep = dtoa_g(auxp->a1_dosage / S_CAST(double, auxp->allele_obs_ct), cswritep);
2248 } else {
2249 cswritep = strcpya_k(cswritep, "NA");
2250 }
2251 }
2252 if (mach_r2_col) {
2253 *cswritep++ = '\t';
2254 if (!suppress_mach_r2) {
2255 cswritep = dtoa_g(auxp->mach_r2, cswritep);
2256 } else {
2257 cswritep = strcpya_k(cswritep, "NA");
2258 }
2259 }
2260 if (test_col) {
2261 *cswritep++ = '\t';
2262 if (test_idx < cur_biallelic_reported_test_ct) {
2263 cswritep = strcpya(cswritep, cur_test_names[test_idx]);
2264 } else {
2265 // always use basic dosage for untested alleles
2266 cswritep = strcpya_k(cswritep, "ADD");
2267 if (!beta_se_multiallelic_fused) {
2268 // extra alt allele covariate.
2269 uint32_t test_xallele_idx = test_idx - cur_biallelic_reported_test_ct;
2270 if (omitted_allele_idx < a1_allele_idx) {
2271 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
2272 }
2273 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= a1_allele_idx);
2274 if (a1_allele_idx < omitted_allele_idx) {
2275 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
2276 }
2277 if (!test_xallele_idx) {
2278 cswritep = strcpya_k(cswritep, "_REF");
2279 } else {
2280 cswritep = strcpya_k(cswritep, "_ALT");
2281 cswritep = u32toa(test_xallele_idx, cswritep);
2282 }
2283 }
2284 }
2285 }
2286 if (nobs_col) {
2287 *cswritep++ = '\t';
2288 cswritep = u32toa(auxp->sample_obs_ct, cswritep);
2289 }
2290 double ln_pval = kLnPvalError;
2291 double tstat = 0.0;
2292 uint32_t test_is_valid;
2293 if ((!cur_constraint_ct) || (test_idx != primary_reported_test_idx)) {
2294 double beta = beta_se_iter[2 * test_idx];
2295 double se = beta_se_iter[2 * test_idx + 1];
2296 test_is_valid = (se != -9.0);
2297 if (test_is_valid) {
2298 tstat = beta / se;
2299 ln_pval = TstatToLnP(tstat, auxp->sample_obs_ct - cur_biallelic_predictor_ct - extra_allele_ct);
2300 }
2301 if (beta_col) {
2302 *cswritep++ = '\t';
2303 if (test_is_valid) {
2304 cswritep = dtoa_g(beta, cswritep);
2305 } else {
2306 cswritep = strcpya_k(cswritep, "NA");
2307 }
2308 }
2309 if (se_col) {
2310 *cswritep++ = '\t';
2311 if (test_is_valid) {
2312 cswritep = dtoa_g(se, cswritep);
2313 } else {
2314 cswritep = strcpya_k(cswritep, "NA");
2315 }
2316 }
2317 if (ci_col) {
2318 *cswritep++ = '\t';
2319 if (test_is_valid) {
2320 const double ci_halfwidth = ci_zt * se;
2321 cswritep = dtoa_g(beta - ci_halfwidth, cswritep);
2322 *cswritep++ = '\t';
2323 cswritep = dtoa_g(beta + ci_halfwidth, cswritep);
2324 } else {
2325 cswritep = strcpya_k(cswritep, "NA\tNA");
2326 }
2327 }
2328 if (t_col) {
2329 *cswritep++ = '\t';
2330 if (test_is_valid) {
2331 cswritep = dtoa_g(tstat, cswritep);
2332 } else {
2333 cswritep = strcpya_k(cswritep, "NA");
2334 }
2335 }
2336 } else {
2337 // joint test
2338 test_is_valid = allele_is_valid;
2339 if (beta_col) {
2340 cswritep = strcpya_k(cswritep, "\tNA");
2341 }
2342 if (se_col) {
2343 cswritep = strcpya_k(cswritep, "\tNA");
2344 }
2345 if (ci_col) {
2346 cswritep = strcpya_k(cswritep, "\tNA\tNA");
2347 }
2348 if (t_col) {
2349 *cswritep++ = '\t';
2350 if (test_is_valid) {
2351 cswritep = dtoa_g(primary_se / u31tod(cur_constraint_ct), cswritep);
2352 } else {
2353 cswritep = strcpya_k(cswritep, "NA");
2354 }
2355 }
2356 // could avoid recomputing
2357 if (test_is_valid) {
2358 ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
2359 }
2360 }
2361 if (p_col) {
2362 *cswritep++ = '\t';
2363 if (test_is_valid) {
2364 if (report_neglog10p) {
2365 const double reported_val = (-kRecipLn10) * ln_pval;
2366 cswritep = dtoa_g(reported_val, cswritep);
2367 } else {
2368 const double reported_ln = MAXV(ln_pval, output_min_ln);
2369 cswritep = lntoa_g(reported_ln, cswritep);
2370 }
2371 } else {
2372 cswritep = strcpya_k(cswritep, "NA");
2373 }
2374 }
2375 if (err_col) {
2376 *cswritep++ = '\t';
2377 if (test_is_valid) {
2378 *cswritep++ = '.';
2379 } else {
2380 uint64_t glm_errcode;
2381 memcpy(&glm_errcode, &(beta_se_iter[2 * test_idx]), 8);
2382 cswritep = AppendGlmErrstr(glm_errcode, cswritep);
2383 }
2384 }
2385 AppendBinaryEoln(&cswritep);
2386 if (unlikely(Cswrite(&css, &cswritep))) {
2387 goto GlmLinear_ret_WRITE_FAIL;
2388 }
2389 if ((test_idx == primary_reported_test_idx) && allele_is_valid) {
2390 if (orig_ln_pvals) {
2391 orig_ln_pvals[valid_allele_ct] = ln_pval;
2392 }
2393 }
2394 }
2395 }
2396 GlmLinear_allele_iterate:
2397 ++allele_bidx;
2398 valid_allele_ct += allele_is_valid;
2399 if (valid_alleles && allele_is_valid) {
2400 SetBit(allele_idx_offset_base + a1_allele_idx, valid_alleles);
2401 }
2402 if (!beta_se_multiallelic_fused) {
2403 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
2404 }
2405 }
2406 if (beta_se_multiallelic_fused) {
2407 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
2408 }
2409 if ((!variant_is_valid) && valid_alleles) {
2410 ClearBit(write_variant_uidx, valid_variants);
2411 }
2412 }
2413 }
2414 if (variant_idx == variant_ct) {
2415 break;
2416 }
2417 if (variant_idx >= next_print_variant_idx) {
2418 if (pct > 10) {
2419 putc_unlocked('\b', stdout);
2420 }
2421 pct = (variant_idx * 100LLU) / variant_ct;
2422 printf("\b\b%u%%", pct++);
2423 fflush(stdout);
2424 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
2425 }
2426 ++read_block_idx;
2427 prev_block_variant_ct = cur_block_variant_ct;
2428 variant_idx += cur_block_variant_ct;
2429 // crucially, this is independent of the PgenReader block_base
2430 // pointers
2431 pgfip->block_base = main_loadbufs[parity];
2432 }
2433 if (unlikely(CswriteCloseNull(&css, cswritep))) {
2434 goto GlmLinear_ret_WRITE_FAIL;
2435 }
2436 if (pct > 10) {
2437 putc_unlocked('\b', stdout);
2438 }
2439 fputs("\b\b", stdout);
2440 logputs("done.\n");
2441 logprintf("Results written to %s .\n", outname);
2442 *valid_allele_ct_ptr = valid_allele_ct;
2443 }
2444 while (0) {
2445 GlmLinear_ret_NOMEM:
2446 reterr = kPglRetNomem;
2447 break;
2448 GlmLinear_ret_TSTREAM_FAIL:
2449 TextStreamErrPrint("--glm local-covar= file", local_covar_txsp);
2450 break;
2451 GlmLinear_ret_PGR_FAIL:
2452 PgenErrPrintN(reterr);
2453 break;
2454 GlmLinear_ret_WRITE_FAIL:
2455 reterr = kPglRetWriteFail;
2456 break;
2457 GlmLinear_ret_INCONSISTENT_INPUT:
2458 reterr = kPglRetInconsistentInput;
2459 break;
2460 GlmLinear_ret_THREAD_CREATE_FAIL:
2461 reterr = kPglRetThreadCreateFail;
2462 break;
2463 }
2464 GlmLinear_ret_1:
2465 CleanupThreads(&tg);
2466 CswriteCloseCond(&css, cswritep);
2467 BigstackReset(bigstack_mark);
2468 pgfip->block_base = nullptr;
2469 return reterr;
2470 }
2471
2472 uintptr_t GetLinearSubbatchWorkspaceSize(uint32_t sample_ct, uint32_t subbatch_size, uint32_t biallelic_predictor_ct, uint32_t max_extra_allele_ct, uint32_t constraint_ct, uint32_t xmain_ct, uint32_t max_returned_difflist_len) {
2473 // sample_ct * max_predictor_ct < 2^31, sample_ct * subbatch_size < 2^31,
2474 // subbatch_size <= 240, and max_predictor_ct < sqrt(2^31), so no overflows
2475
2476 // sample_nm, tmp_nm = sample_ctl words
2477 uintptr_t workspace_size = 2 * RoundUpPow2(BitCtToWordCt(sample_ct) * sizeof(intptr_t), kCacheline);
2478
2479 // nm_pheno_buf = sample_ct * subbatch_size doubles
2480 workspace_size += RoundUpPow2(sample_ct * subbatch_size * sizeof(double), kCacheline);
2481
2482 const uint32_t max_predictor_ct = biallelic_predictor_ct + max_extra_allele_ct;
2483 // predictors_pmaj = (max_predictor_ct + main_mutated + main_omitted) *
2484 // sample_ct doubles
2485 workspace_size += RoundUpPow2((max_predictor_ct + xmain_ct) * sample_ct * sizeof(double), kCacheline);
2486
2487 // xtx_inv, xtx_inv2 = max_predictor_ct * max_predictor_ct doubles
2488 workspace_size += 2 * RoundUpPow2(max_predictor_ct * max_predictor_ct * sizeof(double), kCacheline);
2489
2490 // dbl_2d_buf = max_predictor_ct * max(max_predictor_ct, 7) doubles
2491 workspace_size += RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
2492
2493 // inverse_corr_buf = (max_predictor_ct - 1) * max(max_predictor_ct - 1, 4) doubles
2494 workspace_size += RoundUpPow2((max_predictor_ct - 1) * MAXV((max_predictor_ct - 1), 4) * sizeof(double), kCacheline);
2495
2496 // semicomputed_biallelic_corr_matrix = (max_predictor_ct - 1)^2 doubles
2497 workspace_size += RoundUpPow2((biallelic_predictor_ct - 1) * (biallelic_predictor_ct - 1) * sizeof(double), kCacheline);
2498
2499 // semicomputed_biallelic_inv_corr_sqrts = biallelic_predictor_ct doubles
2500 workspace_size += RoundUpPow2(biallelic_predictor_ct * sizeof(double), kCacheline);
2501
2502 // fitted_coefs, xt_y = max_predictor_ct * subbatch_size doubles
2503 workspace_size += 2 * RoundUpPow2(max_predictor_ct * subbatch_size * sizeof(double), kCacheline);
2504
2505 // inv_1d_buf
2506 workspace_size += RoundUpPow2(MAXV(max_predictor_ct, constraint_ct) * kMatrixInvertBuf1CheckedAlloc, kCacheline);
2507
2508 // machr2_dosage_sums, machr2_dosage_ssqs
2509 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(uint64_t) * 2, kCacheline);
2510
2511 // raregeno
2512 workspace_size += DivUp(max_returned_difflist_len, kNypsPerCacheline) * kCacheline;
2513
2514 // difflist_sample_ids
2515 workspace_size += DivUp(max_returned_difflist_len, kInt32PerCacheline) * kCacheline;
2516
2517 // pheno_ssq_bases, geno_pheno_prods, domdev_pheno_prods: subbatch_size
2518 workspace_size += 3 * RoundUpPow2(subbatch_size * sizeof(double), kCacheline);
2519
2520 if (constraint_ct) {
2521 // tmphxs_buf, h_transpose_buf = constraint_ct * max_predictor_ct doubles
2522 workspace_size += 2 * RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(double), kCacheline);
2523
2524 // inner_buf = constraint_ct * constraint_ct
2525 workspace_size += RoundUpPow2(constraint_ct * constraint_ct * sizeof(double), kCacheline);
2526
2527 // cur_constraints_con_major = constraint_ct * max_predictor_ct doubles
2528 workspace_size += RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(double), kCacheline);
2529 }
2530 return workspace_size;
2531 }
2532
2533 THREAD_FUNC_DECL GlmLinearSubbatchThread(void* raw_arg) {
2534 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
2535 const uintptr_t tidx = arg->tidx;
2536 GlmLinearCtx* ctx = S_CAST(GlmLinearCtx*, arg->sharedp->context);
2537 GlmCtx* common = ctx->common;
2538
2539 PgenReader* pgrp = common->pgr_ptrs[tidx];
2540 PgenVariant pgv;
2541 pgv.genovec = common->genovecs[tidx];
2542 pgv.dosage_present = nullptr;
2543 pgv.dosage_main = nullptr;
2544 pgv.dosage_ct = 0;
2545 if (common->dosage_presents) {
2546 pgv.dosage_present = common->dosage_presents[tidx];
2547 pgv.dosage_main = common->dosage_mains[tidx];
2548 }
2549 unsigned char* workspace_buf = common->workspace_bufs[tidx];
2550 const uintptr_t* variant_include = common->variant_include;
2551 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
2552 const AlleleCode* omitted_alleles = common->omitted_alleles;
2553 const uintptr_t* sex_male_collapsed = common->sex_male_collapsed;
2554 const ChrInfo* cip = common->cip;
2555 const uint32_t* subset_chr_fo_vidx_start = common->subset_chr_fo_vidx_start;
2556 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
2557 const GlmFlags glm_flags = common->glm_flags;
2558 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
2559 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
2560 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
2561 const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
2562 const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
2563 const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
2564 const uint32_t joint_genotypic = (glm_flags / kfGlmGenotypic) & 1;
2565 const uint32_t joint_hethom = (glm_flags / kfGlmHethom) & 1;
2566 const uint32_t domdev_present = joint_genotypic || joint_hethom;
2567 const uint32_t domdev_present_p1 = domdev_present + 1;
2568 const uint32_t reported_pred_uidx_start = 1 - include_intercept;
2569 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
2570 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
2571 const uint32_t is_xchr_model_1 = common->is_xchr_model_1;
2572 const double max_corr = common->max_corr;
2573 const double vif_thresh = common->vif_thresh;
2574 const uintptr_t max_reported_test_ct = common->max_reported_test_ct;
2575 const uintptr_t local_covar_ct = common->local_covar_ct;
2576 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
2577 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!model_dominant) && (!model_recessive) && (!model_hetonly) && (!common->tests_flag) && (!add_interactions);
2578 const uint32_t subbatch_size = ctx->subbatch_size;
2579 uintptr_t max_sample_ct = MAXV(common->sample_ct, common->sample_ct_x);
2580 if (max_sample_ct < common->sample_ct_y) {
2581 max_sample_ct = common->sample_ct_y;
2582 }
2583 pgv.patch_01_set = nullptr;
2584 pgv.patch_01_vals = nullptr;
2585 pgv.patch_10_set = nullptr;
2586 pgv.patch_10_vals = nullptr;
2587 if (common->thread_mhc) {
2588 const uint32_t max_sample_ctl = BitCtToWordCt(max_sample_ct);
2589 pgv.patch_01_set = common->thread_mhc[tidx];
2590 pgv.patch_01_vals = R_CAST(AlleleCode*, &(pgv.patch_01_set[max_sample_ctl]));
2591 AlleleCode* patch_01_vals_end = &(pgv.patch_01_vals[max_sample_ct]);
2592 AlignACToVec(&patch_01_vals_end);
2593 pgv.patch_10_set = R_CAST(uintptr_t*, patch_01_vals_end);
2594 pgv.patch_10_vals = R_CAST(AlleleCode*, &(pgv.patch_10_set[max_sample_ctl]));
2595 }
2596 pgv.patch_01_ct = 0;
2597 pgv.patch_10_ct = 0;
2598 pgv.multidosage_sample_ct = 0;
2599 uint32_t variant_idx_offset = 0;
2600 uint32_t allele_ct = 2;
2601 uint32_t omitted_allele_idx = 0;
2602 uint32_t extra_regression_ct = 0;
2603 double main_dosage_sum = 0.0;
2604 double main_dosage_ssq = 0.0;
2605 double covarless_inverse_buf[9];
2606 for (uint32_t uii = 1; uii != 9; ++uii) {
2607 covarless_inverse_buf[uii] = 0.0;
2608 }
2609 uint32_t max_sparse = 0;
2610 uint32_t difflist_len = 0;
2611 uint32_t parity = 0;
2612 uint64_t new_err_info = 0;
2613 do {
2614 const uintptr_t cur_block_variant_ct = common->cur_block_variant_ct;
2615 uint32_t variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct;
2616 const uint32_t variant_bidx_end = ((tidx + 1) * cur_block_variant_ct) / calc_thread_ct;
2617 uintptr_t variant_uidx_base;
2618 uintptr_t variant_include_bits;
2619 BitIter1Start(variant_include, common->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
2620
2621 uintptr_t allele_bidx = variant_bidx;
2622 if (max_extra_allele_ct) {
2623 allele_bidx = variant_bidx + CountExtraAlleles(variant_include, allele_idx_offsets, common->read_variant_uidx_starts[0], common->read_variant_uidx_starts[tidx], 0);
2624 }
2625 double* beta_se_iter = common->block_beta_se;
2626 if (beta_se_multiallelic_fused) {
2627 beta_se_iter = &(beta_se_iter[(2 * k1LU * subbatch_size) * max_reported_test_ct * variant_bidx]);
2628 } else {
2629 beta_se_iter = &(beta_se_iter[(2 * k1LU * subbatch_size) * max_reported_test_ct * allele_bidx]);
2630 }
2631
2632 LinearAuxResult* block_aux_iter = &(ctx->block_aux[allele_bidx]);
2633 const double* local_covars_iter = nullptr;
2634 if (local_covar_ct) {
2635 // &(nullptr[0]) is okay in C++, but undefined in C
2636 local_covars_iter = &(ctx->local_covars_vcmaj_d[parity][variant_bidx * max_sample_ct * local_covar_ct]);
2637 }
2638 while (variant_bidx < variant_bidx_end) {
2639 const uint32_t variant_idx = variant_bidx + variant_idx_offset;
2640 const uint32_t chr_fo_idx = LastLeqU32(subset_chr_fo_vidx_start, 0, cip->chr_ct, variant_idx);
2641 // const uint32_t chr_fo_idx = LowerBoundNonemptyU32(&(subset_chr_fo_vidx_start[1]), cip->chr_ct, variant_idx + 1);
2642 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
2643 uint32_t cur_variant_bidx_end = subset_chr_fo_vidx_start[chr_fo_idx + 1] - variant_idx_offset;
2644 if (cur_variant_bidx_end > variant_bidx_end) {
2645 cur_variant_bidx_end = variant_bidx_end;
2646 }
2647 const uint32_t is_haploid = IsSet(cip->haploid_mask, chr_idx);
2648 const uint32_t is_regular_x = is_haploid && (chr_idx == x_code);
2649 const uint32_t is_y = (chr_idx == y_code);
2650 const uint32_t is_nonx_haploid = is_haploid && (!is_regular_x);
2651 const uintptr_t* cur_sample_include;
2652 const uint32_t* cur_sample_include_cumulative_popcounts;
2653 const double* cur_pheno_pmaj;
2654 const RegressionNmPrecomp* nm_precomp;
2655 const double* cur_covars_cmaj;
2656 const uintptr_t* cur_parameter_subset;
2657 const uintptr_t* cur_joint_test_params;
2658 uint32_t cur_sample_ct;
2659 uint32_t cur_covar_ct;
2660 uint32_t cur_constraint_ct;
2661 if (is_y && common->sample_include_y) {
2662 cur_sample_include = common->sample_include_y;
2663 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
2664 cur_pheno_pmaj = ctx->pheno_y_d;
2665 nm_precomp = common->nm_precomp_y;
2666 cur_covars_cmaj = ctx->covars_cmaj_y_d;
2667 cur_parameter_subset = common->parameter_subset_y;
2668 cur_joint_test_params = common->joint_test_params_y;
2669 cur_sample_ct = common->sample_ct_y;
2670 cur_covar_ct = common->covar_ct_y;
2671 cur_constraint_ct = common->constraint_ct_y;
2672 } else if (is_regular_x && common->sample_include_x) {
2673 cur_sample_include = common->sample_include_x;
2674 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
2675 cur_pheno_pmaj = ctx->pheno_x_d;
2676 nm_precomp = common->nm_precomp_x;
2677 cur_covars_cmaj = ctx->covars_cmaj_x_d;
2678 cur_parameter_subset = common->parameter_subset_x;
2679 cur_joint_test_params = common->joint_test_params_x;
2680 cur_sample_ct = common->sample_ct_x;
2681 cur_covar_ct = common->covar_ct_x;
2682 cur_constraint_ct = common->constraint_ct_x;
2683 } else {
2684 cur_sample_include = common->sample_include;
2685 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
2686 cur_pheno_pmaj = ctx->pheno_d;
2687 nm_precomp = common->nm_precomp;
2688 cur_covars_cmaj = ctx->covars_cmaj_d;
2689 cur_parameter_subset = common->parameter_subset;
2690 cur_joint_test_params = common->joint_test_params;
2691 cur_sample_ct = common->sample_ct;
2692 cur_covar_ct = common->covar_ct;
2693 cur_constraint_ct = common->constraint_ct;
2694 }
2695 const uint32_t sample_ctl = BitCtToWordCt(cur_sample_ct);
2696 const uint32_t sample_ctl2 = NypCtToWordCt(cur_sample_ct);
2697 const uint32_t cur_biallelic_predictor_ct_base = 2 + domdev_present + cur_covar_ct * (1 + add_interactions * domdev_present_p1);
2698 uint32_t cur_biallelic_predictor_ct = cur_biallelic_predictor_ct_base;
2699 uint32_t literal_covar_ct = cur_covar_ct;
2700 if (cur_parameter_subset) {
2701 cur_biallelic_predictor_ct = PopcountWords(cur_parameter_subset, BitCtToWordCt(cur_biallelic_predictor_ct_base));
2702 literal_covar_ct = PopcountBitRange(cur_parameter_subset, 2 + domdev_present, 2 + domdev_present + cur_covar_ct);
2703 }
2704 const uint32_t max_predictor_ct = cur_biallelic_predictor_ct + max_extra_allele_ct;
2705 uint32_t reported_pred_uidx_biallelic_end;
2706 if (hide_covar) {
2707 if (!cur_parameter_subset) {
2708 reported_pred_uidx_biallelic_end = 2 + domdev_present;
2709 } else {
2710 reported_pred_uidx_biallelic_end = IsSet(cur_parameter_subset, 1) + domdev_present_p1;
2711 }
2712 } else {
2713 reported_pred_uidx_biallelic_end = cur_biallelic_predictor_ct;
2714 }
2715 // nm_predictors_pmaj_buf may require up to two extra columns omitted
2716 // from the main regression.
2717 // 1. In the multiallelic dominant/recessive/hetonly/hethom cases, the
2718 // original genotype column does not appear in the regression, and
2719 // we'd rather not reconstruct it from genovec, etc. when we need to
2720 // swap it out for another allele, so we keep the original genotype in
2721 // an extra column.
2722 // To reduce code bloat, we now handle the biallelic cases in the same
2723 // way; this is one of the more peripheral code paths so adding more
2724 // complexity to speed it up is less justifiable.
2725 // 2. If --parameters excludes the main (possibly
2726 // dominant/recessive/hetonly) genotype column but does care about an
2727 // interaction, we want a copy of what the main genotype column's
2728 // contents would have been to refer to.
2729 const uint32_t main_omitted = cur_parameter_subset && (!IsSet(cur_parameter_subset, 1));
2730 const uint32_t main_mutated = model_dominant || model_recessive || model_hetonly || joint_hethom;
2731 unsigned char* workspace_iter = workspace_buf;
2732 uintptr_t* sample_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
2733 uintptr_t* tmp_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
2734 double* nm_pheno_buf = S_CAST(double*, arena_alloc_raw_rd(cur_sample_ct * subbatch_size * sizeof(double), &workspace_iter));
2735 double* nm_predictors_pmaj_buf = S_CAST(double*, arena_alloc_raw_rd((max_predictor_ct + main_mutated + main_omitted) * cur_sample_ct * sizeof(double), &workspace_iter));
2736 double* xtx_inv = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ct * sizeof(double), &workspace_iter));
2737 double* fitted_coefs = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * subbatch_size * sizeof(double), &workspace_iter));
2738 double* xt_y = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * subbatch_size * sizeof(double), &workspace_iter));
2739 double* semicomputed_biallelic_corr_matrix = S_CAST(double*, arena_alloc_raw_rd((cur_biallelic_predictor_ct - 1) * (cur_biallelic_predictor_ct - 1) * sizeof(double), &workspace_iter));
2740 double* semicomputed_biallelic_inv_corr_sqrts = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
2741 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, arena_alloc_raw_rd(MAXV(max_predictor_ct, cur_constraint_ct) * kMatrixInvertBuf1CheckedAlloc, &workspace_iter));
2742 double* dbl_2d_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), &workspace_iter));
2743 uint64_t* machr2_dosage_sums = S_CAST(uint64_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(uint64_t) * 2, &workspace_iter));
2744 uint64_t* machr2_dosage_ssqs = &(machr2_dosage_sums[max_extra_allele_ct + 2]);
2745 double* pheno_ssq_bases = S_CAST(double*, arena_alloc_raw_rd(subbatch_size * sizeof(double), &workspace_iter));
2746 double* geno_pheno_prods = S_CAST(double*, arena_alloc_raw_rd(subbatch_size * sizeof(double), &workspace_iter));
2747 double* domdev_pheno_prods = S_CAST(double*, arena_alloc_raw_rd(subbatch_size * sizeof(double), &workspace_iter));
2748 double* xtx_inv2 = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ct * sizeof(double), &workspace_iter));
2749
2750 // could technically have this overlap fitted_coefs/xt_y, but that sets
2751 // the stage for future bugs
2752 double* inverse_corr_buf = S_CAST(double*, arena_alloc_raw_rd((max_predictor_ct - 1) * MAXV((max_predictor_ct - 1), 4) * sizeof(double), &workspace_iter));
2753
2754 const uint32_t sparse_optimization_eligible = (!is_regular_x) && nm_precomp;
2755 const uint32_t difflist_eligible = sparse_optimization_eligible && (!pgv.dosage_present) && (!cur_covar_ct);
2756 uintptr_t* raregeno = nullptr;
2757 uint32_t* difflist_sample_ids = nullptr;
2758 if (difflist_eligible) {
2759 max_sparse = cur_sample_ct / kPglMaxDifflistLenDivisor;
2760 const uint32_t max_returned_difflist_len = ctx->max_returned_difflist_len;
2761 raregeno = S_CAST(uintptr_t*, arena_alloc_raw(DivUp(max_returned_difflist_len, kNypsPerCacheline) * kCacheline, &workspace_iter));
2762 difflist_sample_ids = S_CAST(uint32_t*, arena_alloc_raw(DivUp(max_returned_difflist_len, kInt32PerCacheline) * kCacheline, &workspace_iter));
2763 }
2764
2765 // joint test only
2766 double* tmphxs_buf = nullptr;
2767 double* h_transpose_buf = nullptr;
2768 double* inner_buf = nullptr;
2769 double* cur_constraints_con_major = nullptr;
2770 if (cur_constraint_ct) {
2771 tmphxs_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
2772 h_transpose_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
2773 inner_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * cur_constraint_ct * sizeof(double), &workspace_iter));
2774 cur_constraints_con_major = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
2775 ZeroDArr(cur_constraint_ct * max_predictor_ct, cur_constraints_con_major);
2776 const uint32_t first_joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
2777 cur_constraints_con_major[first_joint_test_idx] = 1.0;
2778 // Rest of this matrix must be updated later, since cur_predictor_ct
2779 // changes at multiallelic variants.
2780 }
2781 assert(S_CAST(uintptr_t, workspace_iter - workspace_buf) <= GetLinearSubbatchWorkspaceSize(cur_sample_ct, subbatch_size, cur_biallelic_predictor_ct, max_extra_allele_ct, cur_constraint_ct, main_mutated + main_omitted, ctx->max_returned_difflist_len));
2782 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
2783 const double* cur_pheno = &(cur_pheno_pmaj[pheno_idx * cur_sample_ct]);
2784 pheno_ssq_bases[pheno_idx] = DotprodD(cur_pheno, cur_pheno, cur_sample_ct);
2785 }
2786 const double cur_sample_ct_recip = 1.0 / u31tod(cur_sample_ct);
2787 const double cur_sample_ct_m1_recip = 1.0 / u31tod(cur_sample_ct - 1);
2788 double geno_d_lookup[2];
2789 if (sparse_optimization_eligible) {
2790 if (model_hetonly) {
2791 geno_d_lookup[0] = 1.0;
2792 geno_d_lookup[1] = 0.0;
2793 } else {
2794 geno_d_lookup[1] = 1.0;
2795 if (is_nonx_haploid) {
2796 geno_d_lookup[0] = 0.5;
2797 } else if (model_recessive || joint_hethom) {
2798 geno_d_lookup[0] = 0.0;
2799 } else {
2800 geno_d_lookup[0] = 1.0;
2801 if (!model_dominant) {
2802 geno_d_lookup[1] = 2.0;
2803 }
2804 }
2805 }
2806 }
2807 const double* xtx_image = nullptr;
2808 const double* covarx_dotprod_inv = nullptr;
2809 const double* corr_inv = nullptr;
2810 const double* xt_y_image = nullptr;
2811 if (nm_precomp) {
2812 xtx_image = nm_precomp->xtx_image;
2813 covarx_dotprod_inv = nm_precomp->covarx_dotprod_inv;
2814 corr_inv = nm_precomp->corr_inv;
2815 const uintptr_t nongeno_pred_ct = cur_biallelic_predictor_ct - domdev_present - 2;
2816 const uintptr_t nonintercept_biallelic_pred_ct = cur_biallelic_predictor_ct - 1;
2817 memcpy(semicomputed_biallelic_corr_matrix, nm_precomp->corr_image, nonintercept_biallelic_pred_ct * nonintercept_biallelic_pred_ct * sizeof(double));
2818 memcpy(&(semicomputed_biallelic_inv_corr_sqrts[domdev_present_p1]), nm_precomp->corr_inv_sqrts, nongeno_pred_ct * sizeof(double));
2819 xt_y_image = nm_precomp->xt_y_image;
2820 }
2821 PgrSampleSubsetIndex pssi;
2822 PgrSetSampleSubsetIndex(cur_sample_include_cumulative_popcounts, pgrp, &pssi);
2823 // when this is set, the last fully-processed variant had no missing
2824 // genotypes, and if the current variant also has no missing genotypes we
2825 // may be able to skip reinitialization of most of
2826 // nm_predictors_pmaj_buf.
2827 uint32_t prev_nm = 0;
2828 uint32_t prev_nm_sample_ct = 0;
2829
2830 STD_ARRAY_DECL(uint32_t, 4, genocounts);
2831 for (; variant_bidx != cur_variant_bidx_end; ++variant_bidx) {
2832 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
2833 if (allele_idx_offsets) {
2834 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
2835 if (!beta_se_multiallelic_fused) {
2836 extra_regression_ct = allele_ct - 2;
2837 }
2838 }
2839 const uint32_t allele_ct_m2 = allele_ct - 2;
2840 const uint32_t expected_predictor_ct = cur_biallelic_predictor_ct + allele_ct_m2;
2841 uint32_t difflist_common_geno = UINT32_MAX;
2842 PglErr reterr;
2843 if (!allele_ct_m2) {
2844 if (difflist_eligible) {
2845 reterr = PgrGetDifflistOrGenovec(cur_sample_include, pssi, cur_sample_ct, max_sparse, variant_uidx, pgrp, pgv.genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len);
2846 } else {
2847 reterr = PgrGetD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
2848 }
2849 } else {
2850 reterr = PgrGetMD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, &pgv);
2851 // todo: proper multiallelic dosage support
2852 }
2853 if (unlikely(reterr)) {
2854 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
2855 goto GlmLinearSubbatchThread_err;
2856 }
2857 if (omitted_alleles) {
2858 omitted_allele_idx = omitted_alleles[variant_uidx];
2859 }
2860 uint32_t missing_ct;
2861 if (difflist_common_geno == 2 * omitted_allele_idx) {
2862 ZeroTrailingNyps(difflist_len, raregeno);
2863 GenoarrCountFreqsUnsafe(raregeno, difflist_len, genocounts);
2864 genocounts[difflist_common_geno] = cur_sample_ct - difflist_len;
2865 missing_ct = genocounts[3];
2866 } else {
2867 if (difflist_common_geno <= 2) {
2868 PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, cur_sample_ct, difflist_len, pgv.genovec);
2869 difflist_common_geno = UINT32_MAX;
2870 }
2871 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
2872 GenoarrCountFreqsUnsafe(pgv.genovec, cur_sample_ct, genocounts);
2873 missing_ct = genocounts[3];
2874 if (!missing_ct) {
2875 SetAllBits(cur_sample_ct, sample_nm);
2876 } else {
2877 GenoarrToNonmissing(pgv.genovec, cur_sample_ct, sample_nm);
2878 if (pgv.dosage_ct) {
2879 BitvecOr(pgv.dosage_present, sample_ctl, sample_nm);
2880 missing_ct = cur_sample_ct - PopcountWords(sample_nm, sample_ctl);
2881 }
2882 }
2883 }
2884 uintptr_t const_alleles[DivUp(kPglMaxAlleleCt, kBitsPerWord)];
2885 const uint32_t allele_ctl = DivUp(allele_ct, kBitsPerWord);
2886 ZeroWArr(allele_ctl, const_alleles);
2887 const uint32_t nm_sample_ct = cur_sample_ct - missing_ct;
2888 const uint32_t nm_sample_ctl = BitCtToWordCt(nm_sample_ct);
2889 // first predictor column: intercept
2890 if (!prev_nm) {
2891 assert((!prev_nm_sample_ct) || (nm_predictors_pmaj_buf[prev_nm_sample_ct - 1] == 1.0));
2892 for (uint32_t sample_idx = prev_nm_sample_ct; sample_idx < nm_sample_ct; ++sample_idx) {
2893 nm_predictors_pmaj_buf[sample_idx] = 1.0;
2894 }
2895 }
2896 prev_nm_sample_ct = nm_sample_ct;
2897 // second predictor column: main genotype
2898 double* genotype_vals = &(nm_predictors_pmaj_buf[nm_sample_ct]);
2899 if (main_mutated || main_omitted) {
2900 genotype_vals = &(nm_predictors_pmaj_buf[expected_predictor_ct * nm_sample_ct]);
2901 }
2902 uint32_t sparse_optimization = 0;
2903 double* multi_start = nullptr;
2904 if (!allele_ct_m2) {
2905 // When there are no dosages, and either:
2906 // prev_nm is set and missing_ct is zero, or
2907 // there are no covariates,
2908 // we don't need to call MultiplySelfTranspose() on
2909 // nm_predictors_pmaj_buf to get all the predictor x predictor dot
2910 // products; instead we patch in the genotype x predictor dot
2911 // products that may change, copying the rest from xtx_image.
2912 // As a side effect, it is no longer strictly necessary to fill the
2913 // genotype row of nm_predictors_pmaj_buf. sparse_optimization
2914 // indicates that plink 1.9's QT --assoc sparse dot product algorithm
2915 // will be used instead.
2916 // probable todos: allow a few dosages to be present, cover chrX
2917 // case.
2918 if (omitted_allele_idx) {
2919 if (difflist_common_geno != UINT32_MAX) {
2920 assert(difflist_common_geno == 2);
2921 GenovecInvertUnsafe(difflist_len, raregeno);
2922 ZeroTrailingNyps(difflist_len, raregeno);
2923 difflist_common_geno = 0;
2924 } else {
2925 GenovecInvertUnsafe(cur_sample_ct, pgv.genovec);
2926 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
2927 if (pgv.dosage_ct) {
2928 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
2929 }
2930 }
2931 const uint32_t uii = genocounts[0];
2932 genocounts[0] = genocounts[2];
2933 genocounts[2] = uii;
2934 }
2935 uint64_t dosage_sum = (genocounts[1] + 2 * genocounts[2]) * 0x4000LLU;
2936 uint64_t dosage_ssq = (genocounts[1] + 4LLU * genocounts[2]) * 0x10000000LLU;
2937 if (!missing_ct) {
2938 // originally had genocounts[0] > 0.875 * nm_sample_ct threshold,
2939 // but then tried this on high-MAF data and it was still
2940 // substantially faster
2941 sparse_optimization = sparse_optimization_eligible && (!pgv.dosage_ct) && (prev_nm || (!cur_covar_ct));
2942 if (!sparse_optimization) {
2943 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, genotype_vals);
2944 if (pgv.dosage_ct) {
2945 uintptr_t sample_idx_base = 0;
2946 uintptr_t dosage_present_bits = pgv.dosage_present[0];
2947 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
2948 const uintptr_t sample_idx = BitIter1(pgv.dosage_present, &sample_idx_base, &dosage_present_bits);
2949 const uintptr_t dosage_val = pgv.dosage_main[dosage_idx];
2950 // 32768 -> 2, 16384 -> 1, 0 -> 0
2951 genotype_vals[sample_idx] = kRecipDosageMid * swtod(dosage_val);
2952 dosage_sum += dosage_val;
2953 dosage_ssq += dosage_val * dosage_val;
2954 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_idx);
2955 if (cur_geno && (cur_geno != 3)) {
2956 const uintptr_t prev_val = cur_geno * kDosageMid;
2957 dosage_sum -= prev_val;
2958 dosage_ssq -= prev_val * prev_val;
2959 }
2960 }
2961 }
2962 }
2963 } else {
2964 if (!pgv.dosage_ct) {
2965 sparse_optimization = sparse_optimization_eligible && (!cur_covar_ct);
2966 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, genotype_vals);
2967 } else {
2968 uintptr_t sample_midx_base = 0;
2969 uintptr_t sample_nm_bits = sample_nm[0];
2970 uint32_t dosage_idx = 0;
2971 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2972 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
2973 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_midx);
2974 double cur_val;
2975 if (IsSet(pgv.dosage_present, sample_midx)) {
2976 const uintptr_t dosage_val = pgv.dosage_main[dosage_idx++];
2977 cur_val = kRecipDosageMid * swtod(dosage_val);
2978 dosage_sum += dosage_val;
2979 dosage_ssq += dosage_val * dosage_val;
2980 if (cur_geno && (cur_geno != 3)) {
2981 const uintptr_t prev_val = cur_geno * kDosageMid;
2982 dosage_sum -= prev_val;
2983 dosage_ssq -= prev_val * prev_val;
2984 }
2985 } else {
2986 cur_val = kSmallDoubles[cur_geno];
2987 }
2988 genotype_vals[sample_idx] = cur_val;
2989 }
2990 }
2991 }
2992 // Check for constant genotype column.
2993 // (Technically, we should recheck later in the chrX no-sex-covariate
2994 // --xchr-model 1 corner case.)
2995 if (!pgv.dosage_ct) {
2996 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
2997 const_alleles[0] = 3;
2998 }
2999 } else if (pgv.dosage_ct == nm_sample_ct) {
3000 if (DosageIsConstant(dosage_sum, dosage_ssq, nm_sample_ct)) {
3001 const_alleles[0] = 3;
3002 }
3003 }
3004 machr2_dosage_sums[1 - omitted_allele_idx] = dosage_sum;
3005 machr2_dosage_ssqs[1 - omitted_allele_idx] = dosage_ssq;
3006 machr2_dosage_sums[omitted_allele_idx] = kDosageMax * S_CAST(uint64_t, nm_sample_ct) - dosage_sum;
3007 machr2_dosage_ssqs[omitted_allele_idx] = kDosageMax * (kDosageMax * S_CAST(uint64_t, nm_sample_ct) - 2 * dosage_sum) + dosage_ssq;
3008 } else {
3009 // multiallelic.
3010 // If some but not all alleles have constant dosages, we remove just
3011 // those alleles from the regressions; trim-alts is not necessary to
3012 // see what's going on with the other alleles. To reduce parsing
3013 // complexity, the number of output lines is not affected by this;
3014 // the ones corresponding to the constant alleles have NA values.
3015 // Punt on sparse_optimization for now; may be worth revisiting after
3016 // multiallelic dosage implemented.
3017 // dosage_ct == 0 temporarily guaranteed if we reach here.
3018 assert(!pgv.dosage_ct);
3019 multi_start = &(nm_predictors_pmaj_buf[(expected_predictor_ct - allele_ct_m2) * nm_sample_ct]);
3020 ZeroU64Arr(allele_ct, machr2_dosage_sums);
3021 ZeroU64Arr(allele_ct, machr2_dosage_ssqs);
3022 // postpone multiply for now, since no multiallelic dosages
3023 machr2_dosage_sums[0] = genocounts[1] + 2 * genocounts[0];
3024 machr2_dosage_ssqs[0] = genocounts[1] + 4LLU * genocounts[0];
3025 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
3026 SetBit(0, const_alleles);
3027 }
3028 if (omitted_allele_idx) {
3029 // Main genotype column starts as REF.
3030 if (!missing_ct) {
3031 GenoarrLookup16x8bx2(pgv.genovec, kSmallInvDoublePairs, nm_sample_ct, genotype_vals);
3032 } else {
3033 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallInvDoubles, cur_sample_ct, genotype_vals);
3034 }
3035 }
3036 uint32_t rare_allele_ct = allele_ct_m2;
3037 double* alt1_start = nullptr;
3038 double* rarealt_start = multi_start;
3039 if (omitted_allele_idx != 1) {
3040 if (omitted_allele_idx) {
3041 alt1_start = multi_start;
3042 rarealt_start = &(rarealt_start[nm_sample_ct]);
3043 --rare_allele_ct;
3044 } else {
3045 alt1_start = genotype_vals;
3046 }
3047 if (!missing_ct) {
3048 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, alt1_start);
3049 } else {
3050 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, alt1_start);
3051 }
3052 }
3053 ZeroDArr(rare_allele_ct * nm_sample_ct, rarealt_start);
3054 // Use sums as ones[] and ssqs as twos[] for rarealts; transform to
3055 // actual sums/ssqs later.
3056 if (pgv.patch_01_ct) {
3057 const uintptr_t* patch_set_nm = pgv.patch_01_set;
3058 if (missing_ct) {
3059 CopyBitarrSubset(pgv.patch_01_set, sample_nm, nm_sample_ct, tmp_nm);
3060 patch_set_nm = tmp_nm;
3061 }
3062 uintptr_t sample_idx_base = 0;
3063 uintptr_t cur_bits = patch_set_nm[0];
3064 if (!omitted_allele_idx) {
3065 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
3066 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3067 const uint32_t allele_code = pgv.patch_01_vals[uii];
3068 rarealt_start[(allele_code - 2) * nm_sample_ct + sample_idx] = 1.0;
3069 alt1_start[sample_idx] = 0.0;
3070 machr2_dosage_sums[allele_code] += 1;
3071 }
3072 } else if (omitted_allele_idx == 1) {
3073 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
3074 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3075 const uint32_t allele_code = pgv.patch_01_vals[uii];
3076 rarealt_start[(allele_code - 2) * nm_sample_ct + sample_idx] = 1.0;
3077 machr2_dosage_sums[allele_code] += 1;
3078 }
3079 } else {
3080 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
3081 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3082 alt1_start[sample_idx] = 0.0;
3083 const uint32_t allele_code = pgv.patch_01_vals[uii];
3084 machr2_dosage_sums[allele_code] += 1;
3085 if (allele_code == omitted_allele_idx) {
3086 continue;
3087 }
3088 const uint32_t cur_col = allele_code - 2 - (allele_code > omitted_allele_idx);
3089 rarealt_start[cur_col * nm_sample_ct + sample_idx] = 1.0;
3090 }
3091 }
3092 }
3093 uintptr_t alt1_het_ct = genocounts[1] - pgv.patch_01_ct;
3094 if (pgv.patch_10_ct) {
3095 const uintptr_t* patch_set_nm = pgv.patch_10_set;
3096 if (missing_ct) {
3097 CopyBitarrSubset(pgv.patch_10_set, sample_nm, nm_sample_ct, tmp_nm);
3098 patch_set_nm = tmp_nm;
3099 }
3100 uintptr_t sample_idx_base = 0;
3101 uintptr_t cur_bits = patch_set_nm[0];
3102 if (!omitted_allele_idx) {
3103 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
3104 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3105 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
3106 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
3107 if (ac0 == ac1) {
3108 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] = 2.0;
3109 alt1_start[sample_idx] = 0.0;
3110 machr2_dosage_ssqs[ac0] += 1;
3111 } else {
3112 rarealt_start[(ac1 - 2) * nm_sample_ct + sample_idx] = 1.0;
3113 machr2_dosage_sums[ac1] += 1;
3114 if (ac0 == 1) {
3115 ++alt1_het_ct;
3116 alt1_start[sample_idx] = 1.0;
3117 } else {
3118 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] += 1.0;
3119 alt1_start[sample_idx] = 0.0;
3120 machr2_dosage_sums[ac0] += 1;
3121 }
3122 }
3123 }
3124 } else if (omitted_allele_idx == 1) {
3125 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
3126 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3127 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
3128 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
3129 if (ac0 == ac1) {
3130 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] = 2.0;
3131 machr2_dosage_ssqs[ac0] += 1;
3132 } else {
3133 rarealt_start[(ac1 - 2) * nm_sample_ct + sample_idx] = 1.0;
3134 machr2_dosage_sums[ac1] += 1;
3135 if (ac0 == 1) {
3136 ++alt1_het_ct;
3137 } else {
3138 rarealt_start[(ac0 - 2) * nm_sample_ct + sample_idx] += 1.0;
3139 machr2_dosage_sums[ac0] += 1;
3140 }
3141 }
3142 }
3143 } else {
3144 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
3145 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
3146 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
3147 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
3148 if (ac0 == ac1) {
3149 machr2_dosage_ssqs[ac0] += 1;
3150 alt1_start[sample_idx] = 0.0;
3151 if (ac0 != omitted_allele_idx) {
3152 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
3153 rarealt_start[ac0_col * nm_sample_ct + sample_idx] = 2.0;
3154 }
3155 } else {
3156 machr2_dosage_sums[ac1] += 1;
3157 if (ac1 != omitted_allele_idx) {
3158 const uint32_t ac1_col = ac1 - 2 - (ac1 > omitted_allele_idx);
3159 rarealt_start[ac1_col * nm_sample_ct + sample_idx] = 1.0;
3160 }
3161 if (ac0 == 1) {
3162 ++alt1_het_ct;
3163 alt1_start[sample_idx] = 1.0;
3164 } else {
3165 machr2_dosage_sums[ac0] += 1;
3166 alt1_start[sample_idx] = 0.0;
3167 if (ac0 != omitted_allele_idx) {
3168 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
3169 rarealt_start[ac0_col * nm_sample_ct + sample_idx] += 1.0;
3170 }
3171 }
3172 }
3173 }
3174 }
3175 }
3176 for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) {
3177 const uintptr_t one_ct = machr2_dosage_sums[allele_idx];
3178 const uintptr_t two_ct = machr2_dosage_ssqs[allele_idx];
3179 machr2_dosage_sums[allele_idx] = one_ct + 2 * two_ct;
3180 machr2_dosage_ssqs[allele_idx] = one_ct + 4LLU * two_ct;
3181 if ((one_ct == nm_sample_ct) || (two_ct == nm_sample_ct) || ((!one_ct) && (!two_ct))) {
3182 SetBit(allele_idx, const_alleles);
3183 }
3184 }
3185 const uintptr_t alt1_hom_ct = genocounts[2] - pgv.patch_10_ct;
3186 machr2_dosage_sums[1] = alt1_het_ct + 2 * alt1_hom_ct;
3187 machr2_dosage_ssqs[1] = alt1_het_ct + 4LLU * alt1_hom_ct;
3188 if ((alt1_het_ct == nm_sample_ct) || (alt1_hom_ct == nm_sample_ct) || ((!alt1_het_ct) && (!alt1_hom_ct))) {
3189 SetBit(1, const_alleles);
3190 }
3191 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
3192 machr2_dosage_sums[allele_idx] *= 0x4000LLU;
3193 machr2_dosage_ssqs[allele_idx] *= 0x10000000LLU;
3194 }
3195 }
3196 // usually need to save some of {sample_obs_ct, allele_obs_ct,
3197 // a1_dosage, mach_r2 even for skipped variants
3198 // compute them all for now, could conditionally skip later
3199 uint32_t allele_obs_ct = nm_sample_ct * 2;
3200 if (!is_regular_x) {
3201 if (is_nonx_haploid) {
3202 allele_obs_ct = nm_sample_ct;
3203 // everything is on 0..1 scale, not 0..2
3204 if (!sparse_optimization) {
3205 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3206 genotype_vals[sample_idx] *= 0.5;
3207 }
3208 const uint32_t high_ct = nm_sample_ct * allele_ct_m2;
3209 for (uint32_t uii = 0; uii != high_ct; ++uii) {
3210 multi_start[uii] *= 0.5;
3211 }
3212 }
3213 }
3214 } else {
3215 CopyBitarrSubset(sex_male_collapsed, sample_nm, nm_sample_ct, tmp_nm);
3216 const uintptr_t* male_nm = tmp_nm;
3217 const uint32_t nm_male_ct = PopcountWords(male_nm, nm_sample_ctl);
3218 if (is_xchr_model_1) {
3219 // special case: multiply male values by 0.5
3220 uintptr_t sample_idx_base = 0;
3221 uintptr_t male_nm_bits = male_nm[0];
3222 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
3223 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
3224 genotype_vals[sample_idx] *= 0.5;
3225 // could insert multiallelic loop here instead, but I'm guessing
3226 // that's worse due to locality of writes?
3227 }
3228 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
3229 double* cur_start = &(multi_start[extra_allele_idx * nm_sample_ct]);
3230 sample_idx_base = 0;
3231 male_nm_bits = male_nm[0];
3232 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
3233 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
3234 cur_start[sample_idx] *= 0.5;
3235 }
3236 }
3237 allele_obs_ct -= nm_male_ct;
3238 }
3239 }
3240 const double mach_r2 = MultiallelicDiploidMachR2(machr2_dosage_sums, machr2_dosage_ssqs, nm_sample_ct, allele_ct);
3241 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
3242 if (allele_idx == omitted_allele_idx) {
3243 continue;
3244 }
3245 block_aux_iter->sample_obs_ct = nm_sample_ct;
3246 block_aux_iter->allele_obs_ct = allele_obs_ct;
3247 double a1_dosage = u63tod(machr2_dosage_sums[allele_idx]) * kRecipDosageMid;
3248 if (is_xchr_model_1) {
3249 // ugh.
3250 double* geno_col = genotype_vals;
3251 if (allele_idx > (!omitted_allele_idx)) {
3252 geno_col = &(nm_predictors_pmaj_buf[(expected_predictor_ct - (allele_ct - allele_idx) + (allele_idx < omitted_allele_idx)) * nm_sample_ct]);
3253 }
3254 a1_dosage = 0.0;
3255 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3256 a1_dosage += geno_col[sample_idx];
3257 }
3258 if (!allele_ct_m2) {
3259 main_dosage_sum = a1_dosage;
3260 main_dosage_ssq = 0.0;
3261 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3262 const double cur_dosage = geno_col[sample_idx];
3263 main_dosage_ssq += cur_dosage * cur_dosage;
3264 }
3265 }
3266 } else {
3267 if (is_nonx_haploid) {
3268 a1_dosage *= 0.5;
3269 }
3270 if (!allele_ct_m2) {
3271 main_dosage_sum = a1_dosage;
3272 main_dosage_ssq = u63tod(machr2_dosage_ssqs[allele_idx]) * kRecipDosageMidSq;
3273 if (is_nonx_haploid) {
3274 main_dosage_ssq *= 0.25;
3275 }
3276 }
3277 }
3278 block_aux_iter->a1_dosage = a1_dosage;
3279 block_aux_iter->mach_r2 = mach_r2;
3280 ++block_aux_iter;
3281 }
3282 // now free to skip the actual regression if there are too few samples,
3283 // or there's a zero-variance genotype column
3284 GlmErr glm_err = 0;
3285 if (nm_sample_ct <= expected_predictor_ct) {
3286 glm_err = SetGlmErr0(kGlmErrcodeSampleCtLtePredictorCt);
3287 } else if (IsSet(const_alleles, omitted_allele_idx)) {
3288 glm_err = SetGlmErr0(kGlmErrcodeConstOmittedAllele);
3289 }
3290 if (glm_err) {
3291 if (missing_ct) {
3292 // covariates have not been copied yet, so we can't usually change
3293 // prev_nm from 0 to 1 when missing_ct == 0 (and there's little
3294 // reason to optimize the zero-covariate case).
3295 prev_nm = 0;
3296 }
3297 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
3298 if (beta_se_multiallelic_fused || (!hide_covar)) {
3299 reported_ct += allele_ct_m2;
3300 }
3301 const uintptr_t result_row_ct = (extra_regression_ct + 1) * subbatch_size;
3302 for (uintptr_t ulii = 0; ulii != result_row_ct; ++ulii) {
3303 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
3304 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
3305 beta_se_iter[uii * 2 + 1] = -9.0;
3306 }
3307 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
3308 }
3309 } else {
3310 uint32_t parameter_uidx = 2 + domdev_present;
3311 double* nm_predictors_pmaj_istart = nullptr;
3312 if (!sparse_optimization) {
3313 // only need to do this part once per variant in multiallelic case
3314 double* nm_predictors_pmaj_iter = &(nm_predictors_pmaj_buf[nm_sample_ct * (parameter_uidx - main_omitted)]);
3315 if (missing_ct || (!prev_nm)) {
3316 // fill phenotypes
3317 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3318 const double* cur_pheno = &(cur_pheno_pmaj[pheno_idx * cur_sample_ct]);
3319 double* nm_pheno_col = &(nm_pheno_buf[pheno_idx * nm_sample_ct]);
3320 uintptr_t sample_midx_base = 0;
3321 uintptr_t sample_nm_bits = sample_nm[0];
3322 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3323 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
3324 nm_pheno_col[sample_idx] = cur_pheno[sample_midx];
3325 }
3326 }
3327
3328 // fill covariates
3329 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx, ++parameter_uidx) {
3330 // strictly speaking, we don't need cur_covars_cmaj to be
3331 // vector-aligned
3332 if (cur_parameter_subset && (!IsSet(cur_parameter_subset, parameter_uidx))) {
3333 continue;
3334 }
3335 const double* cur_covar_col;
3336 if (covar_idx < local_covar_ct) {
3337 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
3338 } else {
3339 cur_covar_col = &(cur_covars_cmaj[(covar_idx - local_covar_ct) * cur_sample_ct]);
3340 }
3341 uintptr_t sample_midx_base = 0;
3342 uintptr_t sample_nm_bits = sample_nm[0];
3343 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3344 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
3345 *nm_predictors_pmaj_iter++ = cur_covar_col[sample_midx];
3346 }
3347 }
3348 nm_predictors_pmaj_istart = nm_predictors_pmaj_iter;
3349 prev_nm = !(missing_ct || local_covar_ct);
3350 } else {
3351 // bugfix (15 Aug 2018): this was not handling --parameters
3352 // correctly when a covariate was only needed as part of an
3353 // interaction
3354 parameter_uidx += cur_covar_ct;
3355 nm_predictors_pmaj_istart = &(nm_predictors_pmaj_iter[literal_covar_ct * nm_sample_ct]);
3356 }
3357 }
3358 const uint32_t const_allele_ct = PopcountWords(const_alleles, allele_ctl);
3359 if (const_allele_ct) {
3360 // Must delete constant-allele columns from nm_predictors_pmaj, and
3361 // shift later columns back.
3362 double* read_iter = genotype_vals;
3363 double* write_iter = genotype_vals;
3364 for (uint32_t read_allele_idx = 0; read_allele_idx != allele_ct; ++read_allele_idx) {
3365 if (read_allele_idx == omitted_allele_idx) {
3366 continue;
3367 }
3368 if (!IsSet(const_alleles, read_allele_idx)) {
3369 if (write_iter != read_iter) {
3370 memcpy(write_iter, read_iter, nm_sample_ct * sizeof(double));
3371 }
3372 if (write_iter == genotype_vals) {
3373 write_iter = multi_start;
3374 } else {
3375 write_iter = &(write_iter[nm_sample_ct]);
3376 }
3377 }
3378 if (read_iter == genotype_vals) {
3379 read_iter = multi_start;
3380 } else {
3381 read_iter = &(read_iter[nm_sample_ct]);
3382 }
3383 }
3384 }
3385 const uint32_t cur_predictor_ct = expected_predictor_ct - const_allele_ct;
3386 uint32_t nonconst_extra_regression_idx = UINT32_MAX; // deliberate overflow
3387 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
3388 if (extra_regression_ct) {
3389 if (IsSet(const_alleles, extra_regression_idx + (extra_regression_idx >= omitted_allele_idx))) {
3390 glm_err = SetGlmErr0(kGlmErrcodeConstAllele);
3391 goto GlmLinearSubbatchThread_skip_regression;
3392 }
3393 ++nonconst_extra_regression_idx;
3394 if (nonconst_extra_regression_idx) {
3395 double* swap_target = &(multi_start[(nonconst_extra_regression_idx - 1) * nm_sample_ct]);
3396 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
3397 double dxx = genotype_vals[uii];
3398 genotype_vals[uii] = swap_target[uii];
3399 swap_target[uii] = dxx;
3400 }
3401 }
3402 }
3403 if (!sparse_optimization) {
3404 double* main_vals = &(nm_predictors_pmaj_buf[nm_sample_ct]);
3405 double* domdev_vals = nullptr;
3406 if (main_omitted) {
3407 // if main_mutated, this will be filled below
3408 // if not, this aliases genotype_vals
3409 main_vals = &(nm_predictors_pmaj_buf[(cur_predictor_ct + main_mutated) * nm_sample_ct]);
3410 } else if (joint_genotypic || joint_hethom) {
3411 domdev_vals = &(main_vals[nm_sample_ct]);
3412 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3413 double cur_genotype_val = genotype_vals[sample_idx];
3414 if (cur_genotype_val > 1.0) {
3415 cur_genotype_val = 2.0 - cur_genotype_val;
3416 }
3417 domdev_vals[sample_idx] = cur_genotype_val;
3418 }
3419 }
3420 if (model_dominant) {
3421 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3422 double cur_genotype_val = genotype_vals[sample_idx];
3423 // 0..1..1
3424 if (cur_genotype_val > 1.0) {
3425 cur_genotype_val = 1.0;
3426 }
3427 main_vals[sample_idx] = cur_genotype_val;
3428 }
3429 } else if (model_recessive || joint_hethom) {
3430 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3431 double cur_genotype_val = genotype_vals[sample_idx];
3432 // 0..0..1
3433 if (cur_genotype_val < 1.0) {
3434 cur_genotype_val = 0.0;
3435 } else {
3436 cur_genotype_val -= 1.0;
3437 }
3438 main_vals[sample_idx] = cur_genotype_val;
3439 }
3440 } else if (model_hetonly) {
3441 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3442 double cur_genotype_val = genotype_vals[sample_idx];
3443 // 0..1..0
3444 if (cur_genotype_val > 1.0) {
3445 cur_genotype_val = 2.0 - cur_genotype_val;
3446 }
3447 main_vals[sample_idx] = cur_genotype_val;
3448 }
3449 }
3450
3451 // fill interaction terms
3452 if (add_interactions) {
3453 double* nm_predictors_pmaj_iter = nm_predictors_pmaj_istart;
3454 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx) {
3455 const double* cur_covar_col;
3456 if (covar_idx < local_covar_ct) {
3457 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
3458 } else {
3459 cur_covar_col = &(cur_covars_cmaj[covar_idx * cur_sample_ct]);
3460 }
3461 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
3462 uintptr_t sample_midx_base = 0;
3463 uintptr_t sample_nm_bits = sample_nm[0];
3464 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3465 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
3466 *nm_predictors_pmaj_iter++ = main_vals[sample_idx] * cur_covar_col[sample_midx];
3467 }
3468 }
3469 ++parameter_uidx;
3470 if (domdev_present) {
3471 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
3472 uintptr_t sample_midx_base = 0;
3473 uintptr_t sample_nm_bits = sample_nm[0];
3474 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3475 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
3476 *nm_predictors_pmaj_iter++ = domdev_vals[sample_idx] * cur_covar_col[sample_midx];
3477 }
3478 }
3479 ++parameter_uidx;
3480 }
3481 }
3482 }
3483 }
3484
3485 // bugfix (12 Sep 2017): forgot to implement per-variant VIF and
3486 // max-corr checks
3487 if (xtx_image && (sparse_optimization || (prev_nm && (!allele_ct_m2)))) {
3488 // only need to fill in additive and possibly domdev dot
3489 // products
3490 memcpy(xtx_inv, xtx_image, cur_predictor_ct * cur_predictor_ct * sizeof(double));
3491 memcpy(xt_y, xt_y_image, cur_predictor_ct * subbatch_size * sizeof(double));
3492 if (sparse_optimization) {
3493 // currently does not handle chrX
3494 ZeroDArr(subbatch_size, geno_pheno_prods);
3495 if (domdev_pheno_prods) {
3496 ZeroDArr(subbatch_size, domdev_pheno_prods);
3497 }
3498 double domdev_geno_prod = 0.0;
3499 if (!cur_covar_ct) {
3500 // missing genotypes may be present
3501 if (!difflist_common_geno) {
3502 if (difflist_len) {
3503 const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2;
3504 uint32_t loop_len = kBitsPerWordD2;
3505 for (uint32_t widx = 0; ; ++widx) {
3506 if (widx >= word_ct_m1) {
3507 if (widx > word_ct_m1) {
3508 break;
3509 }
3510 loop_len = ModNz(difflist_len, kBitsPerWordD2);
3511 }
3512 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
3513 uintptr_t raregeno_word = raregeno[widx];
3514 for (uint32_t uii = 0; uii != loop_len; ++uii) {
3515 const uintptr_t cur_geno = raregeno_word & 3;
3516 const uint32_t sample_midx = cur_difflist_sample_ids[uii];
3517 if (cur_geno == 3) {
3518 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3519 const double cur_pheno_val = cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3520 xt_y[pheno_idx * cur_predictor_ct] -= cur_pheno_val;
3521 }
3522 } else {
3523 const double geno_d = geno_d_lookup[cur_geno - 1];
3524 if (domdev_present && (cur_geno == 1)) {
3525 // domdev = 1
3526 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3527 const double cur_pheno_val = cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3528 geno_pheno_prods[pheno_idx] += geno_d * cur_pheno_val;
3529 domdev_pheno_prods[pheno_idx] += cur_pheno_val;
3530 }
3531 domdev_geno_prod += geno_d;
3532 } else {
3533 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3534 geno_pheno_prods[pheno_idx] += geno_d * cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3535 }
3536 }
3537 }
3538 raregeno_word = raregeno_word >> 2;
3539 }
3540 }
3541 }
3542 } else {
3543 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3544 uintptr_t geno_word = pgv.genovec[widx];
3545 if (!geno_word) {
3546 continue;
3547 }
3548 const uint32_t sample_midx_base = widx * kBitsPerWordD2;
3549 uintptr_t missing_word = geno_word & (geno_word >> 1) & kMask5555;
3550 if (missing_word) {
3551 geno_word ^= missing_word * 3;
3552 while (missing_word) {
3553 const uint32_t sample_midx_lowbits = ctzw(missing_word) / 2;
3554 const uint32_t sample_midx = sample_midx_base + sample_midx_lowbits;
3555 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3556 const double cur_pheno_val = cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3557 xt_y[pheno_idx * cur_predictor_ct] -= cur_pheno_val;
3558 }
3559 missing_word &= missing_word - 1;
3560 }
3561 }
3562 while (geno_word) {
3563 const uint32_t lowest_set_bit = ctzw(geno_word);
3564 const uint32_t sample_midx = sample_midx_base + (lowest_set_bit / 2);
3565 const double geno_d = geno_d_lookup[lowest_set_bit & 1];
3566 if (domdev_present && (!(lowest_set_bit & 1))) {
3567 // domdev = 1
3568 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3569 const double cur_pheno_val = cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3570 geno_pheno_prods[pheno_idx] += geno_d * cur_pheno_val;
3571 domdev_pheno_prods[pheno_idx] += cur_pheno_val;
3572 }
3573 domdev_geno_prod += geno_d;
3574 } else {
3575 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3576 geno_pheno_prods[pheno_idx] += geno_d * cur_pheno_pmaj[pheno_idx * cur_sample_ct + sample_midx];
3577 }
3578 }
3579 geno_word &= geno_word - 1;
3580 }
3581 }
3582 }
3583 xtx_inv[0] = u31tod(nm_sample_ct);
3584 } else {
3585 double* geno_dotprod_row = &(xtx_inv[cur_predictor_ct]);
3586 double* domdev_dotprod_row = &(xtx_inv[2 * cur_predictor_ct]);
3587 for (uint32_t widx = 0; widx != sample_ctl2; ++widx) {
3588 uintptr_t geno_word = pgv.genovec[widx];
3589 if (geno_word) {
3590 const uint32_t sample_idx_base = widx * kBitsPerWordD2;
3591 do {
3592 const uint32_t lowest_set_bit = ctzw(geno_word);
3593 // since there are no missing values, we have a het if
3594 // (lowest_set_bit & 1) is zero, and a hom-alt when
3595 // it's one.
3596 const uint32_t sample_idx = sample_idx_base + (lowest_set_bit / 2);
3597 const double geno_d = geno_d_lookup[lowest_set_bit & 1];
3598 for (uintptr_t pred_idx = domdev_present + 2; pred_idx != cur_predictor_ct; ++pred_idx) {
3599 geno_dotprod_row[pred_idx] += geno_d * nm_predictors_pmaj_buf[pred_idx * nm_sample_ct + sample_idx];
3600 }
3601 // can have a separate categorical loop here
3602
3603 if (domdev_present && (!(lowest_set_bit & 1))) {
3604 // domdev = 1
3605 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3606 const double cur_pheno_val = nm_pheno_buf[pheno_idx * nm_sample_ct + sample_idx];
3607 geno_pheno_prods[pheno_idx] += geno_d * cur_pheno_val;
3608 domdev_pheno_prods[pheno_idx] += cur_pheno_val;
3609 }
3610 domdev_geno_prod += geno_d;
3611 for (uintptr_t pred_idx = 3; pred_idx != cur_predictor_ct; ++pred_idx) {
3612 domdev_dotprod_row[pred_idx] += nm_predictors_pmaj_buf[pred_idx * nm_sample_ct + sample_idx];
3613 }
3614 // categorical optimization possible here
3615 } else {
3616 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3617 geno_pheno_prods[pheno_idx] += geno_d * nm_pheno_buf[pheno_idx * nm_sample_ct + sample_idx];
3618 }
3619 }
3620 geno_word &= geno_word - 1;
3621 } while (geno_word);
3622 }
3623 }
3624 }
3625 const double het_ctd = u31tod(genocounts[1]);
3626 const double homalt_ctd = u31tod(genocounts[2]);
3627 xtx_inv[cur_predictor_ct] = het_ctd * geno_d_lookup[0] + homalt_ctd * geno_d_lookup[1];
3628 xtx_inv[cur_predictor_ct + 1] = het_ctd * geno_d_lookup[0] * geno_d_lookup[0] + homalt_ctd * geno_d_lookup[1] * geno_d_lookup[1];
3629 if (domdev_present) {
3630 xtx_inv[cur_predictor_ct + 2] = domdev_geno_prod;
3631 xtx_inv[2 * cur_predictor_ct] = het_ctd;
3632 xtx_inv[2 * cur_predictor_ct + 2] = het_ctd;
3633 }
3634 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3635 double* cur_xt_y = &(xt_y[cur_predictor_ct * pheno_idx]);
3636 cur_xt_y[1] = geno_pheno_prods[pheno_idx];
3637 if (domdev_present) {
3638 cur_xt_y[2] = domdev_pheno_prods[pheno_idx];
3639 }
3640 }
3641 } else {
3642 // !sparse_optimization
3643 uintptr_t start_pred_idx = 0;
3644 if (!(model_dominant || model_recessive || model_hetonly || joint_hethom)) {
3645 start_pred_idx = domdev_present + 2;
3646 xtx_inv[cur_predictor_ct] = main_dosage_sum;
3647 xtx_inv[cur_predictor_ct + 1] = main_dosage_ssq;
3648 }
3649 if (cur_predictor_ct > start_pred_idx) {
3650 // categorical optimization possible here
3651 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[nm_sample_ct]), &(nm_predictors_pmaj_buf[start_pred_idx * nm_sample_ct]), nm_sample_ct, nm_sample_ct, cur_predictor_ct - start_pred_idx, &(xtx_inv[cur_predictor_ct + start_pred_idx]));
3652 }
3653 RowMajorMatrixMultiplyStrided(nm_pheno_buf, &(nm_predictors_pmaj_buf[nm_sample_ct]), subbatch_size, nm_sample_ct, 1, 1, nm_sample_ct, cur_predictor_ct, &(xt_y[1]));
3654 if (domdev_present) {
3655 RowMajorMatrixMultiplyStrided(nm_pheno_buf, &(nm_predictors_pmaj_buf[2 * nm_sample_ct]), subbatch_size, nm_sample_ct, 1, 1, nm_sample_ct, cur_predictor_ct, &(xt_y[2]));
3656 // categorical optimization possible here
3657 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[2 * nm_sample_ct]), nm_predictors_pmaj_buf, nm_sample_ct, nm_sample_ct, cur_predictor_ct, &(xtx_inv[2 * cur_predictor_ct]));
3658 xtx_inv[cur_predictor_ct + 2] = xtx_inv[2 * cur_predictor_ct + 1];
3659 }
3660 }
3661 const double* covarxx_dotprod_inv = covarx_dotprod_inv;
3662 if (!missing_ct) {
3663 glm_err = CheckMaxCorrAndVifNm(xtx_inv, corr_inv, cur_predictor_ct, domdev_present_p1, cur_sample_ct_recip, cur_sample_ct_m1_recip, max_corr, vif_thresh, semicomputed_biallelic_corr_matrix, semicomputed_biallelic_inv_corr_sqrts, dbl_2d_buf, &(dbl_2d_buf[2 * cur_predictor_ct]), &(dbl_2d_buf[3 * cur_predictor_ct]));
3664 } else {
3665 for (uint32_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
3666 dbl_2d_buf[pred_idx] = xtx_inv[pred_idx * cur_predictor_ct];
3667 }
3668 glm_err = CheckMaxCorrAndVif(xtx_inv, 1, cur_predictor_ct, nm_sample_ct, max_corr, vif_thresh, dbl_2d_buf, nullptr, inverse_corr_buf, inv_1d_buf);
3669 covarless_inverse_buf[0] = 1.0 / u31tod(nm_sample_ct);
3670 covarxx_dotprod_inv = covarless_inverse_buf;
3671 }
3672 if (glm_err) {
3673 goto GlmLinearSubbatchThread_skip_regression;
3674 }
3675 const double geno_ssq = xtx_inv[1 + cur_predictor_ct];
3676 if (!domdev_present) {
3677 xtx_inv[1 + cur_predictor_ct] = xtx_inv[cur_predictor_ct];
3678 if (InvertRank1Symm(covarxx_dotprod_inv, &(xtx_inv[1 + cur_predictor_ct]), cur_predictor_ct - 1, 1, geno_ssq, dbl_2d_buf, inverse_corr_buf)) {
3679 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
3680 goto GlmLinearSubbatchThread_skip_regression;
3681 }
3682 } else {
3683 const double domdev_geno_prod = xtx_inv[2 + cur_predictor_ct];
3684 const double domdev_ssq = xtx_inv[2 + 2 * cur_predictor_ct];
3685 xtx_inv[2 + cur_predictor_ct] = xtx_inv[cur_predictor_ct];
3686 xtx_inv[2 + 2 * cur_predictor_ct] = xtx_inv[2 * cur_predictor_ct];
3687 if (InvertRank2Symm(covarxx_dotprod_inv, &(xtx_inv[2 + cur_predictor_ct]), cur_predictor_ct - 2, cur_predictor_ct, 1, geno_ssq, domdev_geno_prod, domdev_ssq, dbl_2d_buf, inverse_corr_buf, &(inverse_corr_buf[2 * (cur_predictor_ct - 2)]))) {
3688 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
3689 goto GlmLinearSubbatchThread_skip_regression;
3690 }
3691 }
3692 // need to make sure xtx_inv remains reflected in NOLAPACK case
3693 memcpy(xtx_inv, dbl_2d_buf, cur_predictor_ct * cur_predictor_ct * sizeof(double));
3694 ReflectMatrix(cur_predictor_ct, xtx_inv);
3695 RowMajorMatrixMultiply(xt_y, xtx_inv, subbatch_size, cur_predictor_ct, cur_predictor_ct, fitted_coefs);
3696 } else {
3697 // generic case
3698 // major categorical optimization possible here, some
3699 // multiallelic optimizations possible
3700 MultiplySelfTranspose(nm_predictors_pmaj_buf, cur_predictor_ct, nm_sample_ct, xtx_inv);
3701
3702 for (uint32_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
3703 dbl_2d_buf[pred_idx] = xtx_inv[pred_idx * cur_predictor_ct];
3704 }
3705 glm_err = CheckMaxCorrAndVif(xtx_inv, 1, cur_predictor_ct, nm_sample_ct, max_corr, vif_thresh, dbl_2d_buf, nullptr, inverse_corr_buf, inv_1d_buf);
3706 if (glm_err) {
3707 goto GlmLinearSubbatchThread_skip_regression;
3708 }
3709 if (LinearRegressionInv(nm_pheno_buf, nm_predictors_pmaj_buf, cur_predictor_ct, nm_sample_ct, subbatch_size, xtx_inv, fitted_coefs, xt_y, inv_1d_buf, dbl_2d_buf)) {
3710 glm_err = SetGlmErr0(kGlmErrcodeRankDeficient);
3711 goto GlmLinearSubbatchThread_skip_regression;
3712 }
3713 }
3714 // RSS = y^T y - y^T X (X^T X)^{-1} X^T y
3715 // = cur_pheno_ssq - xt_y * fitted_coefs
3716 // s^2 = RSS / df
3717 // possible todo: improve numerical stability of this computation
3718 // in non-mean-centered phenotype case
3719
3720 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3721 {
3722 double tmp_pheno_ssq = pheno_ssq_bases[pheno_idx];
3723 if (missing_ct) {
3724 const double* cur_pheno = &(cur_pheno_pmaj[pheno_idx * cur_sample_ct]);
3725 if (!difflist_common_geno) {
3726 const uint32_t raregeno_word_ct = NypCtToWordCt(difflist_len);
3727 for (uint32_t widx = 0; widx != raregeno_word_ct; ++widx) {
3728 uintptr_t missing_word = raregeno[widx];
3729 missing_word = missing_word & (missing_word >> 1) & kMask5555;
3730 if (!missing_word) {
3731 continue;
3732 }
3733 const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]);
3734 do {
3735 const uint32_t difflist_idx = ctzw(missing_word) / 2;
3736 const uint32_t sample_midx = cur_difflist_sample_ids[difflist_idx];
3737 tmp_pheno_ssq -= cur_pheno[sample_midx] * cur_pheno[sample_midx];
3738 missing_word &= missing_word - 1;
3739 } while (missing_word);
3740 }
3741 } else {
3742 uintptr_t sample_midx_base = 0;
3743 uintptr_t sample_nm_inv_bits = ~sample_nm[0];
3744 for (uint32_t missing_idx = 0; missing_idx != missing_ct; ++missing_idx) {
3745 const uintptr_t sample_midx = BitIter0(sample_nm, &sample_midx_base, &sample_nm_inv_bits);
3746 tmp_pheno_ssq -= cur_pheno[sample_midx] * cur_pheno[sample_midx];
3747 }
3748 }
3749 }
3750 const double* tmp_fitted_coefs = &(fitted_coefs[pheno_idx * cur_predictor_ct]);
3751 const double sigma = (tmp_pheno_ssq - DotprodxD(&(xt_y[pheno_idx * cur_predictor_ct]), tmp_fitted_coefs, cur_predictor_ct)) / u31tod(nm_sample_ct - cur_predictor_ct);
3752 for (uint32_t uii = 0; uii != cur_predictor_ct; ++uii) {
3753 const double* s_iter = &(xtx_inv[uii * cur_predictor_ct]);
3754 double* s_iter2 = &(xtx_inv2[uii * cur_predictor_ct]);
3755 #ifdef NOLAPACK
3756 for (uint32_t ujj = 0; ujj != cur_predictor_ct; ++ujj) {
3757 s_iter2[ujj] = s_iter[ujj] * sigma;
3758 }
3759 #else
3760 for (uint32_t ujj = 0; ujj <= uii; ++ujj) {
3761 s_iter2[ujj] = s_iter[ujj] * sigma;
3762 }
3763 #endif
3764 }
3765 // validParameters() check
3766 for (uint32_t pred_uidx = 1; pred_uidx != cur_predictor_ct; ++pred_uidx) {
3767 const double xtx_inv2_diag_element = xtx_inv2[pred_uidx * (cur_predictor_ct + 1)];
3768 if (xtx_inv2_diag_element < 1e-20) {
3769 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
3770 goto GlmLinearSubbatchThread_skip_regression_for_one_pheno;
3771 }
3772 // use dbl_2d_buf[] to store diagonal square roots
3773 dbl_2d_buf[pred_uidx] = sqrt(xtx_inv2_diag_element);
3774 }
3775 dbl_2d_buf[0] = sqrt(xtx_inv2[0]);
3776 for (uint32_t pred_uidx = 1; pred_uidx != cur_predictor_ct; ++pred_uidx) {
3777 const double cur_xtx_inv2_diag_sqrt = 0.99999 * dbl_2d_buf[pred_uidx];
3778 const double* xtx_inv2_row = &(xtx_inv2[pred_uidx * cur_predictor_ct]);
3779 for (uint32_t pred_uidx2 = 0; pred_uidx2 != pred_uidx; ++pred_uidx2) {
3780 if (xtx_inv2_row[pred_uidx2] > cur_xtx_inv2_diag_sqrt * dbl_2d_buf[pred_uidx2]) {
3781 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
3782 goto GlmLinearSubbatchThread_skip_regression_for_one_pheno;
3783 }
3784 }
3785 }
3786 double* beta_se_iter2 = beta_se_iter;
3787 for (uint32_t pred_uidx = reported_pred_uidx_start; pred_uidx != reported_pred_uidx_biallelic_end; ++pred_uidx) {
3788 // In the multiallelic-fused case, if the first allele is
3789 // constant, this writes the beta/se values for the first
3790 // nonconstant, non-omitted allele where the results for the
3791 // first allele belong. We correct that below.
3792 *beta_se_iter2++ = tmp_fitted_coefs[pred_uidx];
3793 *beta_se_iter2++ = dbl_2d_buf[pred_uidx];
3794 }
3795 // move this up since dbl_2d_buf may be clobbered
3796 if (cur_constraint_ct) {
3797 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeRankDeficient);
3798 memcpy(beta_se_iter2, &glm_err2, 8);
3799 ++beta_se_iter2;
3800 *beta_se_iter2++ = -9.0;
3801 }
3802 if (!const_allele_ct) {
3803 if (beta_se_multiallelic_fused || (!hide_covar)) {
3804 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
3805 beta_se_iter2[2 * extra_allele_idx] = tmp_fitted_coefs[cur_biallelic_predictor_ct + extra_allele_idx];
3806 beta_se_iter2[2 * extra_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + extra_allele_idx];
3807 }
3808 }
3809 } else if (!beta_se_multiallelic_fused) {
3810 if (!hide_covar) {
3811 // Need to insert some {CONST_ALLELE, -9} entries.
3812 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
3813 const uint32_t cur_raw_allele_idx = extra_regression_idx + (extra_regression_idx >= omitted_allele_idx);
3814 uint32_t extra_read_allele_idx = 0;
3815 uint32_t extra_write_allele_idx = 0;
3816 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
3817 if ((allele_idx == omitted_allele_idx) || (allele_idx == cur_raw_allele_idx)) {
3818 continue;
3819 }
3820 if (IsSet(const_alleles, allele_idx)) {
3821 memcpy(&(beta_se_iter2[2 * extra_write_allele_idx]), &glm_err2, 8);
3822 beta_se_iter2[2 * extra_write_allele_idx + 1] = -9.0;
3823 } else {
3824 beta_se_iter2[2 * extra_write_allele_idx] = tmp_fitted_coefs[cur_biallelic_predictor_ct + extra_read_allele_idx];
3825 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + extra_read_allele_idx];
3826 ++extra_read_allele_idx;
3827 }
3828 ++extra_write_allele_idx;
3829 }
3830 }
3831 } else {
3832 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
3833 // Special-case first nonconst allele since it's positioned
3834 // discontinuously, and its BETA/SE may already be correctly
3835 // filled.
3836 uint32_t allele_idx = omitted_allele_idx? 0 : 1;
3837 uint32_t extra_write_allele_idx = 0;
3838 if (IsSet(const_alleles, allele_idx)) {
3839 memcpy(&(beta_se_iter[2 * include_intercept]), &glm_err2, 8);
3840 beta_se_iter[2 * include_intercept + 1] = -9.0;
3841 allele_idx = AdvTo0Bit(const_alleles, 1);
3842 if (allele_idx == omitted_allele_idx) {
3843 allele_idx = AdvTo0Bit(const_alleles, omitted_allele_idx + 1);
3844 }
3845 extra_write_allele_idx = allele_idx - 1 - (allele_idx > omitted_allele_idx);
3846 for (uint32_t uii = 0; uii != extra_write_allele_idx; ++uii) {
3847 memcpy(&(beta_se_iter2[2 * uii]), &glm_err2, 8);
3848 beta_se_iter2[2 * uii + 1] = -9.0;
3849 }
3850 beta_se_iter2[2 * extra_write_allele_idx] = tmp_fitted_coefs[1];
3851 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[1];
3852 ++extra_write_allele_idx;
3853 }
3854 ++allele_idx;
3855 uint32_t nonconst_allele_idx_m1 = 0;
3856 for (; allele_idx != allele_ct; ++allele_idx) {
3857 if (allele_idx == omitted_allele_idx) {
3858 continue;
3859 }
3860 if (!IsSet(const_alleles, allele_idx)) {
3861 beta_se_iter2[2 * extra_write_allele_idx] = tmp_fitted_coefs[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
3862 beta_se_iter2[2 * extra_write_allele_idx + 1] = dbl_2d_buf[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
3863 ++nonconst_allele_idx_m1;
3864 } else {
3865 memcpy(&(beta_se_iter2[2 * extra_write_allele_idx]), &glm_err2, 8);
3866 beta_se_iter2[2 * extra_write_allele_idx + 1] = -9.0;
3867 }
3868 ++extra_write_allele_idx;
3869 }
3870 }
3871 if (cur_constraint_ct) {
3872 // probable todo: cur_constraints_con_major manipulation can
3873 // go outside the pheno_idx loop
3874 uint32_t joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
3875 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
3876 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
3877 cur_constraints_con_major[uii * cur_predictor_ct + joint_test_idx] = 1.0;
3878 }
3879 #ifndef NOLAPACK
3880 // xtx_inv2 upper triangle was not filled
3881 ReflectMatrix(cur_predictor_ct, xtx_inv2);
3882 #endif
3883 double chisq;
3884 if (!LinearHypothesisChisq(tmp_fitted_coefs, cur_constraints_con_major, xtx_inv2, cur_constraint_ct, cur_predictor_ct, cur_predictor_ct, &chisq, tmphxs_buf, h_transpose_buf, inner_buf, inv_1d_buf, dbl_2d_buf)) {
3885 beta_se_iter2[-1] = chisq;
3886 }
3887 // next test may have different alt allele count
3888 joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
3889 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
3890 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
3891 cur_constraints_con_major[uii * cur_predictor_ct + joint_test_idx] = 0.0;
3892 }
3893 }
3894 }
3895 while (0) {
3896 GlmLinearSubbatchThread_skip_regression_for_one_pheno:
3897 {
3898 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
3899 if (beta_se_multiallelic_fused || (!hide_covar)) {
3900 reported_ct += allele_ct_m2;
3901 }
3902 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
3903 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
3904 beta_se_iter[uii * 2 + 1] = -9.0;
3905 }
3906 }
3907 }
3908 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
3909 }
3910 while (0) {
3911 GlmLinearSubbatchThread_skip_regression:
3912 {
3913 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
3914 if (beta_se_multiallelic_fused || (!hide_covar)) {
3915 reported_ct += allele_ct_m2;
3916 }
3917 for (uint32_t pheno_idx = 0; pheno_idx != subbatch_size; ++pheno_idx) {
3918 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
3919 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
3920 beta_se_iter[uii * 2 + 1] = -9.0;
3921 }
3922 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
3923 }
3924 }
3925 }
3926 }
3927 }
3928 if (local_covars_iter) {
3929 local_covars_iter = &(local_covars_iter[local_covar_ct * max_sample_ct]);
3930 }
3931 }
3932 }
3933 parity = 1 - parity;
3934 variant_idx_offset += cur_block_variant_ct;
3935 while (0) {
3936 GlmLinearSubbatchThread_err:
3937 UpdateU64IfSmaller(new_err_info, &common->err_info);
3938 }
3939 } while (!THREAD_BLOCK_FINISH(arg));
3940 THREAD_RETURN;
3941 }
3942
3943 CONSTI32(kMaxLinearSubbatchSize, 240);
3944 static_assert(kMaxLinearSubbatchSize + 12 <= kMaxOpenFiles, "kMaxLinearSubbatchSize can't be too close to or larger than kMaxOpenFiles.");
3945
3946 PglErr GlmLinearBatch(const uintptr_t* pheno_batch, const PhenoCol* pheno_cols, const char* pheno_names, const char* const* test_names, const char* const* test_names_x, const char* const* test_names_y, const uint32_t* variant_bps, const char* const* variant_ids, const char* const* allele_storage, const GlmInfo* glm_info_ptr, const uint32_t* local_sample_uidx_order, const uintptr_t* local_variant_include, uint32_t raw_variant_ct, uint32_t completed_pheno_ct, uint32_t batch_size, uintptr_t max_pheno_name_blen, uint32_t max_chr_blen, double ci_size, double ln_pfilter, double output_min_ln, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, uintptr_t overflow_buf_size, uint32_t local_sample_ct, PgenFileInfo* pgfip, GlmLinearCtx* ctx, TextStream* local_covar_txsp, LlStr** outfnames_ll_ptr, char* outname, char* outname_end) {
3947 unsigned char* bigstack_mark = g_bigstack_base;
3948 char** cswritep_arr = nullptr;
3949 CompressStreamState* css_arr = nullptr;
3950 uint32_t subbatch_size = 0;
3951 PglErr reterr = kPglRetSuccess;
3952 ThreadGroup tg;
3953 PreinitThreads(&tg);
3954 {
3955 GlmCtx* common = ctx->common;
3956 const uintptr_t* variant_include = common->variant_include;
3957 const ChrInfo* cip = common->cip;
3958 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
3959 const AlleleCode* omitted_alleles = common->omitted_alleles;
3960
3961 const uint32_t sample_ct = common->sample_ct;
3962 const uint32_t sample_ct_x = common->sample_ct_x;
3963 const uint32_t sample_ct_y = common->sample_ct_y;
3964 const uint32_t covar_ct = common->covar_ct;
3965 const uintptr_t local_covar_ct = common->local_covar_ct;
3966 const uint32_t covar_ct_x = common->covar_ct_x;
3967 const uint32_t covar_ct_y = common->covar_ct_y;
3968
3969 uint32_t max_sample_ct = MAXV(sample_ct, sample_ct_x);
3970 if (max_sample_ct < sample_ct_y) {
3971 max_sample_ct = sample_ct_y;
3972 }
3973 const uintptr_t* sample_include = common->sample_include;
3974 uint32_t* local_sample_idx_order = nullptr;
3975 uint32_t local_line_idx = 0;
3976 uint32_t local_xy = 0; // 1 = chrX, 2 = chrY
3977
3978 const char* local_line_iter = nullptr;
3979 uint32_t local_prev_chr_code = UINT32_MAX;
3980 uint32_t local_chr_code = UINT32_MAX;
3981 uint32_t local_bp = UINT32_MAX;
3982 uint32_t local_skip_chr = 1;
3983 if (local_covar_ct) {
3984 reterr = TextRewind(local_covar_txsp);
3985 if (unlikely(reterr)) {
3986 goto GlmLinearBatch_ret_TSTREAM_FAIL;
3987 }
3988 local_line_idx = glm_info_ptr->local_header_line_ct;
3989 reterr = TextSkip(local_line_idx, local_covar_txsp);
3990 if (unlikely(reterr)) {
3991 goto GlmLinearBatch_ret_TSTREAM_FAIL;
3992 }
3993 if (unlikely(bigstack_alloc_u32(local_sample_ct, &local_sample_idx_order))) {
3994 goto GlmLinearBatch_ret_NOMEM;
3995 }
3996 for (uint32_t uii = 0; uii != local_sample_ct; ++uii) {
3997 const uint32_t cur_uidx = local_sample_uidx_order[uii];
3998 uint32_t cur_idx = UINT32_MAX;
3999 if ((cur_uidx != UINT32_MAX) && IsSet(sample_include, cur_uidx)) {
4000 cur_idx = RawToSubsettedPos(sample_include, common->sample_include_cumulative_popcounts, cur_uidx);
4001 }
4002 local_sample_idx_order[uii] = cur_idx;
4003 }
4004 }
4005
4006 const uint32_t variant_ct = common->variant_ct;
4007
4008 const GlmFlags glm_flags = glm_info_ptr->flags;
4009 const uint32_t report_neglog10p = (glm_flags / kfGlmLog10) & 1;
4010 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
4011 const uint32_t domdev_present = (glm_flags & (kfGlmGenotypic | kfGlmHethom))? 1 : 0;
4012 const uint32_t domdev_present_p1 = domdev_present + 1;
4013
4014 const uint32_t constraint_ct = common->constraint_ct;
4015 const uint32_t constraint_ct_x = common->constraint_ct_x;
4016 const uint32_t constraint_ct_y = common->constraint_ct_y;
4017
4018 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
4019 uint32_t biallelic_predictor_ct = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
4020 uint32_t biallelic_predictor_ct_x = 2 + covar_ct_x * (1 + add_interactions);
4021 uint32_t biallelic_predictor_ct_y = 2 + covar_ct_y * (1 + add_interactions);
4022 const uintptr_t* parameter_subset = common->parameter_subset;
4023 const uintptr_t* parameter_subset_x = common->parameter_subset_x;
4024 const uintptr_t* parameter_subset_y = common->parameter_subset_y;
4025 if (parameter_subset) {
4026 biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct));
4027 if (sample_ct_x) {
4028 biallelic_predictor_ct_x = PopcountWords(parameter_subset_x, BitCtToWordCt(biallelic_predictor_ct_x));
4029 } else {
4030 biallelic_predictor_ct_x = 0;
4031 }
4032 if (sample_ct_y) {
4033 biallelic_predictor_ct_y = PopcountWords(parameter_subset_y, BitCtToWordCt(biallelic_predictor_ct_y));
4034 } else {
4035 biallelic_predictor_ct_y = 0;
4036 }
4037 }
4038 uint32_t biallelic_reported_test_ct = GetBiallelicReportedTestCt(parameter_subset, glm_flags, covar_ct, common->tests_flag);
4039 uintptr_t max_reported_test_ct = biallelic_reported_test_ct;
4040 uint32_t biallelic_reported_test_ct_x = 0;
4041 if (sample_ct_x) {
4042 biallelic_reported_test_ct_x = GetBiallelicReportedTestCt(parameter_subset_x, glm_flags, covar_ct_x, common->tests_flag);
4043 if (biallelic_reported_test_ct_x > max_reported_test_ct) {
4044 max_reported_test_ct = biallelic_reported_test_ct_x;
4045 }
4046 }
4047 uint32_t biallelic_reported_test_ct_y = 0;
4048 if (sample_ct_y) {
4049 biallelic_reported_test_ct_y = GetBiallelicReportedTestCt(parameter_subset_y, glm_flags, covar_ct_y, common->tests_flag);
4050 if (biallelic_reported_test_ct_y > max_reported_test_ct) {
4051 max_reported_test_ct = biallelic_reported_test_ct_y;
4052 }
4053 }
4054 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
4055 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
4056 const GlmColFlags glm_cols = glm_info_ptr->cols;
4057 const uint32_t test_col = glm_cols & kfGlmColTest;
4058 if (unlikely((!test_col) && (max_reported_test_ct > 1))) {
4059 logerrputs("Error: --glm's 'test' column cannot be omitted when results for multiple\npredictors are reported. (Did you forget 'hide-covar'?)\n");
4060 goto GlmLinearBatch_ret_INCONSISTENT_INPUT;
4061 }
4062 const uint32_t main_mutated = ((glm_flags & (kfGlmDominant | kfGlmRecessive | kfGlmHetonly | kfGlmHethom)) != kfGlm0);
4063 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!main_mutated) && (!common->tests_flag) && (!add_interactions);
4064 if (beta_se_multiallelic_fused || (!hide_covar)) {
4065 max_reported_test_ct += max_extra_allele_ct;
4066 }
4067 common->max_reported_test_ct = max_reported_test_ct;
4068
4069 uint32_t x_code = UINT32_MAXM1;
4070 uint32_t x_start = 0;
4071 uint32_t x_end = 0;
4072 if (sample_ct_x) {
4073 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetX, &x_code, &x_start, &x_end);
4074 }
4075 uint32_t y_code = UINT32_MAXM1;
4076 uint32_t y_start = 0;
4077 uint32_t y_end = 0;
4078 if (sample_ct_y) {
4079 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetY, &y_code, &y_start, &y_end);
4080 }
4081 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
4082 const uint32_t chr_col = glm_cols & kfGlmColChrom;
4083
4084 char* chr_buf = nullptr;
4085 if (chr_col) {
4086 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
4087 goto GlmLinearBatch_ret_NOMEM;
4088 }
4089 }
4090
4091 uint32_t calc_thread_ct = (max_thread_ct > 8)? (max_thread_ct - 1) : max_thread_ct;
4092 if (calc_thread_ct > variant_ct) {
4093 calc_thread_ct = variant_ct;
4094 }
4095
4096 subbatch_size = MINV(kMaxLinearSubbatchSize, batch_size);
4097 if (sample_ct * S_CAST(uint64_t, subbatch_size) > 0x7fffffff) {
4098 subbatch_size = 0x7fffffff / sample_ct;
4099 }
4100 if (unlikely(bigstack_calloc_cp(subbatch_size, &cswritep_arr) ||
4101 BIGSTACK_ALLOC_X(CompressStreamState, subbatch_size, &css_arr))) {
4102 goto GlmLinearBatch_ret_NOMEM;
4103 }
4104 for (uint32_t fidx = 0; fidx != subbatch_size; ++fidx) {
4105 PreinitCstream(&(css_arr[fidx]));
4106 }
4107 // Subbatch-size-dependent memory allocations:
4108 // nm_pheno_buf
4109 // fitted_coefs
4110 // xt_y
4111 // block_beta_se_bufs
4112 // css_arr
4113
4114 const uint32_t main_omitted = (parameter_subset && (!IsSet(parameter_subset, 1)));
4115 const uint32_t xmain_ct = main_mutated + main_omitted;
4116 const uint32_t max_returned_difflist_len = ctx->max_returned_difflist_len;
4117 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
4118 common->thread_mhc = nullptr;
4119 common->dosage_presents = nullptr;
4120 common->dosage_mains = nullptr;
4121 const uint32_t output_zst = (glm_flags / kfGlmZs) & 1;
4122 // This cannot be less than what InitCstreamAlloc() actually allocates.
4123 uintptr_t cstream_alloc_size = RoundUpPow2(overflow_buf_size, kCacheline);
4124 if (output_zst) {
4125 cstream_alloc_size += RoundUpPow2(CstreamWkspaceReq(overflow_buf_size), kCacheline);
4126 }
4127 unsigned char* bigstack_mark2 = g_bigstack_base;
4128 const uint32_t is_qt_residualize = (glm_flags / kfGlmQtResidualize) & 1;
4129 const uintptr_t qt_residualize_alloc_size = is_qt_residualize? GetResidualizedPhenoAndXtYWorkspaceSize(max_sample_ct, covar_ct) : 0;
4130 double* pheno_d = nullptr;
4131 double* pheno_x_d = nullptr;
4132 double* pheno_y_d = nullptr;
4133 uintptr_t workspace_alloc;
4134 uint32_t read_block_size;
4135 uintptr_t max_alt_allele_block_size;
4136 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
4137 for (; ; subbatch_size = (subbatch_size + 1) / 2) {
4138 // may permit size 1 here and get rid of GlmLinear() later
4139 if (subbatch_size == 1) {
4140 goto GlmLinearBatch_ret_NOMEM;
4141 }
4142 BigstackReset(bigstack_mark2);
4143 if (bigstack_alloc_d(sample_ct * subbatch_size, &pheno_d)) {
4144 continue;
4145 }
4146 if (common->nm_precomp) {
4147 if (bigstack_alloc_d((2 + domdev_present + (1 - is_qt_residualize) * covar_ct) * subbatch_size, &(common->nm_precomp->xt_y_image))) {
4148 continue;
4149 }
4150 }
4151 if (sample_ct_x) {
4152 if (bigstack_alloc_d(sample_ct_x * subbatch_size, &pheno_x_d)) {
4153 continue;
4154 }
4155 if (common->nm_precomp_x) {
4156 // domdev_present can't be set here.
4157 if (bigstack_alloc_d((2 + (1 - is_qt_residualize) * covar_ct_x) * subbatch_size, &(common->nm_precomp_x->xt_y_image))) {
4158 continue;
4159 }
4160 }
4161 }
4162 if (sample_ct_y) {
4163 if (bigstack_alloc_d(sample_ct_y * subbatch_size, &pheno_y_d)) {
4164 continue;
4165 }
4166 if (common->nm_precomp_y) {
4167 if (bigstack_alloc_d((2 + (1 - is_qt_residualize) * covar_ct_y) * subbatch_size, &(common->nm_precomp_y->xt_y_image))) {
4168 continue;
4169 }
4170 }
4171 }
4172 workspace_alloc = GetLinearSubbatchWorkspaceSize(sample_ct, subbatch_size, biallelic_predictor_ct, max_extra_allele_ct, constraint_ct, xmain_ct, max_returned_difflist_len);
4173 if (sample_ct_x) {
4174 const uintptr_t workspace_alloc_x = GetLinearSubbatchWorkspaceSize(sample_ct_x, subbatch_size, biallelic_predictor_ct_x, max_extra_allele_ct, constraint_ct_x, xmain_ct, max_returned_difflist_len);
4175 if (workspace_alloc_x > workspace_alloc) {
4176 workspace_alloc = workspace_alloc_x;
4177 }
4178 }
4179 if (sample_ct_y) {
4180 const uintptr_t workspace_alloc_y = GetLinearSubbatchWorkspaceSize(sample_ct_y, subbatch_size, biallelic_predictor_ct_y, max_extra_allele_ct, constraint_ct_y, xmain_ct, max_returned_difflist_len);
4181 if (workspace_alloc_y > workspace_alloc) {
4182 workspace_alloc = workspace_alloc_y;
4183 }
4184 }
4185 uintptr_t thread_xalloc_cacheline_ct = (workspace_alloc / kCacheline) + 1;
4186 uintptr_t per_variant_xalloc_byte_ct = max_sample_ct * local_covar_ct * sizeof(double);
4187 uintptr_t per_alt_allele_xalloc_byte_ct = sizeof(LinearAuxResult);
4188 if (beta_se_multiallelic_fused) {
4189 per_variant_xalloc_byte_ct += 2 * max_reported_test_ct * subbatch_size * sizeof(double);
4190 } else {
4191 per_alt_allele_xalloc_byte_ct += 2 * max_reported_test_ct * subbatch_size * sizeof(double);
4192 }
4193
4194 uintptr_t bytes_avail = bigstack_left();
4195 if (bytes_avail < cstream_alloc_size * subbatch_size + qt_residualize_alloc_size) {
4196 continue;
4197 }
4198 bytes_avail -= cstream_alloc_size * subbatch_size + qt_residualize_alloc_size;
4199 if (!PgenMtLoadInit(variant_include, max_sample_ct, variant_ct, bytes_avail, pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, per_variant_xalloc_byte_ct, per_alt_allele_xalloc_byte_ct, pgfip, &calc_thread_ct, &common->genovecs, max_extra_allele_ct? (&common->thread_mhc) : nullptr, nullptr, nullptr, dosage_is_present? (&common->dosage_presents) : nullptr, dosage_is_present? (&common->dosage_mains) : nullptr, nullptr, nullptr, &read_block_size, &max_alt_allele_block_size, main_loadbufs, &common->pgr_ptrs, &common->read_variant_uidx_starts)) {
4200 break;
4201 }
4202 }
4203 g_failed_alloc_attempt_size = 0;
4204 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
4205 goto GlmLinearBatch_ret_NOMEM;
4206 }
4207 LinearAuxResult* linear_block_aux_bufs[2];
4208 double* block_beta_se_bufs[2];
4209
4210 for (uint32_t uii = 0; uii != 2; ++uii) {
4211 if (unlikely(BIGSTACK_ALLOC_X(LinearAuxResult, max_alt_allele_block_size, &(linear_block_aux_bufs[uii])))) {
4212 // shouldn't be possible for these to fail?
4213 goto GlmLinearBatch_ret_NOMEM;
4214 }
4215 if (beta_se_multiallelic_fused) {
4216 if (unlikely(bigstack_alloc_d(read_block_size * (2 * k1LU) * max_reported_test_ct * subbatch_size, &(block_beta_se_bufs[uii])))) {
4217 goto GlmLinearBatch_ret_NOMEM;
4218 }
4219 } else {
4220 if (unlikely(bigstack_alloc_d(max_alt_allele_block_size * 2 * max_reported_test_ct * subbatch_size, &(block_beta_se_bufs[uii])))) {
4221 goto GlmLinearBatch_ret_NOMEM;
4222 }
4223 }
4224 if (local_covar_ct) {
4225 if (unlikely(bigstack_alloc_d(read_block_size * max_sample_ct * local_covar_ct, &(ctx->local_covars_vcmaj_d[uii])))) {
4226 goto GlmLinearBatch_ret_NOMEM;
4227 }
4228 } else {
4229 ctx->local_covars_vcmaj_d[uii] = nullptr;
4230 }
4231 }
4232
4233 common->workspace_bufs = S_CAST(unsigned char**, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(intptr_t)));
4234 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
4235 common->workspace_bufs[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(workspace_alloc));
4236 }
4237 common->err_info = (~0LLU) << 32;
4238 SetThreadFuncAndData(GlmLinearSubbatchThread, ctx, &tg);
4239
4240 const uint32_t subbatch_ct = 1 + (batch_size - 1) / subbatch_size;
4241
4242 const uint32_t ref_col = glm_cols & kfGlmColRef;
4243 const uint32_t alt1_col = glm_cols & kfGlmColAlt1;
4244 const uint32_t alt_col = glm_cols & kfGlmColAlt;
4245 const uintptr_t* nonref_flags = pgfip->nonref_flags;
4246 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
4247 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, glm_cols / kfGlmColMaybeprovref, raw_variant_ct, all_nonref);
4248 const uint32_t omitted_col = glm_cols & kfGlmColOmitted;
4249 const uint32_t ax_col = glm_cols & kfGlmColAx;
4250 const uint32_t a1_ct_col = glm_cols & kfGlmColA1count;
4251 const uint32_t tot_allele_col = glm_cols & kfGlmColTotallele;
4252 const uint32_t a1_freq_col = glm_cols & kfGlmColA1freq;
4253 const uint32_t mach_r2_col = glm_cols & kfGlmColMachR2;
4254 const uint32_t nobs_col = glm_cols & kfGlmColNobs;
4255 const uint32_t beta_col = glm_cols & (kfGlmColBeta | kfGlmColOrbeta);
4256 const uint32_t se_col = glm_cols & kfGlmColSe;
4257 const uint32_t ci_col = (ci_size != 0.0) && (glm_cols & kfGlmColCi);
4258 const uint32_t t_col = glm_cols & kfGlmColTz;
4259 const uint32_t p_col = glm_cols & kfGlmColP;
4260 const uint32_t err_col = glm_cols & kfGlmColErr;
4261 double ci_zt = 0.0;
4262 if (ci_col) {
4263 ci_zt = QuantileToZscore((ci_size + 1.0) * 0.5);
4264 }
4265 for (uint32_t subbatch_idx = 0; subbatch_idx != subbatch_ct; ++subbatch_idx) {
4266 const uint32_t pheno_uidx_start = IdxToUidxBasic(pheno_batch, subbatch_idx * subbatch_size);
4267 if (subbatch_idx == subbatch_ct - 1) {
4268 subbatch_size = batch_size - subbatch_idx * subbatch_size;
4269 }
4270 ctx->subbatch_size = subbatch_size;
4271 uint32_t pheno_uidx = pheno_uidx_start;
4272 for (uint32_t fidx = 0; fidx != subbatch_size; ++fidx, ++pheno_uidx) {
4273 pheno_uidx = AdvTo1Bit(pheno_batch, pheno_uidx);
4274 const char* cur_pheno_name = &(pheno_names[pheno_uidx * max_pheno_name_blen]);
4275 char* outname_end2 = strcpya(&(outname_end[1]), cur_pheno_name);
4276 outname_end2 = strcpya_k(outname_end2, ".glm.linear");
4277 if (output_zst) {
4278 snprintf(outname_end2, 22, ".zst");
4279 } else {
4280 *outname_end2 = '\0';
4281 }
4282
4283 // forced-singlethreaded
4284 char* cswritep;
4285 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &(css_arr[fidx]), &cswritep);
4286 if (unlikely(reterr)) {
4287 goto GlmLinearBatch_ret_1;
4288 }
4289 if (outfnames_ll_ptr) {
4290 if (unlikely(PushLlStr(outname, outfnames_ll_ptr))) {
4291 goto GlmLinearBatch_ret_NOMEM;
4292 }
4293 }
4294 *cswritep++ = '#';
4295 if (chr_col) {
4296 cswritep = strcpya_k(cswritep, "CHROM\t");
4297 }
4298 if (variant_bps) {
4299 cswritep = strcpya_k(cswritep, "POS\t");
4300 }
4301 cswritep = strcpya_k(cswritep, "ID");
4302 if (ref_col) {
4303 cswritep = strcpya_k(cswritep, "\tREF");
4304 }
4305 if (alt1_col) {
4306 cswritep = strcpya_k(cswritep, "\tALT1");
4307 }
4308 if (alt_col) {
4309 cswritep = strcpya_k(cswritep, "\tALT");
4310 }
4311 if (provref_col) {
4312 cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
4313 }
4314 cswritep = strcpya_k(cswritep, "\tA1");
4315 if (omitted_col) {
4316 cswritep = strcpya_k(cswritep, "\tOMITTED");
4317 }
4318 if (ax_col) {
4319 cswritep = strcpya_k(cswritep, "\tAX");
4320 }
4321 if (a1_ct_col) {
4322 cswritep = strcpya_k(cswritep, "\tA1_CT");
4323 }
4324 if (tot_allele_col) {
4325 cswritep = strcpya_k(cswritep, "\tALLELE_CT");
4326 }
4327 if (a1_freq_col) {
4328 cswritep = strcpya_k(cswritep, "\tA1_FREQ");
4329 }
4330 if (mach_r2_col) {
4331 cswritep = strcpya_k(cswritep, "\tMACH_R2");
4332 }
4333 if (test_col) {
4334 cswritep = strcpya_k(cswritep, "\tTEST");
4335 }
4336 if (nobs_col) {
4337 cswritep = strcpya_k(cswritep, "\tOBS_CT");
4338 }
4339 if (beta_col) {
4340 cswritep = strcpya_k(cswritep, "\tBETA");
4341 }
4342 if (se_col) {
4343 cswritep = strcpya_k(cswritep, "\tSE");
4344 }
4345 if (ci_col) {
4346 cswritep = strcpya_k(cswritep, "\tL");
4347 cswritep = dtoa_g(ci_size * 100, cswritep);
4348 cswritep = strcpya_k(cswritep, "\tU");
4349 cswritep = dtoa_g(ci_size * 100, cswritep);
4350 }
4351 if (t_col) {
4352 if (!constraint_ct) {
4353 cswritep = strcpya_k(cswritep, "\tT_STAT");
4354 } else {
4355 // F-statistic for joint tests.
4356 cswritep = strcpya_k(cswritep, "\tT_OR_F_STAT");
4357 }
4358 }
4359 if (p_col) {
4360 if (report_neglog10p) {
4361 cswritep = strcpya_k(cswritep, "\tNEG_LOG10_P");
4362 } else {
4363 cswritep = strcpya_k(cswritep, "\tP");
4364 }
4365 }
4366 if (err_col) {
4367 cswritep = strcpya_k(cswritep, "\tERRCODE");
4368 }
4369 AppendBinaryEoln(&cswritep);
4370 cswritep_arr[fidx] = cswritep;
4371
4372 if (!is_qt_residualize) {
4373 FillPhenoAndXtY(sample_include, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_d, sample_ct, domdev_present_p1, covar_ct, common->nm_precomp? (&(common->nm_precomp->xt_y_image[fidx * (1 + domdev_present_p1 + covar_ct)])) : nullptr, &(pheno_d[fidx * sample_ct]));
4374 if (sample_ct_x) {
4375 FillPhenoAndXtY(common->sample_include_x, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_x_d, sample_ct_x, domdev_present_p1, covar_ct_x, common->nm_precomp_x? (&(common->nm_precomp_x->xt_y_image[fidx * (1 + domdev_present_p1 + covar_ct_x)])) : nullptr, &(pheno_x_d[fidx * sample_ct_x]));
4376 }
4377 if (sample_ct_y) {
4378 FillPhenoAndXtY(common->sample_include_y, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_y_d, sample_ct_y, domdev_present_p1, covar_ct_y, common->nm_precomp_y? (&(common->nm_precomp_y->xt_y_image[fidx * (1 + domdev_present_p1 + covar_ct_y)])) : nullptr, &(pheno_y_d[fidx * sample_ct_y]));
4379 }
4380 } else {
4381 if (unlikely(FillResidualizedPhenoAndXtY(sample_include, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_d, sample_ct, domdev_present_p1, covar_ct, &(common->nm_precomp->xt_y_image[fidx * (1 + domdev_present_p1)]), &(pheno_d[fidx * sample_ct])))) {
4382 // shouldn't be possible
4383 goto GlmLinearBatch_ret_NOMEM;
4384 }
4385 if (sample_ct_x) {
4386 FillResidualizedPhenoAndXtY(common->sample_include_x, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_x_d, sample_ct_x, domdev_present_p1, covar_ct_x, &(common->nm_precomp_x->xt_y_image[fidx * (1 + domdev_present_p1)]), &(pheno_x_d[fidx * sample_ct_x]));
4387 }
4388 if (sample_ct_y) {
4389 FillResidualizedPhenoAndXtY(common->sample_include_y, pheno_cols[pheno_uidx].data.qt, ctx->covars_cmaj_y_d, sample_ct_y, domdev_present_p1, covar_ct_y, &(common->nm_precomp_y->xt_y_image[fidx * (1 + domdev_present_p1)]), &(pheno_y_d[fidx * sample_ct_y]));
4390 }
4391 }
4392 ctx->pheno_d = pheno_d;
4393 ctx->pheno_x_d = pheno_x_d;
4394 ctx->pheno_y_d = pheno_y_d;
4395 }
4396 if (is_qt_residualize) {
4397 common->covar_ct = 0;
4398 common->covar_ct_x = 0;
4399 common->covar_ct_y = 0;
4400 ClearNmPrecompCovars(sample_ct, domdev_present_p1, common->nm_precomp);
4401 if (sample_ct_x) {
4402 ClearNmPrecompCovars(sample_ct_x, domdev_present_p1, common->nm_precomp_x);
4403 }
4404 if (sample_ct_y) {
4405 ClearNmPrecompCovars(sample_ct_y, domdev_present_p1, common->nm_precomp_x);
4406 }
4407 }
4408
4409 // Main workflow:
4410 // 1. Set n=0, load/skip block 0
4411 //
4412 // 2. Spawn threads processing block n
4413 // 3. If n>0, write results for block (n-1)
4414 // 4. Increment n by 1
4415 // 5. Load/skip block n unless eof
4416 // 6. Join threads
4417 // 7. Goto step 2 unless eof
4418 //
4419 // 8, Write results for last block
4420 uintptr_t write_variant_uidx_base = 0;
4421 uintptr_t cur_bits = variant_include[0];
4422 uint32_t parity = 0;
4423 uint32_t read_block_idx = 0;
4424 uint32_t chr_fo_idx = UINT32_MAX;
4425 uint32_t chr_end = 0;
4426 uint32_t chr_buf_blen = 0;
4427 uint32_t suppress_mach_r2 = 0;
4428
4429 uint32_t cur_biallelic_reported_test_ct = 0;
4430 uint32_t primary_reported_test_idx = include_intercept;
4431 uint32_t cur_biallelic_predictor_ct = 0;
4432 uint32_t cur_constraint_ct = 0;
4433
4434 const char* const* cur_test_names = nullptr;
4435 uint32_t prev_block_variant_ct = 0;
4436 uint32_t pct = 0;
4437 uint32_t next_print_variant_idx = variant_ct / 100;
4438 uint32_t allele_ct = 2;
4439 uint32_t omitted_allele_idx = 0;
4440 if (subbatch_size > 1) {
4441 logprintfww5("--glm linear regression on quantitative phenotypes #%u-%u: ", completed_pheno_ct + 1, completed_pheno_ct + subbatch_size);
4442 } else {
4443 logprintfww5("--glm linear regression on phenotype '%s': ", &(pheno_names[pheno_uidx_start * max_pheno_name_blen]));
4444 }
4445 fputs("0%", stdout);
4446 fflush(stdout);
4447 // bugfix (12 May 2019): need to reinitialize this
4448 pgfip->block_base = main_loadbufs[0];
4449 ReinitThreads(&tg);
4450 for (uint32_t variant_idx = 0; ; ) {
4451 const uint32_t cur_block_variant_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
4452 if (unlikely(reterr)) {
4453 goto GlmLinearBatch_ret_PGR_FAIL;
4454 }
4455 if (local_covar_ct && cur_block_variant_ct) {
4456 const uint32_t uidx_start = read_block_idx * read_block_size;
4457 const uint32_t uidx_end = MINV(raw_variant_ct, uidx_start + read_block_size);
4458 if (local_variant_include) {
4459 reterr = ReadLocalCovarBlock(common, local_sample_uidx_order, local_variant_include, uidx_start, uidx_end, cur_block_variant_ct, local_sample_ct, glm_info_ptr->local_cat_ct, local_covar_txsp, &local_line_idx, &local_xy, nullptr, ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
4460 } else {
4461 double* prev_local_covar_row_d = nullptr;
4462 if (variant_idx) {
4463 prev_local_covar_row_d = &(ctx->local_covars_vcmaj_d[1 - parity][S_CAST(uintptr_t, read_block_size - 1) * max_sample_ct * local_covar_ct]);
4464 }
4465 reterr = ReadRfmix2Block(common, variant_bps, local_sample_uidx_order, nullptr, prev_local_covar_row_d, uidx_start, uidx_end, cur_block_variant_ct, local_sample_ct, glm_info_ptr->local_cat_ct, glm_info_ptr->local_chrom_col, glm_info_ptr->local_bp_col, glm_info_ptr->local_first_covar_col, local_covar_txsp, &local_line_iter, &local_line_idx, &local_prev_chr_code, &local_chr_code, &local_bp, &local_skip_chr, nullptr, ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
4466 }
4467 if (unlikely(reterr)) {
4468 goto GlmLinearBatch_ret_1;
4469 }
4470 }
4471 if (variant_idx) {
4472 JoinThreads(&tg);
4473 reterr = S_CAST(PglErr, common->err_info);
4474 if (unlikely(reterr)) {
4475 PgenErrPrintNV(reterr, common->err_info >> 32);
4476 goto GlmLinearBatch_ret_1;
4477 }
4478 }
4479 if (!IsLastBlock(&tg)) {
4480 common->cur_block_variant_ct = cur_block_variant_ct;
4481 const uint32_t uidx_start = read_block_idx * read_block_size;
4482 ComputeUidxStartPartition(variant_include, cur_block_variant_ct, calc_thread_ct, uidx_start, common->read_variant_uidx_starts);
4483 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, common->pgr_ptrs);
4484 ctx->block_aux = linear_block_aux_bufs[parity];
4485 common->block_beta_se = block_beta_se_bufs[parity];
4486 if (variant_idx + cur_block_variant_ct == variant_ct) {
4487 DeclareLastThreadBlock(&tg);
4488 }
4489 if (unlikely(SpawnThreads(&tg))) {
4490 goto GlmLinearBatch_ret_THREAD_CREATE_FAIL;
4491 }
4492 }
4493 parity = 1 - parity;
4494 if (variant_idx) {
4495 // write *previous* block results
4496 const double* beta_se_iter = block_beta_se_bufs[parity];
4497 const LinearAuxResult* cur_block_aux = linear_block_aux_bufs[parity];
4498 uintptr_t allele_bidx = 0;
4499 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_variant_ct; ++variant_bidx) {
4500 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
4501 if (write_variant_uidx >= chr_end) {
4502 do {
4503 ++chr_fo_idx;
4504 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
4505 } while (write_variant_uidx >= chr_end);
4506 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
4507 if ((chr_idx == x_code) && sample_ct_x) {
4508 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_x;
4509 cur_biallelic_predictor_ct = biallelic_predictor_ct_x;
4510 cur_constraint_ct = constraint_ct_x;
4511 cur_test_names = test_names_x;
4512 } else if ((chr_idx == y_code) && sample_ct_y) {
4513 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_y;
4514 cur_biallelic_predictor_ct = biallelic_predictor_ct_y;
4515 cur_constraint_ct = constraint_ct_y;
4516 cur_test_names = test_names_y;
4517 } else {
4518 cur_biallelic_reported_test_ct = biallelic_reported_test_ct;
4519 cur_biallelic_predictor_ct = biallelic_predictor_ct;
4520 cur_constraint_ct = constraint_ct;
4521 cur_test_names = test_names;
4522 }
4523 suppress_mach_r2 = (chr_idx == x_code) || (chr_idx == mt_code);
4524 if (cur_constraint_ct) {
4525 primary_reported_test_idx = cur_biallelic_reported_test_ct - 1;
4526 }
4527 if (chr_col) {
4528 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
4529 *chr_name_end = '\t';
4530 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
4531 }
4532 }
4533 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
4534 if (allele_idx_offsets) {
4535 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
4536 allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offsets[write_variant_uidx];
4537 }
4538 const uint32_t allele_ct_m1 = allele_ct - 1;
4539 const uint32_t extra_allele_ct = allele_ct - 2;
4540 if (omitted_alleles) {
4541 omitted_allele_idx = omitted_alleles[write_variant_uidx];
4542 }
4543 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
4544 for (uint32_t fidx = 0; fidx != subbatch_size; ++fidx) {
4545 char* cswritep = cswritep_arr[fidx];
4546 uint32_t a1_allele_idx = 0;
4547 uintptr_t allele_bidx_tmp = allele_bidx;
4548 // bugfix (20 Mar 2020): In multiallelic unfused case, fidx is
4549 // the *inner* index, allele index is on the outside.
4550 const double* beta_se_iter2 = beta_se_iter;
4551 for (uint32_t nonomitted_allele_idx = 0; nonomitted_allele_idx != allele_ct_m1; ++nonomitted_allele_idx, ++a1_allele_idx) {
4552 if (beta_se_multiallelic_fused) {
4553 if (!nonomitted_allele_idx) {
4554 primary_reported_test_idx = include_intercept;
4555 } else {
4556 primary_reported_test_idx = cur_biallelic_reported_test_ct + nonomitted_allele_idx - 1;
4557 }
4558 }
4559 if (nonomitted_allele_idx == omitted_allele_idx) {
4560 ++a1_allele_idx;
4561 }
4562 const double primary_beta = beta_se_iter2[primary_reported_test_idx * 2];
4563 const double primary_se = beta_se_iter2[primary_reported_test_idx * 2 + 1];
4564 const uint32_t allele_is_valid = (primary_se != -9.0);
4565 {
4566 const LinearAuxResult* auxp = &(cur_block_aux[allele_bidx_tmp]);
4567 if (ln_pfilter <= 0.0) {
4568 if (!allele_is_valid) {
4569 goto GlmLinearBatch_allele_iterate;
4570 }
4571 double primary_ln_pval;
4572 if (!cur_constraint_ct) {
4573 if (primary_beta == 0.0) {
4574 primary_ln_pval = 0.0;
4575 } else if (primary_se == 0.0) {
4576 primary_ln_pval = -DBL_MAX;
4577 } else {
4578 const double primary_tstat = primary_beta / primary_se;
4579 primary_ln_pval = TstatToLnP(primary_tstat, auxp->sample_obs_ct - cur_biallelic_predictor_ct - extra_allele_ct);
4580 }
4581 } else {
4582 primary_ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
4583 }
4584 if (primary_ln_pval > ln_pfilter) {
4585 goto GlmLinearBatch_allele_iterate;
4586 }
4587 }
4588 uint32_t inner_reported_test_ct = cur_biallelic_reported_test_ct;
4589 if (extra_allele_ct) {
4590 if (beta_se_multiallelic_fused) {
4591 if (!nonomitted_allele_idx) {
4592 inner_reported_test_ct = 1 + include_intercept;
4593 } else if (nonomitted_allele_idx == extra_allele_ct) {
4594 inner_reported_test_ct -= include_intercept;
4595 } else {
4596 inner_reported_test_ct = 1;
4597 }
4598 } else if (!hide_covar) {
4599 inner_reported_test_ct += extra_allele_ct;
4600 }
4601 }
4602 // possible todo: make number-to-string operations, strlen(),
4603 // etc. happen only once per variant.
4604 for (uint32_t allele_test_idx = 0; allele_test_idx != inner_reported_test_ct; ++allele_test_idx) {
4605 uint32_t test_idx = allele_test_idx;
4606 if (beta_se_multiallelic_fused && nonomitted_allele_idx) {
4607 if (!allele_test_idx) {
4608 test_idx = primary_reported_test_idx;
4609 } else {
4610 ++test_idx;
4611 }
4612 }
4613 if (chr_col) {
4614 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
4615 }
4616 if (variant_bps) {
4617 cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep);
4618 }
4619 cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
4620 if (ref_col) {
4621 *cswritep++ = '\t';
4622 cswritep = strcpya(cswritep, cur_alleles[0]);
4623 }
4624 if (alt1_col) {
4625 *cswritep++ = '\t';
4626 cswritep = strcpya(cswritep, cur_alleles[1]);
4627 }
4628 if (alt_col) {
4629 *cswritep++ = '\t';
4630 for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) {
4631 if (unlikely(Cswrite(&(css_arr[fidx]), &cswritep))) {
4632 // might not need this assignment, but play it safe
4633 // for now
4634 cswritep_arr[fidx] = cswritep;
4635 goto GlmLinearBatch_ret_WRITE_FAIL;
4636 }
4637 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
4638 }
4639 --cswritep;
4640 }
4641 *cswritep++ = '\t';
4642 if (provref_col) {
4643 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N';
4644 *cswritep++ = '\t';
4645 }
4646 const uint32_t multi_a1 = extra_allele_ct && beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx);
4647 if (multi_a1) {
4648 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4649 if (allele_idx == omitted_allele_idx) {
4650 continue;
4651 }
4652 if (unlikely(Cswrite(&(css_arr[fidx]), &cswritep))) {
4653 cswritep_arr[fidx] = cswritep;
4654 goto GlmLinearBatch_ret_WRITE_FAIL;
4655 }
4656 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
4657 }
4658 --cswritep;
4659 } else {
4660 cswritep = strcpya(cswritep, cur_alleles[a1_allele_idx]);
4661 }
4662 if (omitted_col) {
4663 *cswritep++ = '\t';
4664 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
4665 }
4666 if (ax_col) {
4667 *cswritep++ = '\t';
4668 if (beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx)) {
4669 if (unlikely(Cswrite(&(css_arr[fidx]), &cswritep))) {
4670 cswritep_arr[fidx] = cswritep;
4671 goto GlmLinearBatch_ret_WRITE_FAIL;
4672 }
4673 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
4674 } else {
4675 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4676 if (allele_idx == a1_allele_idx) {
4677 continue;
4678 }
4679 if (unlikely(Cswrite(&(css_arr[fidx]), &cswritep))) {
4680 cswritep_arr[fidx] = cswritep;
4681 goto GlmLinearBatch_ret_WRITE_FAIL;
4682 }
4683 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
4684 }
4685 --cswritep;
4686 }
4687 }
4688 if (a1_ct_col) {
4689 *cswritep++ = '\t';
4690 if (!multi_a1) {
4691 cswritep = dtoa_g(auxp->a1_dosage, cswritep);
4692 } else {
4693 cswritep = strcpya_k(cswritep, "NA");
4694 }
4695 }
4696 if (tot_allele_col) {
4697 *cswritep++ = '\t';
4698 cswritep = u32toa(auxp->allele_obs_ct, cswritep);
4699 }
4700 if (a1_freq_col) {
4701 *cswritep++ = '\t';
4702 if (!multi_a1) {
4703 cswritep = dtoa_g(auxp->a1_dosage / S_CAST(double, auxp->allele_obs_ct), cswritep);
4704 } else {
4705 cswritep = strcpya_k(cswritep, "NA");
4706 }
4707 }
4708 if (mach_r2_col) {
4709 *cswritep++ = '\t';
4710 if (!suppress_mach_r2) {
4711 cswritep = dtoa_g(auxp->mach_r2, cswritep);
4712 } else {
4713 cswritep = strcpya_k(cswritep, "NA");
4714 }
4715 }
4716 if (test_col) {
4717 *cswritep++ = '\t';
4718 if (test_idx < cur_biallelic_reported_test_ct) {
4719 cswritep = strcpya(cswritep, cur_test_names[test_idx]);
4720 } else {
4721 // always use basic dosage for untested alleles
4722 cswritep = strcpya_k(cswritep, "ADD");
4723 if (!beta_se_multiallelic_fused) {
4724 // extra alt allele covariate.
4725 uint32_t test_xallele_idx = test_idx - cur_biallelic_reported_test_ct;
4726 if (omitted_allele_idx < a1_allele_idx) {
4727 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
4728 }
4729 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= a1_allele_idx);
4730 if (a1_allele_idx < omitted_allele_idx) {
4731 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
4732 }
4733 if (!test_xallele_idx) {
4734 cswritep = strcpya_k(cswritep, "_REF");
4735 } else {
4736 cswritep = strcpya_k(cswritep, "_ALT");
4737 cswritep = u32toa(test_xallele_idx, cswritep);
4738 }
4739 }
4740 }
4741 }
4742 if (nobs_col) {
4743 *cswritep++ = '\t';
4744 cswritep = u32toa(auxp->sample_obs_ct, cswritep);
4745 }
4746 double ln_pval = kLnPvalError;
4747 double tstat = 0.0;
4748 uint32_t test_is_valid;
4749 if ((!cur_constraint_ct) || (test_idx != primary_reported_test_idx)) {
4750 double beta = beta_se_iter2[2 * test_idx];
4751 double se = beta_se_iter2[2 * test_idx + 1];
4752 test_is_valid = (se != -9.0);
4753 if (test_is_valid) {
4754 tstat = beta / se;
4755 ln_pval = TstatToLnP(tstat, auxp->sample_obs_ct - cur_biallelic_predictor_ct - extra_allele_ct);
4756 }
4757 if (beta_col) {
4758 *cswritep++ = '\t';
4759 if (test_is_valid) {
4760 cswritep = dtoa_g(beta, cswritep);
4761 } else {
4762 cswritep = strcpya_k(cswritep, "NA");
4763 }
4764 }
4765 if (se_col) {
4766 *cswritep++ = '\t';
4767 if (test_is_valid) {
4768 cswritep = dtoa_g(se, cswritep);
4769 } else {
4770 cswritep = strcpya_k(cswritep, "NA");
4771 }
4772 }
4773 if (ci_col) {
4774 *cswritep++ = '\t';
4775 if (test_is_valid) {
4776 const double ci_halfwidth = ci_zt * se;
4777 cswritep = dtoa_g(beta - ci_halfwidth, cswritep);
4778 *cswritep++ = '\t';
4779 cswritep = dtoa_g(beta + ci_halfwidth, cswritep);
4780 } else {
4781 cswritep = strcpya_k(cswritep, "NA\tNA");
4782 }
4783 }
4784 if (t_col) {
4785 *cswritep++ = '\t';
4786 if (test_is_valid) {
4787 cswritep = dtoa_g(tstat, cswritep);
4788 } else {
4789 cswritep = strcpya_k(cswritep, "NA");
4790 }
4791 }
4792 } else {
4793 // joint test
4794 test_is_valid = allele_is_valid;
4795 if (beta_col) {
4796 cswritep = strcpya_k(cswritep, "\tNA");
4797 }
4798 if (se_col) {
4799 cswritep = strcpya_k(cswritep, "\tNA");
4800 }
4801 if (ci_col) {
4802 cswritep = strcpya_k(cswritep, "\tNA\tNA");
4803 }
4804 if (t_col) {
4805 *cswritep++ = '\t';
4806 if (test_is_valid) {
4807 cswritep = dtoa_g(primary_se / u31tod(cur_constraint_ct), cswritep);
4808 } else {
4809 cswritep = strcpya_k(cswritep, "NA");
4810 }
4811 }
4812 // could avoid recomputing
4813 if (test_is_valid) {
4814 ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
4815 }
4816 }
4817 if (p_col) {
4818 *cswritep++ = '\t';
4819 if (test_is_valid) {
4820 if (report_neglog10p) {
4821 const double reported_val = (-kRecipLn10) * ln_pval;
4822 cswritep = dtoa_g(reported_val, cswritep);
4823 } else {
4824 const double reported_ln = MAXV(ln_pval, output_min_ln);
4825 cswritep = lntoa_g(reported_ln, cswritep);
4826 }
4827 } else {
4828 cswritep = strcpya_k(cswritep, "NA");
4829 }
4830 }
4831 if (err_col) {
4832 *cswritep++ = '\t';
4833 if (test_is_valid) {
4834 *cswritep++ = '.';
4835 } else {
4836 uint64_t glm_errcode;
4837 memcpy(&glm_errcode, &(beta_se_iter2[2 * test_idx]), 8);
4838 cswritep = AppendGlmErrstr(glm_errcode, cswritep);
4839 }
4840 }
4841 AppendBinaryEoln(&cswritep);
4842 if (unlikely(Cswrite(&(css_arr[fidx]), &cswritep))) {
4843 cswritep_arr[fidx] = cswritep;
4844 goto GlmLinearBatch_ret_WRITE_FAIL;
4845 }
4846 }
4847 }
4848 GlmLinearBatch_allele_iterate:
4849 ++allele_bidx_tmp;
4850 if (!beta_se_multiallelic_fused) {
4851 beta_se_iter2 = &(beta_se_iter2[subbatch_size * (2 * k1LU) * max_reported_test_ct]);
4852 }
4853 } // for nonomitted_allele_idx
4854 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
4855 cswritep_arr[fidx] = cswritep;
4856 } // for fidx
4857 if (!beta_se_multiallelic_fused) {
4858 beta_se_iter = &(beta_se_iter[extra_allele_ct * subbatch_size * (2 * k1LU) * max_reported_test_ct]);
4859 }
4860 allele_bidx += allele_ct_m1;
4861 } // for variant_bidx
4862 }
4863 if (variant_idx == variant_ct) {
4864 break;
4865 }
4866 if (variant_idx >= next_print_variant_idx) {
4867 if (pct > 10) {
4868 putc_unlocked('\b', stdout);
4869 }
4870 pct = (variant_idx * 100LLU) / variant_ct;
4871 printf("\b\b%u%%", pct++);
4872 fflush(stdout);
4873 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
4874 }
4875 ++read_block_idx;
4876 prev_block_variant_ct = cur_block_variant_ct;
4877 variant_idx += cur_block_variant_ct;
4878 // crucially, this is independent of the PgenReader block_base
4879 // pointers
4880 pgfip->block_base = main_loadbufs[parity];
4881 }
4882 for (uintptr_t fidx = 0; fidx != subbatch_size; ++fidx) {
4883 if (unlikely(CswriteCloseNull(&(css_arr[fidx]), cswritep_arr[fidx]))) {
4884 goto GlmLinearBatch_ret_WRITE_FAIL;
4885 }
4886 }
4887 if (pct > 10) {
4888 putc_unlocked('\b', stdout);
4889 }
4890 fputs("\b\b", stdout);
4891 logputs("done.\n");
4892 // bugfix (12 May 2019): added batch_size instead of subbatch_size here
4893 completed_pheno_ct += subbatch_size;
4894 }
4895 outname_end[1] = '\0';
4896 logprintfww("Results written to %s<phenotype name>.glm.linear%s .\n", outname, output_zst? ".zst" : "");
4897 }
4898 while (0) {
4899 GlmLinearBatch_ret_NOMEM:
4900 reterr = kPglRetNomem;
4901 break;
4902 GlmLinearBatch_ret_TSTREAM_FAIL:
4903 TextStreamErrPrint("--glm local-covar= file", local_covar_txsp);
4904 break;
4905 GlmLinearBatch_ret_PGR_FAIL:
4906 PgenErrPrintN(reterr);
4907 break;
4908 GlmLinearBatch_ret_WRITE_FAIL:
4909 reterr = kPglRetWriteFail;
4910 break;
4911 GlmLinearBatch_ret_INCONSISTENT_INPUT:
4912 reterr = kPglRetInconsistentInput;
4913 break;
4914 GlmLinearBatch_ret_THREAD_CREATE_FAIL:
4915 reterr = kPglRetThreadCreateFail;
4916 break;
4917 }
4918 GlmLinearBatch_ret_1:
4919 CleanupThreads(&tg);
4920 if (css_arr) {
4921 for (uintptr_t fidx = 0; fidx != subbatch_size; ++fidx) {
4922 CswriteCloseCond(&(css_arr[fidx]), cswritep_arr[fidx]);
4923 }
4924 }
4925 BigstackReset(bigstack_mark);
4926 pgfip->block_base = nullptr;
4927 return reterr;
4928 }
4929
4930 #ifdef __cplusplus
4931 } // namespace plink2
4932 #endif