Debian Codegraph @

plink2_glm.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 "plink2_adjust.h"
18 #include "plink2_compress_stream.h"
19 #include "plink2_glm.h"
20 #include "plink2_glm_linear.h"
21 #include "plink2_glm_logistic.h"
22
23 #ifdef __cplusplus
24 namespace plink2 {
25 #endif
26
27 void InitGlm(GlmInfo* glm_info_ptr) {
28 glm_info_ptr->flags = kfGlm0;
29 glm_info_ptr->cols = kfGlmCol0;
30 glm_info_ptr->mperm_ct = 0;
31 glm_info_ptr->local_cat_ct = 0;
32 glm_info_ptr->local_header_line_ct = 0;
33 glm_info_ptr->local_chrom_col = 0;
34 glm_info_ptr->local_bp_col = 0;
35 glm_info_ptr->local_first_covar_col = 0;
36 glm_info_ptr->max_corr = 0.999;
37 glm_info_ptr->condition_varname = nullptr;
38 glm_info_ptr->condition_list_fname = nullptr;
39 InitRangeList(&(glm_info_ptr->parameters_range_list));
40 InitRangeList(&(glm_info_ptr->tests_range_list));
41 }
42
43 void CleanupGlm(GlmInfo* glm_info_ptr) {
44 free_cond(glm_info_ptr->condition_varname);
45 free_cond(glm_info_ptr->condition_list_fname);
46 CleanupRangeList(&(glm_info_ptr->parameters_range_list));
47 CleanupRangeList(&(glm_info_ptr->tests_range_list));
48 }
49
50 void InitGwasSsf(GwasSsfInfo* gwas_ssf_info_ptr) {
51 gwas_ssf_info_ptr->flags = kfGwasSsf0;
52 gwas_ssf_info_ptr->a1freq_lower_limit = 0.0;
53 gwas_ssf_info_ptr->rsid_mode = kGwasSsfRsidMode0;
54 gwas_ssf_info_ptr->fname = nullptr;
55 gwas_ssf_info_ptr->list_fname = nullptr;
56 }
57
58 void CleanupGwasSsf(GwasSsfInfo* gwas_ssf_info_ptr) {
59 free_cond(gwas_ssf_info_ptr->fname);
60 free_cond(gwas_ssf_info_ptr->list_fname);
61 }
62
63 // [-1] = #CHROM (must be first column)
64 // [0] = POS
65 // [1] = ID
66 // [2] = REF
67 // [3] = ALT
68 // [4] = PROVISIONAL_REF?
69 // [5] = A1
70 // [6] = OMITTED (optional, required to keep multiallelic variants)
71 // [7] = A1_FREQ
72 // [8] = TEST
73 // [9] = OBS_CT
74 // [10] = BETA/OR
75 // [11] = SE/LOG(OR)_SE
76 // [12] = L## (optional)
77 // [13] = U## (optional)
78 // [14] = P/LOG10_P/NEG_LOG10_P
79 ENUM_U31_DEF_START()
80 kGwasSsfColPos = 0,
81 kGwasSsfColId,
82 kGwasSsfColRef,
83 kGwasSsfColAlt,
84 kGwasSsfColProvref,
85 kGwasSsfColA1,
86 kGwasSsfColOmitted,
87 kGwasSsfColA1freq,
88 kGwasSsfColTest,
89 kGwasSsfColObsCt,
90 kGwasSsfColBetaOr,
91 kGwasSsfColSe,
92 kGwasSsfColCiLower,
93 kGwasSsfColCiUpper,
94 kGwasSsfColP,
95 kGwasSsfColNull
96 ENUM_U31_DEF_END(GwasSsfColidx);
97
98 FLAGSET_DEF_START()
99 kfGwasSsfColset0,
100 kfGwasSsfColsetPos = (1 << kGwasSsfColPos),
101 kfGwasSsfColsetId = (1 << kGwasSsfColId),
102 kfGwasSsfColsetRef = (1 << kGwasSsfColRef),
103 kfGwasSsfColsetAlt = (1 << kGwasSsfColAlt),
104 kfGwasSsfColsetProvref = (1 << kGwasSsfColProvref),
105 kfGwasSsfColsetA1 = (1 << kGwasSsfColA1),
106 kfGwasSsfColsetOmitted = (1 << kGwasSsfColOmitted),
107 kfGwasSsfColsetA1freq = (1 << kGwasSsfColA1freq),
108 kfGwasSsfColsetTest = (1 << kGwasSsfColTest),
109 kfGwasSsfColsetObsCt = (1 << kGwasSsfColObsCt),
110 kfGwasSsfColsetBetaOr = (1 << kGwasSsfColBetaOr),
111 kfGwasSsfColsetSe = (1 << kGwasSsfColSe),
112 kfGwasSsfColsetCiLower = (1 << kGwasSsfColCiLower),
113 kfGwasSsfColsetCiUpper = (1 << kGwasSsfColCiUpper),
114 kfGwasSsfColsetP = (1 << kGwasSsfColP),
115
116 kfGwasSsfColsetRequired = kfGwasSsfColsetPos | kfGwasSsfColsetRef | kfGwasSsfColsetAlt | kfGwasSsfColsetA1 | kfGwasSsfColsetA1freq | kfGwasSsfColsetTest | kfGwasSsfColsetObsCt | kfGwasSsfColsetBetaOr | kfGwasSsfColsetSe | kfGwasSsfColsetP
117 FLAGSET_DEF_END(GwasSsfColFlags);
118
119 // this is likely to become a library function. possible todos: benchmark
120 // against bool_table, vectorized code for large allele_code_slen
121 uint32_t AllACGT(const char* allele_code, uint32_t allele_code_slen) {
122 for (uint32_t pos = 0; pos != allele_code_slen; ++pos) {
123 uint32_t uii = ctou32(allele_code[pos]);
124 uii -= 64;
125 if ((uii > 31) || (!((0x10008a >> uii) & 1))) {
126 return 0;
127 }
128 }
129 return 1;
130 }
131
132 // Excludes integers >> 2^64.
133 uint32_t IsRsid(const char* variant_id, uint32_t variant_id_slen) {
134 if ((!StrStartsWith(variant_id, "rs", variant_id_slen)) || (variant_id_slen > 22)) {
135 return 0;
136 }
137 uint32_t uii = strlen("rs");
138 for (; uii != variant_id_slen; ++uii) {
139 if (!IsDigit(variant_id[uii])) {
140 return 0;
141 }
142 }
143 return 1;
144 }
145
146 // If rsid_mode == kGwasSsfRsidModeInfer and force_rsid is false, we peek at
147 // the second input line and proceed under the assumption that rsID is absent
148 // if that doesn't have a rsID. Then, if/when we encounter a later rsID (this
149 // should happen quickly if rsIDs are present at all), we return kPglRetRetry,
150 // and the caller retries with force_rsid true.
151 //
152 // Similarly, if the PROVISIONAL_REF? column is present, we proceed under the
153 // assumption that all values are 'Y' if that's true on the second line, and
154 // retry if we encounter an exception.
155 PglErr GwasSsfInternal(const GwasSsfInfo* gsip, const char* in_fname, const char* out_fname, uint32_t max_line_blen, uint32_t max_thread_ct, TextStream* txsp, uint32_t* force_rsidp, uint32_t* force_refp) {
156 unsigned char* bigstack_mark = g_bigstack_base;
157 char* cswritep = nullptr;
158 uintptr_t line_idx = 0;
159 PglErr reterr = kPglRetSuccess;
160 CompressStreamState css;
161 PreinitCstream(&css);
162 {
163 char* line_iter = TextLineEnd(txsp);
164 ++line_idx;
165 if (!TextGetUnsafe2(txsp, &line_iter)) {
166 if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
167 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s is empty.\n", in_fname);
168 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
169 }
170 goto GwasSsfInternal_ret_TSTREAM_FAIL;
171 }
172 uint32_t col_skips[kGwasSsfColNull];
173 GwasSsfColidx col_types[kGwasSsfColNull];
174 char* first_token_end = FirstSpaceOrEoln(line_iter);
175 const uint32_t first_token_slen = first_token_end - line_iter;
176 GwasSsfColFlags header_cols = kfGwasSsfColset0;
177 uint32_t relevant_postchr_col_ct = 0;
178 uint32_t is_odds_ratio = 0;
179 uint32_t is_neglog10_p = 0;
180 if (unlikely(!strequal_k(line_iter, "#CHROM", first_token_slen))) {
181 if (strequal_k(line_iter, "#POS", first_token_slen) ||
182 strequal_k(line_iter, "#ID", first_token_slen)) {
183 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not have a #CHROM column.\n", in_fname);
184 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
185 }
186 if (strequal_k(line_iter, "CHR", first_token_slen)) {
187 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s appears to be a PLINK 1.x --linear/--logistic output file, which is missing the required A1_FREQ output column. Redo the regression with PLINK 2 --glm.\n", in_fname);
188 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
189 }
190 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not appear to be a PLINK 2 --glm output file.\n", in_fname);
191 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
192 }
193
194 const char* token_end = first_token_end;
195 for (uint32_t col_idx = 1; ; ++col_idx) {
196 const char* linebuf_iter = FirstNonTspace(token_end);
197 if (IsEolnKns(*linebuf_iter)) {
198 break;
199 }
200 token_end = CurTokenEnd(linebuf_iter);
201 const uint32_t token_slen = token_end - linebuf_iter;
202 GwasSsfColidx cur_colidx = kGwasSsfColNull;
203 if (token_slen <= 3) {
204 if (token_slen == 3) {
205 if (memequal_sk(linebuf_iter, "POS")) {
206 cur_colidx = kGwasSsfColPos;
207 } else if (memequal_sk(linebuf_iter, "REF")) {
208 cur_colidx = kGwasSsfColRef;
209 } else if (memequal_sk(linebuf_iter, "ALT")) {
210 cur_colidx = kGwasSsfColAlt;
211 } else if (IsDigit(linebuf_iter[1]) && IsDigit(linebuf_iter[2])) {
212 if (linebuf_iter[0] == 'L') {
213 cur_colidx = kGwasSsfColCiLower;
214 } else if (linebuf_iter[0] == 'U') {
215 cur_colidx = kGwasSsfColCiUpper;
216 }
217 }
218 } else if (token_slen == 2) {
219 if (memequal_sk(linebuf_iter, "ID")) {
220 cur_colidx = kGwasSsfColId;
221 } else if (memequal_sk(linebuf_iter, "A1")) {
222 cur_colidx = kGwasSsfColA1;
223 } else if (memequal_sk(linebuf_iter, "OR")) {
224 cur_colidx = kGwasSsfColBetaOr;
225 is_odds_ratio = 1;
226 } else if (memequal_sk(linebuf_iter, "SE")) {
227 cur_colidx = kGwasSsfColSe;
228 }
229 } else if (strequal_k(linebuf_iter, "P", token_slen)) {
230 cur_colidx = kGwasSsfColP;
231 }
232 } else if (strequal_k(linebuf_iter, "PROVISIONAL_REF?", token_slen)) {
233 cur_colidx = kGwasSsfColProvref;
234 } else if (strequal_k(linebuf_iter, "OMITTED", token_slen)) {
235 cur_colidx = kGwasSsfColOmitted;
236 } else if (strequal_k(linebuf_iter, "A1_FREQ", token_slen)) {
237 cur_colidx = kGwasSsfColA1freq;
238 } else if (strequal_k(linebuf_iter, "TEST", token_slen)) {
239 cur_colidx = kGwasSsfColTest;
240 } else if (strequal_k(linebuf_iter, "OBS_CT", token_slen)) {
241 cur_colidx = kGwasSsfColObsCt;
242 } else if (strequal_k(linebuf_iter, "BETA", token_slen)) {
243 cur_colidx = kGwasSsfColBetaOr;
244 } else if (strequal_k(linebuf_iter, "LOG(OR)_SE", token_slen)) {
245 cur_colidx = kGwasSsfColSe;
246 } else if (strequal_k(linebuf_iter, "LOG10_P", token_slen) || strequal_k(linebuf_iter, "NEG_LOG10_P", token_slen)) {
247 cur_colidx = kGwasSsfColP;
248 is_neglog10_p = 1;
249 }
250 if (cur_colidx != kGwasSsfColNull) {
251 const GwasSsfColFlags cur_colset = S_CAST(GwasSsfColFlags, 1U << cur_colidx);
252 if (unlikely(header_cols & cur_colset)) {
253 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: Conflicting columns in header line of %s .\n", in_fname);
254 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
255 }
256 header_cols |= cur_colset;
257 col_skips[relevant_postchr_col_ct] = col_idx;
258 col_types[relevant_postchr_col_ct++] = cur_colidx;
259 }
260 }
261 if (unlikely((header_cols & kfGwasSsfColsetRequired) != kfGwasSsfColsetRequired)) {
262 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not have all required input columns. (CHROM, POS, REF, ALT, A1, A1_FREQ, TEST, OBS_CT, BETA/OR, SE/LOG(OR)_SE, and P/LOG10_P/NEG_LOG10_P are required.)\n", in_fname);
263 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
264 }
265 // static-cast to remove gcc 4.4 warning
266 GwasSsfRsidMode rsid_mode = (*force_rsidp)? S_CAST(GwasSsfRsidMode, kGwasSsfRsidModeYes) : gsip->rsid_mode;
267 if (unlikely((rsid_mode != kGwasSsfRsidModeNo) && (!(header_cols & kfGwasSsfColsetId)))) {
268 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not have an ID column, and rsid=no was not specified.\n", in_fname);
269 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
270 }
271 // Peek at second line to make informed rsid_mode and ref_mode guesses.
272 ++line_idx;
273 line_iter = AdvPastDelim(line_iter, '\n');
274 if (!TextGetUnsafe2(txsp, &line_iter)) {
275 if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
276 snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s only has a header line.\n", in_fname);
277 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
278 }
279 goto GwasSsfInternal_ret_TSTREAM_FAIL;
280 }
281 // col_skips has not been finalized yet, it still contains raw column
282 // indices.
283 if (rsid_mode == kGwasSsfRsidModeInfer) {
284 const char* variant_id = NextTokenMult(line_iter, col_skips[kGwasSsfColId]);
285 if (unlikely(variant_id == nullptr)) {
286 goto GwasSsfInternal_ret_MISSING_TOKENS;
287 }
288 const uint32_t variant_id_slen = CurTokenEnd(variant_id) - variant_id;
289 if (IsRsid(variant_id, variant_id_slen)) {
290 *force_rsidp = 1;
291 rsid_mode = kGwasSsfRsidModeYes;
292 }
293 }
294 const uint32_t rsid_col = (rsid_mode == kGwasSsfRsidModeYes);
295
296 uint32_t real_ref_found = (*force_refp) || (gsip->flags & kfGwasSsfRealRefAlleles);
297 if ((!real_ref_found) && (header_cols & kfGwasSsfColsetProvref)) {
298 const char* provref_str = NextTokenMult(line_iter, col_skips[kGwasSsfColProvref]);
299 if (unlikely(provref_str == nullptr)) {
300 goto GwasSsfInternal_ret_MISSING_TOKENS;
301 }
302 if ((provref_str[0] == 'N') && IsSpaceOrEoln(provref_str[1])) {
303 *force_refp = 1;
304 real_ref_found = 1;
305 }
306 }
307
308 // Ok, now we can finalize col_skips.
309 for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) {
310 col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
311 }
312
313 const uint32_t output_zst = (gsip->flags / kfGwasSsfZs) & 1;
314
315 // Output line length won't be more than ~2x input line length.
316 // (It can be close to 2x if REF allele is very long and isn't A1.)
317 const uintptr_t overflow_buf_size = kCompressStreamBlock + 512 + ((2 * k1LU) * max_line_blen);
318 reterr = InitCstreamAlloc(out_fname, 0, output_zst, MAXV(1, max_thread_ct - 1), overflow_buf_size, &css, &cswritep);
319 if (unlikely(reterr)) {
320 goto GwasSsfInternal_ret_1;
321 }
322 cswritep = strcpya_k(cswritep, "chromosome\tbase_pair_location\teffect_allele\tother_allele\t");
323 if (!is_odds_ratio) {
324 cswritep = strcpya_k(cswritep, "beta");
325 } else {
326 cswritep = strcpya_k(cswritep, "odds_ratio");
327 }
328 cswritep = strcpya_k(cswritep, "\tstandard_error\teffect_allele_frequency\t");
329 if (is_neglog10_p) {
330 cswritep = strcpya(cswritep, "neg_log_10_");
331 }
332 cswritep = strcpya(cswritep, "p_value");
333 if (real_ref_found) {
334 cswritep = strcpya_k(cswritep, "\tvariant_id");
335 }
336 if (rsid_col) {
337 cswritep = strcpya_k(cswritep, "\trsid");
338 }
339 if (header_cols & kfGwasSsfColsetCiUpper) {
340 cswritep = strcpya_k(cswritep, "\tci_upper");
341 }
342 if (header_cols & kfGwasSsfColsetCiLower) {
343 cswritep = strcpya_k(cswritep, "\tci_lower");
344 }
345 cswritep = strcpya_k(cswritep, "\tn");
346 if (real_ref_found) {
347 cswritep = strcpya_k(cswritep, "\tref_allele");
348 }
349 AppendBinaryEoln(&cswritep);
350
351 // X, XY, PAR1, PAR2 -> 23
352 // Y -> 24
353 // MT -> 25, not 26
354 const unsigned char gwas_ssf_chr_remap[6] = {23, 24, 23, 25, 23, 23};
355 const double a1freq_lower_limit = gsip->a1freq_lower_limit;
356 const uint32_t allow_ambiguous_indels = (gsip->flags / kfGwasSsfAllowAmbiguousIndels) & 1;
357 char a1freq_lower_limit_str[16]; // > kMaxDoubleGSlen
358 uint32_t a1freq_lower_limit_slen = 0;
359 if (a1freq_lower_limit > 0.0) {
360 char* a1freq_lower_limit_end = dtoa_g(a1freq_lower_limit, a1freq_lower_limit_str);
361 a1freq_lower_limit_slen = a1freq_lower_limit_end - a1freq_lower_limit_str;
362 }
363 // If there is no provref column, and the user did not specify
364 // 'real-ref-alleles' on the command line, treat all REF alleles as
365 // provisional for the ambiguous-indel check.
366 uint32_t provref = (!(gsip->flags & kfGwasSsfRealRefAlleles)) && (!(header_cols & kfGwasSsfColsetProvref));
367 goto GwasSsfInternal_main_loop_start;
368
369 for (; TextGetUnsafe2(txsp, &line_iter); ++line_idx) {
370 if (IsEolnKns(*line_iter)) {
371 goto GwasSsfInternal_ret_MISSING_TOKENS;
372 }
373 GwasSsfInternal_main_loop_start:
374 ;
375 const uint32_t chr_code_raw = GetChrCodeRaw(line_iter);
376 if ((!chr_code_raw) || ((chr_code_raw > 26) && (chr_code_raw < kMaxContigs))) {
377 line_iter = AdvPastDelim(line_iter, '\n');
378 continue;
379 }
380
381 char* token_ptrs[kGwasSsfColNull];
382 uint32_t token_slens[kGwasSsfColNull];
383 line_iter = TokenLex(line_iter, R_CAST(uint32_t*, col_types), col_skips, relevant_postchr_col_ct, token_ptrs, token_slens);
384 if (unlikely(!line_iter)) {
385 goto GwasSsfInternal_ret_MISSING_TOKENS;
386 }
387 line_iter = AdvPastDelim(line_iter, '\n');
388 // skip if TEST isn't ADD, or result is NA, or effect/other allele has
389 // non-ACGT character, or OMITTED column is absent and variant is
390 // multiallelic
391 if (!strequal_k(token_ptrs[kGwasSsfColTest], "ADD", token_slens[kGwasSsfColTest])) {
392 continue;
393 }
394 if ((token_ptrs[kGwasSsfColP][0] & 0xdf) == 'N') {
395 continue;
396 }
397 const char* effect_allele = token_ptrs[kGwasSsfColA1];
398 const uint32_t effect_allele_slen = token_slens[kGwasSsfColA1];
399 if (!AllACGT(effect_allele, effect_allele_slen)) {
400 continue;
401 }
402 const char* ref_allele = token_ptrs[kGwasSsfColRef];
403 uint32_t ref_allele_slen = token_slens[kGwasSsfColRef];
404 const char* other_allele;
405 uint32_t other_allele_slen;
406 uint32_t ref_allele_match; // 0 = effect, 1 = other, 2 = neither
407 if (header_cols & kfGwasSsfColsetOmitted) {
408 other_allele = token_ptrs[kGwasSsfColOmitted];
409 other_allele_slen = token_slens[kGwasSsfColOmitted];
410 if (!AllACGT(other_allele, other_allele_slen)) {
411 continue;
412 }
413 if ((ref_allele_slen == effect_allele_slen) && memequal(ref_allele, effect_allele, ref_allele_slen)) {
414 ref_allele_match = 0;
415 } else if ((ref_allele_slen == other_allele_slen) && memequal(ref_allele, other_allele, ref_allele_slen)) {
416 ref_allele_match = 1;
417 } else {
418 ref_allele_match = 2;
419 }
420 } else {
421 const char* alt_str = token_ptrs[kGwasSsfColAlt];
422 const uint32_t alt_slen = token_slens[kGwasSsfColAlt];
423 if (memchr(alt_str, ',', alt_slen) != nullptr) {
424 continue;
425 }
426 // check for REF/ALT match, ALT first (much more likely), error out if
427 // neither.
428 if ((effect_allele_slen == alt_slen) && memequal(effect_allele, alt_str, effect_allele_slen)) {
429 other_allele = ref_allele;
430 other_allele_slen = ref_allele_slen;
431 ref_allele_match = 1;
432 } else if (likely((effect_allele_slen == ref_allele_slen) && memequal(effect_allele, ref_allele, effect_allele_slen))) {
433 other_allele = alt_str;
434 other_allele_slen = alt_slen;
435 ref_allele_match = 0;
436 } else {
437 snprintf(g_logbuf, kLogbufSize, "Error: A1 allele on line %" PRIuPTR " of %s matches neither REF nor ALT.\n", line_idx, in_fname);
438 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
439 }
440 if (!AllACGT(other_allele, other_allele_slen)) {
441 continue;
442 }
443 }
444
445 uint32_t gwas_ssf_chr_code;
446 if (chr_code_raw < kMaxContigs) {
447 if (chr_code_raw < 25) {
448 gwas_ssf_chr_code = chr_code_raw;
449 } else if (chr_code_raw == 25) {
450 gwas_ssf_chr_code = 23;
451 } else {
452 gwas_ssf_chr_code = 25;
453 }
454 } else {
455 gwas_ssf_chr_code = gwas_ssf_chr_remap[chr_code_raw - kMaxContigs];
456 }
457 #ifdef __LP64__
458 char* outline_start = cswritep;
459 #endif
460 cswritep = u32toa_x(gwas_ssf_chr_code, '\t', cswritep);
461
462 // POS
463 const char* pos_str = token_ptrs[kGwasSsfColPos];
464 const uint32_t pos_slen = token_slens[kGwasSsfColPos];
465 cswritep = memcpyax(cswritep, pos_str, pos_slen, '\t');
466
467 // A1
468 cswritep = memcpyax(cswritep, effect_allele, effect_allele_slen, '\t');
469
470 // OMITTED
471 cswritep = memcpyax(cswritep, other_allele, other_allele_slen, '\t');
472
473 // BETA/OR
474 cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColBetaOr], token_slens[kGwasSsfColBetaOr], '\t');
475
476 // SE
477 cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColSe], token_slens[kGwasSsfColSe], '\t');
478
479 // A1_FREQ
480 const char* a1_freq_str = token_ptrs[kGwasSsfColA1freq];
481 if (a1freq_lower_limit == 0.0) {
482 cswritep = memcpya(cswritep, a1_freq_str, token_slens[kGwasSsfColA1freq]);
483 } else {
484 double a1_freq;
485 if (unlikely(!ScanadvDouble(a1_freq_str, &a1_freq))) {
486 snprintf(g_logbuf, kLogbufSize, "Error: Invalid A1_FREQ on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
487 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
488 }
489 if (a1_freq >= a1freq_lower_limit) {
490 cswritep = memcpya(cswritep, a1_freq_str, token_slens[kGwasSsfColA1freq]);
491 } else {
492 cswritep = memcpya(cswritep, a1freq_lower_limit_str, a1freq_lower_limit_slen);
493 }
494 }
495 *cswritep++ = '\t';
496
497 // P
498 cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColP], token_slens[kGwasSsfColP], '\t');
499
500 // C_P_R_A
501 if (header_cols & kfGwasSsfColsetProvref) {
502 const uint32_t provref_slen = token_slens[kGwasSsfColProvref];
503 const char provref_char = token_ptrs[kGwasSsfColProvref][0];
504 provref = (provref_char == 'Y');
505 if (unlikely((provref_slen != 1) || ((!provref) && (provref_char != 'N')))) {
506 snprintf(g_logbuf, kLogbufSize, "Error: Invalid PROVISIONAL_REF? column value on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
507 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
508 }
509 if ((!real_ref_found) && (!provref)) {
510 *force_refp = 1;
511 reterr = kPglRetRetry;
512 goto GwasSsfInternal_ret_1;
513 }
514 }
515
516 // Note that this doesn't catch all ambiguous variants. Specifically,
517 // when REF is neither the effect nor the other allele in a multiallelic
518 // variant, we technically need to know the length of the REF allele to
519 // disambiguate, and that is not currently recorded.
520 // But that's rare. This catches the most common problem case.
521 if (unlikely((!allow_ambiguous_indels) && (effect_allele_slen != other_allele_slen) && provref && (ref_allele_match != 2))) {
522 logerrprintfww("Error: --gwas-ssf: Indel with unknown REF allele on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
523 logerrputs("If you have an upstream VCF or similar file from which the correct REF/ALT\nallele labels can be recovered (see the --ref-allele flag documentation for\ndetails), you are STRONGLY encouraged to recover those labels.\n");
524 goto GwasSsfInternal_ret_MALFORMED_INPUT;
525 }
526
527 if (real_ref_found) {
528 if ((ref_allele_match == 2) || provref) {
529 // at least two ALTs relevant. As of this writing, the specification
530 // doesn't say what to do here.
531 cswritep = strcpya_k(cswritep, "#NA\t");
532 } else {
533 cswritep = u32toa_x(gwas_ssf_chr_code, '_', cswritep);
534 cswritep = memcpyax(cswritep, pos_str, pos_slen, '_');
535 cswritep = memcpyax(cswritep, ref_allele, ref_allele_slen, '_');
536 if (ref_allele_match == 0) {
537 cswritep = memcpya(cswritep, other_allele, other_allele_slen);
538 } else {
539 cswritep = memcpya(cswritep, effect_allele, effect_allele_slen);
540 }
541 *cswritep++ = '\t';
542 }
543 }
544
545 if (rsid_mode != kGwasSsfRsidModeNo) {
546 const char* variant_id = token_ptrs[kGwasSsfColId];
547 const uint32_t variant_id_slen = token_slens[kGwasSsfColId];
548 const uint32_t is_rsid = IsRsid(variant_id, variant_id_slen);
549 if (rsid_col) {
550 if (is_rsid) {
551 cswritep = memcpyax(cswritep, variant_id, variant_id_slen, '\t');
552 } else {
553 cswritep = strcpya_k(cswritep, "#NA\t");
554 }
555 } else if (is_rsid) {
556 *force_rsidp = 1;
557 reterr = kPglRetRetry;
558 goto GwasSsfInternal_ret_1;
559 }
560 }
561
562 if (header_cols & kfGwasSsfColsetCiUpper) {
563 cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColCiUpper], token_slens[kGwasSsfColCiUpper], '\t');
564 }
565 if (header_cols & kfGwasSsfColsetCiLower) {
566 cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColCiLower], token_slens[kGwasSsfColCiLower], '\t');
567 }
568
569 // OBS_CT
570 cswritep = memcpya(cswritep, token_ptrs[kGwasSsfColObsCt], token_slens[kGwasSsfColObsCt]);
571
572 if (real_ref_found) {
573 *cswritep++ = '\t';
574 if (provref || (ref_allele_match == 2)) {
575 cswritep = strcpya_k(cswritep, "#NA");
576 } else if (ref_allele_match == 1) {
577 cswritep = strcpya_k(cswritep, "OA");
578 } else {
579 cswritep = strcpya_k(cswritep, "EA");
580 }
581 }
582
583 AppendBinaryEoln(&cswritep);
584 #ifdef __LP64__
585 if (unlikely(S_CAST(uintptr_t, cswritep - outline_start) > kMaxLongLine)) {
586 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s is too long to process.\n", line_idx, in_fname);
587 goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
588 }
589 #endif
590 if (unlikely(Cswrite(&css, &cswritep))) {
591 goto GwasSsfInternal_ret_WRITE_FAIL;
592 }
593 }
594 if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
595 goto GwasSsfInternal_ret_TSTREAM_FAIL;
596 }
597 if (unlikely(CswriteCloseNull(&css, cswritep))) {
598 goto GwasSsfInternal_ret_WRITE_FAIL;
599 }
600 reterr = kPglRetSuccess;
601 }
602 while (0) {
603 GwasSsfInternal_ret_TSTREAM_FAIL:
604 TextStreamErrPrint(in_fname, txsp);
605 break;
606 GwasSsfInternal_ret_WRITE_FAIL:
607 reterr = kPglRetWriteFail;
608 break;
609 GwasSsfInternal_ret_MISSING_TOKENS:
610 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, in_fname);
611 GwasSsfInternal_ret_MALFORMED_INPUT_WW:
612 WordWrapB(0);
613 logerrputsb();
614 GwasSsfInternal_ret_MALFORMED_INPUT:
615 reterr = kPglRetMalformedInput;
616 break;
617 }
618 GwasSsfInternal_ret_1:
619 CswriteCloseCond(&css, cswritep);
620 BigstackReset(bigstack_mark);
621 return reterr;
622 }
623
624 PglErr GwasSsfOneFile(const GwasSsfInfo* gsip, const char* in_fname, uint32_t max_thread_ct) {
625 unsigned char* bigstack_mark = g_bigstack_base;
626 char* out_fname = nullptr;
627 PglErr reterr = kPglRetSuccess;
628 TextStream txs;
629 PreinitTextStream(&txs);
630 {
631 uint32_t shared_fname_slen = strlen(in_fname);
632 if (StrEndsWith(in_fname, ".zst", shared_fname_slen)) {
633 shared_fname_slen -= 4;
634 }
635 // ".ssf.tsv.zst"
636 if (unlikely(bigstack_alloc_c(shared_fname_slen + 13, &out_fname))) {
637 goto GwasSsfOneFile_ret_NOMEM;
638 }
639 const uint32_t output_zst = (gsip->flags / kfGwasSsfZs) & 1;
640 char* out_fname_iter = memcpya(out_fname, in_fname, shared_fname_slen);
641 out_fname_iter = strcpya_k(out_fname_iter, ".ssf.tsv");
642 if (output_zst) {
643 out_fname_iter = strcpya_k(out_fname_iter, ".zst");
644 }
645 *out_fname_iter = '\0';
646
647 // /6 since output stream may require slightly over 4x this amount of
648 // memory with compression on
649 uint32_t max_line_blen;
650 if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 6, &max_line_blen))) {
651 goto GwasSsfOneFile_ret_NOMEM;
652 }
653 reterr = InitTextStream(in_fname, max_line_blen, output_zst? 1 : MAXV(1, max_thread_ct - 1), &txs);
654 if (unlikely(reterr)) {
655 goto GwasSsfOneFile_ret_TSTREAM_FAIL;
656 }
657
658 uint32_t force_rsid = 0;
659 uint32_t force_ref = 0;
660 do {
661 reterr = GwasSsfInternal(gsip, in_fname, out_fname, max_line_blen, max_thread_ct, &txs, &force_rsid, &force_ref);
662 } while (reterr == kPglRetRetry);
663 if (unlikely(reterr)) {
664 goto GwasSsfOneFile_ret_1;
665 }
666 logprintfww("--gwas-ssf: %s written.\n", out_fname);
667 }
668 while (0) {
669 GwasSsfOneFile_ret_NOMEM:
670 reterr = kPglRetNomem;
671 break;
672 GwasSsfOneFile_ret_TSTREAM_FAIL:
673 TextStreamErrPrint(in_fname, &txs);
674 break;
675 }
676 GwasSsfOneFile_ret_1:
677 CleanupTextStream2(in_fname, &txs, &reterr);
678 BigstackReset(bigstack_mark);
679 return reterr;
680 }
681
682 PglErr GwasSsfStandalone(const GwasSsfInfo* gsip, uint32_t max_thread_ct) {
683 unsigned char* bigstack_mark = g_bigstack_base;
684 PglErr reterr = kPglRetSuccess;
685 TextStream list_txs;
686 PreinitTextStream(&list_txs);
687 {
688 uintptr_t file_ct = 0;
689 if (gsip->fname) {
690 reterr = GwasSsfOneFile(gsip, gsip->fname, max_thread_ct);
691 if (unlikely(reterr)) {
692 goto GwasSsfStandalone_ret_1;
693 }
694 ++file_ct;
695 }
696 if (gsip->list_fname) {
697 reterr = InitTextStream(gsip->list_fname, kTextStreamBlenFast, 1, &list_txs);
698 if (unlikely(reterr)) {
699 goto GwasSsfStandalone_ret_TSTREAM_FAIL;
700 }
701 while (1) {
702 char* first_token_start = TextGet(&list_txs);
703 if (!first_token_start) {
704 break;
705 }
706 if (IsSpaceOrEoln(*first_token_start)) {
707 continue;
708 }
709 char* first_token_end = CurTokenEnd(first_token_start);
710 *first_token_end = '\0';
711 reterr = GwasSsfOneFile(gsip, first_token_start, max_thread_ct);
712 if (unlikely(reterr)) {
713 goto GwasSsfStandalone_ret_1;
714 }
715 ++file_ct;
716 }
717 if (unlikely(TextStreamErrcode2(&list_txs, &reterr))) {
718 goto GwasSsfStandalone_ret_TSTREAM_FAIL;
719 }
720 }
721 logprintf("--gwas-ssf file=/file-list=: %" PRIuPTR " file%s processed.\n", file_ct, (file_ct == 1)? "" : "s");
722 }
723 while (0) {
724 GwasSsfStandalone_ret_TSTREAM_FAIL:
725 TextStreamErrPrint(gsip->list_fname, &list_txs);
726 break;
727 }
728 GwasSsfStandalone_ret_1:
729 CleanupTextStream2(gsip->list_fname, &list_txs, &reterr);
730 BigstackReset(bigstack_mark);
731 return reterr;
732 }
733
734 PglErr GlmLocalOpen(const char* local_covar_fname, const char* local_pvar_fname, const char* local_psam_fname, const SampleIdInfo* siip, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const GlmInfo* glm_info_ptr, uint32_t raw_sample_ct, uint32_t raw_variant_ct, const uintptr_t** sample_include_ptr, const uintptr_t** sex_nm_ptr, const uintptr_t** sex_male_ptr, const uintptr_t** variant_include_ptr, uint32_t* sample_ct_ptr, uint32_t* variant_ct_ptr, TextStream* local_covar_txsp, uint32_t** local_sample_uidx_order_ptr, uintptr_t** local_variant_include_ptr, uint32_t* local_sample_ct_ptr, uint32_t* local_variant_ctl_ptr, uint32_t* local_covar_ct_ptr) {
735 unsigned char* bigstack_mark = g_bigstack_base;
736 unsigned char* bigstack_end_mark = g_bigstack_end;
737 uintptr_t line_idx = 0;
738 PglErr reterr = kPglRetSuccess;
739 const char* txs_fname = nullptr;
740 textFILE local_covar_txf;
741 TextStream txs;
742 PreinitTextFile(&local_covar_txf);
743 PreinitTextStream(&txs);
744 {
745 // 1. read .psam/.fam file, update sample_ct, initialize
746 // local_sample_uidx_order
747 uint32_t max_line_blen;
748 if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) {
749 goto GlmLocalOpen_ret_NOMEM;
750 }
751 txs_fname = local_psam_fname;
752 reterr = InitTextStreamEx(local_psam_fname, 1, kMaxLongLine, max_line_blen, 1, &txs);
753 if (unlikely(reterr)) {
754 goto GlmLocalOpen_ret_TSTREAM_FAIL;
755 }
756 XidMode xid_mode;
757 char* line_start;
758 reterr = LoadXidHeader("glm local-psam=", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
759 if (unlikely(reterr)) {
760 goto GlmLocalOpen_ret_TSTREAM_XID_FAIL;
761 }
762 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
763 const uint32_t orig_sample_ct = *sample_ct_ptr;
764 char* sorted_xidbox;
765 uint32_t* xid_map;
766 uintptr_t max_xid_blen;
767 // IID -> multiple IID+SID not supported for now, may want to add this
768 reterr = SortedXidboxInitAllocEnd(*sample_include_ptr, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
769 if (unlikely(reterr)) {
770 goto GlmLocalOpen_ret_1;
771 }
772 uintptr_t* new_sample_include;
773 char* idbuf;
774 if (unlikely(bigstack_end_calloc_w(raw_sample_ctl, &new_sample_include) ||
775 bigstack_end_alloc_c(max_xid_blen, &idbuf))) {
776 goto GlmLocalOpen_ret_NOMEM;
777 }
778 uint32_t* local_sample_uidx_order = R_CAST(uint32_t*, g_bigstack_base);
779 uintptr_t max_local_sample_ct = RoundDownPow2(bigstack_left(), kCacheline) / sizeof(int32_t);
780 #ifdef __LP64__
781 if (max_local_sample_ct > kMaxLongLine / 2) {
782 max_local_sample_ct = kMaxLongLine / 2;
783 }
784 #endif
785 uintptr_t local_sample_ct = 0;
786 if (line_start[0] == '#') {
787 ++line_idx;
788 line_start = TextGet(&txs);
789 }
790 for (; line_start; ++local_sample_ct, ++line_idx, line_start = TextGet(&txs)) {
791 if (unlikely(line_start[0] == '#')) {
792 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #FID/IID header line is present it must denote the end of the header block.)\n", line_idx, local_psam_fname);
793 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
794 }
795 if (unlikely(local_sample_ct == max_local_sample_ct)) {
796 #ifdef __LP64__
797 if (local_sample_ct == kMaxLongLine / 2) {
798 snprintf(g_logbuf, kLogbufSize, "Error: Too many samples in %s.\n", local_psam_fname);
799 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
800 }
801 #endif
802 goto GlmLocalOpen_ret_NOMEM;
803 }
804 const char* read_ptr = line_start;
805 uint32_t sample_uidx;
806 if (!SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &read_ptr, &sample_uidx, idbuf)) {
807 if (unlikely(IsSet(new_sample_include, sample_uidx))) {
808 TabsToSpaces(idbuf);
809 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s.\n", idbuf, local_psam_fname);
810 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
811 }
812 SetBit(sample_uidx, new_sample_include);
813 local_sample_uidx_order[local_sample_ct] = sample_uidx;
814 } else {
815 if (unlikely(!read_ptr)) {
816 snprintf(g_logbuf, kLogbufSize, "Error: Fewer tokens than expected on line %" PRIuPTR " of %s.\n", line_idx, local_psam_fname);
817 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
818 }
819 local_sample_uidx_order[local_sample_ct] = UINT32_MAX;
820 }
821 }
822 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
823 goto GlmLocalOpen_ret_TSTREAM_FAIL;
824 }
825 BigstackFinalizeU32(local_sample_uidx_order, local_sample_ct);
826 *local_sample_uidx_order_ptr = local_sample_uidx_order;
827 *local_sample_ct_ptr = local_sample_ct;
828 const uint32_t new_sample_ct = PopcountWords(new_sample_include, raw_sample_ctl);
829 assert(new_sample_ct <= orig_sample_ct);
830 if (new_sample_ct < orig_sample_ct) {
831 uintptr_t* sample_include_copy;
832 uintptr_t* sex_nm_copy;
833 uintptr_t* sex_male_copy;
834 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include_copy) ||
835 bigstack_alloc_w(raw_sample_ctl, &sex_nm_copy) ||
836 bigstack_alloc_w(raw_sample_ctl, &sex_male_copy))) {
837 goto GlmLocalOpen_ret_NOMEM;
838 }
839 memcpy(sample_include_copy, new_sample_include, raw_sample_ctl * sizeof(intptr_t));
840 BitvecAndCopy(sample_include_copy, *sex_nm_ptr, raw_sample_ctl, sex_nm_copy);
841 *sex_nm_ptr = sex_nm_copy;
842 BitvecAndCopy(sample_include_copy, *sex_male_ptr, raw_sample_ctl, sex_male_copy);
843 *sex_male_ptr = sex_male_copy;
844 *sample_include_ptr = sample_include_copy;
845 *sample_ct_ptr = new_sample_ct;
846 }
847 BigstackEndReset(TextStreamMemStart(&txs));
848
849 // 2. if local-pvar= specified, read .pvar/.bim file, update variant_ct,
850 // initialize local_variant_ct/local_variant_include.
851 if (local_pvar_fname) {
852 reterr = TextRetarget(local_pvar_fname, &txs);
853 if (unlikely(reterr)) {
854 goto GlmLocalOpen_ret_TSTREAM_FAIL;
855 }
856 txs_fname = local_pvar_fname;
857 line_idx = 0;
858 uint32_t is_header_line;
859 do {
860 ++line_idx;
861 line_start = TextGet(&txs);
862 if (unlikely(!line_start)) {
863 if (!TextStreamErrcode2(&txs, &reterr)) {
864 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", local_pvar_fname);
865 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
866 }
867 goto GlmLocalOpen_ret_TSTREAM_FAIL;
868 }
869 is_header_line = (line_start[0] == '#');
870 } while (is_header_line && (!tokequal_k(line_start, "#CHROM")));
871 uint32_t col_skips[2];
872 uint32_t col_types[2];
873 // uint32_t relevant_postchr_col_ct = 2;
874 if (is_header_line) {
875 // parse header
876 // [-1] = #CHROM (must be first column)
877 // [0] = POS
878 // [1] = ID
879 // don't care about the rest
880 const char* token_end = &(line_start[6]);
881 uint32_t found_header_bitset = 0;
882 uint32_t relevant_postchr_col_ct = 0;
883 const char* linebuf_iter;
884 for (uint32_t col_idx = 1; ; ++col_idx) {
885 linebuf_iter = FirstNonTspace(token_end);
886 if (IsEolnKns(*linebuf_iter)) {
887 break;
888 }
889 token_end = CurTokenEnd(linebuf_iter);
890 const uint32_t token_slen = token_end - linebuf_iter;
891 uint32_t cur_col_type;
892 if (strequal_k(linebuf_iter, "POS", token_slen)) {
893 cur_col_type = 0;
894 } else if (strequal_k(linebuf_iter, "ID", token_slen)) {
895 cur_col_type = 1;
896 } else {
897 continue;
898 }
899 const uint32_t cur_col_type_shifted = 1 << cur_col_type;
900 if (unlikely(found_header_bitset & cur_col_type_shifted)) {
901 // Known column type, so length is limited and we don't have to
902 // worry about buffer overflow.
903 char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '");
904 write_iter = memcpya(write_iter, linebuf_iter, token_slen);
905 write_iter = strcpya_k(write_iter, "' on line ");
906 write_iter = wtoa(line_idx, write_iter);
907 write_iter = strcpya_k(write_iter, " of ");
908 write_iter = strcpya(write_iter, local_pvar_fname);
909 memcpy_k(write_iter, ".\n\0", 4);
910 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
911 }
912 found_header_bitset |= cur_col_type_shifted;
913 col_skips[relevant_postchr_col_ct] = col_idx;
914 col_types[relevant_postchr_col_ct++] = cur_col_type;
915 }
916 if (unlikely(found_header_bitset != 3)) {
917 snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of %s. (POS and ID are required.)\n", line_idx, local_pvar_fname);
918 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
919 }
920 for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) {
921 col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
922 }
923 } else {
924 col_types[0] = 1;
925 col_types[1] = 0;
926 col_skips[0] = 1;
927 // CM column may be omitted
928 const char* linebuf_iter = NextTokenMult(line_start, 4);
929 if (unlikely(!linebuf_iter)) {
930 goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
931 }
932 linebuf_iter = NextToken(linebuf_iter);
933 if (!linebuf_iter) {
934 // #CHROM ID POS ALT REF
935 col_skips[1] = 1;
936 } else {
937 // #CHROM ID CM POS ALT REF
938 col_skips[1] = 2;
939 }
940 }
941 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
942 uintptr_t* new_variant_include;
943 if (unlikely(bigstack_end_calloc_w(raw_variant_ctl, &new_variant_include))) {
944 goto GlmLocalOpen_ret_NOMEM;
945 }
946 uint32_t max_local_variant_ct = kPglMaxVariantCt;
947 if (bigstack_left() < (0x80000000U / CHAR_BIT)) {
948 max_local_variant_ct = RoundDownPow2(bigstack_left(), kCacheline) * CHAR_BIT;
949 }
950 const uintptr_t* orig_variant_include = *variant_include_ptr;
951 uintptr_t* local_variant_include = R_CAST(uintptr_t*, g_bigstack_base);
952 *local_variant_include_ptr = local_variant_include;
953 uint32_t local_variant_ct = 0;
954 uint32_t new_variant_ct = 0;
955 uint32_t prev_variant_uidx = AdvTo1Bit(orig_variant_include, 0);
956 uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
957 uint32_t prev_chr_code = cip->chr_file_order[chr_fo_idx];
958 uint32_t prev_bp = variant_bps[prev_variant_uidx];
959 uint32_t chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
960 if (is_header_line) {
961 ++line_idx;
962 line_start = TextGet(&txs);
963 }
964 for (; line_start; ++local_variant_ct, ++line_idx, line_start = TextGet(&txs)) {
965 if (unlikely(line_start[0] == '#')) {
966 snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx, local_pvar_fname);
967 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
968 }
969 if (unlikely(local_variant_ct == max_local_variant_ct)) {
970 if (max_local_variant_ct == kPglMaxVariantCt) {
971 snprintf(g_logbuf, kLogbufSize, "Error: Too many variants in %s.\n", local_pvar_fname);
972 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
973 }
974 goto GlmLocalOpen_ret_NOMEM;
975 }
976 if (!(local_variant_ct % kBitsPerWord)) {
977 local_variant_include[local_variant_ct / kBitsPerWord] = 0;
978 }
979 char* line_iter = CurTokenEnd(line_start);
980 // #CHROM
981 if (unlikely((*line_iter != '\t') && (*line_iter != ' '))) {
982 goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
983 }
984 const uint32_t cur_chr_code = GetChrCodeCounted(cip, line_iter - line_start, line_start);
985 if (IsI32Neg(cur_chr_code)) {
986 continue;
987 }
988 const uint32_t cur_chr_code_u = cur_chr_code;
989 if (cur_chr_code_u != prev_chr_code) {
990 const uint32_t first_variant_uidx_in_chr = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[cur_chr_code_u]];
991 if (first_variant_uidx_in_chr < prev_variant_uidx) {
992 if (unlikely(new_variant_ct)) {
993 // not worth the trouble of handling this
994 snprintf(g_logbuf, kLogbufSize, "Error: Chromosome order in %s is different from chromosome order in main dataset.\n", local_pvar_fname);
995 goto GlmLocalOpen_ret_INCONSISTENT_INPUT_WW;
996 }
997 continue;
998 }
999 prev_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, first_variant_uidx_in_chr, raw_variant_ct);
1000 if (prev_variant_uidx == raw_variant_ct) {
1001 break;
1002 }
1003 chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
1004 prev_chr_code = cip->chr_file_order[chr_fo_idx];
1005 prev_bp = variant_bps[prev_variant_uidx];
1006 chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
1007 if (cur_chr_code_u != prev_chr_code) {
1008 continue;
1009 }
1010 }
1011 char* token_ptrs[2];
1012 uint32_t token_slens[2];
1013 if (unlikely(!TokenLex(line_iter, col_types, col_skips, 2, token_ptrs, token_slens))) {
1014 goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
1015 }
1016 // POS
1017 int32_t cur_bp;
1018 if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp))) {
1019 snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, local_pvar_fname);
1020 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
1021 }
1022 if (cur_bp < S_CAST(int32_t, prev_bp)) {
1023 continue;
1024 }
1025 const uint32_t cur_bp_u = cur_bp;
1026 if (cur_bp_u > prev_bp) {
1027 do {
1028 prev_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, prev_variant_uidx + 1, raw_variant_ct);
1029 } while ((prev_variant_uidx < chr_end) && (cur_bp_u > variant_bps[prev_variant_uidx]));
1030 if (prev_variant_uidx >= chr_end) {
1031 goto GlmLocalOpen_skip_variant_and_update_chr;
1032 }
1033 prev_bp = variant_bps[prev_variant_uidx];
1034 }
1035 if (cur_bp_u == prev_bp) {
1036 // ID
1037 // note that if there are two same-position variants which appear in
1038 // a different order in the main dataset and the local-pvar file, one
1039 // will be skipped. (probably want to add a warning in this case.)
1040 const uint32_t variant_id_slen = token_slens[1];
1041 char* cur_variant_id = token_ptrs[1];
1042 cur_variant_id[variant_id_slen] = '\0';
1043 const uint32_t variant_id_blen = variant_id_slen + 1;
1044 // bugfix (16 Mar 2022): if a variant filter was applied to the main
1045 // dataset, the local-pvar entry corresponding to prev_variant_uidx
1046 // may be on a later line, even if we fail to find an ID match for
1047 // the current local-pvar ID.
1048 // So we no longer advance prev_variant_uidx/prev_bp here under any
1049 // circumstances. We just scan through the same-bp variant IDs,
1050 // looking for a match, and then advance to the next local-pvar line
1051 // with prev_variant_uidx/prev_bp unchanged.
1052 uint32_t scan_variant_uidx = prev_variant_uidx;
1053 uint32_t scan_bp;
1054 do {
1055 const char* loaded_variant_id = variant_ids[scan_variant_uidx];
1056 if (memequal(cur_variant_id, loaded_variant_id, variant_id_blen)) {
1057 if (unlikely(IsSet(new_variant_include, scan_variant_uidx))) {
1058 snprintf(g_logbuf, kLogbufSize, "Error: Duplicate ID (with duplicate CHROM/POS) '%s' in %s.\n", cur_variant_id, local_pvar_fname);
1059 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
1060 }
1061 SetBit(scan_variant_uidx, new_variant_include);
1062 ++new_variant_ct;
1063 SetBit(local_variant_ct, local_variant_include);
1064 break;
1065 }
1066 scan_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, scan_variant_uidx + 1, raw_variant_ct);
1067 if (scan_variant_uidx >= chr_end) {
1068 break;
1069 }
1070 scan_bp = variant_bps[scan_variant_uidx];
1071 } while (cur_bp_u == scan_bp);
1072 }
1073 continue;
1074 GlmLocalOpen_skip_variant_and_update_chr:
1075 if (prev_variant_uidx == raw_variant_ct) {
1076 break;
1077 }
1078 chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
1079 prev_chr_code = cip->chr_file_order[chr_fo_idx];
1080 prev_bp = variant_bps[prev_variant_uidx];
1081 chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
1082 }
1083 if (!line_start) {
1084 if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
1085 goto GlmLocalOpen_ret_TSTREAM_FAIL;
1086 }
1087 }
1088 BigstackFinalizeW(local_variant_include, BitCtToWordCt(local_variant_ct));
1089 *local_variant_ctl_ptr = BitCtToWordCt(local_variant_ct);
1090 assert(new_variant_ct <= *variant_ct_ptr);
1091 if (new_variant_ct < *variant_ct_ptr) {
1092 uintptr_t* variant_include_copy;
1093 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_copy))) {
1094 goto GlmLocalOpen_ret_NOMEM;
1095 }
1096 memcpy(variant_include_copy, new_variant_include, raw_variant_ctl * sizeof(intptr_t));
1097 *variant_include_ptr = variant_include_copy;
1098 *variant_ct_ptr = new_variant_ct;
1099 }
1100 }
1101
1102 // 3. If not local-cats[0]=, scan first line of local-covar= file to
1103 // determine covariate count.
1104 if (CleanupTextStream2(local_pvar_fname, &txs, &reterr)) {
1105 goto GlmLocalOpen_ret_1;
1106 }
1107 txs_fname = nullptr;
1108 BigstackEndReset(bigstack_end_mark);
1109 uintptr_t loadbuf_size = bigstack_left();
1110 if (loadbuf_size > kMaxLongLine) {
1111 loadbuf_size = kMaxLongLine;
1112 } else if (unlikely(loadbuf_size < kDecompressMinCapacity)) {
1113 // this shouldn't be possible
1114 goto GlmLocalOpen_ret_NOMEM;
1115 }
1116 // don't formally allocate
1117 char* dst = R_CAST(char*, g_bigstack_base);
1118 reterr = TextFileOpenEx(local_covar_fname, kMaxLongLine, loadbuf_size, dst, &local_covar_txf);
1119 if (unlikely(reterr)) {
1120 goto GlmLocalOpen_ret_RFILE_FAIL;
1121 }
1122 const uint32_t local_sample_or_hap_ct = local_sample_ct << ((glm_info_ptr->flags / kfGlmLocalHaps) & 1);
1123 const uint32_t skip_ct = glm_info_ptr->local_first_covar_col? (glm_info_ptr->local_first_covar_col - 1) : 0;
1124 uint32_t local_covar_ct;
1125 if (!glm_info_ptr->local_cat_ct) {
1126 const uint32_t first_nonheader_line_idx = glm_info_ptr->local_header_line_ct + 1;
1127 for (line_idx = 1; line_idx <= first_nonheader_line_idx; ++line_idx) {
1128 line_start = TextFileGet(&local_covar_txf);
1129 if (unlikely(!line_start)) {
1130 if (!TextFileErrcode2(&local_covar_txf, &reterr)) {
1131 snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", local_covar_fname);
1132 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
1133 }
1134 goto GlmLocalOpen_ret_RFILE_FAIL;
1135 }
1136 }
1137 const uint32_t token_ct = CountTokens(line_start);
1138 local_covar_ct = (token_ct - skip_ct) / local_sample_or_hap_ct;
1139 if (unlikely((token_ct < skip_ct) || (local_covar_ct * local_sample_or_hap_ct + skip_ct != token_ct))) {
1140 if (!skip_ct) {
1141 snprintf(g_logbuf, kLogbufSize, "Error: Unexpected token count on line %u of %s (%u, %smultiple of %u expected).\n", first_nonheader_line_idx, local_covar_fname, token_ct, (token_ct == local_sample_or_hap_ct)? "larger " : "", local_sample_or_hap_ct);
1142 } else {
1143 snprintf(g_logbuf, kLogbufSize, "Error: Unexpected token count on line %u of %s (%u, %u more than %smultiple of %u expected).\n", first_nonheader_line_idx, local_covar_fname, token_ct, skip_ct, (token_ct == local_sample_or_hap_ct)? "larger " : "", local_sample_or_hap_ct);
1144 }
1145 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
1146 }
1147 if (glm_info_ptr->flags & kfGlmLocalOmitLast) {
1148 if (unlikely(local_covar_ct == 1)) {
1149 logerrputs("Error: --glm 'local-omit-last' modifier cannot be used when there is only one\nlocal covariate.\n");
1150 goto GlmLocalOpen_ret_INCONSISTENT_INPUT;
1151 }
1152 logprintf("--glm local-covar=: %u local covariates present, %u used.\n", local_covar_ct, local_covar_ct - 1);
1153 --local_covar_ct;
1154 } else {
1155 logprintf("--glm local-covar=: %u local covariate%s present.\n", local_covar_ct, (local_covar_ct == 1)? "" : "s");
1156 }
1157 } else {
1158 local_covar_ct = glm_info_ptr->local_cat_ct - 1;
1159 if (unlikely(local_covar_ct * S_CAST(uint64_t, local_sample_or_hap_ct) > (kMaxLongLine / 2) - skip_ct)) {
1160 snprintf(g_logbuf, kLogbufSize, "Error: <# samples/haplotypes in %s> * <# categories - 1> too large (limited to %u).\n", local_covar_fname, kMaxLongLine / 2 - skip_ct);
1161 goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
1162 }
1163 }
1164 *local_covar_ct_ptr = local_covar_ct;
1165
1166 // 4. Initialize final local-covar reader.
1167 // Quasi-bugfix (6 Jun 2020): even in local-cats case, a header line may
1168 // have a floating point number per (sample, covariate) tuple.
1169 // Permit 24 characters per floating point number instead of 16, since some
1170 // tools dump 15-17 significant digits.
1171 uint64_t enforced_max_line_blen = local_sample_or_hap_ct * 24LLU;
1172 if (!glm_info_ptr->local_cat_ct) {
1173 enforced_max_line_blen *= local_covar_ct + ((glm_info_ptr->flags / kfGlmLocalOmitLast) & 1);
1174 } else {
1175 // Separate ID per (sample, category) possible on header line here.
1176 enforced_max_line_blen *= glm_info_ptr->local_cat_ct;
1177 }
1178 // \r\n
1179 enforced_max_line_blen += 2;
1180 if (unlikely(enforced_max_line_blen > kMaxLongLine)) {
1181 logerrputs("Error: Too many samples/covariates for --glm local-covar=.\n");
1182 goto GlmLocalOpen_ret_MALFORMED_INPUT;
1183 }
1184 if (enforced_max_line_blen < kDecompressMinBlen) {
1185 enforced_max_line_blen = kDecompressMinBlen;
1186 }
1187 uint32_t dst_capacity = enforced_max_line_blen + kDecompressChunkSize;
1188 if (TextFileLinebufLen(&local_covar_txf) > dst_capacity) {
1189 dst_capacity = TextFileLinebufLen(&local_covar_txf);
1190 }
1191 dst_capacity = RoundUpPow2(dst_capacity, kCacheline);
1192 if (bigstack_left() < dst_capacity) {
1193 goto GlmLocalOpen_ret_NOMEM;
1194 }
1195 g_bigstack_base = R_CAST(unsigned char*, &(dst[dst_capacity]));
1196 reterr = TextStreamOpenEx(nullptr, enforced_max_line_blen, dst_capacity, 1, &local_covar_txf, nullptr, local_covar_txsp);
1197 if (unlikely(reterr)) {
1198 TextStreamErrPrint(local_covar_fname, local_covar_txsp);
1199 goto GlmLocalOpen_ret_1;
1200 }
1201 bigstack_mark = g_bigstack_base;
1202 }
1203 while (0) {
1204 GlmLocalOpen_ret_NOMEM:
1205 reterr = kPglRetNomem;
1206 break;
1207 GlmLocalOpen_ret_TSTREAM_XID_FAIL:
1208 if (!TextStreamErrcode(&txs)) {
1209 break;
1210 }
1211 GlmLocalOpen_ret_TSTREAM_FAIL:
1212 TextStreamErrPrint(txs_fname, &txs);
1213 break;
1214 GlmLocalOpen_ret_RFILE_FAIL:
1215 TextFileErrPrint(local_covar_fname, &local_covar_txf);
1216 break;
1217 GlmLocalOpen_ret_MALFORMED_INPUT_WW:
1218 WordWrapB(0);
1219 logerrputsb();
1220 GlmLocalOpen_ret_MALFORMED_INPUT:
1221 reterr = kPglRetMalformedInput;
1222 break;
1223 GlmLocalOpen_ret_MISSING_TOKENS_PVAR:
1224 logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, local_pvar_fname);
1225 reterr = kPglRetMalformedInput;
1226 break;
1227 GlmLocalOpen_ret_INCONSISTENT_INPUT_WW:
1228 WordWrapB(0);
1229 logerrputsb();
1230 GlmLocalOpen_ret_INCONSISTENT_INPUT:
1231 reterr = kPglRetInconsistentInput;
1232 break;
1233 }
1234 GlmLocalOpen_ret_1:
1235 if (txs_fname) {
1236 CleanupTextStream2(txs_fname, &txs, &reterr);
1237 }
1238 CleanupTextFile2(local_covar_fname, &local_covar_txf, &reterr);
1239 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
1240 return reterr;
1241 }
1242
1243 uint32_t CheckForSeparatedQtCovar(const uintptr_t* pheno_cc, const uintptr_t* cur_sample_include, const double* covar_vals, uint32_t sample_ct, double* covar_val_keep_ptr) {
1244 const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
1245 double cur_covar_val = covar_vals[first_sample_uidx];
1246 double ctrl_min;
1247 double ctrl_max;
1248 double case_min;
1249 double case_max;
1250 if (IsSet(pheno_cc, first_sample_uidx)) {
1251 ctrl_min = DBL_MAX;
1252 ctrl_max = -DBL_MAX;
1253 case_min = cur_covar_val;
1254 case_max = cur_covar_val;
1255 } else {
1256 ctrl_min = cur_covar_val;
1257 ctrl_max = cur_covar_val;
1258 case_min = DBL_MAX;
1259 case_max = -DBL_MAX;
1260 }
1261 uintptr_t sample_uidx_base;
1262 uintptr_t cur_bits;
1263 BitIter1Start(cur_sample_include, first_sample_uidx + 1, &sample_uidx_base, &cur_bits);
1264 for (uint32_t sample_idx = 1; sample_idx != sample_ct; ++sample_idx) {
1265 const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
1266 cur_covar_val = covar_vals[sample_uidx];
1267 if (IsSet(pheno_cc, sample_uidx)) {
1268 if (cur_covar_val < case_min) {
1269 if ((ctrl_min < case_max) && (cur_covar_val < ctrl_max)) {
1270 return 0;
1271 }
1272 case_min = cur_covar_val;
1273 } else if (cur_covar_val > case_max) {
1274 if ((ctrl_max > case_min) && (cur_covar_val > ctrl_min)) {
1275 return 0;
1276 }
1277 case_max = cur_covar_val;
1278 }
1279 } else {
1280 if (cur_covar_val < ctrl_min) {
1281 if ((case_min < ctrl_max) && (cur_covar_val < case_max)) {
1282 return 0;
1283 }
1284 ctrl_min = cur_covar_val;
1285 } else if (cur_covar_val > ctrl_max) {
1286 if ((case_max > ctrl_min) && (cur_covar_val > case_min)) {
1287 return 0;
1288 }
1289 ctrl_max = cur_covar_val;
1290 }
1291 }
1292 }
1293 if ((case_min > ctrl_max) || (ctrl_min > case_max)) {
1294 return 2;
1295 }
1296 if (covar_val_keep_ptr) {
1297 *covar_val_keep_ptr = (case_min == ctrl_max)? case_min : case_max;
1298 }
1299 return 1;
1300 }
1301
1302 uint32_t CheckForSeparatedCatCovar(const uintptr_t* pheno_cc, const uintptr_t* cur_sample_include, const PhenoCol* covar_col, uint32_t sample_ct, uint32_t* case_and_ctrl_cat_ct_ptr, uintptr_t* cat_covar_wkspace) {
1303 const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
1304 const uint32_t nonnull_cat_ct = covar_col->nonnull_category_ct;
1305 const uint32_t cur_word_ct = 1 + nonnull_cat_ct / kBitsPerWordD2;
1306 ZeroWArr(cur_word_ct, cat_covar_wkspace);
1307 const uint32_t* covar_cats = covar_col->data.cat;
1308 // If no remaining categories have both cases and controls, we have complete
1309 // separation.
1310 // If some do and some do not, we have quasi-complete separation, and when
1311 // performing ordinary logistic regression, we must remove samples in the
1312 // all-case and/or all-control categories.
1313 uintptr_t sample_uidx_base;
1314 uintptr_t cur_bits;
1315 BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
1316 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1317 const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
1318 const uint32_t cur_cat_idx = covar_cats[sample_uidx];
1319 // Odd bits represent presence of a case, even bits represent presence of a
1320 // control.
1321 const uint32_t is_case = IsSet(pheno_cc, sample_uidx);
1322 SetBit(cur_cat_idx * 2 + is_case, cat_covar_wkspace);
1323 }
1324 uint32_t case_and_ctrl_cat_ct = 0;
1325 uint32_t pheno_by_cat_ct = 0;
1326 for (uint32_t widx = 0; widx != cur_word_ct; ++widx) {
1327 const uintptr_t cur_word = cat_covar_wkspace[widx];
1328 case_and_ctrl_cat_ct += Popcount01Word(Word11(cur_word));
1329 pheno_by_cat_ct += PopcountWord(cur_word);
1330 }
1331 if (!case_and_ctrl_cat_ct) {
1332 return 2;
1333 }
1334 if (case_and_ctrl_cat_ct * 2 == pheno_by_cat_ct) {
1335 // all categories contain both cases and controls.
1336 return 0;
1337 }
1338 if (case_and_ctrl_cat_ct_ptr) {
1339 *case_and_ctrl_cat_ct_ptr = case_and_ctrl_cat_ct;
1340 }
1341 return 1;
1342 }
1343
1344 // Returns 0 if not separated, 1 if quasi-separated, 2 if fully separated.
1345 uint32_t CheckForSeparatedCovar(const uintptr_t* pheno_cc, const uintptr_t* cur_sample_include, const PhenoCol* covar_col, uint32_t sample_ct, uintptr_t* cat_covar_wkspace) {
1346 if (sample_ct < 2) {
1347 return 2;
1348 }
1349 if (covar_col->type_code == kPhenoDtypeOther) {
1350 // local covariate, no precomputation possible
1351 return 0;
1352 }
1353 if (covar_col->type_code == kPhenoDtypeQt) {
1354 return CheckForSeparatedQtCovar(pheno_cc, cur_sample_include, covar_col->data.qt, sample_ct, nullptr);
1355 }
1356 return CheckForSeparatedCatCovar(pheno_cc, cur_sample_include, covar_col, sample_ct, nullptr, cat_covar_wkspace);
1357 }
1358
1359 // Returns 1 if phenotype fully separates the covariate, and the non-Firth
1360 // logistic regression should be aborted.
1361 // Otherwise, if we have quasi-separation, use Stata approach of throwing out
1362 // the covariate, and keeping only samples which have the one covariate value
1363 // present in both cases and controls.
1364 // Note that covar_ct is not a parameter; caller is responsible for
1365 // re-popcounting covar_include.
1366 BoolErr CheckForAndHandleSeparatedCovar(const uintptr_t* pheno_cc, const PhenoCol* covar_cols, uint32_t raw_sample_ctl, uint32_t covar_uidx, uintptr_t* cur_sample_include, uintptr_t* covar_include, uint32_t* sample_ct_ptr, uintptr_t* cat_covar_wkspace) {
1367 uint32_t sample_ct = *sample_ct_ptr;
1368 if (sample_ct < 2) {
1369 return 1;
1370 }
1371 const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
1372 if (cur_covar_col->type_code == kPhenoDtypeOther) {
1373 return 0;
1374 }
1375 const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
1376 if (cur_covar_col->type_code == kPhenoDtypeQt) {
1377 const double* covar_vals = cur_covar_col->data.qt;
1378 double covar_val_keep;
1379 const uint32_t separation_type = CheckForSeparatedQtCovar(pheno_cc, cur_sample_include, covar_vals, sample_ct, &covar_val_keep);
1380 if (separation_type != 1) {
1381 return separation_type / 2;
1382 }
1383 uintptr_t sample_uidx_base;
1384 uintptr_t cur_bits;
1385 BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
1386 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1387 const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
1388 if (covar_vals[sample_uidx] != covar_val_keep) {
1389 ClearBit(sample_uidx, cur_sample_include);
1390 }
1391 }
1392 *sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
1393 ClearBit(covar_uidx, covar_include);
1394 return 0;
1395 }
1396 uint32_t case_and_ctrl_cat_ct;
1397 const uint32_t separation_type = CheckForSeparatedCatCovar(pheno_cc, cur_sample_include, cur_covar_col, sample_ct, &case_and_ctrl_cat_ct, cat_covar_wkspace);
1398 if (separation_type != 1) {
1399 return separation_type / 2;
1400 }
1401 // more than one category contains both cases and controls (so we don't need
1402 // to remove the categorical covariate), but at least one does not, so we
1403 // still have to prune some samples.
1404 const uint32_t nonnull_cat_ct = cur_covar_col->nonnull_category_ct;
1405 const uint32_t cur_word_ct = 1 + nonnull_cat_ct / kBitsPerWordD2;
1406 for (uint32_t widx = 0; widx != cur_word_ct; ++widx) {
1407 const uintptr_t cur_word = cat_covar_wkspace[widx];
1408 cat_covar_wkspace[widx] = Word11(cur_word);
1409 }
1410 uintptr_t sample_uidx_base;
1411 uintptr_t cur_bits;
1412 BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
1413 const uint32_t* covar_cats = cur_covar_col->data.cat;
1414 // bugfix (7 Jul 2018): this needs to check sample_idx, not sample_uidx
1415 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1416 const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
1417 if (!IsSet(cat_covar_wkspace, covar_cats[sample_uidx] * 2)) {
1418 ClearBit(sample_uidx, cur_sample_include);
1419 }
1420 }
1421 *sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
1422 if (case_and_ctrl_cat_ct == 1) {
1423 ClearBit(covar_uidx, covar_include);
1424 }
1425 return 0;
1426 }
1427
1428 BoolErr GlmDetermineCovars(const uintptr_t* pheno_cc, const uintptr_t* initial_covar_include, const PhenoCol* covar_cols, uint32_t raw_sample_ct, uint32_t raw_covar_ctl, uint32_t initial_covar_ct, uint32_t covar_max_nonnull_cat_ct, uint32_t is_sometimes_firth, uint32_t is_always_firth, uintptr_t* cur_sample_include, uintptr_t* covar_include, uint32_t* sample_ct_ptr, uint32_t* covar_ct_ptr, uint32_t* extra_cat_ct_ptr, uint16_t* separation_found_ptr) {
1429 unsigned char* bigstack_mark = g_bigstack_base;
1430 BoolErr reterr = 0;
1431 {
1432 // bugfix (11 Mar 2020): if no covariates provided, covar_include ==
1433 // nullptr is possible, and covar_include[0] dereference below is optimized
1434 // out by some but not all compilers.
1435 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
1436 if (!covar_include) {
1437 *sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
1438 goto GlmDetermineCovars_ret_NOCOVAR;
1439 }
1440
1441 uintptr_t* sample_include_backup;
1442 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include_backup))) {
1443 goto GlmDetermineCovars_ret_NOMEM;
1444 }
1445 memcpy(sample_include_backup, cur_sample_include, raw_sample_ctl * sizeof(intptr_t));
1446 memcpy(covar_include, initial_covar_include, raw_covar_ctl * sizeof(intptr_t));
1447 // bugfix (28 Apr 2018): initial_covar_include can contain an extra sex set
1448 // bit at the end.
1449 if (PopcountWords(initial_covar_include, raw_covar_ctl) > initial_covar_ct) {
1450 uintptr_t last_word = covar_include[raw_covar_ctl - 1];
1451 const uint32_t highest_set_bit_idx = bsrw(last_word);
1452 covar_include[raw_covar_ctl - 1] -= k1LU << highest_set_bit_idx;
1453 }
1454
1455 // 1. Determine samples for which all phenotype/covariate values are
1456 // present, then provisionally remove the covariates which are constant
1457 // over that set in linear case, or produce separation in logistic case
1458 uintptr_t covar_uidx_base = 0;
1459 uintptr_t cur_bits = covar_include[0];
1460 for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
1461 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1462 if (covar_cols[covar_uidx].nonmiss) {
1463 BitvecAnd(covar_cols[covar_uidx].nonmiss, raw_sample_ctl, cur_sample_include);
1464 }
1465 }
1466 uint32_t prev_sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
1467 covar_uidx_base = 0;
1468 cur_bits = initial_covar_include[0];
1469 for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
1470 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
1471 if ((covar_cols[covar_uidx].type_code != kPhenoDtypeOther) && IsConstCovar(&(covar_cols[covar_uidx]), cur_sample_include, raw_sample_ct)) {
1472 ClearBit(covar_uidx, covar_include);
1473 }
1474 }
1475 uint32_t covar_ct = PopcountWords(covar_include, raw_covar_ctl);
1476 if (covar_ct != initial_covar_ct) {
1477 // 2. If any covariates were removed, redetermine the samples for which
1478 // all phenotype/covariate values are present. If there are more than
1479 // before, add back any provisionally removed covariates which don't
1480 // have any missing values in the new sample set, and are now
1481 // nonconstant.
1482 // Categorical covariates should behave just like they had been
1483 // pre-split into n-1 0/1 indicator variables.
1484 memcpy(cur_sample_include, sample_include_backup, raw_sample_ctl * sizeof(intptr_t));
1485 covar_uidx_base = 0;
1486 cur_bits = covar_include[0];
1487 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1488 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1489 if (covar_cols[covar_uidx].nonmiss) {
1490 BitvecAnd(covar_cols[covar_uidx].nonmiss, raw_sample_ctl, cur_sample_include);
1491 }
1492 }
1493 uint32_t new_sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
1494 if (new_sample_ct > prev_sample_ct) {
1495 prev_sample_ct = new_sample_ct;
1496 covar_uidx_base = 0;
1497 cur_bits = initial_covar_include[0];
1498 for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
1499 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
1500 if (!IsSet(covar_include, covar_uidx)) {
1501 const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
1502 if (PopcountWordsIntersect(cur_sample_include, cur_covar_col->nonmiss, raw_sample_ctl) == prev_sample_ct) {
1503 if (!IsConstCovar(cur_covar_col, cur_sample_include, raw_sample_ct)) {
1504 SetBit(covar_uidx, covar_include);
1505 }
1506 }
1507 }
1508 }
1509 covar_ct = PopcountWords(covar_include, raw_covar_ctl);
1510 }
1511 }
1512 if (!covar_ct) {
1513 *sample_ct_ptr = prev_sample_ct;
1514 goto GlmDetermineCovars_ret_NOCOVAR;
1515 }
1516 if (prev_sample_ct < 3) {
1517 goto GlmDetermineCovars_ret_SKIP;
1518 }
1519 // 3. if quantitative trait, remove samples corresponding to single-element
1520 // categories or constant-except-for-one-sample regular covariates.
1521 uint32_t sample_ct = prev_sample_ct;
1522 uint32_t extra_cat_ct = 0;
1523 BigstackReset(sample_include_backup);
1524 if (!pheno_cc) {
1525 uintptr_t* cat_one_obs = nullptr;
1526 uintptr_t* cat_two_or_more_obs = nullptr;
1527 uint32_t* cat_first_sample_uidxs = nullptr;
1528 if (covar_max_nonnull_cat_ct) {
1529 const uint32_t max_cat_ctl = 1 + (covar_max_nonnull_cat_ct / kBitsPerWord);
1530 if (unlikely(bigstack_alloc_w(max_cat_ctl, &cat_one_obs) ||
1531 bigstack_alloc_w(max_cat_ctl, &cat_two_or_more_obs) ||
1532 bigstack_alloc_u32(covar_max_nonnull_cat_ct + 1, &cat_first_sample_uidxs))) {
1533 goto GlmDetermineCovars_ret_NOMEM;
1534 }
1535 }
1536 do {
1537 prev_sample_ct = sample_ct;
1538 covar_uidx_base = 0;
1539 cur_bits = covar_include[0];
1540 extra_cat_ct = 0;
1541 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1542 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1543 const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
1544 if (cur_covar_col->type_code == kPhenoDtypeOther) {
1545 continue;
1546 }
1547 // bugfix (31 Aug 2018): sample_uidx_base/cur_sample_include_bits
1548 // must be reset on each iteration
1549 uintptr_t sample_uidx_base = 0;
1550 uintptr_t cur_sample_include_bits = cur_sample_include[0];
1551 if (cur_covar_col->type_code == kPhenoDtypeQt) {
1552 const double* pheno_vals = cur_covar_col->data.qt;
1553 const uint32_t first_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
1554 double common_pheno_val = pheno_vals[first_sample_uidx];
1555 const uint32_t second_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
1556 const double second_pheno_val = pheno_vals[second_sample_uidx];
1557 uint32_t sample_idx = 2;
1558 uint32_t sample_uidx_remove;
1559 if (second_pheno_val != common_pheno_val) {
1560 sample_uidx_remove = second_sample_uidx;
1561 const uint32_t third_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
1562 const double third_pheno_val = pheno_vals[third_sample_uidx];
1563 if (third_pheno_val == second_pheno_val) {
1564 common_pheno_val = second_pheno_val;
1565 sample_uidx_remove = first_sample_uidx;
1566 } else if (third_pheno_val != common_pheno_val) {
1567 continue;
1568 }
1569 sample_idx = 3;
1570 } else {
1571 sample_uidx_remove = UINT32_MAX;
1572 }
1573 // minor bugfix (8 Jul 2018): forgot to increment sample_uidx on
1574 // first loop iteration here
1575 // sample_ct >= 3 guaranteed
1576 for (; sample_idx != sample_ct; ++sample_idx) {
1577 const uint32_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
1578 if (pheno_vals[sample_uidx] != common_pheno_val) {
1579 if (sample_uidx_remove == UINT32_MAX) {
1580 sample_uidx_remove = sample_uidx;
1581 } else {
1582 break;
1583 }
1584 }
1585 }
1586 if (sample_idx == sample_ct) {
1587 if (sample_uidx_remove != UINT32_MAX) {
1588 if (--sample_ct == 2) {
1589 goto GlmDetermineCovars_ret_SKIP;
1590 }
1591 ClearBit(sample_uidx_remove, cur_sample_include);
1592 } else {
1593 // constant covariate, remove it
1594 ClearBit(covar_uidx, covar_include);
1595 }
1596 }
1597 } else {
1598 const uint32_t cur_nonnull_cat_ct = cur_covar_col->nonnull_category_ct;
1599 const uint32_t cur_cat_ctl = 1 + (cur_nonnull_cat_ct / kBitsPerWord);
1600 ZeroWArr(cur_cat_ctl, cat_one_obs);
1601 ZeroWArr(cur_cat_ctl, cat_two_or_more_obs);
1602 const uint32_t* pheno_vals = cur_covar_col->data.cat;
1603 for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
1604 const uint32_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
1605 const uint32_t cur_cat_idx = pheno_vals[sample_uidx];
1606 if (!IsSet(cat_two_or_more_obs, cur_cat_idx)) {
1607 if (IsSet(cat_one_obs, cur_cat_idx)) {
1608 SetBit(cur_cat_idx, cat_two_or_more_obs);
1609 } else {
1610 SetBit(cur_cat_idx, cat_one_obs);
1611 cat_first_sample_uidxs[cur_cat_idx] = sample_uidx;
1612 }
1613 }
1614 }
1615 for (uint32_t widx = 0; widx != cur_cat_ctl; ++widx) {
1616 uintptr_t cur_word = cat_one_obs[widx] & (~cat_two_or_more_obs[widx]);
1617 if (cur_word) {
1618 const uint32_t* cat_first_sample_uidxs_iter = &(cat_first_sample_uidxs[widx * kBitsPerWord]);
1619 do {
1620 const uint32_t cat_idx_lowbits = ctzw(cur_word);
1621
1622 // this could be moved out of the loop, but unlikely to be
1623 // profitable...
1624 --sample_ct;
1625
1626 ClearBit(cat_first_sample_uidxs_iter[cat_idx_lowbits], cur_sample_include);
1627 cur_word &= cur_word - 1;
1628 } while (cur_word);
1629 }
1630 }
1631 if (sample_ct < 3) {
1632 goto GlmDetermineCovars_ret_SKIP;
1633 }
1634 uint32_t remaining_cat_ct = PopcountWords(cat_two_or_more_obs, cur_cat_ctl);
1635 if (remaining_cat_ct <= 1) {
1636 // now a constant covariate, remove it
1637 ClearBit(covar_uidx, covar_include);
1638 } else {
1639 extra_cat_ct += remaining_cat_ct - 2;
1640 }
1641 }
1642 }
1643 covar_ct = PopcountWords(covar_include, raw_covar_ctl);
1644 } while (sample_ct < prev_sample_ct);
1645 } else {
1646 uintptr_t* cat_covar_wkspace;
1647 if (unlikely(bigstack_alloc_w(1 + (covar_max_nonnull_cat_ct / kBitsPerWordD2), &cat_covar_wkspace))) {
1648 goto GlmDetermineCovars_ret_NOMEM;
1649 }
1650 if (!is_always_firth) {
1651 if (!is_sometimes_firth) {
1652 do {
1653 prev_sample_ct = sample_ct;
1654 // bugfix (23 Nov 2023): these need to be reinitialized when the
1655 // while condition is actually true
1656 covar_uidx_base = 0;
1657 cur_bits = covar_include[0];
1658 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1659 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1660 if (CheckForAndHandleSeparatedCovar(pheno_cc, covar_cols, raw_sample_ctl, covar_uidx, cur_sample_include, covar_include, &sample_ct, cat_covar_wkspace)) {
1661 *separation_found_ptr = 1;
1662 goto GlmDetermineCovars_ret_SKIP;
1663 }
1664 }
1665 covar_ct = PopcountWords(covar_include, raw_covar_ctl);
1666 } while (sample_ct < prev_sample_ct);
1667 } else {
1668 covar_uidx_base = 0;
1669 cur_bits = covar_include[0];
1670 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1671 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1672 if (CheckForSeparatedCovar(pheno_cc, cur_sample_include, &(covar_cols[covar_uidx]), sample_ct, cat_covar_wkspace)) {
1673 *separation_found_ptr = 1;
1674 break;
1675 }
1676 }
1677 }
1678 }
1679
1680 // now count extra categories
1681 covar_uidx_base = 0;
1682 cur_bits = covar_include[0];
1683 extra_cat_ct = 0;
1684 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1685 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1686 const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
1687 if (cur_covar_col->type_code == kPhenoDtypeCat) {
1688 const uint32_t remaining_cat_ct = IdentifyRemainingCats(cur_sample_include, cur_covar_col, sample_ct, cat_covar_wkspace);
1689 if (remaining_cat_ct > 2) {
1690 extra_cat_ct += remaining_cat_ct - 2;
1691 }
1692 }
1693 }
1694 }
1695 *sample_ct_ptr = sample_ct;
1696 *covar_ct_ptr = covar_ct;
1697 *extra_cat_ct_ptr = extra_cat_ct;
1698 }
1699 while (0) {
1700 GlmDetermineCovars_ret_NOMEM:
1701 reterr = 1;
1702 break;
1703 GlmDetermineCovars_ret_SKIP:
1704 *sample_ct_ptr = 0;
1705 GlmDetermineCovars_ret_NOCOVAR:
1706 *covar_ct_ptr = 0;
1707 break;
1708 }
1709 BigstackReset(bigstack_mark);
1710 return reterr;
1711 }
1712
1713 uint32_t CollapseParamOrTestSubset(const uintptr_t* covar_include, const uintptr_t* raw_params_or_tests, uint32_t domdev_present, uint32_t raw_covar_ct, uint32_t covar_ct, uint32_t add_interactions, uintptr_t* new_params_or_tests) {
1714 const uint32_t first_covar_pred_idx = 2 + domdev_present;
1715 const uint32_t domdev_present_p1 = domdev_present + 1;
1716 uint32_t first_interaction_pred_read_idx = 0;
1717 uint32_t first_interaction_pred_write_idx = 0;
1718 if (add_interactions) {
1719 first_interaction_pred_read_idx = first_covar_pred_idx + raw_covar_ct;
1720 first_interaction_pred_write_idx = first_covar_pred_idx + covar_ct;
1721 }
1722 const uint32_t write_idx_ct = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
1723 const uint32_t write_idx_ctl = BitCtToWordCt(write_idx_ct);
1724 ZeroWArr(write_idx_ctl, new_params_or_tests);
1725 // intercept, additive, domdev
1726 new_params_or_tests[0] = raw_params_or_tests[0] & (3 + 4 * domdev_present);
1727 // bugfix (26 Jun 2019): covar_include == nullptr when covar_ct == 0
1728 if (covar_ct) {
1729 uintptr_t covar_uidx_base = 0;
1730 uintptr_t cur_bits = covar_include[0];
1731 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1732 const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
1733 if (IsSet(raw_params_or_tests, first_covar_pred_idx + covar_uidx)) {
1734 SetBit(first_covar_pred_idx + covar_idx, new_params_or_tests);
1735 }
1736 if (add_interactions) {
1737 if (IsSet(raw_params_or_tests, first_interaction_pred_read_idx + domdev_present_p1 * covar_uidx)) {
1738 SetBit(first_interaction_pred_write_idx + domdev_present_p1 * covar_idx, new_params_or_tests);
1739 }
1740 if (domdev_present) {
1741 if (IsSet(raw_params_or_tests, first_interaction_pred_read_idx + 2 * covar_uidx + 1)) {
1742 SetBit(first_interaction_pred_write_idx + 2 * covar_idx + 1, new_params_or_tests);
1743 }
1744 }
1745 }
1746 }
1747 }
1748 return PopcountWords(new_params_or_tests, write_idx_ctl);
1749 }
1750
1751 void PrintPrescanErrmsg(const char* domain_str, const char* pheno_name, const char** covar_names, GlmErr glm_err, uint32_t local_covar_ct, uint32_t skip_invalid_pheno, uint32_t is_batch) {
1752 const GlmErrcode errcode = GetGlmErrCode(glm_err);
1753 const char* msg_start = skip_invalid_pheno? "Note: Skipping " : "Error: Cannot proceed with ";
1754 if (errcode == kGlmErrcodeUnstableScale) {
1755 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s'%s, since genotype/covariate scales vary too widely for numerical stability of the current implementation. Try rescaling your covariates with e.g. --covar-variance-standardize.\n", msg_start, domain_str, pheno_name, is_batch? ", and other(s) with identical missingness patterns" : "");
1756 } else if (errcode == kGlmErrcodeVifInfinite) {
1757 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s'%s, since covariate correlation matrix could not be inverted (VIF_INFINITE).%s\n", msg_start, domain_str, pheno_name, is_batch? ", and other(s) with identical missingness patterns" : "", domain_str[0]? "" : " You may want to remove redundant covariates and try again.");
1758 } else if (errcode == kGlmErrcodeLogisticConvergeFail) {
1759 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s', since covariate-only logistic regression failed to converge, and Firth-fallback was disabled.\n", msg_start, domain_str, pheno_name);
1760 } else if (errcode == kGlmErrcodeFirthConvergeFail) {
1761 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s', since covariate-only Firth regression failed to converge.\n", msg_start, domain_str, pheno_name);
1762 } else {
1763 const char* covar_name1 = covar_names[GetGlmErrArg1(glm_err) + local_covar_ct];
1764 if (errcode == kGlmErrcodeVifTooHigh) {
1765 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s'%s, since variance inflation factor for covariate '%s' is too high (VIF_TOO_HIGH).%s\n", msg_start, domain_str, pheno_name, is_batch? ", and other(s) with identical missingness patterns" : "", covar_name1, domain_str[0]? "" : " You may want to remove redundant covariates and try again.");
1766 } else {
1767 const char* covar_name2 = covar_names[GetGlmErrArg2(glm_err) + local_covar_ct];
1768 snprintf(g_logbuf, kLogbufSize, "%s%s--glm regression on phenotype '%s'%s, since correlation between covariates '%s' and '%s' is too high (CORR_TOO_HIGH).%s\n", msg_start, domain_str, pheno_name, is_batch? ", and other(s) with identical missingness patterns" : "", covar_name1, covar_name2, domain_str[0]? "" : " You may want to remove redundant covariates and try again.");
1769 }
1770 }
1771 WordWrapB(0);
1772 if (skip_invalid_pheno) {
1773 logputsb();
1774 } else {
1775 logerrputsb();
1776 }
1777 }
1778
1779 BoolErr AllocAndInitReportedTestNames(const uintptr_t* parameter_subset, const char* const* covar_names, GlmFlags glm_flags, uint32_t covar_ct, uint32_t user_constraint_ct, const char*** cur_test_names_ptr) {
1780 const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
1781 const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
1782 const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
1783 const uint32_t is_hethom = (glm_flags / kfGlmHethom) & 1;
1784 const uint32_t domdev_present = (glm_flags & kfGlmGenotypic) || is_hethom;
1785 char main_effect[4];
1786 if (model_dominant) {
1787 memcpy(main_effect, "DOMx", 4);
1788 } else if (model_recessive) {
1789 memcpy(main_effect, "RECx", 4);
1790 } else if (model_hetonly) {
1791 memcpy(main_effect, "HETx", 4);
1792 } else if (is_hethom) {
1793 memcpy(main_effect, "HOMx", 4);
1794 } else {
1795 memcpy(main_effect, "ADDx", 4);
1796 }
1797 const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
1798 const uint32_t include_main_effect = (!parameter_subset) || IsSet(parameter_subset, 1);
1799 char domdev_str[8];
1800 uint32_t domdev_slen = 7;
1801 if (!is_hethom) {
1802 snprintf(domdev_str, 8, "DOMDEVx");
1803 } else {
1804 snprintf(domdev_str, 8, "HETx");
1805 domdev_slen = 4;
1806 }
1807
1808 const uint32_t joint_test = domdev_present || user_constraint_ct;
1809
1810 if (glm_flags & kfGlmHideCovar) {
1811 const uint32_t biallelic_reported_test_ct = include_intercept + include_main_effect + domdev_present + joint_test;
1812 char* test_name_buf_iter;
1813 if (unlikely(bigstack_alloc_kcp(biallelic_reported_test_ct, cur_test_names_ptr) ||
1814 bigstack_alloc_c(64, &test_name_buf_iter))) {
1815 return 1;
1816 }
1817 const char** cur_test_names = *cur_test_names_ptr;
1818 uint32_t write_idx = 0;
1819 if (include_intercept) {
1820 char* iter_next = memcpya_k(test_name_buf_iter, "INTERCEPT", 10);
1821 cur_test_names[write_idx++] = test_name_buf_iter;
1822 test_name_buf_iter = iter_next;
1823 }
1824 if (include_main_effect) {
1825 char* iter_next = memcpyax_k(test_name_buf_iter, main_effect, 3, '\0');
1826 cur_test_names[write_idx++] = test_name_buf_iter;
1827 test_name_buf_iter = iter_next;
1828 }
1829 if (domdev_present) {
1830 char* iter_next = memcpyax(test_name_buf_iter, domdev_str, domdev_slen - 1, '\0');
1831 cur_test_names[write_idx++] = test_name_buf_iter;
1832 test_name_buf_iter = iter_next;
1833 }
1834 if (joint_test) {
1835 if (user_constraint_ct) {
1836 char* iter_next = strcpya_k(test_name_buf_iter, "USER_");
1837 iter_next = u32toa(user_constraint_ct, iter_next);
1838 snprintf(iter_next, 64 - 10 - 4 - 8 - 15, "DF");
1839 } else {
1840 snprintf(test_name_buf_iter, 64 - 10 - 4 - 8, "GENO_2DF");
1841 }
1842 cur_test_names[write_idx++] = test_name_buf_iter;
1843 }
1844 assert(write_idx == biallelic_reported_test_ct);
1845 return 0;
1846 }
1847 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
1848 const uint32_t domdev_present_p1 = domdev_present + 1;
1849 uint32_t biallelic_predictor_ct_base = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
1850 uint32_t biallelic_predictor_ct = biallelic_predictor_ct_base;
1851 if (parameter_subset) {
1852 biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct_base));
1853 }
1854 const uint32_t biallelic_reported_test_ct = biallelic_predictor_ct + joint_test + include_intercept - 1;
1855 uintptr_t test_name_buf_alloc = 64;
1856 if (add_interactions) {
1857 // don't bother optimizing this for parameter_subset case for now
1858 uintptr_t covar_name_total_blen = covar_ct;
1859 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1860 covar_name_total_blen += strlen(covar_names[covar_idx]);
1861 }
1862 // ADDx[covar name], etc.
1863 test_name_buf_alloc += 4 * covar_ct + covar_name_total_blen;
1864 if (is_hethom) {
1865 // HETx
1866 test_name_buf_alloc += 4 * covar_ct + covar_name_total_blen;
1867 } else if (domdev_present) {
1868 // DOMDEVx
1869 test_name_buf_alloc += 7 * covar_ct + covar_name_total_blen;
1870 }
1871 }
1872 char* test_name_buf_iter;
1873 if (unlikely(bigstack_alloc_kcp(biallelic_reported_test_ct, cur_test_names_ptr) ||
1874 bigstack_alloc_c(test_name_buf_alloc, &test_name_buf_iter))) {
1875 return 1;
1876 }
1877 const char** cur_test_names = *cur_test_names_ptr;
1878 uint32_t write_idx = 0;
1879 if (include_intercept) {
1880 char* iter_next = memcpya_k(test_name_buf_iter, "INTERCEPT", 10);
1881 cur_test_names[write_idx++] = test_name_buf_iter;
1882 test_name_buf_iter = iter_next;
1883 }
1884 if (include_main_effect) {
1885 char* iter_next = memcpyax_k(test_name_buf_iter, main_effect, 3, '\0');
1886 cur_test_names[write_idx++] = test_name_buf_iter;
1887 test_name_buf_iter = iter_next;
1888 }
1889 if (domdev_present) {
1890 char* iter_next = memcpyax(test_name_buf_iter, domdev_str, domdev_slen - 1, '\0');
1891 cur_test_names[write_idx++] = test_name_buf_iter;
1892 test_name_buf_iter = iter_next;
1893 }
1894 uint32_t pred_uidx = 2 + domdev_present;
1895 // bugfix (16 Aug 2021): sex + interaction?
1896 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx, ++pred_uidx) {
1897 if (parameter_subset && (!IsSet(parameter_subset, pred_uidx))) {
1898 continue;
1899 }
1900 // just point to the existing string, its lifetime is sufficient
1901 cur_test_names[write_idx++] = covar_names[covar_idx];
1902 }
1903 if (add_interactions) {
1904 for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
1905 const char* cur_covar_name = covar_names[covar_idx];
1906 if ((!parameter_subset) || IsSet(parameter_subset, pred_uidx)) {
1907 char* iter_next = memcpya(test_name_buf_iter, main_effect, 4);
1908 iter_next = strcpyax(iter_next, cur_covar_name, '\0');
1909 cur_test_names[write_idx++] = test_name_buf_iter;
1910 test_name_buf_iter = iter_next;
1911 }
1912 ++pred_uidx;
1913 if (domdev_present) {
1914 if ((!parameter_subset) || IsSet(parameter_subset, pred_uidx)) {
1915 char* iter_next = memcpya(test_name_buf_iter, domdev_str, domdev_slen);
1916 iter_next = strcpyax(iter_next, cur_covar_name, '\0');
1917 cur_test_names[write_idx++] = test_name_buf_iter;
1918 test_name_buf_iter = iter_next;
1919 }
1920 ++pred_uidx;
1921 }
1922 }
1923 }
1924 if (joint_test) {
1925 if (user_constraint_ct) {
1926 char* iter_next = strcpya_k(test_name_buf_iter, "USER_");
1927 iter_next = u32toa(user_constraint_ct, iter_next);
1928 snprintf(iter_next, 64 - 10 - 4 - 8 - 15, "DF");
1929 } else {
1930 snprintf(test_name_buf_iter, 64 - 10 - 4 - 8, "GENO_2DF");
1931 }
1932 cur_test_names[write_idx++] = test_name_buf_iter;
1933 }
1934 assert(write_idx == biallelic_reported_test_ct);
1935 return 0;
1936 }
1937
1938 static const double kSexMaleToCovarD[2] = {2.0, 1.0};
1939
1940 void SexInteractionReshuffle(uint32_t first_interaction_pred_uidx, uint32_t raw_covar_ct, uint32_t domdev_present, uint32_t biallelic_raw_predictor_ctl, uintptr_t* __restrict parameters_or_tests, uintptr_t* __restrict parameter_subset_reshuffle_buf) {
1941 ZeroWArr(biallelic_raw_predictor_ctl, parameter_subset_reshuffle_buf);
1942 CopyBitarrRange(parameters_or_tests, 0, 0, first_interaction_pred_uidx - 1, parameter_subset_reshuffle_buf);
1943 // bugfix (16 Aug 2021): raw_covar_ct includes sex
1944 const uint32_t raw_nonsex_interaction_ct = (raw_covar_ct - 1) * (domdev_present + 1);
1945 CopyBitarrRange(parameters_or_tests, first_interaction_pred_uidx - 1, first_interaction_pred_uidx, raw_nonsex_interaction_ct, parameter_subset_reshuffle_buf);
1946 const uint32_t first_sex_parameter_idx = first_interaction_pred_uidx - 1 + raw_nonsex_interaction_ct;
1947 if (IsSet(parameters_or_tests, first_sex_parameter_idx)) {
1948 SetBit(first_interaction_pred_uidx - 1, parameter_subset_reshuffle_buf);
1949 }
1950 if (IsSet(parameters_or_tests, first_sex_parameter_idx + 1)) {
1951 SetBit(first_sex_parameter_idx + 1, parameter_subset_reshuffle_buf);
1952 }
1953 if (domdev_present && IsSet(parameters_or_tests, first_sex_parameter_idx + 2)) {
1954 SetBit(first_sex_parameter_idx + 2, parameter_subset_reshuffle_buf);
1955 }
1956 memcpy(parameters_or_tests, parameter_subset_reshuffle_buf, biallelic_raw_predictor_ctl * sizeof(intptr_t));
1957 }
1958
1959 PglErr GlmMain(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const PhenoCol* covar_cols, const char* covar_names, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const AlleleCode* maj_alleles, const char* const* allele_storage, const GlmInfo* glm_info_ptr, const AdjustInfo* adjust_info_ptr, const APerm* aperm_ptr, const char* local_covar_fname, const char* local_pvar_fname, const char* local_psam_fname, const GwasSsfInfo* gsip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t orig_covar_ct, uintptr_t max_covar_name_blen, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, uint32_t xchr_model, double ci_size, double vif_thresh, double ln_pfilter, double output_min_ln, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, PgenReader* simple_pgrp, char* outname, char* outname_end) {
1960 unsigned char* bigstack_mark = g_bigstack_base;
1961 unsigned char* bigstack_end_mark = g_bigstack_end;
1962
1963 // We may temporarily clear the cip->haploid_mask bit for chrX if all samples
1964 // are female. (This is only checked on function entry, it is not rechecked
1965 // on a per-phenotype basis.) Track this here so we can reverse it on
1966 // function exit.
1967 uint32_t x_fully_diploid = 0;
1968
1969 LlStr* gwas_ssf_ll = nullptr;
1970 PglErr reterr = kPglRetSuccess;
1971 TextStream local_covar_txs;
1972 TokenStream tks;
1973 PreinitTextStream(&local_covar_txs);
1974 PreinitTokenStream(&tks);
1975 GlmCtx common;
1976 GlmLogisticCtx logistic_ctx;
1977 GlmLinearCtx linear_ctx;
1978 logistic_ctx.common = &common;
1979 linear_ctx.common = &common;
1980 {
1981 if (unlikely(!pheno_ct)) {
1982 logerrputs("Error: No phenotypes loaded.\n");
1983 goto GlmMain_ret_INCONSISTENT_INPUT;
1984 }
1985 if (unlikely(orig_sample_ct < 2)) {
1986 logerrputs("Error: --glm requires at least two samples.\n");
1987 goto GlmMain_ret_DEGENERATE_DATA;
1988 }
1989 assert(orig_variant_ct);
1990 // common linear/logistic initialization
1991 const GlmFlags glm_flags = glm_info_ptr->flags;
1992 const uintptr_t* early_variant_include = orig_variant_include;
1993 uint32_t* local_sample_uidx_order = nullptr;
1994 uintptr_t* local_variant_include = nullptr;
1995 uint32_t variant_ct = orig_variant_ct;
1996 uint32_t local_sample_ct = 0;
1997 uint32_t local_variant_ctl = 0;
1998 uint32_t local_covar_ct = 0;
1999 if (local_covar_fname) {
2000 reterr = GlmLocalOpen(local_covar_fname, local_pvar_fname, local_psam_fname, siip, cip, variant_bps, variant_ids, glm_info_ptr, raw_sample_ct, raw_variant_ct, &orig_sample_include, &sex_nm, &sex_male, &early_variant_include, &orig_sample_ct, &variant_ct, &local_covar_txs, &local_sample_uidx_order, &local_variant_include, &local_sample_ct, &local_variant_ctl, &local_covar_ct);
2001 if (unlikely(reterr)) {
2002 goto GlmMain_ret_1;
2003 }
2004 }
2005
2006 common.glm_flags = glm_flags;
2007 common.dosage_presents = nullptr;
2008 common.dosage_mains = nullptr;
2009 const uint32_t output_zst = (glm_flags / kfGlmZs) & 1;
2010 const uint32_t perm_adapt = (glm_flags / kfGlmPerm) & 1;
2011 const uint32_t perms_total = perm_adapt? aperm_ptr->max : glm_info_ptr->mperm_ct;
2012 // <output prefix>.<pheno name>.glm.logistic.hybrid{,.perm,.mperm}[.zst]
2013 uint32_t pheno_name_blen_capacity = kPglFnamesize - 21 - (4 * output_zst) - S_CAST(uintptr_t, outname_end - outname);
2014 if (perms_total) {
2015 pheno_name_blen_capacity -= 6 - perm_adapt;
2016 }
2017 if (unlikely(max_pheno_name_blen > pheno_name_blen_capacity)) {
2018 logerrputs("Error: Phenotype name and/or --out argument too long.\n");
2019 goto GlmMain_ret_INCONSISTENT_INPUT;
2020 }
2021 *outname_end = '.';
2022 const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
2023 const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1;
2024
2025 // synthetic categorical covariate name could be ~twice max ID length?
2026 const uintptr_t overflow_buf_size = kCompressStreamBlock + 2 * kMaxIdSlen + max_chr_blen + kMaxIdSlen + 1024 + 2 * max_allele_slen;
2027
2028 uintptr_t* cur_sample_include;
2029 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_sample_include) ||
2030 bigstack_alloc_u32(raw_sample_ctl, &common.sample_include_cumulative_popcounts))) {
2031 goto GlmMain_ret_NOMEM;
2032 }
2033 common.sample_include = cur_sample_include;
2034 common.cip = cip;
2035 common.allele_idx_offsets = allele_idx_offsets;
2036
2037 const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
2038 uint32_t max_variant_ct = variant_ct;
2039
2040 uint32_t x_start;
2041 uint32_t x_end;
2042 GetXymtStartAndEnd(cip, kChrOffsetX, &x_start, &x_end);
2043 uint32_t y_start;
2044 uint32_t y_end;
2045 GetXymtStartAndEnd(cip, kChrOffsetY, &y_start, &y_end);
2046
2047 uintptr_t* sex_male_collapsed_buf = nullptr;
2048 uint32_t variant_ct_y = 0;
2049 const uint32_t domdev_present = (glm_flags & (kfGlmGenotypic | kfGlmHethom))? 1 : 0;
2050 const uint32_t sex_nm_ct = PopcountWords(sex_nm, raw_sample_ctl);
2051 const uint32_t male_ct = PopcountWords(sex_male, raw_sample_ctl);
2052 uint32_t add_sex_covar = !(glm_flags & kfGlmNoXSex);
2053 if (add_sex_covar && ((!male_ct) || (male_ct == sex_nm_ct))) {
2054 add_sex_covar = 0;
2055 }
2056 const uintptr_t* sex_nonfemale = sex_male;
2057 uint32_t nonfemale_ct = male_ct;
2058 if (sex_nm_ct != orig_sample_ct) {
2059 uintptr_t* sex_nonfemale_tmp;
2060 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sex_nonfemale_tmp))) {
2061 goto GlmMain_ret_NOMEM;
2062 }
2063 AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, sex_nonfemale_tmp);
2064 sex_nonfemale = sex_nonfemale_tmp;
2065 nonfemale_ct = PopcountWords(sex_nonfemale, raw_sample_ctl);
2066 }
2067 uint32_t variant_ct_x = 0;
2068 {
2069 uint32_t x_code;
2070 if (XymtExists(cip, kChrOffsetX, &x_code)) {
2071 variant_ct_x = CountChrVariantsUnsafe(early_variant_include, cip, x_code);
2072 x_fully_diploid = (!male_ct) && (sex_nm_ct == orig_sample_ct) && variant_ct_x && xchr_model;
2073 if (x_fully_diploid) {
2074 ClearBit(x_code, cip->haploid_mask);
2075 }
2076 }
2077 }
2078 uintptr_t* cur_sample_include_y_buf = nullptr;
2079 if (domdev_present || (glm_flags & (kfGlmDominant | kfGlmRecessive | kfGlmHetonly))) {
2080 // dominant/recessive/hetonly/genotypic/hethom suppress all chromosomes
2081 // which aren't fully diploid.
2082
2083 xchr_model = 0;
2084 // update (18 Sep 2021): chrX is no longer suppressed if all samples are
2085 // female.
2086 if (x_fully_diploid) {
2087 xchr_model = 2;
2088 logputs("--glm: Including chrX, despite presence of a diploid-only modifier\n('dominant', 'recessive', 'hetonly', 'genotypic', 'hethom'), since all samples\nare female.\n");
2089 } else {
2090 // bugfix (20 Sep 2021): need this to avoid double-subtraction.
2091 variant_ct_x = 0;
2092 }
2093 uintptr_t* variant_include_nohap = nullptr;
2094 const uint32_t chr_ct = cip->chr_ct;
2095 uint32_t removed_variant_ct = 0;
2096 for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) {
2097 const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx];
2098 if (IsSet(cip->haploid_mask, chr_idx)) {
2099 const uint32_t variant_uidx_start = cip->chr_fo_vidx_start[chr_fo_idx];
2100 const uint32_t variant_uidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1];
2101 const uint32_t cur_chr_variant_ct = PopcountBitRange(early_variant_include, variant_uidx_start, variant_uidx_end);
2102 if (cur_chr_variant_ct) {
2103 if (!removed_variant_ct) {
2104 // no main-loop logic for excluding all haploid chromosomes, so
2105 // make a full copy of early_variant_include and throw away our
2106 // reference to the original
2107 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_nohap))) {
2108 goto GlmMain_ret_NOMEM;
2109 }
2110 memcpy(variant_include_nohap, early_variant_include, raw_variant_ctl * sizeof(intptr_t));
2111 }
2112 ClearBitsNz(variant_uidx_start, variant_uidx_end, variant_include_nohap);
2113 removed_variant_ct += cur_chr_variant_ct;
2114 }
2115 }
2116 }
2117 if (removed_variant_ct) {
2118 if (unlikely(variant_ct == removed_variant_ct)) {
2119 logerrputs("Error: No variants remaining for --glm ('dominant', 'recessive', 'hetonly',\n'genotypic', and 'hethom' only operate on diploid data).\n");
2120 goto GlmMain_ret_DEGENERATE_DATA;
2121 }
2122 variant_ct -= removed_variant_ct;
2123 early_variant_include = variant_include_nohap;
2124 max_variant_ct = variant_ct;
2125 }
2126 } else {
2127 if (variant_ct_x) {
2128 // --xchr-model 0 now only suppresses chrX.
2129 if (xchr_model) {
2130 if (unlikely(bigstack_alloc_w(BitCtToWordCt(orig_sample_ct), &sex_male_collapsed_buf))) {
2131 goto GlmMain_ret_NOMEM;
2132 }
2133 } else {
2134 max_variant_ct -= variant_ct_x;
2135 if (unlikely(!max_variant_ct)) {
2136 logerrputs("Error: No variants remaining for --glm, due to --xchr-model 0.\n");
2137 goto GlmMain_ret_DEGENERATE_DATA;
2138 }
2139 }
2140 }
2141 uint32_t y_code;
2142 if (XymtExists(cip, kChrOffsetY, &y_code)) {
2143 variant_ct_y = CountChrVariantsUnsafe(early_variant_include, cip, y_code);
2144 if (variant_ct_y) {
2145 if (!nonfemale_ct) {
2146 logputs("--glm: Skipping chrY since all samples are female.\n");
2147 max_variant_ct -= variant_ct_y;
2148 if (unlikely(!max_variant_ct)) {
2149 logerrputs("Error: No variants remaining for --glm.\n");
2150 goto GlmMain_ret_DEGENERATE_DATA;
2151 }
2152 } else if (nonfemale_ct < orig_sample_ct) {
2153 // may as well check for only-chrY special case
2154 if (max_variant_ct != variant_ct_y) {
2155 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_sample_include_y_buf))) {
2156 // covar_include_y allocation postponed since raw_covar_ct not
2157 // yet known
2158 goto GlmMain_ret_NOMEM;
2159 }
2160 } else {
2161 orig_sample_include = sex_nonfemale;
2162 orig_sample_ct = nonfemale_ct;
2163 }
2164 }
2165 }
2166 }
2167 }
2168 if (add_sex_covar && (!variant_ct_x) && (!(glm_flags & kfGlmSex))) {
2169 add_sex_covar = 0;
2170 }
2171 common.sex_male_collapsed = sex_male_collapsed_buf;
2172 common.omitted_alleles = (glm_flags & kfGlmOmitRef)? nullptr : maj_alleles;
2173 uint32_t raw_covar_ct = orig_covar_ct + local_covar_ct;
2174 if (unlikely((!raw_covar_ct) && (!(glm_flags & kfGlmAllowNoCovars)))) {
2175 // now possible due to --not-covar
2176 logerrputs("Error: --glm invoked with no covariates, and 'allow-no-covars' was not\nspecified.\n");
2177 goto GlmMain_ret_INCONSISTENT_INPUT;
2178 }
2179 if (glm_info_ptr->condition_varname || glm_info_ptr->condition_list_fname || local_covar_ct || add_sex_covar) {
2180 uint32_t condition_ct = 0;
2181 PhenoCol* new_covar_cols;
2182 char* new_covar_names;
2183 uintptr_t new_max_covar_name_blen = max_covar_name_blen;
2184 if (add_sex_covar && (new_max_covar_name_blen < 4)) {
2185 new_max_covar_name_blen = 4;
2186 }
2187 if (local_covar_ct && (new_max_covar_name_blen < 6 + UintSlen(local_covar_ct + 1))) {
2188 new_max_covar_name_blen = 6 + UintSlen(local_covar_ct + 1);
2189 }
2190 if (glm_info_ptr->condition_varname || glm_info_ptr->condition_list_fname) {
2191 assert(g_bigstack_end == bigstack_end_mark);
2192 const uint32_t condition_multiallelic = (glm_flags / kfGlmConditionMultiallelic) & 1;
2193 if (condition_multiallelic) {
2194 logerrputs("Error: --condition[-list] 'multiallelic' implementation is under development.\n");
2195 reterr = kPglRetNotYetSupported;
2196 goto GlmMain_ret_1;
2197 }
2198 // reserve space for condition-list worst case (roughly sqrt(2^31)),
2199 // since that's relatively small
2200 const uint32_t condition_ct_max = 46338;
2201 uint32_t* condition_uidxs;
2202 if (unlikely(bigstack_end_alloc_u32(condition_ct_max, &condition_uidxs))) {
2203 goto GlmMain_ret_NOMEM;
2204 }
2205 if (glm_info_ptr->condition_varname) {
2206 int32_t ii = GetVariantUidxWithoutHtable(glm_info_ptr->condition_varname, variant_ids, orig_variant_include, orig_variant_ct);
2207 if (ii >= 0) {
2208 condition_uidxs[0] = ii;
2209 condition_ct = 1;
2210 const uint32_t condition_blen = strlen(glm_info_ptr->condition_varname) + 1;
2211 // drop "CSNP" column name for sanity's sake
2212 if (new_max_covar_name_blen < condition_blen) {
2213 new_max_covar_name_blen = condition_blen;
2214 }
2215 // TODO: this count will be different with a multiallelic variant
2216 logputs("--glm: One --condition covariate added.\n");
2217 } else {
2218 if (unlikely(ii == -2)) {
2219 logerrprintfww("Error: Duplicate --condition variant ID '%s'.\n", glm_info_ptr->condition_varname);
2220 goto GlmMain_ret_INVALID_CMDLINE;
2221 }
2222 logerrprintfww("Warning: --condition variant ID '%s' not found.\n", glm_info_ptr->condition_varname);
2223 }
2224 } else {
2225 // 1. (re)construct variant ID hash table
2226 uintptr_t* already_seen;
2227 if (unlikely(bigstack_calloc_w(raw_variant_ctl, &already_seen))) {
2228 goto GlmMain_ret_NOMEM;
2229 }
2230 reterr = InitTokenStream(glm_info_ptr->condition_list_fname, MAXV(max_thread_ct - 1, 1), &tks);
2231 if (unlikely(reterr)) {
2232 goto GlmMain_ret_TKSTREAM_FAIL;
2233 }
2234 uint32_t* variant_id_htable = nullptr;
2235 uint32_t variant_id_htable_size;
2236 reterr = AllocAndPopulateIdHtableMt(orig_variant_include, variant_ids, orig_variant_ct, 0, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr);
2237 if (unlikely(reterr)) {
2238 goto GlmMain_ret_1;
2239 }
2240
2241 // 2. iterate through --condition-list file, make sure no IDs are
2242 // duplicate in loaded fileset, warn about duplicates in
2243 // --condition-list file
2244 uintptr_t skip_ct = 0;
2245 uintptr_t duplicate_ct = 0;
2246 while (1) {
2247 char* shard_boundaries[2];
2248 reterr = TksNext(&tks, 1, shard_boundaries);
2249 if (reterr) {
2250 break;
2251 }
2252 const char* shard_iter = shard_boundaries[0];
2253 const char* shard_end = shard_boundaries[1];
2254 while (1) {
2255 shard_iter = FirstPostspaceBounded(shard_iter, shard_end);
2256 if (shard_iter == shard_end) {
2257 break;
2258 }
2259 const char* token_end = CurTokenEnd(shard_iter);
2260 const uint32_t token_slen = token_end - shard_iter;
2261 uint32_t cur_variant_uidx = VariantIdDupflagHtableFind(shard_iter, variant_ids, variant_id_htable, token_slen, variant_id_htable_size, max_variant_id_slen);
2262 if (cur_variant_uidx >> 31) {
2263 if (unlikely(cur_variant_uidx != UINT32_MAX)) {
2264 logerrprintfww("Error: --condition-list variant ID '%s' appears multiple times.\n", variant_ids[cur_variant_uidx & 0x7fffffff]);
2265 goto GlmMain_ret_INCONSISTENT_INPUT;
2266 }
2267 ++skip_ct;
2268 } else if (IsSet(already_seen, cur_variant_uidx)) {
2269 ++duplicate_ct;
2270 } else {
2271 if (unlikely(condition_ct == condition_ct_max)) {
2272 logerrputs("Error: Too many --condition-list variant IDs.\n");
2273 goto GlmMain_ret_MALFORMED_INPUT;
2274 }
2275 SetBit(cur_variant_uidx, already_seen);
2276 condition_uidxs[condition_ct++] = cur_variant_uidx;
2277 if (new_max_covar_name_blen <= token_slen) {
2278 new_max_covar_name_blen = token_slen + 1;
2279 }
2280 }
2281 shard_iter = token_end;
2282 }
2283 }
2284 if (unlikely(reterr != kPglRetEof)) {
2285 goto GlmMain_ret_TKSTREAM_FAIL;
2286 }
2287 if (CleanupTokenStream3("--condition-list file", &tks, &reterr)) {
2288 goto GlmMain_ret_1;
2289 }
2290 if (skip_ct || duplicate_ct) {
2291 if (skip_ct && duplicate_ct) {
2292 logerrprintfww("Warning: %" PRIuPTR " --condition-list variant ID%s not found, and %" PRIuPTR " duplicate ID%s present.\n", skip_ct, (skip_ct == 1)? "" : "s", duplicate_ct, (duplicate_ct == 1)? "" : "s");
2293 } else if (skip_ct) {
2294 logerrprintf("Warning: %" PRIuPTR " --condition-list variant ID%s not found.\n", skip_ct, (skip_ct == 1)? "" : "s");
2295 } else {
2296 logerrprintf("Warning: %" PRIuPTR " duplicate --condition-list variant ID%s present.\n", duplicate_ct, (duplicate_ct == 1)? "" : "s");
2297 }
2298 }
2299 logprintf("--condition-list: %u variant ID%s loaded.\n", condition_ct, (condition_ct == 1)? "" : "s");
2300
2301 // free hash table, duplicate tracker, TokenStream
2302 BigstackReset(already_seen);
2303 }
2304 raw_covar_ct += condition_ct;
2305 if (unlikely(BIGSTACK_ALLOC_X(PhenoCol, raw_covar_ct + add_sex_covar, &new_covar_cols) ||
2306 bigstack_alloc_c((raw_covar_ct + add_sex_covar) * new_max_covar_name_blen, &new_covar_names))) {
2307 goto GlmMain_ret_NOMEM;
2308 }
2309 if (condition_ct) {
2310 BigstackEndSet(condition_uidxs);
2311 uintptr_t* genovec;
2312 uintptr_t* dosage_present;
2313 Dosage* dosage_main;
2314 if (unlikely(bigstack_end_alloc_w(NypCtToWordCt(raw_sample_ct), &genovec) ||
2315 bigstack_end_alloc_w(raw_sample_ctl, &dosage_present) ||
2316 bigstack_end_alloc_dosage(raw_sample_ct, &dosage_main))) {
2317 goto GlmMain_ret_NOMEM;
2318 }
2319 PgrSampleSubsetIndex null_pssi;
2320 PgrClearSampleSubsetIndex(simple_pgrp, &null_pssi);
2321 uint32_t allele_ct = 2;
2322 for (uint32_t condition_idx = 0; condition_idx != condition_ct; ++condition_idx) {
2323 const uint32_t cur_variant_uidx = condition_uidxs[condition_idx];
2324 if (allele_idx_offsets) {
2325 allele_ct = allele_idx_offsets[cur_variant_uidx + 1] - allele_idx_offsets[cur_variant_uidx];
2326 if ((allele_ct != 2) && (!condition_multiallelic)) {
2327 logerrputs("Error: --condition[-list] includes a multiallelic variant, but 'multiallelic'\nmodifier was not specified.\n");
2328 goto GlmMain_ret_INCONSISTENT_INPUT;
2329 }
2330 }
2331 uint32_t dosage_ct;
2332 reterr = PgrGetD(nullptr, null_pssi, raw_sample_ct, cur_variant_uidx, simple_pgrp, genovec, dosage_present, dosage_main, &dosage_ct);
2333 if (unlikely(reterr)) {
2334 PgenErrPrintV(reterr, cur_variant_uidx);
2335 goto GlmMain_ret_1;
2336 }
2337 // alpha 2 update: default to major allele, respect omit-ref
2338 if (common.omitted_alleles && common.omitted_alleles[cur_variant_uidx]) {
2339 GenovecInvertUnsafe(raw_sample_ct, genovec);
2340 if (dosage_ct) {
2341 BiallelicDosage16Invert(dosage_ct, dosage_main);
2342 }
2343 }
2344 PhenoCol* cur_covar_col = &(new_covar_cols[local_covar_ct + condition_idx]);
2345 uintptr_t* cur_nonmiss;
2346 double* cur_covar_vals;
2347 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_nonmiss) ||
2348 bigstack_alloc_d(raw_sample_ct, &cur_covar_vals))) {
2349 goto GlmMain_ret_NOMEM;
2350 }
2351 cur_covar_col->category_names = nullptr;
2352 cur_covar_col->nonmiss = cur_nonmiss;
2353 cur_covar_col->data.qt = cur_covar_vals;
2354 cur_covar_col->type_code = kPhenoDtypeQt;
2355 cur_covar_col->nonnull_category_ct = 0;
2356 GenoarrToNonmissing(genovec, raw_sample_ct, cur_nonmiss);
2357 GenoarrLookup16x8bx2(genovec, kSmallDoublePairs, raw_sample_ct, cur_covar_vals);
2358 if (dosage_ct) {
2359 uintptr_t sample_uidx_base = 0;
2360 uintptr_t cur_bits = dosage_present[0];
2361 for (uint32_t dosage_idx = 0; dosage_idx != dosage_ct; ++dosage_idx) {
2362 const uintptr_t sample_uidx = BitIter1(dosage_present, &sample_uidx_base, &cur_bits);
2363 cur_covar_vals[sample_uidx] = kRecipDosageMid * u31tod(dosage_main[dosage_idx]);
2364 }
2365 BitvecOr(dosage_present, raw_sample_ctl, cur_nonmiss);
2366 }
2367 if (glm_flags & kfGlmConditionDominant) {
2368 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
2369 if (cur_covar_vals[sample_uidx] > 1.0) {
2370 cur_covar_vals[sample_uidx] = 1.0;
2371 }
2372 }
2373 } else if (glm_flags & kfGlmConditionRecessive) {
2374 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
2375 double dxx = cur_covar_vals[sample_uidx];
2376 if (dxx <= 1.0) {
2377 dxx = 0;
2378 } else {
2379 dxx -= 1.0;
2380 }
2381 cur_covar_vals[sample_uidx] = dxx;
2382 }
2383 }
2384 // quasi-bugfix (21 Feb 2018): also should respect
2385 // "--xchr-model 1", and divide by 2 in haploid case.
2386 const uint32_t chr_idx = GetVariantChr(cip, cur_variant_uidx);
2387 if (IsSet(cip->haploid_mask, chr_idx)) {
2388 if (chr_idx == cip->xymt_codes[kChrOffsetX]) {
2389 if (xchr_model == 1) {
2390 if (unlikely(glm_flags & (kfGlmConditionDominant | kfGlmConditionRecessive))) {
2391 // this is technically allowed when all samples are female,
2392 // but unimportant to mention that in the error message.
2393 logerrputs("Error: --condition[-list] 'dominant'/'recessive' cannot be used with a chrX\nvariant when \"--xchr-model 1\" is in effect.\n");
2394 goto GlmMain_ret_INCONSISTENT_INPUT;
2395 }
2396 uintptr_t sample_uidx_base = 0;
2397 uintptr_t cur_bits = sex_male[0];
2398 for (uint32_t male_idx = 0; male_idx != male_ct; ++male_idx) {
2399 const uintptr_t sample_uidx = BitIter1(sex_male, &sample_uidx_base, &cur_bits);
2400 cur_covar_vals[sample_uidx] *= 0.5;
2401 }
2402 }
2403 } else {
2404 if (unlikely(glm_flags & (kfGlmConditionDominant | kfGlmConditionRecessive))) {
2405 logerrputs("Error: --condition[-list] 'dominant'/'recessive' cannot be used with haploid\nvariants.\n");
2406 goto GlmMain_ret_INCONSISTENT_INPUT;
2407 }
2408 for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) {
2409 cur_covar_vals[sample_uidx] *= 0.5;
2410 }
2411 }
2412 }
2413 strcpy(&(new_covar_names[(local_covar_ct + condition_idx) * new_max_covar_name_blen]), variant_ids[cur_variant_uidx]);
2414 }
2415 BigstackEndReset(bigstack_end_mark);
2416 }
2417 } else {
2418 if (unlikely(BIGSTACK_ALLOC_X(PhenoCol, raw_covar_ct + add_sex_covar, &new_covar_cols) ||
2419 bigstack_alloc_c((raw_covar_ct + add_sex_covar) * new_max_covar_name_blen, &new_covar_names))) {
2420 goto GlmMain_ret_NOMEM;
2421 }
2422 }
2423 memcpy(&(new_covar_cols[condition_ct + local_covar_ct]), covar_cols, orig_covar_ct * sizeof(PhenoCol));
2424 const char* covar_names_read_iter = covar_names;
2425 // bugfix (11 May 2017): local covar names come before, not after,
2426 // --condition[-list] covar names
2427 char* covar_names_write_iter = new_covar_names;
2428 for (uint32_t local_covar_idx = 0; local_covar_idx != local_covar_ct; ++local_covar_idx) {
2429 memcpy_k(covar_names_write_iter, "LOCAL", 5);
2430 char* name_end = u32toa(local_covar_idx + 1, &(covar_names_write_iter[5]));
2431 *name_end = '\0';
2432 new_covar_cols[local_covar_idx].type_code = kPhenoDtypeOther;
2433 new_covar_cols[local_covar_idx].nonmiss = nullptr;
2434 covar_names_write_iter = &(covar_names_write_iter[new_max_covar_name_blen]);
2435 }
2436 covar_names_write_iter = &(covar_names_write_iter[condition_ct * new_max_covar_name_blen]);
2437 for (uint32_t old_covar_idx = 0; old_covar_idx != orig_covar_ct; ++old_covar_idx) {
2438 strcpy(covar_names_write_iter, covar_names_read_iter);
2439 covar_names_read_iter = &(covar_names_read_iter[max_covar_name_blen]);
2440 covar_names_write_iter = &(covar_names_write_iter[new_max_covar_name_blen]);
2441 }
2442 if (add_sex_covar) {
2443 PhenoCol* new_sex_col = &(new_covar_cols[raw_covar_ct++]);
2444 double* sex_covar_vals;
2445 if (unlikely(bigstack_alloc_d(raw_sample_ct, &sex_covar_vals))) {
2446 goto GlmMain_ret_NOMEM;
2447 }
2448 uintptr_t sample_uidx_base = 0;
2449 uintptr_t cur_bits = sex_nm[0];
2450 for (uint32_t sample_idx = 0; sample_idx != orig_sample_ct; ++sample_idx) {
2451 const uintptr_t sample_uidx = BitIter1(sex_nm, &sample_uidx_base, &cur_bits);
2452 // 1/2 instead of 1/0 coding; user shouldn't have to worry about
2453 // signs changing when they use --sex instead of using the sex column
2454 // from a .bim/.psam file
2455 sex_covar_vals[sample_uidx] = kSexMaleToCovarD[IsSet(sex_male, sample_uidx)];
2456 }
2457 new_sex_col->category_names = nullptr;
2458 new_sex_col->nonmiss = K_CAST(uintptr_t*, sex_nm);
2459 new_sex_col->data.qt = sex_covar_vals;
2460 new_sex_col->type_code = kPhenoDtypeQt;
2461 new_sex_col->nonnull_category_ct = 0;
2462 strcpy_k(covar_names_write_iter, "SEX");
2463 }
2464 covar_cols = new_covar_cols;
2465 covar_names = new_covar_names;
2466 max_covar_name_blen = new_max_covar_name_blen;
2467 }
2468 const uint32_t raw_covar_ctl = BitCtToWordCt(raw_covar_ct);
2469 uintptr_t* initial_covar_include = nullptr;
2470 uintptr_t* covar_include = nullptr;
2471 uintptr_t* cur_sample_include_x_buf = nullptr;
2472 uintptr_t* covar_include_x = nullptr;
2473 uint32_t covar_max_nonnull_cat_ct = 0;
2474 if (raw_covar_ctl) {
2475 if (unlikely(bigstack_alloc_w(raw_covar_ctl, &initial_covar_include) ||
2476 bigstack_alloc_w(raw_covar_ctl, &covar_include))) {
2477 goto GlmMain_ret_NOMEM;
2478 }
2479 ZeroWArr(raw_covar_ctl, initial_covar_include);
2480 for (uint32_t covar_uidx = 0; covar_uidx != raw_covar_ct; ++covar_uidx) {
2481 const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
2482 if (cur_covar_col->type_code != kPhenoDtypeOther) {
2483 if (!IsConstCovar(cur_covar_col, orig_sample_include, raw_sample_ct)) {
2484 SetBit(covar_uidx, initial_covar_include);
2485 if (cur_covar_col->type_code == kPhenoDtypeCat) {
2486 if (cur_covar_col->nonnull_category_ct > covar_max_nonnull_cat_ct) {
2487 covar_max_nonnull_cat_ct = cur_covar_col->nonnull_category_ct;
2488 }
2489 }
2490 } else {
2491 logerrprintf("Warning: Excluding constant covariate '%s' from --glm.\n", &(covar_names[covar_uidx * max_covar_name_blen]));
2492 }
2493 } else {
2494 // local covariate, always include
2495 SetBit(covar_uidx, initial_covar_include);
2496 }
2497 }
2498 if (unlikely(covar_max_nonnull_cat_ct && (glm_info_ptr->parameters_range_list.name_ct || glm_info_ptr->tests_range_list.name_ct))) {
2499 // todo: permit this, and automatically expand a single parameter index
2500 // referring to a categorical covariate into the appropriate range of
2501 // final predictor indices
2502 logerrputs("Error: --parameters/--tests cannot currently be used directly with categorical\ncovariates; expand them into binary covariates with --split-cat-pheno first.\n");
2503 goto GlmMain_ret_INCONSISTENT_INPUT;
2504 }
2505 }
2506 const uint32_t domdev_present_p1 = domdev_present + 1;
2507 const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
2508 // multiallelic case: one more predictor per extra allele
2509 const uint32_t biallelic_raw_predictor_ct = 2 + domdev_present + raw_covar_ct * (1 + add_interactions * domdev_present_p1);
2510
2511 const uint32_t max_extra_allele_ct = MaxAlleleCtSubset(early_variant_include, allele_idx_offsets, raw_variant_ct, variant_ct, PgrGetMaxAlleleCt(simple_pgrp)) - 2;
2512 if (unlikely(biallelic_raw_predictor_ct + max_extra_allele_ct > 46340)) {
2513 logerrputs("Error: Too many predictors for --glm.\n");
2514 if ((biallelic_raw_predictor_ct > 46000) && (max_extra_allele_ct < 23170)) {
2515 logerrputs("Try reducing the number of covariates.\n");
2516 } else if ((max_extra_allele_ct > 46000) && (biallelic_raw_predictor_ct < 23170)) {
2517 logerrputs("Try removing/splitting the variants with the most alternate alleles.\n");
2518 } else {
2519 logerrputs("Try reducing the number of covariates, and removing/splitting the variants with\nthe most alternate alleles.\n");
2520 }
2521 reterr = kPglRetNotYetSupported;
2522 goto GlmMain_ret_1;
2523 }
2524 const uint32_t biallelic_raw_predictor_ctl = BitCtToWordCt(biallelic_raw_predictor_ct);
2525 const uint32_t first_covar_pred_uidx = 2 + domdev_present;
2526 uint32_t first_interaction_pred_uidx = 0;
2527 if (add_interactions) {
2528 first_interaction_pred_uidx = first_covar_pred_uidx + raw_covar_ct;
2529 }
2530
2531 uintptr_t* raw_parameter_subset = nullptr;
2532 common.parameter_subset = nullptr;
2533 common.parameter_subset_x = nullptr;
2534 common.parameter_subset_y = nullptr;
2535 common.vif_thresh = vif_thresh;
2536 common.max_corr = glm_info_ptr->max_corr;
2537 // bugfix (20 Feb 2018): common.is_xchr_model_1 initialization was either
2538 // accidentally deleted, or I forgot to add it in the first place...
2539 common.is_xchr_model_1 = (xchr_model == 1);
2540 common.tests_flag = glm_info_ptr->tests_range_list.name_ct || (glm_flags & kfGlmTestsAll);
2541 const uint32_t joint_test = domdev_present || common.tests_flag;
2542 if (glm_info_ptr->parameters_range_list.name_ct) {
2543 if (unlikely(bigstack_calloc_w(biallelic_raw_predictor_ctl, &raw_parameter_subset) ||
2544 bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.parameter_subset) ||
2545 bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.parameter_subset_x) ||
2546 bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.parameter_subset_y))) {
2547 goto GlmMain_ret_NOMEM;
2548 }
2549 raw_parameter_subset[0] = 1; // intercept (index 0) always included
2550 NumericRangeListToBitarr(&(glm_info_ptr->parameters_range_list), biallelic_raw_predictor_ct, 0, 1, raw_parameter_subset);
2551 if (unlikely(domdev_present && ((raw_parameter_subset[0] & 7) != 7))) {
2552 // this breaks the joint test
2553 logerrputs("Error: --parameters cannot exclude 1 or 2 when the 'genotypic' or 'hethom'\nmodifier is present.\n");
2554 goto GlmMain_ret_INVALID_CMDLINE;
2555 }
2556 if (unlikely((glm_flags & kfGlmHideCovar) && (!joint_test) && (!(raw_parameter_subset[0] & 2)))) {
2557 logerrputs("Error: 'hide-covar' modifier suppresses all output due to --parameters setting.\n");
2558 goto GlmMain_ret_INVALID_CMDLINE;
2559 }
2560 }
2561 uintptr_t* raw_joint_test_params = nullptr;
2562 uintptr_t* joint_test_params_buf = nullptr;
2563 common.joint_test_params = nullptr;
2564 common.joint_test_params_x = nullptr;
2565 common.joint_test_params_y = nullptr;
2566 common.constraint_ct = 0;
2567 common.constraint_ct_x = 0;
2568 common.constraint_ct_y = 0;
2569 if (joint_test) {
2570 if (unlikely(bigstack_calloc_w(biallelic_raw_predictor_ctl, &raw_joint_test_params) ||
2571 bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.joint_test_params) ||
2572 bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.joint_test_params_x))) {
2573 goto GlmMain_ret_NOMEM;
2574 }
2575
2576 // includes intercept
2577 uint32_t raw_param_ct = biallelic_raw_predictor_ct;
2578 if (raw_parameter_subset) {
2579 if (unlikely(bigstack_alloc_w(biallelic_raw_predictor_ctl, &joint_test_params_buf))) {
2580 goto GlmMain_ret_NOMEM;
2581 }
2582 raw_param_ct = PopcountWords(raw_parameter_subset, biallelic_raw_predictor_ctl);
2583 }
2584
2585 if (!common.tests_flag) {
2586 // 1, 2
2587 raw_joint_test_params[0] = 6;
2588 } else {
2589 uintptr_t* tests_buf;
2590 if (unlikely(bigstack_alloc_w(biallelic_raw_predictor_ctl, &common.joint_test_params_y) ||
2591 bigstack_calloc_w(biallelic_raw_predictor_ctl, &tests_buf))) {
2592 goto GlmMain_ret_NOMEM;
2593 }
2594 if (glm_info_ptr->tests_range_list.name_ct) {
2595 if (unlikely(NumericRangeListToBitarr(&(glm_info_ptr->tests_range_list), raw_param_ct, 0, 0, tests_buf))) {
2596 logerrputs("Error: Invalid --tests expression.\n");
2597 goto GlmMain_ret_INVALID_CMDLINE;
2598 }
2599 } else {
2600 FillBitsNz(1, raw_param_ct, tests_buf);
2601 }
2602 if (raw_parameter_subset) {
2603 ExpandBytearr(tests_buf, raw_parameter_subset, biallelic_raw_predictor_ctl, raw_param_ct, 0, raw_joint_test_params);
2604 } else {
2605 memcpy(raw_joint_test_params, tests_buf, biallelic_raw_predictor_ctl * sizeof(intptr_t));
2606 }
2607 BigstackReset(tests_buf);
2608 }
2609 }
2610 if (raw_parameter_subset) {
2611 if (add_sex_covar && first_interaction_pred_uidx) {
2612 // special case: when add_sex_covar is true, the added sex covariate is
2613 // simply the last covariate, with predictor index
2614 // (first_interaction_pred_uidx - 1). This lines up with --parameters
2615 // when interactions are not requested; but when they are, we have a
2616 // small reshuffle to do.
2617 uintptr_t* parameter_subset_reshuffle_buf;
2618 if (unlikely(bigstack_alloc_w(biallelic_raw_predictor_ctl, &parameter_subset_reshuffle_buf))) {
2619 goto GlmMain_ret_NOMEM;
2620 }
2621 SexInteractionReshuffle(first_interaction_pred_uidx, raw_covar_ct, domdev_present, biallelic_raw_predictor_ctl, raw_parameter_subset, parameter_subset_reshuffle_buf);
2622 if (common.tests_flag) {
2623 SexInteractionReshuffle(first_interaction_pred_uidx, raw_covar_ct, domdev_present, biallelic_raw_predictor_ctl, raw_joint_test_params, parameter_subset_reshuffle_buf);
2624 }
2625 BigstackReset(parameter_subset_reshuffle_buf);
2626 }
2627 // if there were any constant covariates, exclude them from
2628 // raw_parameter_subset... but only after --tests has been processed, so
2629 // we handle indexes properly.
2630 // note that, if appended sex covariate is present at all, it is always
2631 // nonconstant.
2632 if (initial_covar_include) {
2633 const uint32_t nonconst_covar_ct = PopcountWords(initial_covar_include, raw_covar_ctl);
2634 const uint32_t removed_covar_ct = raw_covar_ct - nonconst_covar_ct;
2635 uintptr_t covar_uidx_base = 0;
2636 uintptr_t cur_inv_bits = ~initial_covar_include[0];
2637 for (uint32_t removed_covar_idx = 0; removed_covar_idx != removed_covar_ct; ++removed_covar_idx) {
2638 const uintptr_t covar_uidx = BitIter0(initial_covar_include, &covar_uidx_base, &cur_inv_bits);
2639 ClearBit(first_covar_pred_uidx + covar_uidx, raw_parameter_subset);
2640 if (first_interaction_pred_uidx) {
2641 const uint32_t geno_interaction_uidx = first_interaction_pred_uidx + covar_uidx * domdev_present_p1;
2642 ClearBit(geno_interaction_uidx, raw_parameter_subset);
2643 if (domdev_present) {
2644 ClearBit(geno_interaction_uidx + 1, raw_parameter_subset);
2645 }
2646 }
2647 }
2648 // if any loaded nonconstant covariates aren't referenced in
2649 // raw_parameter_subset, remove them from initial_covar_include
2650 covar_uidx_base = 0;
2651 uintptr_t cur_bits = initial_covar_include[0];
2652 for (uint32_t nonconst_covar_idx = 0; nonconst_covar_idx != nonconst_covar_ct; ++nonconst_covar_idx) {
2653 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
2654 uint32_t cur_covar_is_referenced = IsSet(raw_parameter_subset, first_covar_pred_uidx + covar_uidx);
2655 if (add_interactions) {
2656 cur_covar_is_referenced = cur_covar_is_referenced || IsSet(raw_parameter_subset, first_interaction_pred_uidx + covar_uidx * domdev_present_p1);
2657 if (domdev_present) {
2658 cur_covar_is_referenced = cur_covar_is_referenced || IsSet(raw_parameter_subset, first_interaction_pred_uidx + covar_uidx * 2 + 1);
2659 }
2660 }
2661 if (!cur_covar_is_referenced) {
2662 ClearBit(covar_uidx, initial_covar_include);
2663 }
2664 }
2665 // May as well remove constant covariates from joint test.
2666 if (common.tests_flag) {
2667 BitvecAnd(raw_parameter_subset, biallelic_raw_predictor_ctl, raw_joint_test_params);
2668 }
2669 }
2670 // if your regression doesn't involve genotype data, you should be using
2671 // e.g. R, not plink...
2672 if (unlikely((!(raw_parameter_subset[0] & 2)) &&
2673 ((!domdev_present) || (!(raw_parameter_subset[0] & 4))) &&
2674 ((!add_interactions) || (!PopcountBitRange(raw_parameter_subset, first_interaction_pred_uidx, biallelic_raw_predictor_ct))))) {
2675 logerrputs("Error: --parameters must retain at least one dosage-dependent variable.\n");
2676 goto GlmMain_ret_INCONSISTENT_INPUT;
2677 }
2678 }
2679 // computation of these counts moved here, since --parameters can reduce
2680 // the number of relevant covariates
2681 uint32_t initial_nonx_covar_ct = 0;
2682 if (initial_covar_include) {
2683 initial_nonx_covar_ct = PopcountWords(initial_covar_include, raw_covar_ctl);
2684 }
2685 uint32_t initial_y_covar_ct = 0;
2686 uintptr_t* covar_include_y = nullptr;
2687 if (!initial_nonx_covar_ct) {
2688 // BigstackReset(initial_covar_include); // not ok with parameters
2689 initial_covar_include = nullptr;
2690 covar_include = nullptr;
2691 } else {
2692 initial_y_covar_ct = initial_nonx_covar_ct - (cur_sample_include_y_buf && add_sex_covar && IsSet(initial_covar_include, raw_covar_ct - 1));
2693 if (add_sex_covar && (!(glm_flags & kfGlmSex))) {
2694 // may as well verify there's at least one non-x/non-y variant
2695 // (if only chrX and chrY present, don't allocate
2696 // cur_sample_include_x_buf, just make chrX the baseline instead)
2697 if (IsSet(initial_covar_include, raw_covar_ct - 1) && (variant_ct != variant_ct_x + variant_ct_y)) {
2698 if (unlikely(bigstack_alloc_w(raw_sample_ctl, &cur_sample_include_x_buf) ||
2699 bigstack_alloc_w(raw_covar_ctl, &covar_include_x))) {
2700 goto GlmMain_ret_NOMEM;
2701 }
2702 --initial_nonx_covar_ct;
2703 }
2704 }
2705 if (cur_sample_include_y_buf) {
2706 if (unlikely(bigstack_alloc_w(raw_covar_ctl, &covar_include_y))) {
2707 goto GlmMain_ret_NOMEM;
2708 }
2709 }
2710 }
2711
2712 const uint32_t report_adjust = (adjust_info_ptr->flags & kfAdjustColAll);
2713 const uint32_t is_sometimes_firth = !(glm_flags & kfGlmNoFirth);
2714 const uint32_t is_always_firth = glm_flags & kfGlmFirth;
2715 const uint32_t skip_invalid_pheno = (glm_flags / kfGlmSkipInvalidPheno) & 1;
2716 const uint32_t glm_pos_col = glm_info_ptr->cols & kfGlmColPos;
2717 const uint32_t gcount_cc_col = glm_info_ptr->cols & kfGlmColGcountcc;
2718 const uint32_t xtx_state = (add_interactions || local_covar_ct)? 0 : domdev_present_p1;
2719
2720 const uintptr_t raw_allele_ct = allele_idx_offsets? allele_idx_offsets[raw_variant_ct] : (2 * raw_variant_ct);
2721 const uintptr_t raw_allele_ctl = BitCtToWordCt(raw_allele_ct);
2722
2723 common.max_extra_allele_ct = max_extra_allele_ct;
2724
2725 const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct);
2726 uintptr_t* pheno_include;
2727 if (unlikely(bigstack_alloc_w(pheno_ctl, &pheno_include))) {
2728 goto GlmMain_ret_NOMEM;
2729 }
2730 SetAllBits(pheno_ct, pheno_include);
2731 const uint32_t is_qt_residualize = (glm_flags / kfGlmQtResidualize) & 1;
2732
2733 LlStr** gwas_ssf_ll_ptr = IsGwasSsf(gsip)? (&gwas_ssf_ll) : nullptr;
2734 uintptr_t* valid_variants = nullptr;
2735 uintptr_t* valid_alleles = nullptr;
2736 unsigned char* bigstack_mark2 = g_bigstack_base;
2737 if (report_adjust || perms_total) {
2738 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &valid_variants) ||
2739 bigstack_alloc_w(raw_allele_ctl, &valid_alleles))) {
2740 goto GlmMain_ret_NOMEM;
2741 }
2742 bigstack_mark2 = g_bigstack_base;
2743 } else if (pheno_ct > 1) {
2744 // When there are multiple quantitative phenotypes with the same
2745 // missingness pattern, they can be processed more efficiently together.
2746 uintptr_t* pheno_batch;
2747 uint32_t* pheno_nm_hashes;
2748 uintptr_t* pheno_nonmiss_tmp; // might be able to move this later
2749 if (unlikely(bigstack_alloc_w(pheno_ctl, &pheno_batch) ||
2750 bigstack_alloc_u32(pheno_ct, &pheno_nm_hashes) ||
2751 bigstack_alloc_w(raw_sample_ctl, &pheno_nonmiss_tmp))) {
2752 goto GlmMain_ret_NOMEM;
2753 }
2754 uint32_t completed_pheno_ct = 0;
2755 for (uint32_t pheno_uidx = 0; pheno_uidx != pheno_ct; ++pheno_uidx) {
2756 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
2757 const PhenoDtype dtype_code = cur_pheno_col->type_code;
2758 if (dtype_code != kPhenoDtypeQt) {
2759 ClearBit(pheno_uidx, pheno_include);
2760 continue;
2761 }
2762 BitvecAndCopy(orig_sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include);
2763 if (IsConstCovar(cur_pheno_col, cur_sample_include, raw_sample_ct)) {
2764 const char* cur_pheno_name = &(pheno_names[pheno_uidx * max_pheno_name_blen]);
2765 if (unlikely(!skip_invalid_pheno)) {
2766 logerrprintfww("Error: --glm quantitative phenotype '%s' is constant.\n", cur_pheno_name);
2767 goto GlmMain_ret_INCONSISTENT_INPUT;
2768 }
2769 logprintfww("--glm: Skipping constant quantitative phenotype '%s'.\n", cur_pheno_name);
2770 ClearBit(pheno_uidx, pheno_include);
2771 continue;
2772 }
2773 // May want to use 64-bit XXH3 hashes instead. But let's get this
2774 // working first.
2775 pheno_nm_hashes[pheno_uidx] = Hash32(cur_sample_include, raw_sample_ctl * sizeof(intptr_t));
2776 }
2777 unsigned char* bigstack_mark3 = g_bigstack_base;
2778
2779 for (uint32_t pheno_uidx = 0; pheno_uidx != pheno_ct; ++pheno_uidx) {
2780 if (!IsSet(pheno_include, pheno_uidx)) {
2781 continue;
2782 }
2783 ZeroWArr(pheno_ctl, pheno_batch);
2784 SetBit(pheno_uidx, pheno_batch);
2785 const uint32_t cur_hash = pheno_nm_hashes[pheno_uidx];
2786 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
2787 BitvecAndCopy(orig_sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include);
2788 // possible todo: switch to O(n log n)-expected-time algorithm here.
2789 // But unlikely to matter since this cost should be minuscule compared
2790 // to the actual regressions, and in the
2791 // all-phenotype-values-are-present case this is O(n) anyway.
2792 for (uint32_t pheno_uidx2 = pheno_uidx + 1; pheno_uidx2 != pheno_ct; ++pheno_uidx2) {
2793 if ((!IsSet(pheno_include, pheno_uidx2)) || (cur_hash != pheno_nm_hashes[pheno_uidx2])) {
2794 continue;
2795 }
2796 const PhenoCol* candidate_pheno_col = &(pheno_cols[pheno_uidx2]);
2797 BitvecAndCopy(orig_sample_include, candidate_pheno_col->nonmiss, raw_sample_ctl, pheno_nonmiss_tmp);
2798 if (memequal(cur_sample_include, pheno_nonmiss_tmp, raw_sample_ctl * sizeof(intptr_t))) {
2799 SetBit(pheno_uidx2, pheno_batch);
2800 }
2801 }
2802 uint32_t batch_size = PopcountWords(pheno_batch, pheno_ctl);
2803 if (batch_size == 1) {
2804 continue;
2805 }
2806 // probable todo: pull out lots of shared code with the non-batch
2807 // phenotype loop.
2808 uint32_t sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
2809 uint32_t covar_ct = 0;
2810 uint32_t extra_cat_ct = 0;
2811 BigstackDoubleReset(bigstack_mark3, bigstack_end_mark);
2812 if (initial_nonx_covar_ct) {
2813 uint16_t dummy = 0;
2814 if (unlikely(GlmDetermineCovars(nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_nonx_covar_ct, covar_max_nonnull_cat_ct, 0, 0, cur_sample_include, covar_include, &sample_ct, &covar_ct, &extra_cat_ct, &dummy))) {
2815 goto GlmMain_ret_NOMEM;
2816 }
2817 }
2818 uint32_t biallelic_predictor_ct = 2 + domdev_present + (covar_ct + extra_cat_ct) * (1 + add_interactions * domdev_present_p1);
2819 if (raw_parameter_subset) {
2820 biallelic_predictor_ct = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct, add_interactions, common.parameter_subset);
2821 }
2822 if (raw_joint_test_params) {
2823 common.constraint_ct = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct, add_interactions, common.joint_test_params);
2824 if (raw_parameter_subset) {
2825 memcpy(joint_test_params_buf, common.joint_test_params, biallelic_raw_predictor_ctl * sizeof(intptr_t));
2826 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params);
2827 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset, biallelic_predictor_ct, common.joint_test_params);
2828 }
2829 }
2830 const char* first_pheno_name = &(pheno_names[pheno_uidx * max_pheno_name_blen]);
2831 if (sample_ct <= biallelic_predictor_ct) {
2832 if (unlikely(!skip_invalid_pheno)) {
2833 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s'.\n", first_pheno_name);
2834 goto GlmMain_ret_INCONSISTENT_INPUT;
2835 }
2836 logprintfww("Note: Skipping --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since # samples <= # predictor columns.\n", first_pheno_name);
2837 BitvecInvmask(pheno_batch, pheno_ctl, pheno_include);
2838 continue;
2839 }
2840 #ifdef __LP64__
2841 if (RoundUpPow2(sample_ct, 4) * S_CAST(uint64_t, biallelic_predictor_ct + max_extra_allele_ct) > 0x7fffffff) {
2842 // todo: remove this constraint in LAPACK_ILP64 case?
2843 if (unlikely(!skip_invalid_pheno)) {
2844 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
2845 goto GlmMain_ret_INCONSISTENT_INPUT;
2846 }
2847 logerrprintfww("Warning: Skipping --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
2848 BitvecInvmask(pheno_batch, pheno_ctl, pheno_include);
2849 continue;
2850 }
2851 #endif
2852 if (common.tests_flag && (!common.constraint_ct)) {
2853 if (unlikely(!skip_invalid_pheno)) {
2854 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples for --glm phenotype '%s'.\n", first_pheno_name);
2855 goto GlmMain_ret_INCONSISTENT_INPUT;
2856 }
2857 logprintfww("Note: Skipping --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since --tests predictor(s) are constant for all remaining samples.\n", first_pheno_name);
2858 BitvecInvmask(pheno_batch, pheno_ctl, pheno_include);
2859 continue;
2860 }
2861 if (covar_ct < initial_nonx_covar_ct) {
2862 uintptr_t covar_uidx_base = 0;
2863 uintptr_t cur_bits = initial_covar_include[0];
2864 for (uint32_t covar_idx = 0; covar_idx != initial_nonx_covar_ct; ++covar_idx) {
2865 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
2866 if (!IsSet(covar_include, covar_uidx)) {
2867 logerrprintfww("Warning: %sot including covariate '%s' in --glm regression on phenotype '%s', and other(s) with identical missingness patterns.\n", cur_sample_include_x_buf? (cur_sample_include_y_buf? "Outside of chrX, n" : "Outside of chrX and chrY, n") : (cur_sample_include_y_buf? "Outside of chrY, n" : "N"), &(covar_names[covar_uidx * max_covar_name_blen]), first_pheno_name);
2868 }
2869 }
2870 }
2871
2872 // cur_sample_include_x == nullptr: chrX uses same samples and
2873 // covariates as the rest of the genome. sample_ct_x always zero to
2874 // force most chrX-specific initialization to be skipped (exception:
2875 // sex_male_collapsed, needed for allele count/freq reporting)
2876 // cur_sample_include_x non-null: if sample_ct_x == 0, we skip the
2877 // entire chromosome. otherwise, we have different covariates than
2878 // the rest of the genome.
2879 uintptr_t* cur_sample_include_x = cur_sample_include_x_buf;
2880 uint32_t sample_ct_x = 0;
2881 uint32_t covar_ct_x = 0;
2882 uint32_t extra_cat_ct_x = 0;
2883 uint32_t biallelic_predictor_ct_x = 0;
2884 uint32_t x_samples_are_different = 0;
2885 if (cur_sample_include_x) {
2886 BitvecAndCopy(orig_sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include_x);
2887 uint16_t dummy = 0;
2888 if (unlikely(GlmDetermineCovars(nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_nonx_covar_ct + 1, covar_max_nonnull_cat_ct, 0, 0, cur_sample_include_x, covar_include_x, &sample_ct_x, &covar_ct_x, &extra_cat_ct_x, &dummy))) {
2889 goto GlmMain_ret_NOMEM;
2890 }
2891 x_samples_are_different = (sample_ct_x != sample_ct) || (!wordsequal(cur_sample_include, cur_sample_include_x, raw_sample_ctl));
2892 if ((!x_samples_are_different) && (covar_ct == covar_ct_x) && wordsequal(covar_include, covar_include_x, raw_covar_ctl)) {
2893 logprintfww("Note: chrX samples and covariate(s) in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, are the same as that for the rest of the genome.\n", first_pheno_name);
2894 sample_ct_x = 0;
2895 cur_sample_include_x = nullptr;
2896 } else {
2897 if (!sample_ct_x) {
2898 if (unlikely(!skip_invalid_pheno)) {
2899 logerrprintfww("Error: --glm regression on phenotype '%s' is degenerate on chrX.\n", first_pheno_name);
2900 goto GlmMain_ret_INCONSISTENT_INPUT;
2901 }
2902 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', and other(s) with identical missingness patterns.\n", first_pheno_name);
2903 } else {
2904 biallelic_predictor_ct_x = 2 + domdev_present + (covar_ct_x + extra_cat_ct_x) * (1 + add_interactions * domdev_present_p1);
2905 if (raw_parameter_subset) {
2906 biallelic_predictor_ct_x = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct_x, add_interactions, common.parameter_subset_x);
2907 }
2908 if (raw_joint_test_params) {
2909 common.constraint_ct_x = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct_x, add_interactions, common.joint_test_params_x);
2910 if (raw_parameter_subset) {
2911 memcpy(joint_test_params_buf, common.joint_test_params_x, biallelic_raw_predictor_ctl * sizeof(intptr_t));
2912 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params_x);
2913 // bugfix (2 Oct 2023): parameter_subset ->
2914 // parameter_subset_x
2915 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset_x, biallelic_predictor_ct_x, common.joint_test_params_x);
2916 }
2917 }
2918 if (sample_ct_x <= biallelic_predictor_ct_x) {
2919 if (unlikely(!skip_invalid_pheno)) {
2920 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s' on chrX.\n", first_pheno_name);
2921 goto GlmMain_ret_INCONSISTENT_INPUT;
2922 }
2923 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since # remaining samples <= # predictor columns.\n", first_pheno_name);
2924 sample_ct_x = 0;
2925 #ifdef __LP64__
2926 } else if (RoundUpPow2(sample_ct_x, 4) * S_CAST(uint64_t, biallelic_predictor_ct_x + max_extra_allele_ct) > 0x7fffffff) {
2927 if (unlikely(!skip_invalid_pheno)) {
2928 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' on chrX (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
2929 goto GlmMain_ret_INCONSISTENT_INPUT;
2930 }
2931 logerrprintfww("Warning: Skipping chrX in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
2932 sample_ct_x = 0;
2933 #endif
2934 } else {
2935 for (uint32_t pheno_uidx2 = pheno_uidx; pheno_uidx2 != pheno_ct; ++pheno_uidx2) {
2936 if (!IsSet(pheno_batch, pheno_uidx2)) {
2937 continue;
2938 }
2939 const PhenoCol* candidate_pheno_col = &(pheno_cols[pheno_uidx2]);
2940 if (IsConstCovar(candidate_pheno_col, cur_sample_include_x, raw_sample_ct)) {
2941 // Punt to single-phenotype-at-a-time handler.
2942 ClearBit(pheno_uidx2, pheno_batch);
2943 }
2944 }
2945 // possible todo: reset first_pheno_name here
2946 }
2947 if (sample_ct_x && common.tests_flag && (!common.constraint_ct_x)) {
2948 if (unlikely(!skip_invalid_pheno)) {
2949 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples on chrX for --glm phenotype '%s'.\n", first_pheno_name);
2950 goto GlmMain_ret_INCONSISTENT_INPUT;
2951 }
2952 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since --tests predictor(s) are constant for all remaining samples.\n", first_pheno_name);
2953 sample_ct_x = 0;
2954 }
2955 if (sample_ct_x && (covar_ct_x < initial_nonx_covar_ct + 1)) {
2956 uintptr_t covar_uidx_base = 0;
2957 uintptr_t cur_bits = initial_covar_include[0];
2958 for (uint32_t covar_idx = 0; covar_idx != covar_ct_x; ++covar_idx) {
2959 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
2960 if (!IsSet(covar_include_x, covar_uidx)) {
2961 logerrprintfww("Warning: On chrX, not including covariate '%s' in --glm regression on phenotype '%s', and other(s) with identical missingness patterns.\n", &(covar_names[covar_uidx * max_covar_name_blen]), first_pheno_name);
2962 }
2963 }
2964 }
2965 }
2966 }
2967 }
2968
2969 uintptr_t* cur_sample_include_y = cur_sample_include_y_buf;
2970 uint32_t sample_ct_y = 0;
2971 uint32_t covar_ct_y = 0;
2972 uint32_t extra_cat_ct_y = 0;
2973 uint32_t biallelic_predictor_ct_y = 0;
2974 uint32_t y_samples_are_different = 0;
2975 if (cur_sample_include_y) {
2976 BitvecAndCopy(orig_sample_include, sex_nonfemale, raw_sample_ctl, cur_sample_include_y);
2977 BitvecAnd(cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include_y);
2978 uint16_t dummy = 0;
2979 if (unlikely(GlmDetermineCovars(nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_y_covar_ct, covar_max_nonnull_cat_ct, 0, 0, cur_sample_include_y, covar_include_y, &sample_ct_y, &covar_ct_y, &extra_cat_ct_y, &dummy))) {
2980 goto GlmMain_ret_NOMEM;
2981 }
2982 y_samples_are_different = (sample_ct_y != sample_ct) || (!wordsequal(cur_sample_include, cur_sample_include_y, raw_sample_ctl));
2983 if ((!y_samples_are_different) && (covar_ct == covar_ct_y) && wordsequal(covar_include, covar_include_y, raw_covar_ctl)) {
2984 logprintfww("Note: chrY samples and covariate(s) in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, are the same as that for the rest of the genome.\n", first_pheno_name);
2985 sample_ct_y = 0;
2986 cur_sample_include_y = nullptr;
2987 } else {
2988 if (!sample_ct_y) {
2989 if (unlikely(!skip_invalid_pheno)) {
2990 logerrprintfww("Error: --glm regression on phenotype '%s' is degenerate on chrY.\n", first_pheno_name);
2991 goto GlmMain_ret_INCONSISTENT_INPUT;
2992 }
2993 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', and other(s) with identical missingness patterns.\n", first_pheno_name);
2994 } else {
2995 biallelic_predictor_ct_y = 2 + domdev_present + (covar_ct_y + extra_cat_ct_y) * (1 + add_interactions * domdev_present_p1);
2996 if (raw_parameter_subset) {
2997 biallelic_predictor_ct_y = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct_y, add_interactions, common.parameter_subset_y);
2998 }
2999 if (raw_joint_test_params) {
3000 assert(common.tests_flag);
3001 common.constraint_ct_y = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct_y, add_interactions, common.joint_test_params_y);
3002 if (raw_parameter_subset) {
3003 memcpy(joint_test_params_buf, common.joint_test_params_y, biallelic_raw_predictor_ctl * sizeof(intptr_t));
3004 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params_y);
3005 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset_y, biallelic_predictor_ct_y, common.joint_test_params_y);
3006 }
3007 }
3008 if (sample_ct_y <= biallelic_predictor_ct_y) {
3009 if (unlikely(!skip_invalid_pheno)) {
3010 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s' on chrY.\n", first_pheno_name);
3011 goto GlmMain_ret_INCONSISTENT_INPUT;
3012 }
3013 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since # remaining samples <= # predictor columns.\n", first_pheno_name);
3014 sample_ct_y = 0;
3015 #ifdef __LP64__
3016 } else if (RoundUpPow2(sample_ct_y, 4) * S_CAST(uint64_t, biallelic_predictor_ct_y + max_extra_allele_ct) > 0x7fffffff) {
3017 if (unlikely(!skip_invalid_pheno)) {
3018 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' on chrY (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
3019 goto GlmMain_ret_INCONSISTENT_INPUT;
3020 }
3021 logerrprintfww("Warning: Skipping chrY in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", first_pheno_name);
3022 sample_ct_y = 0;
3023 #endif
3024 } else {
3025 for (uint32_t pheno_uidx2 = pheno_uidx; pheno_uidx2 != pheno_ct; ++pheno_uidx2) {
3026 if (!IsSet(pheno_batch, pheno_uidx2)) {
3027 continue;
3028 }
3029 const PhenoCol* candidate_pheno_col = &(pheno_cols[pheno_uidx2]);
3030 if (IsConstCovar(candidate_pheno_col, cur_sample_include_y, raw_sample_ct)) {
3031 // Punt to single-phenotype-at-a-time handler.
3032 ClearBit(pheno_uidx2, pheno_batch);
3033 }
3034 }
3035 }
3036 if (sample_ct_y && common.tests_flag && (!common.constraint_ct_y)) {
3037 if (unlikely(!skip_invalid_pheno)) {
3038 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples on chrY for --glm phenotype '%s'.\n", first_pheno_name);
3039 goto GlmMain_ret_INCONSISTENT_INPUT;
3040 }
3041 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', and other(s) with identical missingness patterns, since --tests predictor(s) are constant for all remaining samples.\n", first_pheno_name);
3042 sample_ct_y = 0;
3043 }
3044 if (sample_ct_y && (covar_ct_y < initial_y_covar_ct)) {
3045 uintptr_t covar_uidx_base = 0;
3046 uintptr_t cur_bits = initial_covar_include[0];
3047 for (uint32_t covar_idx = 0; covar_idx != covar_ct_y; ++covar_idx) {
3048 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
3049 if (!IsSet(covar_include_y, covar_uidx)) {
3050 logerrprintfww("Warning: On chrY, not including covariate '%s' in --glm regression on phenotype '%s', and other(s) with identical missingness patterns.\n", &(covar_names[covar_uidx * max_covar_name_blen]), first_pheno_name);
3051 }
3052 }
3053 }
3054 }
3055 }
3056 }
3057
3058 batch_size = PopcountWords(pheno_batch, pheno_ctl);
3059 if (batch_size <= 1) {
3060 continue;
3061 }
3062
3063 // Expand categorical covariates and perform VIF and correlation checks
3064 // here.
3065 const char** cur_covar_names = nullptr;
3066 GlmErr glm_err;
3067 {
3068 double* covars_cmaj_d = nullptr;
3069 if (unlikely(GlmAllocFillAndTestCovarsQt(cur_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, common.max_corr, vif_thresh, xtx_state, &common.nm_precomp, &covars_cmaj_d, &cur_covar_names, &glm_err))) {
3070 goto GlmMain_ret_NOMEM;
3071 }
3072 linear_ctx.covars_cmaj_d = covars_cmaj_d;
3073 if (glm_err) {
3074 PrintPrescanErrmsg("", first_pheno_name, cur_covar_names, glm_err, local_covar_ct, skip_invalid_pheno, 1);
3075 if (unlikely(!skip_invalid_pheno)) {
3076 goto GlmMain_ret_INCONSISTENT_INPUT;
3077 }
3078 BitvecInvmask(pheno_batch, pheno_ctl, pheno_include);
3079 continue;
3080 }
3081 }
3082 const char** cur_covar_names_x = nullptr;
3083 common.nm_precomp_x = nullptr;
3084 linear_ctx.covars_cmaj_x_d = nullptr;
3085 if (sample_ct_x) {
3086 double* covars_cmaj_d = nullptr;
3087 if (unlikely(GlmAllocFillAndTestCovarsQt(cur_sample_include_x, covar_include_x, covar_cols, covar_names, sample_ct_x, covar_ct_x, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_x, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, &common.nm_precomp_x, &covars_cmaj_d, &cur_covar_names_x, &glm_err))) {
3088 goto GlmMain_ret_NOMEM;
3089 }
3090 linear_ctx.covars_cmaj_x_d = covars_cmaj_d;
3091 if (glm_err) {
3092 PrintPrescanErrmsg("chrX in ", first_pheno_name, cur_covar_names_x, glm_err, local_covar_ct, skip_invalid_pheno, 1);
3093 if (unlikely(!skip_invalid_pheno)) {
3094 goto GlmMain_ret_INCONSISTENT_INPUT;
3095 }
3096 sample_ct_x = 0;
3097 }
3098 }
3099 const char** cur_covar_names_y = nullptr;
3100 common.nm_precomp_y = nullptr;
3101 linear_ctx.covars_cmaj_y_d = nullptr;
3102 if (sample_ct_y) {
3103 double* covars_cmaj_d = nullptr;
3104 if (unlikely(GlmAllocFillAndTestCovarsQt(cur_sample_include_y, covar_include_y, covar_cols, covar_names, sample_ct_y, covar_ct_y, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_y, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, &common.nm_precomp_y, &covars_cmaj_d, &cur_covar_names_y, &glm_err))) {
3105 goto GlmMain_ret_NOMEM;
3106 }
3107 linear_ctx.covars_cmaj_y_d = covars_cmaj_d;
3108 if (glm_err) {
3109 PrintPrescanErrmsg("chrY in ", first_pheno_name, cur_covar_names_y, glm_err, local_covar_ct, skip_invalid_pheno, 1);
3110 if (unlikely(!skip_invalid_pheno)) {
3111 goto GlmMain_ret_INCONSISTENT_INPUT;
3112 }
3113 sample_ct_y = 0;
3114 }
3115 }
3116
3117 const char** cur_test_names = nullptr;
3118 const char** cur_test_names_x = nullptr;
3119 const char** cur_test_names_y = nullptr;
3120 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset, cur_covar_names, glm_flags, covar_ct + extra_cat_ct, common.tests_flag? common.constraint_ct : 0, &cur_test_names))) {
3121 goto GlmMain_ret_NOMEM;
3122 }
3123 if (sample_ct_x) {
3124 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset_x, cur_covar_names_x, glm_flags, covar_ct_x + extra_cat_ct_x, common.tests_flag? common.constraint_ct_x : 0, &cur_test_names_x))) {
3125 goto GlmMain_ret_NOMEM;
3126 }
3127 }
3128 if (sample_ct_y) {
3129 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset_y, cur_covar_names_y, glm_flags, covar_ct_y + extra_cat_ct_y, common.tests_flag? common.constraint_ct_y : 0, &cur_test_names_y))) {
3130 goto GlmMain_ret_NOMEM;
3131 }
3132 }
3133
3134 const uintptr_t* cur_variant_include = early_variant_include;
3135 const uintptr_t* cur_local_variant_include = local_variant_include;
3136 const uint32_t skip_x = variant_ct_x && ((!xchr_model) || (cur_sample_include_x && (!sample_ct_x)));
3137 const uint32_t skip_y = variant_ct_y && ((!male_ct) || (cur_sample_include_y && (!sample_ct_y)));
3138 uint32_t cur_variant_ct = variant_ct;
3139 if (skip_x || skip_y) {
3140 uintptr_t* tmp_variant_include;
3141 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &tmp_variant_include))) {
3142 goto GlmMain_ret_NOMEM;
3143 }
3144 memcpy(tmp_variant_include, early_variant_include, raw_variant_ctl * sizeof(intptr_t));
3145 uintptr_t* tmp_local_variant_include = nullptr;
3146 if (local_variant_include) {
3147 if (unlikely(bigstack_alloc_w(local_variant_ctl, &tmp_local_variant_include))) {
3148 goto GlmMain_ret_NOMEM;
3149 }
3150 memcpy(tmp_local_variant_include, local_variant_include, local_variant_ctl * sizeof(intptr_t));
3151 }
3152 if (skip_x) {
3153 if (local_variant_include) {
3154 const uint32_t variant_ct_before_x = PopcountBitRange(early_variant_include, 0, x_start);
3155 uint32_t local_uidx_first = IdxToUidxBasic(local_variant_include, variant_ct_before_x);
3156 uint32_t local_uidx_last = FindNth1BitFrom(local_variant_include, local_uidx_first, variant_ct_x);
3157 ClearBitsNz(local_uidx_first, local_uidx_last + 1, tmp_local_variant_include);
3158 }
3159 ClearBitsNz(x_start, x_end, tmp_variant_include);
3160 cur_variant_ct -= variant_ct_x;
3161 }
3162 if (skip_y) {
3163 if (local_variant_include) {
3164 const uint32_t variant_ct_before_y = PopcountBitRange(early_variant_include, 0, y_start);
3165 uint32_t local_uidx_first = IdxToUidxBasic(local_variant_include, variant_ct_before_y);
3166 uint32_t local_uidx_last = FindNth1BitFrom(local_variant_include, local_uidx_first, variant_ct_y);
3167 ClearBitsNz(local_uidx_first, local_uidx_last + 1, tmp_local_variant_include);
3168 }
3169 ClearBitsNz(y_start, y_end, tmp_variant_include);
3170 cur_variant_ct -= variant_ct_y;
3171 }
3172 cur_variant_include = tmp_variant_include;
3173 cur_local_variant_include = tmp_local_variant_include;
3174 }
3175 if (sex_male_collapsed_buf && (!skip_x)) {
3176 if (!cur_sample_include_x) {
3177 CopyBitarrSubset(sex_male, cur_sample_include, sample_ct, sex_male_collapsed_buf);
3178 } else {
3179 CopyBitarrSubset(sex_male, cur_sample_include_x, sample_ct_x, sex_male_collapsed_buf);
3180 }
3181 }
3182 FillCumulativePopcounts(cur_sample_include, raw_sample_ctl, common.sample_include_cumulative_popcounts);
3183 common.sample_ct = sample_ct;
3184 common.sample_ct_x = sample_ct_x;
3185 common.covar_ct = covar_ct + extra_cat_ct;
3186 common.local_covar_ct = local_covar_ct;
3187 if (sample_ct_x) {
3188 uint32_t* cumulative_popcounts;
3189 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) {
3190 goto GlmMain_ret_NOMEM;
3191 }
3192 FillCumulativePopcounts(cur_sample_include_x, raw_sample_ctl, cumulative_popcounts);
3193 common.sample_include_x_cumulative_popcounts = cumulative_popcounts;
3194 common.sample_include_x = cur_sample_include_x;
3195 common.covar_ct_x = covar_ct_x + extra_cat_ct_x;
3196 // common.male_ct = PopcountWordsIntersect(cur_sample_include_x, sex_male, raw_sample_ctl);
3197 } else {
3198 // technically only need this if variant_ct_x && (!skip_x)
3199 // common.male_ct = PopcountWordsIntersect(cur_sample_include, sex_male, raw_sample_ctl);
3200
3201 // defensive
3202 common.sample_include_x = nullptr;
3203 common.sample_include_x_cumulative_popcounts = nullptr;
3204 common.covar_ct_x = 0;
3205 }
3206 common.sample_ct_y = sample_ct_y;
3207 if (sample_ct_y) {
3208 uint32_t* cumulative_popcounts;
3209 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) {
3210 goto GlmMain_ret_NOMEM;
3211 }
3212 FillCumulativePopcounts(cur_sample_include_y, raw_sample_ctl, cumulative_popcounts);
3213 common.sample_include_y_cumulative_popcounts = cumulative_popcounts;
3214 common.sample_include_y = cur_sample_include_y;
3215 common.covar_ct_y = covar_ct_y + extra_cat_ct_y;
3216 } else {
3217 common.sample_include_y = nullptr;
3218 common.sample_include_y_cumulative_popcounts = nullptr;
3219 common.covar_ct_y = 0;
3220 }
3221 linear_ctx.max_returned_difflist_len = 0;
3222 if ((is_qt_residualize || (!common.covar_ct) || (sample_ct_y && (!common.covar_ct_y))) && common.nm_precomp && (!(pgfip->gflags & kfPgenGlobalDosagePresent))) {
3223 linear_ctx.max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
3224 }
3225
3226 uint32_t* subset_chr_fo_vidx_start;
3227 if (unlikely(AllocAndFillSubsetChrFoVidxStart(cur_variant_include, cip, &subset_chr_fo_vidx_start))) {
3228 goto GlmMain_ret_NOMEM;
3229 }
3230 common.subset_chr_fo_vidx_start = subset_chr_fo_vidx_start;
3231 common.variant_include = cur_variant_include;
3232 common.variant_ct = cur_variant_ct;
3233
3234 if (glm_flags & kfGlmPhenoIds) {
3235 // Possible todo: have file-copy library function which uses
3236 // sendfile() with Linux kernel 2.6.33+, etc.
3237 uint32_t pheno_uidx2 = 0;
3238 for (uint32_t pheno_idx = 0; pheno_idx != batch_size; ++pheno_idx, ++pheno_uidx2) {
3239 pheno_uidx2 = AdvTo1Bit(pheno_batch, pheno_uidx2);
3240 char* outname_end2 = strcpya(&(outname_end[1]), &(pheno_names[pheno_uidx2 * max_pheno_name_blen]));
3241 outname_end2 = strcpya_k(outname_end2, ".glm.linear");
3242 strcpy_k(outname_end2, ".id");
3243 reterr = WriteSampleIds(cur_sample_include, siip, outname, sample_ct);
3244 if (unlikely(reterr)) {
3245 goto GlmMain_ret_1;
3246 }
3247 if (sample_ct_x && x_samples_are_different) {
3248 strcpy_k(outname_end2, ".x.id");
3249 reterr = WriteSampleIds(cur_sample_include_x, siip, outname, sample_ct_x);
3250 if (unlikely(reterr)) {
3251 goto GlmMain_ret_1;
3252 }
3253 }
3254 if (sample_ct_y && y_samples_are_different) {
3255 strcpy_k(outname_end2, ".y.id");
3256 reterr = WriteSampleIds(cur_sample_include_y, siip, outname, sample_ct_y);
3257 if (unlikely(reterr)) {
3258 goto GlmMain_ret_1;
3259 }
3260 }
3261 }
3262 }
3263 reterr = GlmLinearBatch(pheno_batch, pheno_cols, pheno_names, cur_test_names, cur_test_names_x, cur_test_names_y, glm_pos_col? variant_bps : nullptr, variant_ids, allele_storage, glm_info_ptr, local_sample_uidx_order, cur_local_variant_include, raw_variant_ct, completed_pheno_ct, batch_size, max_pheno_name_blen, max_chr_blen, ci_size, ln_pfilter, output_min_ln, max_thread_ct, pgr_alloc_cacheline_ct, overflow_buf_size, local_sample_ct, pgfip, &linear_ctx, &local_covar_txs, gwas_ssf_ll_ptr, outname, outname_end);
3264 if (unlikely(reterr)) {
3265 goto GlmMain_ret_1;
3266 }
3267 completed_pheno_ct += batch_size;
3268 BitvecInvmask(pheno_batch, pheno_ctl, pheno_include);
3269 }
3270 for (uint32_t pheno_uidx = 0; pheno_uidx != pheno_ct; ++pheno_uidx) {
3271 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
3272 const PhenoDtype dtype_code = cur_pheno_col->type_code;
3273 if (dtype_code != kPhenoDtypeQt) {
3274 SetBit(pheno_uidx, pheno_include);
3275 }
3276 }
3277 }
3278
3279 for (uint32_t pheno_uidx = 0; pheno_uidx != pheno_ct; ++pheno_uidx) {
3280 if (!IsSet(pheno_include, pheno_uidx)) {
3281 continue;
3282 }
3283 const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]);
3284 const PhenoDtype dtype_code = cur_pheno_col->type_code;
3285 const char* cur_pheno_name = &(pheno_names[pheno_uidx * max_pheno_name_blen]);
3286 if (dtype_code == kPhenoDtypeCat) {
3287 // todo: check if there are only two categories after linear-style
3288 // covariate QC, and automatically use ordinary logistic regression in
3289 // that case? (need to indicate which category is treated as 'case'
3290 // and which is 'control'...)
3291 // longer-term todo: multinomial logistic regression?
3292 logprintfww("--glm: Skipping categorical phenotype '%s'.\n", cur_pheno_name);
3293 continue;
3294 }
3295
3296 BitvecAndCopy(orig_sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include);
3297 const uint32_t is_logistic = (dtype_code == kPhenoDtypeCc);
3298 uint32_t sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
3299 if (is_logistic) {
3300 const uint32_t initial_case_ct = PopcountWordsIntersect(cur_sample_include, cur_pheno_col->data.cc, raw_sample_ctl);
3301 if ((!initial_case_ct) || (initial_case_ct == sample_ct)) {
3302 if (unlikely(!skip_invalid_pheno)) {
3303 logerrprintfww("Error: All samples for --glm phenotype '%s' are %s.\n", cur_pheno_name, initial_case_ct? "cases" : "controls");
3304 goto GlmMain_ret_INCONSISTENT_INPUT;
3305 }
3306 logprintfww("--glm: Skipping case/control phenotype '%s' since all samples are %s.\n", cur_pheno_name, initial_case_ct? "cases" : "controls");
3307 continue;
3308 }
3309 } else {
3310 if (IsConstCovar(cur_pheno_col, cur_sample_include, raw_sample_ct)) {
3311 if (unlikely(!skip_invalid_pheno)) {
3312 logerrprintfww("Error: --glm quantitative phenotype '%s' is constant.\n", cur_pheno_name);
3313 goto GlmMain_ret_INCONSISTENT_INPUT;
3314 }
3315 logprintfww("--glm: Skipping constant quantitative phenotype '%s'.\n", cur_pheno_name);
3316 continue;
3317 }
3318 }
3319 uint32_t covar_ct = 0;
3320 uint32_t extra_cat_ct = 0;
3321 logistic_ctx.separation_found = 0;
3322 BigstackDoubleReset(bigstack_mark2, bigstack_end_mark);
3323 if (initial_nonx_covar_ct) {
3324 if (unlikely(GlmDetermineCovars(is_logistic? cur_pheno_col->data.cc : nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_nonx_covar_ct, covar_max_nonnull_cat_ct, is_sometimes_firth, is_always_firth, cur_sample_include, covar_include, &sample_ct, &covar_ct, &extra_cat_ct, &logistic_ctx.separation_found))) {
3325 goto GlmMain_ret_NOMEM;
3326 }
3327 }
3328 uint32_t biallelic_predictor_ct = 2 + domdev_present + (covar_ct + extra_cat_ct) * (1 + add_interactions * domdev_present_p1);
3329 if (raw_parameter_subset) {
3330 biallelic_predictor_ct = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct, add_interactions, common.parameter_subset);
3331 }
3332 if (raw_joint_test_params) {
3333 common.constraint_ct = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct, add_interactions, common.joint_test_params);
3334 if (raw_parameter_subset) {
3335 // bugfix (2 Feb 2019): forgot to properly take --parameters into
3336 // account
3337 memcpy(joint_test_params_buf, common.joint_test_params, biallelic_raw_predictor_ctl * sizeof(intptr_t));
3338 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params);
3339 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset, biallelic_predictor_ct, common.joint_test_params);
3340 }
3341 }
3342 if (sample_ct <= biallelic_predictor_ct) {
3343 if (unlikely(!skip_invalid_pheno)) {
3344 if ((!is_sometimes_firth) && logistic_ctx.separation_found) {
3345 logerrprintfww("Error: (Quasi-)separated covariate(s) were present for --glm phenotype '%s'. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3346 } else {
3347 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s'.\n", cur_pheno_name);
3348 }
3349 goto GlmMain_ret_INCONSISTENT_INPUT;
3350 }
3351 if ((!is_sometimes_firth) && logistic_ctx.separation_found) {
3352 logerrprintfww("Warning: Skipping --glm regression on phenotype '%s' since (quasi-)separated covariate(s) were present. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3353 } else {
3354 logprintfww("Note: Skipping --glm regression on phenotype '%s' since # samples <= # predictor columns.\n", cur_pheno_name);
3355 }
3356 continue;
3357 }
3358 #ifdef __LP64__
3359 if (RoundUpPow2(sample_ct, 4) * S_CAST(uint64_t, biallelic_predictor_ct + max_extra_allele_ct) > 0x7fffffff) {
3360 // todo: remove this constraint in LAPACK_ILP64 case?
3361 if (unlikely(!skip_invalid_pheno)) {
3362 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3363 goto GlmMain_ret_INCONSISTENT_INPUT;
3364 }
3365 logprintfww("Note: Skipping --glm regression on phenotype '%s' since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3366 continue;
3367 }
3368 #endif
3369 uint32_t case_ct = 0;
3370 if (is_logistic) {
3371 case_ct = PopcountWordsIntersect(cur_sample_include, cur_pheno_col->data.cc, raw_sample_ctl);
3372 if ((!case_ct) || (case_ct == sample_ct)) {
3373 if (unlikely(!skip_invalid_pheno)) {
3374 logerrprintfww("Error: All remaining samples for --glm phenotype '%s' are %s.\n", cur_pheno_name, case_ct? "cases" : "controls");
3375 goto GlmMain_ret_INCONSISTENT_INPUT;
3376 }
3377 logprintfww("--glm: Skipping case/control phenotype '%s' since all remaining samples are %s.\n", cur_pheno_name, case_ct? "cases" : "controls");
3378 // without any e.g. cases in the dataset, every single covariate
3379 // should fail the separation check, so covar_ct should be zero here
3380 assert(!covar_ct);
3381 continue;
3382 }
3383 // quasi-bugfix (4 Jun 2018): "one in ten" rule of thumb applies to
3384 // minimum of case and control counts, not total sample count
3385 if (MINV(case_ct, sample_ct - case_ct) < 10 * biallelic_predictor_ct) {
3386 if (case_ct * 2 < sample_ct) {
3387 logerrprintfww("Warning: --glm remaining case count is less than 10x predictor count for phenotype '%s'.\n", cur_pheno_name);
3388 } else {
3389 logerrprintfww("Warning: --glm remaining control count is less than 10x predictor count for phenotype '%s'.\n", cur_pheno_name);
3390 }
3391 }
3392 } else {
3393 // verify phenotype is still nonconstant
3394 if (IsConstCovar(cur_pheno_col, cur_sample_include, raw_sample_ct)) {
3395 if (unlikely(!skip_invalid_pheno)) {
3396 logerrprintfww("Error: --glm quantitative phenotype '%s' is constant for all remaining samples.\n", cur_pheno_name);
3397 goto GlmMain_ret_INCONSISTENT_INPUT;
3398 }
3399 logprintfww("--glm: Skipping quantitative phenotype '%s' since phenotype is constant for all remaining samples.\n", cur_pheno_name);
3400 continue;
3401 }
3402 }
3403 if (common.tests_flag && (!common.constraint_ct)) {
3404 if (unlikely(!skip_invalid_pheno)) {
3405 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples for --glm phenotype '%s'.\n", cur_pheno_name);
3406 goto GlmMain_ret_INCONSISTENT_INPUT;
3407 }
3408 logprintfww("Note: Skipping --glm regression on phenotype '%s' since --tests predictor(s) are constant for all remaining samples.\n", cur_pheno_name);
3409 continue;
3410 }
3411 if (covar_ct < initial_nonx_covar_ct) {
3412 uintptr_t covar_uidx_base = 0;
3413 uintptr_t cur_bits = initial_covar_include[0];
3414 for (uint32_t covar_idx = 0; covar_idx != initial_nonx_covar_ct; ++covar_idx) {
3415 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
3416 if (!IsSet(covar_include, covar_uidx)) {
3417 logerrprintfww("Warning: %sot including covariate '%s' in --glm regression on phenotype '%s'.\n", cur_sample_include_x_buf? (cur_sample_include_y_buf? "Outside of chrX, n" : "Outside of chrX and chrY, n") : (cur_sample_include_y_buf? "Outside of chrY, n" : "N"), &(covar_names[covar_uidx * max_covar_name_blen]), cur_pheno_name);
3418 }
3419 }
3420 }
3421
3422 // cur_sample_include_x == nullptr: chrX uses same samples and covariates
3423 // as the rest of the genome. sample_ct_x always zero to force most
3424 // chrX-specific initialization to be skipped (exception:
3425 // sex_male_collapsed, needed for allele count/freq reporting)
3426 // cur_sample_include_x non-null: if sample_ct_x == 0, we skip the entire
3427 // chromosome. otherwise, we have different covariates than the rest
3428 // of the genome.
3429 uintptr_t* cur_sample_include_x = cur_sample_include_x_buf;
3430 uint32_t sample_ct_x = 0;
3431 uint32_t covar_ct_x = 0;
3432 uint32_t extra_cat_ct_x = 0;
3433 uint32_t biallelic_predictor_ct_x = 0;
3434 uint32_t x_samples_are_different = 0;
3435 if (cur_sample_include_x) {
3436 BitvecAndCopy(orig_sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include_x);
3437 logistic_ctx.separation_found_x = 0;
3438 if (unlikely(GlmDetermineCovars(is_logistic? cur_pheno_col->data.cc : nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_nonx_covar_ct + 1, covar_max_nonnull_cat_ct, is_sometimes_firth, is_always_firth, cur_sample_include_x, covar_include_x, &sample_ct_x, &covar_ct_x, &extra_cat_ct_x, &logistic_ctx.separation_found_x))) {
3439 goto GlmMain_ret_NOMEM;
3440 }
3441 x_samples_are_different = (sample_ct_x != sample_ct) || (!wordsequal(cur_sample_include, cur_sample_include_x, raw_sample_ctl));
3442 if ((!x_samples_are_different) && (covar_ct == covar_ct_x) && wordsequal(covar_include, covar_include_x, raw_covar_ctl)) {
3443 logprintfww("Note: chrX samples and covariate(s) in --glm regression on phenotype '%s' are the same as that for the rest of the genome.\n", cur_pheno_name);
3444 sample_ct_x = 0;
3445 cur_sample_include_x = nullptr;
3446 } else {
3447 if (!sample_ct_x) {
3448 if (unlikely(!skip_invalid_pheno)) {
3449 logerrprintfww("Error: --glm regression on phenotype '%s' is degenerate on chrX.\n", cur_pheno_name);
3450 goto GlmMain_ret_INCONSISTENT_INPUT;
3451 }
3452 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s'.\n", cur_pheno_name);
3453 } else {
3454 biallelic_predictor_ct_x = 2 + domdev_present + (covar_ct_x + extra_cat_ct_x) * (1 + add_interactions * domdev_present_p1);
3455 if (raw_parameter_subset) {
3456 biallelic_predictor_ct_x = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct_x, add_interactions, common.parameter_subset_x);
3457 }
3458 if (raw_joint_test_params) {
3459 common.constraint_ct_x = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct_x, add_interactions, common.joint_test_params_x);
3460 if (raw_parameter_subset) {
3461 memcpy(joint_test_params_buf, common.joint_test_params_x, biallelic_raw_predictor_ctl * sizeof(intptr_t));
3462 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params_x);
3463 // bugfix (14 Sep 2020): forgot to use parameter_subset_x
3464 // instead of parameter_subset here
3465 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset_x, biallelic_predictor_ct_x, common.joint_test_params_x);
3466 }
3467 }
3468 if (sample_ct_x <= biallelic_predictor_ct_x) {
3469 if (unlikely(!skip_invalid_pheno)) {
3470 if ((!is_sometimes_firth) && logistic_ctx.separation_found_x) {
3471 logerrprintfww("Error: (Quasi-)separated covariate(s) were present for --glm phenotype '%s' on chrX. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3472 } else {
3473 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s' on chrX.\n", cur_pheno_name);
3474 }
3475 goto GlmMain_ret_INCONSISTENT_INPUT;
3476 }
3477 if ((!is_sometimes_firth) && logistic_ctx.separation_found_x) {
3478 logerrprintfww("Warning: Skipping --glm regression on phenotype '%s' on chrX, since (quasi-)separated covariate(s) were present. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3479 } else {
3480 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', since # remaining samples <= # predictor columns.\n", cur_pheno_name);
3481 }
3482 sample_ct_x = 0;
3483 #ifdef __LP64__
3484 } else if (RoundUpPow2(sample_ct_x, 4) * S_CAST(uint64_t, biallelic_predictor_ct_x + max_extra_allele_ct) > 0x7fffffff) {
3485 if (unlikely(!skip_invalid_pheno)) {
3486 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' on chrX (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3487 goto GlmMain_ret_INCONSISTENT_INPUT;
3488 }
3489 logerrprintfww("Warning: Skipping chrX in --glm regression on phenotype '%s', since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3490 sample_ct_x = 0;
3491 #endif
3492 } else if (is_logistic) {
3493 const uint32_t case_ct_x = PopcountWordsIntersect(cur_sample_include_x, cur_pheno_col->data.cc, raw_sample_ctl);
3494 if ((!case_ct_x) || (case_ct_x == sample_ct_x)) {
3495 if (unlikely(!skip_invalid_pheno)) {
3496 logerrprintfww("Error: All remaining samples on chrX for --glm phenotype '%s' are %s.\n", cur_pheno_name, case_ct? "cases" : "controls");
3497 goto GlmMain_ret_INCONSISTENT_INPUT;
3498 }
3499 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', since all remaining samples are %s.\n", cur_pheno_name, case_ct_x? "cases" : "controls");
3500 sample_ct_x = 0;
3501 }
3502 } else {
3503 if (IsConstCovar(cur_pheno_col, cur_sample_include_x, raw_sample_ct)) {
3504 if (unlikely(!skip_invalid_pheno)) {
3505 logerrprintfww("Error: --glm quantitative phenotype '%s' is constant for all remaining samples on chrX.\n", cur_pheno_name);
3506 goto GlmMain_ret_INCONSISTENT_INPUT;
3507 }
3508 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', since phenotype is constant for all remaining samples.\n", cur_pheno_name);
3509 sample_ct_x = 0;
3510 }
3511 }
3512 if (sample_ct_x && common.tests_flag && (!common.constraint_ct_x)) {
3513 if (unlikely(!skip_invalid_pheno)) {
3514 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples on chrX for --glm phenotype '%s'.\n", cur_pheno_name);
3515 goto GlmMain_ret_INCONSISTENT_INPUT;
3516 }
3517 logprintfww("Note: Skipping chrX in --glm regression on phenotype '%s', since --tests predictor(s) are constant for all remaining samples.\n", cur_pheno_name);
3518 sample_ct_x = 0;
3519 }
3520 if (sample_ct_x && (covar_ct_x < initial_nonx_covar_ct + 1)) {
3521 uintptr_t covar_uidx_base = 0;
3522 uintptr_t cur_bits = initial_covar_include[0];
3523 for (uint32_t covar_idx = 0; covar_idx != covar_ct_x; ++covar_idx) {
3524 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
3525 if (!IsSet(covar_include_x, covar_uidx)) {
3526 logerrprintfww("Warning: On chrX, not including covariate '%s' in --glm regression on phenotype '%s'.\n", &(covar_names[covar_uidx * max_covar_name_blen]), cur_pheno_name);
3527 }
3528 }
3529 }
3530 }
3531 }
3532 }
3533
3534 uintptr_t* cur_sample_include_y = cur_sample_include_y_buf;
3535 uint32_t sample_ct_y = 0;
3536 uint32_t covar_ct_y = 0;
3537 uint32_t extra_cat_ct_y = 0;
3538 uint32_t biallelic_predictor_ct_y = 0;
3539 uint32_t y_samples_are_different = 0;
3540 if (cur_sample_include_y) {
3541 BitvecAndCopy(orig_sample_include, sex_nonfemale, raw_sample_ctl, cur_sample_include_y);
3542 BitvecAnd(cur_pheno_col->nonmiss, raw_sample_ctl, cur_sample_include_y);
3543 logistic_ctx.separation_found_y = 0;
3544 if (unlikely(GlmDetermineCovars(is_logistic? cur_pheno_col->data.cc : nullptr, initial_covar_include, covar_cols, raw_sample_ct, raw_covar_ctl, initial_y_covar_ct, covar_max_nonnull_cat_ct, is_sometimes_firth, is_always_firth, cur_sample_include_y, covar_include_y, &sample_ct_y, &covar_ct_y, &extra_cat_ct_y, &logistic_ctx.separation_found_y))) {
3545 goto GlmMain_ret_NOMEM;
3546 }
3547 y_samples_are_different = (sample_ct_y != sample_ct) || (!wordsequal(cur_sample_include, cur_sample_include_y, raw_sample_ctl));
3548 if ((!y_samples_are_different) && (covar_ct == covar_ct_y) && wordsequal(covar_include, covar_include_y, raw_covar_ctl)) {
3549 logprintfww("Note: chrY samples and covariate(s) in --glm regression on phenotype '%s' are the same as that for the rest of the genome.\n", cur_pheno_name);
3550 sample_ct_y = 0;
3551 cur_sample_include_y = nullptr;
3552 } else {
3553 if (!sample_ct_y) {
3554 if (unlikely(!skip_invalid_pheno)) {
3555 logerrprintfww("Error: --glm regression on phenotype '%s' is degenerate on chrY.\n", cur_pheno_name);
3556 goto GlmMain_ret_INCONSISTENT_INPUT;
3557 }
3558 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s'.\n", cur_pheno_name);
3559 } else {
3560 biallelic_predictor_ct_y = 2 + domdev_present + (covar_ct_y + extra_cat_ct_y) * (1 + add_interactions * domdev_present_p1);
3561 if (raw_parameter_subset) {
3562 biallelic_predictor_ct_y = CollapseParamOrTestSubset(covar_include, raw_parameter_subset, domdev_present, raw_covar_ct, covar_ct_y, add_interactions, common.parameter_subset_y);
3563 }
3564 if (raw_joint_test_params) {
3565 assert(common.tests_flag);
3566 common.constraint_ct_y = CollapseParamOrTestSubset(covar_include, raw_joint_test_params, domdev_present, raw_covar_ct, covar_ct_y, add_interactions, common.joint_test_params_y);
3567 if (raw_parameter_subset) {
3568 memcpy(joint_test_params_buf, common.joint_test_params_y, biallelic_raw_predictor_ctl * sizeof(intptr_t));
3569 ZeroWArr(biallelic_raw_predictor_ctl, common.joint_test_params_y);
3570 CopyBitarrSubset(joint_test_params_buf, common.parameter_subset_y, biallelic_predictor_ct_y, common.joint_test_params_y);
3571 }
3572 }
3573 if (sample_ct_y <= biallelic_predictor_ct_y) {
3574 if (unlikely(!skip_invalid_pheno)) {
3575 if ((!is_sometimes_firth) && logistic_ctx.separation_found_x) {
3576 logerrprintfww("Error: (Quasi-)separated covariate(s) were present for --glm phenotype '%s' on chrY. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3577 } else {
3578 logerrprintfww("Error: # samples <= # predictor columns for --glm phenotype '%s' on chrY.\n", cur_pheno_name);
3579 }
3580 goto GlmMain_ret_INCONSISTENT_INPUT;
3581 }
3582 if ((!is_sometimes_firth) && logistic_ctx.separation_found_x) {
3583 logerrprintfww("Warning: Skipping --glm regression on phenotype '%s' on chrY, since (quasi-)separated covariate(s) were present. Try removing inappropriate covariates, and/or using Firth logistic regression.\n", cur_pheno_name);
3584 } else {
3585 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', since # remaining samples <= # predictor columns.\n", cur_pheno_name);
3586 }
3587 sample_ct_y = 0;
3588 #ifdef __LP64__
3589 } else if (RoundUpPow2(sample_ct_y, 4) * S_CAST(uint64_t, biallelic_predictor_ct_y + max_extra_allele_ct) > 0x7fffffff) {
3590 if (unlikely(!skip_invalid_pheno)) {
3591 logerrprintfww("Error: Too many samples or predictors for --glm regression on phenotype '%s' on chrY (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3592 goto GlmMain_ret_INCONSISTENT_INPUT;
3593 }
3594 logerrprintfww("Warning: Skipping chrY in --glm regression on phenotype '%s', since there are too many samples or predictors (internal matrices currently limited to ~2^31 entries).\n", cur_pheno_name);
3595 sample_ct_y = 0;
3596 #endif
3597 } else if (is_logistic) {
3598 const uint32_t case_ct_y = PopcountWordsIntersect(cur_sample_include_y, cur_pheno_col->data.cc, raw_sample_ctl);
3599 if ((!case_ct_y) || (case_ct_y == sample_ct_y)) {
3600 if (unlikely(!skip_invalid_pheno)) {
3601 logerrprintfww("Error: All remaining samples on chrY for --glm phenotype '%s' are %s.\n", cur_pheno_name, case_ct? "cases" : "controls");
3602 goto GlmMain_ret_INCONSISTENT_INPUT;
3603 }
3604 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', since all remaining samples are %s.\n", cur_pheno_name, case_ct_y? "cases" : "controls");
3605 sample_ct_y = 0;
3606 }
3607 } else {
3608 if (IsConstCovar(cur_pheno_col, cur_sample_include_y, raw_sample_ct)) {
3609 if (unlikely(!skip_invalid_pheno)) {
3610 logerrprintfww("Error: --glm quantitative phenotype '%s' is constant for all remaining samples on chrY.\n", cur_pheno_name);
3611 goto GlmMain_ret_INCONSISTENT_INPUT;
3612 }
3613 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', since phenotype is constant for all remaining samples.\n", cur_pheno_name);
3614 sample_ct_y = 0;
3615 }
3616 }
3617 if (sample_ct_y && common.tests_flag && (!common.constraint_ct_y)) {
3618 if (unlikely(!skip_invalid_pheno)) {
3619 logerrprintfww("Error: --tests predictor(s) are constant for all remaining samples on chrY for --glm phenotype '%s'.\n", cur_pheno_name);
3620 goto GlmMain_ret_INCONSISTENT_INPUT;
3621 }
3622 logprintfww("Note: Skipping chrY in --glm regression on phenotype '%s', since --tests predictor(s) are constant for all remaining samples.\n", cur_pheno_name);
3623 sample_ct_y = 0;
3624 }
3625 if (sample_ct_y && (covar_ct_y < initial_y_covar_ct)) {
3626 uintptr_t covar_uidx_base = 0;
3627 uintptr_t cur_bits = initial_covar_include[0];
3628 for (uint32_t covar_idx = 0; covar_idx != covar_ct_y; ++covar_idx) {
3629 const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
3630 if (!IsSet(covar_include_y, covar_uidx)) {
3631 logerrprintfww("Warning: On chrY, not including covariate '%s' in --glm regression on phenotype '%s'.\n", &(covar_names[covar_uidx * max_covar_name_blen]), cur_pheno_name);
3632 }
3633 }
3634 }
3635 }
3636 }
3637 }
3638
3639 // Expand categorical covariates and perform VIF and correlation checks
3640 // here.
3641 const char** cur_covar_names = nullptr;
3642 GlmErr glm_err;
3643 logistic_ctx.pheno_cc = nullptr;
3644 logistic_ctx.gcount_case_interleaved_vec = nullptr;
3645 logistic_ctx.cc_residualize = nullptr;
3646 if (is_logistic) {
3647 linear_ctx.pheno_d = nullptr;
3648 linear_ctx.covars_cmaj_d = nullptr;
3649 float* pheno_f = nullptr;
3650 double* pheno_d = nullptr;
3651 float* covars_cmaj_f = nullptr;
3652 double* covars_cmaj_d = nullptr;
3653 if (unlikely(GlmAllocFillAndTestPhenoCovarsCc(cur_sample_include, cur_pheno_col->data.cc, covar_include, covar_cols, covar_names, sample_ct, domdev_present_p1, covar_ct, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, glm_flags, &logistic_ctx.pheno_cc, gcount_cc_col? (&logistic_ctx.gcount_case_interleaved_vec) : nullptr, &pheno_f, &pheno_d, &common.nm_precomp, &covars_cmaj_f, &covars_cmaj_d, &logistic_ctx.cc_residualize, &cur_covar_names, &glm_err))) {
3654 goto GlmMain_ret_NOMEM;
3655 }
3656 logistic_ctx.pheno_f = pheno_f;
3657 logistic_ctx.pheno_d = pheno_d;
3658 logistic_ctx.covars_cmaj_f = covars_cmaj_f;
3659 logistic_ctx.covars_cmaj_d = covars_cmaj_d;
3660 } else {
3661 logistic_ctx.pheno_f = nullptr;
3662 logistic_ctx.covars_cmaj_f = nullptr;
3663 logistic_ctx.pheno_d = nullptr;
3664 logistic_ctx.covars_cmaj_d = nullptr;
3665 double* pheno_d = nullptr;
3666 double* covars_cmaj_d = nullptr;
3667 if (unlikely(GlmAllocFillAndTestPhenoCovarsQt(cur_sample_include, cur_pheno_col->data.qt, covar_include, covar_cols, covar_names, sample_ct, is_qt_residualize, covar_ct, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, &pheno_d, &common.nm_precomp, &covars_cmaj_d, &cur_covar_names, &glm_err))) {
3668 goto GlmMain_ret_NOMEM;
3669 }
3670 linear_ctx.pheno_d = pheno_d;
3671 linear_ctx.covars_cmaj_d = covars_cmaj_d;
3672 }
3673 if (glm_err) {
3674 PrintPrescanErrmsg("", cur_pheno_name, cur_covar_names, glm_err, local_covar_ct, skip_invalid_pheno, 0);
3675 if (unlikely(!skip_invalid_pheno)) {
3676 goto GlmMain_ret_INCONSISTENT_INPUT;
3677 }
3678 continue;
3679 }
3680 const char** cur_covar_names_x = nullptr;
3681 common.nm_precomp_x = nullptr;
3682 logistic_ctx.pheno_x_cc = nullptr;
3683 logistic_ctx.gcount_case_interleaved_vec_x = nullptr;
3684 logistic_ctx.pheno_x_f = nullptr;
3685 logistic_ctx.covars_cmaj_x_f = nullptr;
3686 logistic_ctx.pheno_x_d = nullptr;
3687 logistic_ctx.covars_cmaj_x_d = nullptr;
3688 logistic_ctx.cc_residualize_x = nullptr;
3689 linear_ctx.pheno_x_d = nullptr;
3690 linear_ctx.covars_cmaj_x_d = nullptr;
3691 if (sample_ct_x) {
3692 if (is_logistic) {
3693 float* pheno_f = nullptr;
3694 double* pheno_d = nullptr;
3695 float* covars_cmaj_f = nullptr;
3696 double* covars_cmaj_d = nullptr;
3697 if (unlikely(GlmAllocFillAndTestPhenoCovarsCc(cur_sample_include_x, cur_pheno_col->data.cc, covar_include_x, covar_cols, covar_names, sample_ct_x, domdev_present_p1, covar_ct_x, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_x, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, glm_flags, &logistic_ctx.pheno_x_cc, gcount_cc_col? (&logistic_ctx.gcount_case_interleaved_vec_x) : nullptr, &pheno_f, &pheno_d, &common.nm_precomp_x, &covars_cmaj_f, &covars_cmaj_d, &logistic_ctx.cc_residualize_x, &cur_covar_names_x, &glm_err))) {
3698 goto GlmMain_ret_NOMEM;
3699 }
3700 logistic_ctx.pheno_x_f = pheno_f;
3701 logistic_ctx.pheno_x_d = pheno_d;
3702 logistic_ctx.covars_cmaj_x_f = covars_cmaj_f;
3703 logistic_ctx.covars_cmaj_x_d = covars_cmaj_d;
3704 } else {
3705 double* pheno_d = nullptr;
3706 double* covars_cmaj_d = nullptr;
3707 if (unlikely(GlmAllocFillAndTestPhenoCovarsQt(cur_sample_include_x, cur_pheno_col->data.qt, covar_include_x, covar_cols, covar_names, sample_ct_x, is_qt_residualize, covar_ct_x, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_x, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, &pheno_d, &common.nm_precomp_x, &covars_cmaj_d, &cur_covar_names_x, &glm_err))) {
3708 goto GlmMain_ret_NOMEM;
3709 }
3710 linear_ctx.pheno_x_d = pheno_d;
3711 linear_ctx.covars_cmaj_x_d = covars_cmaj_d;
3712 }
3713 if (glm_err) {
3714 PrintPrescanErrmsg("chrX in ", cur_pheno_name, cur_covar_names_x, glm_err, local_covar_ct, skip_invalid_pheno, 0);
3715 if (unlikely(!skip_invalid_pheno)) {
3716 goto GlmMain_ret_INCONSISTENT_INPUT;
3717 }
3718 sample_ct_x = 0;
3719 }
3720 }
3721 const char** cur_covar_names_y = nullptr;
3722 common.nm_precomp_y = nullptr;
3723 logistic_ctx.pheno_y_cc = nullptr;
3724 logistic_ctx.gcount_case_interleaved_vec_y = nullptr;
3725 logistic_ctx.pheno_y_f = nullptr;
3726 logistic_ctx.covars_cmaj_y_f = nullptr;
3727 logistic_ctx.pheno_y_d = nullptr;
3728 logistic_ctx.covars_cmaj_y_d = nullptr;
3729 logistic_ctx.cc_residualize_y = nullptr;
3730 linear_ctx.pheno_y_d = nullptr;
3731 linear_ctx.covars_cmaj_y_d = nullptr;
3732 if (sample_ct_y) {
3733 if (is_logistic) {
3734 float* pheno_f = nullptr;
3735 double* pheno_d = nullptr;
3736 float* covars_cmaj_f = nullptr;
3737 double* covars_cmaj_d = nullptr;
3738 if (unlikely(GlmAllocFillAndTestPhenoCovarsCc(cur_sample_include_y, cur_pheno_col->data.cc, covar_include_y, covar_cols, covar_names, sample_ct_y, domdev_present_p1, covar_ct_y, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_y, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, glm_flags, &logistic_ctx.pheno_y_cc, gcount_cc_col? (&logistic_ctx.gcount_case_interleaved_vec_y) : nullptr, &pheno_f, &pheno_d, &common.nm_precomp_y, &covars_cmaj_f, &covars_cmaj_d, &logistic_ctx.cc_residualize_y, &cur_covar_names_y, &glm_err))) {
3739 goto GlmMain_ret_NOMEM;
3740 }
3741 logistic_ctx.pheno_y_f = pheno_f;
3742 logistic_ctx.pheno_y_d = pheno_d;
3743 logistic_ctx.covars_cmaj_y_f = covars_cmaj_f;
3744 logistic_ctx.covars_cmaj_y_d = covars_cmaj_d;
3745 } else {
3746 double* pheno_d = nullptr;
3747 double* covars_cmaj_d = nullptr;
3748 if (unlikely(GlmAllocFillAndTestPhenoCovarsQt(cur_sample_include_y, cur_pheno_col->data.qt, covar_include_y, covar_cols, covar_names, sample_ct_y, is_qt_residualize, covar_ct_y, local_covar_ct, covar_max_nonnull_cat_ct, extra_cat_ct_y, max_covar_name_blen, common.max_corr, vif_thresh, xtx_state, &pheno_d, &common.nm_precomp_y, &covars_cmaj_d, &cur_covar_names_y, &glm_err))) {
3749 goto GlmMain_ret_NOMEM;
3750 }
3751 linear_ctx.pheno_y_d = pheno_d;
3752 linear_ctx.covars_cmaj_y_d = covars_cmaj_d;
3753 }
3754 if (glm_err) {
3755 PrintPrescanErrmsg("chrY in ", cur_pheno_name, cur_covar_names_y, glm_err, local_covar_ct, skip_invalid_pheno, 0);
3756 if (unlikely(!skip_invalid_pheno)) {
3757 goto GlmMain_ret_INCONSISTENT_INPUT;
3758 }
3759 sample_ct_y = 0;
3760 }
3761 }
3762 const char** cur_test_names = nullptr;
3763 const char** cur_test_names_x = nullptr;
3764 const char** cur_test_names_y = nullptr;
3765 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset, cur_covar_names, glm_flags, covar_ct + extra_cat_ct, common.tests_flag? common.constraint_ct : 0, &cur_test_names))) {
3766 goto GlmMain_ret_NOMEM;
3767 }
3768 if (sample_ct_x) {
3769 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset_x, cur_covar_names_x, glm_flags, covar_ct_x + extra_cat_ct_x, common.tests_flag? common.constraint_ct_x : 0, &cur_test_names_x))) {
3770 goto GlmMain_ret_NOMEM;
3771 }
3772 }
3773 if (sample_ct_y) {
3774 if (unlikely(AllocAndInitReportedTestNames(common.parameter_subset_y, cur_covar_names_y, glm_flags, covar_ct_y + extra_cat_ct_y, common.tests_flag? common.constraint_ct_y : 0, &cur_test_names_y))) {
3775 goto GlmMain_ret_NOMEM;
3776 }
3777 }
3778
3779 // okay, we know what variants we're running the regression on, and we've
3780 // done much of the necessary covariate preprocessing. now prepare to
3781 // launch GlmLogistic()/GlmLinear().
3782
3783 const uintptr_t* cur_variant_include = early_variant_include;
3784 const uintptr_t* cur_local_variant_include = local_variant_include;
3785 const uint32_t skip_x = variant_ct_x && ((!xchr_model) || (cur_sample_include_x && (!sample_ct_x)));
3786 const uint32_t skip_y = variant_ct_y && ((!male_ct) || (cur_sample_include_y && (!sample_ct_y)));
3787 uint32_t cur_variant_ct = variant_ct;
3788 if (skip_x || skip_y) {
3789 uintptr_t* tmp_variant_include;
3790 if (unlikely(bigstack_alloc_w(raw_variant_ctl, &tmp_variant_include))) {
3791 goto GlmMain_ret_NOMEM;
3792 }
3793 memcpy(tmp_variant_include, early_variant_include, raw_variant_ctl * sizeof(intptr_t));
3794 uintptr_t* tmp_local_variant_include = nullptr;
3795 if (local_variant_include) {
3796 if (unlikely(bigstack_alloc_w(local_variant_ctl, &tmp_local_variant_include))) {
3797 goto GlmMain_ret_NOMEM;
3798 }
3799 memcpy(tmp_local_variant_include, local_variant_include, local_variant_ctl * sizeof(intptr_t));
3800 }
3801 if (skip_x) {
3802 if (local_variant_include) {
3803 const uint32_t variant_ct_before_x = PopcountBitRange(early_variant_include, 0, x_start);
3804 uint32_t local_uidx_first = IdxToUidxBasic(local_variant_include, variant_ct_before_x);
3805 uint32_t local_uidx_last = FindNth1BitFrom(local_variant_include, local_uidx_first, variant_ct_x);
3806 ClearBitsNz(local_uidx_first, local_uidx_last + 1, tmp_local_variant_include);
3807 }
3808 ClearBitsNz(x_start, x_end, tmp_variant_include);
3809 cur_variant_ct -= variant_ct_x;
3810 }
3811 if (skip_y) {
3812 if (local_variant_include) {
3813 const uint32_t variant_ct_before_y = PopcountBitRange(early_variant_include, 0, y_start);
3814 uint32_t local_uidx_first = IdxToUidxBasic(local_variant_include, variant_ct_before_y);
3815 uint32_t local_uidx_last = FindNth1BitFrom(local_variant_include, local_uidx_first, variant_ct_y);
3816 ClearBitsNz(local_uidx_first, local_uidx_last + 1, tmp_local_variant_include);
3817 }
3818 ClearBitsNz(y_start, y_end, tmp_variant_include);
3819 cur_variant_ct -= variant_ct_y;
3820 }
3821 cur_variant_include = tmp_variant_include;
3822 cur_local_variant_include = tmp_local_variant_include;
3823 }
3824 if (sex_male_collapsed_buf && (!skip_x)) {
3825 if (!cur_sample_include_x) {
3826 CopyBitarrSubset(sex_male, cur_sample_include, sample_ct, sex_male_collapsed_buf);
3827 } else {
3828 CopyBitarrSubset(sex_male, cur_sample_include_x, sample_ct_x, sex_male_collapsed_buf);
3829 }
3830 }
3831 // todo: if permutation test, also keep whatever statistic is most
3832 // appropriate for that
3833 FillCumulativePopcounts(cur_sample_include, raw_sample_ctl, common.sample_include_cumulative_popcounts);
3834 common.sample_ct = sample_ct;
3835 common.sample_ct_x = sample_ct_x;
3836 common.covar_ct = (is_qt_residualize && (!is_logistic))? 0 : (covar_ct + extra_cat_ct);
3837 common.local_covar_ct = local_covar_ct;
3838 if (sample_ct_x) {
3839 uint32_t* cumulative_popcounts;
3840 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) {
3841 goto GlmMain_ret_NOMEM;
3842 }
3843 FillCumulativePopcounts(cur_sample_include_x, raw_sample_ctl, cumulative_popcounts);
3844 common.sample_include_x_cumulative_popcounts = cumulative_popcounts;
3845 common.sample_include_x = cur_sample_include_x;
3846 common.covar_ct_x = (is_qt_residualize && (!is_logistic))? 0 : (covar_ct_x + extra_cat_ct_x);
3847 // common.male_ct = PopcountWordsIntersect(cur_sample_include_x, sex_male, raw_sample_ctl);
3848 } else {
3849 // technically only need this if variant_ct_x && (!skip_x)
3850 // common.male_ct = PopcountWordsIntersect(cur_sample_include, sex_male, raw_sample_ctl);
3851
3852 // defensive
3853 common.sample_include_x = nullptr;
3854 common.sample_include_x_cumulative_popcounts = nullptr;
3855 common.covar_ct_x = 0;
3856 }
3857 common.sample_ct_y = sample_ct_y;
3858 if (sample_ct_y) {
3859 uint32_t* cumulative_popcounts;
3860 if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) {
3861 goto GlmMain_ret_NOMEM;
3862 }
3863 FillCumulativePopcounts(cur_sample_include_y, raw_sample_ctl, cumulative_popcounts);
3864 common.sample_include_y_cumulative_popcounts = cumulative_popcounts;
3865 common.sample_include_y = cur_sample_include_y;
3866 common.covar_ct_y = (is_qt_residualize && (!is_logistic))? 0 : (covar_ct_y + extra_cat_ct_y);
3867 } else {
3868 common.sample_include_y = nullptr;
3869 common.sample_include_y_cumulative_popcounts = nullptr;
3870 common.covar_ct_y = 0;
3871 }
3872
3873 double* orig_ln_pvals = nullptr;
3874 double* orig_permstat = nullptr;
3875 if (report_adjust || perms_total) {
3876 const uintptr_t cur_allele_ct = cur_variant_ct + CountExtraAlleles(cur_variant_include, allele_idx_offsets, 0, raw_variant_ct, 0);
3877 if (unlikely(bigstack_alloc_d(cur_allele_ct, &orig_ln_pvals))) {
3878 goto GlmMain_ret_NOMEM;
3879 }
3880 memcpy(valid_variants, cur_variant_include, raw_variant_ctl * sizeof(intptr_t));
3881 ZeroWArr(raw_allele_ctl, valid_alleles);
3882 if (perms_total) {
3883 if (is_logistic) {
3884 if (unlikely(bigstack_alloc_d(cur_allele_ct, &orig_permstat))) {
3885 goto GlmMain_ret_NOMEM;
3886 }
3887 } else {
3888 // unfortunately, signs are reversed
3889 orig_permstat = orig_ln_pvals;
3890 }
3891 }
3892 }
3893
3894 uint32_t* subset_chr_fo_vidx_start;
3895 if (unlikely(AllocAndFillSubsetChrFoVidxStart(cur_variant_include, cip, &subset_chr_fo_vidx_start))) {
3896 goto GlmMain_ret_NOMEM;
3897 }
3898 common.subset_chr_fo_vidx_start = subset_chr_fo_vidx_start;
3899 common.variant_include = cur_variant_include;
3900 common.variant_ct = cur_variant_ct;
3901 // this is safe, see pheno_name_blen_capacity check above
3902 char* outname_end2 = strcpya(&(outname_end[1]), cur_pheno_name);
3903 if (is_logistic) {
3904 if (is_always_firth) {
3905 outname_end2 = strcpya_k(outname_end2, ".glm.firth");
3906 } else if (is_sometimes_firth) {
3907 outname_end2 = strcpya_k(outname_end2, ".glm.logistic.hybrid");
3908 } else {
3909 outname_end2 = strcpya_k(outname_end2, ".glm.logistic");
3910 }
3911 } else {
3912 outname_end2 = strcpya_k(outname_end2, ".glm.linear");
3913 }
3914 // write IDs
3915 if (glm_flags & kfGlmPhenoIds) {
3916 snprintf(outname_end2, 22, ".id");
3917 reterr = WriteSampleIds(cur_sample_include, siip, outname, sample_ct);
3918 if (unlikely(reterr)) {
3919 goto GlmMain_ret_1;
3920 }
3921 if (sample_ct_x && x_samples_are_different) {
3922 // quasi-bugfix (7 Jan 2017): use ".x.id" suffix instead of ".id.x",
3923 // since the last part of the file extension should indicate format
3924 snprintf(outname_end2, 22, ".x.id");
3925 reterr = WriteSampleIds(cur_sample_include_x, siip, outname, sample_ct_x);
3926 if (unlikely(reterr)) {
3927 goto GlmMain_ret_1;
3928 }
3929 }
3930 if (sample_ct_y && y_samples_are_different) {
3931 snprintf(outname_end2, 22, ".y.id");
3932 reterr = WriteSampleIds(cur_sample_include_y, siip, outname, sample_ct_y);
3933 if (unlikely(reterr)) {
3934 goto GlmMain_ret_1;
3935 }
3936 }
3937 }
3938
3939 if (output_zst) {
3940 snprintf(outname_end2, 22, ".zst");
3941 } else {
3942 *outname_end2 = '\0';
3943 }
3944
3945 uintptr_t valid_allele_ct = 0;
3946 if (is_logistic) {
3947 reterr = GlmLogistic(cur_pheno_name, cur_test_names, cur_test_names_x, cur_test_names_y, glm_pos_col? variant_bps : nullptr, variant_ids, allele_storage, glm_info_ptr, local_sample_uidx_order, cur_local_variant_include, outname, raw_variant_ct, max_chr_blen, ci_size, ln_pfilter, output_min_ln, max_thread_ct, pgr_alloc_cacheline_ct, overflow_buf_size, local_sample_ct, pgfip, &logistic_ctx, &local_covar_txs, gwas_ssf_ll_ptr, valid_variants, valid_alleles, orig_ln_pvals, orig_permstat, &valid_allele_ct);
3948 } else {
3949 // keep in sync with GlmLinearThread() difflist_eligible
3950 linear_ctx.max_returned_difflist_len = 0;
3951 if (((!common.covar_ct) || (sample_ct_y && (!common.covar_ct_y))) && common.nm_precomp && (!(pgfip->gflags & kfPgenGlobalDosagePresent))) {
3952 linear_ctx.max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor);
3953 }
3954 reterr = GlmLinear(cur_pheno_name, cur_test_names, cur_test_names_x, cur_test_names_y, glm_pos_col? variant_bps : nullptr, variant_ids, allele_storage, glm_info_ptr, local_sample_uidx_order, cur_local_variant_include, outname, raw_variant_ct, max_chr_blen, ci_size, ln_pfilter, output_min_ln, max_thread_ct, pgr_alloc_cacheline_ct, overflow_buf_size, local_sample_ct, pgfip, &linear_ctx, &local_covar_txs, gwas_ssf_ll_ptr, valid_variants, valid_alleles, orig_ln_pvals, &valid_allele_ct);
3955 }
3956 if (unlikely(reterr)) {
3957 goto GlmMain_ret_1;
3958 }
3959 if (report_adjust) {
3960 reterr = Multcomp(valid_variants, cip, nullptr, variant_bps, variant_ids, valid_alleles, allele_idx_offsets, allele_storage, pgfip->nonref_flags, nullptr, adjust_info_ptr, orig_ln_pvals, nullptr, raw_variant_ct, valid_allele_ct, max_allele_slen, pgfip->gflags, ln_pfilter, output_min_ln, joint_test, max_thread_ct, outname, outname_end2);
3961 if (unlikely(reterr)) {
3962 goto GlmMain_ret_1;
3963 }
3964 }
3965 if (perms_total) {
3966 // todo
3967 logerrputs("Error: --glm permutation tests are under development.\n");
3968 reterr = kPglRetNotYetSupported;
3969 goto GlmMain_ret_1;
3970 // note that orig_permstat signs are now flipped for linear case
3971 }
3972 }
3973 if (gwas_ssf_ll_ptr) {
3974 const uint32_t delete_orig_glm = gsip->flags & kfGwasSsfDeleteOrigGlm;
3975 while (gwas_ssf_ll) {
3976 const char* in_fname = gwas_ssf_ll->str;
3977 reterr = GwasSsfOneFile(gsip, in_fname, max_thread_ct);
3978 if (unlikely(reterr)) {
3979 goto GlmMain_ret_1;
3980 }
3981 // Don't need to free linked list nodes yet, but we may need to delete
3982 // files here.
3983 if (delete_orig_glm) {
3984 if (unlikely(unlink(in_fname))) {
3985 logerrprintfww("Error: --gwas-ssf delete-orig-glm: Failed to delete %s .\n", in_fname);
3986 goto GlmMain_ret_WRITE_FAIL;
3987 }
3988 }
3989 gwas_ssf_ll = gwas_ssf_ll->next;
3990 }
3991 }
3992 }
3993 while (0) {
3994 GlmMain_ret_NOMEM:
3995 reterr = kPglRetNomem;
3996 break;
3997 GlmMain_ret_TKSTREAM_FAIL:
3998 TokenStreamErrPrint("--condition-list file", &tks);
3999 break;
4000 GlmMain_ret_WRITE_FAIL:
4001 reterr = kPglRetWriteFail;
4002 break;
4003 GlmMain_ret_INVALID_CMDLINE:
4004 reterr = kPglRetInvalidCmdline;
4005 break;
4006 GlmMain_ret_MALFORMED_INPUT:
4007 reterr = kPglRetMalformedInput;
4008 break;
4009 GlmMain_ret_INCONSISTENT_INPUT:
4010 reterr = kPglRetInconsistentInput;
4011 break;
4012 GlmMain_ret_DEGENERATE_DATA:
4013 reterr = kPglRetDegenerateData;
4014 break;
4015 }
4016 GlmMain_ret_1:
4017 llstr_free_cond(gwas_ssf_ll);
4018 CleanupTokenStream2("--condition-list file", &tks, &reterr);
4019 CleanupTextStream2(local_covar_fname, &local_covar_txs, &reterr);
4020 if (x_fully_diploid) {
4021 SetBit(cip->xymt_codes[kChrOffsetX], cip->haploid_mask);
4022 }
4023 BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
4024 return reterr;
4025 }
4026
4027 /*
4028 void LogisticTest() {
4029 LogisticTestInternal();
4030 }
4031 */
4032
4033 #ifdef __cplusplus
4034 } // namespace plink2
4035 #endif