Debian Codegraph @

plink2_glm_logistic.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_fmath.h"
18 #include "include/plink2_stats.h"
19 #include "plink2_compress_stream.h"
20 #include "plink2_glm_logistic.h"
21
22 #ifdef __cplusplus
23 namespace plink2 {
24 #endif
25
26 // refugee from plink2_stats.h; important to remove its plink2_matrix.h
27 // dependency
28
29 // outer_buf = constraint_ct
30 // inner_buf = constraint_ct x constraint_ct
31 // tmphxs_buf and h_transpose_buf are constraint_ct x predictor_ct
32 // mi_buf only needs to be of length 2 * constraint_ct
33 BoolErr LinearHypothesisChisqF(const float* coef, const float* constraints_con_major, const float* cov_matrix, uint32_t constraint_ct, uint32_t predictor_ct, uint32_t cov_stride, double* chisq_ptr, float* tmphxs_buf, float* h_transpose_buf, float* inner_buf, double* half_inverted_buf, MatrixInvertBuf1* mi_buf, double* dbl_2d_buf, float* outer_buf) {
34 ColMajorFvectorMatrixMultiplyStrided(coef, constraints_con_major, predictor_ct, predictor_ct, constraint_ct, outer_buf);
35 // h-transpose does not have a special stride
36 FmatrixTransposeCopy(constraints_con_major, constraint_ct, predictor_ct, predictor_ct, h_transpose_buf);
37 ColMajorFmatrixMultiplyStrided(h_transpose_buf, cov_matrix, constraint_ct, constraint_ct, predictor_ct, cov_stride, predictor_ct, constraint_ct, tmphxs_buf);
38 // tmp[][] is now predictor-major
39 ColMajorFmatrixMultiplyStrided(tmphxs_buf, constraints_con_major, constraint_ct, constraint_ct, constraint_ct, predictor_ct, predictor_ct, constraint_ct, inner_buf);
40
41 if (InvertFmatrixFirstHalf(constraint_ct, constraint_ct, inner_buf, half_inverted_buf, mi_buf, dbl_2d_buf)) {
42 return 1;
43 }
44 InvertFmatrixSecondHalf(constraint_ct, constraint_ct, half_inverted_buf, inner_buf, mi_buf, dbl_2d_buf);
45 double result = 0.0;
46 const float* inner_iter = inner_buf;
47 if (constraint_ct > kDotprodFThresh) {
48 for (uint32_t constraint_idx = 0; constraint_idx != constraint_ct; ++constraint_idx) {
49 result += S_CAST(double, DotprodF(inner_iter, outer_buf, constraint_ct) * outer_buf[constraint_idx]);
50 inner_iter = &(inner_iter[constraint_ct]);
51 }
52 } else {
53 for (uint32_t constraint_idx = 0; constraint_idx != constraint_ct; ++constraint_idx) {
54 result += S_CAST(double, DotprodFShort(inner_iter, outer_buf, constraint_ct) * outer_buf[constraint_idx]);
55 inner_iter = &(inner_iter[constraint_ct]);
56 }
57 }
58 if (result < 0.0) {
59 // guard against floating point error
60 result = 0.0;
61 }
62 *chisq_ptr = result;
63 return 0;
64 }
65
66 // Only called by GlmLogisticThreadF(), so there are the following differences
67 // from CheckMaxCorrAndVif():
68 // * predictor_dotprods is not precomputed; we start with predictors_pmaj
69 // instead.
70 // * predictors_pmaj already has the intercept stripped off, so we don't need
71 // relevant_predictor_ct := predictor_ct - 1, etc.
72 // * sample_stride parameter added, since predictors_pmaj has vector-aligned
73 // rather than packed rows.
74 // * dbl_2d_buf not assumed to be filled with row sums, we compute them here.
75 // (probably want to modify CheckMaxCorrAndVif() to do the same.)
76 // This now uses double-precision arithmetic since matrix inversion is too
77 // inconsistent if we stick to single-precision.
78 GlmErr CheckMaxCorrAndVifF(const float* predictors_pmaj, uint32_t predictor_ct, uint32_t sample_ct, uint32_t sample_stride, double max_corr, double vif_thresh, float* predictor_dotprod_buf, double* dbl_2d_buf, double* inverse_corr_buf, MatrixInvertBuf1* inv_1d_buf) {
79 MultiplySelfTransposeStridedF(predictors_pmaj, predictor_ct, sample_ct, sample_stride, predictor_dotprod_buf);
80 for (uintptr_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
81 const float* predictor_row = &(predictors_pmaj[pred_idx * sample_stride]);
82 double row_sum = 0.0;
83 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
84 row_sum += S_CAST(double, predictor_row[sample_idx]);
85 }
86 dbl_2d_buf[pred_idx] = row_sum;
87 }
88 const uint32_t predictor_ct_p1 = predictor_ct + 1;
89 const double sample_ct_recip = 1.0 / u31tod(sample_ct);
90 const double sample_ct_m1_d = u31tod(sample_ct - 1);
91 const double sample_ct_m1_recip = 1.0 / sample_ct_m1_d;
92 for (uint32_t pred_idx1 = 0; pred_idx1 != predictor_ct; ++pred_idx1) {
93 double* sample_corr_row = &(inverse_corr_buf[pred_idx1 * predictor_ct]);
94 const float* predictor_dotprod_row = &(predictor_dotprod_buf[pred_idx1 * predictor_ct]);
95 const double covar1_mean_adj = dbl_2d_buf[pred_idx1] * sample_ct_recip;
96 for (uint32_t pred_idx2 = 0; pred_idx2 <= pred_idx1; ++pred_idx2) {
97 sample_corr_row[pred_idx2] = (S_CAST(double, predictor_dotprod_row[pred_idx2]) - covar1_mean_adj * dbl_2d_buf[pred_idx2]) * sample_ct_m1_recip;
98 }
99 }
100 // now use dbl_2d_buf to store inverse-sqrts, to get to correlation matrix
101 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
102 dbl_2d_buf[pred_idx] = 1.0 / sqrt(inverse_corr_buf[pred_idx * predictor_ct_p1]);
103 }
104 // invert_symmdef_matrix only cares about bottom left of inverse_corr_buf[]
105 for (uint32_t pred_idx1 = 1; pred_idx1 != predictor_ct; ++pred_idx1) {
106 const double inverse_stdev1 = dbl_2d_buf[pred_idx1];
107 double* corr_row_iter = &(inverse_corr_buf[pred_idx1 * predictor_ct]);
108 const double* inverse_stdev2_iter = dbl_2d_buf;
109 for (uintptr_t pred_idx2 = 0; pred_idx2 != pred_idx1; ++pred_idx2) {
110 const double cur_corr = (*corr_row_iter) * inverse_stdev1 * (*inverse_stdev2_iter++);
111 if (fabs(cur_corr) > max_corr) {
112 return SetGlmErr2(kGlmErrcodeCorrTooHigh, pred_idx2, pred_idx1);
113 }
114 *corr_row_iter++ = cur_corr;
115 }
116 }
117 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
118 inverse_corr_buf[pred_idx * predictor_ct_p1] = 1.0;
119 }
120 if (InvertSymmdefMatrixChecked(predictor_ct, inverse_corr_buf, inv_1d_buf, dbl_2d_buf)) {
121 return SetGlmErr0(kGlmErrcodeVifInfinite);
122 }
123
124 // VIFs = diagonal elements of inverse correlation matrix
125 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
126 if (inverse_corr_buf[pred_idx * predictor_ct_p1] > vif_thresh) {
127 return SetGlmErr1(kGlmErrcodeVifTooHigh, pred_idx);
128 }
129 }
130 return 0;
131 }
132
133 static const float kSmallFloatPairs[32] = PAIR_TABLE16(0.0, 1.0, 2.0, 3.0);
134
135 static const float kSmallInvFloatPairs[32] = PAIR_TABLE16(2.0, 1.0, 0.0, 3.0);
136
137 static const float kSmallInvFloats[4] = {2.0, 1.0, 0.0, 3.0};
138
139 uint32_t GenoarrToFloatsRemoveMissing(const uintptr_t* genoarr, const float* __restrict table, uint32_t sample_ct, float* __restrict dst) {
140 assert(sample_ct);
141 const uint32_t sample_ctl2m1 = (sample_ct - 1) / kBitsPerWordD2;
142 uint32_t subgroup_len = kBitsPerWordD2;
143 float* dst_iter = dst;
144 for (uint32_t widx = 0; ; ++widx) {
145 if (widx >= sample_ctl2m1) {
146 if (widx > sample_ctl2m1) {
147 return S_CAST(uint32_t, dst_iter - dst);
148 }
149 subgroup_len = ModNz(sample_ct, kBitsPerWordD2);
150 }
151 uintptr_t geno_word = genoarr[widx];
152 for (uint32_t uii = 0; uii != subgroup_len; ++uii) {
153 const uintptr_t cur_geno = geno_word & 3;
154 if (cur_geno < 3) {
155 *dst_iter++ = table[cur_geno];
156 }
157 geno_word >>= 2;
158 }
159 }
160 }
161
162 // #####
163 // The following code is based on the winning submission of Pascal Pons in the
164 // "GWASSpeedup" contest run in April 2013 by Babbage Analytics & Innovation
165 // and TopCoder, who have donated the results to be used in PLINK. See:
166 // Hill A, Loh PR, Bharadwaj RB, Pons P, Shang J, Guinan E, Lakhani K,
167 // Kilty I, Jelinsky SA (2017) Stepwise Distributed Open Innovation Contests
168 // for Software Development - Acceleration of Genome-Wide Association
169 // Analysis. Gigascience, 6.
170 // #####
171
172 #ifdef __LP64__
173 // For equivalent "normal" C/C++ code, see the non-__LP64__ versions of these
174 // functions.
175
176 // N.B. This requires all mm[] rows to be zero-padded at the end, and there
177 // can't be nan values at the end of vect[]. (The other way around works too.)
178 //
179 // This is currently a bit faster than sgemm and sgemv on my Mac, so it isn't
180 // appropriate to throw out this code yet.
181 # ifdef FVEC_32
182 static inline void MultMatrixDxnVectNF(const float* mm, const float* vect, uint32_t col_ct, uint32_t row_ct, float* __restrict dest) {
183 const uintptr_t col_ctav = RoundUpPow2(col_ct, kFloatPerFVec);
184 uint32_t row_idx = 0;
185 __m256 s1;
186 __m256 s2;
187 __m256 s3;
188 if (row_ct > 3) {
189 const uint32_t row_ctm3 = row_ct - 3;
190 // Handle 4 rows at a time in this loop, regardless of vector size.
191 for (; row_idx < row_ctm3; row_idx += 4) {
192 s1 = _mm256_setzero_ps();
193 s2 = _mm256_setzero_ps();
194 s3 = _mm256_setzero_ps();
195 __m256 s4 = _mm256_setzero_ps();
196 for (uint32_t col_idx = 0; col_idx < col_ct; col_idx += kFloatPerFVec) {
197 const float* mm_ptr = &(mm[row_idx * col_ctav + col_idx]);
198 const __m256 vv = _mm256_load_ps(&(vect[col_idx]));
199 __m256 a1 = _mm256_load_ps(mm_ptr);
200 __m256 a2 = _mm256_load_ps(&(mm_ptr[col_ctav]));
201 __m256 a3 = _mm256_load_ps(&(mm_ptr[2 * col_ctav]));
202 __m256 a4 = _mm256_load_ps(&(mm_ptr[3 * col_ctav]));
203 s1 = _mm256_fmadd_ps(a1, vv, s1);
204 s2 = _mm256_fmadd_ps(a2, vv, s2);
205 s3 = _mm256_fmadd_ps(a3, vv, s3);
206 s4 = _mm256_fmadd_ps(a4, vv, s4);
207 }
208 *dest++ = VecFHsum(R_CAST(VecF, s1));
209 *dest++ = VecFHsum(R_CAST(VecF, s2));
210 *dest++ = VecFHsum(R_CAST(VecF, s3));
211 *dest++ = VecFHsum(R_CAST(VecF, s4));
212 }
213 }
214 s1 = _mm256_setzero_ps();
215 s2 = _mm256_setzero_ps();
216 s3 = _mm256_setzero_ps();
217 switch (row_ct % 4) {
218 case 3:
219 for (uint32_t col_idx = 0; col_idx < col_ct; col_idx += kFloatPerFVec) {
220 const float* mm_ptr = &(mm[row_idx * col_ctav + col_idx]);
221 const __m256 vv = _mm256_load_ps(&(vect[col_idx]));
222 __m256 a1 = _mm256_load_ps(mm_ptr);
223 __m256 a2 = _mm256_load_ps(&(mm_ptr[col_ctav]));
224 __m256 a3 = _mm256_load_ps(&(mm_ptr[2 * col_ctav]));
225 s1 = _mm256_fmadd_ps(a1, vv, s1);
226 s2 = _mm256_fmadd_ps(a2, vv, s2);
227 s3 = _mm256_fmadd_ps(a3, vv, s3);
228 }
229 *dest++ = VecFHsum(R_CAST(VecF, s1));
230 *dest++ = VecFHsum(R_CAST(VecF, s2));
231 *dest = VecFHsum(R_CAST(VecF, s3));
232 break;
233 case 2:
234 for (uint32_t col_idx = 0; col_idx < col_ct; col_idx += kFloatPerFVec) {
235 const float* mm_ptr = &(mm[row_idx * col_ctav + col_idx]);
236 const __m256 vv = _mm256_load_ps(&(vect[col_idx]));
237 __m256 a1 = _mm256_load_ps(mm_ptr);
238 __m256 a2 = _mm256_load_ps(&(mm_ptr[col_ctav]));
239 s1 = _mm256_fmadd_ps(a1, vv, s1);
240 s2 = _mm256_fmadd_ps(a2, vv, s2);
241 }
242 *dest++ = VecFHsum(R_CAST(VecF, s1));
243 *dest = VecFHsum(R_CAST(VecF, s2));
244 break;
245 case 1:
246 for (uint32_t col_idx = 0; col_idx < col_ct; col_idx += kFloatPerFVec) {
247 const __m256 vv = _mm256_load_ps(&(vect[col_idx]));
248 __m256 a1 = _mm256_load_ps(&(mm[row_idx * col_ctav + col_idx]));
249 s1 = _mm256_fmadd_ps(a1, vv, s1);
250 }
251 *dest = VecFHsum(R_CAST(VecF, s1));
252 break;
253 }
254 }
255
256 # else // !FVEC_32
257 static inline void MultMatrixDxnVectNF(const float* mm, const float* vect, uint32_t col_ct, uint32_t row_ct, float* __restrict dest) {
258 const uint32_t col_ctav = RoundUpPow2(col_ct, kFloatPerFVec);
259 ColMajorFvectorMatrixMultiplyStrided(vect, mm, col_ct, col_ctav, row_ct, dest);
260 }
261
262 # endif // !FVEC_32
263 // !__LP64__
264
265 static inline void LogisticSseF(uint32_t nn, float* vect) {
266 const VecF zero = vecf_setzero();
267 const VecF one = VCONST_F(1.0);
268 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
269 VecF aa = *R_CAST(VecF*, &(vect[uii]));
270 aa = zero - aa;
271 // tried substituting in vexpf() here on OS X; it was slower without being
272 // significantly more accurate.
273 aa = fmath_exp_ps(aa);
274 aa = aa + one;
275 aa = one / aa;
276 *R_CAST(VecF*, &(vect[uii])) = aa;
277 }
278 }
279
280 static inline void ComputeVAndPMinusYF(const float* yy, uint32_t nn, float* __restrict pp, float* __restrict vv) {
281 const VecF one = VCONST_F(1.0);
282 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
283 VecF ptmp = *R_CAST(VecF*, &(pp[uii]));
284 VecF one_minus_ptmp = one - ptmp;
285 *R_CAST(VecF*, &(vv[uii])) = ptmp * one_minus_ptmp;
286 VecF ytmp = *R_CAST(const VecF*, &(yy[uii]));
287 *R_CAST(VecF*, &(pp[uii])) = ptmp - ytmp;
288 }
289 }
290
291 static inline void ComputeVF(const float* pp, uint32_t nn, float* __restrict vv) {
292 const VecF one = VCONST_F(1.0);
293 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
294 VecF ptmp = *R_CAST(const VecF*, &(pp[uii]));
295 VecF one_minus_ptmp = one - ptmp;
296 *R_CAST(VecF*, &(vv[uii])) = ptmp * one_minus_ptmp;
297 }
298 }
299
300 static inline float TripleProductF(const float* v1, const float* v2, const float* v3, uint32_t nn) {
301 VecF sum = vecf_setzero();
302 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
303 VecF aa = *R_CAST(const VecF*, &(v1[uii]));
304 VecF bb = *R_CAST(const VecF*, &(v2[uii]));
305 VecF cc = *R_CAST(const VecF*, &(v3[uii]));
306 sum = sum + aa * bb * cc;
307 }
308 return VecFHsum(sum);
309 }
310
311 static inline void ComputeTwoDiagTripleProductF(const float* aa, const float* bb, const float* vv, uint32_t nn, float* __restrict raa_ptr, float* __restrict rab_ptr, float* __restrict rbb_ptr) {
312 VecF saa = vecf_setzero();
313 VecF sab = vecf_setzero();
314 VecF sbb = vecf_setzero();
315 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
316 const VecF vtmp = *R_CAST(const VecF*, &(vv[uii]));
317 const VecF atmp = *R_CAST(const VecF*, &(aa[uii]));
318 const VecF btmp = *R_CAST(const VecF*, &(bb[uii]));
319 const VecF av = atmp * vtmp;
320 const VecF bv = btmp * vtmp;
321 saa = saa + atmp * av;
322 sab = sab + atmp * bv;
323 sbb = sbb + btmp * bv;
324 }
325 *raa_ptr = VecFHsum(saa);
326 *rab_ptr = VecFHsum(sab);
327 *rbb_ptr = VecFHsum(sbb);
328 }
329
330 static inline void ComputeThreeTripleProductF(const float* bb, const float* a1, const float* a2, const float* a3, const float* vv, uint32_t nn, float* __restrict r1_ptr, float* __restrict r2_ptr, float* __restrict r3_ptr) {
331 VecF s1 = vecf_setzero();
332 VecF s2 = vecf_setzero();
333 VecF s3 = vecf_setzero();
334 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
335 const VecF a1tmp = *R_CAST(const VecF*, &(a1[uii]));
336 const VecF a2tmp = *R_CAST(const VecF*, &(a2[uii]));
337 const VecF a3tmp = *R_CAST(const VecF*, &(a3[uii]));
338 const VecF vtmp = *R_CAST(const VecF*, &(vv[uii]));
339 VecF btmp = *R_CAST(const VecF*, &(bb[uii]));
340 btmp = btmp * vtmp;
341 s1 = s1 + a1tmp * btmp;
342 s2 = s2 + a2tmp * btmp;
343 s3 = s3 + a3tmp * btmp;
344 }
345 *r1_ptr = VecFHsum(s1);
346 *r2_ptr = VecFHsum(s2);
347 *r3_ptr = VecFHsum(s3);
348 }
349
350 static inline void ComputeTwoPlusOneTripleProductF(const float* bb, const float* a1, const float* a2, const float* vv, uint32_t nn, float* __restrict r1_ptr, float* __restrict r2_ptr, float* __restrict r3_ptr) {
351 VecF s1 = vecf_setzero();
352 VecF s2 = vecf_setzero();
353 VecF s3 = vecf_setzero();
354 for (uint32_t uii = 0; uii < nn; uii += kFloatPerFVec) {
355 const VecF a1tmp = *R_CAST(const VecF*, &(a1[uii]));
356 const VecF a2tmp = *R_CAST(const VecF*, &(a2[uii]));
357 const VecF btmp = *R_CAST(const VecF*, &(bb[uii]));
358 const VecF vtmp = *R_CAST(const VecF*, &(vv[uii]));
359 const VecF bv = btmp * vtmp;
360 s1 = s1 + btmp * bv;
361 s2 = s2 + a1tmp * bv;
362 s3 = s3 + a2tmp * bv;
363 }
364 *r1_ptr = VecFHsum(s1);
365 *r2_ptr = VecFHsum(s2);
366 *r3_ptr = VecFHsum(s3);
367 }
368 #else // no __LP64__ (and hence, unsafe to assume presence of SSE2)
369 static inline void LogisticSseF(uint32_t nn, float* vect) {
370 // We use explicit static_cast<float> instead of e.g. 1.0f because
371 // handling of the latter is actually implementation-specific; see
372 // http://nullprogram.com/blog/2018/05/01/
373 // In particular, that blog post claims that
374 // int float_compare() {
375 // float x = 1.3f;
376 // return x == 1.3f;
377 // }
378 // returns 0 under gcc and 1 under clang (with -std=c99 -m32, which is one of
379 // plink2's compilation settings)????!!!!!!!
380 // Unless the author is outright mistaken, this suggests that use of the f
381 // suffix should be considered a bug ~100% of the time.
382 for (uint32_t uii = 0; uii != nn; ++uii) {
383 vect[uii] = S_CAST(float, 1.0) / (1 + expf(-vect[uii]));
384 }
385 }
386
387 static inline void ComputeVAndPMinusYF(const float* yy, uint32_t nn, float* __restrict pp, float* __restrict vv) {
388 for (uint32_t uii = 0; uii != nn; ++uii) {
389 vv[uii] = pp[uii] * (S_CAST(float, 1.0) - pp[uii]);
390 pp[uii] -= yy[uii];
391 }
392 }
393
394 static inline void ComputeVF(const float* pp, uint32_t nn, float* __restrict vv) {
395 for (uint32_t uii = 0; uii != nn; ++uii) {
396 vv[uii] = pp[uii] * (S_CAST(float, 1.0) - pp[uii]);
397 }
398 }
399
400 static inline void MultMatrixDxnVectNF(const float* mm, const float* vect, uint32_t col_ct, uint32_t row_ct, float* __restrict dest) {
401 const uint32_t col_ctav = RoundUpPow2(col_ct, kFloatPerFVec);
402 ColMajorFvectorMatrixMultiplyStrided(vect, mm, col_ct, col_ctav, row_ct, dest);
403 }
404
405 static inline float TripleProductF(const float* v1, const float* v2, const float* v3, uint32_t nn) {
406 float fxx = 0.0;
407 for (uint32_t uii = 0; uii != nn; ++uii) {
408 fxx += v1[uii] * v2[uii] * v3[uii];
409 }
410 return fxx;
411 }
412
413 static inline void ComputeTwoDiagTripleProductF(const float* aa, const float* bb, const float* vv, uint32_t nn, float* __restrict raa_ptr, float* __restrict rab_ptr, float* __restrict rbb_ptr) {
414 float raa = 0.0;
415 float rab = 0.0;
416 float rbb = 0.0;
417 for (uint32_t uii = 0; uii != nn; ++uii) {
418 const float fxx = aa[uii];
419 const float fyy = bb[uii];
420 float fzz = vv[uii];
421 raa += fxx * fxx * fzz;
422 fzz *= fyy;
423 rab += fxx * fzz;
424 rbb += fyy * fzz;
425 }
426 *raa_ptr = raa;
427 *rab_ptr = rab;
428 *rbb_ptr = rbb;
429 }
430
431 static inline void ComputeThreeTripleProductF(const float* bb, const float* a1, const float* a2, const float* a3, const float* vv, uint32_t nn, float* __restrict r1_ptr, float* __restrict r2_ptr, float* __restrict r3_ptr) {
432 float r1 = 0.0;
433 float r2 = 0.0;
434 float r3 = 0.0;
435 for (uint32_t uii = 0; uii != nn; ++uii) {
436 const float fxx = bb[uii] * vv[uii];
437 r1 += a1[uii] * fxx;
438 r2 += a2[uii] * fxx;
439 r3 += a3[uii] * fxx;
440 }
441 *r1_ptr = r1;
442 *r2_ptr = r2;
443 *r3_ptr = r3;
444 }
445
446 static inline void ComputeTwoPlusOneTripleProductF(const float* bb, const float* a1, const float* a2, const float* vv, uint32_t nn, float* __restrict r1_ptr, float* __restrict r2_ptr, float* __restrict r3_ptr) {
447 float r1 = 0.0;
448 float r2 = 0.0;
449 float r3 = 0.0;
450 for (uint32_t uii = 0; uii != nn; ++uii) {
451 const float fxx = bb[uii];
452 const float fyy = fxx * vv[uii];
453 r1 += fxx * fyy;
454 r2 += a1[uii] * fyy;
455 r3 += a2[uii] * fyy;
456 }
457 *r1_ptr = r1;
458 *r2_ptr = r2;
459 *r3_ptr = r3;
460 }
461 #endif
462 BoolErr ComputeLoglikCheckedF(const float* yy, const float* pp, uint32_t sample_ct, double* loglik_ptr) {
463 // possible todo: look for a high-precision way to accelerate this.
464 double loglik = 0.0;
465 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
466 const double new_pi = S_CAST(double, pp[sample_idx]);
467 if ((new_pi == 0.0) || (new_pi == 1.0)) {
468 return 1;
469 }
470 loglik += (yy[sample_idx] != S_CAST(float, 0.0))? log(new_pi) : log1p(-new_pi);
471 }
472 *loglik_ptr = loglik;
473 return 0;
474 }
475
476 // M V M^T
477 // This is the biggest logistic/Firth regression bottleneck.
478 // Tried to replace this with sqrt(v) followed by ssyrk, but that was slower.
479 // Also tried to take advantage of the first row of M being constant-1, and
480 // managed to fail.
481 void ComputeHessianF(const float* mm, const float* vv, uint32_t col_ct, uint32_t row_ct, float* __restrict dest) {
482 const uintptr_t col_ctav = RoundUpPow2(col_ct, kFloatPerFVec);
483 const uintptr_t row_ctav = RoundUpPow2(row_ct, kFloatPerFVec);
484 const uintptr_t row_ctavp1 = row_ctav + 1;
485 if (row_ct > 3) {
486 const uint32_t row_ctm3 = row_ct - 3;
487 for (uint32_t row_idx = 0; row_idx < row_ctm3; row_idx += 3) {
488 const float* mm_cur = &(mm[row_idx * col_ctav]);
489 ComputeTwoDiagTripleProductF(mm_cur, &(mm_cur[col_ctav]), vv, col_ct, &(dest[row_idx * row_ctavp1]), &(dest[(row_idx + 1) * row_ctavp1 - 1]), &(dest[(row_idx + 1) * row_ctavp1]));
490 ComputeTwoPlusOneTripleProductF(&(mm_cur[2 * col_ctav]), &(mm_cur[col_ctav]), mm_cur, vv, col_ct, &(dest[(row_idx + 2) * row_ctavp1]), &(dest[(row_idx + 2) * row_ctavp1 - 1]), &(dest[(row_idx + 2) * row_ctavp1 - 2]));
491 for (uint32_t row_idx2 = row_idx + 3; row_idx2 != row_ct; ++row_idx2) {
492 ComputeThreeTripleProductF(&(mm[row_idx2 * col_ctav]), mm_cur, &(mm_cur[col_ctav]), &(mm_cur[2 * col_ctav]), vv, col_ct, &(dest[row_idx2 * row_ctav + row_idx]), &(dest[row_idx2 * row_ctav + row_idx + 1]), &(dest[row_idx2 * row_ctav + row_idx + 2]));
493 }
494 }
495 }
496 switch (row_ct % 3) {
497 case 0:
498 ComputeTwoPlusOneTripleProductF(&(mm[(row_ct - 3) * col_ctav]), &(mm[(row_ct - 2) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct, &(dest[(row_ct - 3) * row_ctavp1]), &(dest[(row_ct - 2) * row_ctavp1 - 1]), &(dest[(row_ct - 1) * row_ctavp1 - 2]));
499 // fall through
500 case 2:
501 ComputeTwoDiagTripleProductF(&(mm[(row_ct - 2) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct, &(dest[(row_ct - 2) * row_ctavp1]), &(dest[(row_ct - 1) * row_ctavp1 - 1]), &(dest[(row_ct - 1) * row_ctavp1]));
502 break;
503 case 1:
504 dest[(row_ct - 1) * row_ctavp1] = TripleProductF(&(mm[(row_ct - 1) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct);
505 }
506 }
507
508 void CholeskyDecompositionF(const float* aa, uint32_t predictor_ct, float* __restrict ll) {
509 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kFloatPerFVec);
510 const uintptr_t predictor_ctavp1 = predictor_ctav + 1;
511 const float* aa_diag_elem_ptr = aa;
512 float* cur_ll_row = ll;
513 for (uint32_t row_idx = 0; row_idx != predictor_ct; ++row_idx) {
514 float fxx = *aa_diag_elem_ptr;
515 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
516 const float fyy = cur_ll_row[col_idx];
517 fxx -= fyy * fyy;
518 }
519 float fyy;
520 if (fxx >= S_CAST(float, 0.0)) {
521 fyy = sqrtf(fxx);
522 } else {
523 fyy = S_CAST(float, 1e-6);
524 }
525 cur_ll_row[row_idx] = fyy;
526 fyy = S_CAST(float, 1.0) / fyy; // now 1.0 / L[j][j]
527 const float* aa_col_iter = aa_diag_elem_ptr;
528 float* cur_ll_row2 = cur_ll_row;
529 for (uint32_t row_idx2 = row_idx + 1; row_idx2 != predictor_ct; ++row_idx2) {
530 aa_col_iter = &(aa_col_iter[predictor_ctav]);
531 float fxx2 = *aa_col_iter;
532 cur_ll_row2 = &(cur_ll_row2[predictor_ctav]);
533 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
534 fxx2 -= cur_ll_row[col_idx] * cur_ll_row2[col_idx];
535 }
536 cur_ll_row2[row_idx] = fxx2 * fyy;
537 }
538 aa_diag_elem_ptr = &(aa_diag_elem_ptr[predictor_ctavp1]);
539 cur_ll_row = &(cur_ll_row[predictor_ctav]);
540 }
541 }
542
543 void SolveLinearSystemF(const float* ll, const float* yy, uint32_t predictor_ct, float* __restrict xx) {
544 // Finds x such that y = L(L^T)x, via forward and backward substitution
545 //
546 // might want to use this in NOLAPACK case only, since we can now produce
547 // 32-bit Linux builds with statically linked LAPACK
548 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kFloatPerFVec);
549 {
550 const float* cur_ll_row = ll;
551 for (uint32_t row_idx = 0; row_idx != predictor_ct; ++row_idx) {
552 float fxx = yy[row_idx];
553 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
554 // Note that it doesn't matter what xx starts with. First iteration of
555 // outer loop reads no values of xx and sets xx[0], second iteration
556 // reads xx[0] and sets xx[1], etc.
557 fxx -= cur_ll_row[col_idx] * xx[col_idx];
558 }
559 xx[row_idx] = fxx / cur_ll_row[row_idx];
560 cur_ll_row = &(cur_ll_row[predictor_ctav]);
561 }
562 }
563 for (uint32_t col_idx = predictor_ct; col_idx; ) {
564 float* xx_stop = &(xx[--col_idx]);
565 float fxx = *xx_stop;
566 const float* ll_col_iter = &(ll[(predictor_ct - 1) * predictor_ctav + col_idx]);
567 for (float* xx_iter = &(xx[predictor_ct - 1]); xx_iter != xx_stop; --xx_iter) {
568 fxx -= (*ll_col_iter) * (*xx_iter);
569 ll_col_iter -= predictor_ctav;
570 }
571 *xx_stop = fxx / (*ll_col_iter);
572 }
573 }
574
575 BoolErr LogisticRegressionF(const float* yy, const float* xx, const float* sample_offsets, uint32_t sample_ct, uint32_t predictor_ct, float* __restrict coef, uint32_t* is_unfinished_ptr, float* __restrict ll, float* __restrict pp, float* __restrict vv, float* __restrict hh, float* __restrict grad, float* __restrict dcoef) {
576 // Similar to first part of logistic.cpp fitLM(), but incorporates changes
577 // from Pascal Pons et al.'s TopCoder code.
578 //
579 // Preallocated buffers (initial contents irrelevant):
580 // vv = sample variance buffer
581 // hh = hessian matrix buffer, predictor_ct^2, rows vector-aligned
582 // grad = gradient buffer Y[] (length predictor_ct)
583 // dcoef = current coefficient change buffer (length predictor_ct)
584 //
585 // Inputs:
586 // xx = covariate (and usually genotype) matrix, covariate-major, rows are
587 // vector-aligned, trailing row elements must be zeroed out
588 // yy = case/control phenotype; trailing elements must be zeroed out
589 //
590 // Input/output:
591 // coef = starting point, overwritten with logistic regression betas.
592 //
593 // Outputs:
594 // ll = cholesky decomposition matrix, predictor_ct^2, rows vector-aligned
595 // pp = final likelihoods minus Y[] (not currently used by callers)
596 //
597 // Returns 1 on convergence failure, 0 otherwise.
598 // is_unfinished assumed to be initialized to 0, and is set to 1 if we hit
599 // the iteration limit without satisfying other convergence criteria; the
600 // main return value is 0 in this case.
601 const uintptr_t sample_ctav = RoundUpPow2(sample_ct, kFloatPerFVec);
602 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kFloatPerFVec);
603 float min_delta_coef = 1e9;
604
605 ZeroFArr(predictor_ct * predictor_ctav, ll);
606 // quasi-bugfix (9 Oct 2024)
607 // technically wasn't needed because LogisticSseF() implementation mapped nan
608 // to not-nan, but we don't want to depend on that
609 ZeroFArr(sample_ctav - sample_ct, &(pp[sample_ct]));
610 ZeroFArr(sample_ctav - sample_ct, &(vv[sample_ct]));
611 for (uint32_t iteration = 0; ; ++iteration) {
612 // P[i] = \sum_j X[i][j] * coef[j];
613 ColMajorFmatrixVectorMultiplyStrided(xx, coef, sample_ct, sample_ctav, predictor_ct, pp);
614 if (sample_offsets) {
615 AddFVec(sample_offsets, sample_ctav, pp);
616 }
617 // Possible future optimization: suppose categorical covariates are
618 // represented as categorical-covariate-major uint16_t* kk, indicating for
619 // each sample which raw covariate index is 1 (with one "fallow" covariate
620 // index at the end).
621 // Then the above expression becomes
622 // P[i] = \sum_j^{regular} X[i][j] * coef[j] +
623 // \sum_j^{cats} coef[K[i][j]]
624
625 // P[i] = 1 / (1 + exp(-P[i]));
626 LogisticSseF(sample_ct, pp);
627
628 // V[i] = P[i] * (1 - P[i]);
629 // P[i] -= Y[i];
630 ComputeVAndPMinusYF(yy, sample_ct, pp, vv);
631
632 // Possible categorical optimizations:
633 // 1. skip terms between different categories of the same covariate
634 // 2. all same-category terms within the same covariate can be handled with
635 // a single loop over the samples
636 // 3. terms involving a regular covariate and a categorical covariate can
637 // be handled with one loop over the samples; covers all categories
638 // 4. similarly, one loop over the samples is enough to update all category
639 // pairs between two categorical covariates
640 ComputeHessianF(xx, vv, sample_ct, predictor_ct, hh);
641
642 // grad = X^T P
643 // Separate categorical loop also possible here
644 MultMatrixDxnVectNF(xx, pp, sample_ct, predictor_ct, grad);
645
646 CholeskyDecompositionF(hh, predictor_ct, ll);
647
648 SolveLinearSystemF(ll, grad, predictor_ct, dcoef);
649
650 float delta_coef = 0.0;
651 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
652 const float cur_dcoef = dcoef[pred_idx];
653 delta_coef += fabsf(cur_dcoef);
654 coef[pred_idx] -= cur_dcoef;
655 }
656 if (delta_coef < min_delta_coef) {
657 min_delta_coef = delta_coef;
658 }
659 if (delta_coef != delta_coef) {
660 return 1;
661 }
662 if (iteration > 3) {
663 if (((delta_coef > S_CAST(float, 20.0)) && (delta_coef > 2 * min_delta_coef)) || ((iteration > 6) && (fabsf(S_CAST(float, 1.0) - delta_coef) < S_CAST(float, 1e-3)))) {
664 return 1;
665 }
666 if (iteration > 13) {
667 // If fabsf(any coefficient) > 8e3, this is almost certainly a form of
668 // convergence failure that didn't get caught by the
669 // (delta_coef > 20.0) check due to a precision quirk. (8e3 threshold
670 // ~= 1e-4 * 2^23, since floats have 23 bits of precision)
671 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
672 if (fabsf(coef[pred_idx]) > S_CAST(float, 8e3)) {
673 return 1;
674 }
675 }
676 *is_unfinished_ptr = 1;
677 return 0;
678 }
679 }
680 // Pons reported that 1.1e-3 was dangerous, so I agree with the decision to
681 // tighten this threshold from 1e-3 to 1e-4.
682 if (delta_coef < S_CAST(float, 1e-4)) {
683 // Be more conservative in throwing out results when we don't hit the
684 // iteration limit.
685 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
686 if (fabsf(coef[pred_idx]) > S_CAST(float, 6e4)) {
687 return 1;
688 }
689 }
690 return 0;
691 }
692 }
693 }
694
695 #ifdef __LP64__
696 void CopyAndMeanCenterF(const float* src, uintptr_t ct, float* __restrict dst) {
697 const uintptr_t fullvec_ct = ct / kFloatPerFVec;
698 const VecF* src_alias = R_CAST(const VecF*, src);
699 VecF vsum = vecf_setzero();
700 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
701 vsum += src_alias[vidx];
702 }
703 float sum = VecFHsum(vsum);
704 const uintptr_t trailing_start_idx = fullvec_ct * kFloatPerFVec;
705 for (uintptr_t ulii = trailing_start_idx; ulii != ct; ++ulii) {
706 sum += src[ulii];
707 }
708
709 const float neg_mean = -sum / S_CAST(float, ct);
710 const VecF neg_vmean = VCONST_F(neg_mean);
711 VecF* dst_alias = R_CAST(VecF*, dst);
712 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
713 dst_alias[vidx] = src_alias[vidx] + neg_vmean;
714 }
715 if (trailing_start_idx != ct) {
716 for (uintptr_t ulii = trailing_start_idx; ulii != ct; ++ulii) {
717 dst[ulii] = src[ulii] + neg_mean;
718 }
719 const uintptr_t trailing_stop_idx = trailing_start_idx + kFloatPerFVec;
720 for (uintptr_t ulii = ct; ulii != trailing_stop_idx; ++ulii) {
721 dst[ulii] = S_CAST(float, 0.0);
722 }
723 }
724 }
725 #else
726 void CopyAndMeanCenterF(const float* src, uintptr_t ct, float* __restrict dst) {
727 float sum = 0.0;
728 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
729 sum += src[ulii];
730 }
731 const float mean = sum / u31tof(ct);
732 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
733 dst[ulii] = src[ulii] - mean;
734 }
735 }
736 #endif
737
738 BoolErr LogisticRegressionResidualizedF(const float* yy, const float* xx, const uintptr_t* sample_nm, const CcResidualizeCtx* cc_residualize, uint32_t nm_sample_ct, uint32_t orig_predictor_ct, float* coef, uint32_t* is_unfinished_ptr, float* ll, float* pp, float* vv, float* hh, float* grad, float* dcoef, float* mean_centered_pmaj_buf, float* sample_offsets_buf) {
739 if (!cc_residualize->logistic_nm_sample_offsets_f) {
740 return 1;
741 }
742 const uintptr_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kFloatPerFVec);
743 const uint32_t domdev_present_p1 = cc_residualize->domdev_present_p1;
744 for (uint32_t geno_idx = 0; geno_idx != domdev_present_p1; ++geno_idx) {
745 CopyAndMeanCenterF(&(xx[(geno_idx + 1) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[geno_idx * nm_sample_ctav]));
746 }
747 const uint32_t prefitted_pred_ct = cc_residualize->prefitted_pred_ct;
748 const uint32_t orig_biallelic_predictor_ct = domdev_present_p1 + prefitted_pred_ct;
749 const uint32_t extra_allele_ct = orig_predictor_ct - orig_biallelic_predictor_ct;
750 for (uint32_t extra_allele_idx = 0; extra_allele_idx != extra_allele_ct; ++extra_allele_idx) {
751 CopyAndMeanCenterF(&(xx[(extra_allele_idx + orig_biallelic_predictor_ct) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[(extra_allele_idx + domdev_present_p1) * nm_sample_ctav]));
752 }
753 const float* sample_offsets = cc_residualize->logistic_nm_sample_offsets_f;
754 if (nm_sample_ct != cc_residualize->sample_ct) {
755 uintptr_t sample_idx_base = 0;
756 uintptr_t sample_nm_bits = sample_nm[0];
757 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
758 const uintptr_t sample_idx = BitIter1(sample_nm, &sample_idx_base, &sample_nm_bits);
759 sample_offsets_buf[uii] = sample_offsets[sample_idx];
760 }
761 // todo: check if this is actually needed
762 const uint32_t remainder = (-nm_sample_ct) & (kFloatPerFVec - 1);
763 ZeroFArr(remainder, &(sample_offsets_buf[nm_sample_ct]));
764 sample_offsets = sample_offsets_buf;
765 }
766 // genotype, domdev?, other alleles
767 const uint32_t regressed_predictor_ct = domdev_present_p1 + extra_allele_ct;
768 const uint32_t regressed_predictor_ctav = RoundUpPow2(regressed_predictor_ct, kFloatPerFVec);
769 if (LogisticRegressionF(yy, mean_centered_pmaj_buf, sample_offsets, nm_sample_ct, regressed_predictor_ct, &(coef[1]), is_unfinished_ptr, ll, pp, vv, hh, grad, dcoef)) {
770 return 1;
771 }
772 // hh and ll are shifted up and to the left from what the caller expects, due
773 // to the missing intercept. Correct that here.
774 // bugfix (4 Sep 2021): Initially thought only bottom-left triangle mattered,
775 // but that's not true for genotypic/hethom case. Also, wider stride
776 // expected when regressed_predictor_ct is an exact multiple of
777 // kFloatPerFVec.
778 const uint32_t expected_predictor_ctav = RoundUpPow2(regressed_predictor_ct + 1, kFloatPerFVec);
779 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
780 memcpy(&(hh[write_row_idx * expected_predictor_ctav + 1]), &(hh[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(float));
781 }
782 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
783 memcpy(&(ll[write_row_idx * expected_predictor_ctav + 1]), &(ll[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(float));
784 }
785 return 0;
786 }
787
788 // tmpNxK, interpreted as column-major, is sample_ct x predictor_ct
789 // X, interpreted as column-major, is also sample_ct x predictor_ct
790 // Hdiag[i] = V[i] (\sum_j tmpNxK[i][j] X[i][j])
791 void FirthComputeHdiagWeightsF(const float* yy, const float* xx, const float* pp, const float* hh, const float* vv, uint32_t predictor_ct, uint32_t predictor_ctav, uint32_t sample_ct, uint32_t sample_ctav, float* hdiag, float* ww, float* tmpnxk_buf) {
792 ColMajorFmatrixMultiplyStrided(xx, hh, sample_ct, sample_ctav, predictor_ct, predictor_ctav, predictor_ct, sample_ctav, tmpnxk_buf);
793 #ifdef __LP64__
794 const VecF half = VCONST_F(0.5);
795 for (uint32_t sample_offset = 0; sample_offset < sample_ctav; sample_offset += kFloatPerFVec) {
796 VecF dotprods = vecf_setzero();
797 const float* xx_row = &(xx[sample_offset]);
798 const float* tmpnxk_row = &(tmpnxk_buf[sample_offset]);
799 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
800 const VecF cur_xx = *R_CAST(const VecF*, &(xx_row[pred_uidx * sample_ctav]));
801 const VecF cur_tmpnxk = *R_CAST(const VecF*, &(tmpnxk_row[pred_uidx * sample_ctav]));
802 dotprods = dotprods + cur_xx * cur_tmpnxk;
803 }
804 // Can handle categorical covariates in a separate loop here, and load the
805 // dotprods increment into a union, etc.
806 const VecF cur_vv = *R_CAST(const VecF*, &(vv[sample_offset]));
807 const VecF cur_pi = *R_CAST(const VecF*, &(pp[sample_offset]));
808 const VecF cur_yy = *R_CAST(const VecF*, &(yy[sample_offset]));
809 const VecF cur_hdiag = cur_vv * dotprods;
810 *R_CAST(VecF*, &(hdiag[sample_offset])) = cur_hdiag;
811 const VecF half_minus_cur_pis = half - cur_pi;
812 const VecF yy_minus_cur_pis = cur_yy - cur_pi;
813 *R_CAST(VecF*, &(ww[sample_offset])) = yy_minus_cur_pis + cur_hdiag * half_minus_cur_pis;
814 }
815 #else
816 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
817 float dotprod = 0.0;
818 const float* xx_row = &(xx[sample_idx]);
819 const float* tmpnxk_row = &(tmpnxk_buf[sample_idx]);
820 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
821 dotprod += xx_row[pred_uidx * sample_ctav] * tmpnxk_row[pred_uidx * sample_ctav];
822 }
823 const float cur_hdiag = vv[sample_idx] * dotprod;
824 hdiag[sample_idx] = cur_hdiag;
825 const float cur_pi = pp[sample_idx];
826 ww[sample_idx] = (yy[sample_idx] - cur_pi) + cur_hdiag * (S_CAST(float, 0.5) - cur_pi);
827 }
828 #endif
829 }
830
831 void FirthComputeSecondWeightsF(const float* hdiag, const float* vv, __maybe_unused uint32_t sample_ct, __maybe_unused uint32_t sample_ctav, float* ww) {
832 #ifdef __LP64__
833 const VecF one = VCONST_F(1.0);
834 for (uint32_t sample_offset = 0; sample_offset < sample_ctav; sample_offset += kFloatPerFVec) {
835 const VecF cur_hdiag = *R_CAST(const VecF*, &(hdiag[sample_offset]));
836 const VecF cur_vv = *R_CAST(const VecF*, &(vv[sample_offset]));
837 *R_CAST(VecF*, &(ww[sample_offset])) = (one + cur_hdiag) * cur_vv;
838 }
839 #else
840 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
841 ww[sample_idx] = (S_CAST(float, 1.0) + hdiag[sample_idx]) * vv[sample_idx];
842 }
843 #endif
844 }
845
846 BoolErr FirthRegressionF(const float* yy, const float* xx, const float* sample_offsets, uint32_t sample_ct, uint32_t predictor_ct, float* beta, uint32_t* is_unfinished_ptr, float* hh, double* half_inverted_buf, MatrixInvertBuf1* inv_1d_buf, double* dbl_2d_buf, float* pp, float* vv, float* ustar, float* delta, float* hdiag, float* ww, float* hh0, float* tmpnxk_buf) {
847 // This is a port of Georg Heinze's logistf 1.24.1 R function (called with
848 // pl=FALSE), adapted to use many of plink 1.9's optimizations; see
849 // https://github.com/georgheinze/logistf
850 // (Before 30 Dec 2022, this function was based on an earlier version of
851 // logistf.)
852 //
853 // Preallocated buffers (initial contents irrelevant):
854 // half_inverted_buf, inv_1d_buf, dbl_2d_buf = for matrix inversion
855 // pp = likelihoods minus Y[] (not currently used by callers)
856 // vv = sample variance buffer
857 // ustar = gradient buffer (length predictor_ct)
858 // delta = current coefficient change buffer (length predictor_ct)
859 // hdiag = intermediate multiplier for weights (length sample_ct)
860 // ww = weight buffer (length sample_ct)
861 // hh0 = just like hh below, but not returned
862 //
863 // Inputs:
864 // xx = covariate (and usually genotype) matrix, covariate-major, rows are
865 // vector-aligned, trailing row elements must be zeroed out
866 // yy = case/control phenotype
867 // sample_offsets = in residualized mode, product of pre-fitted covariate
868 // beta vector with covariate matrix. otherwise, nullptr.
869 //
870 // Input/output:
871 // beta = starting point, overwritten with regression betas.
872 //
873 // Outputs:
874 // hh = variance-covariance matrix buffer, predictor_ct^2, rows
875 // vector-aligned. (spends some time as pre-inversion Hessian matrix
876 // too)
877 //
878 // Returns 1 on convergence failure, 0 otherwise.
879 // is_unfinished assumed to be initialized to 0, and is set to 1 if we hit
880 // the iteration limit without satisfying other convergence criteria; the
881 // main return value is 0 in this case.
882 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kFloatPerFVec);
883 const uintptr_t sample_ctav = RoundUpPow2(sample_ct, kFloatPerFVec);
884
885 // bugfix (4 Nov 2017): ustar[] trailing elements must be zeroed out
886 ZeroFArr(predictor_ctav - predictor_ct, &(ustar[predictor_ct]));
887
888 const uint32_t trailing_sample_ct = sample_ctav - sample_ct;
889 if (trailing_sample_ct) {
890 // bunch of other trailing elements must also be zeroed out
891 ZeroFArr(trailing_sample_ct, &(pp[sample_ct]));
892 ZeroFArr(trailing_sample_ct, &(vv[sample_ct]));
893 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
894 ZeroFArr(trailing_sample_ct, &(tmpnxk_buf[sample_ct + pred_idx * sample_ctav]));
895 }
896 }
897
898 // start with 80% of most logistf convergence defaults (some reduction is
899 // appropriate to be consistent with single-precision arithmetic). (Update,
900 // 9 Apr 2020: max_iter now matches logistf default since we've been shown a
901 // concrete example where it matters in a way that isn't masked by the
902 // single- vs. double-precision difference.)
903 const uint32_t max_iter = 25;
904 const float gconv = S_CAST(float, 0.0001);
905 const float xconv = S_CAST(float, 0.0001);
906 const double lconv = 0.0001;
907 float delta_max = 0.0;
908 double loglik_old = 0.0;
909 for (uint32_t iter_idx = 0; ; ++iter_idx) {
910 // P[i] = \sum_j beta[j] * X[i][j];
911 // categorical optimization possible here
912 ColMajorFmatrixVectorMultiplyStrided(xx, beta, sample_ct, sample_ctav, predictor_ct, pp);
913 if (sample_offsets) {
914 AddFVec(sample_offsets, sample_ctav, pp);
915 }
916 // P[i] = 1 / (1 + exp(-P[i]));
917 LogisticSseF(sample_ct, pp);
918 double loglik;
919 if (ComputeLoglikCheckedF(yy, pp, sample_ct, &loglik)) {
920 return 1;
921 }
922 // V[i] = P[i] * (1 - P[i]);
923 ComputeVF(pp, sample_ct, vv);
924 // P[i] -= Y[i] NOT done here
925
926 // hessian = X diag(V) X'
927 // note that only lower triangle is filled here
928 ComputeHessianF(xx, vv, sample_ct, predictor_ct, hh0);
929
930 // we shouldn't need to compute the log directly, since underflow <->
931 // regression failure, right? check this.
932 if (InvertSymmdefFmatrixFirstHalf(predictor_ct, predictor_ctav, hh0, half_inverted_buf, inv_1d_buf, dbl_2d_buf)) {
933 return 1;
934 }
935 double dethh = HalfSymmInvertedDet(half_inverted_buf, inv_1d_buf, predictor_ct, predictor_ct);
936 loglik += 0.5 * log(dethh);
937
938 InvertSymmdefFmatrixSecondHalf(predictor_ct, predictor_ctav, half_inverted_buf, hh0, inv_1d_buf, dbl_2d_buf);
939
940 // bugfix (13 Oct 2017): trailing elements of hh0[] rows can't be arbitrary
941 // for later MultMatrixDxnVectNF() call
942 ReflectFmatrix0(predictor_ct, predictor_ctav, hh0);
943
944 FirthComputeHdiagWeightsF(yy, xx, pp, hh0, vv, predictor_ct, predictor_ctav, sample_ct, sample_ctav, hdiag, ww, tmpnxk_buf);
945
946 // gradient = X' W
947 // categorical optimization possible here
948 MultMatrixDxnVectNF(xx, ww, sample_ct, predictor_ct, ustar);
949 if (iter_idx) {
950 float ustar_max = 0.0;
951 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
952 const float abs_ustar_cur = fabsf(ustar[pred_uidx]);
953 if (abs_ustar_cur > ustar_max) {
954 ustar_max = abs_ustar_cur;
955 }
956 }
957 const double loglik_change = loglik - loglik_old;
958 if ((delta_max <= xconv) && (ustar_max < gconv) && (loglik_change < lconv)) {
959 return 0;
960 }
961 if (iter_idx > max_iter) {
962 *is_unfinished_ptr = 1;
963 return 0;
964 }
965 }
966 loglik_old = loglik;
967
968 FirthComputeSecondWeightsF(hdiag, vv, sample_ct, sample_ctav, ww);
969 ComputeHessianF(xx, ww, sample_ct, predictor_ct, hh);
970 if (InvertSymmdefFmatrixFirstHalf(predictor_ct, predictor_ctav, hh, half_inverted_buf, inv_1d_buf, dbl_2d_buf)) {
971 return 1;
972 }
973 InvertSymmdefFmatrixSecondHalf(predictor_ct, predictor_ctav, half_inverted_buf, hh, inv_1d_buf, dbl_2d_buf);
974 ReflectFmatrix0(predictor_ct, predictor_ctav, hh);
975
976 // delta := hh * ustar (note that hh is inverted already)
977 MultMatrixDxnVectNF(hh, ustar, predictor_ct, predictor_ct, delta);
978
979 delta_max = 0.0;
980 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
981 const float abs_delta_cur = fabsf(delta[pred_uidx]);
982 if (abs_delta_cur > delta_max) {
983 delta_max = abs_delta_cur;
984 }
985 }
986 const float maxstep = 5.0;
987 if (delta_max > maxstep) {
988 const float scaling_factor = maxstep / delta_max;
989 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
990 delta[pred_uidx] *= scaling_factor;
991 }
992 delta_max = maxstep;
993 }
994 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
995 beta[pred_uidx] += delta[pred_uidx];
996 }
997 }
998 }
999
1000 BoolErr FirthRegressionResidualizedF(const float* yy, const float* xx, const uintptr_t* sample_nm, const CcResidualizeCtx* cc_residualize, uint32_t nm_sample_ct, uint32_t orig_predictor_ct, float* beta, uint32_t* is_unfinished_ptr, float* hh, double* half_inverted_buf, MatrixInvertBuf1* inv_1d_buf, double* dbl_2d_buf, float* pp, float* vv, float* ustar, float* delta, float* hdiag, float* ww, float* hh0_buf, float* tmpnxk_buf, float* mean_centered_pmaj_buf, float* sample_offsets_buf) {
1001 // todo: deduplicate with LogisticRegressionResidualizedF()
1002 const uintptr_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kFloatPerFVec);
1003 const uint32_t domdev_present_p1 = cc_residualize->domdev_present_p1;
1004 for (uint32_t geno_idx = 0; geno_idx != domdev_present_p1; ++geno_idx) {
1005 CopyAndMeanCenterF(&(xx[(geno_idx + 1) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[geno_idx * nm_sample_ctav]));
1006 }
1007 const uint32_t prefitted_pred_ct = cc_residualize->prefitted_pred_ct;
1008 const uint32_t orig_biallelic_predictor_ct = domdev_present_p1 + prefitted_pred_ct;
1009 const uint32_t extra_allele_ct = orig_predictor_ct - orig_biallelic_predictor_ct;
1010 for (uint32_t extra_allele_idx = 0; extra_allele_idx != extra_allele_ct; ++extra_allele_idx) {
1011 CopyAndMeanCenterF(&(xx[(extra_allele_idx + orig_biallelic_predictor_ct) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[(extra_allele_idx + domdev_present_p1) * nm_sample_ctav]));
1012 }
1013 const float* sample_offsets = cc_residualize->firth_nm_sample_offsets_f;
1014 if (nm_sample_ct != cc_residualize->sample_ct) {
1015 uintptr_t sample_idx_base = 0;
1016 uintptr_t sample_nm_bits = sample_nm[0];
1017 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
1018 const uintptr_t sample_idx = BitIter1(sample_nm, &sample_idx_base, &sample_nm_bits);
1019 sample_offsets_buf[uii] = sample_offsets[sample_idx];
1020 }
1021 const uint32_t remainder = (-nm_sample_ct) & (kFloatPerFVec - 1);
1022 ZeroFArr(remainder, &(sample_offsets_buf[nm_sample_ct]));
1023 sample_offsets = sample_offsets_buf;
1024 }
1025 const uint32_t regressed_predictor_ct = domdev_present_p1 + extra_allele_ct;
1026 const uint32_t regressed_predictor_ctav = RoundUpPow2(regressed_predictor_ct, kFloatPerFVec);
1027 if (FirthRegressionF(yy, mean_centered_pmaj_buf, sample_offsets, nm_sample_ct, regressed_predictor_ct, &(beta[1]), is_unfinished_ptr, hh, half_inverted_buf, inv_1d_buf, dbl_2d_buf, pp, vv, ustar, delta, hdiag, ww, hh0_buf, tmpnxk_buf)) {
1028 return 1;
1029 }
1030 // hh is shifted up and to the left from what the caller expects, due to the
1031 // missing intercept. Correct that here.
1032 // bugfix (4 Sep 2021): Initially thought only bottom-left triangle mattered,
1033 // but that's not true for genotypic/hethom case. Also, wider stride
1034 // expected when regressed_predictor_ct is an exact multiple of
1035 // kFloatPerFVec.
1036 const uint32_t expected_predictor_ctav = RoundUpPow2(regressed_predictor_ct + 1, kFloatPerFVec);
1037 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
1038 memcpy(&(hh[write_row_idx * expected_predictor_ctav + 1]), &(hh[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(float));
1039 }
1040 return 0;
1041 }
1042
1043 uintptr_t GetLogisticWorkspaceSizeF(uint32_t sample_ct, uint32_t biallelic_predictor_ct, uint32_t domdev_present_p1, uint32_t max_extra_allele_ct, uint32_t constraint_ct, uint32_t xmain_ct, uint32_t gcount_cc, uint32_t is_sometimes_firth, uint32_t is_cc_residualize) {
1044 // sample_ctav * max_predictor_ct < 2^31, and sample_ct >=
1045 // biallelic_predictor_ct, so no overflows?
1046 // could round everything up to multiples of 16 instead of 64
1047 const uint32_t max_predictor_ct = biallelic_predictor_ct + max_extra_allele_ct;
1048 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kFloatPerFVec);
1049 const uint32_t max_predictor_ctav = RoundUpPow2(max_predictor_ct, kFloatPerFVec);
1050 // sample_nm, pheno_cc_nm, tmp_nm = sample_ctl words
1051 uintptr_t workspace_size = 3 * RoundUpPow2(BitCtToWordCt(sample_ct) * sizeof(intptr_t), kCacheline);
1052
1053 // yy = sample_ctav floats
1054 workspace_size += RoundUpPow2(sample_ctav * sizeof(float), kCacheline);
1055
1056 // xx = (max_predictor_ct + main_mutated + main_omitted) * sample_ctav floats
1057 workspace_size += RoundUpPow2((max_predictor_ct + xmain_ct) * sample_ctav * sizeof(float), kCacheline);
1058
1059 // hh = max_predictor_ct * max_predictor_ctav floats
1060 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(float), kCacheline);
1061
1062 // pp, vv = sample_ctav floats
1063 workspace_size += 2 * RoundUpPow2(sample_ctav * sizeof(float), kCacheline);
1064
1065 // coef, grad, dcoef = max_predictor_ctav floats
1066 workspace_size += 3 * RoundUpPow2(max_predictor_ctav * sizeof(float), kCacheline);
1067
1068 // ll = max_predictor_ct * max_predictor_ctav floats
1069 // (technically not needed in pure-Firth case)
1070 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(float), kCacheline);
1071
1072 // semicomputed_biallelic_xtx
1073 workspace_size += RoundUpPow2(biallelic_predictor_ct * biallelic_predictor_ct * sizeof(double), kCacheline);
1074
1075 // semicomputed_biallelic_corr_matrix
1076 workspace_size += RoundUpPow2((biallelic_predictor_ct - 1) * (biallelic_predictor_ct - 1) * sizeof(double), kCacheline);
1077
1078 // semicomputed_biallelic_inv_corr_sqrts
1079 workspace_size += RoundUpPow2(biallelic_predictor_ct * sizeof(double), kCacheline);
1080
1081 // inv_1d_buf
1082 workspace_size += RoundUpPow2(max_predictor_ct * kMatrixInvertBuf1CheckedAlloc, kCacheline);
1083
1084 // dbl_2d_buf = max_predictor_ct * max_predictor_ct floats, or VIF/Firth
1085 // (which can be max_predictor_ct * 7 floats).
1086 workspace_size += RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
1087
1088 // a1_dosages, a1_case_dosages
1089 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(double) * 2, kCacheline);
1090
1091 // machr2_dosage_sums, machr2_dosage_ssqs
1092 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(uint64_t) * 2, kCacheline);
1093
1094 if (gcount_cc && max_extra_allele_ct) {
1095 // case_one_cts, case_two_cts
1096 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(int32_t) * 2, kCacheline);
1097 }
1098
1099 // predictor_dotprod_buf
1100 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ct * sizeof(float), kCacheline);
1101
1102 const uintptr_t other_2d_byte_ct = max_predictor_ct * MAXV(max_predictor_ct, 3) * sizeof(double);
1103 // inverse_corr_buf/half_inverted_buf
1104 workspace_size += RoundUpPow2(other_2d_byte_ct, kCacheline);
1105
1106 if (is_sometimes_firth) {
1107 // hdiag, ww = sample_ctav floats
1108 workspace_size += 2 * RoundUpPow2(sample_ctav * sizeof(float), kCacheline);
1109
1110 // hh0 = max_predictor_ct * max_predictor_ctav floats
1111 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(float), kCacheline);
1112
1113 // tmpnxk_buf = max_predictor_ct * sample_ctav floats
1114 workspace_size += RoundUpPow2(max_predictor_ct * sample_ctav * sizeof(float), kCacheline);
1115 }
1116 if (is_cc_residualize) {
1117 // mean_centered_pmaj_buf = (domdev_present_p1 + max_extra_allele_ct) *
1118 // sample_ctav floats
1119 workspace_size += RoundUpPow2((domdev_present_p1 + max_extra_allele_ct) * sample_ctav * sizeof(float), kCacheline);
1120
1121 // sample_offsets_buf
1122 workspace_size += RoundUpPow2(sample_ctav * sizeof(float), kCacheline);
1123 }
1124 if (constraint_ct) {
1125 // tmphxs_buf, h_transpose_buf = constraint_ct * max_predictor_ctav floats
1126 workspace_size += 2 * RoundUpPow2(constraint_ct * max_predictor_ctav * sizeof(float), kCacheline);
1127
1128 // inner_buf = constraint_ct * constraint_ct
1129 workspace_size += RoundUpPow2(constraint_ct * constraint_ct * sizeof(float), kCacheline);
1130
1131 // outer_buf = constraint_ct
1132 workspace_size += RoundUpPow2(constraint_ct * sizeof(float), kCacheline);
1133
1134 // constraints_con_major = constraint_ct * max_predictor_ct
1135 workspace_size += RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(float), kCacheline);
1136 }
1137 return workspace_size;
1138 }
1139
1140 static const float kSmallFloats[4] = {0.0, 1.0, 2.0, 3.0};
1141
1142 THREAD_FUNC_DECL GlmLogisticThreadF(void* raw_arg) {
1143 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
1144 const uintptr_t tidx = arg->tidx;
1145 GlmLogisticCtx* ctx = S_CAST(GlmLogisticCtx*, arg->sharedp->context);
1146 GlmCtx* common = ctx->common;
1147
1148 PgenReader* pgrp = common->pgr_ptrs[tidx];
1149 PgenVariant pgv;
1150 pgv.genovec = common->genovecs[tidx];
1151 pgv.dosage_present = nullptr;
1152 pgv.dosage_main = nullptr;
1153 if (common->dosage_presents) {
1154 pgv.dosage_present = common->dosage_presents[tidx];
1155 pgv.dosage_main = common->dosage_mains[tidx];
1156 }
1157 unsigned char* workspace_buf = common->workspace_bufs[tidx];
1158 const uintptr_t* variant_include = common->variant_include;
1159 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
1160 const AlleleCode* omitted_alleles = common->omitted_alleles;
1161 const uintptr_t* sex_male_collapsed = common->sex_male_collapsed;
1162 const ChrInfo* cip = common->cip;
1163 const uint32_t* subset_chr_fo_vidx_start = common->subset_chr_fo_vidx_start;
1164 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
1165 const GlmFlags glm_flags = common->glm_flags;
1166 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
1167 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
1168 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
1169 const uint32_t is_sometimes_firth = !(glm_flags & kfGlmNoFirth);
1170 const uint32_t is_always_firth = (glm_flags / kfGlmFirth) & 1;
1171 const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
1172 const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
1173 const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
1174 const uint32_t joint_genotypic = (glm_flags / kfGlmGenotypic) & 1;
1175 const uint32_t joint_hethom = (glm_flags / kfGlmHethom) & 1;
1176 const double max_corr = common->max_corr;
1177 const double vif_thresh = common->vif_thresh;
1178 const uint32_t domdev_present = joint_genotypic || joint_hethom;
1179 const uint32_t domdev_present_p1 = domdev_present + 1;
1180 const uint32_t reported_pred_uidx_start = 1 - include_intercept;
1181 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
1182 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
1183 const uint32_t is_xchr_model_1 = common->is_xchr_model_1;
1184 const uintptr_t max_reported_test_ct = common->max_reported_test_ct;
1185 const uintptr_t local_covar_ct = common->local_covar_ct;
1186 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
1187 // bugfix (20 Mar 2020): Also need to exclude dominant/recessive.
1188 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!model_dominant) && (!model_recessive) && (!model_hetonly) && (!common->tests_flag) && (!add_interactions);
1189 uintptr_t max_sample_ct = MAXV(common->sample_ct, common->sample_ct_x);
1190 if (max_sample_ct < common->sample_ct_y) {
1191 max_sample_ct = common->sample_ct_y;
1192 }
1193 SetPgvThreadMhcNull(max_sample_ct, tidx, common->thread_mhc, &pgv);
1194 pgv.patch_01_ct = 0;
1195 pgv.patch_10_ct = 0;
1196 pgv.multidosage_sample_ct = 0;
1197 uint32_t variant_idx_offset = 0;
1198 uint32_t allele_ct = 2;
1199 uint32_t omitted_allele_idx = 0;
1200 uint32_t extra_regression_ct = 0;
1201 double main_dosage_sum = 0.0;
1202 double main_dosage_ssq = 0.0;
1203 uint32_t parity = 0;
1204 uint64_t new_err_info = 0;
1205 do {
1206 const uintptr_t cur_block_variant_ct = common->cur_block_variant_ct;
1207 uint32_t variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct;
1208 const uint32_t variant_bidx_end = ((tidx + 1) * cur_block_variant_ct) / calc_thread_ct;
1209 uintptr_t variant_uidx_base;
1210 uintptr_t variant_include_bits;
1211 BitIter1Start(variant_include, common->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
1212
1213 double* beta_se_iter = common->block_beta_se;
1214 uintptr_t allele_bidx = variant_bidx;
1215 if (max_extra_allele_ct) {
1216 allele_bidx = variant_bidx + CountExtraAlleles(variant_include, allele_idx_offsets, common->read_variant_uidx_starts[0], common->read_variant_uidx_starts[tidx], 0);
1217 }
1218 if (beta_se_multiallelic_fused) {
1219 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * variant_bidx]);
1220 } else {
1221 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * allele_bidx]);
1222 }
1223
1224 LogisticAuxResult* block_aux_iter = &(ctx->block_aux[allele_bidx]);
1225 const float* local_covars_iter = nullptr;
1226 if (local_covar_ct) {
1227 // &(nullptr[0]) is okay in C++, but undefined in C
1228 local_covars_iter = &(ctx->local_covars_vcmaj_f[parity][variant_bidx * max_sample_ct * local_covar_ct]);
1229 }
1230 while (variant_bidx < variant_bidx_end) {
1231 const uint32_t variant_idx = variant_bidx + variant_idx_offset;
1232 const uint32_t chr_fo_idx = LastLeqU32(subset_chr_fo_vidx_start, 0, cip->chr_ct, variant_idx);
1233 // const uint32_t chr_fo_idx = LowerBoundNonemptyU32(&(subset_chr_fo_vidx_start[1]), cip->chr_ct, variant_idx + 1);
1234 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
1235 uint32_t cur_variant_bidx_end = subset_chr_fo_vidx_start[chr_fo_idx + 1] - variant_idx_offset;
1236 if (cur_variant_bidx_end > variant_bidx_end) {
1237 cur_variant_bidx_end = variant_bidx_end;
1238 }
1239 // "regular" = not all-female special case.
1240 const uint32_t is_haploid = IsSet(cip->haploid_mask, chr_idx);
1241 const uint32_t is_regular_x = is_haploid && (chr_idx == x_code);
1242 const uint32_t is_y = (chr_idx == y_code);
1243 const uint32_t is_nonx_haploid = is_haploid && (!is_regular_x);
1244 const uintptr_t* cur_sample_include;
1245 const uint32_t* cur_sample_include_cumulative_popcounts;
1246 const uintptr_t* cur_pheno_cc;
1247 const uintptr_t* cur_gcount_case_interleaved_vec;
1248 const float* cur_pheno;
1249 const RegressionNmPrecomp* nm_precomp;
1250 const float* cur_covars_cmaj;
1251 const uintptr_t* cur_parameter_subset;
1252 const uintptr_t* cur_joint_test_params;
1253 const CcResidualizeCtx* cur_cc_residualize;
1254 uint32_t cur_sample_ct;
1255 uint32_t cur_covar_ct;
1256 uint32_t cur_constraint_ct;
1257 uint32_t cur_is_always_firth;
1258 if (is_y && common->sample_include_y) {
1259 cur_sample_include = common->sample_include_y;
1260 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
1261 cur_pheno_cc = ctx->pheno_y_cc;
1262 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec_y;
1263 cur_pheno = ctx->pheno_y_f;
1264 nm_precomp = common->nm_precomp_y;
1265 cur_covars_cmaj = ctx->covars_cmaj_y_f;
1266 cur_parameter_subset = common->parameter_subset_y;
1267 cur_joint_test_params = common->joint_test_params_y;
1268 cur_cc_residualize = ctx->cc_residualize_y;
1269 cur_sample_ct = common->sample_ct_y;
1270 cur_covar_ct = common->covar_ct_y;
1271 cur_constraint_ct = common->constraint_ct_y;
1272 cur_is_always_firth = is_always_firth || ctx->separation_found_y;
1273 } else if (is_regular_x && common->sample_include_x) {
1274 cur_sample_include = common->sample_include_x;
1275 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
1276 cur_pheno_cc = ctx->pheno_x_cc;
1277 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec_x;
1278 cur_pheno = ctx->pheno_x_f;
1279 nm_precomp = common->nm_precomp_x;
1280 cur_covars_cmaj = ctx->covars_cmaj_x_f;
1281 cur_parameter_subset = common->parameter_subset_x;
1282 cur_joint_test_params = common->joint_test_params_x;
1283 cur_cc_residualize = ctx->cc_residualize_x;
1284 cur_sample_ct = common->sample_ct_x;
1285 cur_covar_ct = common->covar_ct_x;
1286 cur_constraint_ct = common->constraint_ct_x;
1287 cur_is_always_firth = is_always_firth || ctx->separation_found_x;
1288 } else {
1289 cur_sample_include = common->sample_include;
1290 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
1291 cur_pheno_cc = ctx->pheno_cc;
1292 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec;
1293 cur_pheno = ctx->pheno_f;
1294 nm_precomp = common->nm_precomp;
1295 cur_covars_cmaj = ctx->covars_cmaj_f;
1296 cur_parameter_subset = common->parameter_subset;
1297 cur_joint_test_params = common->joint_test_params;
1298 cur_cc_residualize = ctx->cc_residualize;
1299 cur_sample_ct = common->sample_ct;
1300 cur_covar_ct = common->covar_ct;
1301 cur_constraint_ct = common->constraint_ct;
1302 cur_is_always_firth = is_always_firth || ctx->separation_found;
1303 }
1304 const uint32_t sample_ctl = BitCtToWordCt(cur_sample_ct);
1305 const uint32_t sample_ctav = RoundUpPow2(cur_sample_ct, kFloatPerFVec);
1306 const uint32_t cur_case_ct = PopcountWords(cur_pheno_cc, sample_ctl);
1307 const uint32_t cur_biallelic_predictor_ct_base = 2 + domdev_present + cur_covar_ct * (1 + add_interactions * domdev_present_p1);
1308 uint32_t cur_biallelic_predictor_ct = cur_biallelic_predictor_ct_base;
1309 uint32_t literal_covar_ct = cur_covar_ct;
1310 if (cur_parameter_subset) {
1311 cur_biallelic_predictor_ct = PopcountWords(cur_parameter_subset, BitCtToWordCt(cur_biallelic_predictor_ct_base));
1312 literal_covar_ct = PopcountBitRange(cur_parameter_subset, 2 + domdev_present, 2 + domdev_present + cur_covar_ct);
1313 }
1314 const uint32_t max_predictor_ct = cur_biallelic_predictor_ct + max_extra_allele_ct;
1315 const uint32_t max_predictor_ctav = RoundUpPow2(max_predictor_ct, kFloatPerFVec);
1316 uint32_t reported_pred_uidx_biallelic_end;
1317 if (hide_covar) {
1318 if (!cur_parameter_subset) {
1319 reported_pred_uidx_biallelic_end = 2 + domdev_present;
1320 } else {
1321 reported_pred_uidx_biallelic_end = 1 + IsSet(cur_parameter_subset, 1) + domdev_present;
1322 }
1323 } else {
1324 reported_pred_uidx_biallelic_end = cur_biallelic_predictor_ct;
1325 }
1326 // nm_predictors_pmaj_buf may require up to two extra columns omitted
1327 // from the main regression.
1328 // 1. In the multiallelic dominant/recessive/hetonly/hethom cases, the
1329 // original genotype column does not appear in the regression, and
1330 // we'd rather not reconstruct it from genovec, etc. when we need to
1331 // swap it out for another allele, so we keep the original genotype in
1332 // an extra column.
1333 // To reduce code bloat, we now handle the biallelic cases in the same
1334 // way; this is one of the more peripheral code paths so adding more
1335 // complexity to speed it up is less justifiable.
1336 // 2. If --parameters excludes the main (possibly
1337 // dominant/recessive/hetonly) genotype column but does care about an
1338 // interaction, we want a copy of what the main genotype column's
1339 // contents would have been to refer to.
1340 const uint32_t main_omitted = cur_parameter_subset && (!IsSet(cur_parameter_subset, 1));
1341 const uint32_t main_mutated = model_dominant || model_recessive || model_hetonly || joint_hethom;
1342 unsigned char* workspace_iter = workspace_buf;
1343 uintptr_t* sample_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
1344 uintptr_t* pheno_cc_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
1345 uintptr_t* tmp_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
1346 float* nm_pheno_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1347 float* nm_predictors_pmaj_buf = S_CAST(float*, arena_alloc_raw_rd((max_predictor_ct + main_mutated + main_omitted) * sample_ctav * sizeof(float), &workspace_iter));
1348 float* coef_return = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(float), &workspace_iter));
1349 float* hh_return = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(float), &workspace_iter));
1350 float* pp_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1351 float* sample_variance_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1352 float* gradient_buf = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(float), &workspace_iter));
1353 float* dcoef_buf = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(float), &workspace_iter));
1354 float* cholesky_decomp_return = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(float), &workspace_iter));
1355
1356 double* semicomputed_biallelic_xtx = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
1357 // currently overallocates
1358 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));
1359 double* semicomputed_biallelic_inv_corr_sqrts = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
1360
1361 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, arena_alloc_raw_rd(max_predictor_ct * kMatrixInvertBuf1CheckedAlloc, &workspace_iter));
1362 const uintptr_t dbl_2d_byte_ct = RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
1363 double* dbl_2d_buf = S_CAST(double*, arena_alloc_raw(dbl_2d_byte_ct, &workspace_iter));
1364 double* a1_dosages = S_CAST(double*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(double) * 2, &workspace_iter));
1365 double* a1_case_dosages = &(a1_dosages[max_extra_allele_ct + 2]);
1366 uint64_t* machr2_dosage_sums = S_CAST(uint64_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(uint64_t) * 2, &workspace_iter));
1367 uint64_t* machr2_dosage_ssqs = &(machr2_dosage_sums[max_extra_allele_ct + 2]);
1368 uint32_t* case_one_cts = nullptr;
1369 uint32_t* case_two_cts = nullptr;
1370 if (cur_gcount_case_interleaved_vec && max_extra_allele_ct) {
1371 case_one_cts = S_CAST(uint32_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(int32_t) * 2, &workspace_iter));
1372 case_two_cts = &(case_one_cts[max_extra_allele_ct + 2]);
1373 }
1374 float* predictor_dotprod_buf = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ct * sizeof(float), &workspace_iter));
1375 const uintptr_t other_2d_byte_ct = RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 3) * sizeof(double), kCacheline);
1376 double* inverse_corr_buf = S_CAST(double*, arena_alloc_raw(other_2d_byte_ct, &workspace_iter));
1377
1378 // these could use the same memory, but not a big deal, use the less
1379 // bug-prone approach for now
1380 // Firth-only
1381 float* hdiag_buf = nullptr;
1382 float* score_buf = nullptr;
1383 float* hh0_buf = nullptr;
1384 float* tmpnxk_buf = nullptr;
1385 if (is_sometimes_firth) {
1386 hdiag_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1387 score_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1388 hh0_buf = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(float), &workspace_iter));
1389 tmpnxk_buf = S_CAST(float*, arena_alloc_raw_rd(max_predictor_ct * sample_ctav * sizeof(float), &workspace_iter));
1390 }
1391 float* mean_centered_pmaj_buf = nullptr;
1392 float* sample_offsets_buf = nullptr;
1393 if (cur_cc_residualize) {
1394 mean_centered_pmaj_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float) * (domdev_present_p1 + max_extra_allele_ct), &workspace_iter));
1395 sample_offsets_buf = S_CAST(float*, arena_alloc_raw_rd(sample_ctav * sizeof(float), &workspace_iter));
1396 }
1397
1398 // joint test only
1399 float* tmphxs_buf = nullptr;
1400 float* h_transpose_buf = nullptr;
1401 float* inner_buf = nullptr;
1402 float* outer_buf = nullptr;
1403 float* cur_constraints_con_major = nullptr;
1404 if (cur_constraint_ct) {
1405 tmphxs_buf = S_CAST(float*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ctav * sizeof(float), &workspace_iter));
1406 h_transpose_buf = S_CAST(float*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ctav * sizeof(float), &workspace_iter));
1407 inner_buf = S_CAST(float*, arena_alloc_raw_rd(cur_constraint_ct * cur_constraint_ct * sizeof(float), &workspace_iter));
1408 outer_buf = S_CAST(float*, arena_alloc_raw_rd(cur_constraint_ct * sizeof(float), &workspace_iter));
1409 // bugfix (27 Jan 2019): forgot sizeof(float) here
1410 cur_constraints_con_major = S_CAST(float*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(float), &workspace_iter));
1411 ZeroFArr(cur_constraint_ct * max_predictor_ct, cur_constraints_con_major);
1412 const uint32_t first_joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
1413 cur_constraints_con_major[first_joint_test_idx] = 1.0;
1414 // Rest of this matrix must be updated later, since cur_predictor_ct
1415 // changes at multiallelic variants.
1416 }
1417 assert(S_CAST(uintptr_t, workspace_iter - workspace_buf) == GetLogisticWorkspaceSizeF(cur_sample_ct, cur_biallelic_predictor_ct, domdev_present_p1, max_extra_allele_ct, cur_constraint_ct, main_mutated + main_omitted, cur_gcount_case_interleaved_vec != nullptr, is_sometimes_firth, cur_cc_residualize != nullptr));
1418 const double cur_sample_ct_recip = 1.0 / u31tod(cur_sample_ct);
1419 const double cur_sample_ct_m1_recip = 1.0 / u31tod(cur_sample_ct - 1);
1420 const double* corr_inv = nullptr;
1421 if (nm_precomp) {
1422 memcpy(semicomputed_biallelic_xtx, nm_precomp->xtx_image, cur_biallelic_predictor_ct * cur_biallelic_predictor_ct * sizeof(double));
1423 corr_inv = nm_precomp->corr_inv;
1424 const uintptr_t nongeno_pred_ct = cur_biallelic_predictor_ct - domdev_present - 2;
1425 const uintptr_t nonintercept_biallelic_pred_ct = cur_biallelic_predictor_ct - 1;
1426 memcpy(semicomputed_biallelic_corr_matrix, nm_precomp->corr_image, nonintercept_biallelic_pred_ct * nonintercept_biallelic_pred_ct * sizeof(double));
1427 memcpy(&(semicomputed_biallelic_inv_corr_sqrts[domdev_present_p1]), nm_precomp->corr_inv_sqrts, nongeno_pred_ct * sizeof(double));
1428 }
1429 PgrSampleSubsetIndex pssi;
1430 PgrSetSampleSubsetIndex(cur_sample_include_cumulative_popcounts, pgrp, &pssi);
1431 // when this is set, the last fully-processed variant had no missing
1432 // genotypes, and if the current variant also has no missing genotypes we
1433 // may be able to skip reinitialization of most of
1434 // nm_predictors_pmaj_buf.
1435 // (todo: do we want to track prev_biallelic_nm?)
1436 uint32_t prev_nm = 0;
1437
1438 STD_ARRAY_DECL(uint32_t, 4, genocounts);
1439 for (; variant_bidx != cur_variant_bidx_end; ++variant_bidx) {
1440 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
1441 if (allele_idx_offsets) {
1442 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
1443 if (!beta_se_multiallelic_fused) {
1444 extra_regression_ct = allele_ct - 2;
1445 }
1446 }
1447 const uint32_t allele_ct_m2 = allele_ct - 2;
1448 const uint32_t expected_predictor_ct = cur_biallelic_predictor_ct + allele_ct_m2;
1449 PglErr reterr;
1450 if (!allele_ct_m2) {
1451 reterr = PgrGetD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
1452 } else {
1453 reterr = PgrGetMD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, &pgv);
1454 // todo: proper multiallelic dosage support
1455 }
1456 if (unlikely(reterr)) {
1457 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
1458 goto GlmLogisticThreadF_err;
1459 }
1460 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
1461 GenoarrCountFreqsUnsafe(pgv.genovec, cur_sample_ct, genocounts);
1462 uint32_t missing_ct = genocounts[3];
1463 if (!missing_ct) {
1464 SetAllBits(cur_sample_ct, sample_nm);
1465 } else {
1466 GenoarrToNonmissing(pgv.genovec, cur_sample_ct, sample_nm);
1467 if (pgv.dosage_ct) {
1468 BitvecOr(pgv.dosage_present, sample_ctl, sample_nm);
1469 missing_ct = cur_sample_ct - PopcountWords(sample_nm, sample_ctl);
1470 }
1471 }
1472 if (omitted_alleles) {
1473 omitted_allele_idx = omitted_alleles[variant_uidx];
1474 }
1475 // Once sizeof(AlleleCode) > 1, we probably want to allocate this from
1476 // g_bigstack instead of the thread stack.
1477 uintptr_t const_alleles[DivUp(kPglMaxAlleleCt, kBitsPerWord)];
1478 const uint32_t allele_ctl = DivUp(allele_ct, kBitsPerWord);
1479 ZeroWArr(allele_ctl, const_alleles);
1480 const uint32_t nm_sample_ct = cur_sample_ct - missing_ct;
1481 const uint32_t nm_sample_ctl = BitCtToWordCt(nm_sample_ct);
1482 const uint32_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kFloatPerFVec);
1483 const uint32_t nm_sample_ct_rem = nm_sample_ctav - nm_sample_ct;
1484 // first predictor column: intercept
1485 if (!prev_nm) {
1486 FillFVec(nm_sample_ct, S_CAST(float, 1.0), nm_predictors_pmaj_buf);
1487 }
1488 // second predictor column: genotype
1489 float* genotype_vals = &(nm_predictors_pmaj_buf[nm_sample_ctav]);
1490 if (main_mutated || main_omitted) {
1491 // bugfix (9 Oct 2024)
1492 ZeroFArr(nm_sample_ct_rem, &(genotype_vals[nm_sample_ct]));
1493 genotype_vals = &(nm_predictors_pmaj_buf[expected_predictor_ct * nm_sample_ctav]);
1494 }
1495 CopyBitarrSubset(cur_pheno_cc, sample_nm, nm_sample_ct, pheno_cc_nm);
1496 const uint32_t nm_case_ct = PopcountWords(pheno_cc_nm, nm_sample_ctl);
1497 float* multi_start = nullptr;
1498 if (!allele_ct_m2) {
1499 if (omitted_allele_idx) {
1500 GenovecInvertUnsafe(cur_sample_ct, pgv.genovec);
1501 // ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
1502 if (pgv.dosage_ct) {
1503 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
1504 }
1505 const uint32_t uii = genocounts[0];
1506 genocounts[0] = genocounts[2];
1507 genocounts[2] = uii;
1508 }
1509 uint64_t dosage_sum = (genocounts[1] + 2 * genocounts[2]) * 0x4000LLU;
1510 uint64_t dosage_ssq = (genocounts[1] + 4LLU * genocounts[2]) * 0x10000000LLU;
1511 if (!missing_ct) {
1512 GenoarrLookup16x4bx2(pgv.genovec, kSmallFloatPairs, nm_sample_ct, genotype_vals);
1513 if (pgv.dosage_ct) {
1514 uintptr_t sample_idx_base = 0;
1515 uintptr_t dosage_present_bits = pgv.dosage_present[0];
1516 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
1517 const uintptr_t sample_idx = BitIter1(pgv.dosage_present, &sample_idx_base, &dosage_present_bits);
1518 const uint32_t dosage_val = pgv.dosage_main[dosage_idx];
1519 // 32768 -> 2, 16384 -> 1, 0 -> 0
1520 genotype_vals[sample_idx] = kRecipDosageMidf * u31tof(dosage_val);
1521 dosage_sum += dosage_val;
1522 dosage_ssq += dosage_val * dosage_val;
1523 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_idx);
1524 if (cur_geno && (cur_geno != 3)) {
1525 const uintptr_t prev_val = cur_geno * kDosageMid;
1526 dosage_sum -= prev_val;
1527 dosage_ssq -= prev_val * prev_val;
1528 }
1529 }
1530 }
1531 } else {
1532 if (!pgv.dosage_ct) {
1533 GenoarrToFloatsRemoveMissing(pgv.genovec, kSmallFloats, cur_sample_ct, genotype_vals);
1534 } else {
1535 uintptr_t sample_midx_base = 0;
1536 uintptr_t sample_nm_bits = sample_nm[0];
1537 uint32_t dosage_idx = 0;
1538 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1539 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1540 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_midx);
1541 float cur_val;
1542 if (IsSet(pgv.dosage_present, sample_midx)) {
1543 const uint32_t dosage_val = pgv.dosage_main[dosage_idx++];
1544 cur_val = kRecipDosageMidf * u31tof(dosage_val);
1545 dosage_sum += dosage_val;
1546 dosage_ssq += dosage_val * dosage_val;
1547 if (cur_geno && (cur_geno != 3)) {
1548 const uintptr_t prev_val = cur_geno * kDosageMid;
1549 dosage_sum -= prev_val;
1550 dosage_ssq -= prev_val * prev_val;
1551 }
1552 } else {
1553 // cur_geno != 3 guaranteed
1554 cur_val = kSmallFloats[cur_geno];
1555 }
1556 genotype_vals[sample_idx] = cur_val;
1557 }
1558 }
1559 }
1560 // Check for constant genotype column.
1561 // (Technically, we should recheck later in the chrX no-sex-covariate
1562 // --xchr-model 1 corner case.)
1563 if (!pgv.dosage_ct) {
1564 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
1565 // bugfix (28 Mar 2020): didn't set the bit that actually
1566 // mattered last week...
1567 const_alleles[0] = 3;
1568 }
1569 } else if (pgv.dosage_ct == nm_sample_ct) {
1570 if (DosageIsConstant(dosage_sum, dosage_ssq, nm_sample_ct)) {
1571 const_alleles[0] = 3;
1572 }
1573 }
1574 machr2_dosage_sums[1 - omitted_allele_idx] = dosage_sum;
1575 machr2_dosage_ssqs[1 - omitted_allele_idx] = dosage_ssq;
1576 machr2_dosage_sums[omitted_allele_idx] = kDosageMax * S_CAST(uint64_t, nm_sample_ct) - dosage_sum;
1577 machr2_dosage_ssqs[omitted_allele_idx] = kDosageMax * (kDosageMax * S_CAST(uint64_t, nm_sample_ct) - 2 * dosage_sum) + dosage_ssq;
1578 if (cur_gcount_case_interleaved_vec) {
1579 // gcountcc
1580 STD_ARRAY_REF(uint32_t, 6) cur_geno_hardcall_cts = block_aux_iter->geno_hardcall_cts;
1581 GenoarrCountSubsetFreqs(pgv.genovec, cur_gcount_case_interleaved_vec, cur_sample_ct, cur_case_ct, R_CAST(STD_ARRAY_REF(uint32_t, 4), cur_geno_hardcall_cts));
1582 for (uint32_t geno_hardcall_idx = 0; geno_hardcall_idx != 3; ++geno_hardcall_idx) {
1583 cur_geno_hardcall_cts[3 + geno_hardcall_idx] = genocounts[geno_hardcall_idx] - cur_geno_hardcall_cts[geno_hardcall_idx];
1584 }
1585 }
1586 } else {
1587 // multiallelic.
1588 // Update (18 Mar 2020): If some but not all alleles have constant
1589 // dosages, we remove just those alleles from the regressions;
1590 // trim-alts is not necessary to see what's going on with the other
1591 // alleles. To reduce parsing complexity, the number of output lines
1592 // is not affected by this; the ones corresponding to the constant
1593 // alleles have NA values.
1594
1595 // dosage_ct == 0 temporarily guaranteed if we reach here.
1596 assert(!pgv.dosage_ct);
1597 multi_start = &(nm_predictors_pmaj_buf[(expected_predictor_ct - allele_ct_m2) * nm_sample_ctav]);
1598 ZeroU64Arr(allele_ct, machr2_dosage_sums);
1599 ZeroU64Arr(allele_ct, machr2_dosage_ssqs);
1600 // postpone multiply for now, since no multiallelic dosages
1601 // Use sums as ones[] and ssqs as twos[] for rarealts; transform to
1602 // actual sums/ssqs later.
1603 machr2_dosage_sums[0] = genocounts[1];
1604 machr2_dosage_ssqs[0] = genocounts[0];
1605 if (omitted_allele_idx) {
1606 // Main genotype column starts as REF.
1607 if (!missing_ct) {
1608 GenoarrLookup16x4bx2(pgv.genovec, kSmallInvFloatPairs, nm_sample_ct, genotype_vals);
1609 } else {
1610 GenoarrToFloatsRemoveMissing(pgv.genovec, kSmallInvFloats, cur_sample_ct, genotype_vals);
1611 }
1612 }
1613 uint32_t rare_allele_ct = allele_ct_m2;
1614 float* alt1_start = nullptr;
1615 float* rarealt_start = multi_start;
1616 if (omitted_allele_idx != 1) {
1617 if (omitted_allele_idx) {
1618 alt1_start = multi_start;
1619 ZeroFArr(nm_sample_ct_rem, &(alt1_start[nm_sample_ct]));
1620 rarealt_start = &(rarealt_start[nm_sample_ctav]);
1621 --rare_allele_ct;
1622 } else {
1623 alt1_start = genotype_vals;
1624 }
1625 if (!missing_ct) {
1626 GenoarrLookup16x4bx2(pgv.genovec, kSmallFloatPairs, nm_sample_ct, alt1_start);
1627 } else {
1628 GenoarrToFloatsRemoveMissing(pgv.genovec, kSmallFloats, cur_sample_ct, alt1_start);
1629 }
1630 }
1631 ZeroFArr(rare_allele_ct * nm_sample_ctav, rarealt_start);
1632 if (pgv.patch_01_ct) {
1633 const uintptr_t* patch_set_nm = pgv.patch_01_set;
1634 if (missing_ct) {
1635 CopyBitarrSubset(pgv.patch_01_set, sample_nm, nm_sample_ct, tmp_nm);
1636 patch_set_nm = tmp_nm;
1637 }
1638 uintptr_t sample_idx_base = 0;
1639 uintptr_t cur_bits = patch_set_nm[0];
1640 if (!omitted_allele_idx) {
1641 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
1642 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1643 const uint32_t allele_code = pgv.patch_01_vals[uii];
1644 rarealt_start[(allele_code - 2) * nm_sample_ctav + sample_idx] = 1.0;
1645 alt1_start[sample_idx] = 0.0;
1646 machr2_dosage_sums[allele_code] += 1;
1647 }
1648 } else if (omitted_allele_idx == 1) {
1649 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
1650 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1651 const uint32_t allele_code = pgv.patch_01_vals[uii];
1652 rarealt_start[(allele_code - 2) * nm_sample_ctav + sample_idx] = 1.0;
1653 machr2_dosage_sums[allele_code] += 1;
1654 }
1655 } else {
1656 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
1657 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1658 alt1_start[sample_idx] = 0.0;
1659 const uint32_t allele_code = pgv.patch_01_vals[uii];
1660 machr2_dosage_sums[allele_code] += 1;
1661 if (allele_code == omitted_allele_idx) {
1662 continue;
1663 }
1664 const uint32_t cur_col = allele_code - 2 - (allele_code > omitted_allele_idx);
1665 rarealt_start[cur_col * nm_sample_ctav + sample_idx] = 1.0;
1666 }
1667 }
1668 }
1669 uintptr_t alt1_het_ct = genocounts[1] - pgv.patch_01_ct;
1670 if (pgv.patch_10_ct) {
1671 const uintptr_t* patch_set_nm = pgv.patch_10_set;
1672 if (missing_ct) {
1673 CopyBitarrSubset(pgv.patch_10_set, sample_nm, nm_sample_ct, tmp_nm);
1674 patch_set_nm = tmp_nm;
1675 }
1676 uintptr_t sample_idx_base = 0;
1677 uintptr_t cur_bits = patch_set_nm[0];
1678 if (!omitted_allele_idx) {
1679 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
1680 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1681 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
1682 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
1683 if (ac0 == ac1) {
1684 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] = 2.0;
1685 alt1_start[sample_idx] = 0.0;
1686 machr2_dosage_ssqs[ac0] += 1;
1687 } else {
1688 rarealt_start[(ac1 - 2) * nm_sample_ctav + sample_idx] = 1.0;
1689 machr2_dosage_sums[ac1] += 1;
1690 if (ac0 == 1) {
1691 ++alt1_het_ct;
1692 alt1_start[sample_idx] = 1.0;
1693 } else {
1694 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] += S_CAST(float, 1.0);
1695 alt1_start[sample_idx] = 0.0;
1696 machr2_dosage_sums[ac0] += 1;
1697 }
1698 }
1699 }
1700 } else if (omitted_allele_idx == 1) {
1701 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
1702 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1703 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
1704 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
1705 if (ac0 == ac1) {
1706 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] = 2.0;
1707 machr2_dosage_ssqs[ac0] += 1;
1708 } else {
1709 rarealt_start[(ac1 - 2) * nm_sample_ctav + sample_idx] = 1.0;
1710 machr2_dosage_sums[ac1] += 1;
1711 if (ac0 == 1) {
1712 ++alt1_het_ct;
1713 } else {
1714 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] += S_CAST(float, 1.0);
1715 machr2_dosage_sums[ac0] += 1;
1716 }
1717 }
1718 }
1719 } else {
1720 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
1721 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
1722 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
1723 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
1724 if (ac0 == ac1) {
1725 machr2_dosage_ssqs[ac0] += 1;
1726 alt1_start[sample_idx] = 0.0;
1727 if (ac0 != omitted_allele_idx) {
1728 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
1729 rarealt_start[ac0_col * nm_sample_ctav + sample_idx] = 2.0;
1730 }
1731 } else {
1732 machr2_dosage_sums[ac1] += 1;
1733 if (ac1 != omitted_allele_idx) {
1734 const uint32_t ac1_col = ac1 - 2 - (ac1 > omitted_allele_idx);
1735 rarealt_start[ac1_col * nm_sample_ctav + sample_idx] = 1.0;
1736 }
1737 if (ac0 == 1) {
1738 ++alt1_het_ct;
1739 alt1_start[sample_idx] = 1.0;
1740 } else {
1741 machr2_dosage_sums[ac0] += 1;
1742 alt1_start[sample_idx] = 0.0;
1743 if (ac0 != omitted_allele_idx) {
1744 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
1745 rarealt_start[ac0_col * nm_sample_ctav + sample_idx] += S_CAST(float, 1.0);
1746 }
1747 }
1748 }
1749 }
1750 }
1751 }
1752 machr2_dosage_sums[1] = alt1_het_ct;
1753 machr2_dosage_ssqs[1] = genocounts[2] - pgv.patch_10_ct;
1754 if (cur_gcount_case_interleaved_vec) {
1755 // gcountcc. Need case-specific one_cts and two_cts for each
1756 // allele.
1757 STD_ARRAY_DECL(uint32_t, 4, case_hardcall_cts);
1758 GenoarrCountSubsetFreqs(pgv.genovec, cur_gcount_case_interleaved_vec, cur_sample_ct, cur_case_ct, case_hardcall_cts);
1759 ZeroU32Arr(allele_ct, case_one_cts);
1760 ZeroU32Arr(allele_ct, case_two_cts);
1761 uint32_t case_alt1_het_ct = case_hardcall_cts[1];
1762 case_one_cts[0] = case_alt1_het_ct;
1763 case_two_cts[0] = case_hardcall_cts[0];
1764 if (pgv.patch_01_ct) {
1765 uintptr_t sample_widx = 0;
1766 uintptr_t cur_bits = pgv.patch_01_set[0];
1767 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
1768 const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_bits);
1769 if (cur_pheno_cc[sample_widx] & lowbit) {
1770 const uint32_t allele_code = pgv.patch_01_vals[uii];
1771 case_one_cts[allele_code] += 1;
1772 }
1773 }
1774 for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) {
1775 case_alt1_het_ct -= case_one_cts[allele_idx];
1776 }
1777 }
1778 uint32_t case_alt1_hom_ct = case_hardcall_cts[2];
1779 if (pgv.patch_10_ct) {
1780 uintptr_t sample_widx = 0;
1781 uintptr_t cur_bits = pgv.patch_10_set[0];
1782 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
1783 const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_bits);
1784 if (cur_pheno_cc[sample_widx] & lowbit) {
1785 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
1786 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
1787 --case_alt1_hom_ct;
1788 if (ac0 == ac1) {
1789 case_two_cts[ac0] += 1;
1790 } else {
1791 case_one_cts[ac1] += 1;
1792 if (ac0 == 1) {
1793 ++case_alt1_het_ct;
1794 } else {
1795 case_one_cts[ac0] += 1;
1796 }
1797 }
1798 }
1799 }
1800 }
1801 case_one_cts[1] = case_alt1_het_ct;
1802 case_two_cts[1] = case_alt1_hom_ct;
1803 uint32_t nonomitted_allele_idx = 0;
1804 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
1805 if (allele_idx == omitted_allele_idx) {
1806 continue;
1807 }
1808 const uint32_t one_ct = machr2_dosage_sums[allele_idx];
1809 const uint32_t two_ct = machr2_dosage_ssqs[allele_idx];
1810 const uint32_t case_one_ct = case_one_cts[allele_idx];
1811 const uint32_t case_two_ct = case_two_cts[allele_idx];
1812 STD_ARRAY_REF(uint32_t, 6) dst = block_aux_iter[nonomitted_allele_idx].geno_hardcall_cts;
1813 dst[0] = nm_case_ct - case_one_ct - case_two_ct;
1814 dst[1] = case_one_ct;
1815 dst[2] = case_two_ct;
1816 dst[3] = nm_sample_ct - one_ct - two_ct - dst[0];
1817 dst[4] = one_ct - case_one_ct;
1818 dst[5] = two_ct - case_two_ct;
1819 ++nonomitted_allele_idx;
1820 }
1821 }
1822 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
1823 const uintptr_t one_ct = machr2_dosage_sums[allele_idx];
1824 const uintptr_t two_ct = machr2_dosage_ssqs[allele_idx];
1825 machr2_dosage_sums[allele_idx] = (one_ct + 2 * two_ct) * 0x4000LLU;
1826 machr2_dosage_ssqs[allele_idx] = (one_ct + 4LLU * two_ct) * 0x10000000LLU;
1827 if ((one_ct == nm_sample_ct) || (two_ct == nm_sample_ct) || ((!one_ct) && (!two_ct))) {
1828 SetBit(allele_idx, const_alleles);
1829 }
1830 }
1831 }
1832 ZeroFArr(nm_sample_ct_rem, &(genotype_vals[nm_sample_ct]));
1833 // usually need to save some of {sample_obs_ct, allele_obs_ct,
1834 // a1_dosage, case_allele_obs_ct, a1_case_dosage, mach_r2 even for
1835 // skipped variants
1836 // compute them all for now, could conditionally skip later
1837 uint32_t allele_obs_ct = nm_sample_ct * 2;
1838 uint32_t case_allele_obs_ct = nm_case_ct * 2;
1839 if (!is_regular_x) {
1840 if (is_nonx_haploid) {
1841 allele_obs_ct = nm_sample_ct;
1842 case_allele_obs_ct = nm_case_ct;
1843 // everything is on 0..1 scale, not 0..2
1844 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1845 genotype_vals[sample_idx] *= S_CAST(float, 0.5);
1846 }
1847 const uint32_t high_ct = nm_sample_ct * allele_ct_m2;
1848 for (uint32_t uii = 0; uii != high_ct; ++uii) {
1849 multi_start[uii] *= S_CAST(float, 0.5);
1850 }
1851 }
1852 } else {
1853 CopyBitarrSubset(sex_male_collapsed, sample_nm, nm_sample_ct, tmp_nm);
1854 const uintptr_t* male_nm = tmp_nm;
1855 const uint32_t nm_male_ct = PopcountWords(male_nm, nm_sample_ctl);
1856 if (is_xchr_model_1) {
1857 // special case: multiply male values by 0.5
1858 uintptr_t sample_idx_base = 0;
1859 uintptr_t male_nm_bits = male_nm[0];
1860 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
1861 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
1862 genotype_vals[sample_idx] *= S_CAST(float, 0.5);
1863 // could insert multiallelic loop here isntead, but I'm guessing
1864 // that's worse due to locality of writes?
1865 }
1866 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
1867 float* cur_start = &(multi_start[extra_allele_idx * nm_sample_ctav]);
1868 sample_idx_base = 0;
1869 male_nm_bits = male_nm[0];
1870 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
1871 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
1872 cur_start[sample_idx] *= S_CAST(float, 0.5);
1873 }
1874 }
1875 allele_obs_ct -= nm_male_ct;
1876 case_allele_obs_ct -= PopcountWordsIntersect(pheno_cc_nm, male_nm, nm_sample_ctl);
1877 }
1878 }
1879 const double mach_r2 = MultiallelicDiploidMachR2(machr2_dosage_sums, machr2_dosage_ssqs, nm_sample_ct, allele_ct);
1880 uint32_t nonomitted_allele_idx = 0;
1881 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
1882 if (allele_idx == omitted_allele_idx) {
1883 continue;
1884 }
1885
1886 float* geno_col = genotype_vals;
1887 if (allele_idx > (!omitted_allele_idx)) {
1888 geno_col = &(nm_predictors_pmaj_buf[(expected_predictor_ct - (allele_ct - allele_idx) + (allele_idx < omitted_allele_idx)) * nm_sample_ctav]);
1889 }
1890 double a1_dosage = u63tod(machr2_dosage_sums[allele_idx]) * kRecipDosageMid;
1891 if (is_xchr_model_1) {
1892 // ugh.
1893 a1_dosage = 0.0;
1894 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1895 a1_dosage += S_CAST(double, geno_col[sample_idx]);
1896 }
1897 } else {
1898 if (is_nonx_haploid) {
1899 a1_dosage *= 0.5;
1900 }
1901 }
1902 a1_dosages[allele_idx] = a1_dosage;
1903
1904 // todo: shortcut if gcountcc computed and no dosages
1905 double a1_case_dosage = 0.0;
1906 uintptr_t sample_idx_base = 0;
1907 uintptr_t pheno_cc_nm_bits = pheno_cc_nm[0];
1908 for (uint32_t uii = 0; uii != nm_case_ct; ++uii) {
1909 const uintptr_t sample_idx = BitIter1(pheno_cc_nm, &sample_idx_base, &pheno_cc_nm_bits);
1910 a1_case_dosage += S_CAST(double, geno_col[sample_idx]);
1911 }
1912 a1_case_dosages[allele_idx] = a1_case_dosage;
1913 block_aux_iter[nonomitted_allele_idx].sample_obs_ct = nm_sample_ct;
1914 block_aux_iter[nonomitted_allele_idx].allele_obs_ct = allele_obs_ct;
1915 if (!allele_ct_m2) {
1916 // Need main_dosage_sum and main_dosage_ssq for now (probably move
1917 // this computation in-place later).
1918 if (is_xchr_model_1) {
1919 main_dosage_sum = a1_dosage;
1920 main_dosage_ssq = 0.0;
1921 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1922 const double cur_dosage = S_CAST(double, geno_col[sample_idx]);
1923 main_dosage_ssq += cur_dosage * cur_dosage;
1924 }
1925 } else {
1926 main_dosage_sum = a1_dosage;
1927 main_dosage_ssq = u63tod(machr2_dosage_ssqs[allele_idx]) * kRecipDosageMidSq;
1928 if (is_nonx_haploid) {
1929 main_dosage_ssq *= 0.25;
1930 }
1931 }
1932 }
1933 block_aux_iter[nonomitted_allele_idx].a1_dosage = a1_dosage;
1934
1935 // bugfix (4 Sep 2018): forgot to save this
1936 block_aux_iter[nonomitted_allele_idx].case_allele_obs_ct = case_allele_obs_ct;
1937
1938 block_aux_iter[nonomitted_allele_idx].a1_case_dosage = a1_case_dosage;
1939 block_aux_iter[nonomitted_allele_idx].firth_fallback = 0;
1940 block_aux_iter[nonomitted_allele_idx].is_unfinished = 0;
1941 block_aux_iter[nonomitted_allele_idx].mach_r2 = mach_r2;
1942 ++nonomitted_allele_idx;
1943 }
1944 // Now free to skip the actual regression if there are too few samples,
1945 // or omitted allele corresponds to a zero-variance genotype column.
1946 // If another allele has zero variance but the omitted allele does not,
1947 // we now salvage as many alleles as we can.
1948 GlmErr glm_err = 0;
1949 if (nm_sample_ct <= expected_predictor_ct) {
1950 // reasonable for this to override CONST_ALLELE
1951 glm_err = SetGlmErr0(kGlmErrcodeSampleCtLtePredictorCt);
1952 } else if (IsSet(const_alleles, omitted_allele_idx)) {
1953 glm_err = SetGlmErr0(kGlmErrcodeConstOmittedAllele);
1954 }
1955 if (glm_err) {
1956 if (missing_ct) {
1957 // covariates have not been copied yet, so we can't usually change
1958 // prev_nm from 0 to 1 when missing_ct == 0 (and there's little
1959 // reason to optimize the zero-covariate case)
1960 prev_nm = 0;
1961 }
1962 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
1963 if (allele_ct_m2 && (beta_se_multiallelic_fused || (!hide_covar))) {
1964 reported_ct += allele_ct_m2;
1965 }
1966 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
1967 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
1968 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
1969 beta_se_iter[uii * 2 + 1] = -9.0;
1970 }
1971 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
1972 }
1973 } else {
1974 {
1975 double omitted_dosage = u63tod(allele_obs_ct);
1976 double omitted_case_dosage = u63tod(case_allele_obs_ct);
1977 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
1978 if (allele_idx == omitted_allele_idx) {
1979 continue;
1980 }
1981 omitted_dosage -= a1_dosages[allele_idx];
1982 omitted_case_dosage -= a1_case_dosages[allele_idx];
1983 }
1984 a1_dosages[omitted_allele_idx] = omitted_dosage;
1985 a1_case_dosages[omitted_allele_idx] = omitted_case_dosage;
1986 }
1987 uint32_t parameter_uidx = 2 + domdev_present;
1988 float* nm_predictors_pmaj_istart = nullptr;
1989 // only need to do this part once per variant in multiallelic case
1990 float* nm_predictors_pmaj_iter = &(nm_predictors_pmaj_buf[nm_sample_ctav * (parameter_uidx - main_omitted)]);
1991 if (missing_ct || (!prev_nm)) {
1992 // fill phenotype
1993 uintptr_t sample_midx_base = 0;
1994 uintptr_t sample_nm_bits = sample_nm[0];
1995 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
1996 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
1997 nm_pheno_buf[sample_idx] = cur_pheno[sample_midx];
1998 }
1999 // bugfix (13 Oct 2017): must guarantee trailing phenotype values
2000 // are valid (exact contents don't matter since they are multiplied
2001 // by zero, but they can't be nan)
2002 ZeroFArr(nm_sample_ct_rem, &(nm_pheno_buf[nm_sample_ct]));
2003
2004 // fill covariates
2005 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx, ++parameter_uidx) {
2006 // strictly speaking, we don't need cur_covars_cmaj to be
2007 // vector-aligned
2008 if (cur_parameter_subset && (!IsSet(cur_parameter_subset, parameter_uidx))) {
2009 continue;
2010 }
2011 const float* cur_covar_col;
2012 if (covar_idx < local_covar_ct) {
2013 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
2014 } else {
2015 cur_covar_col = &(cur_covars_cmaj[(covar_idx - local_covar_ct) * sample_ctav]);
2016 }
2017 sample_midx_base = 0;
2018 sample_nm_bits = sample_nm[0];
2019 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2020 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
2021 *nm_predictors_pmaj_iter++ = cur_covar_col[sample_midx];
2022 }
2023 ZeromovFArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
2024 }
2025 nm_predictors_pmaj_istart = nm_predictors_pmaj_iter;
2026 // bugfix (13 Apr 2021): if local covariates are present, we can't
2027 // optimize as aggressively
2028 prev_nm = !(missing_ct || local_covar_ct);
2029 } else {
2030 // bugfix (15 Aug 2018): this was not handling --parameters
2031 // correctly when a covariate was only needed as part of an
2032 // interaction
2033 parameter_uidx += cur_covar_ct;
2034 nm_predictors_pmaj_istart = &(nm_predictors_pmaj_iter[literal_covar_ct * nm_sample_ctav]);
2035 }
2036 const uint32_t const_allele_ct = PopcountWords(const_alleles, allele_ctl);
2037 if (const_allele_ct) {
2038 // Must delete constant-allele columns from nm_predictors_pmaj, and
2039 // shift later columns back.
2040 float* read_iter = genotype_vals;
2041 float* write_iter = genotype_vals;
2042 for (uint32_t read_allele_idx = 0; read_allele_idx != allele_ct; ++read_allele_idx) {
2043 if (read_allele_idx == omitted_allele_idx) {
2044 continue;
2045 }
2046 if (!IsSet(const_alleles, read_allele_idx)) {
2047 if (write_iter != read_iter) {
2048 memcpy(write_iter, read_iter, nm_sample_ctav * sizeof(float));
2049 }
2050 if (write_iter == genotype_vals) {
2051 write_iter = multi_start;
2052 } else {
2053 write_iter = &(write_iter[nm_sample_ctav]);
2054 }
2055 }
2056 if (read_iter == genotype_vals) {
2057 read_iter = multi_start;
2058 } else {
2059 read_iter = &(read_iter[nm_sample_ctav]);
2060 }
2061 }
2062 }
2063 const uint32_t cur_predictor_ct = expected_predictor_ct - const_allele_ct;
2064 const uint32_t cur_predictor_ctav = RoundUpPow2(cur_predictor_ct, kFloatPerFVec);
2065 const uint32_t cur_predictor_ctavp1 = cur_predictor_ctav + 1;
2066 uint32_t nonconst_extra_regression_idx = UINT32_MAX; // deliberate overflow
2067 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
2068 float* main_vals = &(nm_predictors_pmaj_buf[nm_sample_ctav]);
2069 float* domdev_vals = nullptr;
2070 uint32_t is_unfinished = 0;
2071 uint32_t is_residualized = 0;
2072 // _stop instead of _ct since, in the residualized case, the
2073 // intercept (predictor index 0) is not included; we iterate over
2074 // the predictor indices in [1, _stop).
2075 uint32_t cur_regressed_predictor_stop = cur_predictor_ct;
2076 uint32_t cur_regressed_predictor_ctav = cur_predictor_ctav;
2077 uint32_t cur_regressed_predictor_ctavp1 = cur_predictor_ctavp1;
2078 uint32_t cur_biallelic_regressed_predictor_stop = cur_biallelic_predictor_ct;
2079 if (extra_regression_ct) {
2080 if (IsSet(const_alleles, extra_regression_idx + (extra_regression_idx >= omitted_allele_idx))) {
2081 glm_err = SetGlmErr0(kGlmErrcodeConstAllele);
2082 goto GlmLogisticThreadF_skip_regression;
2083 }
2084 ++nonconst_extra_regression_idx;
2085 if (nonconst_extra_regression_idx) {
2086 float* swap_target = &(multi_start[(nonconst_extra_regression_idx - 1) * nm_sample_ctav]);
2087 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
2088 float fxx = genotype_vals[uii];
2089 genotype_vals[uii] = swap_target[uii];
2090 swap_target[uii] = fxx;
2091 }
2092 }
2093 }
2094 if (main_omitted) {
2095 // if main_mutated, this will be filled below
2096 // if not, this aliases genotype_vals
2097 main_vals = &(nm_predictors_pmaj_buf[(cur_predictor_ct + main_mutated) * nm_sample_ctav]);
2098 } else if (joint_genotypic || joint_hethom) {
2099 // in hethom case, do this before clobbering genotype data
2100 domdev_vals = &(main_vals[nm_sample_ctav]);
2101 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2102 float cur_genotype_val = genotype_vals[sample_idx];
2103 if (cur_genotype_val > S_CAST(float, 1.0)) {
2104 cur_genotype_val = S_CAST(float, 2.0) - cur_genotype_val;
2105 }
2106 domdev_vals[sample_idx] = cur_genotype_val;
2107 }
2108 ZeroFArr(nm_sample_ct_rem, &(domdev_vals[nm_sample_ct]));
2109 }
2110 if (model_dominant) {
2111 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2112 float cur_genotype_val = genotype_vals[sample_idx];
2113 // 0..1..1
2114 if (cur_genotype_val > S_CAST(float, 1.0)) {
2115 cur_genotype_val = 1.0;
2116 }
2117 main_vals[sample_idx] = cur_genotype_val;
2118 }
2119 } else if (model_recessive || joint_hethom) {
2120 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2121 float cur_genotype_val = genotype_vals[sample_idx];
2122 // 0..0..1
2123 if (cur_genotype_val < S_CAST(float, 1.0)) {
2124 cur_genotype_val = 0.0;
2125 } else {
2126 cur_genotype_val -= S_CAST(float, 1.0);
2127 }
2128 main_vals[sample_idx] = cur_genotype_val;
2129 }
2130 } else if (model_hetonly) {
2131 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2132 float cur_genotype_val = genotype_vals[sample_idx];
2133 // 0..1..0
2134 if (cur_genotype_val > S_CAST(float, 1.0)) {
2135 cur_genotype_val = S_CAST(float, 2.0) - cur_genotype_val;
2136 }
2137 main_vals[sample_idx] = cur_genotype_val;
2138 }
2139 }
2140
2141 // fill interaction terms
2142 if (add_interactions) {
2143 nm_predictors_pmaj_iter = nm_predictors_pmaj_istart;
2144 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx) {
2145 const float* cur_covar_col;
2146 if (covar_idx < local_covar_ct) {
2147 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
2148 } else {
2149 cur_covar_col = &(cur_covars_cmaj[covar_idx * sample_ctav]);
2150 }
2151 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
2152 uintptr_t sample_midx_base = 0;
2153 uintptr_t sample_nm_bits = sample_nm[0];
2154 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2155 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
2156 *nm_predictors_pmaj_iter++ = main_vals[sample_idx] * cur_covar_col[sample_midx];
2157 }
2158 ZeromovFArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
2159 }
2160 ++parameter_uidx;
2161 if (domdev_present) {
2162 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
2163 uintptr_t sample_midx_base = 0;
2164 uintptr_t sample_nm_bits = sample_nm[0];
2165 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
2166 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
2167 *nm_predictors_pmaj_iter++ = domdev_vals[sample_idx] * cur_covar_col[sample_midx];
2168 }
2169 ZeromovFArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
2170 }
2171 ++parameter_uidx;
2172 }
2173 }
2174 }
2175 if (corr_inv && prev_nm && (!allele_ct_m2)) {
2176 uintptr_t start_pred_idx = 0;
2177 if (!(model_dominant || model_recessive || model_hetonly || joint_hethom)) {
2178 start_pred_idx = domdev_present + 2;
2179 semicomputed_biallelic_xtx[cur_predictor_ct] = main_dosage_sum;
2180 semicomputed_biallelic_xtx[cur_predictor_ct + 1] = main_dosage_ssq;
2181 }
2182 if (cur_predictor_ct > start_pred_idx) {
2183 ColMajorFvectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[nm_sample_ctav]), &(nm_predictors_pmaj_buf[start_pred_idx * nm_sample_ctav]), nm_sample_ct, nm_sample_ctav, cur_predictor_ct - start_pred_idx, &(predictor_dotprod_buf[start_pred_idx]));
2184 for (uint32_t uii = start_pred_idx; uii != cur_predictor_ct; ++uii) {
2185 semicomputed_biallelic_xtx[cur_predictor_ct + uii] = S_CAST(double, predictor_dotprod_buf[uii]);
2186 }
2187 }
2188 if (domdev_present) {
2189 ColMajorFvectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[2 * nm_sample_ctav]), nm_predictors_pmaj_buf, nm_sample_ct, nm_sample_ctav, cur_predictor_ct, predictor_dotprod_buf);
2190 for (uint32_t uii = 0; uii != cur_predictor_ct; ++uii) {
2191 semicomputed_biallelic_xtx[2 * cur_predictor_ct + uii] = S_CAST(double, predictor_dotprod_buf[uii]);
2192 }
2193 semicomputed_biallelic_xtx[cur_predictor_ct + 2] = semicomputed_biallelic_xtx[2 * cur_predictor_ct + 1];
2194 }
2195 glm_err = CheckMaxCorrAndVifNm(semicomputed_biallelic_xtx, 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]));
2196 if (glm_err) {
2197 goto GlmLogisticThreadF_skip_regression;
2198 }
2199 } else {
2200 glm_err = CheckMaxCorrAndVifF(&(nm_predictors_pmaj_buf[nm_sample_ctav]), cur_predictor_ct - 1, nm_sample_ct, nm_sample_ctav, max_corr, vif_thresh, predictor_dotprod_buf, dbl_2d_buf, inverse_corr_buf, inv_1d_buf);
2201 if (glm_err) {
2202 goto GlmLogisticThreadF_skip_regression;
2203 }
2204 }
2205 ZeroFArr(cur_predictor_ctav, coef_return);
2206 if (!cur_is_always_firth) {
2207 // Does any genotype column have zero case or zero control
2208 // dosage? If yes, faster to skip logistic regression than
2209 // wait for convergence failure.
2210 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
2211 if (IsSet(const_alleles, allele_idx)) {
2212 continue;
2213 }
2214 const double tot_dosage = a1_dosages[allele_idx];
2215 const double case_dosage = a1_case_dosages[allele_idx];
2216 if ((case_dosage == 0.0) || (case_dosage == tot_dosage)) {
2217 if (is_sometimes_firth) {
2218 goto GlmLogisticThreadF_firth_fallback;
2219 }
2220 glm_err = SetGlmErr1(kGlmErrcodeSeparation, allele_idx);
2221 goto GlmLogisticThreadF_skip_regression;
2222 }
2223 }
2224 if (!cur_cc_residualize) {
2225 if (LogisticRegressionF(nm_pheno_buf, nm_predictors_pmaj_buf, nullptr, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, cholesky_decomp_return, pp_buf, sample_variance_buf, hh_return, gradient_buf, dcoef_buf)) {
2226 if (is_sometimes_firth) {
2227 ZeroFArr(cur_predictor_ctav, coef_return);
2228 goto GlmLogisticThreadF_firth_fallback;
2229 }
2230 glm_err = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
2231 goto GlmLogisticThreadF_skip_regression;
2232 }
2233 } else {
2234 if (LogisticRegressionResidualizedF(nm_pheno_buf, nm_predictors_pmaj_buf, sample_nm, cur_cc_residualize, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, cholesky_decomp_return, pp_buf, sample_variance_buf, hh_return, gradient_buf, dcoef_buf, mean_centered_pmaj_buf, sample_offsets_buf)) {
2235 if (is_sometimes_firth) {
2236 ZeroFArr(cur_predictor_ctav, coef_return);
2237 goto GlmLogisticThreadF_firth_fallback;
2238 }
2239 glm_err = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
2240 goto GlmLogisticThreadF_skip_regression;
2241 }
2242 is_residualized = 1;
2243 cur_regressed_predictor_stop = domdev_present + allele_ct;
2244 cur_regressed_predictor_ctav = RoundUpPow2(cur_regressed_predictor_stop, kFloatPerFVec);
2245 cur_regressed_predictor_ctavp1 = cur_regressed_predictor_ctav + 1;
2246 cur_biallelic_regressed_predictor_stop = domdev_present + 2;
2247 }
2248 // unlike FirthRegressionF(), hh_return isn't inverted yet, do
2249 // that here
2250 for (uint32_t pred_uidx = is_residualized; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
2251 float* hh_inv_row = &(hh_return[pred_uidx * cur_regressed_predictor_ctav]);
2252 // ZeroFArr(cur_regressed_predictor_stop, gradient_buf);
2253 // gradient_buf[pred_uidx] = 1.0;
2254 // (y is gradient_buf, x is dcoef_buf)
2255 // SolveLinearSystemF(cholesky_decomp_return, &(gradient_buf[is_residualized]), cur_regressed_predictor_stop - is_residualized, &(hh_inv_row[is_residualized]));
2256 // that works, but doesn't exploit the sparsity of y
2257
2258 // hh_return does now have vector-aligned rows
2259 ZeroFArr(pred_uidx, hh_inv_row);
2260
2261 float fxx = 1.0;
2262 for (uint32_t row_idx = pred_uidx; row_idx != cur_regressed_predictor_stop; ++row_idx) {
2263 const float* ll_row = &(cholesky_decomp_return[row_idx * cur_regressed_predictor_ctav]);
2264 for (uint32_t col_idx = pred_uidx; col_idx != row_idx; ++col_idx) {
2265 fxx -= ll_row[col_idx] * hh_inv_row[col_idx];
2266 }
2267 hh_inv_row[row_idx] = fxx / ll_row[row_idx];
2268 fxx = 0.0;
2269 }
2270 for (uint32_t col_idx = cur_regressed_predictor_stop; col_idx > is_residualized; ) {
2271 fxx = hh_inv_row[--col_idx];
2272 float* hh_inv_row_iter = &(hh_inv_row[cur_regressed_predictor_stop - 1]);
2273 for (uint32_t row_idx = cur_regressed_predictor_stop - 1; row_idx > col_idx; --row_idx) {
2274 fxx -= cholesky_decomp_return[row_idx * cur_regressed_predictor_ctav + col_idx] * (*hh_inv_row_iter--);
2275 }
2276 *hh_inv_row_iter = fxx / cholesky_decomp_return[col_idx * cur_regressed_predictor_ctavp1];
2277 }
2278 }
2279 } else {
2280 if (!is_always_firth) {
2281 GlmLogisticThreadF_firth_fallback:
2282 block_aux_iter[extra_regression_idx].firth_fallback = 1;
2283 if (allele_ct_m2 && beta_se_multiallelic_fused) {
2284 for (uint32_t uii = 1; uii != allele_ct - 1; ++uii) {
2285 block_aux_iter[uii].firth_fallback = 1;
2286 }
2287 }
2288 }
2289 if (!cur_cc_residualize) {
2290 if (FirthRegressionF(nm_pheno_buf, nm_predictors_pmaj_buf, nullptr, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, hh_return, inverse_corr_buf, inv_1d_buf, dbl_2d_buf, pp_buf, sample_variance_buf, gradient_buf, dcoef_buf, hdiag_buf, score_buf, hh0_buf, tmpnxk_buf)) {
2291 glm_err = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
2292 goto GlmLogisticThreadF_skip_regression;
2293 }
2294 } else {
2295 if (FirthRegressionResidualizedF(nm_pheno_buf, nm_predictors_pmaj_buf, sample_nm, cur_cc_residualize, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, hh_return, inverse_corr_buf, inv_1d_buf, dbl_2d_buf, pp_buf, sample_variance_buf, gradient_buf, dcoef_buf, hdiag_buf, score_buf, hh0_buf, tmpnxk_buf, mean_centered_pmaj_buf, sample_offsets_buf)) {
2296 glm_err = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
2297 goto GlmLogisticThreadF_skip_regression;
2298 }
2299 is_residualized = 1;
2300 cur_regressed_predictor_stop = domdev_present + allele_ct;
2301 cur_regressed_predictor_ctav = RoundUpPow2(cur_regressed_predictor_stop, kFloatPerFVec);
2302 cur_regressed_predictor_ctavp1 = cur_regressed_predictor_ctav + 1;
2303 cur_biallelic_regressed_predictor_stop = domdev_present + 2;
2304 }
2305 }
2306 // validParameters() check
2307 for (uint32_t pred_uidx = 1; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
2308 const float hh_inv_diag_element = hh_return[pred_uidx * cur_regressed_predictor_ctavp1];
2309 if ((hh_inv_diag_element < S_CAST(float, 1e-20)) || (!isfinite_f(hh_inv_diag_element))) {
2310 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
2311 goto GlmLogisticThreadF_skip_regression;
2312 }
2313 // use sample_variance_buf[] to store diagonal square roots
2314 sample_variance_buf[pred_uidx] = sqrtf(hh_inv_diag_element);
2315 }
2316 if (!is_residualized) {
2317 sample_variance_buf[0] = sqrtf(hh_return[0]);
2318 }
2319 for (uint32_t pred_uidx = 1 + is_residualized; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
2320 const float cur_hh_inv_diag_sqrt = S_CAST(float, 0.99999) * sample_variance_buf[pred_uidx];
2321 const float* hh_inv_row_iter = &(hh_return[pred_uidx * cur_regressed_predictor_ctav + is_residualized]);
2322 const float* hh_inv_diag_sqrts_iter = &(sample_variance_buf[is_residualized]);
2323 for (uint32_t pred_uidx2 = is_residualized; pred_uidx2 != pred_uidx; ++pred_uidx2) {
2324 if ((*hh_inv_row_iter++) > cur_hh_inv_diag_sqrt * (*hh_inv_diag_sqrts_iter++)) {
2325 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
2326 goto GlmLogisticThreadF_skip_regression;
2327 }
2328 }
2329 }
2330 if (is_unfinished) {
2331 block_aux_iter[extra_regression_idx].is_unfinished = 1;
2332 if (allele_ct_m2 && beta_se_multiallelic_fused) {
2333 for (uint32_t uii = 1; uii != allele_ct - 1; ++uii) {
2334 block_aux_iter[uii].is_unfinished = 1;
2335 }
2336 }
2337 }
2338 {
2339 double* beta_se_iter2 = beta_se_iter;
2340 for (uint32_t pred_uidx = reported_pred_uidx_start; pred_uidx != reported_pred_uidx_biallelic_end; ++pred_uidx) {
2341 // In the multiallelic-fused case, if the first allele is
2342 // constant, this writes the beta/se values for the first
2343 // nonconstant, non-omitted allele where the results for the
2344 // first allele belong. We correct that at the end of this
2345 // block.
2346 *beta_se_iter2++ = S_CAST(double, coef_return[pred_uidx]);
2347 *beta_se_iter2++ = S_CAST(double, sample_variance_buf[pred_uidx]);
2348 }
2349 if (cur_constraint_ct) {
2350 // bugfix (4 Sep 2021): forgot to update this for residualize
2351 // case
2352 *beta_se_iter2++ = 0.0;
2353
2354 uint32_t joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
2355 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
2356 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
2357 cur_constraints_con_major[uii * cur_regressed_predictor_stop + joint_test_idx] = 1.0;
2358 }
2359 double chisq;
2360 if (!LinearHypothesisChisqF(coef_return, cur_constraints_con_major, hh_return, cur_constraint_ct, cur_regressed_predictor_stop, cur_regressed_predictor_ctav, &chisq, tmphxs_buf, h_transpose_buf, inner_buf, inverse_corr_buf, inv_1d_buf, dbl_2d_buf, outer_buf)) {
2361 *beta_se_iter2++ = chisq;
2362 } else {
2363 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeRankDeficient);
2364 memcpy(&(beta_se_iter2[-1]), &glm_err2, 8);
2365 *beta_se_iter2++ = -9.0;
2366 }
2367 // next test may have different alt allele count
2368 joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
2369 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
2370 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
2371 cur_constraints_con_major[uii * cur_regressed_predictor_stop + joint_test_idx] = 0.0;
2372 }
2373 }
2374 if (!const_allele_ct) {
2375 if (beta_se_multiallelic_fused || (!hide_covar)) {
2376 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
2377 *beta_se_iter2++ = S_CAST(double, coef_return[cur_biallelic_regressed_predictor_stop + extra_allele_idx]);
2378 *beta_se_iter2++ = S_CAST(double, sample_variance_buf[cur_biallelic_regressed_predictor_stop + extra_allele_idx]);
2379 }
2380 }
2381 } else if (!beta_se_multiallelic_fused) {
2382 if (!hide_covar) {
2383 // Need to insert some {CONST_ALLELE, -9} entries.
2384 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
2385 const uint32_t cur_raw_allele_idx = extra_regression_idx + (extra_regression_idx >= omitted_allele_idx);
2386 uint32_t extra_read_allele_idx = 0;
2387 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
2388 if ((allele_idx == omitted_allele_idx) || (allele_idx == cur_raw_allele_idx)) {
2389 continue;
2390 }
2391 if (IsSet(const_alleles, allele_idx)) {
2392 memcpy(beta_se_iter2, &glm_err2, 8);
2393 beta_se_iter2[1] = -9.0;
2394 beta_se_iter2 = &(beta_se_iter2[2]);
2395 } else {
2396 *beta_se_iter2++ = S_CAST(double, coef_return[cur_biallelic_regressed_predictor_stop + extra_read_allele_idx]);
2397 *beta_se_iter2++ = S_CAST(double, sample_variance_buf[cur_biallelic_regressed_predictor_stop + extra_read_allele_idx]);
2398 ++extra_read_allele_idx;
2399 }
2400 }
2401 }
2402 } else {
2403 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
2404 // Special-case first nonconst allele since it's positioned
2405 // discontinuously, and its BETA/SE may already be correctly
2406 // filled.
2407 uint32_t allele_idx = omitted_allele_idx? 0 : 1;
2408 if (IsSet(const_alleles, allele_idx)) {
2409 memcpy(&(beta_se_iter[2 * include_intercept]), &glm_err2, 8);
2410 beta_se_iter[2 * include_intercept + 1] = -9.0;
2411 allele_idx = AdvTo0Bit(const_alleles, 1);
2412 if (allele_idx == omitted_allele_idx) {
2413 allele_idx = AdvTo0Bit(const_alleles, omitted_allele_idx + 1);
2414 }
2415 const uint32_t skip_ct = allele_idx - 1 - (allele_idx > omitted_allele_idx);
2416 for (uint32_t uii = 0; uii != skip_ct; ++uii) {
2417 memcpy(beta_se_iter2, &glm_err2, 8);
2418 beta_se_iter2[1] = -9.0;
2419 beta_se_iter2 = &(beta_se_iter2[2]);
2420 }
2421 *beta_se_iter2++ = S_CAST(double, coef_return[1]);
2422 *beta_se_iter2++ = S_CAST(double, sample_variance_buf[1]);
2423 }
2424 ++allele_idx;
2425 uint32_t nonconst_allele_idx_m1 = 0;
2426 for (; allele_idx != allele_ct; ++allele_idx) {
2427 if (allele_idx == omitted_allele_idx) {
2428 continue;
2429 }
2430 if (!IsSet(const_alleles, allele_idx)) {
2431 *beta_se_iter2++ = S_CAST(double, coef_return[cur_biallelic_predictor_ct + nonconst_allele_idx_m1]);
2432 *beta_se_iter2++ = S_CAST(double, sample_variance_buf[cur_biallelic_predictor_ct + nonconst_allele_idx_m1]);
2433 ++nonconst_allele_idx_m1;
2434 } else {
2435 memcpy(beta_se_iter2, &glm_err2, 8);
2436 beta_se_iter2[1] = -9.0;
2437 beta_se_iter2 = &(beta_se_iter2[2]);
2438 }
2439 }
2440 }
2441 }
2442 while (0) {
2443 GlmLogisticThreadF_skip_regression:
2444 {
2445 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
2446 if (allele_ct_m2 && (beta_se_multiallelic_fused || (!hide_covar))) {
2447 reported_ct += allele_ct_m2;
2448 }
2449 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
2450 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
2451 beta_se_iter[uii * 2 + 1] = -9.0;
2452 }
2453 }
2454 }
2455 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
2456 }
2457 }
2458 block_aux_iter = &(block_aux_iter[allele_ct - 1]);
2459 if (local_covars_iter) {
2460 local_covars_iter = &(local_covars_iter[local_covar_ct * max_sample_ct]);
2461 }
2462 }
2463 }
2464 parity = 1 - parity;
2465 variant_idx_offset += cur_block_variant_ct;
2466 while (0) {
2467 GlmLogisticThreadF_err:
2468 UpdateU64IfSmaller(new_err_info, &common->err_info);
2469 }
2470 } while (!THREAD_BLOCK_FINISH(arg));
2471 THREAD_RETURN;
2472 }
2473
2474 // LogisticSseD doesn't exist since logistic_v_unsafe is used instead
2475
2476 static inline void MultMatrixDxnVectND(const double* mm, const double* vect, uint32_t col_ct, uint32_t row_ct, double* __restrict dest) {
2477 const uint32_t col_ctav = RoundUpPow2(col_ct, kDoublePerDVec);
2478 ColMajorVectorMatrixMultiplyStrided(vect, mm, col_ct, col_ctav, row_ct, dest);
2479 }
2480
2481 #ifdef __LP64__
2482 static inline void ComputeVD(const double* pp, uint32_t nn, double* __restrict vv) {
2483 const VecD one = VCONST_D(1.0);
2484 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2485 const VecD cur_pp = *R_CAST(const VecD*, &(pp[uii]));
2486 *R_CAST(VecD*, &(vv[uii])) = cur_pp * (one - cur_pp);
2487 }
2488 }
2489
2490 static inline void ComputeVAndPMinusYD(const double* yy, uint32_t nn, double* pp, double* __restrict vv) {
2491 const VecD one = VCONST_D(1.0);
2492 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2493 VecD ptmp = *R_CAST(VecD*, &(pp[uii]));
2494 VecD one_minus_ptmp = one - ptmp;
2495 *R_CAST(VecD*, &(vv[uii])) = ptmp * one_minus_ptmp;
2496 VecD ytmp = *R_CAST(const VecD*, &(yy[uii]));
2497 *R_CAST(VecD*, &(pp[uii])) = ptmp - ytmp;
2498 }
2499 }
2500
2501 static inline double TripleProductD(const double* v1, const double* v2, const double* v3, uint32_t nn) {
2502 VecD sum = vecd_setzero();
2503 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2504 VecD aa = *R_CAST(const VecD*, &(v1[uii]));
2505 VecD bb = *R_CAST(const VecD*, &(v2[uii]));
2506 VecD cc = *R_CAST(const VecD*, &(v3[uii]));
2507 sum = sum + aa * bb * cc;
2508 }
2509 return VecDHsum(sum);
2510 }
2511
2512 static inline void ComputeTwoDiagTripleProductD(const double* aa, const double* bb, const double* vv, uint32_t nn, double* __restrict raa_ptr, double* __restrict rab_ptr, double* __restrict rbb_ptr) {
2513 VecD saa = vecd_setzero();
2514 VecD sab = vecd_setzero();
2515 VecD sbb = vecd_setzero();
2516 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2517 const VecD vtmp = *R_CAST(const VecD*, &(vv[uii]));
2518 const VecD atmp = *R_CAST(const VecD*, &(aa[uii]));
2519 const VecD btmp = *R_CAST(const VecD*, &(bb[uii]));
2520 const VecD av = atmp * vtmp;
2521 const VecD bv = btmp * vtmp;
2522 saa = saa + atmp * av;
2523 sab = sab + atmp * bv;
2524 sbb = sbb + btmp * bv;
2525 }
2526 *raa_ptr = VecDHsum(saa);
2527 *rab_ptr = VecDHsum(sab);
2528 *rbb_ptr = VecDHsum(sbb);
2529 }
2530
2531 static inline void ComputeThreeTripleProductD(const double* bb, const double* a1, const double* a2, const double* a3, const double* vv, uint32_t nn, double* __restrict r1_ptr, double* __restrict r2_ptr, double* __restrict r3_ptr) {
2532 VecD s1 = vecd_setzero();
2533 VecD s2 = vecd_setzero();
2534 VecD s3 = vecd_setzero();
2535 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2536 const VecD a1tmp = *R_CAST(const VecD*, &(a1[uii]));
2537 const VecD a2tmp = *R_CAST(const VecD*, &(a2[uii]));
2538 const VecD a3tmp = *R_CAST(const VecD*, &(a3[uii]));
2539 const VecD vtmp = *R_CAST(const VecD*, &(vv[uii]));
2540 VecD btmp = *R_CAST(const VecD*, &(bb[uii]));
2541 btmp = btmp * vtmp;
2542 s1 = s1 + a1tmp * btmp;
2543 s2 = s2 + a2tmp * btmp;
2544 s3 = s3 + a3tmp * btmp;
2545 }
2546 *r1_ptr = VecDHsum(s1);
2547 *r2_ptr = VecDHsum(s2);
2548 *r3_ptr = VecDHsum(s3);
2549 }
2550
2551 static inline void ComputeTwoPlusOneTripleProductD(const double* bb, const double* a1, const double* a2, const double* vv, uint32_t nn, double* __restrict r1_ptr, double* __restrict r2_ptr, double* __restrict r3_ptr) {
2552 VecD s1 = vecd_setzero();
2553 VecD s2 = vecd_setzero();
2554 VecD s3 = vecd_setzero();
2555 for (uint32_t uii = 0; uii < nn; uii += kDoublePerDVec) {
2556 const VecD a1tmp = *R_CAST(const VecD*, &(a1[uii]));
2557 const VecD a2tmp = *R_CAST(const VecD*, &(a2[uii]));
2558 const VecD btmp = *R_CAST(const VecD*, &(bb[uii]));
2559 const VecD vtmp = *R_CAST(const VecD*, &(vv[uii]));
2560 const VecD bv = btmp * vtmp;
2561 s1 = s1 + btmp * bv;
2562 s2 = s2 + a1tmp * bv;
2563 s3 = s3 + a2tmp * bv;
2564 }
2565 *r1_ptr = VecDHsum(s1);
2566 *r2_ptr = VecDHsum(s2);
2567 *r3_ptr = VecDHsum(s3);
2568 }
2569 #else // !__LP64__
2570 static inline void ComputeVD(const double* pp, uint32_t nn, double* __restrict vv) {
2571 for (uint32_t uii = 0; uii != nn; ++uii) {
2572 const double cur_pp = pp[uii];
2573 vv[uii] = cur_pp * (1.0 - cur_pp);
2574 }
2575 }
2576
2577 static inline void ComputeVAndPMinusYD(const double* yy, uint32_t nn, double* __restrict pp, double* __restrict vv) {
2578 for (uint32_t uii = 0; uii != nn; ++uii) {
2579 vv[uii] = pp[uii] * (1.0 - pp[uii]);
2580 pp[uii] -= yy[uii];
2581 }
2582 }
2583
2584 static inline double TripleProductD(const double* v1, const double* v2, const double* v3, uint32_t nn) {
2585 double dxx = 0.0;
2586 for (uint32_t uii = 0; uii != nn; ++uii) {
2587 dxx += v1[uii] * v2[uii] * v3[uii];
2588 }
2589 return dxx;
2590 }
2591
2592 static inline void ComputeTwoDiagTripleProductD(const double* aa, const double* bb, const double* vv, uint32_t nn, double* __restrict raa_ptr, double* __restrict rab_ptr, double* __restrict rbb_ptr) {
2593 double raa = 0.0;
2594 double rab = 0.0;
2595 double rbb = 0.0;
2596 for (uint32_t uii = 0; uii != nn; ++uii) {
2597 const double dxx = aa[uii];
2598 const double dyy = bb[uii];
2599 double dzz = vv[uii];
2600 raa += dxx * dxx * dzz;
2601 dzz *= dyy;
2602 rab += dxx * dzz;
2603 rbb += dyy * dzz;
2604 }
2605 *raa_ptr = raa;
2606 *rab_ptr = rab;
2607 *rbb_ptr = rbb;
2608 }
2609
2610 static inline void ComputeThreeTripleProductD(const double* bb, const double* a1, const double* a2, const double* a3, const double* vv, uint32_t nn, double* __restrict r1_ptr, double* __restrict r2_ptr, double* __restrict r3_ptr) {
2611 double r1 = 0.0;
2612 double r2 = 0.0;
2613 double r3 = 0.0;
2614 for (uint32_t uii = 0; uii != nn; ++uii) {
2615 const double dxx = bb[uii] * vv[uii];
2616 r1 += a1[uii] * dxx;
2617 r2 += a2[uii] * dxx;
2618 r3 += a3[uii] * dxx;
2619 }
2620 *r1_ptr = r1;
2621 *r2_ptr = r2;
2622 *r3_ptr = r3;
2623 }
2624
2625 static inline void ComputeTwoPlusOneTripleProductD(const double* bb, const double* a1, const double* a2, const double* vv, uint32_t nn, double* __restrict r1_ptr, double* __restrict r2_ptr, double* __restrict r3_ptr) {
2626 double r1 = 0.0;
2627 double r2 = 0.0;
2628 double r3 = 0.0;
2629 for (uint32_t uii = 0; uii != nn; ++uii) {
2630 const double dxx = bb[uii];
2631 const double dyy = dxx * vv[uii];
2632 r1 += dxx * dyy;
2633 r2 += a1[uii] * dyy;
2634 r3 += a2[uii] * dyy;
2635 }
2636 *r1_ptr = r1;
2637 *r2_ptr = r2;
2638 *r3_ptr = r3;
2639 }
2640 #endif
2641
2642 double ComputeLoglikD(const double* yy, const double* pp, uint32_t sample_ct) {
2643 // possible todo: look for a high-precision way to accelerate this.
2644 double loglik = 0.0;
2645 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2646 const double new_pi = pp[sample_idx];
2647 loglik += (yy[sample_idx] != 0.0)? log(new_pi) : log1p(-new_pi);
2648 }
2649 return loglik;
2650 }
2651
2652 BoolErr ComputeLoglikCheckedD(const double* yy, const double* pp, uint32_t sample_ct, double* loglik_ptr) {
2653 // possible todo: look for a high-precision way to accelerate this.
2654 double loglik = 0.0;
2655 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2656 const double new_pi = pp[sample_idx];
2657 // Imitate logistf stopping condition.
2658 if ((new_pi == 0.0) || (new_pi == 1.0)) {
2659 return 1;
2660 }
2661 loglik += (yy[sample_idx] != 0.0)? log(new_pi) : log1p(-new_pi);
2662 }
2663 *loglik_ptr = loglik;
2664 return 0;
2665 }
2666
2667 void ComputeHessianD(const double* mm, const double* vv, uint32_t col_ct, uint32_t row_ct, double* __restrict dest) {
2668 const uintptr_t col_ctav = RoundUpPow2(col_ct, kDoublePerDVec);
2669 const uintptr_t row_ctav = RoundUpPow2(row_ct, kDoublePerDVec);
2670 const uintptr_t row_ctavp1 = row_ctav + 1;
2671 if (row_ct > 3) {
2672 const uint32_t row_ctm3 = row_ct - 3;
2673 for (uint32_t row_idx = 0; row_idx < row_ctm3; row_idx += 3) {
2674 const double* mm_cur = &(mm[row_idx * col_ctav]);
2675 ComputeTwoDiagTripleProductD(mm_cur, &(mm_cur[col_ctav]), vv, col_ct, &(dest[row_idx * row_ctavp1]), &(dest[(row_idx + 1) * row_ctavp1 - 1]), &(dest[(row_idx + 1) * row_ctavp1]));
2676 ComputeTwoPlusOneTripleProductD(&(mm_cur[2 * col_ctav]), &(mm_cur[col_ctav]), mm_cur, vv, col_ct, &(dest[(row_idx + 2) * row_ctavp1]), &(dest[(row_idx + 2) * row_ctavp1 - 1]), &(dest[(row_idx + 2) * row_ctavp1 - 2]));
2677 for (uint32_t row_idx2 = row_idx + 3; row_idx2 != row_ct; ++row_idx2) {
2678 ComputeThreeTripleProductD(&(mm[row_idx2 * col_ctav]), mm_cur, &(mm_cur[col_ctav]), &(mm_cur[2 * col_ctav]), vv, col_ct, &(dest[row_idx2 * row_ctav + row_idx]), &(dest[row_idx2 * row_ctav + row_idx + 1]), &(dest[row_idx2 * row_ctav + row_idx + 2]));
2679 }
2680 }
2681 }
2682 switch (row_ct % 3) {
2683 case 0:
2684 ComputeTwoPlusOneTripleProductD(&(mm[(row_ct - 3) * col_ctav]), &(mm[(row_ct - 2) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct, &(dest[(row_ct - 3) * row_ctavp1]), &(dest[(row_ct - 2) * row_ctavp1 - 1]), &(dest[(row_ct - 1) * row_ctavp1 - 2]));
2685 // fall through
2686 case 2:
2687 ComputeTwoDiagTripleProductD(&(mm[(row_ct - 2) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct, &(dest[(row_ct - 2) * row_ctavp1]), &(dest[(row_ct - 1) * row_ctavp1 - 1]), &(dest[(row_ct - 1) * row_ctavp1]));
2688 break;
2689 case 1:
2690 dest[(row_ct - 1) * row_ctavp1] = TripleProductD(&(mm[(row_ct - 1) * col_ctav]), &(mm[(row_ct - 1) * col_ctav]), vv, col_ct);
2691 }
2692 }
2693
2694 void CholeskyDecompositionD(const double* aa, uint32_t predictor_ct, double* __restrict ll) {
2695 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
2696 const uintptr_t predictor_ctavp1 = predictor_ctav + 1;
2697 const double* aa_diag_elem_ptr = aa;
2698 double* cur_ll_row = ll;
2699 for (uint32_t row_idx = 0; row_idx != predictor_ct; ++row_idx) {
2700 double dxx = *aa_diag_elem_ptr;
2701 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
2702 const double dyy = cur_ll_row[col_idx];
2703 dxx -= dyy * dyy;
2704 }
2705 double dyy;
2706 if (dxx >= 0.0) {
2707 dyy = sqrt(dxx);
2708 } else {
2709 dyy = 1e-14;
2710 }
2711 cur_ll_row[row_idx] = dyy;
2712 dyy = 1.0 / dyy; // now 1.0 / L[j][j]
2713 const double* aa_col_iter = aa_diag_elem_ptr;
2714 double* cur_ll_row2 = cur_ll_row;
2715 for (uint32_t row_idx2 = row_idx + 1; row_idx2 != predictor_ct; ++row_idx2) {
2716 aa_col_iter = &(aa_col_iter[predictor_ctav]);
2717 double dxx2 = *aa_col_iter;
2718 cur_ll_row2 = &(cur_ll_row2[predictor_ctav]);
2719 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
2720 dxx2 -= cur_ll_row[col_idx] * cur_ll_row2[col_idx];
2721 }
2722 cur_ll_row2[row_idx] = dxx2 * dyy;
2723 }
2724 aa_diag_elem_ptr = &(aa_diag_elem_ptr[predictor_ctavp1]);
2725 cur_ll_row = &(cur_ll_row[predictor_ctav]);
2726 }
2727 }
2728
2729 void SolveLinearSystemD(const double* ll, const double* yy, uint32_t predictor_ct, double* __restrict xx) {
2730 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
2731 {
2732 const double* cur_ll_row = ll;
2733 for (uint32_t row_idx = 0; row_idx != predictor_ct; ++row_idx) {
2734 double dxx = yy[row_idx];
2735 for (uint32_t col_idx = 0; col_idx != row_idx; ++col_idx) {
2736 dxx -= cur_ll_row[col_idx] * xx[col_idx];
2737 }
2738 xx[row_idx] = dxx / cur_ll_row[row_idx];
2739 cur_ll_row = &(cur_ll_row[predictor_ctav]);
2740 }
2741 }
2742 for (uint32_t col_idx = predictor_ct; col_idx; ) {
2743 double* xx_stop = &(xx[--col_idx]);
2744 double dxx = *xx_stop;
2745 const double* ll_col_iter = &(ll[(predictor_ct - 1) * predictor_ctav + col_idx]);
2746 for (double* xx_iter = &(xx[predictor_ct - 1]); xx_iter != xx_stop; --xx_iter) {
2747 dxx -= (*ll_col_iter) * (*xx_iter);
2748 ll_col_iter -= predictor_ctav;
2749 }
2750 *xx_stop = dxx / (*ll_col_iter);
2751 }
2752 }
2753
2754 BoolErr LogisticRegressionD(const double* yy, const double* xx, const double* sample_offsets, uint32_t sample_ct, uint32_t predictor_ct, uint32_t* is_unfinished_ptr, double* __restrict coef, double* __restrict ll, double* __restrict pp, double* __restrict vv, double* __restrict hh, double* __restrict grad, double* __restrict dcoef, MatrixInvertBuf1* __restrict mi_buf, double* __restrict dbl_2d_buf) {
2755 // This imitates R glm.fit(). Main differences from LogisticRegressionF(),
2756 // beyond precision:
2757 // - Initialization is somewhat different.
2758 // - Convergence criteria are now
2759 // maxit = 25
2760 // |dev - dev_{old}| / (|dev| + 0.1) < 1e-8, where dev := -2 *
2761 // log-likelihood.
2762 // Support for sample_offsets was added in Mar 2024. I had thought that
2763 // cc-residualize without single-prec didn't make sense since single-prec
2764 // should offer more of a speed boost for less accuracy cost on the initial
2765 // margin, but it turns out that the current single-precision functions have
2766 // unreliable convergence on biobank-scale datasets, so cc-residualize on its
2767 // own is often the fastest mode that still works.
2768 //
2769 // Preallocated buffers (initial contents irrelevant):
2770 // vv = sample variance buffer
2771 // grad = gradient buffer Y[] (length predictor_ct)
2772 // dcoef = current coefficient change buffer (length predictor_ct)
2773 // mi_buf, dbl_2d_buf: only for NOLAPACK case
2774 //
2775 // Inputs:
2776 // xx = covariate (and usually genotype) matrix, covariate-major, rows are
2777 // vector-aligned, trailing row elements must be zeroed out
2778 // yy = case/control phenotype; trailing elements must be zeroed out
2779 //
2780 // Outputs:
2781 // coef = main result.
2782 // ll = cholesky decomposition matrix, predictor_ct^2, rows vector-aligned
2783 // hh = hessian matrix buffer, predictor_ct^2, rows vector-aligned
2784 // pp = final likelihoods minus Y[] (not currently used by callers).
2785 //
2786 // Returns 1 on convergence failure, 0 otherwise.
2787 // is_unfinished assumed to be initialized to 0, and is set to 1 if we hit
2788 // the iteration limit without satisfying other convergence criteria; the
2789 // main return value is 0 in this case.
2790 const uint32_t maxit = 25;
2791
2792 const uintptr_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
2793 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
2794 // some room to optimize this initialization
2795 double loglik_old;
2796 {
2797 // Initial loglik_old computation deliberately omitted, since it doesn't
2798 // correspond to a coef[] setting. It's very unlikely for R glm.fit to
2799 // "converge" on the first iteration, but when it does, it doesn't have the
2800 // same meaning as satisfying the convergence criterion on later
2801 // iterations.
2802 double* zz = vv;
2803 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
2804 // 2 * (ln 3 + 4/3)
2805 zz[sample_idx] = (yy[sample_idx] - 0.5) * 4.863891244002886;
2806 }
2807
2808 // For the first iteration, we need to initialize coef in the same manner
2809 // as glm.fit() if we want to generate identical (up to Cholesky rounding)
2810 // results.
2811 BoolErr reterr = LinearRegressionDVec(zz, xx, predictor_ct, sample_ct, coef, hh, grad, mi_buf, dbl_2d_buf);
2812 if (unlikely(reterr)) {
2813 return 1;
2814 }
2815
2816 // P[i] = \sum_j X[i][j] * coef[j];
2817 ColMajorMatrixVectorMultiplyStrided(xx, coef, sample_ct, sample_ctav, predictor_ct, pp);
2818 if (sample_offsets) {
2819 AddDVec(sample_offsets, sample_ctav, pp);
2820 }
2821
2822 // P[i] = 1 / (1 + exp(-P[i]));
2823 logistic_v_unsafe(pp, sample_ctav);
2824
2825 const double loglik = ComputeLoglikD(yy, pp, sample_ct);
2826 if (loglik != loglik) {
2827 return 1;
2828 }
2829 loglik_old = loglik;
2830 }
2831
2832 ZeroDArr(predictor_ct * predictor_ctav, ll);
2833 // bugfix (9 Oct 2024): although trailing elements of pp and vv are mostly
2834 // irrelevant, they cannot be nan
2835 ZeroDArr(sample_ctav - sample_ct, &(pp[sample_ct]));
2836 ZeroDArr(sample_ctav - sample_ct, &(vv[sample_ct]));
2837
2838 // This index is 1 less than 'iter' in glm.R.
2839 for (uint32_t iteration = 1; iteration != maxit; ++iteration) {
2840 // V[i] = P[i] * (1 - P[i]);
2841 // P[i] -= Y[i];
2842 ComputeVAndPMinusYD(yy, sample_ctav, pp, vv);
2843 // V and P may both contain trailing garbage.
2844
2845 ComputeHessianD(xx, vv, sample_ct, predictor_ct, hh);
2846
2847 // grad = X^T P
2848 // Separate categorical loop also possible here
2849 ColMajorVectorMatrixMultiplyStrided(pp, xx, sample_ct, sample_ctav, predictor_ct, grad);
2850
2851 // maybe this should use a QR decomposition instead?
2852 CholeskyDecompositionD(hh, predictor_ct, ll);
2853
2854 SolveLinearSystemD(ll, grad, predictor_ct, dcoef);
2855
2856 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
2857 coef[pred_idx] -= dcoef[pred_idx];
2858 }
2859 // P[i] = \sum_j X[i][j] * coef[j];
2860 ColMajorMatrixVectorMultiplyStrided(xx, coef, sample_ct, sample_ctav, predictor_ct, pp);
2861 if (sample_offsets) {
2862 AddDVec(sample_offsets, sample_ctav, pp);
2863 }
2864
2865 // P[i] = 1 / (1 + exp(-P[i]));
2866 logistic_v_unsafe(pp, sample_ctav);
2867 const double loglik = ComputeLoglikD(yy, pp, sample_ct);
2868 if (loglik != loglik) {
2869 return 1;
2870 }
2871
2872 // TODO: determine other non-convergence criteria
2873 if (fabs(loglik - loglik_old) < 1e-8 * (0.05 + fabs(loglik))) {
2874 return 0;
2875 }
2876 loglik_old = loglik;
2877 }
2878 *is_unfinished_ptr = 1;
2879 return 0;
2880 }
2881
2882 #ifdef __LP64__
2883 void CopyAndMeanCenterD(const double* src, uintptr_t ct, double* __restrict dst) {
2884 const uintptr_t fullvec_ct = ct / kDoublePerDVec;
2885 const VecD* src_alias = R_CAST(const VecD*, src);
2886 VecD vsum = vecd_setzero();
2887 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
2888 vsum += src_alias[vidx];
2889 }
2890 double sum = VecDHsum(vsum);
2891 const uintptr_t trailing_start_idx = fullvec_ct * kDoublePerDVec;
2892 for (uintptr_t ulii = trailing_start_idx; ulii != ct; ++ulii) {
2893 sum += src[ulii];
2894 }
2895
2896 const double neg_mean = -sum / u31tod(ct);
2897 const VecD neg_vmean = VCONST_D(neg_mean);
2898 VecD* dst_alias = R_CAST(VecD*, dst);
2899 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
2900 dst_alias[vidx] = src_alias[vidx] + neg_vmean;
2901 }
2902 if (trailing_start_idx != ct) {
2903 for (uintptr_t ulii = trailing_start_idx; ulii != ct; ++ulii) {
2904 dst[ulii] = src[ulii] + neg_mean;
2905 }
2906 const uintptr_t trailing_stop_idx = trailing_start_idx + kDoublePerDVec;
2907 for (uintptr_t ulii = ct; ulii != trailing_stop_idx; ++ulii) {
2908 dst[ulii] = 0.0;
2909 }
2910 }
2911 }
2912 #else
2913 void CopyAndMeanCenterD(const double* src, uintptr_t ct, double* __restrict dst) {
2914 double sum = 0.0;
2915 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
2916 sum += src[ulii];
2917 }
2918 const double mean = sum / u31tod(ct);
2919 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
2920 dst[ulii] = src[ulii] - mean;
2921 }
2922 }
2923 #endif
2924
2925 BoolErr LogisticRegressionResidualizedD(const double* yy, const double* xx, const uintptr_t* sample_nm, const CcResidualizeCtx* cc_residualize, uint32_t nm_sample_ct, uint32_t orig_predictor_ct, uint32_t* is_unfinished_ptr, double* coef, double* ll, MatrixInvertBuf1* inv_1d_buf, double* dbl_2d_buf, double* pp, double* vv, double* hh, double* grad, double* dcoef, double* mean_centered_pmaj_buf, double* sample_offsets_buf) {
2926 if (!cc_residualize->logistic_nm_sample_offsets_d) {
2927 return 1;
2928 }
2929 const uintptr_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kDoublePerDVec);
2930 const uint32_t domdev_present_p1 = cc_residualize->domdev_present_p1;
2931 for (uint32_t geno_idx = 0; geno_idx != domdev_present_p1; ++geno_idx) {
2932 CopyAndMeanCenterD(&(xx[(geno_idx + 1) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[geno_idx * nm_sample_ctav]));
2933 }
2934 const uint32_t prefitted_pred_ct = cc_residualize->prefitted_pred_ct;
2935 const uint32_t orig_biallelic_predictor_ct = domdev_present_p1 + prefitted_pred_ct;
2936 const uint32_t extra_allele_ct = orig_predictor_ct - orig_biallelic_predictor_ct;
2937 for (uint32_t extra_allele_idx = 0; extra_allele_idx != extra_allele_ct; ++extra_allele_idx) {
2938 CopyAndMeanCenterD(&(xx[(extra_allele_idx + orig_biallelic_predictor_ct) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[(extra_allele_idx + domdev_present_p1) * nm_sample_ctav]));
2939 }
2940 const double* sample_offsets = cc_residualize->logistic_nm_sample_offsets_d;
2941 if (nm_sample_ct != cc_residualize->sample_ct) {
2942 uintptr_t sample_idx_base = 0;
2943 uintptr_t sample_nm_bits = sample_nm[0];
2944 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
2945 const uintptr_t sample_idx = BitIter1(sample_nm, &sample_idx_base, &sample_nm_bits);
2946 sample_offsets_buf[uii] = sample_offsets[sample_idx];
2947 }
2948 // todo: check if this is actually needed
2949 const uint32_t remainder = (-nm_sample_ct) & (kDoublePerDVec - 1);
2950 ZeroDArr(remainder, &(sample_offsets_buf[nm_sample_ct]));
2951 sample_offsets = sample_offsets_buf;
2952 }
2953 // genotype, domdev?, other alleles
2954 const uint32_t regressed_predictor_ct = domdev_present_p1 + extra_allele_ct;
2955 const uint32_t regressed_predictor_ctav = RoundUpPow2(regressed_predictor_ct, kDoublePerDVec);
2956 if (LogisticRegressionD(yy, mean_centered_pmaj_buf, sample_offsets, nm_sample_ct, regressed_predictor_ct, is_unfinished_ptr, &(coef[1]), ll, pp, vv, hh, grad, dcoef, inv_1d_buf, dbl_2d_buf)) {
2957 return 1;
2958 }
2959 // hh and ll are shifted up and to the left from what the caller expects, due
2960 // to the missing intercept. Correct that here.
2961 const uint32_t expected_predictor_ctav = RoundUpPow2(regressed_predictor_ct + 1, kDoublePerDVec);
2962 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
2963 memcpy(&(hh[write_row_idx * expected_predictor_ctav + 1]), &(hh[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(double));
2964 }
2965 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
2966 memcpy(&(ll[write_row_idx * expected_predictor_ctav + 1]), &(ll[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(double));
2967 }
2968 return 0;
2969 }
2970
2971 void FirthComputeHdiagWeightsD(const double* yy, const double* xx, const double* pp, const double* hh, const double* vv, uint32_t predictor_ct, uint32_t predictor_ctav, uint32_t sample_ct, uint32_t sample_ctav, double* hdiag, double* ww, double* tmpnxk_buf) {
2972 ColMajorMatrixMultiplyStrided(xx, hh, sample_ct, sample_ctav, predictor_ct, predictor_ctav, predictor_ct, sample_ctav, tmpnxk_buf);
2973 // Assumes tau = 0.5.
2974 #ifdef __LP64__
2975 // * tmpNxK, interpreted as column-major, is sample_ct x predictor_ct, must
2976 // have trailing elements of each column zeroed out (otherwise nan may leak
2977 // into trailing elements of hdiag, then ww, ...)
2978 // * X, interpreted as column-major, is also sample_ct x predictor_ct
2979 // * Hdiag[i] = V[i] (\sum_j tmpNxK[i][j] X[i][j])
2980 // * W[i] = (Y[i] - P[i]) + Hdiag[i] * (0.5 - P[i])
2981 const VecD half = VCONST_D(0.5);
2982 for (uint32_t sample_offset = 0; sample_offset < sample_ctav; sample_offset += kDoublePerDVec) {
2983 VecD dotprods = vecd_setzero();
2984 const double* xx_row = &(xx[sample_offset]);
2985 const double* tmpnxk_row = &(tmpnxk_buf[sample_offset]);
2986 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
2987 const VecD cur_xx = *R_CAST(const VecD*, &(xx_row[pred_uidx * sample_ctav]));
2988 const VecD cur_tmpnxk = *R_CAST(const VecD*, &(tmpnxk_row[pred_uidx * sample_ctav]));
2989 dotprods = dotprods + cur_xx * cur_tmpnxk;
2990 }
2991 // Can handle categorical covariates in a separate loop here, and load the
2992 // dotprods increment into a union, etc.
2993 const VecD cur_vv = *R_CAST(const VecD*, &(vv[sample_offset]));
2994 const VecD cur_pi = *R_CAST(const VecD*, &(pp[sample_offset]));
2995 const VecD cur_yy = *R_CAST(const VecD*, &(yy[sample_offset]));
2996 const VecD cur_hdiag = cur_vv * dotprods;
2997 *R_CAST(VecD*, &(hdiag[sample_offset])) = cur_hdiag;
2998 const VecD half_minus_cur_pis = half - cur_pi;
2999 const VecD yy_minus_cur_pis = cur_yy - cur_pi;
3000 *R_CAST(VecD*, &(ww[sample_offset])) = yy_minus_cur_pis + cur_hdiag * half_minus_cur_pis;
3001 }
3002 #else
3003 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3004 double dotprod = 0.0;
3005 const double* xx_row = &(xx[sample_idx]);
3006 const double* tmpnxk_row = &(tmpnxk_buf[sample_idx]);
3007 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
3008 dotprod += xx_row[pred_uidx * sample_ctav] * tmpnxk_row[pred_uidx * sample_ctav];
3009 }
3010 const double cur_hdiag = vv[sample_idx] * dotprod;
3011 hdiag[sample_idx] = cur_hdiag;
3012 const double cur_pi = pp[sample_idx];
3013 ww[sample_idx] = (yy[sample_idx] - cur_pi) + cur_hdiag * (0.5 - cur_pi);
3014 }
3015 #endif
3016 }
3017
3018 void FirthComputeSecondWeightsD(const double* hdiag, const double* vv, __maybe_unused uint32_t sample_ct, __maybe_unused uint32_t sample_ctav, double* ww) {
3019 #ifdef __LP64__
3020 const VecD one = VCONST_D(1.0);
3021 for (uint32_t sample_offset = 0; sample_offset < sample_ctav; sample_offset += kDoublePerDVec) {
3022 const VecD cur_hdiag = *R_CAST(const VecD*, &(hdiag[sample_offset]));
3023 const VecD cur_vv = *R_CAST(const VecD*, &(vv[sample_offset]));
3024 *R_CAST(VecD*, &(ww[sample_offset])) = (one + cur_hdiag) * cur_vv;
3025 }
3026 #else
3027 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3028 ww[sample_idx] = (1.0 + hdiag[sample_idx]) * vv[sample_idx];
3029 }
3030 #endif
3031 }
3032
3033 BoolErr FirthRegressionD(const double* yy, const double* xx, const double* sample_offsets, uint32_t sample_ct, uint32_t predictor_ct, double* beta, uint32_t* is_unfinished_ptr, double* hh, MatrixInvertBuf1* inv_1d_buf, double* dbl_2d_buf, double* pp, double* vv, double* ustar, double* delta, double* hdiag, double* ww, double* hh0, double* tmpnxk_buf) {
3034 // This is a port of Georg Heinze's logistf 1.24.1 R function (called with
3035 // pl=FALSE), adapted to use many of plink 1.9's optimizations; see
3036 // https://github.com/georgheinze/logistf
3037 //
3038 // Preallocated buffers (initial contents irrelevant):
3039 // inv_1d_buf, dbl_2d_buf = for matrix inversion
3040 // pp = likelihoods minus Y[] (not currently used by callers)
3041 // vv = sample variance buffer
3042 // ustar = gradient buffer (length predictor_ct)
3043 // delta = current coefficient change buffer (length predictor_ct)
3044 // hdiag = intermediate multiplier for weights (length sample_ct)
3045 // ww = weight buffer (length sample_ct)
3046 // hh0 = just like hh below, but not returned
3047 //
3048 // Inputs:
3049 // xx = covariate (and usually genotype) matrix, covariate-major, rows are
3050 // vector-aligned, trailing row elements must be zeroed out
3051 // yy = case/control phenotype
3052 // sample_offsets = in residualized mode, product of pre-fitted covariate
3053 // beta vector with covariate matrix. otherwise, nullptr.
3054 //
3055 // Input/output:
3056 // beta = starting point, overwritten with logistic regression betas.
3057 //
3058 // Outputs:
3059 // hh = variance-covariance matrix buffer, predictor_ct^2, rows
3060 // vector-aligned. (spends some time as pre-inversion Hessian matrix
3061 // too)
3062 //
3063 // Returns 1 on convergence failure, 0 otherwise.
3064 // is_unfinished assumed to be initialized to 0, and is set to 1 if we hit
3065 // the iteration limit without satisfying other convergence criteria; the
3066 // main return value is 0 in this case.
3067 const uintptr_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
3068 const uintptr_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
3069
3070 // ustar[] trailing elements must be zeroed out
3071 ZeroDArr(predictor_ctav - predictor_ct, &(ustar[predictor_ct]));
3072
3073 const uint32_t trailing_sample_ct = sample_ctav - sample_ct;
3074 if (trailing_sample_ct) {
3075 // bunch of other trailing elements must also be zeroed out
3076 ZeroDArr(trailing_sample_ct, &(pp[sample_ct]));
3077 ZeroDArr(trailing_sample_ct, &(vv[sample_ct]));
3078 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
3079 ZeroDArr(trailing_sample_ct, &(tmpnxk_buf[sample_ct + pred_idx * sample_ctav]));
3080 }
3081 }
3082
3083 const uint32_t max_iter = 25;
3084 const double gconv = 0.00001;
3085 const double xconv = 0.00001;
3086 const double lconv = 0.00001;
3087 double delta_max = 0.0;
3088 double loglik_old = 0.0;
3089 for (uint32_t iter_idx = 0; ; ++iter_idx) {
3090 // P[i] = \sum_j beta[j] * X[i][j];
3091 // categorical optimization possible here
3092 ColMajorMatrixVectorMultiplyStrided(xx, beta, sample_ct, sample_ctav, predictor_ct, pp);
3093 if (sample_offsets) {
3094 AddDVec(sample_offsets, sample_ctav, pp);
3095 }
3096 // P[i] = 1 / (1 + exp(-P[i]));
3097 logistic_v_unsafe(pp, sample_ct);
3098 double loglik;
3099 if (ComputeLoglikCheckedD(yy, pp, sample_ct, &loglik)) {
3100 return 1;
3101 }
3102 // V[i] = P[i] * (1 - P[i]);
3103 ComputeVD(pp, sample_ct, vv);
3104 // P[i] -= Y[i] NOT done here
3105
3106 // hessian = X diag(V) X'
3107 // note that only lower triangle is filled here
3108 ComputeHessianD(xx, vv, sample_ct, predictor_ct, hh0);
3109 // we shouldn't need to compute the log directly, since underflow <->
3110 // regression failure, right? check this.
3111 if (InvertSymmdefMatrixFirstHalf(predictor_ct, predictor_ctav, hh0, inv_1d_buf, dbl_2d_buf)) {
3112 return 1;
3113 }
3114 const double dethh = HalfSymmInvertedDet(hh0, inv_1d_buf, predictor_ct, predictor_ctav);
3115 loglik += 0.5 * log(dethh);
3116
3117 InvertSymmdefMatrixSecondHalf(predictor_ct, predictor_ctav, hh0, inv_1d_buf, dbl_2d_buf);
3118 // trailing elements of hh0[] rows can't be arbitrary for later
3119 // MultMatrixDxnVectND() call
3120 ReflectStridedMatrix0(predictor_ct, predictor_ctav, hh0);
3121
3122 FirthComputeHdiagWeightsD(yy, xx, pp, hh0, vv, predictor_ct, predictor_ctav, sample_ct, sample_ctav, hdiag, ww, tmpnxk_buf);
3123
3124 // gradient = X' W
3125 // categorical optimization possible here
3126 MultMatrixDxnVectND(xx, ww, sample_ct, predictor_ct, ustar);
3127 if (iter_idx) {
3128 double ustar_max = 0.0;
3129 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
3130 const double abs_ustar_cur = fabs(ustar[pred_uidx]);
3131 if (abs_ustar_cur > ustar_max) {
3132 ustar_max = abs_ustar_cur;
3133 }
3134 }
3135 const double loglik_change = loglik - loglik_old;
3136 if ((delta_max <= xconv) && (ustar_max < gconv) && (loglik_change < lconv)) {
3137 return 0;
3138 }
3139 if (iter_idx > max_iter) {
3140 *is_unfinished_ptr = 1;
3141 return 0;
3142 }
3143 }
3144 loglik_old = loglik;
3145
3146 FirthComputeSecondWeightsD(hdiag, vv, sample_ct, sample_ctav, ww);
3147 ComputeHessianD(xx, ww, sample_ct, predictor_ct, hh);
3148 if (InvertSymmdefStridedMatrix(predictor_ct, predictor_ctav, hh, inv_1d_buf, dbl_2d_buf)) {
3149 return 1;
3150 }
3151 ReflectStridedMatrix0(predictor_ct, predictor_ctav, hh);
3152
3153 // delta := hh * ustar (note that hh is inverted already)
3154 MultMatrixDxnVectND(hh, ustar, predictor_ct, predictor_ct, delta);
3155
3156 delta_max = 0.0;
3157 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
3158 const double abs_delta_cur = fabs(delta[pred_uidx]);
3159 if (abs_delta_cur > delta_max) {
3160 delta_max = abs_delta_cur;
3161 }
3162 }
3163 const double maxstep = 5.0;
3164 if (delta_max > maxstep) {
3165 const double scaling_factor = maxstep / delta_max;
3166 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
3167 delta[pred_uidx] *= scaling_factor;
3168 }
3169 delta_max = maxstep;
3170 }
3171 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
3172 beta[pred_uidx] += delta[pred_uidx];
3173 }
3174 }
3175 }
3176
3177 BoolErr FirthRegressionResidualizedD(const double* yy, const double* xx, const uintptr_t* sample_nm, const CcResidualizeCtx* cc_residualize, uint32_t nm_sample_ct, uint32_t orig_predictor_ct, double* beta, uint32_t* is_unfinished_ptr, double* hh, MatrixInvertBuf1* inv_1d_buf, double* dbl_2d_buf, double* pp, double* vv, double* ustar, double* delta, double* hdiag, double* ww, double* hh0_buf, double* tmpnxk_buf, double* mean_centered_pmaj_buf, double* sample_offsets_buf) {
3178 // todo: deduplicate with LogisticRegressionResidualizedD()
3179 const uintptr_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kDoublePerDVec);
3180 const uint32_t domdev_present_p1 = cc_residualize->domdev_present_p1;
3181 for (uint32_t geno_idx = 0; geno_idx != domdev_present_p1; ++geno_idx) {
3182 CopyAndMeanCenterD(&(xx[(geno_idx + 1) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[geno_idx * nm_sample_ctav]));
3183 }
3184 const uint32_t prefitted_pred_ct = cc_residualize->prefitted_pred_ct;
3185 const uint32_t orig_biallelic_predictor_ct = domdev_present_p1 + prefitted_pred_ct;
3186 const uint32_t extra_allele_ct = orig_predictor_ct - orig_biallelic_predictor_ct;
3187 for (uint32_t extra_allele_idx = 0; extra_allele_idx != extra_allele_ct; ++extra_allele_idx) {
3188 CopyAndMeanCenterD(&(xx[(extra_allele_idx + orig_biallelic_predictor_ct) * nm_sample_ctav]), nm_sample_ct, &(mean_centered_pmaj_buf[(extra_allele_idx + domdev_present_p1) * nm_sample_ctav]));
3189 }
3190 const double* sample_offsets = cc_residualize->firth_nm_sample_offsets_d;
3191 if (nm_sample_ct != cc_residualize->sample_ct) {
3192 uintptr_t sample_idx_base = 0;
3193 uintptr_t sample_nm_bits = sample_nm[0];
3194 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
3195 const uintptr_t sample_idx = BitIter1(sample_nm, &sample_idx_base, &sample_nm_bits);
3196 sample_offsets_buf[uii] = sample_offsets[sample_idx];
3197 }
3198 const uint32_t remainder = (-nm_sample_ct) & (kDoublePerDVec - 1);
3199 ZeroDArr(remainder, &(sample_offsets_buf[nm_sample_ct]));
3200 sample_offsets = sample_offsets_buf;
3201 }
3202 const uint32_t regressed_predictor_ct = domdev_present_p1 + extra_allele_ct;
3203 const uint32_t regressed_predictor_ctav = RoundUpPow2(regressed_predictor_ct, kDoublePerDVec);
3204 if (FirthRegressionD(yy, mean_centered_pmaj_buf, sample_offsets, nm_sample_ct, regressed_predictor_ct, &(beta[1]), is_unfinished_ptr, hh, inv_1d_buf, dbl_2d_buf, pp, vv, ustar, delta, hdiag, ww, hh0_buf, tmpnxk_buf)) {
3205 return 1;
3206 }
3207 // hh is shifted up and to the left from what the caller expects, due to the
3208 // missing intercept. Correct that here.
3209 const uint32_t expected_predictor_ctav = RoundUpPow2(regressed_predictor_ct + 1, kDoublePerDVec);
3210 for (uint32_t write_row_idx = regressed_predictor_ct; write_row_idx; --write_row_idx) {
3211 memcpy(&(hh[write_row_idx * expected_predictor_ctav + 1]), &(hh[(write_row_idx - 1) * regressed_predictor_ctav]), regressed_predictor_ct * sizeof(double));
3212 }
3213 return 0;
3214 }
3215
3216 BoolErr GlmAllocFillAndTestPhenoCovarsCc(const uintptr_t* sample_include, const uintptr_t* pheno_cc, const uintptr_t* covar_include, const PhenoCol* covar_cols, const char* covar_names, uintptr_t sample_ct, uint32_t domdev_present_p1, 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, GlmFlags glm_flags, uintptr_t** pheno_cc_collapsed_ptr, uintptr_t** gcount_case_interleaved_vec_ptr, float** pheno_f_ptr, double** pheno_d_ptr, RegressionNmPrecomp** nm_precomp_ptr, float** covars_cmaj_f_ptr, double** covars_cmaj_d_ptr, CcResidualizeCtx** cc_residualize_ptr, const char*** cur_covar_names_ptr, GlmErr* glm_err_ptr) {
3217 const uint32_t is_single_prec = (glm_flags / kfGlmSinglePrecCc) & 1;
3218 const uintptr_t sample_ctav = is_single_prec? RoundUpPow2(sample_ct, kFloatPerFVec) : RoundUpPow2(sample_ct, kDoublePerDVec);
3219 const uintptr_t new_covar_ct = covar_ct + extra_cat_ct;
3220 const uintptr_t new_nonlocal_covar_ct = new_covar_ct - local_covar_ct;
3221 const uint32_t sample_ctv = BitCtToVecCt(sample_ct);
3222 const uint32_t is_cc_residualize = !!(glm_flags & (kfGlmFirthResidualize | kfGlmCcResidualize));
3223 if (unlikely(bigstack_alloc_w(sample_ctv * kWordsPerVec, pheno_cc_collapsed_ptr) ||
3224 bigstack_alloc_kcp(new_covar_ct, cur_covar_names_ptr))) {
3225 return 1;
3226 }
3227 if (is_single_prec) {
3228 if (unlikely(bigstack_alloc_f(sample_ctav, pheno_f_ptr) ||
3229 bigstack_alloc_f(new_nonlocal_covar_ct * sample_ctav, covars_cmaj_f_ptr))) {
3230 return 1;
3231 }
3232 } else {
3233 if (unlikely(bigstack_alloc_d(sample_ctav, pheno_d_ptr))) {
3234 return 1;
3235 }
3236 }
3237 if (is_cc_residualize) {
3238 assert(!local_covar_ct);
3239 // Interactions and local covariates prohibited with firth-residualize,
3240 // so xtx_state guaranteed to be nonzero.
3241 if (unlikely(BIGSTACK_ALLOC_X(CcResidualizeCtx, 1, cc_residualize_ptr))) {
3242 return 1;
3243 }
3244 (*cc_residualize_ptr)->logistic_nm_sample_offsets_f = nullptr;
3245 (*cc_residualize_ptr)->firth_nm_sample_offsets_f = nullptr;
3246 (*cc_residualize_ptr)->logistic_nm_sample_offsets_d = nullptr;
3247 (*cc_residualize_ptr)->firth_nm_sample_offsets_d = nullptr;
3248 if ((glm_flags & (kfGlmFirth | kfGlmCcResidualize)) == kfGlmCcResidualize) {
3249 if (is_single_prec) {
3250 if (unlikely(bigstack_alloc_f(sample_ctav, &((*cc_residualize_ptr)->logistic_nm_sample_offsets_f)))) {
3251 return 1;
3252 }
3253 } else {
3254 if (unlikely(bigstack_alloc_d(sample_ctav, &((*cc_residualize_ptr)->logistic_nm_sample_offsets_d)))) {
3255 return 1;
3256 }
3257 }
3258 }
3259 if (!(glm_flags & kfGlmNoFirth)) {
3260 if (is_single_prec) {
3261 if (unlikely(bigstack_alloc_f(sample_ctav, &((*cc_residualize_ptr)->firth_nm_sample_offsets_f)))) {
3262 return 1;
3263 }
3264 } else {
3265 if (unlikely(bigstack_alloc_d(sample_ctav, &((*cc_residualize_ptr)->firth_nm_sample_offsets_d)))) {
3266 return 1;
3267 }
3268 }
3269 }
3270 (*cc_residualize_ptr)->prefitted_pred_ct = 1 + new_covar_ct;
3271 (*cc_residualize_ptr)->domdev_present_p1 = domdev_present_p1;
3272 (*cc_residualize_ptr)->sample_ct = sample_ct;
3273 }
3274 double* corr_buf = nullptr;
3275 unsigned char* bigstack_mark = g_bigstack_base;
3276 *nm_precomp_ptr = nullptr;
3277 if (xtx_state) {
3278 if (unlikely(BIGSTACK_ALLOC_X(RegressionNmPrecomp, 1, nm_precomp_ptr))) {
3279 return 1;
3280 }
3281 // x^2 + (2*xtx_state + 2)x + (5*xtx_state - 1)
3282 // 2x^2 + (2*xtx_state + 2)x + (5*xtx_state - 1)
3283 // 3x^2 + (4*xtx_state + 2)x + (8*xtx_state - 3)
3284 // 3x^2 + (4*xtx_state + 3)x + (8*xtx_state - 3)
3285 if (unlikely(bigstack_alloc_d(8 * xtx_state - 3 +
3286 new_covar_ct * (3 + 4 * xtx_state + 3 * new_covar_ct),
3287 &((*nm_precomp_ptr)->xtx_image)) ||
3288 bigstack_alloc_d(new_covar_ct * (new_covar_ct + 1), &corr_buf))) {
3289 return 1;
3290 }
3291 (*nm_precomp_ptr)->covarx_dotprod_inv = nullptr;
3292 (*nm_precomp_ptr)->corr_inv = &((*nm_precomp_ptr)->xtx_image[(new_covar_ct + xtx_state + 1) * (new_covar_ct + xtx_state + 1)]);
3293 (*nm_precomp_ptr)->corr_image = &((*nm_precomp_ptr)->corr_inv[new_covar_ct * new_covar_ct]);
3294 (*nm_precomp_ptr)->corr_inv_sqrts = &((*nm_precomp_ptr)->corr_image[(new_covar_ct + xtx_state) * (new_covar_ct + xtx_state)]);
3295 (*nm_precomp_ptr)->xt_y_image = nullptr;
3296 bigstack_mark = R_CAST(unsigned char*, corr_buf);
3297 }
3298
3299 double* covars_cmaj_d;
3300 double* covar_dotprod;
3301 double* inverse_corr_buf;
3302 if (unlikely(bigstack_alloc_d(new_nonlocal_covar_ct * sample_ct, &covars_cmaj_d) ||
3303 bigstack_alloc_d(new_nonlocal_covar_ct * new_nonlocal_covar_ct, &covar_dotprod) ||
3304 bigstack_alloc_d(new_nonlocal_covar_ct * new_nonlocal_covar_ct, &inverse_corr_buf))) {
3305 return 1;
3306 }
3307 if (!is_single_prec) {
3308 *covars_cmaj_d_ptr = covars_cmaj_d;
3309 bigstack_mark = R_CAST(unsigned char*, covar_dotprod);
3310 }
3311 uintptr_t* pheno_cc_collapsed = *pheno_cc_collapsed_ptr;
3312 CopyBitarrSubset(pheno_cc, sample_include, sample_ct, pheno_cc_collapsed);
3313 const uint32_t sample_remv = sample_ctav - sample_ct;
3314 if (is_single_prec) {
3315 float* pheno_f_iter = *pheno_f_ptr;
3316 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3317 // can use the bitvector equivalent of GenoarrLookup...(), but this isn't
3318 // in a critical loop so I'll postpone writing those functions for now
3319 *pheno_f_iter++ = kSmallFloats[IsSet(pheno_cc_collapsed, sample_idx)];
3320 }
3321 ZeroFArr(sample_remv, pheno_f_iter);
3322 } else {
3323 double* pheno_d_iter = *pheno_d_ptr;
3324 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3325 *pheno_d_iter++ = kSmallDoubles[IsSet(pheno_cc_collapsed, sample_idx)];
3326 }
3327 ZeroDArr(sample_remv, pheno_d_iter);
3328 }
3329 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, *cur_covar_names_ptr, glm_err_ptr);
3330 if (unlikely(reterr)) {
3331 return (reterr == kPglRetNomem);
3332 }
3333 if (is_single_prec) {
3334 double* covar_read_iter = covars_cmaj_d;
3335 float* covar_write_iter = *covars_cmaj_f_ptr;
3336 for (uintptr_t covar_idx = 0; covar_idx != new_nonlocal_covar_ct; ++covar_idx) {
3337 for (uintptr_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
3338 *covar_write_iter++ = S_CAST(float, *covar_read_iter++);
3339 }
3340 ZeroFArr(sample_remv, covar_write_iter);
3341 covar_write_iter = &(covar_write_iter[sample_remv]);
3342 }
3343 }
3344 if (xtx_state) {
3345 // error-out should be impossible
3346 InitNmPrecomp(covars_cmaj_d, covar_dotprod, corr_buf, inverse_corr_buf, sample_ct, 0, new_covar_ct, xtx_state, *nm_precomp_ptr);
3347 if (is_cc_residualize) {
3348 BigstackReset(bigstack_mark);
3349 const uintptr_t pred_ct = new_covar_ct + 1;
3350 const uintptr_t pred_ctav = RoundUpPow2(pred_ct, kFloatPerFVec);
3351 double* dbl_2d_buf;
3352 if (is_single_prec) {
3353 float* xx;
3354 float* coefs;
3355 float* hh;
3356 double* half_inverted_buf;
3357 float* ll;
3358 float* pp;
3359 float* vv;
3360 float* grad;
3361 float* dcoef;
3362 float* hdiag;
3363 float* ww;
3364 float* hh0_buf;
3365 float* tmpnxk_buf;
3366 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, bigstack_alloc(pred_ct * kMatrixInvertBuf1CheckedAlloc));
3367 // see GetLogisticWorkspaceSizeF() and corresponding code at top of
3368 // GlmLogisticThread{F,D}()
3369 if (unlikely((!inv_1d_buf) ||
3370 bigstack_alloc_f(sample_ctav * pred_ct, &xx) ||
3371 bigstack_calloc_f(pred_ctav, &coefs) ||
3372 bigstack_alloc_f(pred_ct * pred_ctav, &hh) ||
3373 bigstack_alloc_d(pred_ct * MAXV(pred_ct, 3), &half_inverted_buf) ||
3374 bigstack_alloc_d(pred_ct * MAXV(pred_ct, 7), &dbl_2d_buf) ||
3375 bigstack_alloc_f(pred_ct * pred_ctav, &ll) ||
3376 bigstack_alloc_f(sample_ctav, &pp) ||
3377 bigstack_alloc_f(sample_ctav, &vv) ||
3378 bigstack_alloc_f(pred_ctav, &grad) ||
3379 bigstack_alloc_f(pred_ctav, &dcoef) ||
3380 bigstack_alloc_f(sample_ctav, &hdiag) ||
3381 bigstack_alloc_f(sample_ctav, &ww) ||
3382 bigstack_alloc_f(pred_ct * pred_ctav, &hh0_buf) ||
3383 bigstack_alloc_f(sample_ctav * pred_ct, &tmpnxk_buf))) {
3384 return 1;
3385 }
3386 FillFVec(sample_ct, 1.0, xx);
3387 memcpy(&(xx[sample_ctav]), *covars_cmaj_f_ptr, sample_ctav * (pred_ct - 1) * sizeof(float));
3388 uint32_t is_unfinished = 0;
3389 float* logistic_nm_sample_offsets_f = (*cc_residualize_ptr)->logistic_nm_sample_offsets_f;
3390 if (logistic_nm_sample_offsets_f) {
3391 if (unlikely(LogisticRegressionF(*pheno_f_ptr, xx, nullptr, sample_ct, pred_ct, coefs, &is_unfinished, ll, pp, vv, hh, grad, dcoef) || is_unfinished)) {
3392 if (glm_flags & kfGlmNoFirth) {
3393 *glm_err_ptr = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
3394 return 0;
3395 }
3396 (*cc_residualize_ptr)->logistic_nm_sample_offsets_f = nullptr;
3397 }
3398 ColMajorFmatrixVectorMultiplyStrided(xx, coefs, sample_ct, sample_ctav, pred_ct, logistic_nm_sample_offsets_f);
3399 ZeroFArr(sample_ctav - sample_ct, &(logistic_nm_sample_offsets_f[sample_ct]));
3400 ZeroFArr(pred_ctav, coefs);
3401 }
3402 float* firth_nm_sample_offsets_f = (*cc_residualize_ptr)->firth_nm_sample_offsets_f;
3403 if (firth_nm_sample_offsets_f) {
3404 if (unlikely(FirthRegressionF(*pheno_f_ptr, xx, nullptr, sample_ct, pred_ct, coefs, &is_unfinished, hh, half_inverted_buf, inv_1d_buf, dbl_2d_buf, pp, vv, grad, dcoef, hdiag, ww, hh0_buf, tmpnxk_buf) || is_unfinished)) {
3405 *glm_err_ptr = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
3406 return 0;
3407 }
3408 ColMajorFmatrixVectorMultiplyStrided(xx, coefs, sample_ct, sample_ctav, pred_ct, firth_nm_sample_offsets_f);
3409 ZeroFArr(sample_ctav - sample_ct, &(firth_nm_sample_offsets_f[sample_ct]));
3410 }
3411 } else {
3412 double* xx;
3413 double* coefs;
3414 double* hh;
3415 double* ll;
3416 double* pp;
3417 double* vv;
3418 double* grad;
3419 double* dcoef;
3420 double* hdiag;
3421 double* ww;
3422 double* hh0_buf;
3423 double* tmpnxk_buf;
3424 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, bigstack_alloc(pred_ct * kMatrixInvertBuf1CheckedAlloc));
3425 if (unlikely((!inv_1d_buf) ||
3426 bigstack_alloc_d(sample_ctav * pred_ct, &xx) ||
3427 bigstack_alloc_d(pred_ctav, &coefs) ||
3428 bigstack_alloc_d(pred_ct * pred_ctav, &hh) ||
3429 bigstack_alloc_d(pred_ct * MAXV(pred_ct, 7), &dbl_2d_buf) ||
3430 bigstack_alloc_d(pred_ct * pred_ctav, &ll) ||
3431 bigstack_alloc_d(sample_ctav, &pp) ||
3432 bigstack_alloc_d(sample_ctav, &vv) ||
3433 bigstack_alloc_d(pred_ctav, &grad) ||
3434 bigstack_alloc_d(pred_ctav, &dcoef) ||
3435 bigstack_alloc_d(sample_ctav, &hdiag) ||
3436 bigstack_alloc_d(sample_ctav, &ww) ||
3437 bigstack_alloc_d(pred_ct * pred_ctav, &hh0_buf) ||
3438 bigstack_alloc_d(sample_ctav * pred_ct, &tmpnxk_buf))) {
3439 return 1;
3440 }
3441 FillDVec(sample_ct, 1.0, xx);
3442 for (uintptr_t pred_idx = 1; pred_idx != pred_ct; ++pred_idx) {
3443 double* write_row_start = &(xx[sample_ctav * pred_idx]);
3444 memcpy(write_row_start, &(covars_cmaj_d[sample_ct * (pred_idx - 1)]), sample_ct * sizeof(double));
3445 ZeroDArr(sample_ctav - sample_ct, &(write_row_start[sample_ct]));
3446 }
3447 uint32_t is_unfinished = 0;
3448 double* logistic_nm_sample_offsets_d = (*cc_residualize_ptr)->logistic_nm_sample_offsets_d;
3449 if (logistic_nm_sample_offsets_d) {
3450 if (unlikely(LogisticRegressionD(*pheno_d_ptr, xx, nullptr, sample_ct, pred_ct, &is_unfinished, coefs, ll, pp, vv, hh, grad, dcoef, inv_1d_buf, dbl_2d_buf) || is_unfinished)) {
3451 if (glm_flags & kfGlmNoFirth) {
3452 *glm_err_ptr = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
3453 return 0;
3454 }
3455 (*cc_residualize_ptr)->logistic_nm_sample_offsets_d = nullptr;
3456 }
3457 ColMajorMatrixVectorMultiplyStrided(xx, coefs, sample_ct, sample_ctav, pred_ct, logistic_nm_sample_offsets_d);
3458 ZeroDArr(sample_ctav - sample_ct, &(logistic_nm_sample_offsets_d[sample_ct]));
3459 }
3460 double* firth_nm_sample_offsets_d = (*cc_residualize_ptr)->firth_nm_sample_offsets_d;
3461 if (firth_nm_sample_offsets_d) {
3462 ZeroDArr(pred_ctav, coefs);
3463 if (unlikely(FirthRegressionD(*pheno_d_ptr, xx, nullptr, sample_ct, pred_ct, coefs, &is_unfinished, hh, inv_1d_buf, dbl_2d_buf, pp, vv, grad, dcoef, hdiag, ww, hh0_buf, tmpnxk_buf) || is_unfinished)) {
3464 *glm_err_ptr = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
3465 return 0;
3466 }
3467 ColMajorMatrixVectorMultiplyStrided(xx, coefs, sample_ct, sample_ctav, pred_ct, firth_nm_sample_offsets_d);
3468 ZeroDArr(sample_ctav - sample_ct, &(firth_nm_sample_offsets_d[sample_ct]));
3469 }
3470 }
3471 // probable todo: print fitted coefficients and standard errors to log
3472 }
3473 }
3474 BigstackReset(bigstack_mark);
3475 if (gcount_case_interleaved_vec_ptr) {
3476 if (unlikely(bigstack_alloc_w(sample_ctv * kWordsPerVec, gcount_case_interleaved_vec_ptr))) {
3477 return 1;
3478 }
3479 ZeroTrailingWords(BitCtToWordCt(sample_ct), pheno_cc_collapsed);
3480 FillInterleavedMaskVec(pheno_cc_collapsed, sample_ctv, *gcount_case_interleaved_vec_ptr);
3481 }
3482 return 0;
3483 }
3484
3485 uintptr_t GetLogisticWorkspaceSizeD(uint32_t sample_ct, uint32_t biallelic_predictor_ct, uint32_t domdev_present_p1, uint32_t max_extra_allele_ct, uint32_t constraint_ct, uint32_t xmain_ct, uint32_t gcount_cc, uint32_t is_sometimes_firth, uint32_t is_cc_residualize) {
3486 // sample_ctav * max_predictor_ct < 2^31, and sample_ct >=
3487 // biallelic_predictor_ct, so no overflows?
3488 // could round everything up to multiples of 16 instead of 64
3489 const uint32_t max_predictor_ct = biallelic_predictor_ct + max_extra_allele_ct;
3490 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
3491 const uint32_t max_predictor_ctav = RoundUpPow2(max_predictor_ct, kDoublePerDVec);
3492 // sample_nm, pheno_cc_nm, tmp_nm = sample_ctl words
3493 uintptr_t workspace_size = 3 * RoundUpPow2(BitCtToWordCt(sample_ct) * sizeof(intptr_t), kCacheline);
3494
3495 // yy = sample_ctav doubles
3496 workspace_size += RoundUpPow2(sample_ctav * sizeof(double), kCacheline);
3497
3498 // xx = (max_predictor_ct + main_mutated + main_omitted) * sample_ctav
3499 // doubles
3500 workspace_size += RoundUpPow2((max_predictor_ct + xmain_ct) * sample_ctav * sizeof(double), kCacheline);
3501
3502 // hh = max_predictor_ct * max_predictor_ctav doubles
3503 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(double), kCacheline);
3504
3505 // pp, vv = sample_ctav doubles
3506 workspace_size += 2 * RoundUpPow2(sample_ctav * sizeof(double), kCacheline);
3507
3508 // coef, grad, dcoef = max_predictor_ctav doubles
3509 workspace_size += 3 * RoundUpPow2(max_predictor_ctav * sizeof(double), kCacheline);
3510
3511 // ll = max_predictor_ct * max_predictor_ctav doubles
3512 // (technically not needed in pure-Firth case)
3513 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(double), kCacheline);
3514
3515 // semicomputed_biallelic_xtx
3516 workspace_size += RoundUpPow2(biallelic_predictor_ct * biallelic_predictor_ct * sizeof(double), kCacheline);
3517
3518 // semicomputed_biallelic_corr_matrix
3519 workspace_size += RoundUpPow2((biallelic_predictor_ct - 1) * (biallelic_predictor_ct - 1) * sizeof(double), kCacheline);
3520
3521 // semicomputed_biallelic_inv_corr_sqrts
3522 workspace_size += RoundUpPow2(biallelic_predictor_ct * sizeof(double), kCacheline);
3523
3524 // inv_1d_buf
3525 workspace_size += RoundUpPow2(max_predictor_ct * kMatrixInvertBuf1CheckedAlloc, kCacheline);
3526
3527 // dbl_2d_buf = max_predictor_ct * max_predictor_ct doubles, or VIF/Firth
3528 // (which can be max_predictor_ct * 7 doubles)
3529 workspace_size += RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
3530
3531 // a1_dosages, a1_case_dosages
3532 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(double) * 2, kCacheline);
3533
3534 // machr2_dosage_sums, machr2_dosage_ssqs
3535 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(uint64_t) * 2, kCacheline);
3536
3537 if (gcount_cc && max_extra_allele_ct) {
3538 // case_one_cts, case_two_cts
3539 workspace_size += RoundUpPow2((2 + max_extra_allele_ct) * sizeof(int32_t) * 2, kCacheline);
3540 }
3541
3542 // predictor_dotprod_buf
3543 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ct * sizeof(double), kCacheline);
3544
3545 const uintptr_t other_2d_byte_ct = max_predictor_ct * MAXV(max_predictor_ct, 3) * sizeof(double);
3546 // inverse_corr_buf/half_inverted_buf
3547 workspace_size += RoundUpPow2(other_2d_byte_ct, kCacheline);
3548
3549 if (is_sometimes_firth) {
3550 // hdiag, ww = sample_ctav doubles
3551 workspace_size += 2 * RoundUpPow2(sample_ctav * sizeof(double), kCacheline);
3552
3553 // hh0 = max_predictor_ct * max_predictor_ctav doubles
3554 workspace_size += RoundUpPow2(max_predictor_ct * max_predictor_ctav * sizeof(double), kCacheline);
3555
3556 // tmpnxk_buf = max_predictor_ct * sample_ctav doubles
3557 workspace_size += RoundUpPow2(max_predictor_ct * sample_ctav * sizeof(double), kCacheline);
3558 }
3559 if (is_cc_residualize) {
3560 // mean_centered_pmaj_buf = (domdev_present_p1 + max_extra_allele_ct) *
3561 // sample_ctav doubles
3562 workspace_size += RoundUpPow2((domdev_present_p1 + max_extra_allele_ct) * sample_ctav * sizeof(double), kCacheline);
3563
3564 // sample_offsets_buf
3565 workspace_size += RoundUpPow2(sample_ctav * sizeof(double), kCacheline);
3566 }
3567 if (constraint_ct) {
3568 // tmphxs_buf, h_transpose_buf = constraint_ct * max_predictor_ctav doubles
3569 workspace_size += 2 * RoundUpPow2(constraint_ct * max_predictor_ctav * sizeof(double), kCacheline);
3570
3571 // inner_buf = constraint_ct * constraint_ct
3572 workspace_size += RoundUpPow2(constraint_ct * constraint_ct * sizeof(double), kCacheline);
3573
3574 // outer_buf = constraint_ct
3575 workspace_size += RoundUpPow2(constraint_ct * sizeof(double), kCacheline);
3576
3577 // constraints_con_major = constraint_ct * max_predictor_ct
3578 workspace_size += RoundUpPow2(constraint_ct * max_predictor_ct * sizeof(double), kCacheline);
3579 }
3580 return workspace_size;
3581 }
3582
3583
3584 THREAD_FUNC_DECL GlmLogisticThreadD(void* raw_arg) {
3585 ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg);
3586 const uintptr_t tidx = arg->tidx;
3587 GlmLogisticCtx* ctx = S_CAST(GlmLogisticCtx*, arg->sharedp->context);
3588 GlmCtx* common = ctx->common;
3589
3590 PgenReader* pgrp = common->pgr_ptrs[tidx];
3591 PgenVariant pgv;
3592 pgv.genovec = common->genovecs[tidx];
3593 pgv.dosage_present = nullptr;
3594 pgv.dosage_main = nullptr;
3595 if (common->dosage_presents) {
3596 pgv.dosage_present = common->dosage_presents[tidx];
3597 pgv.dosage_main = common->dosage_mains[tidx];
3598 }
3599 unsigned char* workspace_buf = common->workspace_bufs[tidx];
3600 const uintptr_t* variant_include = common->variant_include;
3601 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
3602 const AlleleCode* omitted_alleles = common->omitted_alleles;
3603 const uintptr_t* sex_male_collapsed = common->sex_male_collapsed;
3604 const ChrInfo* cip = common->cip;
3605 const uint32_t* subset_chr_fo_vidx_start = common->subset_chr_fo_vidx_start;
3606 const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp);
3607 const GlmFlags glm_flags = common->glm_flags;
3608 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
3609 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
3610 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
3611 const uint32_t is_sometimes_firth = !(glm_flags & kfGlmNoFirth);
3612 const uint32_t is_always_firth = (glm_flags / kfGlmFirth) & 1;
3613 const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
3614 const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
3615 const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
3616 const uint32_t joint_genotypic = (glm_flags / kfGlmGenotypic) & 1;
3617 const uint32_t joint_hethom = (glm_flags / kfGlmHethom) & 1;
3618 const double max_corr = common->max_corr;
3619 const double vif_thresh = common->vif_thresh;
3620 const uint32_t domdev_present = joint_genotypic || joint_hethom;
3621 const uint32_t domdev_present_p1 = domdev_present + 1;
3622 const uint32_t reported_pred_uidx_start = 1 - include_intercept;
3623 const uint32_t x_code = cip->xymt_codes[kChrOffsetX];
3624 const uint32_t y_code = cip->xymt_codes[kChrOffsetY];
3625 const uint32_t is_xchr_model_1 = common->is_xchr_model_1;
3626 const uintptr_t max_reported_test_ct = common->max_reported_test_ct;
3627 const uintptr_t local_covar_ct = common->local_covar_ct;
3628 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
3629 // bugfix (20 Mar 2020): Also need to exclude dominant/recessive.
3630 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!model_dominant) && (!model_recessive) && (!model_hetonly) && (!common->tests_flag) && (!add_interactions);
3631 uintptr_t max_sample_ct = MAXV(common->sample_ct, common->sample_ct_x);
3632 if (max_sample_ct < common->sample_ct_y) {
3633 max_sample_ct = common->sample_ct_y;
3634 }
3635 SetPgvThreadMhcNull(max_sample_ct, tidx, common->thread_mhc, &pgv);
3636 pgv.patch_01_ct = 0;
3637 pgv.patch_10_ct = 0;
3638 pgv.multidosage_sample_ct = 0;
3639 uint32_t variant_idx_offset = 0;
3640 uint32_t allele_ct = 2;
3641 uint32_t omitted_allele_idx = 0;
3642 uint32_t extra_regression_ct = 0;
3643 double main_dosage_sum = 0.0;
3644 double main_dosage_ssq = 0.0;
3645 uint32_t parity = 0;
3646 uint64_t new_err_info = 0;
3647 do {
3648 const uintptr_t cur_block_variant_ct = common->cur_block_variant_ct;
3649 uint32_t variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct;
3650 const uint32_t variant_bidx_end = ((tidx + 1) * cur_block_variant_ct) / calc_thread_ct;
3651 uintptr_t variant_uidx_base;
3652 uintptr_t variant_include_bits;
3653 BitIter1Start(variant_include, common->read_variant_uidx_starts[tidx], &variant_uidx_base, &variant_include_bits);
3654
3655 double* beta_se_iter = common->block_beta_se;
3656 uintptr_t allele_bidx = variant_bidx;
3657 if (max_extra_allele_ct) {
3658 allele_bidx = variant_bidx + CountExtraAlleles(variant_include, allele_idx_offsets, common->read_variant_uidx_starts[0], common->read_variant_uidx_starts[tidx], 0);
3659 }
3660 if (beta_se_multiallelic_fused) {
3661 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * variant_bidx]);
3662 } else {
3663 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct * allele_bidx]);
3664 }
3665
3666 LogisticAuxResult* block_aux_iter = &(ctx->block_aux[allele_bidx]);
3667 const double* local_covars_iter = nullptr;
3668 if (local_covar_ct) {
3669 local_covars_iter = &(ctx->local_covars_vcmaj_d[parity][variant_bidx * max_sample_ct * local_covar_ct]);
3670 }
3671 while (variant_bidx < variant_bidx_end) {
3672 const uint32_t variant_idx = variant_bidx + variant_idx_offset;
3673 const uint32_t chr_fo_idx = LastLeqU32(subset_chr_fo_vidx_start, 0, cip->chr_ct, variant_idx);
3674 // const uint32_t chr_fo_idx = LowerBoundNonemptyU32(&(subset_chr_fo_vidx_start[1]), cip->chr_ct, variant_idx + 1);
3675 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
3676 uint32_t cur_variant_bidx_end = subset_chr_fo_vidx_start[chr_fo_idx + 1] - variant_idx_offset;
3677 if (cur_variant_bidx_end > variant_bidx_end) {
3678 cur_variant_bidx_end = variant_bidx_end;
3679 }
3680 // "regular" = not all-female special case.
3681 const uint32_t is_haploid = IsSet(cip->haploid_mask, chr_idx);
3682 const uint32_t is_regular_x = is_haploid && (chr_idx == x_code);
3683 const uint32_t is_y = (chr_idx == y_code);
3684 const uint32_t is_nonx_haploid = is_haploid && (!is_regular_x);
3685 const uintptr_t* cur_sample_include;
3686 const uint32_t* cur_sample_include_cumulative_popcounts;
3687 const uintptr_t* cur_pheno_cc;
3688 const uintptr_t* cur_gcount_case_interleaved_vec;
3689 const double* cur_pheno;
3690 const RegressionNmPrecomp* nm_precomp;
3691 const double* cur_covars_cmaj;
3692 const uintptr_t* cur_parameter_subset;
3693 const uintptr_t* cur_joint_test_params;
3694 const CcResidualizeCtx* cur_cc_residualize;
3695 uint32_t cur_sample_ct;
3696 uint32_t cur_covar_ct;
3697 uint32_t cur_constraint_ct;
3698 uint32_t cur_is_always_firth;
3699 if (is_y && common->sample_include_y) {
3700 cur_sample_include = common->sample_include_y;
3701 cur_sample_include_cumulative_popcounts = common->sample_include_y_cumulative_popcounts;
3702 cur_pheno_cc = ctx->pheno_y_cc;
3703 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec_y;
3704 cur_pheno = ctx->pheno_y_d;
3705 nm_precomp = common->nm_precomp_y;
3706 cur_covars_cmaj = ctx->covars_cmaj_y_d;
3707 cur_parameter_subset = common->parameter_subset_y;
3708 cur_joint_test_params = common->joint_test_params_y;
3709 cur_cc_residualize = ctx->cc_residualize_y;
3710 cur_sample_ct = common->sample_ct_y;
3711 cur_covar_ct = common->covar_ct_y;
3712 cur_constraint_ct = common->constraint_ct_y;
3713 cur_is_always_firth = is_always_firth || ctx->separation_found_y;
3714 } else if (is_regular_x && common->sample_include_x) {
3715 cur_sample_include = common->sample_include_x;
3716 cur_sample_include_cumulative_popcounts = common->sample_include_x_cumulative_popcounts;
3717 cur_pheno_cc = ctx->pheno_x_cc;
3718 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec_x;
3719 cur_pheno = ctx->pheno_x_d;
3720 nm_precomp = common->nm_precomp_x;
3721 cur_covars_cmaj = ctx->covars_cmaj_x_d;
3722 cur_parameter_subset = common->parameter_subset_x;
3723 cur_joint_test_params = common->joint_test_params_x;
3724 cur_cc_residualize = ctx->cc_residualize_x;
3725 cur_sample_ct = common->sample_ct_x;
3726 cur_covar_ct = common->covar_ct_x;
3727 cur_constraint_ct = common->constraint_ct_x;
3728 cur_is_always_firth = is_always_firth || ctx->separation_found_x;
3729 } else {
3730 cur_sample_include = common->sample_include;
3731 cur_sample_include_cumulative_popcounts = common->sample_include_cumulative_popcounts;
3732 cur_pheno_cc = ctx->pheno_cc;
3733 cur_gcount_case_interleaved_vec = ctx->gcount_case_interleaved_vec;
3734 cur_pheno = ctx->pheno_d;
3735 nm_precomp = common->nm_precomp;
3736 cur_covars_cmaj = ctx->covars_cmaj_d;
3737 cur_parameter_subset = common->parameter_subset;
3738 cur_joint_test_params = common->joint_test_params;
3739 cur_cc_residualize = ctx->cc_residualize;
3740 cur_sample_ct = common->sample_ct;
3741 cur_covar_ct = common->covar_ct;
3742 cur_constraint_ct = common->constraint_ct;
3743 cur_is_always_firth = is_always_firth || ctx->separation_found;
3744 }
3745 const uint32_t sample_ctl = BitCtToWordCt(cur_sample_ct);
3746 const uint32_t sample_ctav = RoundUpPow2(cur_sample_ct, kDoublePerDVec);
3747 const uint32_t cur_case_ct = PopcountWords(cur_pheno_cc, sample_ctl);
3748 const uint32_t cur_biallelic_predictor_ct_base = 2 + domdev_present + cur_covar_ct * (1 + add_interactions * domdev_present_p1);
3749 uint32_t cur_biallelic_predictor_ct = cur_biallelic_predictor_ct_base;
3750 uint32_t literal_covar_ct = cur_covar_ct;
3751 if (cur_parameter_subset) {
3752 cur_biallelic_predictor_ct = PopcountWords(cur_parameter_subset, BitCtToWordCt(cur_biallelic_predictor_ct_base));
3753 literal_covar_ct = PopcountBitRange(cur_parameter_subset, 2 + domdev_present, 2 + domdev_present + cur_covar_ct);
3754 }
3755 const uint32_t max_predictor_ct = cur_biallelic_predictor_ct + max_extra_allele_ct;
3756 const uint32_t max_predictor_ctav = RoundUpPow2(max_predictor_ct, kDoublePerDVec);
3757 uint32_t reported_pred_uidx_biallelic_end;
3758 if (hide_covar) {
3759 if (!cur_parameter_subset) {
3760 reported_pred_uidx_biallelic_end = 2 + domdev_present;
3761 } else {
3762 reported_pred_uidx_biallelic_end = 1 + IsSet(cur_parameter_subset, 1) + domdev_present;
3763 }
3764 } else {
3765 reported_pred_uidx_biallelic_end = cur_biallelic_predictor_ct;
3766 }
3767 // nm_predictors_pmaj_buf may require up to two extra columns omitted
3768 // from the main regression.
3769 // 1. In the multiallelic dominant/recessive/hetonly/hethom cases, the
3770 // original genotype column does not appear in the regression, and
3771 // we'd rather not reconstruct it from genovec, etc. when we need to
3772 // swap it out for another allele, so we keep the original genotype in
3773 // an extra column.
3774 // To reduce code bloat, we now handle the biallelic cases in the same
3775 // way; this is one of the more peripheral code paths so adding more
3776 // complexity to speed it up is less justifiable.
3777 // 2. If --parameters excludes the main (possibly
3778 // dominant/recessive/hetonly) genotype column but does care about an
3779 // interaction, we want a copy of what the main genotype column's
3780 // contents would have been to refer to.
3781 const uint32_t main_omitted = cur_parameter_subset && (!IsSet(cur_parameter_subset, 1));
3782 const uint32_t main_mutated = model_dominant || model_recessive || model_hetonly || joint_hethom;
3783 unsigned char* workspace_iter = workspace_buf;
3784 uintptr_t* sample_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
3785 uintptr_t* pheno_cc_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
3786 uintptr_t* tmp_nm = S_CAST(uintptr_t*, arena_alloc_raw_rd(sample_ctl * sizeof(intptr_t), &workspace_iter));
3787 double* nm_pheno_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3788 double* nm_predictors_pmaj_buf = S_CAST(double*, arena_alloc_raw_rd((max_predictor_ct + main_mutated + main_omitted) * sample_ctav * sizeof(double), &workspace_iter));
3789 double* coef_return = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(double), &workspace_iter));
3790 double* hh_return = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(double), &workspace_iter));
3791 double* pp_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3792 double* sample_variance_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3793 double* gradient_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(double), &workspace_iter));
3794 double* dcoef_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ctav * sizeof(double), &workspace_iter));
3795 double* cholesky_decomp_return = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(double), &workspace_iter));
3796
3797 double* semicomputed_biallelic_xtx = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
3798 // currently overallocates
3799 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));
3800 double* semicomputed_biallelic_inv_corr_sqrts = S_CAST(double*, arena_alloc_raw_rd(cur_biallelic_predictor_ct * sizeof(double), &workspace_iter));
3801
3802 MatrixInvertBuf1* inv_1d_buf = S_CAST(MatrixInvertBuf1*, arena_alloc_raw_rd(max_predictor_ct * kMatrixInvertBuf1CheckedAlloc, &workspace_iter));
3803 const uintptr_t dbl_2d_byte_ct = RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 7) * sizeof(double), kCacheline);
3804 double* dbl_2d_buf = S_CAST(double*, arena_alloc_raw(dbl_2d_byte_ct, &workspace_iter));
3805 double* a1_dosages = S_CAST(double*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(double) * 2, &workspace_iter));
3806 double* a1_case_dosages = &(a1_dosages[max_extra_allele_ct + 2]);
3807 uint64_t* machr2_dosage_sums = S_CAST(uint64_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(uint64_t) * 2, &workspace_iter));
3808 uint64_t* machr2_dosage_ssqs = &(machr2_dosage_sums[max_extra_allele_ct + 2]);
3809 uint32_t* case_one_cts = nullptr;
3810 uint32_t* case_two_cts = nullptr;
3811 if (cur_gcount_case_interleaved_vec && max_extra_allele_ct) {
3812 case_one_cts = S_CAST(uint32_t*, arena_alloc_raw_rd((max_extra_allele_ct + 2) * sizeof(int32_t) * 2, &workspace_iter));
3813 case_two_cts = &(case_one_cts[max_extra_allele_ct + 2]);
3814 }
3815 double* predictor_dotprod_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ct * sizeof(double), &workspace_iter));
3816 const uintptr_t other_2d_byte_ct = RoundUpPow2(max_predictor_ct * MAXV(max_predictor_ct, 3) * sizeof(double), kCacheline);
3817 double* inverse_corr_buf = S_CAST(double*, arena_alloc_raw(other_2d_byte_ct, &workspace_iter));
3818
3819 // these could use the same memory, but not a big deal, use the less
3820 // bug-prone approach for now
3821 // Firth-only
3822 double* hdiag_buf = nullptr;
3823 double* score_buf = nullptr;
3824 double* hh0_buf = nullptr;
3825 double* tmpnxk_buf = nullptr;
3826 if (is_sometimes_firth) {
3827 hdiag_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3828 score_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3829 hh0_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * max_predictor_ctav * sizeof(double), &workspace_iter));
3830 tmpnxk_buf = S_CAST(double*, arena_alloc_raw_rd(max_predictor_ct * sample_ctav * sizeof(double), &workspace_iter));
3831 }
3832 double* mean_centered_pmaj_buf = nullptr;
3833 double* sample_offsets_buf = nullptr;
3834 if (cur_cc_residualize) {
3835 mean_centered_pmaj_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double) * (domdev_present_p1 + max_extra_allele_ct), &workspace_iter));
3836 sample_offsets_buf = S_CAST(double*, arena_alloc_raw_rd(sample_ctav * sizeof(double), &workspace_iter));
3837 }
3838
3839 // joint test only
3840 double* tmphxs_buf = nullptr;
3841 double* h_transpose_buf = nullptr;
3842 double* inner_buf = nullptr;
3843 double* outer_buf = nullptr;
3844 double* cur_constraints_con_major = nullptr;
3845 if (cur_constraint_ct) {
3846 tmphxs_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ctav * sizeof(double), &workspace_iter));
3847 h_transpose_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ctav * sizeof(double), &workspace_iter));
3848 inner_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * cur_constraint_ct * sizeof(double), &workspace_iter));
3849 outer_buf = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * sizeof(double), &workspace_iter));
3850 cur_constraints_con_major = S_CAST(double*, arena_alloc_raw_rd(cur_constraint_ct * max_predictor_ct * sizeof(double), &workspace_iter));
3851 ZeroDArr(cur_constraint_ct * max_predictor_ct, cur_constraints_con_major);
3852 const uint32_t first_joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
3853 cur_constraints_con_major[first_joint_test_idx] = 1.0;
3854 // Rest of this matrix must be updated later, since cur_predictor_ct
3855 // changes at multiallelic variants.
3856 }
3857 assert(S_CAST(uintptr_t, workspace_iter - workspace_buf) == GetLogisticWorkspaceSizeD(cur_sample_ct, cur_biallelic_predictor_ct, domdev_present_p1, max_extra_allele_ct, cur_constraint_ct, main_mutated + main_omitted, cur_gcount_case_interleaved_vec != nullptr, is_sometimes_firth, cur_cc_residualize != nullptr));
3858 const double cur_sample_ct_recip = 1.0 / u31tod(cur_sample_ct);
3859 const double cur_sample_ct_m1_recip = 1.0 / u31tod(cur_sample_ct - 1);
3860 const double* corr_inv = nullptr;
3861 if (nm_precomp) {
3862 memcpy(semicomputed_biallelic_xtx, nm_precomp->xtx_image, cur_biallelic_predictor_ct * cur_biallelic_predictor_ct * sizeof(double));
3863 corr_inv = nm_precomp->corr_inv;
3864 const uintptr_t nongeno_pred_ct = cur_biallelic_predictor_ct - domdev_present - 2;
3865 const uintptr_t nonintercept_biallelic_pred_ct = cur_biallelic_predictor_ct - 1;
3866 memcpy(semicomputed_biallelic_corr_matrix, nm_precomp->corr_image, nonintercept_biallelic_pred_ct * nonintercept_biallelic_pred_ct * sizeof(double));
3867 memcpy(&(semicomputed_biallelic_inv_corr_sqrts[domdev_present_p1]), nm_precomp->corr_inv_sqrts, nongeno_pred_ct * sizeof(double));
3868 }
3869 PgrSampleSubsetIndex pssi;
3870 PgrSetSampleSubsetIndex(cur_sample_include_cumulative_popcounts, pgrp, &pssi);
3871 // when this is set, the last fully-processed variant had no missing
3872 // genotypes, and if the current variant also has no missing genotypes we
3873 // may be able to skip reinitialization of most of
3874 // nm_predictors_pmaj_buf.
3875 // (todo: do we want to track prev_biallelic_nm?)
3876 uint32_t prev_nm = 0;
3877
3878 STD_ARRAY_DECL(uint32_t, 4, genocounts);
3879 for (; variant_bidx != cur_variant_bidx_end; ++variant_bidx) {
3880 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits);
3881 if (allele_idx_offsets) {
3882 allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
3883 if (!beta_se_multiallelic_fused) {
3884 extra_regression_ct = allele_ct - 2;
3885 }
3886 }
3887 const uint32_t allele_ct_m2 = allele_ct - 2;
3888 const uint32_t expected_predictor_ct = cur_biallelic_predictor_ct + allele_ct_m2;
3889 PglErr reterr;
3890 if (!allele_ct_m2) {
3891 reterr = PgrGetD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &(pgv.dosage_ct));
3892 } else {
3893 reterr = PgrGetMD(cur_sample_include, pssi, cur_sample_ct, variant_uidx, pgrp, &pgv);
3894 // todo: proper multiallelic dosage support
3895 }
3896 if (unlikely(reterr)) {
3897 new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr);
3898 goto GlmLogisticThreadD_err;
3899 }
3900 ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
3901 GenoarrCountFreqsUnsafe(pgv.genovec, cur_sample_ct, genocounts);
3902 uint32_t missing_ct = genocounts[3];
3903 if (!missing_ct) {
3904 SetAllBits(cur_sample_ct, sample_nm);
3905 } else {
3906 GenoarrToNonmissing(pgv.genovec, cur_sample_ct, sample_nm);
3907 if (pgv.dosage_ct) {
3908 BitvecOr(pgv.dosage_present, sample_ctl, sample_nm);
3909 missing_ct = cur_sample_ct - PopcountWords(sample_nm, sample_ctl);
3910 }
3911 }
3912 if (omitted_alleles) {
3913 omitted_allele_idx = omitted_alleles[variant_uidx];
3914 }
3915 // Once sizeof(AlleleCode) > 1, we probably want to allocate this from
3916 // g_bigstack instead of the thread stack.
3917 uintptr_t const_alleles[DivUp(kPglMaxAlleleCt, kBitsPerWord)];
3918 const uint32_t allele_ctl = DivUp(allele_ct, kBitsPerWord);
3919 ZeroWArr(allele_ctl, const_alleles);
3920 const uint32_t nm_sample_ct = cur_sample_ct - missing_ct;
3921 const uint32_t nm_sample_ctl = BitCtToWordCt(nm_sample_ct);
3922 const uint32_t nm_sample_ctav = RoundUpPow2(nm_sample_ct, kDoublePerDVec);
3923 const uint32_t nm_sample_ct_rem = nm_sample_ctav - nm_sample_ct;
3924 // first predictor column: intercept
3925 if (!prev_nm) {
3926 FillDVec(nm_sample_ct, 1.0, nm_predictors_pmaj_buf);
3927 }
3928 // second predictor column: genotype
3929 double* genotype_vals = &(nm_predictors_pmaj_buf[nm_sample_ctav]);
3930 if (main_mutated || main_omitted) {
3931 // bugfix (9 Oct 2024)
3932 ZeroDArr(nm_sample_ct_rem, &(genotype_vals[nm_sample_ct]));
3933 genotype_vals = &(nm_predictors_pmaj_buf[expected_predictor_ct * nm_sample_ctav]);
3934 }
3935 CopyBitarrSubset(cur_pheno_cc, sample_nm, nm_sample_ct, pheno_cc_nm);
3936 const uint32_t nm_case_ct = PopcountWords(pheno_cc_nm, nm_sample_ctl);
3937 double* multi_start = nullptr;
3938 if (!allele_ct_m2) {
3939 if (omitted_allele_idx) {
3940 GenovecInvertUnsafe(cur_sample_ct, pgv.genovec);
3941 // ZeroTrailingNyps(cur_sample_ct, pgv.genovec);
3942 if (pgv.dosage_ct) {
3943 BiallelicDosage16Invert(pgv.dosage_ct, pgv.dosage_main);
3944 }
3945 const uint32_t uii = genocounts[0];
3946 genocounts[0] = genocounts[2];
3947 genocounts[2] = uii;
3948 }
3949 uint64_t dosage_sum = (genocounts[1] + 2 * genocounts[2]) * 0x4000LLU;
3950 uint64_t dosage_ssq = (genocounts[1] + 4LLU * genocounts[2]) * 0x10000000LLU;
3951 if (!missing_ct) {
3952 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, genotype_vals);
3953 if (pgv.dosage_ct) {
3954 uintptr_t sample_idx_base = 0;
3955 uintptr_t dosage_present_bits = pgv.dosage_present[0];
3956 for (uint32_t dosage_idx = 0; dosage_idx != pgv.dosage_ct; ++dosage_idx) {
3957 const uintptr_t sample_idx = BitIter1(pgv.dosage_present, &sample_idx_base, &dosage_present_bits);
3958 const uint32_t dosage_val = pgv.dosage_main[dosage_idx];
3959 // 32768 -> 2, 16384 -> 1, 0 -> 0
3960 genotype_vals[sample_idx] = kRecipDosageMid * u31tod(dosage_val);
3961 dosage_sum += dosage_val;
3962 dosage_ssq += dosage_val * dosage_val;
3963 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_idx);
3964 if (cur_geno && (cur_geno != 3)) {
3965 const uintptr_t prev_val = cur_geno * kDosageMid;
3966 dosage_sum -= prev_val;
3967 dosage_ssq -= prev_val * prev_val;
3968 }
3969 }
3970 }
3971 } else {
3972 if (!pgv.dosage_ct) {
3973 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, genotype_vals);
3974 } else {
3975 uintptr_t sample_midx_base = 0;
3976 uintptr_t sample_nm_bits = sample_nm[0];
3977 uint32_t dosage_idx = 0;
3978 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
3979 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
3980 const uintptr_t cur_geno = GetNyparrEntry(pgv.genovec, sample_midx);
3981 double cur_val;
3982 if (IsSet(pgv.dosage_present, sample_midx)) {
3983 const uint32_t dosage_val = pgv.dosage_main[dosage_idx++];
3984 cur_val = kRecipDosageMid * u31tod(dosage_val);
3985 dosage_sum += dosage_val;
3986 dosage_ssq += dosage_val * dosage_val;
3987 if (cur_geno && (cur_geno != 3)) {
3988 const uintptr_t prev_val = cur_geno * kDosageMid;
3989 dosage_sum -= prev_val;
3990 dosage_ssq -= prev_val * prev_val;
3991 }
3992 } else {
3993 // cur_geno != 3 guaranteed
3994 cur_val = kSmallDoubles[cur_geno];
3995 }
3996 genotype_vals[sample_idx] = cur_val;
3997 }
3998 }
3999 }
4000 // Check for constant genotype column.
4001 // (Technically, we should recheck later in the chrX no-sex-covariate
4002 // --xchr-model 1 corner case.)
4003 if (!pgv.dosage_ct) {
4004 if ((genocounts[0] == nm_sample_ct) || (genocounts[1] == nm_sample_ct) || (genocounts[2] == nm_sample_ct)) {
4005 const_alleles[0] = 3;
4006 }
4007 } else if (pgv.dosage_ct == nm_sample_ct) {
4008 if (DosageIsConstant(dosage_sum, dosage_ssq, nm_sample_ct)) {
4009 const_alleles[0] = 3;
4010 }
4011 }
4012 machr2_dosage_sums[1 - omitted_allele_idx] = dosage_sum;
4013 machr2_dosage_ssqs[1 - omitted_allele_idx] = dosage_ssq;
4014 machr2_dosage_sums[omitted_allele_idx] = kDosageMax * S_CAST(uint64_t, nm_sample_ct) - dosage_sum;
4015 machr2_dosage_ssqs[omitted_allele_idx] = kDosageMax * (kDosageMax * S_CAST(uint64_t, nm_sample_ct) - 2 * dosage_sum) + dosage_ssq;
4016 if (cur_gcount_case_interleaved_vec) {
4017 // gcountcc
4018 STD_ARRAY_REF(uint32_t, 6) cur_geno_hardcall_cts = block_aux_iter->geno_hardcall_cts;
4019 GenoarrCountSubsetFreqs(pgv.genovec, cur_gcount_case_interleaved_vec, cur_sample_ct, cur_case_ct, R_CAST(STD_ARRAY_REF(uint32_t, 4), cur_geno_hardcall_cts));
4020 for (uint32_t geno_hardcall_idx = 0; geno_hardcall_idx != 3; ++geno_hardcall_idx) {
4021 cur_geno_hardcall_cts[3 + geno_hardcall_idx] = genocounts[geno_hardcall_idx] - cur_geno_hardcall_cts[geno_hardcall_idx];
4022 }
4023 }
4024 } else {
4025 // multiallelic.
4026 // Update (18 Mar 2020): If some but not all alleles have constant
4027 // dosages, we remove just those alleles from the regressions;
4028 // trim-alts is not necessary to see what's going on with the other
4029 // alleles. To reduce parsing complexity, the number of output lines
4030 // is not affected by this; the ones corresponding to the constant
4031 // alleles have NA values.
4032
4033 // dosage_ct == 0 temporarily guaranteed if we reach here.
4034 assert(!pgv.dosage_ct);
4035 multi_start = &(nm_predictors_pmaj_buf[(expected_predictor_ct - allele_ct_m2) * nm_sample_ctav]);
4036 ZeroU64Arr(allele_ct, machr2_dosage_sums);
4037 ZeroU64Arr(allele_ct, machr2_dosage_ssqs);
4038 // postpone multiply for now, since no multiallelic dosages
4039 // Use sums as ones[] and ssqs as twos[] for rarealts; transform to
4040 // actual sums/ssqs later.
4041 machr2_dosage_sums[0] = genocounts[1];
4042 machr2_dosage_ssqs[0] = genocounts[0];
4043 if (omitted_allele_idx) {
4044 // Main genotype column starts as REF.
4045 if (!missing_ct) {
4046 GenoarrLookup16x8bx2(pgv.genovec, kSmallInvDoublePairs, nm_sample_ct, genotype_vals);
4047 } else {
4048 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallInvDoubles, cur_sample_ct, genotype_vals);
4049 }
4050 }
4051 uint32_t rare_allele_ct = allele_ct_m2;
4052 double* alt1_start = nullptr;
4053 double* rarealt_start = multi_start;
4054 if (omitted_allele_idx != 1) {
4055 if (omitted_allele_idx) {
4056 alt1_start = multi_start;
4057 ZeroDArr(nm_sample_ct_rem, &(alt1_start[nm_sample_ct]));
4058 rarealt_start = &(rarealt_start[nm_sample_ctav]);
4059 --rare_allele_ct;
4060 } else {
4061 alt1_start = genotype_vals;
4062 }
4063 if (!missing_ct) {
4064 GenoarrLookup16x8bx2(pgv.genovec, kSmallDoublePairs, nm_sample_ct, alt1_start);
4065 } else {
4066 GenoarrToDoublesRemoveMissing(pgv.genovec, kSmallDoubles, cur_sample_ct, alt1_start);
4067 }
4068 }
4069 ZeroDArr(rare_allele_ct * nm_sample_ctav, rarealt_start);
4070 if (pgv.patch_01_ct) {
4071 const uintptr_t* patch_set_nm = pgv.patch_01_set;
4072 if (missing_ct) {
4073 CopyBitarrSubset(pgv.patch_01_set, sample_nm, nm_sample_ct, tmp_nm);
4074 patch_set_nm = tmp_nm;
4075 }
4076 uintptr_t sample_idx_base = 0;
4077 uintptr_t cur_bits = patch_set_nm[0];
4078 if (!omitted_allele_idx) {
4079 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
4080 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4081 const uint32_t allele_code = pgv.patch_01_vals[uii];
4082 rarealt_start[(allele_code - 2) * nm_sample_ctav + sample_idx] = 1.0;
4083 alt1_start[sample_idx] = 0.0;
4084 machr2_dosage_sums[allele_code] += 1;
4085 }
4086 } else if (omitted_allele_idx == 1) {
4087 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
4088 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4089 const uint32_t allele_code = pgv.patch_01_vals[uii];
4090 rarealt_start[(allele_code - 2) * nm_sample_ctav + sample_idx] = 1.0;
4091 machr2_dosage_sums[allele_code] += 1;
4092 }
4093 } else {
4094 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
4095 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4096 alt1_start[sample_idx] = 0.0;
4097 const uint32_t allele_code = pgv.patch_01_vals[uii];
4098 machr2_dosage_sums[allele_code] += 1;
4099 if (allele_code == omitted_allele_idx) {
4100 continue;
4101 }
4102 const uint32_t cur_col = allele_code - 2 - (allele_code > omitted_allele_idx);
4103 rarealt_start[cur_col * nm_sample_ctav + sample_idx] = 1.0;
4104 }
4105 }
4106 }
4107 uintptr_t alt1_het_ct = genocounts[1] - pgv.patch_01_ct;
4108 if (pgv.patch_10_ct) {
4109 const uintptr_t* patch_set_nm = pgv.patch_10_set;
4110 if (missing_ct) {
4111 CopyBitarrSubset(pgv.patch_10_set, sample_nm, nm_sample_ct, tmp_nm);
4112 patch_set_nm = tmp_nm;
4113 }
4114 uintptr_t sample_idx_base = 0;
4115 uintptr_t cur_bits = patch_set_nm[0];
4116 if (!omitted_allele_idx) {
4117 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
4118 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4119 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
4120 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
4121 if (ac0 == ac1) {
4122 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] = 2.0;
4123 alt1_start[sample_idx] = 0.0;
4124 machr2_dosage_ssqs[ac0] += 1;
4125 } else {
4126 rarealt_start[(ac1 - 2) * nm_sample_ctav + sample_idx] = 1.0;
4127 machr2_dosage_sums[ac1] += 1;
4128 if (ac0 == 1) {
4129 ++alt1_het_ct;
4130 alt1_start[sample_idx] = 1.0;
4131 } else {
4132 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] += 1.0;
4133 alt1_start[sample_idx] = 0.0;
4134 machr2_dosage_sums[ac0] += 1;
4135 }
4136 }
4137 }
4138 } else if (omitted_allele_idx == 1) {
4139 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
4140 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4141 const AlleleCode ac0 = pgv.patch_10_vals[2 * uii];
4142 const AlleleCode ac1 = pgv.patch_10_vals[2 * uii + 1];
4143 if (ac0 == ac1) {
4144 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] = 2.0;
4145 machr2_dosage_ssqs[ac0] += 1;
4146 } else {
4147 rarealt_start[(ac1 - 2) * nm_sample_ctav + sample_idx] = 1.0;
4148 machr2_dosage_sums[ac1] += 1;
4149 if (ac0 == 1) {
4150 ++alt1_het_ct;
4151 } else {
4152 rarealt_start[(ac0 - 2) * nm_sample_ctav + sample_idx] += 1.0;
4153 machr2_dosage_sums[ac0] += 1;
4154 }
4155 }
4156 }
4157 } else {
4158 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
4159 const uintptr_t sample_idx = BitIter1(patch_set_nm, &sample_idx_base, &cur_bits);
4160 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
4161 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
4162 if (ac0 == ac1) {
4163 machr2_dosage_ssqs[ac0] += 1;
4164 alt1_start[sample_idx] = 0.0;
4165 if (ac0 != omitted_allele_idx) {
4166 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
4167 rarealt_start[ac0_col * nm_sample_ctav + sample_idx] = 2.0;
4168 }
4169 } else {
4170 machr2_dosage_sums[ac1] += 1;
4171 if (ac1 != omitted_allele_idx) {
4172 const uint32_t ac1_col = ac1 - 2 - (ac1 > omitted_allele_idx);
4173 rarealt_start[ac1_col * nm_sample_ctav + sample_idx] = 1.0;
4174 }
4175 if (ac0 == 1) {
4176 ++alt1_het_ct;
4177 alt1_start[sample_idx] = 1.0;
4178 } else {
4179 machr2_dosage_sums[ac0] += 1;
4180 alt1_start[sample_idx] = 0.0;
4181 if (ac0 != omitted_allele_idx) {
4182 const uint32_t ac0_col = ac0 - 2 - (ac0 > omitted_allele_idx);
4183 rarealt_start[ac0_col * nm_sample_ctav + sample_idx] += 1.0;
4184 }
4185 }
4186 }
4187 }
4188 }
4189 }
4190 machr2_dosage_sums[1] = alt1_het_ct;
4191 machr2_dosage_ssqs[1] = genocounts[2] - pgv.patch_10_ct;
4192 if (cur_gcount_case_interleaved_vec) {
4193 // gcountcc. Need case-specific one_cts and two_cts for each
4194 // allele.
4195 STD_ARRAY_DECL(uint32_t, 4, case_hardcall_cts);
4196 GenoarrCountSubsetFreqs(pgv.genovec, cur_gcount_case_interleaved_vec, cur_sample_ct, cur_case_ct, case_hardcall_cts);
4197 ZeroU32Arr(allele_ct, case_one_cts);
4198 ZeroU32Arr(allele_ct, case_two_cts);
4199 uint32_t case_alt1_het_ct = case_hardcall_cts[1];
4200 case_one_cts[0] = case_alt1_het_ct;
4201 case_two_cts[0] = case_hardcall_cts[0];
4202 if (pgv.patch_01_ct) {
4203 uintptr_t sample_widx = 0;
4204 uintptr_t cur_bits = pgv.patch_01_set[0];
4205 for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) {
4206 const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_bits);
4207 if (cur_pheno_cc[sample_widx] & lowbit) {
4208 const uint32_t allele_code = pgv.patch_01_vals[uii];
4209 case_one_cts[allele_code] += 1;
4210 }
4211 }
4212 for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) {
4213 case_alt1_het_ct -= case_one_cts[allele_idx];
4214 }
4215 }
4216 uint32_t case_alt1_hom_ct = case_hardcall_cts[2];
4217 if (pgv.patch_10_ct) {
4218 uintptr_t sample_widx = 0;
4219 uintptr_t cur_bits = pgv.patch_10_set[0];
4220 for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) {
4221 const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_bits);
4222 if (cur_pheno_cc[sample_widx] & lowbit) {
4223 const uint32_t ac0 = pgv.patch_10_vals[2 * uii];
4224 const uint32_t ac1 = pgv.patch_10_vals[2 * uii + 1];
4225 --case_alt1_hom_ct;
4226 if (ac0 == ac1) {
4227 case_two_cts[ac0] += 1;
4228 } else {
4229 case_one_cts[ac1] += 1;
4230 if (ac0 == 1) {
4231 ++case_alt1_het_ct;
4232 } else {
4233 case_one_cts[ac0] += 1;
4234 }
4235 }
4236 }
4237 }
4238 }
4239 case_one_cts[1] = case_alt1_het_ct;
4240 case_two_cts[1] = case_alt1_hom_ct;
4241 uint32_t nonomitted_allele_idx = 0;
4242 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4243 if (allele_idx == omitted_allele_idx) {
4244 continue;
4245 }
4246 const uint32_t one_ct = machr2_dosage_sums[allele_idx];
4247 const uint32_t two_ct = machr2_dosage_ssqs[allele_idx];
4248 const uint32_t case_one_ct = case_one_cts[allele_idx];
4249 const uint32_t case_two_ct = case_two_cts[allele_idx];
4250 STD_ARRAY_REF(uint32_t, 6) dst = block_aux_iter[nonomitted_allele_idx].geno_hardcall_cts;
4251 dst[0] = nm_case_ct - case_one_ct - case_two_ct;
4252 dst[1] = case_one_ct;
4253 dst[2] = case_two_ct;
4254 dst[3] = nm_sample_ct - one_ct - two_ct - dst[0];
4255 dst[4] = one_ct - case_one_ct;
4256 dst[5] = two_ct - case_two_ct;
4257 ++nonomitted_allele_idx;
4258 }
4259 }
4260 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4261 const uintptr_t one_ct = machr2_dosage_sums[allele_idx];
4262 const uintptr_t two_ct = machr2_dosage_ssqs[allele_idx];
4263 machr2_dosage_sums[allele_idx] = (one_ct + 2 * two_ct) * 0x4000LLU;
4264 machr2_dosage_ssqs[allele_idx] = (one_ct + 4LLU * two_ct) * 0x10000000LLU;
4265 if ((one_ct == nm_sample_ct) || (two_ct == nm_sample_ct) || ((!one_ct) && (!two_ct))) {
4266 SetBit(allele_idx, const_alleles);
4267 }
4268 }
4269 }
4270 ZeroDArr(nm_sample_ct_rem, &(genotype_vals[nm_sample_ct]));
4271 // usually need to save some of {sample_obs_ct, allele_obs_ct,
4272 // a1_dosage, case_allele_obs_ct, a1_case_dosage, mach_r2 even for
4273 // skipped variants
4274 // compute them all for now, could conditionally skip later
4275 uint32_t allele_obs_ct = nm_sample_ct * 2;
4276 uint32_t case_allele_obs_ct = nm_case_ct * 2;
4277 if (!is_regular_x) {
4278 if (is_nonx_haploid) {
4279 allele_obs_ct = nm_sample_ct;
4280 case_allele_obs_ct = nm_case_ct;
4281 // everything is on 0..1 scale, not 0..2
4282 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4283 genotype_vals[sample_idx] *= 0.5;
4284 }
4285 const uint32_t high_ct = nm_sample_ct * allele_ct_m2;
4286 for (uint32_t uii = 0; uii != high_ct; ++uii) {
4287 multi_start[uii] *= 0.5;
4288 }
4289 }
4290 } else {
4291 CopyBitarrSubset(sex_male_collapsed, sample_nm, nm_sample_ct, tmp_nm);
4292 const uintptr_t* male_nm = tmp_nm;
4293 const uint32_t nm_male_ct = PopcountWords(male_nm, nm_sample_ctl);
4294 if (is_xchr_model_1) {
4295 // special case: multiply male values by 0.5
4296 uintptr_t sample_idx_base = 0;
4297 uintptr_t male_nm_bits = male_nm[0];
4298 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
4299 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
4300 genotype_vals[sample_idx] *= 0.5;
4301 // could insert multiallelic loop here isntead, but I'm guessing
4302 // that's worse due to locality of writes?
4303 }
4304 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
4305 double* cur_start = &(multi_start[extra_allele_idx * nm_sample_ctav]);
4306 sample_idx_base = 0;
4307 male_nm_bits = male_nm[0];
4308 for (uint32_t male_idx = 0; male_idx != nm_male_ct; ++male_idx) {
4309 const uintptr_t sample_idx = BitIter1(male_nm, &sample_idx_base, &male_nm_bits);
4310 cur_start[sample_idx] *= 0.5;
4311 }
4312 }
4313 allele_obs_ct -= nm_male_ct;
4314 case_allele_obs_ct -= PopcountWordsIntersect(pheno_cc_nm, male_nm, nm_sample_ctl);
4315 }
4316 }
4317 const double mach_r2 = MultiallelicDiploidMachR2(machr2_dosage_sums, machr2_dosage_ssqs, nm_sample_ct, allele_ct);
4318 uint32_t nonomitted_allele_idx = 0;
4319 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4320 if (allele_idx == omitted_allele_idx) {
4321 continue;
4322 }
4323
4324 double* geno_col = genotype_vals;
4325 if (allele_idx > (!omitted_allele_idx)) {
4326 geno_col = &(nm_predictors_pmaj_buf[(expected_predictor_ct - (allele_ct - allele_idx) + (allele_idx < omitted_allele_idx)) * nm_sample_ctav]);
4327 }
4328 double a1_dosage = u63tod(machr2_dosage_sums[allele_idx]) * kRecipDosageMid;
4329 if (is_xchr_model_1) {
4330 // ugh.
4331 a1_dosage = 0.0;
4332 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4333 a1_dosage += geno_col[sample_idx];
4334 }
4335 } else {
4336 if (is_nonx_haploid) {
4337 a1_dosage *= 0.5;
4338 }
4339 }
4340 a1_dosages[allele_idx] = a1_dosage;
4341
4342 // todo: shortcut if gcountcc computed and no dosages
4343 double a1_case_dosage = 0.0;
4344 uintptr_t sample_idx_base = 0;
4345 uintptr_t pheno_cc_nm_bits = pheno_cc_nm[0];
4346 for (uint32_t uii = 0; uii != nm_case_ct; ++uii) {
4347 const uintptr_t sample_idx = BitIter1(pheno_cc_nm, &sample_idx_base, &pheno_cc_nm_bits);
4348 a1_case_dosage += geno_col[sample_idx];
4349 }
4350 a1_case_dosages[allele_idx] = a1_case_dosage;
4351 block_aux_iter[nonomitted_allele_idx].sample_obs_ct = nm_sample_ct;
4352 block_aux_iter[nonomitted_allele_idx].allele_obs_ct = allele_obs_ct;
4353 if (!allele_ct_m2) {
4354 // Need main_dosage_sum and main_dosage_ssq for now (probably move
4355 // this computation in-place later).
4356 if (is_xchr_model_1) {
4357 main_dosage_sum = a1_dosage;
4358 main_dosage_ssq = 0.0;
4359 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4360 const double cur_dosage = geno_col[sample_idx];
4361 main_dosage_ssq += cur_dosage * cur_dosage;
4362 }
4363 } else {
4364 main_dosage_sum = a1_dosage;
4365 main_dosage_ssq = u63tod(machr2_dosage_ssqs[allele_idx]) * kRecipDosageMidSq;
4366 if (is_nonx_haploid) {
4367 main_dosage_ssq *= 0.25;
4368 }
4369 }
4370 }
4371 block_aux_iter[nonomitted_allele_idx].a1_dosage = a1_dosage;
4372
4373 // bugfix (4 Sep 2018): forgot to save this
4374 block_aux_iter[nonomitted_allele_idx].case_allele_obs_ct = case_allele_obs_ct;
4375
4376 block_aux_iter[nonomitted_allele_idx].a1_case_dosage = a1_case_dosage;
4377 block_aux_iter[nonomitted_allele_idx].firth_fallback = 0;
4378 block_aux_iter[nonomitted_allele_idx].is_unfinished = 0;
4379 block_aux_iter[nonomitted_allele_idx].mach_r2 = mach_r2;
4380 ++nonomitted_allele_idx;
4381 }
4382 // Now free to skip the actual regression if there are too few samples,
4383 // or omitted allele corresponds to a zero-variance genotype column.
4384 // If another allele has zero variance but the omitted allele does not,
4385 // we now salvage as many alleles as we can.
4386 GlmErr glm_err = 0;
4387 if (nm_sample_ct <= expected_predictor_ct) {
4388 // reasonable for this to override CONST_ALLELE
4389 glm_err = SetGlmErr0(kGlmErrcodeSampleCtLtePredictorCt);
4390 } else if (IsSet(const_alleles, omitted_allele_idx)) {
4391 glm_err = SetGlmErr0(kGlmErrcodeConstOmittedAllele);
4392 }
4393 if (glm_err) {
4394 if (missing_ct) {
4395 // covariates have not been copied yet, so we can't usually change
4396 // prev_nm from 0 to 1 when missing_ct == 0 (and there's little
4397 // reason to optimize the zero-covariate case)
4398 prev_nm = 0;
4399 }
4400 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
4401 if (allele_ct_m2 && (beta_se_multiallelic_fused || (!hide_covar))) {
4402 reported_ct += allele_ct_m2;
4403 }
4404 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
4405 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
4406 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
4407 beta_se_iter[uii * 2 + 1] = -9.0;
4408 }
4409 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
4410 }
4411 } else {
4412 {
4413 double omitted_dosage = u63tod(allele_obs_ct);
4414 double omitted_case_dosage = u63tod(case_allele_obs_ct);
4415 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4416 if (allele_idx == omitted_allele_idx) {
4417 continue;
4418 }
4419 omitted_dosage -= a1_dosages[allele_idx];
4420 omitted_case_dosage -= a1_case_dosages[allele_idx];
4421 }
4422 a1_dosages[omitted_allele_idx] = omitted_dosage;
4423 a1_case_dosages[omitted_allele_idx] = omitted_case_dosage;
4424 }
4425 uint32_t parameter_uidx = 2 + domdev_present;
4426 double* nm_predictors_pmaj_istart = nullptr;
4427 // only need to do this part once per variant in multiallelic case
4428 double* nm_predictors_pmaj_iter = &(nm_predictors_pmaj_buf[nm_sample_ctav * (parameter_uidx - main_omitted)]);
4429 if (missing_ct || (!prev_nm)) {
4430 // fill phenotype
4431 uintptr_t sample_midx_base = 0;
4432 uintptr_t sample_nm_bits = sample_nm[0];
4433 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4434 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
4435 nm_pheno_buf[sample_idx] = cur_pheno[sample_midx];
4436 }
4437 // bugfix (13 Oct 2017): must guarantee trailing phenotype values
4438 // are valid (exact contents don't matter since they are multiplied
4439 // by zero, but they can't be nan)
4440 ZeroDArr(nm_sample_ct_rem, &(nm_pheno_buf[nm_sample_ct]));
4441
4442 // fill covariates
4443 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx, ++parameter_uidx) {
4444 // unlike the float case, cur_covars_cmaj is NOT vector-aligned
4445 if (cur_parameter_subset && (!IsSet(cur_parameter_subset, parameter_uidx))) {
4446 continue;
4447 }
4448 const double* cur_covar_col;
4449 if (covar_idx < local_covar_ct) {
4450 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
4451 } else {
4452 cur_covar_col = &(cur_covars_cmaj[(covar_idx - local_covar_ct) * cur_sample_ct]);
4453 }
4454 sample_midx_base = 0;
4455 sample_nm_bits = sample_nm[0];
4456 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4457 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
4458 *nm_predictors_pmaj_iter++ = cur_covar_col[sample_midx];
4459 }
4460 ZeromovDArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
4461 }
4462 nm_predictors_pmaj_istart = nm_predictors_pmaj_iter;
4463 // bugfix (13 Apr 2021): if local covariates are present, we can't
4464 // optimize as aggressively
4465 prev_nm = !(missing_ct || local_covar_ct);
4466 } else {
4467 // bugfix (15 Aug 2018): this was not handling --parameters
4468 // correctly when a covariate was only needed as part of an
4469 // interaction
4470 parameter_uidx += cur_covar_ct;
4471 nm_predictors_pmaj_istart = &(nm_predictors_pmaj_iter[literal_covar_ct * nm_sample_ctav]);
4472 }
4473 const uint32_t const_allele_ct = PopcountWords(const_alleles, allele_ctl);
4474 if (const_allele_ct) {
4475 // Must delete constant-allele columns from nm_predictors_pmaj, and
4476 // shift later columns back.
4477 double* read_iter = genotype_vals;
4478 double* write_iter = genotype_vals;
4479 for (uint32_t read_allele_idx = 0; read_allele_idx != allele_ct; ++read_allele_idx) {
4480 if (read_allele_idx == omitted_allele_idx) {
4481 continue;
4482 }
4483 if (!IsSet(const_alleles, read_allele_idx)) {
4484 if (write_iter != read_iter) {
4485 memcpy(write_iter, read_iter, nm_sample_ctav * sizeof(double));
4486 }
4487 if (write_iter == genotype_vals) {
4488 write_iter = multi_start;
4489 } else {
4490 write_iter = &(write_iter[nm_sample_ctav]);
4491 }
4492 }
4493 if (read_iter == genotype_vals) {
4494 read_iter = multi_start;
4495 } else {
4496 read_iter = &(read_iter[nm_sample_ctav]);
4497 }
4498 }
4499 }
4500 const uint32_t cur_predictor_ct = expected_predictor_ct - const_allele_ct;
4501 const uint32_t cur_predictor_ctav = RoundUpPow2(cur_predictor_ct, kDoublePerDVec);
4502 const uint32_t cur_predictor_ctavp1 = cur_predictor_ctav + 1;
4503 uint32_t nonconst_extra_regression_idx = UINT32_MAX; // deliberate overflow
4504 for (uint32_t extra_regression_idx = 0; extra_regression_idx <= extra_regression_ct; ++extra_regression_idx) {
4505 double* main_vals = &(nm_predictors_pmaj_buf[nm_sample_ctav]);
4506 double* domdev_vals = nullptr;
4507 uint32_t is_unfinished = 0;
4508 uint32_t is_residualized = 0;
4509 // _stop instead of _ct since, in the residualized case, the
4510 // intercept (predictor index 0) is not included; we iterate over
4511 // the predictor indices in [1, _stop).
4512 uint32_t cur_regressed_predictor_stop = cur_predictor_ct;
4513 uint32_t cur_regressed_predictor_ctav = cur_predictor_ctav;
4514 uint32_t cur_regressed_predictor_ctavp1 = cur_predictor_ctavp1;
4515 uint32_t cur_biallelic_regressed_predictor_stop = cur_biallelic_predictor_ct;
4516 if (extra_regression_ct) {
4517 if (IsSet(const_alleles, extra_regression_idx + (extra_regression_idx >= omitted_allele_idx))) {
4518 glm_err = SetGlmErr0(kGlmErrcodeConstAllele);
4519 goto GlmLogisticThreadD_skip_regression;
4520 }
4521 ++nonconst_extra_regression_idx;
4522 if (nonconst_extra_regression_idx) {
4523 double* swap_target = &(multi_start[(nonconst_extra_regression_idx - 1) * nm_sample_ctav]);
4524 for (uint32_t uii = 0; uii != nm_sample_ct; ++uii) {
4525 double dxx = genotype_vals[uii];
4526 genotype_vals[uii] = swap_target[uii];
4527 swap_target[uii] = dxx;
4528 }
4529 }
4530 }
4531 if (main_omitted) {
4532 // if main_mutated, this will be filled below
4533 // if not, this aliases genotype_vals
4534 main_vals = &(nm_predictors_pmaj_buf[(cur_predictor_ct + main_mutated) * nm_sample_ctav]);
4535 } else if (joint_genotypic || joint_hethom) {
4536 // in hethom case, do this before clobbering genotype data
4537 domdev_vals = &(main_vals[nm_sample_ctav]);
4538 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4539 double cur_genotype_val = genotype_vals[sample_idx];
4540 if (cur_genotype_val > 1.0) {
4541 cur_genotype_val = 2.0 - cur_genotype_val;
4542 }
4543 domdev_vals[sample_idx] = cur_genotype_val;
4544 }
4545 ZeroDArr(nm_sample_ct_rem, &(domdev_vals[nm_sample_ct]));
4546 }
4547 if (model_dominant) {
4548 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4549 double cur_genotype_val = genotype_vals[sample_idx];
4550 // 0..1..1
4551 if (cur_genotype_val > 1.0) {
4552 cur_genotype_val = 1.0;
4553 }
4554 main_vals[sample_idx] = cur_genotype_val;
4555 }
4556 } else if (model_recessive || joint_hethom) {
4557 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4558 double cur_genotype_val = genotype_vals[sample_idx];
4559 // 0..0..1
4560 if (cur_genotype_val < 1.0) {
4561 cur_genotype_val = 0.0;
4562 } else {
4563 cur_genotype_val -= 1.0;
4564 }
4565 main_vals[sample_idx] = cur_genotype_val;
4566 }
4567 } else if (model_hetonly) {
4568 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4569 double cur_genotype_val = genotype_vals[sample_idx];
4570 // 0..1..0
4571 if (cur_genotype_val > 1.0) {
4572 cur_genotype_val = 2.0 - cur_genotype_val;
4573 }
4574 main_vals[sample_idx] = cur_genotype_val;
4575 }
4576 }
4577
4578 // fill interaction terms
4579 if (add_interactions) {
4580 nm_predictors_pmaj_iter = nm_predictors_pmaj_istart;
4581 for (uint32_t covar_idx = 0; covar_idx != cur_covar_ct; ++covar_idx) {
4582 const double* cur_covar_col;
4583 if (covar_idx < local_covar_ct) {
4584 cur_covar_col = &(local_covars_iter[covar_idx * max_sample_ct]);
4585 } else {
4586 cur_covar_col = &(cur_covars_cmaj[covar_idx * cur_sample_ct]);
4587 }
4588 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
4589 uintptr_t sample_midx_base = 0;
4590 uintptr_t sample_nm_bits = sample_nm[0];
4591 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4592 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
4593 *nm_predictors_pmaj_iter++ = main_vals[sample_idx] * cur_covar_col[sample_midx];
4594 }
4595 ZeromovDArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
4596 }
4597 ++parameter_uidx;
4598 if (domdev_present) {
4599 if ((!cur_parameter_subset) || IsSet(cur_parameter_subset, parameter_uidx)) {
4600 uintptr_t sample_midx_base = 0;
4601 uintptr_t sample_nm_bits = sample_nm[0];
4602 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4603 const uintptr_t sample_midx = BitIter1(sample_nm, &sample_midx_base, &sample_nm_bits);
4604 *nm_predictors_pmaj_iter++ = domdev_vals[sample_idx] * cur_covar_col[sample_midx];
4605 }
4606 ZeromovDArr(nm_sample_ct_rem, &nm_predictors_pmaj_iter);
4607 }
4608 ++parameter_uidx;
4609 }
4610 }
4611 }
4612 if (corr_inv && prev_nm && (!allele_ct_m2)) {
4613 uintptr_t start_pred_idx = 0;
4614 if (!(model_dominant || model_recessive || model_hetonly || joint_hethom)) {
4615 start_pred_idx = domdev_present + 2;
4616 semicomputed_biallelic_xtx[cur_predictor_ct] = main_dosage_sum;
4617 semicomputed_biallelic_xtx[cur_predictor_ct + 1] = main_dosage_ssq;
4618 }
4619 if (cur_predictor_ct > start_pred_idx) {
4620 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[nm_sample_ctav]), &(nm_predictors_pmaj_buf[start_pred_idx * nm_sample_ctav]), nm_sample_ct, nm_sample_ctav, cur_predictor_ct - start_pred_idx, &(predictor_dotprod_buf[start_pred_idx]));
4621 for (uint32_t uii = start_pred_idx; uii != cur_predictor_ct; ++uii) {
4622 semicomputed_biallelic_xtx[cur_predictor_ct + uii] = predictor_dotprod_buf[uii];
4623 }
4624 }
4625 if (domdev_present) {
4626 ColMajorVectorMatrixMultiplyStrided(&(nm_predictors_pmaj_buf[2 * nm_sample_ctav]), nm_predictors_pmaj_buf, nm_sample_ct, nm_sample_ctav, cur_predictor_ct, predictor_dotprod_buf);
4627 for (uint32_t uii = 0; uii != cur_predictor_ct; ++uii) {
4628 semicomputed_biallelic_xtx[2 * cur_predictor_ct + uii] = predictor_dotprod_buf[uii];
4629 }
4630 semicomputed_biallelic_xtx[cur_predictor_ct + 2] = semicomputed_biallelic_xtx[2 * cur_predictor_ct + 1];
4631 }
4632 glm_err = CheckMaxCorrAndVifNm(semicomputed_biallelic_xtx, 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]));
4633 if (glm_err) {
4634 goto GlmLogisticThreadD_skip_regression;
4635 }
4636 } else {
4637 MultiplySelfTransposeStrided(&(nm_predictors_pmaj_buf[nm_sample_ctav]), cur_predictor_ct - 1, nm_sample_ct, nm_sample_ctav, predictor_dotprod_buf);
4638 for (uintptr_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
4639 const double* predictor_row = &(nm_predictors_pmaj_buf[pred_idx * nm_sample_ctav]);
4640 double row_sum = 0.0;
4641 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4642 row_sum += predictor_row[sample_idx];
4643 }
4644 dbl_2d_buf[pred_idx - 1] = row_sum;
4645 }
4646 glm_err = CheckMaxCorrAndVif(predictor_dotprod_buf, 0, cur_predictor_ct - 1, nm_sample_ct, max_corr, vif_thresh, dbl_2d_buf, nullptr, inverse_corr_buf, inv_1d_buf);
4647 if (glm_err) {
4648 goto GlmLogisticThreadD_skip_regression;
4649 }
4650 }
4651 ZeroDArr(cur_predictor_ctav, coef_return);
4652 if (!cur_is_always_firth) {
4653 // Does any genotype column have zero case or zero control
4654 // dosage? If yes, faster to skip logistic regression than
4655 // wait for convergence failure.
4656 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4657 if (IsSet(const_alleles, allele_idx)) {
4658 continue;
4659 }
4660 const double tot_dosage = a1_dosages[allele_idx];
4661 const double case_dosage = a1_case_dosages[allele_idx];
4662 if ((case_dosage == 0.0) || (case_dosage == tot_dosage)) {
4663 if (is_sometimes_firth) {
4664 goto GlmLogisticThreadD_firth_fallback;
4665 }
4666 glm_err = SetGlmErr1(kGlmErrcodeSeparation, allele_idx);
4667 goto GlmLogisticThreadD_skip_regression;
4668 }
4669 }
4670 if (!cur_cc_residualize) {
4671 if (LogisticRegressionD(nm_pheno_buf, nm_predictors_pmaj_buf, nullptr, nm_sample_ct, cur_predictor_ct, &is_unfinished, coef_return, cholesky_decomp_return, pp_buf, sample_variance_buf, hh_return, gradient_buf, dcoef_buf, inv_1d_buf, dbl_2d_buf)) {
4672 if (is_sometimes_firth) {
4673 ZeroDArr(cur_predictor_ctav, coef_return);
4674 goto GlmLogisticThreadD_firth_fallback;
4675 }
4676 glm_err = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
4677 goto GlmLogisticThreadD_skip_regression;
4678 }
4679 } else {
4680 if (LogisticRegressionResidualizedD(nm_pheno_buf, nm_predictors_pmaj_buf, sample_nm, cur_cc_residualize, nm_sample_ct, cur_predictor_ct, &is_unfinished, coef_return, cholesky_decomp_return, inv_1d_buf, dbl_2d_buf, pp_buf, sample_variance_buf, hh_return, gradient_buf, dcoef_buf, mean_centered_pmaj_buf, sample_offsets_buf)) {
4681 if (is_sometimes_firth) {
4682 ZeroDArr(cur_predictor_ctav, coef_return);
4683 goto GlmLogisticThreadD_firth_fallback;
4684 }
4685 glm_err = SetGlmErr0(kGlmErrcodeLogisticConvergeFail);
4686 goto GlmLogisticThreadD_skip_regression;
4687 }
4688 is_residualized = 1;
4689 cur_regressed_predictor_stop = domdev_present + allele_ct;
4690 cur_regressed_predictor_ctav = RoundUpPow2(cur_regressed_predictor_stop, kDoublePerDVec);
4691 cur_regressed_predictor_ctavp1 = cur_regressed_predictor_ctav + 1;
4692 cur_biallelic_regressed_predictor_stop = domdev_present + 2;
4693 }
4694 // unlike FirthRegressionD(), hh_return isn't inverted yet, do
4695 // that here
4696 for (uint32_t pred_uidx = is_residualized; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
4697 double* hh_inv_row = &(hh_return[pred_uidx * cur_regressed_predictor_ctav]);
4698 // ZeroDArr(cur_regressed_predictor_stop, gradient_buf);
4699 // gradient_buf[pred_uidx] = 1.0;
4700 // (y is gradient_buf, x is dcoef_buf)
4701 // SolveLinearSystemD(cholesky_decomp_return, &(gradient_buf[is_residualized]), cur_regressed_predictor_stop - is_residualized, &(hh_inv_row[is_residualized]));
4702 // that works, but doesn't exploit the sparsity of y
4703
4704 // hh_return does now have vector-aligned rows
4705 ZeroDArr(pred_uidx, hh_inv_row);
4706
4707 double dxx = 1.0;
4708 for (uint32_t row_idx = pred_uidx; row_idx != cur_regressed_predictor_stop; ++row_idx) {
4709 const double* ll_row = &(cholesky_decomp_return[row_idx * cur_regressed_predictor_ctav]);
4710 for (uint32_t col_idx = pred_uidx; col_idx != row_idx; ++col_idx) {
4711 dxx -= ll_row[col_idx] * hh_inv_row[col_idx];
4712 }
4713 hh_inv_row[row_idx] = dxx / ll_row[row_idx];
4714 dxx = 0.0;
4715 }
4716 for (uint32_t col_idx = cur_regressed_predictor_stop; col_idx > is_residualized; ) {
4717 dxx = hh_inv_row[--col_idx];
4718 double* hh_inv_row_iter = &(hh_inv_row[cur_regressed_predictor_stop - 1]);
4719 for (uint32_t row_idx = cur_regressed_predictor_stop - 1; row_idx > col_idx; --row_idx) {
4720 dxx -= cholesky_decomp_return[row_idx * cur_regressed_predictor_ctav + col_idx] * (*hh_inv_row_iter--);
4721 }
4722 *hh_inv_row_iter = dxx / cholesky_decomp_return[col_idx * cur_regressed_predictor_ctavp1];
4723 }
4724 }
4725 } else {
4726 if (!is_always_firth) {
4727 GlmLogisticThreadD_firth_fallback:
4728 block_aux_iter[extra_regression_idx].firth_fallback = 1;
4729 if (allele_ct_m2 && beta_se_multiallelic_fused) {
4730 for (uint32_t uii = 1; uii != allele_ct - 1; ++uii) {
4731 block_aux_iter[uii].firth_fallback = 1;
4732 }
4733 }
4734 }
4735 if (!cur_cc_residualize) {
4736 #ifndef NDEBUG
4737 if (g_debug_on && (variant_uidx == 0)) {
4738 // Dump phenotype values and predictor matrix to .inputs .
4739 char fname_buf[kPglFnamesize + 8];
4740 const uint32_t outname_slen = strlen(common->outname);
4741 char* fname_write_iter = memcpya(fname_buf, common->outname, outname_slen);
4742 strcpy_k(fname_write_iter, ".inputs");
4743 FILE* outfile;
4744 if (unlikely(fopen_checked(fname_buf, FOPEN_WB, &outfile))) {
4745 fprintf(stderr, "\nPanic: Failed to open .inputs file for writing.\n");
4746 exit(S_CAST(int, kPglRetOpenFail));
4747 }
4748 for (uint32_t sample_idx = 0; sample_idx != nm_sample_ct; ++sample_idx) {
4749 fprintf(outfile, "%g ", nm_pheno_buf[sample_idx]);
4750 for (uintptr_t pred_idx = 1; pred_idx != cur_predictor_ct; ++pred_idx) {
4751 fprintf(outfile, " %g", nm_predictors_pmaj_buf[nm_sample_ctav * pred_idx + sample_idx]);
4752 }
4753 fprintf(outfile, "\n");
4754 }
4755 fclose(outfile);
4756 }
4757 #endif
4758 if (FirthRegressionD(nm_pheno_buf, nm_predictors_pmaj_buf, nullptr, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, hh_return, inv_1d_buf, dbl_2d_buf, pp_buf, sample_variance_buf, gradient_buf, dcoef_buf, hdiag_buf, score_buf, hh0_buf, tmpnxk_buf)) {
4759 glm_err = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
4760 goto GlmLogisticThreadD_skip_regression;
4761 }
4762 } else {
4763 if (FirthRegressionResidualizedD(nm_pheno_buf, nm_predictors_pmaj_buf, sample_nm, cur_cc_residualize, nm_sample_ct, cur_predictor_ct, coef_return, &is_unfinished, hh_return, inv_1d_buf, dbl_2d_buf, pp_buf, sample_variance_buf, gradient_buf, dcoef_buf, hdiag_buf, score_buf, hh0_buf, tmpnxk_buf, mean_centered_pmaj_buf, sample_offsets_buf)) {
4764 glm_err = SetGlmErr0(kGlmErrcodeFirthConvergeFail);
4765 goto GlmLogisticThreadD_skip_regression;
4766 }
4767 is_residualized = 1;
4768 cur_regressed_predictor_stop = domdev_present + allele_ct;
4769 cur_regressed_predictor_ctav = RoundUpPow2(cur_regressed_predictor_stop, kDoublePerDVec);
4770 cur_regressed_predictor_ctavp1 = cur_regressed_predictor_ctav + 1;
4771 cur_biallelic_regressed_predictor_stop = domdev_present + 2;
4772 }
4773 }
4774 // validParameters() check
4775 for (uint32_t pred_uidx = 1; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
4776 const double hh_inv_diag_element = hh_return[pred_uidx * cur_regressed_predictor_ctavp1];
4777 if ((hh_inv_diag_element < 1e-20) || (!isfinite_d(hh_inv_diag_element))) {
4778 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
4779 goto GlmLogisticThreadD_skip_regression;
4780 }
4781 // use sample_variance_buf[] to store diagonal square roots
4782 sample_variance_buf[pred_uidx] = sqrt(hh_inv_diag_element);
4783 }
4784 if (!is_residualized) {
4785 sample_variance_buf[0] = sqrt(hh_return[0]);
4786 }
4787 for (uint32_t pred_uidx = 1 + is_residualized; pred_uidx != cur_regressed_predictor_stop; ++pred_uidx) {
4788 const double cur_hh_inv_diag_sqrt = 0.99999 * sample_variance_buf[pred_uidx];
4789 const double* hh_inv_row_iter = &(hh_return[pred_uidx * cur_regressed_predictor_ctav + is_residualized]);
4790 const double* hh_inv_diag_sqrts_iter = &(sample_variance_buf[is_residualized]);
4791 for (uint32_t pred_uidx2 = is_residualized; pred_uidx2 != pred_uidx; ++pred_uidx2) {
4792 if ((*hh_inv_row_iter++) > cur_hh_inv_diag_sqrt * (*hh_inv_diag_sqrts_iter++)) {
4793 glm_err = SetGlmErr0(kGlmErrcodeInvalidResult);
4794 goto GlmLogisticThreadD_skip_regression;
4795 }
4796 }
4797 }
4798 if (is_unfinished) {
4799 block_aux_iter[extra_regression_idx].is_unfinished = 1;
4800 if (allele_ct_m2 && beta_se_multiallelic_fused) {
4801 for (uint32_t uii = 1; uii != allele_ct - 1; ++uii) {
4802 block_aux_iter[uii].is_unfinished = 1;
4803 }
4804 }
4805 }
4806 {
4807 double* beta_se_iter2 = beta_se_iter;
4808 for (uint32_t pred_uidx = reported_pred_uidx_start; pred_uidx != reported_pred_uidx_biallelic_end; ++pred_uidx) {
4809 // In the multiallelic-fused case, if the first allele is
4810 // constant, this writes the beta/se values for the first
4811 // nonconstant, non-omitted allele where the results for the
4812 // first allele belong. We correct that at the end of this
4813 // block.
4814 *beta_se_iter2++ = coef_return[pred_uidx];
4815 *beta_se_iter2++ = sample_variance_buf[pred_uidx];
4816 }
4817 if (cur_constraint_ct) {
4818 // bugfix (4 Sep 2021): forgot to update this for residualize
4819 // case
4820 *beta_se_iter2++ = 0.0;
4821
4822 uint32_t joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
4823 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
4824 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
4825 cur_constraints_con_major[uii * cur_regressed_predictor_stop + joint_test_idx] = 1.0;
4826 }
4827 double chisq;
4828 if (!LinearHypothesisChisq(coef_return, cur_constraints_con_major, hh_return, cur_constraint_ct, cur_regressed_predictor_stop, cur_regressed_predictor_ctav, &chisq, tmphxs_buf, h_transpose_buf, inner_buf, inv_1d_buf, outer_buf)) {
4829 *beta_se_iter2++ = chisq;
4830 } else {
4831 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeRankDeficient);
4832 memcpy(&(beta_se_iter2[-1]), &glm_err2, 8);
4833 *beta_se_iter2++ = -9.0;
4834 }
4835 // next test may have different alt allele count
4836 joint_test_idx = AdvTo1Bit(cur_joint_test_params, 0);
4837 for (uint32_t uii = 1; uii != cur_constraint_ct; ++uii) {
4838 joint_test_idx = AdvTo1Bit(cur_joint_test_params, joint_test_idx + 1);
4839 cur_constraints_con_major[uii * cur_regressed_predictor_stop + joint_test_idx] = 0.0;
4840 }
4841 }
4842 if (!const_allele_ct) {
4843 if (beta_se_multiallelic_fused || (!hide_covar)) {
4844 for (uint32_t extra_allele_idx = 0; extra_allele_idx != allele_ct_m2; ++extra_allele_idx) {
4845 *beta_se_iter2++ = coef_return[cur_biallelic_regressed_predictor_stop + extra_allele_idx];
4846 *beta_se_iter2++ = sample_variance_buf[cur_biallelic_regressed_predictor_stop + extra_allele_idx];
4847 }
4848 }
4849 } else if (!beta_se_multiallelic_fused) {
4850 if (!hide_covar) {
4851 // Need to insert some {CONST_ALLELE, -9} entries.
4852 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
4853 const uint32_t cur_raw_allele_idx = extra_regression_idx + (extra_regression_idx >= omitted_allele_idx);
4854 uint32_t extra_read_allele_idx = 0;
4855 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
4856 if ((allele_idx == omitted_allele_idx) || (allele_idx == cur_raw_allele_idx)) {
4857 continue;
4858 }
4859 if (IsSet(const_alleles, allele_idx)) {
4860 memcpy(beta_se_iter2, &glm_err2, 8);
4861 beta_se_iter2[1] = -9.0;
4862 beta_se_iter2 = &(beta_se_iter2[2]);
4863 } else {
4864 *beta_se_iter2++ = coef_return[cur_biallelic_regressed_predictor_stop + extra_read_allele_idx];
4865 *beta_se_iter2++ = sample_variance_buf[cur_biallelic_regressed_predictor_stop + extra_read_allele_idx];
4866 ++extra_read_allele_idx;
4867 }
4868 }
4869 }
4870 } else {
4871 const GlmErr glm_err2 = SetGlmErr0(kGlmErrcodeConstAllele);
4872 // Special-case first nonconst allele since it's positioned
4873 // discontinuously, and its BETA/SE may already be correctly
4874 // filled.
4875 uint32_t allele_idx = omitted_allele_idx? 0 : 1;
4876 if (IsSet(const_alleles, allele_idx)) {
4877 memcpy(&(beta_se_iter[2 * include_intercept]), &glm_err2, 8);
4878 beta_se_iter[2 * include_intercept + 1] = -9.0;
4879 allele_idx = AdvTo0Bit(const_alleles, 1);
4880 if (allele_idx == omitted_allele_idx) {
4881 allele_idx = AdvTo0Bit(const_alleles, omitted_allele_idx + 1);
4882 }
4883 const uint32_t skip_ct = allele_idx - 1 - (allele_idx > omitted_allele_idx);
4884 for (uint32_t uii = 0; uii != skip_ct; ++uii) {
4885 memcpy(beta_se_iter2, &glm_err2, 8);
4886 beta_se_iter2[1] = -9.0;
4887 beta_se_iter2 = &(beta_se_iter2[2]);
4888 }
4889 *beta_se_iter2++ = coef_return[1];
4890 *beta_se_iter2++ = sample_variance_buf[1];
4891 }
4892 ++allele_idx;
4893 uint32_t nonconst_allele_idx_m1 = 0;
4894 for (; allele_idx != allele_ct; ++allele_idx) {
4895 if (allele_idx == omitted_allele_idx) {
4896 continue;
4897 }
4898 if (!IsSet(const_alleles, allele_idx)) {
4899 *beta_se_iter2++ = coef_return[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
4900 *beta_se_iter2++ = sample_variance_buf[cur_biallelic_predictor_ct + nonconst_allele_idx_m1];
4901 ++nonconst_allele_idx_m1;
4902 } else {
4903 memcpy(beta_se_iter2, &glm_err2, 8);
4904 beta_se_iter2[1] = -9.0;
4905 beta_se_iter2 = &(beta_se_iter2[2]);
4906 }
4907 }
4908 }
4909 }
4910 while (0) {
4911 GlmLogisticThreadD_skip_regression:
4912 {
4913 uint32_t reported_ct = reported_pred_uidx_biallelic_end + (cur_constraint_ct != 0) - reported_pred_uidx_start;
4914 if (allele_ct_m2 && (beta_se_multiallelic_fused || (!hide_covar))) {
4915 reported_ct += allele_ct_m2;
4916 }
4917 for (uint32_t uii = 0; uii != reported_ct; ++uii) {
4918 memcpy(&(beta_se_iter[uii * 2]), &glm_err, 8);
4919 beta_se_iter[uii * 2 + 1] = -9.0;
4920 }
4921 }
4922 }
4923 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
4924 }
4925 }
4926 block_aux_iter = &(block_aux_iter[allele_ct - 1]);
4927 if (local_covars_iter) {
4928 local_covars_iter = &(local_covars_iter[local_covar_ct * max_sample_ct]);
4929 }
4930 }
4931 }
4932 parity = 1 - parity;
4933 variant_idx_offset += cur_block_variant_ct;
4934 while (0) {
4935 GlmLogisticThreadD_err:
4936 UpdateU64IfSmaller(new_err_info, &common->err_info);
4937 }
4938 } while (!THREAD_BLOCK_FINISH(arg));
4939 THREAD_RETURN;
4940 }
4941
4942 // only pass the parameters which aren't also needed by the compute threads,
4943 // for now
4944 // valid_variants and valid_alleles are a bit redundant, may want to remove the
4945 // former later, but let's make that decision during/after permutation test
4946 // implementation
4947 PglErr GlmLogistic(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, GlmLogisticCtx* ctx, TextStream* local_covar_txsp, LlStr** outfnames_ll_ptr, uintptr_t* valid_variants, uintptr_t* valid_alleles, double* orig_ln_pvals, double* orig_permstat, uintptr_t* valid_allele_ct_ptr) {
4948 unsigned char* bigstack_mark = g_bigstack_base;
4949 char* cswritep = nullptr;
4950 PglErr reterr = kPglRetSuccess;
4951 CompressStreamState css;
4952 ThreadGroup tg;
4953 PreinitCstream(&css);
4954 PreinitThreads(&tg);
4955 {
4956 GlmCtx* common = ctx->common;
4957 const uintptr_t* variant_include = common->variant_include;
4958 const ChrInfo* cip = common->cip;
4959 const uintptr_t* allele_idx_offsets = common->allele_idx_offsets;
4960 const AlleleCode* omitted_alleles = common->omitted_alleles;
4961
4962 const uint32_t sample_ct = common->sample_ct;
4963 const uint32_t sample_ct_x = common->sample_ct_x;
4964 const uint32_t sample_ct_y = common->sample_ct_y;
4965 const uint32_t covar_ct = common->covar_ct;
4966 const uintptr_t local_covar_ct = common->local_covar_ct;
4967 const uint32_t covar_ct_x = common->covar_ct_x;
4968 const uint32_t covar_ct_y = common->covar_ct_y;
4969
4970 uint32_t max_sample_ct = MAXV(sample_ct, sample_ct_x);
4971 if (max_sample_ct < sample_ct_y) {
4972 max_sample_ct = sample_ct_y;
4973 }
4974 // obvious todo: wrap these in structs
4975 uint32_t* local_sample_idx_order = nullptr;
4976 uint32_t local_line_idx = 0;
4977 uint32_t local_xy = 0; // 1 = chrX, 2 = chrY
4978
4979 const char* local_line_iter = nullptr;
4980 uint32_t local_prev_chr_code = UINT32_MAX;
4981 uint32_t local_chr_code = UINT32_MAX;
4982 uint32_t local_bp = UINT32_MAX;
4983 uint32_t local_skip_chr = 1;
4984 if (local_covar_ct) {
4985 reterr = TextRewind(local_covar_txsp);
4986 if (unlikely(reterr)) {
4987 goto GlmLogistic_ret_TSTREAM_FAIL;
4988 }
4989 local_line_idx = glm_info_ptr->local_header_line_ct;
4990 reterr = TextSkip(local_line_idx, local_covar_txsp);
4991 if (unlikely(reterr)) {
4992 goto GlmLogistic_ret_TSTREAM_FAIL;
4993 }
4994 if (unlikely(bigstack_alloc_u32(local_sample_ct, &local_sample_idx_order))) {
4995 goto GlmLogistic_ret_NOMEM;
4996 }
4997 for (uint32_t uii = 0; uii != local_sample_ct; ++uii) {
4998 const uint32_t cur_uidx = local_sample_uidx_order[uii];
4999 uint32_t cur_idx = UINT32_MAX;
5000 if ((cur_uidx != UINT32_MAX) && IsSet(common->sample_include, cur_uidx)) {
5001 cur_idx = RawToSubsettedPos(common->sample_include, common->sample_include_cumulative_popcounts, cur_uidx);
5002 }
5003 local_sample_idx_order[uii] = cur_idx;
5004 }
5005 }
5006
5007 const uint32_t variant_ct = common->variant_ct;
5008
5009 const GlmFlags glm_flags = glm_info_ptr->flags;
5010 const uint32_t output_zst = (glm_flags / kfGlmZs) & 1;
5011 // forced-singlethreaded
5012 reterr = InitCstreamAlloc(outname, 0, output_zst, 1, overflow_buf_size, &css, &cswritep);
5013 if (unlikely(reterr)) {
5014 goto GlmLogistic_ret_1;
5015 }
5016 if (outfnames_ll_ptr) {
5017 if (unlikely(PushLlStr(outname, outfnames_ll_ptr))) {
5018 goto GlmLogistic_ret_NOMEM;
5019 }
5020 }
5021 const uint32_t report_neglog10p = (glm_flags / kfGlmLog10) & 1;
5022 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
5023 const uint32_t domdev_present = (glm_flags & (kfGlmGenotypic | kfGlmHethom))? 1 : 0;
5024 const uint32_t domdev_present_p1 = domdev_present + 1;
5025
5026 const uint32_t constraint_ct = common->constraint_ct;
5027 const uint32_t constraint_ct_x = common->constraint_ct_x;
5028 const uint32_t constraint_ct_y = common->constraint_ct_y;
5029
5030 const uint32_t max_extra_allele_ct = common->max_extra_allele_ct;
5031 uint32_t biallelic_predictor_ct = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
5032 uint32_t biallelic_predictor_ct_x = 2 + domdev_present + covar_ct_x * (1 + add_interactions * domdev_present_p1);
5033 uint32_t biallelic_predictor_ct_y = 2 + domdev_present + covar_ct_y * (1 + add_interactions * domdev_present_p1);
5034 const uintptr_t* parameter_subset = common->parameter_subset;
5035 const uintptr_t* parameter_subset_x = common->parameter_subset_x;
5036 const uintptr_t* parameter_subset_y = common->parameter_subset_y;
5037 if (parameter_subset) {
5038 biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct));
5039 if (sample_ct_x) {
5040 biallelic_predictor_ct_x = PopcountWords(parameter_subset_x, BitCtToWordCt(biallelic_predictor_ct_x));
5041 } else {
5042 biallelic_predictor_ct_x = 0;
5043 }
5044 if (sample_ct_y) {
5045 biallelic_predictor_ct_y = PopcountWords(parameter_subset_y, BitCtToWordCt(biallelic_predictor_ct_x));
5046 } else {
5047 biallelic_predictor_ct_y = 0;
5048 }
5049 }
5050 uint32_t biallelic_reported_test_ct = GetBiallelicReportedTestCt(parameter_subset, glm_flags, covar_ct, common->tests_flag);
5051 uintptr_t max_reported_test_ct = biallelic_reported_test_ct;
5052 uint32_t biallelic_reported_test_ct_x = 0;
5053 if (sample_ct_x) {
5054 biallelic_reported_test_ct_x = GetBiallelicReportedTestCt(parameter_subset_x, glm_flags, covar_ct_x, common->tests_flag);
5055 if (biallelic_reported_test_ct_x > max_reported_test_ct) {
5056 max_reported_test_ct = biallelic_reported_test_ct_x;
5057 }
5058 }
5059 uint32_t biallelic_reported_test_ct_y = 0;
5060 if (sample_ct_y) {
5061 biallelic_reported_test_ct_y = GetBiallelicReportedTestCt(parameter_subset_y, glm_flags, covar_ct_y, common->tests_flag);
5062 if (biallelic_reported_test_ct_y > max_reported_test_ct) {
5063 max_reported_test_ct = biallelic_reported_test_ct_y;
5064 }
5065 }
5066 const uint32_t hide_covar = (glm_flags / kfGlmHideCovar) & 1;
5067 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
5068 const GlmColFlags glm_cols = glm_info_ptr->cols;
5069 const uint32_t test_col = glm_cols & kfGlmColTest;
5070 if (unlikely((!test_col) && (max_reported_test_ct > 1))) {
5071 // this is okay in plain multiallelic case due to A1 column
5072 logerrputs("Error: --glm's 'test' column cannot be omitted when results for multiple\npredictors are reported. (Did you forget 'hide-covar'?)\n");
5073 goto GlmLogistic_ret_INCONSISTENT_INPUT;
5074 }
5075 const uint32_t main_mutated = ((glm_flags & (kfGlmDominant | kfGlmRecessive | kfGlmHetonly | kfGlmHethom)) != kfGlm0);
5076 // if 'fused', one row per variant
5077 // otherwise, one row per tested allele
5078 const uint32_t beta_se_multiallelic_fused = (!domdev_present) && (!main_mutated) && (!common->tests_flag) && (!add_interactions);
5079 if (beta_se_multiallelic_fused || (!hide_covar)) {
5080 max_reported_test_ct += max_extra_allele_ct;
5081 }
5082 common->max_reported_test_ct = max_reported_test_ct;
5083
5084 const uint32_t is_sometimes_firth = !(glm_flags & kfGlmNoFirth);
5085 const uint32_t is_always_firth = (glm_flags / kfGlmFirth) & 1;
5086 const uint32_t is_cc_residualize = !!(glm_flags & (kfGlmFirthResidualize | kfGlmCcResidualize));
5087
5088 uint32_t x_code = UINT32_MAXM1;
5089 uint32_t x_start = 0;
5090 uint32_t x_end = 0;
5091 if (sample_ct_x) {
5092 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetX, &x_code, &x_start, &x_end);
5093 }
5094 uint32_t y_code = UINT32_MAXM1;
5095 uint32_t y_start = 0;
5096 uint32_t y_end = 0;
5097 if (sample_ct_y) {
5098 GetXymtCodeStartAndEndUnsafe(cip, kChrOffsetY, &y_code, &y_start, &y_end);
5099 }
5100 const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT];
5101 const uint32_t chr_col = glm_cols & kfGlmColChrom;
5102
5103 // includes trailing tab
5104 char* chr_buf = nullptr;
5105 if (chr_col) {
5106 if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) {
5107 goto GlmLogistic_ret_NOMEM;
5108 }
5109 }
5110
5111 uint32_t calc_thread_ct = (max_thread_ct > 8)? (max_thread_ct - 1) : max_thread_ct;
5112 if (calc_thread_ct > variant_ct) {
5113 calc_thread_ct = variant_ct;
5114 }
5115
5116 const uint32_t is_single_prec = (glm_flags / kfGlmSinglePrecCc) & 1;
5117 const uint32_t main_omitted = parameter_subset && (!IsSet(parameter_subset, 1));
5118 const uint32_t xmain_ct = main_mutated + main_omitted;
5119 const uint32_t gcount_cc_col = glm_cols & kfGlmColGcountcc;
5120 // workflow is similar to --make-bed
5121 uintptr_t workspace_alloc;
5122 if (is_single_prec) {
5123 workspace_alloc = GetLogisticWorkspaceSizeF(sample_ct, biallelic_predictor_ct, domdev_present_p1, max_extra_allele_ct, constraint_ct, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5124 if (sample_ct_x) {
5125 const uintptr_t workspace_alloc_x = GetLogisticWorkspaceSizeF(sample_ct_x, biallelic_predictor_ct_x, domdev_present_p1, max_extra_allele_ct, constraint_ct_x, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5126 if (workspace_alloc_x > workspace_alloc) {
5127 workspace_alloc = workspace_alloc_x;
5128 }
5129 }
5130 if (sample_ct_y) {
5131 const uintptr_t workspace_alloc_y = GetLogisticWorkspaceSizeF(sample_ct_y, biallelic_predictor_ct_y, domdev_present_p1, max_extra_allele_ct, constraint_ct_y, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5132 if (workspace_alloc_y > workspace_alloc) {
5133 workspace_alloc = workspace_alloc_y;
5134 }
5135 }
5136 } else {
5137 workspace_alloc = GetLogisticWorkspaceSizeD(sample_ct, biallelic_predictor_ct, domdev_present_p1, max_extra_allele_ct, constraint_ct, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5138 if (sample_ct_x) {
5139 const uintptr_t workspace_alloc_x = GetLogisticWorkspaceSizeD(sample_ct_x, biallelic_predictor_ct_x, domdev_present_p1, max_extra_allele_ct, constraint_ct_x, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5140 if (workspace_alloc_x > workspace_alloc) {
5141 workspace_alloc = workspace_alloc_x;
5142 }
5143 }
5144 if (sample_ct_y) {
5145 const uintptr_t workspace_alloc_y = GetLogisticWorkspaceSizeD(sample_ct_y, biallelic_predictor_ct_y, domdev_present_p1, max_extra_allele_ct, constraint_ct_y, xmain_ct, gcount_cc_col, is_sometimes_firth, is_cc_residualize);
5146 if (workspace_alloc_y > workspace_alloc) {
5147 workspace_alloc = workspace_alloc_y;
5148 }
5149 }
5150 }
5151 // +1 is for top-level common->workspace_bufs
5152 const uint32_t dosage_is_present = pgfip->gflags & kfPgenGlobalDosagePresent;
5153 uintptr_t thread_xalloc_cacheline_ct = (workspace_alloc / kCacheline) + 1;
5154
5155 uintptr_t per_variant_xalloc_byte_ct = max_sample_ct * local_covar_ct * (2 - is_single_prec) * sizeof(float);
5156 uintptr_t per_alt_allele_xalloc_byte_ct = sizeof(LogisticAuxResult);
5157 if (beta_se_multiallelic_fused) {
5158 per_variant_xalloc_byte_ct += 2 * max_reported_test_ct * sizeof(double);
5159 } else {
5160 per_alt_allele_xalloc_byte_ct += 2 * max_reported_test_ct * sizeof(double);
5161 }
5162 STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs);
5163 common->thread_mhc = nullptr;
5164 common->dosage_presents = nullptr;
5165 common->dosage_mains = nullptr;
5166 uint32_t read_block_size;
5167 uintptr_t max_alt_allele_block_size;
5168 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))) {
5169 goto GlmLogistic_ret_NOMEM;
5170 }
5171 if (unlikely(SetThreadCt(calc_thread_ct, &tg))) {
5172 goto GlmLogistic_ret_NOMEM;
5173 }
5174 LogisticAuxResult* logistic_block_aux_bufs[2];
5175 double* block_beta_se_bufs[2];
5176
5177 for (uint32_t uii = 0; uii != 2; ++uii) {
5178 if (unlikely(BIGSTACK_ALLOC_X(LogisticAuxResult, max_alt_allele_block_size, &(logistic_block_aux_bufs[uii])))) {
5179 goto GlmLogistic_ret_NOMEM;
5180 }
5181 if (beta_se_multiallelic_fused) {
5182 if (unlikely(bigstack_alloc_d(read_block_size * 2 * max_reported_test_ct, &(block_beta_se_bufs[uii])))) {
5183 goto GlmLogistic_ret_NOMEM;
5184 }
5185 } else {
5186 if (unlikely(bigstack_alloc_d(max_alt_allele_block_size * 2 * max_reported_test_ct, &(block_beta_se_bufs[uii])))) {
5187 goto GlmLogistic_ret_NOMEM;
5188 }
5189 }
5190 if (local_covar_ct) {
5191 // bugfix (18 May 2018): don't want sizeof(float) here
5192 if (is_single_prec) {
5193 if (unlikely(bigstack_alloc_f(read_block_size * max_sample_ct * local_covar_ct, &(ctx->local_covars_vcmaj_f[uii])))) {
5194 goto GlmLogistic_ret_NOMEM;
5195 }
5196 } else {
5197 if (unlikely(bigstack_alloc_d(read_block_size * max_sample_ct * local_covar_ct, &(ctx->local_covars_vcmaj_d[uii])))) {
5198 goto GlmLogistic_ret_NOMEM;
5199 }
5200 }
5201 } else {
5202 ctx->local_covars_vcmaj_f[uii] = nullptr;
5203 ctx->local_covars_vcmaj_d[uii] = nullptr;
5204 }
5205 }
5206
5207 if (is_single_prec && (max_sample_ct > 100000)) {
5208 logerrputs("Warning: --glm's 'single-prec-cc' mode is not recommended on more than ~100000\nsamples.\n");
5209 }
5210 common->workspace_bufs = S_CAST(unsigned char**, bigstack_alloc_raw_rd(calc_thread_ct * sizeof(intptr_t)));
5211 for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) {
5212 common->workspace_bufs[tidx] = S_CAST(unsigned char*, bigstack_alloc_raw(workspace_alloc));
5213 }
5214 common->err_info = (~0LLU) << 32;
5215 #ifndef NDEBUG
5216 // temporary debug
5217 common->outname = outname;
5218 #endif
5219 SetThreadFuncAndData(is_single_prec? GlmLogisticThreadF : GlmLogisticThreadD, ctx, &tg);
5220
5221 const uint32_t ref_col = glm_cols & kfGlmColRef;
5222 const uint32_t alt1_col = glm_cols & kfGlmColAlt1;
5223 const uint32_t alt_col = glm_cols & kfGlmColAlt;
5224 const uintptr_t* nonref_flags = pgfip->nonref_flags;
5225 const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags);
5226 const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, glm_cols / kfGlmColMaybeprovref, raw_variant_ct, all_nonref);
5227 const uint32_t omitted_col = glm_cols & kfGlmColOmitted;
5228 const uint32_t ax_col = glm_cols & kfGlmColAx;
5229 const uint32_t a1_ct_col = glm_cols & kfGlmColA1count;
5230 const uint32_t tot_allele_col = glm_cols & kfGlmColTotallele;
5231 const uint32_t a1_ct_cc_col = glm_cols & kfGlmColA1countcc;
5232 const uint32_t tot_allele_cc_col = glm_cols & kfGlmColTotallelecc;
5233 const uint32_t a1_freq_col = glm_cols & kfGlmColA1freq;
5234 const uint32_t a1_freq_cc_col = glm_cols & kfGlmColA1freqcc;
5235 const uint32_t mach_r2_col = glm_cols & kfGlmColMachR2;
5236 const uint32_t firth_yn_col = (glm_cols & kfGlmColFirthYn) && is_sometimes_firth && (!is_always_firth);
5237 const uint32_t nobs_col = glm_cols & kfGlmColNobs;
5238 const uint32_t orbeta_col = glm_cols & (kfGlmColBeta | kfGlmColOrbeta);
5239 const uint32_t report_beta_instead_of_odds_ratio = glm_cols & kfGlmColBeta;
5240 const uint32_t se_col = glm_cols & kfGlmColSe;
5241 const uint32_t ci_col = (ci_size != 0.0) && (glm_cols & kfGlmColCi);
5242 const uint32_t z_col = glm_cols & kfGlmColTz;
5243 const uint32_t p_col = glm_cols & kfGlmColP;
5244 const uint32_t err_col = glm_cols & kfGlmColErr;
5245 *cswritep++ = '#';
5246 if (chr_col) {
5247 cswritep = strcpya_k(cswritep, "CHROM\t");
5248 }
5249 if (variant_bps) {
5250 cswritep = strcpya_k(cswritep, "POS\t");
5251 }
5252 cswritep = strcpya_k(cswritep, "ID");
5253 if (ref_col) {
5254 cswritep = strcpya_k(cswritep, "\tREF");
5255 }
5256 if (alt1_col) {
5257 cswritep = strcpya_k(cswritep, "\tALT1");
5258 }
5259 if (alt_col) {
5260 cswritep = strcpya_k(cswritep, "\tALT");
5261 }
5262 if (provref_col) {
5263 cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?");
5264 }
5265 cswritep = strcpya_k(cswritep, "\tA1");
5266 if (omitted_col) {
5267 cswritep = strcpya_k(cswritep, "\tOMITTED");
5268 }
5269 if (ax_col) {
5270 cswritep = strcpya_k(cswritep, "\tAX");
5271 }
5272 if (a1_ct_col) {
5273 cswritep = strcpya_k(cswritep, "\tA1_CT");
5274 }
5275 if (tot_allele_col) {
5276 cswritep = strcpya_k(cswritep, "\tALLELE_CT");
5277 }
5278 if (a1_ct_cc_col) {
5279 cswritep = strcpya_k(cswritep, "\tA1_CASE_CT\tA1_CTRL_CT");
5280 }
5281 if (tot_allele_cc_col) {
5282 cswritep = strcpya_k(cswritep, "\tCASE_ALLELE_CT\tCTRL_ALLELE_CT");
5283 }
5284 if (gcount_cc_col) {
5285 cswritep = strcpya_k(cswritep, "\tCASE_NON_A1_CT\tCASE_HET_A1_CT\tCASE_HOM_A1_CT\tCTRL_NON_A1_CT\tCTRL_HET_A1_CT\tCTRL_HOM_A1_CT");
5286 }
5287 if (a1_freq_col) {
5288 cswritep = strcpya_k(cswritep, "\tA1_FREQ");
5289 }
5290 if (a1_freq_cc_col) {
5291 cswritep = strcpya_k(cswritep, "\tA1_CASE_FREQ\tA1_CTRL_FREQ");
5292 }
5293 if (mach_r2_col) {
5294 cswritep = strcpya_k(cswritep, "\tMACH_R2");
5295 }
5296 if (firth_yn_col) {
5297 cswritep = strcpya_k(cswritep, "\tFIRTH?");
5298 }
5299 if (test_col) {
5300 cswritep = strcpya_k(cswritep, "\tTEST");
5301 }
5302 if (nobs_col) {
5303 cswritep = strcpya_k(cswritep, "\tOBS_CT");
5304 }
5305 if (orbeta_col) {
5306 if (report_beta_instead_of_odds_ratio) {
5307 cswritep = strcpya_k(cswritep, "\tBETA");
5308 } else {
5309 cswritep = strcpya_k(cswritep, "\tOR");
5310 }
5311 }
5312 if (se_col) {
5313 if (report_beta_instead_of_odds_ratio) {
5314 cswritep = strcpya_k(cswritep, "\tSE");
5315 } else {
5316 cswritep = strcpya_k(cswritep, "\tLOG(OR)_SE");
5317 }
5318 }
5319 double ci_zt = 0.0;
5320 if (ci_col) {
5321 cswritep = strcpya_k(cswritep, "\tL");
5322 cswritep = dtoa_g(ci_size * 100, cswritep);
5323 cswritep = strcpya_k(cswritep, "\tU");
5324 cswritep = dtoa_g(ci_size * 100, cswritep);
5325 ci_zt = QuantileToZscore((ci_size + 1.0) * 0.5);
5326 }
5327 if (z_col) {
5328 if (!constraint_ct) {
5329 cswritep = strcpya_k(cswritep, "\tZ_STAT");
5330 } else {
5331 // F-statistic for joint tests.
5332 cswritep = strcpya_k(cswritep, "\tZ_OR_F_STAT");
5333 }
5334 }
5335 if (p_col) {
5336 if (report_neglog10p) {
5337 cswritep = strcpya_k(cswritep, "\tNEG_LOG10_P");
5338 } else {
5339 cswritep = strcpya_k(cswritep, "\tP");
5340 }
5341 }
5342 if (err_col) {
5343 cswritep = strcpya_k(cswritep, "\tERRCODE");
5344 }
5345 AppendBinaryEoln(&cswritep);
5346
5347 // Main workflow:
5348 // 1. Set n=0, load/skip block 0
5349 //
5350 // 2. Spawn threads processing block n
5351 // 3. If n>0, write results for block (n-1)
5352 // 4. Increment n by 1
5353 // 5. Load/skip block n unless eof
5354 // 6. Join threads
5355 // 7. Goto step 2 unless eof
5356 //
5357 // 8, Write results for last block
5358 uintptr_t write_variant_uidx_base = 0;
5359 uintptr_t cur_bits = variant_include[0];
5360 uint32_t parity = 0;
5361 uint32_t read_block_idx = 0;
5362 uint32_t chr_fo_idx = UINT32_MAX;
5363 uint32_t chr_end = 0;
5364 uint32_t chr_buf_blen = 0;
5365 uint32_t suppress_mach_r2 = 0;
5366
5367 uint32_t cur_biallelic_reported_test_ct = 0;
5368 uint32_t primary_reported_test_idx = include_intercept;
5369 uint32_t cur_constraint_ct = 0;
5370
5371 const char* const* cur_test_names = nullptr;
5372 uint32_t prev_block_variant_ct = 0;
5373 uint32_t pct = 0;
5374 uint32_t next_print_variant_idx = variant_ct / 100;
5375 uint32_t allele_ct = 2;
5376 uint32_t omitted_allele_idx = 0;
5377 uintptr_t valid_allele_ct = 0;
5378 logprintfww5("--glm %s regression on phenotype '%s': ", is_always_firth? "Firth" : (is_sometimes_firth? "logistic-Firth hybrid" : "logistic"), cur_pheno_name);
5379 fputs("0%", stdout);
5380 fflush(stdout);
5381 for (uint32_t variant_idx = 0; ; ) {
5382 const uint32_t cur_block_variant_ct = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr);
5383 if (unlikely(reterr)) {
5384 goto GlmLogistic_ret_PGR_FAIL;
5385 }
5386 if (local_covar_ct && cur_block_variant_ct) {
5387 const uint32_t uidx_start = read_block_idx * read_block_size;
5388 const uint32_t uidx_end = MINV(raw_variant_ct, uidx_start + read_block_size);
5389 if (local_variant_include) {
5390 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, is_single_prec? ctx->local_covars_vcmaj_f[parity] : nullptr, is_single_prec? nullptr : ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
5391 } else {
5392 float* prev_local_covar_row_f = nullptr;
5393 if (variant_idx) {
5394 prev_local_covar_row_f = &(ctx->local_covars_vcmaj_f[1 - parity][S_CAST(uintptr_t, read_block_size - 1) * max_sample_ct * local_covar_ct]);
5395 }
5396 reterr = ReadRfmix2Block(common, variant_bps, local_sample_uidx_order, prev_local_covar_row_f, nullptr, 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, is_single_prec? ctx->local_covars_vcmaj_f[parity] : nullptr, is_single_prec? nullptr : ctx->local_covars_vcmaj_d[parity], local_sample_idx_order);
5397 }
5398 if (unlikely(reterr)) {
5399 goto GlmLogistic_ret_1;
5400 }
5401 }
5402 if (variant_idx) {
5403 JoinThreads(&tg);
5404 reterr = S_CAST(PglErr, common->err_info);
5405 if (unlikely(reterr)) {
5406 PgenErrPrintNV(reterr, common->err_info >> 32);
5407 goto GlmLogistic_ret_1;
5408 }
5409 }
5410 if (!IsLastBlock(&tg)) {
5411 common->cur_block_variant_ct = cur_block_variant_ct;
5412 const uint32_t uidx_start = read_block_idx * read_block_size;
5413 ComputeUidxStartPartition(variant_include, cur_block_variant_ct, calc_thread_ct, uidx_start, common->read_variant_uidx_starts);
5414 PgrCopyBaseAndOffset(pgfip, calc_thread_ct, common->pgr_ptrs);
5415 ctx->block_aux = logistic_block_aux_bufs[parity];
5416 common->block_beta_se = block_beta_se_bufs[parity];
5417 if (variant_idx + cur_block_variant_ct == variant_ct) {
5418 DeclareLastThreadBlock(&tg);
5419 }
5420 if (unlikely(SpawnThreads(&tg))) {
5421 goto GlmLogistic_ret_THREAD_CREATE_FAIL;
5422 }
5423 }
5424 parity = 1 - parity;
5425 if (variant_idx) {
5426 // write *previous* block results
5427 const double* beta_se_iter = block_beta_se_bufs[parity];
5428 const LogisticAuxResult* cur_block_aux = logistic_block_aux_bufs[parity];
5429 uintptr_t allele_bidx = 0;
5430 for (uint32_t variant_bidx = 0; variant_bidx != prev_block_variant_ct; ++variant_bidx) {
5431 const uint32_t write_variant_uidx = BitIter1(variant_include, &write_variant_uidx_base, &cur_bits);
5432 if (write_variant_uidx >= chr_end) {
5433 do {
5434 ++chr_fo_idx;
5435 chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
5436 } while (write_variant_uidx >= chr_end);
5437 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
5438 if ((chr_idx == x_code) && sample_ct_x) {
5439 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_x;
5440 cur_constraint_ct = constraint_ct_x;
5441 cur_test_names = test_names_x;
5442 } else if ((chr_idx == y_code) && sample_ct_y) {
5443 cur_biallelic_reported_test_ct = biallelic_reported_test_ct_y;
5444 cur_constraint_ct = constraint_ct_y;
5445 cur_test_names = test_names_y;
5446 } else {
5447 cur_biallelic_reported_test_ct = biallelic_reported_test_ct;
5448 cur_constraint_ct = constraint_ct;
5449 cur_test_names = test_names;
5450 }
5451 suppress_mach_r2 = (chr_idx == x_code) || (chr_idx == mt_code);
5452 if (cur_constraint_ct) {
5453 // bugfix (17 May 2018): this was using reported_test_ct instead
5454 // of cur_reported_test_ct.
5455 primary_reported_test_idx = cur_biallelic_reported_test_ct - 1;
5456 }
5457 if (chr_col) {
5458 char* chr_name_end = chrtoa(cip, chr_idx, chr_buf);
5459 *chr_name_end = '\t';
5460 chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf);
5461 }
5462 }
5463 uintptr_t allele_idx_offset_base = write_variant_uidx * 2;
5464 if (allele_idx_offsets) {
5465 allele_idx_offset_base = allele_idx_offsets[write_variant_uidx];
5466 allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offsets[write_variant_uidx];
5467 }
5468 const uint32_t allele_ct_m1 = allele_ct - 1;
5469 const uint32_t extra_allele_ct = allele_ct - 2;
5470 if (omitted_alleles) {
5471 omitted_allele_idx = omitted_alleles[write_variant_uidx];
5472 }
5473 const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]);
5474 uint32_t variant_is_valid = 0;
5475 uint32_t a1_allele_idx = 0;
5476 for (uint32_t nonomitted_allele_idx = 0; nonomitted_allele_idx != allele_ct_m1; ++nonomitted_allele_idx, ++a1_allele_idx) {
5477 if (beta_se_multiallelic_fused) {
5478 if (!nonomitted_allele_idx) {
5479 primary_reported_test_idx = include_intercept;
5480 } else {
5481 primary_reported_test_idx = cur_biallelic_reported_test_ct + nonomitted_allele_idx - 1;
5482 }
5483 }
5484 if (nonomitted_allele_idx == omitted_allele_idx) {
5485 ++a1_allele_idx;
5486 }
5487 const double primary_beta = beta_se_iter[primary_reported_test_idx * 2];
5488 const double primary_se = beta_se_iter[primary_reported_test_idx * 2 + 1];
5489 const uint32_t allele_is_valid = (primary_se != -9.0);
5490 variant_is_valid |= allele_is_valid;
5491 {
5492 const LogisticAuxResult* auxp = &(cur_block_aux[allele_bidx]);
5493 if (ln_pfilter <= 0.0) {
5494 if (!allele_is_valid) {
5495 goto GlmLogistic_allele_iterate;
5496 }
5497 double permstat;
5498 double primary_ln_pval;
5499 if (!cur_constraint_ct) {
5500 permstat = fabs(primary_beta / primary_se);
5501 // could precompute a tstat threshold instead
5502 primary_ln_pval = ZscoreToLnP(permstat);
5503 } else {
5504 // cur_constraint_ct may be different on chrX/chrY than it is
5505 // on autosomes, so just have permstat be -log(pval) to be
5506 // safe
5507 primary_ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
5508 permstat = -primary_ln_pval;
5509 }
5510 if (primary_ln_pval > ln_pfilter) {
5511 if (orig_ln_pvals) {
5512 orig_ln_pvals[valid_allele_ct] = primary_ln_pval;
5513 }
5514 if (orig_permstat) {
5515 orig_permstat[valid_allele_ct] = permstat;
5516 }
5517 goto GlmLogistic_allele_iterate;
5518 }
5519 }
5520 uint32_t inner_reported_test_ct = cur_biallelic_reported_test_ct;
5521 if (extra_allele_ct) {
5522 if (beta_se_multiallelic_fused) {
5523 // in fused case, we're only performing a single multiple
5524 // regression, so list all additive results together,
5525 // possibly with intercept before.
5526 if (!nonomitted_allele_idx) {
5527 inner_reported_test_ct = 1 + include_intercept;
5528 } else if (nonomitted_allele_idx == extra_allele_ct) {
5529 inner_reported_test_ct -= include_intercept;
5530 } else {
5531 inner_reported_test_ct = 1;
5532 }
5533 } else if (!hide_covar) {
5534 inner_reported_test_ct += extra_allele_ct;
5535 }
5536 }
5537 // possible todo: make number-to-string operations, strlen(),
5538 // etc. happen only once per variant.
5539 for (uint32_t allele_test_idx = 0; allele_test_idx != inner_reported_test_ct; ++allele_test_idx) {
5540 uint32_t test_idx = allele_test_idx;
5541 if (beta_se_multiallelic_fused && nonomitted_allele_idx) {
5542 if (!allele_test_idx) {
5543 test_idx = primary_reported_test_idx;
5544 } else {
5545 // bugfix (26 Jun 2019): only correct to add 1 here in
5546 // include_intercept case
5547 test_idx += include_intercept;
5548 }
5549 }
5550 if (chr_col) {
5551 cswritep = memcpya(cswritep, chr_buf, chr_buf_blen);
5552 }
5553 if (variant_bps) {
5554 cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep);
5555 }
5556 cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]);
5557 if (ref_col) {
5558 *cswritep++ = '\t';
5559 cswritep = strcpya(cswritep, cur_alleles[0]);
5560 }
5561 if (alt1_col) {
5562 *cswritep++ = '\t';
5563 cswritep = strcpya(cswritep, cur_alleles[1]);
5564 }
5565 if (alt_col) {
5566 *cswritep++ = '\t';
5567 for (uint32_t tmp_allele_idx = 1; tmp_allele_idx != allele_ct; ++tmp_allele_idx) {
5568 if (unlikely(Cswrite(&css, &cswritep))) {
5569 goto GlmLogistic_ret_WRITE_FAIL;
5570 }
5571 cswritep = strcpyax(cswritep, cur_alleles[tmp_allele_idx], ',');
5572 }
5573 --cswritep;
5574 }
5575 *cswritep++ = '\t';
5576 if (provref_col) {
5577 *cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N';
5578 *cswritep++ = '\t';
5579 }
5580 const uint32_t multi_a1 = extra_allele_ct && beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx);
5581 if (multi_a1) {
5582 for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) {
5583 if (allele_idx == omitted_allele_idx) {
5584 continue;
5585 }
5586 if (unlikely(Cswrite(&css, &cswritep))) {
5587 goto GlmLogistic_ret_WRITE_FAIL;
5588 }
5589 cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ',');
5590 }
5591 --cswritep;
5592 } else {
5593 cswritep = strcpya(cswritep, cur_alleles[a1_allele_idx]);
5594 }
5595 if (omitted_col) {
5596 *cswritep++ = '\t';
5597 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
5598 }
5599 if (ax_col) {
5600 *cswritep++ = '\t';
5601 if (beta_se_multiallelic_fused && (test_idx != primary_reported_test_idx)) {
5602 if (unlikely(Cswrite(&css, &cswritep))) {
5603 goto GlmLogistic_ret_WRITE_FAIL;
5604 }
5605 cswritep = strcpya(cswritep, cur_alleles[omitted_allele_idx]);
5606 } else {
5607 for (uint32_t tmp_allele_idx = 0; tmp_allele_idx != allele_ct; ++tmp_allele_idx) {
5608 if (tmp_allele_idx == a1_allele_idx) {
5609 continue;
5610 }
5611 if (unlikely(Cswrite(&css, &cswritep))) {
5612 goto GlmLogistic_ret_WRITE_FAIL;
5613 }
5614 cswritep = strcpyax(cswritep, cur_alleles[tmp_allele_idx], ',');
5615 }
5616 --cswritep;
5617 }
5618 }
5619 if (a1_ct_col) {
5620 *cswritep++ = '\t';
5621 if (!multi_a1) {
5622 cswritep = dtoa_g(auxp->a1_dosage, cswritep);
5623 } else {
5624 cswritep = strcpya_k(cswritep, "NA");
5625 }
5626 }
5627 if (tot_allele_col) {
5628 *cswritep++ = '\t';
5629 cswritep = u32toa(auxp->allele_obs_ct, cswritep);
5630 }
5631 if (a1_ct_cc_col) {
5632 *cswritep++ = '\t';
5633 if (!multi_a1) {
5634 cswritep = dtoa_g(auxp->a1_case_dosage, cswritep);
5635 *cswritep++ = '\t';
5636 cswritep = dtoa_g(auxp->a1_dosage - auxp->a1_case_dosage, cswritep);
5637 } else {
5638 cswritep = strcpya_k(cswritep, "NA\tNA");
5639 }
5640 }
5641 if (tot_allele_cc_col) {
5642 *cswritep++ = '\t';
5643 cswritep = u32toa_x(auxp->case_allele_obs_ct, '\t', cswritep);
5644 cswritep = u32toa(auxp->allele_obs_ct - auxp->case_allele_obs_ct, cswritep);
5645 }
5646 if (gcount_cc_col) {
5647 if (!multi_a1) {
5648 STD_ARRAY_KREF(uint32_t, 6) cur_geno_hardcall_cts = auxp->geno_hardcall_cts;
5649 for (uint32_t uii = 0; uii != 6; ++uii) {
5650 *cswritep++ = '\t';
5651 cswritep = u32toa(cur_geno_hardcall_cts[uii], cswritep);
5652 }
5653 } else {
5654 cswritep = strcpya_k(cswritep, "\tNA\tNA\tNA\tNA\tNA\tNA");
5655 }
5656 }
5657 if (a1_freq_col) {
5658 *cswritep++ = '\t';
5659 if (!multi_a1) {
5660 cswritep = dtoa_g(auxp->a1_dosage / S_CAST(double, auxp->allele_obs_ct), cswritep);
5661 } else {
5662 cswritep = strcpya_k(cswritep, "NA");
5663 }
5664 }
5665 if (a1_freq_cc_col) {
5666 *cswritep++ = '\t';
5667 if (!multi_a1) {
5668 cswritep = dtoa_g(auxp->a1_case_dosage / S_CAST(double, auxp->case_allele_obs_ct), cswritep);
5669 *cswritep++ = '\t';
5670 cswritep = dtoa_g((auxp->a1_dosage - auxp->a1_case_dosage) / S_CAST(double, auxp->allele_obs_ct - auxp->case_allele_obs_ct), cswritep);
5671 } else {
5672 cswritep = strcpya_k(cswritep, "NA\tNA");
5673 }
5674 }
5675 if (mach_r2_col) {
5676 *cswritep++ = '\t';
5677 if (!suppress_mach_r2) {
5678 cswritep = dtoa_g(auxp->mach_r2, cswritep);
5679 } else {
5680 cswritep = strcpya_k(cswritep, "NA");
5681 }
5682 }
5683 if (firth_yn_col) {
5684 *cswritep++ = '\t';
5685 // 'Y' - 'N' = 11
5686 *cswritep++ = 'N' + 11 * auxp->firth_fallback;
5687 }
5688 if (test_col) {
5689 *cswritep++ = '\t';
5690 if (test_idx < cur_biallelic_reported_test_ct) {
5691 cswritep = strcpya(cswritep, cur_test_names[test_idx]);
5692 } else {
5693 // always use basic dosage for untested alleles
5694 cswritep = strcpya_k(cswritep, "ADD");
5695 if (!beta_se_multiallelic_fused) {
5696 // extra alt allele covariate.
5697 uint32_t test_xallele_idx = test_idx - cur_biallelic_reported_test_ct;
5698 // now we have the 0-based relative position in a list
5699 // with the omitted_allele_idx and a1_allele_idx removed.
5700 // correct this to the absolute index. (there may be a
5701 // cleaner way to do this with nonomitted_allele_idx?)
5702 if (omitted_allele_idx < a1_allele_idx) {
5703 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
5704 }
5705 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= a1_allele_idx);
5706 if (a1_allele_idx < omitted_allele_idx) {
5707 test_xallele_idx = test_xallele_idx + (test_xallele_idx >= omitted_allele_idx);
5708 }
5709 if (!test_xallele_idx) {
5710 cswritep = strcpya_k(cswritep, "_REF");
5711 } else {
5712 cswritep = strcpya_k(cswritep, "_ALT");
5713 cswritep = u32toa(test_xallele_idx, cswritep);
5714 }
5715 }
5716 }
5717 }
5718 if (nobs_col) {
5719 *cswritep++ = '\t';
5720 cswritep = u32toa(auxp->sample_obs_ct, cswritep);
5721 }
5722 double ln_pval = kLnPvalError;
5723 double permstat = 0.0;
5724 uint32_t test_is_valid;
5725 if ((!cur_constraint_ct) || (test_idx != primary_reported_test_idx)) {
5726 double beta = beta_se_iter[2 * test_idx];
5727 double se = beta_se_iter[2 * test_idx + 1];
5728 test_is_valid = (se != -9.0);
5729 if (test_is_valid) {
5730 permstat = beta / se;
5731 ln_pval = ZscoreToLnP(permstat);
5732 }
5733 if (orbeta_col) {
5734 *cswritep++ = '\t';
5735 if (test_is_valid) {
5736 if (report_beta_instead_of_odds_ratio) {
5737 cswritep = dtoa_g(beta, cswritep);
5738 } else {
5739 cswritep = lntoa_g(beta, cswritep);
5740 }
5741 } else {
5742 cswritep = strcpya_k(cswritep, "NA");
5743 }
5744 }
5745 if (se_col) {
5746 *cswritep++ = '\t';
5747 if (test_is_valid) {
5748 cswritep = dtoa_g(se, cswritep);
5749 } else {
5750 cswritep = strcpya_k(cswritep, "NA");
5751 }
5752 }
5753 if (ci_col) {
5754 *cswritep++ = '\t';
5755 if (test_is_valid) {
5756 const double ci_halfwidth = ci_zt * se;
5757 if (report_beta_instead_of_odds_ratio) {
5758 cswritep = dtoa_g(beta - ci_halfwidth, cswritep);
5759 *cswritep++ = '\t';
5760 cswritep = dtoa_g(beta + ci_halfwidth, cswritep);
5761 } else {
5762 cswritep = lntoa_g(beta - ci_halfwidth, cswritep);
5763 *cswritep++ = '\t';
5764 cswritep = lntoa_g(beta + ci_halfwidth, cswritep);
5765 }
5766 } else {
5767 cswritep = strcpya_k(cswritep, "NA\tNA");
5768 }
5769 }
5770 if (z_col) {
5771 *cswritep++ = '\t';
5772 if (test_is_valid) {
5773 cswritep = dtoa_g(permstat, cswritep);
5774 } else {
5775 cswritep = strcpya_k(cswritep, "NA");
5776 }
5777 }
5778 } else {
5779 // joint test: use F-test instead of Wald test
5780 test_is_valid = allele_is_valid;
5781 if (orbeta_col) {
5782 cswritep = strcpya_k(cswritep, "\tNA");
5783 }
5784 if (se_col) {
5785 cswritep = strcpya_k(cswritep, "\tNA");
5786 }
5787 if (ci_col) {
5788 cswritep = strcpya_k(cswritep, "\tNA\tNA");
5789 }
5790 if (z_col) {
5791 *cswritep++ = '\t';
5792 if (test_is_valid) {
5793 cswritep = dtoa_g(primary_se / u31tod(cur_constraint_ct), cswritep);
5794 } else {
5795 cswritep = strcpya_k(cswritep, "NA");
5796 }
5797 }
5798 // could avoid recomputing
5799 if (test_is_valid) {
5800 ln_pval = FstatToLnP(primary_se / u31tod(cur_constraint_ct), cur_constraint_ct, auxp->sample_obs_ct);
5801 permstat = -ln_pval;
5802 }
5803 }
5804 if (p_col) {
5805 *cswritep++ = '\t';
5806 if (test_is_valid) {
5807 if (report_neglog10p) {
5808 double reported_val = (-kRecipLn10) * ln_pval;
5809 cswritep = dtoa_g(reported_val, cswritep);
5810 } else {
5811 double reported_ln = MAXV(ln_pval, output_min_ln);
5812 cswritep = lntoa_g(reported_ln, cswritep);
5813 }
5814 } else {
5815 cswritep = strcpya_k(cswritep, "NA");
5816 }
5817 }
5818 if (err_col) {
5819 *cswritep++ = '\t';
5820 if (test_is_valid) {
5821 if (!auxp->is_unfinished) {
5822 *cswritep++ = '.';
5823 } else {
5824 cswritep = strcpya_k(cswritep, "UNFINISHED");
5825 }
5826 } else {
5827 uint64_t glm_errcode;
5828 memcpy(&glm_errcode, &(beta_se_iter[2 * test_idx]), 8);
5829 cswritep = AppendGlmErrstr(glm_errcode, cswritep);
5830 }
5831 }
5832 AppendBinaryEoln(&cswritep);
5833 if (unlikely(Cswrite(&css, &cswritep))) {
5834 goto GlmLogistic_ret_WRITE_FAIL;
5835 }
5836 if ((test_idx == primary_reported_test_idx) && allele_is_valid) {
5837 if (orig_ln_pvals) {
5838 orig_ln_pvals[valid_allele_ct] = ln_pval;
5839 }
5840 if (orig_permstat) {
5841 orig_permstat[valid_allele_ct] = permstat;
5842 }
5843 }
5844 }
5845 }
5846 GlmLogistic_allele_iterate:
5847 ++allele_bidx;
5848 valid_allele_ct += allele_is_valid;
5849 if (valid_alleles && allele_is_valid) {
5850 SetBit(allele_idx_offset_base + a1_allele_idx, valid_alleles);
5851 }
5852 if (!beta_se_multiallelic_fused) {
5853 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
5854 }
5855 }
5856 if (beta_se_multiallelic_fused) {
5857 beta_se_iter = &(beta_se_iter[2 * max_reported_test_ct]);
5858 }
5859 if ((!variant_is_valid) && valid_alleles) {
5860 ClearBit(write_variant_uidx, valid_variants);
5861 }
5862 }
5863 }
5864 if (variant_idx == variant_ct) {
5865 break;
5866 }
5867 if (variant_idx >= next_print_variant_idx) {
5868 if (pct > 10) {
5869 putc_unlocked('\b', stdout);
5870 }
5871 pct = (variant_idx * 100LLU) / variant_ct;
5872 printf("\b\b%u%%", pct++);
5873 fflush(stdout);
5874 next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100;
5875 }
5876 ++read_block_idx;
5877 prev_block_variant_ct = cur_block_variant_ct;
5878 variant_idx += cur_block_variant_ct;
5879 // crucially, this is independent of the PgenReader block_base
5880 // pointers
5881 pgfip->block_base = main_loadbufs[parity];
5882 }
5883 if (unlikely(CswriteCloseNull(&css, cswritep))) {
5884 goto GlmLogistic_ret_WRITE_FAIL;
5885 }
5886 if (pct > 10) {
5887 putc_unlocked('\b', stdout);
5888 }
5889 fputs("\b\b", stdout);
5890 logputs("done.\n");
5891 logprintf("Results written to %s .\n", outname);
5892 #ifndef NDEBUG
5893 // temporary debug
5894 if (g_debug_on && (variant_ct == 1) && ctx->separation_found) {
5895 char fname_buf[kPglFnamesize + 8];
5896 const uint32_t outname_slen = strlen(outname);
5897 char* fname_write_iter = memcpya(fname_buf, outname, outname_slen);
5898 strcpy_k(fname_write_iter, ".inputs");
5899 logprintf("Debug matrix written to %s .\n", fname_buf);
5900 }
5901 #endif
5902 *valid_allele_ct_ptr = valid_allele_ct;
5903 }
5904 while (0) {
5905 GlmLogistic_ret_NOMEM:
5906 reterr = kPglRetNomem;
5907 break;
5908 GlmLogistic_ret_TSTREAM_FAIL:
5909 TextStreamErrPrint("--glm local-covar= file", local_covar_txsp);
5910 break;
5911 GlmLogistic_ret_PGR_FAIL:
5912 PgenErrPrintN(reterr);
5913 break;
5914 GlmLogistic_ret_WRITE_FAIL:
5915 reterr = kPglRetWriteFail;
5916 break;
5917 GlmLogistic_ret_INCONSISTENT_INPUT:
5918 reterr = kPglRetInconsistentInput;
5919 break;
5920 GlmLogistic_ret_THREAD_CREATE_FAIL:
5921 reterr = kPglRetThreadCreateFail;
5922 break;
5923 }
5924 GlmLogistic_ret_1:
5925 CleanupThreads(&tg);
5926 CswriteCloseCond(&css, cswritep);
5927 BigstackReset(bigstack_mark);
5928 pgfip->block_base = nullptr;
5929 return reterr;
5930 }
5931
5932 /*
5933 static inline BoolErr vecaligned_malloc2(uintptr_t size, void* aligned_pp) {
5934 if (vecaligned_malloc(size, aligned_pp)) {
5935 return 1;
5936 }
5937 memset(*S_CAST(unsigned char**, aligned_pp), 85, size);
5938 return 0;
5939 }
5940
5941 void LogisticTestFirthF() {
5942 const uint32_t sample_ct = 2777;
5943 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kFloatPerFVec);
5944 const uint32_t predictor_ct = 5;
5945 const uint32_t predictor_ctav = RoundUpPow2(predictor_ct, kFloatPerFVec);
5946 float* yy;
5947 float* xx;
5948 float* beta;
5949 float* pp;
5950 float* vv;
5951 float* hh;
5952 float* ustar;
5953 float* delta;
5954 MatrixInvertBuf1* inv_1d_buf;
5955 double* dbl_2d_buf;
5956 float* hdiag;
5957 float* ww;
5958 float* hh0_buf;
5959 float* tmpnxk_buf;
5960 double* half_inverted_buf;
5961 vecaligned_malloc2(sample_ctav * sizeof(float), &yy);
5962 vecaligned_malloc2(sample_ctav * predictor_ct * sizeof(float), &xx);
5963 vecaligned_malloc2(predictor_ctav * sizeof(float), &beta);
5964 vecaligned_malloc2(sample_ctav * sizeof(float), &pp);
5965 vecaligned_malloc2(sample_ctav * sizeof(float), &vv);
5966 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(float), &hh);
5967 vecaligned_malloc2(predictor_ctav * sizeof(float), &ustar);
5968 vecaligned_malloc2(predictor_ctav * sizeof(float), &delta);
5969 vecaligned_malloc2(predictor_ct * kMatrixInvertBuf1CheckedAlloc, &inv_1d_buf);
5970 vecaligned_malloc2(predictor_ct * MAXV(predictor_ct, 7) * sizeof(double), &dbl_2d_buf);
5971 vecaligned_malloc2(sample_ctav * sizeof(float), &hdiag);
5972 vecaligned_malloc2(sample_ctav * sizeof(float), &ww);
5973 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(float), &hh0_buf);
5974 vecaligned_malloc2(predictor_ct * sample_ctav * sizeof(float), &tmpnxk_buf);
5975 vecaligned_malloc2(predictor_ct * MAXV(predictor_ct, 3) * sizeof(double), &half_inverted_buf);
5976 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
5977 if (cos(S_CAST(double, sample_idx + 1) * 0.001) > 0.0) {
5978 yy[sample_idx] = 1.0;
5979 } else {
5980 yy[sample_idx] = 0.0;
5981 }
5982 }
5983 ZeroFArr(sample_ctav - sample_ct, &(yy[sample_ct]));
5984 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
5985 float* xx_col = &(xx[pred_idx * sample_ctav]);
5986 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
5987 float dxx = S_CAST(float, 1.0);
5988 float dyy = S_CAST(float, sample_idx + 1) * S_CAST(float, 0.001);
5989 for (uint32_t uii = 0; uii < pred_idx; ++uii) {
5990 dxx *= dyy;
5991 }
5992 xx_col[sample_idx] = dxx;
5993 }
5994 ZeroFArr(sample_ctav - sample_ct, &(xx_col[sample_ct]));
5995 }
5996 ZeroFArr(predictor_ctav, beta);
5997 uint32_t is_unfinished = 0;
5998 BoolErr reterr = FirthRegressionF(yy, xx, nullptr, sample_ct, predictor_ct, beta, &is_unfinished, hh, half_inverted_buf, inv_1d_buf, dbl_2d_buf, pp, vv, ustar, delta, hdiag, ww, hh0_buf, tmpnxk_buf);
5999 printf("coef: %g %g %g %g %g\n", S_CAST(double, beta[0]), S_CAST(double, beta[1]), S_CAST(double, beta[2]), S_CAST(double, beta[3]), S_CAST(double, beta[4]));
6000 printf("sqrt(diag(hh)): %g %g %g %g %g\n", S_CAST(double, sqrtf(hh[0])), S_CAST(double, sqrtf(hh[predictor_ctav + 1])), S_CAST(double, sqrtf(hh[2 * (predictor_ctav + 1)])), S_CAST(double, sqrtf(hh[3 * (predictor_ctav + 1)])), S_CAST(double, sqrtf(hh[4 * (predictor_ctav + 1)])));
6001 printf("p-values:");
6002 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
6003 const double bt = S_CAST(double, beta[pred_idx]);
6004 const double se = S_CAST(double, sqrtf(hh[pred_idx * (predictor_ctav + 1)]));
6005 const double permstat = bt / se;
6006 const double ln_pval = ZscoreToLnP(permstat);
6007 char outbuf[24];
6008 char* outbuf_iter = outbuf;
6009 *outbuf_iter++ = ' ';
6010 outbuf_iter = lntoa_g(ln_pval, outbuf_iter);
6011 *outbuf_iter = '\0';
6012 fputs(outbuf, stdout);
6013 }
6014 printf("\n");
6015 printf("reterr: %u is_unfinished: %u\n", S_CAST(uint32_t, reterr), is_unfinished);
6016 }
6017
6018 void LogisticTestD() {
6019 const uint32_t sample_ct = 2777;
6020 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
6021 const uint32_t predictor_ct = 5;
6022 const uint32_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
6023 double* yy;
6024 double* xx;
6025 double* coef;
6026 double* ll;
6027 double* pp;
6028 double* vv;
6029 double* hh;
6030 double* grad;
6031 double* dcoef;
6032 MatrixInvertBuf1* inv_1d_buf;
6033 double* dbl_2d_buf;
6034 vecaligned_malloc2(sample_ctav * sizeof(double), &yy);
6035 vecaligned_malloc2(sample_ctav * predictor_ct * sizeof(double), &xx);
6036 vecaligned_malloc2(predictor_ctav * sizeof(double), &coef);
6037 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(double), &ll);
6038 vecaligned_malloc2(sample_ctav * sizeof(double), &pp);
6039 vecaligned_malloc2(sample_ctav * sizeof(double), &vv);
6040 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(double), &hh);
6041 vecaligned_malloc2(predictor_ctav * sizeof(double), &grad);
6042 vecaligned_malloc2(predictor_ctav * sizeof(double), &dcoef);
6043 vecaligned_malloc2(predictor_ct * kMatrixInvertBuf1CheckedAlloc, &inv_1d_buf);
6044 vecaligned_malloc2(predictor_ct * MAXV(predictor_ct, 7) * sizeof(double), &dbl_2d_buf);
6045 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
6046 if (cos(S_CAST(double, sample_idx + 1) * 0.001) > 0.0) {
6047 yy[sample_idx] = 1.0;
6048 } else {
6049 yy[sample_idx] = 0.0;
6050 }
6051 }
6052 ZeroDArr(sample_ctav - sample_ct, &(yy[sample_ct]));
6053 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
6054 double* xx_col = &(xx[pred_idx * sample_ctav]);
6055 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
6056 double dxx = 1.0;
6057 double dyy = S_CAST(double, sample_idx + 1) * 0.001;
6058 for (uint32_t uii = 0; uii < pred_idx; ++uii) {
6059 dxx *= dyy;
6060 }
6061 xx_col[sample_idx] = dxx;
6062 }
6063 ZeroDArr(sample_ctav - sample_ct, &(xx_col[sample_ct]));
6064 }
6065 ZeroDArr(predictor_ctav, coef);
6066 uint32_t is_unfinished = 0;
6067 BoolErr reterr = LogisticRegressionD(yy, xx, nullptr, sample_ct, predictor_ct, &is_unfinished, coef, ll, pp, vv, hh, grad, dcoef, inv_1d_buf, dbl_2d_buf);
6068 printf("coef: %g %g %g %g %g\n", coef[0], coef[1], coef[2], coef[3], coef[4]);
6069 for (uint32_t pred_uidx = 0; pred_uidx != predictor_ct; ++pred_uidx) {
6070 double* hh_inv_row = &(hh[pred_uidx * predictor_ctav]);
6071 ZeroDArr(predictor_ct, grad);
6072 grad[pred_uidx] = 1.0;
6073 SolveLinearSystemD(ll, grad, predictor_ct, hh_inv_row);
6074 }
6075 printf("sqrt(diag(hh)): %g %g %g %g %g\n", sqrt(hh[0]), sqrt(hh[predictor_ctav + 1]), sqrt(hh[2 * (predictor_ctav + 1)]), sqrt(hh[3 * (predictor_ctav + 1)]), sqrt(hh[4 * (predictor_ctav + 1)]));
6076 printf("p-values:");
6077 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
6078 const double bt = coef[pred_idx];
6079 const double se = sqrt(hh[pred_idx * (predictor_ctav + 1)]);
6080 const double permstat = bt / se;
6081 const double ln_pval = ZscoreToLnP(permstat);
6082 char outbuf[24];
6083 char* outbuf_iter = outbuf;
6084 *outbuf_iter++ = ' ';
6085 outbuf_iter = lntoa_g(ln_pval, outbuf_iter);
6086 *outbuf_iter = '\0';
6087 fputs(outbuf, stdout);
6088 }
6089 printf("\n");
6090 printf("reterr: %u is_unfinished: %u\n", S_CAST(uint32_t, reterr), is_unfinished);
6091 }
6092
6093 void LogisticTestFirthD() {
6094 const uint32_t sample_ct = 2777;
6095 const uint32_t sample_ctav = RoundUpPow2(sample_ct, kDoublePerDVec);
6096 const uint32_t predictor_ct = 5;
6097 const uint32_t predictor_ctav = RoundUpPow2(predictor_ct, kDoublePerDVec);
6098 double* yy;
6099 double* xx;
6100 double* beta;
6101 double* pp;
6102 double* vv;
6103 double* hh;
6104 double* ustar;
6105 double* delta;
6106 MatrixInvertBuf1* inv_1d_buf;
6107 double* dbl_2d_buf;
6108 double* hdiag;
6109 double* ww;
6110 double* hh0_buf;
6111 double* tmpnxk_buf;
6112 vecaligned_malloc2(sample_ctav * sizeof(double), &yy);
6113 vecaligned_malloc2(sample_ctav * predictor_ct * sizeof(double), &xx);
6114 vecaligned_malloc2(predictor_ctav * sizeof(double), &beta);
6115 vecaligned_malloc2(sample_ctav * sizeof(double), &pp);
6116 vecaligned_malloc2(sample_ctav * sizeof(double), &vv);
6117 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(double), &hh);
6118 vecaligned_malloc2(predictor_ctav * sizeof(double), &ustar);
6119 vecaligned_malloc2(predictor_ctav * sizeof(double), &delta);
6120 vecaligned_malloc2(predictor_ct * kMatrixInvertBuf1CheckedAlloc, &inv_1d_buf);
6121 vecaligned_malloc2(predictor_ct * MAXV(predictor_ct, 7) * sizeof(double), &dbl_2d_buf);
6122 vecaligned_malloc2(sample_ctav * sizeof(double), &hdiag);
6123 vecaligned_malloc2(sample_ctav * sizeof(double), &ww);
6124 vecaligned_malloc2(predictor_ct * predictor_ctav * sizeof(double), &hh0_buf);
6125 vecaligned_malloc2(predictor_ct * sample_ctav * sizeof(double), &tmpnxk_buf);
6126 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
6127 if (cos(S_CAST(double, sample_idx + 1) * 0.001) > 0.0) {
6128 yy[sample_idx] = 1.0;
6129 } else {
6130 yy[sample_idx] = 0.0;
6131 }
6132 }
6133 ZeroDArr(sample_ctav - sample_ct, &(yy[sample_ct]));
6134 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
6135 double* xx_col = &(xx[pred_idx * sample_ctav]);
6136 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
6137 double dxx = 1.0;
6138 double dyy = S_CAST(double, sample_idx + 1) * 0.001;
6139 for (uint32_t uii = 0; uii < pred_idx; ++uii) {
6140 dxx *= dyy;
6141 }
6142 xx_col[sample_idx] = dxx;
6143 }
6144 ZeroDArr(sample_ctav - sample_ct, &(xx_col[sample_ct]));
6145 }
6146 ZeroDArr(predictor_ctav, beta);
6147 uint32_t is_unfinished = 0;
6148 BoolErr reterr = FirthRegressionD(yy, xx, nullptr, sample_ct, predictor_ct, &is_unfinished, beta, hh, inv_1d_buf, dbl_2d_buf, pp, vv, ustar, delta, hdiag, ww, hh0_buf, tmpnxk_buf);
6149 printf("beta: %g %g %g %g %g\n", beta[0], beta[1], beta[2], beta[3], beta[4]);
6150 printf("sqrt(diag(hh)): %g %g %g %g %g\n", sqrt(hh[0]), sqrt(hh[predictor_ctav + 1]), sqrt(hh[2 * (predictor_ctav + 1)]), sqrt(hh[3 * (predictor_ctav + 1)]), sqrt(hh[4 * (predictor_ctav + 1)]));
6151 printf("p-values:");
6152 for (uint32_t pred_idx = 0; pred_idx != predictor_ct; ++pred_idx) {
6153 const double bt = beta[pred_idx];
6154 const double se = sqrt(hh[pred_idx * (predictor_ctav + 1)]);
6155 const double permstat = bt / se;
6156 const double ln_pval = ZscoreToLnP(permstat);
6157 char outbuf[24];
6158 char* outbuf_iter = outbuf;
6159 *outbuf_iter++ = ' ';
6160 outbuf_iter = lntoa_g(ln_pval, outbuf_iter);
6161 *outbuf_iter = '\0';
6162 fputs(outbuf, stdout);
6163 }
6164 printf("\n");
6165 printf("reterr: %u is_unfinished: %u\n", S_CAST(uint32_t, reterr), is_unfinished);
6166 }
6167
6168 void LogisticTestInternal() {
6169 LogisticTestFirthD();
6170 }
6171 */
6172
6173 #ifdef __cplusplus
6174 } // namespace plink2
6175 #endif