Debian Codegraph @

plink2_glm_shared.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_glm_shared.h"
19
20 #ifdef __cplusplus
21 namespace plink2 {
22 #endif
23
24 static const char kGlmErrcodeStrs[][24] = {"", "SAMPLE_CT<=PREDICTOR_CT", "CONST_OMITTED_ALLELE", "CONST_ALLELE", "CORR_TOO_HIGH", "VIF_INFINITE", "VIF_TOO_HIGH", "SEPARATION", "RANK_DEFICIENT", "LOGISTIC_CONVERGE_FAIL", "FIRTH_CONVERGE_FAIL", "INVALID_RESULT"};
25
26 char* AppendGlmErrstr(GlmErr glm_err, char* write_iter) {
27 // todo: support predictor args
28 GlmErrcode errcode = GetGlmErrCode(glm_err);
29 write_iter = strcpya(write_iter, kGlmErrcodeStrs[errcode]);
30 if (errcode == kGlmErrcodeSeparation) {
31 *write_iter++ = ',';
32 const uint32_t allele_idx = GetGlmErrArg1(glm_err);
33 if (!allele_idx) {
34 write_iter = strcpya_k(write_iter, "REF");
35 } else {
36 write_iter = strcpya_k(write_iter, "ALT");
37 write_iter = u32toa(allele_idx, write_iter);
38 }
39 }
40 return write_iter;
41 }
42
43 // * first_predictor_idx should be 1 if first term is constant-1 intercept, 0
44 // otherwise
45 // * dbl_2d_buf[n] expected to be sum of predictor row n on input, is destroyed
46 // * if corr_buf is not nullptr, lower left is filled with uninverted
47 // correlation matrix on exit
48 // * lower left of inverse_corr_buf is filled on return
49 GlmErr CheckMaxCorrAndVif(const double* predictor_dotprods, uint32_t first_predictor_idx, uint32_t predictor_ct, uintptr_t sample_ct, double max_corr, double vif_thresh, double* dbl_2d_buf, double* corr_buf, double* inverse_corr_buf, MatrixInvertBuf1* matrix_invert_buf1) {
50 // we have dot products, now determine
51 // (dotprod - sum(a)mean(b)) / (N-1)
52 // to get small-sample covariance
53 const uintptr_t relevant_predictor_ct = predictor_ct - first_predictor_idx;
54 if (relevant_predictor_ct == 1) {
55 // bugfix (31 Jul 2019): precomputed images are wrong if these aren't
56 // initialized
57 if (corr_buf) {
58 corr_buf[0] = 1.0;
59 corr_buf[1] = 1.0;
60 }
61 inverse_corr_buf[0] = 1.0;
62 return 0;
63 }
64 const uintptr_t relevant_predictor_ct_p1 = relevant_predictor_ct + 1;
65 const double sample_ct_recip = 1.0 / u31tod(sample_ct);
66 const double sample_ct_m1_d = u31tod(sample_ct - 1);
67 const double sample_ct_m1_recip = 1.0 / sample_ct_m1_d;
68 for (uintptr_t pred_idx1 = 0; pred_idx1 != relevant_predictor_ct; ++pred_idx1) {
69 double* sample_corr_row = &(inverse_corr_buf[pred_idx1 * relevant_predictor_ct]);
70 const uintptr_t input_pred_idx1 = pred_idx1 + first_predictor_idx;
71 const double* predictor_dotprods_row = &(predictor_dotprods[input_pred_idx1 * predictor_ct]);
72 const double covar1_mean_adj = dbl_2d_buf[input_pred_idx1] * sample_ct_recip;
73 for (uintptr_t pred_idx2 = 0; pred_idx2 <= pred_idx1; ++pred_idx2) {
74 const uintptr_t input_pred_idx2 = pred_idx2 + first_predictor_idx;
75 sample_corr_row[pred_idx2] = (predictor_dotprods_row[input_pred_idx2] - covar1_mean_adj * dbl_2d_buf[input_pred_idx2]) * sample_ct_m1_recip;
76 }
77 }
78 // now use dbl_2d_buf to store inverse-sqrts, to get to correlation matrix
79 for (uintptr_t pred_idx = 0; pred_idx != relevant_predictor_ct; ++pred_idx) {
80 dbl_2d_buf[pred_idx] = 1.0 / sqrt(inverse_corr_buf[pred_idx * relevant_predictor_ct_p1]);
81 }
82 // invert_symmdef_matrix only cares about bottom left of inverse_corr_buf[]
83 for (uintptr_t pred_idx1 = 1; pred_idx1 != relevant_predictor_ct; ++pred_idx1) {
84 const double inverse_stdev1 = dbl_2d_buf[pred_idx1];
85 double* corr_row_iter = &(inverse_corr_buf[pred_idx1 * relevant_predictor_ct]);
86 const double* inverse_stdev2_iter = dbl_2d_buf;
87 for (uintptr_t pred_idx2 = 0; pred_idx2 != pred_idx1; ++pred_idx2) {
88 const double cur_corr = (*corr_row_iter) * inverse_stdev1 * (*inverse_stdev2_iter++);
89 // bugfix (14 Sep 2017): need to take absolute value here
90 if (fabs(cur_corr) > max_corr) {
91 return SetGlmErr2(kGlmErrcodeCorrTooHigh, pred_idx2, pred_idx1);
92 }
93 *corr_row_iter++ = cur_corr;
94 }
95 }
96 for (uintptr_t pred_idx = 0; pred_idx != relevant_predictor_ct; ++pred_idx) {
97 inverse_corr_buf[pred_idx * relevant_predictor_ct_p1] = 1.0;
98 }
99 if (corr_buf) {
100 memcpy(corr_buf, inverse_corr_buf, relevant_predictor_ct * relevant_predictor_ct * sizeof(double));
101 memcpy(&(corr_buf[relevant_predictor_ct * relevant_predictor_ct]), dbl_2d_buf, relevant_predictor_ct * sizeof(double));
102 }
103 if (InvertSymmdefMatrixChecked(relevant_predictor_ct, inverse_corr_buf, matrix_invert_buf1, dbl_2d_buf)) {
104 return SetGlmErr0(kGlmErrcodeVifInfinite);
105 }
106 // VIFs = diagonal elements of inverse correlation matrix
107 for (uintptr_t pred_idx = 0; pred_idx != relevant_predictor_ct; ++pred_idx) {
108 if (inverse_corr_buf[pred_idx * relevant_predictor_ct_p1] > vif_thresh) {
109 return SetGlmErr1(kGlmErrcodeVifTooHigh, pred_idx);
110 }
111 }
112 return 0;
113 }
114
115 // no-missing-genotype optimizations:
116 // * most of the inter-predictor correlation matrix can be initialized once
117 // from an image, doesn't even need to be refreshed; same goes for
118 // inv_corr_sqrts
119 // * inverse of that matrix can be precomputed, and used in rank 1 inverse
120 // update (rank 2 for domdev case)
121 //
122 // Other notes:
123 // * dbl_2d_buf does not need to store row sums, since we can get that from
124 // predictor_dotprods (first actual, though "irrelevant", predictor is
125 // all-1).
126 // * predictor_ct includes intercept.
127 // * geno_pred_ct must be 1 or 2.
128 // * ainv_b_buf[] must have size at least 4 * nongeno_pred_ct.
129 GlmErr CheckMaxCorrAndVifNm(const double* predictor_dotprods, const double* corr_inv, uint32_t predictor_ct, uint32_t geno_pred_ct, double sample_ct_recip, double sample_ct_m1_recip, double max_corr, double vif_thresh, double* __restrict semicomputed_corr_matrix, double* __restrict semicomputed_inv_corr_sqrts, double* __restrict corr_row_buf, double* __restrict inverse_corr_diag, double* __restrict ainv_b_buf) {
130 // we have dot products, now determine
131 // (dotprod - sum(a)mean(b)) / (N-1)
132 // to get small-sample covariance
133 if (predictor_ct == 2) {
134 return 0;
135 }
136 const uintptr_t relevant_predictor_ct = predictor_ct - 1;
137 const uintptr_t relevant_predictor_ct_p1 = predictor_ct;
138 // predictor_dotprods[] *rows* 1 (and 2, if geno_pred_ct == 2) are filled,
139 // rather than columns
140 {
141 const double covar1_mean_adj = predictor_dotprods[predictor_ct] * sample_ct_recip;
142 semicomputed_corr_matrix[0] = (predictor_dotprods[predictor_ct + 1] - covar1_mean_adj * predictor_dotprods[predictor_ct]) * sample_ct_m1_recip;
143 }
144 for (uintptr_t pred_idx1 = 1; pred_idx1 != relevant_predictor_ct; ++pred_idx1) {
145 double* sample_corr_row = &(semicomputed_corr_matrix[pred_idx1 * relevant_predictor_ct]);
146 const uintptr_t input_pred_idx1 = pred_idx1 + 1;
147 const double* predictor_dotprods_row = &(predictor_dotprods[input_pred_idx1 * predictor_ct]);
148 const double covar1_mean_adj = predictor_dotprods_row[0] * sample_ct_recip;
149 uintptr_t pred_idx2 = 0;
150 for (; pred_idx2 != geno_pred_ct; ++pred_idx2) {
151 const uintptr_t input_pred_idx2 = pred_idx2 + 1;
152 sample_corr_row[pred_idx2] = (predictor_dotprods[input_pred_idx2 * predictor_ct + input_pred_idx1] - covar1_mean_adj * predictor_dotprods[input_pred_idx2 * predictor_ct]) * sample_ct_m1_recip;
153 }
154 // document whether pred_idx2 guaranteed to be <= input_pred_idx1 if this
155 // code is revisited
156 for (; pred_idx2 < input_pred_idx1; ++pred_idx2) {
157 const uintptr_t input_pred_idx2 = pred_idx2 + 1;
158 sample_corr_row[pred_idx2] = (predictor_dotprods_row[input_pred_idx2] - covar1_mean_adj * predictor_dotprods[input_pred_idx2 * predictor_ct]) * sample_ct_m1_recip;
159 }
160 }
161 // assumes semicomputed_inv_corr_sqrts[geno_pred_ct..] is pre-initialized
162 semicomputed_inv_corr_sqrts[0] = 1.0 / sqrt(semicomputed_corr_matrix[0]);
163 const uintptr_t nongeno_pred_ct = relevant_predictor_ct - geno_pred_ct;
164 double inverse_stdev1 = semicomputed_inv_corr_sqrts[0];
165 const double* nongeno_inverse_stdevs = &(semicomputed_inv_corr_sqrts[geno_pred_ct]);
166 const double* corr_col = &(semicomputed_corr_matrix[geno_pred_ct * relevant_predictor_ct]);
167 for (uintptr_t nongeno_pred_idx = 0; nongeno_pred_idx != nongeno_pred_ct; ++nongeno_pred_idx) {
168 const double inverse_stdev2 = nongeno_inverse_stdevs[nongeno_pred_idx];
169 const double cur_corr = inverse_stdev1 * inverse_stdev2 * corr_col[nongeno_pred_idx * relevant_predictor_ct];
170 if (fabs(cur_corr) > max_corr) {
171 return SetGlmErr2(kGlmErrcodeCorrTooHigh, 0, geno_pred_ct + nongeno_pred_idx);
172 }
173 corr_row_buf[nongeno_pred_idx] = cur_corr;
174 }
175 if (geno_pred_ct == 1) {
176 if (InvertRank1SymmDiag(corr_inv, corr_row_buf, nongeno_pred_ct, 1.0, inverse_corr_diag, ainv_b_buf)) {
177 return SetGlmErr0(kGlmErrcodeVifInfinite);
178 }
179 } else {
180 inverse_stdev1 = 1.0 / sqrt(semicomputed_corr_matrix[relevant_predictor_ct_p1]);
181 corr_col = &(semicomputed_corr_matrix[geno_pred_ct * relevant_predictor_ct + 1]);
182 double* corr_row2 = &(corr_row_buf[nongeno_pred_ct]);
183 for (uintptr_t nongeno_pred_idx = 0; nongeno_pred_idx != nongeno_pred_ct; ++nongeno_pred_idx) {
184 const double inverse_stdev2 = nongeno_inverse_stdevs[nongeno_pred_idx];
185 const double cur_corr = inverse_stdev1 * inverse_stdev2 * corr_col[nongeno_pred_idx * relevant_predictor_ct];
186 if (fabs(cur_corr) > max_corr) {
187 return SetGlmErr2(kGlmErrcodeCorrTooHigh, 1, 2 + nongeno_pred_idx);
188 }
189 corr_row2[nongeno_pred_idx] = cur_corr;
190 }
191 const double inverse_stdev2 = semicomputed_inv_corr_sqrts[0];
192 const double cur_corr = inverse_stdev1 * inverse_stdev2 * semicomputed_corr_matrix[relevant_predictor_ct];
193 if (fabs(cur_corr) > max_corr) {
194 return SetGlmErr2(kGlmErrcodeCorrTooHigh, 0, 1);
195 }
196 // do we want special handling of nongeno_pred_ct == 0?
197 if (InvertRank2SymmDiag(corr_inv, corr_row_buf, nongeno_pred_ct, 1.0, cur_corr, 1.0, inverse_corr_diag, ainv_b_buf, &(ainv_b_buf[2 * nongeno_pred_ct]))) {
198 return SetGlmErr0(kGlmErrcodeVifInfinite);
199 }
200 }
201 // VIFs = diagonal elements of inverse correlation matrix
202 for (uintptr_t pred_idx = 0; pred_idx != relevant_predictor_ct; ++pred_idx) {
203 if (inverse_corr_diag[pred_idx] > vif_thresh) {
204 return SetGlmErr1(kGlmErrcodeVifTooHigh, pred_idx);
205 }
206 }
207 return 0;
208 }
209
210 PglErr GlmFillAndTestCovars(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, double* covar_dotprod, double* corr_buf, double* inverse_corr_buf, double* covars_cmaj, const char** cur_covar_names, GlmErr* glm_err_ptr) {
211 *glm_err_ptr = 0;
212 if (covar_ct == local_covar_ct) {
213 // bugfix (5 Mar 2018): need to copy local-covar names
214 for (uintptr_t local_covar_read_idx = 0; local_covar_read_idx != covar_ct; ++local_covar_read_idx) {
215 cur_covar_names[local_covar_read_idx] = &(covar_names[local_covar_read_idx * max_covar_name_blen]);
216 }
217 return kPglRetSuccess;
218 }
219 const uintptr_t new_covar_ct = covar_ct + extra_cat_ct;
220 const uintptr_t new_nonlocal_covar_ct = new_covar_ct - local_covar_ct;
221 const uint32_t covar_max_cat_ctl = 1 + (covar_max_nonnull_cat_ct / kBitsPerWord);
222 MatrixInvertBuf1* matrix_invert_buf1;
223 uintptr_t* cat_covar_wkspace;
224 double* dbl_2d_buf;
225 if (unlikely(BIGSTACK_ALLOC_X(MatrixInvertBuf1, kMatrixInvertBuf1CheckedAlloc * new_nonlocal_covar_ct, &matrix_invert_buf1) ||
226 bigstack_alloc_w(covar_max_cat_ctl, &cat_covar_wkspace) ||
227 bigstack_alloc_d(new_nonlocal_covar_ct * new_nonlocal_covar_ct, &dbl_2d_buf))) {
228 return kPglRetNomem;
229 }
230 uint32_t* cat_obs_buf;
231 // bugfix (11 May 2020): we were previously only initializing cat_obs_buf
232 // when extra_cat_ct > 0; this resulted in segfaults when every categorical
233 // covariate had only two categories.
234 if (unlikely(bigstack_alloc_u32(covar_max_nonnull_cat_ct + 1, &cat_obs_buf))) {
235 return kPglRetNomem;
236 }
237 unsigned char* alloc_base = g_bigstack_base;
238 unsigned char* new_covar_name_alloc = g_bigstack_end;
239 const uint32_t first_sample_uidx = AdvTo1Bit(sample_include, 0);
240 uintptr_t covar_read_uidx_base = 0;
241 uintptr_t covar_include_bits = covar_include[0];
242 const char** cur_covar_names_iter = cur_covar_names;
243 double* covar_write_iter = covars_cmaj;
244 double* sum_iter = dbl_2d_buf;
245 // Quasi-bugfix (22 Jan 2019): Main loop is too numerically unstable,
246 // especially in the single-precision logistic/Firth regression case, when a
247 // covariate is on a very different scale from the main genotype column (or
248 // other covariates). We now check sum-of-squares and (rescaled) sample
249 // variance of each fixed covariate column, and error out when the range of
250 // either value exceeds ~6 orders of magnitude. (Conveniently, this catches
251 // the fairly common "year of birth" problem.)
252 // Initial ssq and variance values correspond to genotype columns with a MAF
253 // range of [0.01, 0.5].
254 double max_ssq = 1.5 * u31tod(sample_ct);
255 double min_ssq_minus_sqmean = 0.0198 * u31tod(sample_ct - 1);
256 for (uintptr_t covar_read_idx = 0; covar_read_idx != covar_ct; ++covar_read_idx) {
257 const uintptr_t covar_read_uidx = BitIter1(covar_include, &covar_read_uidx_base, &covar_include_bits);
258 const PhenoCol* cur_covar_col = &(covar_cols[covar_read_uidx]);
259 const char* covar_name_base = &(covar_names[covar_read_uidx * max_covar_name_blen]);
260 if (cur_covar_col->type_code == kPhenoDtypeOther) {
261 // local covariate
262 *cur_covar_names_iter++ = covar_name_base;
263 } else if (cur_covar_col->type_code == kPhenoDtypeQt) {
264 *cur_covar_names_iter++ = covar_name_base;
265 const double* covar_vals = cur_covar_col->data.qt;
266 uintptr_t sample_uidx_base;
267 uintptr_t sample_include_bits;
268 BitIter1Start(sample_include, first_sample_uidx, &sample_uidx_base, &sample_include_bits);
269 double covar_sum = 0.0;
270 double covar_ssq = 0.0;
271 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
272 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
273 const double cur_covar_val = covar_vals[sample_uidx];
274 covar_sum += cur_covar_val;
275 covar_ssq += cur_covar_val * cur_covar_val;
276 *covar_write_iter++ = cur_covar_val;
277 }
278 *sum_iter++ = covar_sum;
279 if (covar_ssq > max_ssq) {
280 max_ssq = covar_ssq;
281 }
282 covar_ssq -= covar_sum * covar_sum / u31tod(sample_ct);
283 if (covar_ssq < min_ssq_minus_sqmean) {
284 min_ssq_minus_sqmean = covar_ssq;
285 }
286 } else {
287 // this is equivalent to "--split-cat-pheno omit-most covar-01"
288 const uint32_t cur_cat_ct = cur_covar_col->nonnull_category_ct + 1;
289 const uint32_t cur_cat_ctl = BitCtToWordCt(cur_cat_ct);
290 const uint32_t largest_cat_uidx = IdentifyRemainingCatsAndMostCommon(sample_include, cur_covar_col, sample_ct, cat_covar_wkspace, cat_obs_buf);
291 const uint32_t remaining_cat_ct = PopcountWords(cat_covar_wkspace, cur_cat_ctl);
292 assert(remaining_cat_ct >= 2);
293 ClearBit(largest_cat_uidx, cat_covar_wkspace);
294 const uint32_t* covar_vals = cur_covar_col->data.cat;
295 const char* const* cur_category_names = cur_covar_col->category_names;
296 const uint32_t covar_name_base_slen = strlen(covar_name_base);
297 uintptr_t cat_uidx_base;
298 uintptr_t cat_covar_wkspace_bits;
299 BitIter1Start(cat_covar_wkspace, 1, &cat_uidx_base, &cat_covar_wkspace_bits);
300 for (uint32_t cat_idx = 1; cat_idx != remaining_cat_ct; ++cat_idx) {
301 const uintptr_t cat_uidx = BitIter1(cat_covar_wkspace, &cat_uidx_base, &cat_covar_wkspace_bits);
302 const char* catname = cur_category_names[cat_uidx];
303 const uint32_t catname_slen = strlen(catname);
304 new_covar_name_alloc -= covar_name_base_slen + catname_slen + 2;
305 if (unlikely(new_covar_name_alloc < alloc_base)) {
306 return kPglRetNomem;
307 }
308 char* new_covar_name_write = memcpyax(new_covar_name_alloc, covar_name_base, covar_name_base_slen, '=');
309 memcpy(new_covar_name_write, catname, catname_slen + 1);
310 *cur_covar_names_iter++ = R_CAST(const char*, new_covar_name_alloc);
311
312 uintptr_t sample_uidx_base;
313 uintptr_t sample_include_bits;
314 BitIter1Start(sample_include, first_sample_uidx, &sample_uidx_base, &sample_include_bits);
315 uint32_t cur_cat_obs_ct = 0;
316 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
317 const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits);
318 const uint32_t cur_sample_is_in_cat = (covar_vals[sample_uidx] == cat_uidx);
319 cur_cat_obs_ct += cur_sample_is_in_cat;
320 *covar_write_iter++ = u31tod(cur_sample_is_in_cat);
321 }
322 double covar_ssq = u31tod(cur_cat_obs_ct);
323 *sum_iter++ = covar_ssq;
324 if (covar_ssq > max_ssq) {
325 max_ssq = covar_ssq;
326 }
327 covar_ssq -= covar_ssq * covar_ssq / u31tod(sample_ct);
328 if (covar_ssq < min_ssq_minus_sqmean) {
329 min_ssq_minus_sqmean = covar_ssq;
330 }
331 }
332 }
333 }
334 BigstackEndSet(new_covar_name_alloc);
335 if (min_ssq_minus_sqmean * 1048576.0 < max_ssq) {
336 // probable todo: automatically variance-standardize, while keeping track
337 // of the linear transformations so we can translate results back to
338 // original units in the final output.
339 *glm_err_ptr = SetGlmErr0(kGlmErrcodeUnstableScale);
340 return kPglRetSkipped;
341 }
342 assert(covar_write_iter == &(covars_cmaj[new_nonlocal_covar_ct * sample_ct]));
343 MultiplySelfTranspose(covars_cmaj, new_nonlocal_covar_ct, sample_ct, covar_dotprod);
344 // intentionally ignore error code, since all callers check glm_err
345 *glm_err_ptr = CheckMaxCorrAndVif(covar_dotprod, 0, new_nonlocal_covar_ct, sample_ct, max_corr, vif_thresh, dbl_2d_buf, corr_buf, inverse_corr_buf, matrix_invert_buf1);
346 BigstackReset(matrix_invert_buf1);
347 return kPglRetSuccess;
348 }
349
350 BoolErr InitNmPrecomp(const double* covars_cmaj, const double* covar_dotprod, const double* corr_buf, const double* corr_inv_tri, uint32_t sample_ct, uint32_t is_qt, uintptr_t new_covar_ct, uintptr_t xtx_state, RegressionNmPrecomp* nm_precomp) {
351 uintptr_t stride = new_covar_ct + 1 + xtx_state;
352 double* xtx_image = nm_precomp->xtx_image;
353 ZeroDArr(stride * stride, xtx_image);
354 xtx_image[0] = u31tod(sample_ct);
355 for (uintptr_t covar_idx = 0; covar_idx != new_covar_ct; ++covar_idx) {
356 const double* cur_covar = &(covars_cmaj[covar_idx * sample_ct]);
357 double dxx = 0.0;
358 for (uint32_t uii = 0; uii != sample_ct; ++uii) {
359 dxx += cur_covar[uii];
360 }
361 double* xtx_image_row = &(xtx_image[(covar_idx + 1 + xtx_state) * stride]);
362 xtx_image_row[0] = dxx;
363 memcpy(&(xtx_image_row[1 + xtx_state]), &(covar_dotprod[covar_idx * new_covar_ct]), (covar_idx + 1) * sizeof(double));
364 }
365 if (is_qt) {
366 // also save precomputed inverse of covar dotprods, with intercept included
367 // (not currently needed in logistic case)
368 double* covarx_dotprod_inv = nm_precomp->covarx_dotprod_inv;
369 covarx_dotprod_inv[0] = xtx_image[0];
370 const uintptr_t new_covar_ct_p1 = new_covar_ct + 1;
371 for (uintptr_t row_idx = 1; row_idx != new_covar_ct_p1; ++row_idx) {
372 covarx_dotprod_inv[row_idx * new_covar_ct_p1] = xtx_image[(row_idx + xtx_state) * stride];
373 memcpy(&(covarx_dotprod_inv[row_idx * new_covar_ct_p1 + 1]), &(covar_dotprod[(row_idx - 1) * new_covar_ct]), row_idx * sizeof(double));
374 }
375 // this makes assumptions about amount of space past corr_inv...
376 if (InvertSymmdefMatrixChecked(new_covar_ct_p1, covarx_dotprod_inv, R_CAST(MatrixInvertBuf1*, &(nm_precomp->corr_inv[new_covar_ct_p1 * MAXV(new_covar_ct_p1, 3)])), nm_precomp->corr_inv)) {
377 return 1;
378 }
379 ReflectMatrix(new_covar_ct_p1, covarx_dotprod_inv);
380 // xt_y_image fill no longer happens in this function (since that's
381 // inappropriate in the QT-batch case)
382 }
383
384 memcpy(nm_precomp->corr_inv, corr_inv_tri, new_covar_ct * new_covar_ct * sizeof(double));
385 ReflectMatrix(new_covar_ct, nm_precomp->corr_inv);
386 --stride;
387 double* corr_image = nm_precomp->corr_image;
388 // also store uninverted correlation matrix
389 ZeroDArr(stride * stride, corr_image);
390 for (uintptr_t orig_row_idx = 0; orig_row_idx != new_covar_ct; ++orig_row_idx) {
391 memcpy(&(corr_image[(orig_row_idx + xtx_state) * stride + xtx_state]), &(corr_buf[orig_row_idx * new_covar_ct]), (orig_row_idx + 1) * sizeof(double));
392 }
393 // and store inverse-sqrts after the correlation matrix
394 memcpy(nm_precomp->corr_inv_sqrts, &(corr_buf[new_covar_ct * new_covar_ct]), new_covar_ct * sizeof(double));
395 return 0;
396 }
397
398 uint32_t DosageIsConstant(uint64_t dosage_sum, uint64_t dosage_ssq, uint32_t nm_sample_ct) {
399 // Dosages are all identical iff dosage_sum * dosage_sum ==
400 // dosage_ssq * nm_sample_ct.
401 // Unfortunately, uint64 isn't enough for this comparison.
402 const uint64_t dosage_sum_hi = dosage_sum >> 32;
403 const uint64_t dosage_sum_lo = S_CAST(uint32_t, dosage_sum);
404 const uint64_t dosage_ssq_hi = dosage_ssq >> 32;
405 const uint64_t dosage_ssq_lo = S_CAST(uint32_t, dosage_ssq);
406
407 // (a * 2^32 + b)^2 = a^2 * 2^64 + 2ab * 2^32 + b^2
408 const uint64_t lhs_ab = dosage_sum_hi * dosage_sum_lo;
409 const uint64_t lhs_b2 = dosage_sum_lo * dosage_sum_lo;
410 const uint64_t lhs_lo = lhs_b2 + (lhs_ab << 33);
411 const uint64_t lhs_hi = (lhs_lo < lhs_b2) + (lhs_ab >> 31) + dosage_sum_hi * dosage_sum_hi;
412
413 // (a * 2^32 + b) * c = ac * 2^32 + bc
414 const uint64_t rhs_ac = dosage_ssq_hi * nm_sample_ct;
415 const uint64_t rhs_bc = dosage_ssq_lo * nm_sample_ct;
416 const uint64_t rhs_lo = rhs_bc + (rhs_ac << 32);
417 const uint64_t rhs_hi = (rhs_lo < rhs_bc) + (rhs_ac >> 32);
418 return (lhs_hi == rhs_hi) && (lhs_lo == rhs_lo);
419 }
420
421 uint32_t GetBiallelicReportedTestCt(const uintptr_t* parameter_subset, GlmFlags glm_flags, uint32_t covar_ct, uint32_t tests_flag) {
422 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
423 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
424 const uint32_t domdev_present = (glm_flags & (kfGlmGenotypic | kfGlmHethom))? 1 : 0;
425 const uint32_t joint_test = domdev_present || tests_flag;
426
427 if (hide_covar) {
428 if (!parameter_subset) {
429 return 1 + include_intercept + domdev_present + joint_test;
430 }
431 return include_intercept + domdev_present + joint_test + IsSet(parameter_subset, 1);
432 }
433
434 const uint32_t domdev_present_p1 = domdev_present + 1;
435 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
436 const uint32_t biallelic_predictor_ct_base = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
437 uint32_t biallelic_predictor_ct = biallelic_predictor_ct_base;
438 if (parameter_subset) {
439 biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct_base));
440 }
441 return biallelic_predictor_ct + joint_test + include_intercept - 1;
442 }
443
444 typedef struct LocalCovarCoeffparseCtxStruct {
445 uint32_t* sample_idx_order;
446 uint32_t max_sample_ct;
447 uint32_t cur_sample_ct;
448 uint32_t tokens_per_sample;
449 uint32_t local_covar_ct;
450 uint32_t omit_last;
451 uint32_t local_haps;
452 uint32_t local_cat_ct;
453 uint32_t local_cats_1based;
454 } LocalCovarCoeffparseCtx;
455
456 // Processes a single line's worth of payload.
457 PglErr LoadLocalCovarCoeffs(const LocalCovarCoeffparseCtx* ctx, const char* local_line_iter, uint32_t local_line_idx, float* local_covars_vcmaj_f_iter, double* local_covars_vcmaj_d_iter) {
458 const uint32_t* sample_idx_order = ctx->sample_idx_order;
459 const uint32_t max_sample_ct = ctx->max_sample_ct;
460 const uint32_t cur_sample_ct = ctx->cur_sample_ct;
461 const uint32_t tokens_per_sample = ctx->tokens_per_sample;
462 const uint32_t local_covar_ct = ctx->local_covar_ct;
463 const uint32_t omit_last = ctx->omit_last;
464 const uint32_t local_haps = ctx->local_haps;
465 const uint32_t local_cat_ct = ctx->local_cat_ct;
466 const uint32_t local_cats_1based = ctx->local_cats_1based;
467 const uint32_t max_cat_idx = local_cat_ct + local_cats_1based - 1;
468 uint32_t sample_idx = 0;
469 for (uint32_t local_sample_idx = 0; sample_idx != cur_sample_ct; ++local_sample_idx) {
470 const uint32_t cur_sample_idx = sample_idx_order[local_sample_idx];
471 if (cur_sample_idx == UINT32_MAX) {
472 local_line_iter = NextTokenMult(local_line_iter, tokens_per_sample);
473 if (unlikely(!local_line_iter)) {
474 logputs("\n");
475 logerrprintfww("Error: Fewer tokens than expected on line %u of --glm local-covar= file.\n", local_line_idx);
476 return kPglRetMalformedInput;
477 }
478 continue;
479 }
480 if (local_cat_ct) {
481 uint32_t cat_idx;
482 if (unlikely(ScanmovUintCapped(max_cat_idx, &local_line_iter, &cat_idx) || (cat_idx < local_cats_1based))) {
483 logputs("\n");
484 logerrprintf("Error: Invalid category index on line %u of --glm local-covar= file.\n", local_line_idx);
485 return kPglRetMalformedInput;
486 }
487 cat_idx -= local_cats_1based;
488 local_line_iter = FirstNonTspace(FirstSpaceOrEoln(local_line_iter));
489 if (!local_haps) {
490 if (cat_idx != max_cat_idx) {
491 const uint32_t offset = cat_idx * max_sample_ct + cur_sample_idx;
492 if (local_covars_vcmaj_f_iter) {
493 local_covars_vcmaj_f_iter[offset] = 1.0;
494 } else {
495 local_covars_vcmaj_d_iter[offset] = 1.0;
496 }
497 }
498 } else {
499 if (cat_idx != max_cat_idx) {
500 const uint32_t offset = cat_idx * max_sample_ct + cur_sample_idx;
501 if (local_covars_vcmaj_f_iter) {
502 local_covars_vcmaj_f_iter[offset] = 0.5;
503 } else {
504 local_covars_vcmaj_d_iter[offset] = 0.5;
505 }
506 }
507 if (unlikely(ScanmovUintCapped(max_cat_idx, &local_line_iter, &cat_idx) || (cat_idx < local_cats_1based))) {
508 logputs("\n");
509 logerrprintf("Error: Invalid category index on line %u of --glm local-covar= file.\n", local_line_idx);
510 return kPglRetMalformedInput;
511 }
512 cat_idx -= local_cats_1based;
513 local_line_iter = FirstNonTspace(FirstSpaceOrEoln(local_line_iter));
514 if (cat_idx != max_cat_idx) {
515 const uint32_t offset = cat_idx * max_sample_ct + cur_sample_idx;
516 if (local_covars_vcmaj_f_iter) {
517 local_covars_vcmaj_f_iter[offset] += S_CAST(float, 0.5);
518 } else {
519 local_covars_vcmaj_d_iter[offset] += 0.5;
520 }
521 }
522 }
523 } else {
524 if (local_covars_vcmaj_f_iter) {
525 float* local_covars_f_iter2 = &(local_covars_vcmaj_f_iter[cur_sample_idx]);
526 for (uint32_t covar_idx = 0; covar_idx != local_covar_ct; ++covar_idx) {
527 double dxx;
528 local_line_iter = ScantokDouble(local_line_iter, &dxx);
529 if (unlikely((!local_line_iter) || (fabs(dxx) > 3.4028235677973362e38))) {
530 logputs("\n");
531 logerrprintf("Error: Invalid or missing token on line %u of --glm local-covar= file.\n", local_line_idx);
532 return kPglRetMalformedInput;
533 }
534 *local_covars_f_iter2 = S_CAST(float, dxx);
535 local_covars_f_iter2 = &(local_covars_f_iter2[max_sample_ct]);
536 local_line_iter = FirstNonTspace(local_line_iter);
537 }
538 } else {
539 double* local_covars_d_iter2 = &(local_covars_vcmaj_d_iter[cur_sample_idx]);
540 for (uint32_t covar_idx = 0; covar_idx != local_covar_ct; ++covar_idx) {
541 double dxx;
542 local_line_iter = ScantokDouble(local_line_iter, &dxx);
543 if (unlikely(!local_line_iter)) {
544 logputs("\n");
545 logerrprintf("Error: Invalid or missing token on line %u of --glm local-covar= file.\n", local_line_idx);
546 return kPglRetMalformedInput;
547 }
548 *local_covars_d_iter2 = dxx;
549 local_covars_d_iter2 = &(local_covars_d_iter2[max_sample_ct]);
550 local_line_iter = FirstNonTspace(local_line_iter);
551 }
552 }
553 if (omit_last) {
554 local_line_iter = FirstNonTspace(FirstSpaceOrEoln(local_line_iter));
555 }
556 if (local_haps) {
557 if (local_covars_vcmaj_f_iter) {
558 float* local_covars_f_iter2 = &(local_covars_vcmaj_f_iter[cur_sample_idx]);
559 for (uint32_t covar_idx = 0; covar_idx != local_covar_ct; ++covar_idx) {
560 double dxx;
561 local_line_iter = ScantokDouble(local_line_iter, &dxx);
562 if (unlikely((!local_line_iter) || (fabs(dxx) > 3.4028235677973362e38))) {
563 logputs("\n");
564 logerrprintf("Error: Invalid or missing token on line %u of --glm local-covar= file.\n", local_line_idx);
565 return kPglRetMalformedInput;
566 }
567 *local_covars_f_iter2 = S_CAST(float, (S_CAST(double, *local_covars_f_iter2) + dxx) * 0.5);
568 local_covars_f_iter2 = &(local_covars_f_iter2[max_sample_ct]);
569 local_line_iter = FirstNonTspace(local_line_iter);
570 }
571 } else {
572 double* local_covars_d_iter2 = &(local_covars_vcmaj_d_iter[cur_sample_idx]);
573 for (uint32_t covar_idx = 0; covar_idx != local_covar_ct; ++covar_idx) {
574 double dxx;
575 local_line_iter = ScantokDouble(local_line_iter, &dxx);
576 if (unlikely(!local_line_iter)) {
577 logputs("\n");
578 logerrprintf("Error: Invalid or missing token on line %u of --glm local-covar= file.\n", local_line_idx);
579 return kPglRetMalformedInput;
580 }
581 // may as well defend against overflow
582 *local_covars_d_iter2 = (*local_covars_d_iter2) * 0.5 + dxx * 0.5;
583 local_covars_d_iter2 = &(local_covars_d_iter2[max_sample_ct]);
584 local_line_iter = FirstNonTspace(local_line_iter);
585 }
586 }
587 if (omit_last) {
588 local_line_iter = FirstNonTspace(FirstSpaceOrEoln(local_line_iter));
589 }
590 }
591 }
592 ++sample_idx;
593 }
594 return kPglRetSuccess;
595 }
596
597 PglErr ReadLocalCovarBlock(const GlmCtx* common, const uint32_t* local_sample_uidx_order, const uintptr_t* local_variant_include, uint32_t variant_uidx_start, uint32_t variant_uidx_end, uint32_t cur_block_variant_ct, uint32_t local_sample_ct, uint32_t local_cat_ct, TextStream* local_covar_txsp, uint32_t* local_line_idx_ptr, uint32_t* local_xy_ptr, float* local_covars_vcmaj_f_iter, double* local_covars_vcmaj_d_iter, uint32_t* local_sample_idx_order) {
598 const ChrInfo* cip = common->cip;
599 const uintptr_t* variant_include = common->variant_include;
600 const uint32_t sample_ct = common->sample_ct;
601 const uint32_t sample_ct_x = common->sample_ct_x;
602 const uint32_t sample_ct_y = common->sample_ct_y;
603 const uint32_t local_covar_ct = common->local_covar_ct;
604 const GlmFlags flags = common->glm_flags;
605 const uint32_t omit_last = (flags / kfGlmLocalOmitLast) & 1;
606 const uint32_t local_haps = (flags / kfGlmLocalHaps) & 1;
607
608 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
609 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
610 uint32_t max_sample_ct = MAXV(sample_ct, sample_ct_x);
611 if (max_sample_ct < sample_ct_y) {
612 max_sample_ct = sample_ct_y;
613 }
614 LocalCovarCoeffparseCtx coeffparse_ctx;
615 coeffparse_ctx.sample_idx_order = local_sample_idx_order;
616 coeffparse_ctx.max_sample_ct = max_sample_ct;
617 // cur_sample_ct filled a bit later
618 coeffparse_ctx.tokens_per_sample = (local_cat_ct? 1 : (local_covar_ct + omit_last)) << local_haps;
619 coeffparse_ctx.local_covar_ct = local_covar_ct;
620 coeffparse_ctx.omit_last = omit_last;
621 coeffparse_ctx.local_haps = local_haps;
622 coeffparse_ctx.local_cat_ct = local_cat_ct;
623 coeffparse_ctx.local_cats_1based = (flags / kfGlmLocalCats1based) & 1;
624 uint32_t variant_bidx = 0;
625 if (local_cat_ct) {
626 // assert(local_covar_ct == local_cat_ct - 1);
627 if (local_covars_vcmaj_f_iter) {
628 ZeroFArr(local_covar_ct * max_sample_ct * S_CAST(uintptr_t, cur_block_variant_ct), local_covars_vcmaj_f_iter);
629 } else {
630 ZeroDArr(local_covar_ct * max_sample_ct * S_CAST(uintptr_t, cur_block_variant_ct), local_covars_vcmaj_d_iter);
631 }
632 }
633 uintptr_t variant_uidx_base;
634 uintptr_t cur_bits;
635 BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits);
636 uint32_t local_line_idx = *local_line_idx_ptr;
637 while (variant_bidx < cur_block_variant_ct) {
638 const uint32_t variant_uidx1 = BitIter1NoAdv(variant_include, &variant_uidx_base, &cur_bits);
639 const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx1);
640 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
641 const uint32_t chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
642 uint32_t cur_variant_bidx_end = cur_block_variant_ct;
643 if (chr_end < variant_uidx_end) {
644 cur_variant_bidx_end = variant_bidx + PopcountBitRange(variant_include, variant_uidx1, chr_end);
645 assert(cur_variant_bidx_end <= cur_block_variant_ct);
646 }
647 const uint32_t is_x = (chr_idx == x_code);
648 const uint32_t is_y = (chr_idx == y_code);
649 const uintptr_t* cur_sample_include;
650 const uint32_t* cur_sample_include_cumulative_popcounts;
651 if (is_y && common->sample_include_y) {
652 cur_sample_include = common->sample_include_y;
653 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
654 coeffparse_ctx.cur_sample_ct = sample_ct_y;
655 } else if (is_x && common->sample_include_x) {
656 cur_sample_include = common->sample_include_x;
657 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
658 coeffparse_ctx.cur_sample_ct = sample_ct_x;
659 } else {
660 cur_sample_include = common->sample_include;
661 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
662 coeffparse_ctx.cur_sample_ct = sample_ct;
663 }
664 const uint32_t new_local_xy = is_x + 2 * is_y;
665 if (new_local_xy != *local_xy_ptr) {
666 for (uint32_t uii = 0; uii != local_sample_ct; ++uii) {
667 const uint32_t cur_uidx = local_sample_uidx_order[uii];
668 uint32_t cur_idx = UINT32_MAX;
669 if ((cur_uidx != UINT32_MAX) && IsSet(cur_sample_include, cur_uidx)) {
670 cur_idx = RawToSubsettedPos(cur_sample_include, cur_sample_include_cumulative_popcounts, cur_uidx);
671 }
672 local_sample_idx_order[uii] = cur_idx;
673 }
674 *local_xy_ptr = new_local_xy;
675 }
676 for (; variant_bidx != cur_variant_bidx_end; ++variant_bidx) {
677 BitIter1(variant_include, &variant_uidx_base, &cur_bits);
678 if (!IsSet(local_variant_include, local_line_idx)) {
679 uint32_t local_line_idx_target_m1 = AdvTo1Bit(local_variant_include, local_line_idx);
680 PglErr reterr = TextSkipNz(local_line_idx_target_m1 - local_line_idx, local_covar_txsp);
681 if (unlikely(reterr)) {
682 if (reterr == kPglRetEof) {
683 logputs("\n");
684 logerrputs("Error: --glm local-covar= file has fewer lines than local-pvar= file.\n");
685 return kPglRetInconsistentInput;
686 }
687 TextStreamErrPrint("--glm local-covar= file", local_covar_txsp);
688 return reterr;
689 }
690 local_line_idx = local_line_idx_target_m1;
691 }
692 ++local_line_idx;
693 PglErr reterr = kPglRetSuccess;
694 char* local_covar_line_start = TextGet(local_covar_txsp);
695 if (unlikely(!local_covar_line_start)) {
696 if (!TextStreamErrcode2(local_covar_txsp, &reterr)) {
697 logputs("\n");
698 logerrputs("Error: --glm local-covar= file has fewer lines than local-pvar= file.\n");
699 return kPglRetInconsistentInput;
700 }
701 TextStreamErrPrint("--glm local-covar= file", local_covar_txsp);
702 return reterr;
703 }
704 reterr = LoadLocalCovarCoeffs(&coeffparse_ctx, local_covar_line_start, local_line_idx, local_covars_vcmaj_f_iter, local_covars_vcmaj_d_iter);
705 if (unlikely(reterr)) {
706 return reterr;
707 }
708 if (local_covars_vcmaj_f_iter) {
709 local_covars_vcmaj_f_iter += max_sample_ct * local_covar_ct;
710 } else {
711 local_covars_vcmaj_d_iter += max_sample_ct * local_covar_ct;
712 }
713 }
714 }
715 *local_line_idx_ptr = local_line_idx;
716 return kPglRetSuccess;
717 }
718
719 static inline void ZeroLocalCovarRows(uint32_t row_ct, uintptr_t row_width, uint32_t* variant_bidx_ptr, float** local_covars_vcmaj_f_iterp, double** local_covars_vcmaj_d_iterp) {
720 *variant_bidx_ptr += row_ct;
721 const uintptr_t elem_ct = row_ct * row_width;
722 if (*local_covars_vcmaj_f_iterp) {
723 ZeroFArr(elem_ct, *local_covars_vcmaj_f_iterp);
724 *local_covars_vcmaj_f_iterp += elem_ct;
725 } else {
726 ZeroDArr(elem_ct, *local_covars_vcmaj_d_iterp);
727 *local_covars_vcmaj_d_iterp += elem_ct;
728 }
729 }
730
731 void DuplicateLocalCovarRow(uint32_t row_ct, uintptr_t row_width, uint32_t* variant_bidx_ptr, float** local_covars_vcmaj_f_iterp, double** local_covars_vcmaj_d_iterp) {
732 if (*local_covars_vcmaj_f_iterp) {
733 float* local_covars_vcmaj_f_iter = *local_covars_vcmaj_f_iterp;
734 // Could also copy one row at a time, but I'd expect doubling to be
735 // slightly more efficient.
736 for (uint32_t row_idx = 1; row_idx < row_ct; row_idx *= 2) {
737 uint32_t row_copy_ct = row_ct - row_idx;
738 if (row_copy_ct > row_idx) {
739 row_copy_ct = row_idx;
740 }
741 memcpy(&(local_covars_vcmaj_f_iter[row_idx * row_width]), local_covars_vcmaj_f_iter, row_copy_ct * row_width * sizeof(float));
742 }
743 local_covars_vcmaj_f_iter = &(local_covars_vcmaj_f_iter[row_ct * row_width]);
744 } else {
745 double* local_covars_vcmaj_d_iter = *local_covars_vcmaj_d_iterp;
746 for (uint32_t row_idx = 1; row_idx < row_ct; row_idx *= 2) {
747 uint32_t row_copy_ct = row_ct - row_idx;
748 if (row_copy_ct > row_idx) {
749 row_copy_ct = row_idx;
750 }
751 memcpy(&(local_covars_vcmaj_d_iter[row_idx * row_width]), local_covars_vcmaj_d_iter, row_copy_ct * row_width * sizeof(double));
752 }
753 *local_covars_vcmaj_d_iterp = &(local_covars_vcmaj_d_iter[row_ct * row_width]);
754 }
755 *variant_bidx_ptr += row_ct;
756 }
757
758
759 PglErr ReadRfmix2Block(const GlmCtx* common, const uint32_t* variant_bps, const uint32_t* local_sample_uidx_order, const float* prev_local_covar_row_f, const double* prev_local_covar_row_d, uint32_t variant_uidx_start, uint32_t variant_uidx_end, uint32_t cur_block_variant_ct, uint32_t local_sample_ct, uint32_t local_cat_ct, uint32_t local_chrom_col, uint32_t local_bp_col, uint32_t local_first_covar_col, TextStream* local_covar_txsp, const char** local_line_iterp, uint32_t* local_line_idx_ptr, uint32_t* local_prev_chr_code_ptr, uint32_t* local_chr_code_ptr, uint32_t* local_bp_ptr, uint32_t* local_skip_chr_ptr, float* local_covars_vcmaj_f_iter, double* local_covars_vcmaj_d_iter, uint32_t* local_sample_idx_order) {
760 const ChrInfo* cip = common->cip;
761 const uintptr_t* variant_include = common->variant_include;
762 const uint32_t sample_ct = common->sample_ct;
763 const uint32_t sample_ct_x = common->sample_ct_x;
764 const uint32_t sample_ct_y = common->sample_ct_y;
765 const uint32_t local_covar_ct = common->local_covar_ct;
766 const GlmFlags flags = common->glm_flags;
767 const uint32_t omit_last = (flags / kfGlmLocalOmitLast) & 1;
768 const uint32_t local_haps = (flags / kfGlmLocalHaps) & 1;
769 // There are several complications here:
770 // 1. Until we've seen the beginning of the next line, we don't know the end
771 // of the (possibly empty) variant range the current set of local
772 // covariates applies to.
773 // 2. The aforementioned variant range may go past the end of the current
774 // variant block.
775 // 3. There may be variants which aren't contained in any local-covar
776 // interval (either before the first local-covar position on that
777 // chromosome, or on a chromosome absent from the local-covar file).
778 // To address (1), we structure the main loop such that the first part
779 // duplicates row contents and advances the matrix-filling iterator when
780 // necessary, the second part speculatively parses local covariates to the
781 // next matrix row, and the last part reads the position fields on the next
782 // line.
783 // To manage (2), we track local_prev_chr_code, local_chr_code, local_bp, and
784 // prev_local_covar_row across function calls. When local_prev_chr_code !=
785 // local_chr_code on function restart, we know we need to replicate
786 // prev_local_covar_row to the end of that chromosome, exiting early if the
787 // end of the chromosome is past variant_uidx_end; otherwise, we need to
788 // replicate it up to the first variant with position >= local_bp, possibly
789 // exiting early. This is no different from within-variant-block iteration,
790 // so the main loop is written such that function reentry isn't
791 // special-cased outside of needing to know prev_local_covar_row.
792 // For (3), we zero-fill the affected local covariate rows.
793 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
794 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
795 uint32_t max_sample_ct = MAXV(sample_ct, sample_ct_x);
796 if (max_sample_ct < sample_ct_y) {
797 max_sample_ct = sample_ct_y;
798 }
799
800 LocalCovarCoeffparseCtx coeffparse_ctx;
801 coeffparse_ctx.sample_idx_order = local_sample_idx_order;
802 coeffparse_ctx.max_sample_ct = max_sample_ct;
803 // cur_sample_ct filled a bit later
804 coeffparse_ctx.tokens_per_sample = (local_cat_ct? 1 : (local_covar_ct + omit_last)) << local_haps;
805 coeffparse_ctx.local_covar_ct = local_covar_ct;
806 coeffparse_ctx.omit_last = omit_last;
807 coeffparse_ctx.local_haps = local_haps;
808 coeffparse_ctx.local_cat_ct = local_cat_ct;
809 coeffparse_ctx.local_cats_1based = (flags / kfGlmLocalCats1based) & 1;
810
811 const char* local_line_iter = *local_line_iterp;
812 uint32_t local_line_idx = *local_line_idx_ptr;
813 uint32_t first_skip;
814 uint32_t second_skip;
815 uint32_t last_skip;
816 if (local_chrom_col < local_bp_col) {
817 first_skip = local_chrom_col - 1;
818 second_skip = local_bp_col - local_chrom_col;
819 last_skip = local_first_covar_col - local_bp_col;
820 } else {
821 first_skip = local_bp_col - 1;
822 second_skip = local_chrom_col - local_bp_col;
823 last_skip = local_first_covar_col - local_chrom_col;
824 }
825 const uintptr_t row_width = local_covar_ct * max_sample_ct;
826 uint32_t local_prev_chr_code = *local_prev_chr_code_ptr;
827 uint32_t local_chr_code = *local_chr_code_ptr;
828 uint32_t local_bp = *local_bp_ptr;
829 uint32_t local_skip_chr = *local_skip_chr_ptr;
830 // might be inaccurate at file-start and EOF, but that's okay since these
831 // variables are reinitialized before use in the first case, and irrelevant
832 // in the second
833 uint32_t is_x = (local_chr_code == x_code);
834 uint32_t is_y = (local_chr_code == y_code);
835 uint32_t local_xy = is_x + 2 * is_y;
836 const uintptr_t* cur_sample_include;
837 const uint32_t* cur_sample_include_cumulative_popcounts;
838 if (is_y && common->sample_include_y) {
839 cur_sample_include = common->sample_include_y;
840 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
841 coeffparse_ctx.cur_sample_ct = sample_ct_y;
842 } else if (is_x && common->sample_include_x) {
843 cur_sample_include = common->sample_include_x;
844 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
845 coeffparse_ctx.cur_sample_ct = sample_ct_x;
846 } else {
847 cur_sample_include = common->sample_include;
848 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
849 coeffparse_ctx.cur_sample_ct = sample_ct;
850 }
851 // Necessary for cross-block duplication to work.
852 if (prev_local_covar_row_f) {
853 memcpy(local_covars_vcmaj_f_iter, prev_local_covar_row_f, row_width * sizeof(float));
854 } else if (prev_local_covar_row_d) {
855 memcpy(local_covars_vcmaj_d_iter, prev_local_covar_row_d, row_width * sizeof(double));
856 }
857
858 uint32_t variant_bidx = 0;
859 uint32_t variant_uidx = AdvTo1Bit(variant_include, variant_uidx_start);
860 uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
861 uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
862 uint32_t variant_uidx_chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
863 if (variant_uidx_chr_end > variant_uidx_end) {
864 variant_uidx_chr_end = variant_uidx_end;
865 }
866 uint32_t variant_bp = (chr_idx == local_prev_chr_code)? variant_bps[variant_uidx] : UINT32_MAX;
867 while (1) {
868 // Loop invariants:
869 // local_chr_code and local_bp are from the current line, if we're not at
870 // the beginning or end of the file. In the latter two cases,
871 // local_chr_code is UINT32_MAX.
872 // local_prev_chr_code is from the previous relevant line, or UINT32_MAX
873 // at the beginning of the file.
874 // variant_uidx = next variant we need to fill local covariates for.
875 // chr_fo_idx and chr_idx correspond to variant_uidx.
876 // variant_uidx_chr_end is min(end of chr_fo_idx, variant_uidx_end).
877 // variant_bp is UINT32_MAX if we've already iterated through all
878 // variants on local_prev_chr_code (or we're at the beginning of the
879 // file); otherwise it also corresponds to variant_uidx.
880 // local_skip_chr is set iff either all variants on local_chr_code were
881 // filtered out, or local_chr_code == UINT32_MAX.
882 // If local_skip_chr isn't true, variant_uidx is not before the start of
883 // local_prev_chr_code, or after the end of local_chr_code.
884 if (!local_skip_chr) {
885 // Part 1.
886 const uint32_t backfill_stop_bp = (local_chr_code == chr_idx)? local_bp : UINT32_MAX;
887 if (backfill_stop_bp > variant_bp) {
888 // At least one variant in [prev pos, current pos) (or [prev pos, end
889 // of chromosome) if we're moving on to a new chromosome). Count how
890 // many there are, and fill that many lines of the matrix.
891 const uint32_t next_variant_uidx = ExpsearchU32(variant_bps, variant_uidx, variant_uidx_chr_end, backfill_stop_bp);
892 const uint32_t row_ct = PopcountBitRange(variant_include, variant_uidx, next_variant_uidx);
893 DuplicateLocalCovarRow(row_ct, row_width, &variant_bidx, &local_covars_vcmaj_f_iter, &local_covars_vcmaj_d_iter);
894 if (variant_bidx == cur_block_variant_ct) {
895 break;
896 }
897 variant_uidx = AdvTo1Bit(variant_include, next_variant_uidx);
898 if (variant_uidx >= variant_uidx_chr_end) {
899 // probable todo: helper function for this
900 chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
901 chr_idx = cip->chr_file_order[chr_fo_idx];
902 variant_uidx_chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
903 if (variant_uidx_chr_end > variant_uidx_end) {
904 variant_uidx_chr_end = variant_uidx_end;
905 }
906 variant_bp = UINT32_MAX;
907 }
908 }
909 if (local_chr_code != local_prev_chr_code) {
910 const uint32_t local_chr_fo_idx = cip->chr_idx_to_foidx[local_chr_code];
911 if (local_chr_code != chr_idx) {
912 // Some variants are on chromosomes entirely absent from the
913 // local-covar file. Zero-fill the covariate values for these
914 // variants; NA results will be reported for them.
915 const uint32_t local_chr_start_vidx = cip->chr_fo_vidx_start[local_chr_fo_idx];
916 uint32_t row_ct;
917 if (local_chr_start_vidx >= variant_uidx_chr_end) {
918 row_ct = cur_block_variant_ct - variant_bidx;
919 } else {
920 // Verify that we aren't going backwards. (This condition works
921 // since we don't enter the block in the local_skip_chr case.)
922 if (unlikely(local_chr_start_vidx < variant_uidx)) {
923 logputs("\n");
924 logerrputs("Error: --glm local-covar= file has a different chromosome order than the main\ndataset.\n");
925 return kPglRetInconsistentInput;
926 }
927 row_ct = PopcountBitRange(variant_include, variant_uidx, local_chr_start_vidx);
928 }
929 ZeroLocalCovarRows(row_ct, row_width, &variant_bidx, &local_covars_vcmaj_f_iter, &local_covars_vcmaj_d_iter);
930 if (variant_bidx == cur_block_variant_ct) {
931 break;
932 }
933 variant_uidx = AdvTo1Bit(variant_include, local_chr_start_vidx);
934 chr_fo_idx = local_chr_fo_idx;
935 chr_idx = local_chr_code;
936 variant_uidx_chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
937 if (variant_uidx_chr_end > variant_uidx_end) {
938 variant_uidx_chr_end = variant_uidx_end;
939 }
940 }
941 variant_bp = variant_bps[variant_uidx];
942 }
943 if (local_cat_ct) {
944 if (local_covars_vcmaj_f_iter) {
945 ZeroFArr(local_covar_ct * max_sample_ct, local_covars_vcmaj_f_iter);
946 } else {
947 ZeroDArr(local_covar_ct * max_sample_ct, local_covars_vcmaj_d_iter);
948 }
949 }
950 // Part 2.
951 PglErr reterr = LoadLocalCovarCoeffs(&coeffparse_ctx, local_line_iter, local_line_idx, local_covars_vcmaj_f_iter, local_covars_vcmaj_d_iter);
952 if (unlikely(reterr)) {
953 return reterr;
954 }
955 }
956 // Part 3.
957
958 // Not const for now, due to limitation of GetChrCodeCounted().
959 char* line_start = TextGet(local_covar_txsp);
960 if (!line_start) {
961 PglErr reterr = TextStreamErrcode(local_covar_txsp);
962 if (unlikely(reterr)) {
963 return reterr;
964 }
965 // EOF.
966 local_line_iter = nullptr;
967 local_chr_code = UINT32_MAX;
968 local_skip_chr = 1;
969 if (local_prev_chr_code == chr_idx) {
970 uint32_t row_ct = cur_block_variant_ct - variant_bidx;
971 if (variant_uidx_chr_end < variant_uidx_end) {
972 row_ct = PopcountBitRange(variant_include, variant_uidx, variant_uidx_chr_end);
973 }
974 if (row_ct) {
975 DuplicateLocalCovarRow(row_ct, row_width, &variant_bidx, &local_covars_vcmaj_f_iter, &local_covars_vcmaj_d_iter);
976 if (variant_bidx == cur_block_variant_ct) {
977 break;
978 }
979 }
980 variant_uidx = AdvTo1Bit(variant_include, variant_uidx_chr_end);
981 chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx);
982 chr_idx = cip->chr_file_order[chr_fo_idx];
983 // no need to update variant_uidx_chr_end or variant_bp
984 }
985 const uintptr_t remaining_variant_ct = cur_block_variant_ct - variant_bidx;
986 ZeroLocalCovarRows(remaining_variant_ct, row_width, &variant_bidx, &local_covars_vcmaj_f_iter, &local_covars_vcmaj_d_iter);
987 break;
988 }
989 ++local_line_idx;
990 char* tok1_start = NextTokenMult0(line_start, first_skip);
991 if (unlikely(!tok1_start)) {
992 logputs("\n");
993 logerrprintf("Error: Line %u of --glm local-covar= file has fewer tokens than expected.\n", local_line_idx);
994 return kPglRetMalformedInput;
995 }
996 char* tok1_end = CurTokenEnd(tok1_start);
997 char* tok2_start = NextTokenMult(tok1_end, second_skip);
998 if (unlikely(!tok2_start)) {
999 logputs("\n");
1000 logerrprintf("Error: Line %u of --glm local-covar= file has fewer tokens than expected.\n", local_line_idx);
1001 return kPglRetMalformedInput;
1002 }
1003 char* tok2_end = CurTokenEnd(tok2_start);
1004 local_line_iter = NextTokenMult(tok2_end, last_skip);
1005 if (unlikely(!local_line_iter)) {
1006 logputs("\n");
1007 logerrprintf("Error: Line %u of --glm local-covar= file has fewer tokens than expected.\n", local_line_idx);
1008 return kPglRetMalformedInput;
1009 }
1010 char* chr_code_start = tok1_start;
1011 char* chr_code_end = tok1_end;
1012 char* bp_col_start = tok2_start;
1013 if (local_chrom_col > local_bp_col) {
1014 chr_code_start = tok2_start;
1015 chr_code_end = tok2_end;
1016 bp_col_start = tok1_start;
1017 }
1018 const uint32_t next_chr_code = GetChrCodeCounted(cip, chr_code_end - chr_code_start, chr_code_start);
1019 if (next_chr_code != local_chr_code) {
1020 local_skip_chr = IsI32Neg(next_chr_code) || (!IsSet(cip->chr_mask, next_chr_code));
1021 if (local_skip_chr) {
1022 continue;
1023 }
1024 // Still possible for all variants in this chromosome to have been
1025 // filtered out.
1026 const uint32_t new_chr_fo_idx = cip->chr_idx_to_foidx[next_chr_code];
1027 if (local_chr_code != UINT32_MAX) {
1028 // May as well sanity-check this.
1029 const uint32_t old_chr_fo_idx = cip->chr_idx_to_foidx[local_chr_code];
1030 if (unlikely(old_chr_fo_idx > new_chr_fo_idx)) {
1031 logputs("\n");
1032 logerrputs("Error: --glm local-covar= file has a different chromosome order than the main\ndataset.\n");
1033 return kPglRetInconsistentInput;
1034 }
1035 }
1036 const uint32_t chr_start_vidx = cip->chr_fo_vidx_start[new_chr_fo_idx];
1037 const uint32_t chr_end_vidx = cip->chr_fo_vidx_start[new_chr_fo_idx + 1];
1038 local_skip_chr = !PopcountBitRange(variant_include, chr_start_vidx, chr_end_vidx);
1039 if (local_skip_chr) {
1040 continue;
1041 }
1042 // May as well ensure that local_prev_chr_code is either UINT32_MAX,
1043 // or corresponds to a not-totally-excluded chromosome, so failures
1044 // of the sanity check above are more likely to be meaningful.
1045 local_prev_chr_code = local_chr_code;
1046 local_chr_code = next_chr_code;
1047 local_bp = UINT32_MAX;
1048 is_x = (local_chr_code == x_code);
1049 is_y = (local_chr_code == y_code);
1050 const uint32_t new_local_xy = is_x + 2 * is_y;
1051 if (new_local_xy != local_xy) {
1052 local_xy = new_local_xy;
1053 if (is_y && common->sample_include_y) {
1054 cur_sample_include = common->sample_include_y;
1055 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
1056 coeffparse_ctx.cur_sample_ct = sample_ct_y;
1057 } else if (is_x && common->sample_include_x) {
1058 cur_sample_include = common->sample_include_x;
1059 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
1060 coeffparse_ctx.cur_sample_ct = sample_ct_x;
1061 } else {
1062 cur_sample_include = common->sample_include;
1063 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
1064 coeffparse_ctx.cur_sample_ct = sample_ct;
1065 }
1066 for (uint32_t uii = 0; uii != local_sample_ct; ++uii) {
1067 const uint32_t cur_uidx = local_sample_uidx_order[uii];
1068 uint32_t cur_idx = UINT32_MAX;
1069 if ((cur_uidx != UINT32_MAX) && IsSet(cur_sample_include, cur_uidx)) {
1070 cur_idx = RawToSubsettedPos(cur_sample_include, cur_sample_include_cumulative_popcounts, cur_uidx);
1071 }
1072 local_sample_idx_order[uii] = cur_idx;
1073 }
1074 }
1075 } else if (local_skip_chr) {
1076 continue;
1077 }
1078 uint32_t next_bp;
1079 if (unlikely(ScanPosintDefcap(bp_col_start, &next_bp))) {
1080 logputs("\n");
1081 logerrprintf("Error: Line %u of --glm local-covar= file has fewer tokens than expected.\n", local_line_idx);
1082 return kPglRetMalformedInput;
1083 }
1084 // could conditionally prohibit duplicate positions
1085 if (unlikely(S_CAST(int32_t, next_bp) < S_CAST(int32_t, local_bp))) {
1086 logputs("\n");
1087 logerrputs("Error: Positions in --glm local-covar= file are not sorted.\n");
1088 return kPglRetMalformedInput;
1089 }
1090 local_bp = next_bp;
1091 }
1092 *local_line_iterp = local_line_iter;
1093 *local_line_idx_ptr = local_line_idx;
1094 *local_prev_chr_code_ptr = local_prev_chr_code;
1095 *local_chr_code_ptr = local_chr_code;
1096 *local_bp_ptr = local_bp;
1097 *local_skip_chr_ptr = local_skip_chr;
1098 return kPglRetSuccess;
1099 }
1100
1101 const double kSmallDoublePairs[32] ALIGNV16 = PAIR_TABLE16(0.0, 1.0, 2.0, 3.0);
1102
1103 const double kSmallInvDoublePairs[32] ALIGNV16 = PAIR_TABLE16(2.0, 1.0, 0.0, 3.0);
1104
1105 const double kSmallInvDoubles[4] = {2.0, 1.0, 0.0, 3.0};
1106
1107 uint32_t GenoarrToDoublesRemoveMissing(const uintptr_t* genoarr, const double* __restrict table, uint32_t sample_ct, double* __restrict dst) {
1108 assert(sample_ct);
1109 const uint32_t sample_ctl2m1 = (sample_ct - 1) / kBitsPerWordD2;
1110 uint32_t subgroup_len = kBitsPerWordD2;
1111 double* dst_iter = dst;
1112 for (uint32_t widx = 0; ; ++widx) {
1113 if (widx >= sample_ctl2m1) {
1114 if (widx > sample_ctl2m1) {
1115 return dst_iter - dst;
1116 }
1117 subgroup_len = ModNz(sample_ct, kBitsPerWordD2);
1118 }
1119 uintptr_t geno_word = genoarr[widx];
1120 for (uint32_t uii = 0; uii != subgroup_len; ++uii) {
1121 const uintptr_t cur_geno = geno_word & 3;
1122 if (cur_geno < 3) {
1123 // *dst_iter++ = u31tod(cur_geno);
1124 *dst_iter++ = table[cur_geno];
1125 }
1126 geno_word >>= 2;
1127 }
1128 }
1129 }
1130
1131 BoolErr LinearHypothesisChisq(const double* coef, const double* constraints_con_major, const double* cov_matrix, uintptr_t constraint_ct, uintptr_t predictor_ct, uintptr_t cov_stride, double* chisq_ptr, double* tmphxs_buf, double* h_transpose_buf, double* inner_buf, MatrixInvertBuf1* mi_buf, double* outer_buf) {
1132 // See PLINK model.cpp Model::linearHypothesis().
1133 //
1134 // outer_buf = constraint_ct
1135 // inner_buf = constraint_ct x constraint_ct
1136 // tmphxs_buf and h_transpose_buf are constraint_ct x predictor_ct
1137 // mi_buf only needs to be of length 2 * constraint_ct
1138 //
1139 // Since no PLINK function ever calls this with nonzero h[] values, this just
1140 // takes a df (constraint_ct) parameter for now; it's trivial to switch to
1141 // the more general interface later.
1142 ColMajorVectorMatrixMultiplyStrided(coef, constraints_con_major, predictor_ct, predictor_ct, constraint_ct, outer_buf);
1143 MatrixTransposeCopy(constraints_con_major, constraint_ct, predictor_ct, h_transpose_buf);
1144 ColMajorMatrixMultiplyStrided(h_transpose_buf, cov_matrix, constraint_ct, constraint_ct, predictor_ct, cov_stride, predictor_ct, constraint_ct, tmphxs_buf);
1145 // tmp[][] is now predictor-major
1146 ColMajorMatrixMultiply(tmphxs_buf, constraints_con_major, constraint_ct, constraint_ct, predictor_ct, inner_buf);
1147
1148 // don't need H-transpose any more, so we can use h_transpose_buf for matrix
1149 // inversion
1150 if (InvertMatrix(constraint_ct, inner_buf, mi_buf, h_transpose_buf)) {
1151 return 1;
1152 }
1153 double result = 0.0;
1154 const double* inner_iter = inner_buf;
1155 if (constraint_ct > kDotprodDThresh) {
1156 for (uintptr_t constraint_idx = 0; constraint_idx != constraint_ct; ++constraint_idx) {
1157 result += DotprodD(inner_iter, outer_buf, constraint_ct) * outer_buf[constraint_idx];
1158 inner_iter = &(inner_iter[constraint_ct]);
1159 }
1160 } else {
1161 for (uintptr_t constraint_idx = 0; constraint_idx != constraint_ct; ++constraint_idx) {
1162 result += DotprodDShort(inner_iter, outer_buf, constraint_ct) * outer_buf[constraint_idx];
1163 inner_iter = &(inner_iter[constraint_ct]);
1164 }
1165 }
1166 if (result < 0.0) {
1167 // guard against floating point error
1168 result = 0.0;
1169 }
1170 *chisq_ptr = result;
1171 return 0;
1172 }
1173
1174 #ifdef __cplusplus
1175 } // namespace plink2
1176 #endif