// This file is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
// Christopher Chang.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see .
#include "plink2_adjust.h"
#include "plink2_compress_stream.h"
#include "plink2_glm.h"
#include "plink2_glm_linear.h"
#include "plink2_glm_logistic.h"
#ifdef __cplusplus
namespace plink2 {
#endif
void InitGlm(GlmInfo* glm_info_ptr) {
glm_info_ptr->flags = kfGlm0;
glm_info_ptr->cols = kfGlmCol0;
glm_info_ptr->mperm_ct = 0;
glm_info_ptr->local_cat_ct = 0;
glm_info_ptr->local_header_line_ct = 0;
glm_info_ptr->local_chrom_col = 0;
glm_info_ptr->local_bp_col = 0;
glm_info_ptr->local_first_covar_col = 0;
glm_info_ptr->max_corr = 0.999;
glm_info_ptr->condition_varname = nullptr;
glm_info_ptr->condition_list_fname = nullptr;
InitRangeList(&(glm_info_ptr->parameters_range_list));
InitRangeList(&(glm_info_ptr->tests_range_list));
}
void CleanupGlm(GlmInfo* glm_info_ptr) {
free_cond(glm_info_ptr->condition_varname);
free_cond(glm_info_ptr->condition_list_fname);
CleanupRangeList(&(glm_info_ptr->parameters_range_list));
CleanupRangeList(&(glm_info_ptr->tests_range_list));
}
void InitGwasSsf(GwasSsfInfo* gwas_ssf_info_ptr) {
gwas_ssf_info_ptr->flags = kfGwasSsf0;
gwas_ssf_info_ptr->a1freq_lower_limit = 0.0;
gwas_ssf_info_ptr->rsid_mode = kGwasSsfRsidMode0;
gwas_ssf_info_ptr->fname = nullptr;
gwas_ssf_info_ptr->list_fname = nullptr;
}
void CleanupGwasSsf(GwasSsfInfo* gwas_ssf_info_ptr) {
free_cond(gwas_ssf_info_ptr->fname);
free_cond(gwas_ssf_info_ptr->list_fname);
}
// [-1] = #CHROM (must be first column)
// [0] = POS
// [1] = ID
// [2] = REF
// [3] = ALT
// [4] = PROVISIONAL_REF?
// [5] = A1
// [6] = OMITTED (optional, required to keep multiallelic variants)
// [7] = A1_FREQ
// [8] = TEST
// [9] = OBS_CT
// [10] = BETA/OR
// [11] = SE/LOG(OR)_SE
// [12] = L## (optional)
// [13] = U## (optional)
// [14] = P/LOG10_P/NEG_LOG10_P
ENUM_U31_DEF_START()
kGwasSsfColPos = 0,
kGwasSsfColId,
kGwasSsfColRef,
kGwasSsfColAlt,
kGwasSsfColProvref,
kGwasSsfColA1,
kGwasSsfColOmitted,
kGwasSsfColA1freq,
kGwasSsfColTest,
kGwasSsfColObsCt,
kGwasSsfColBetaOr,
kGwasSsfColSe,
kGwasSsfColCiLower,
kGwasSsfColCiUpper,
kGwasSsfColP,
kGwasSsfColNull
ENUM_U31_DEF_END(GwasSsfColidx);
FLAGSET_DEF_START()
kfGwasSsfColset0,
kfGwasSsfColsetPos = (1 << kGwasSsfColPos),
kfGwasSsfColsetId = (1 << kGwasSsfColId),
kfGwasSsfColsetRef = (1 << kGwasSsfColRef),
kfGwasSsfColsetAlt = (1 << kGwasSsfColAlt),
kfGwasSsfColsetProvref = (1 << kGwasSsfColProvref),
kfGwasSsfColsetA1 = (1 << kGwasSsfColA1),
kfGwasSsfColsetOmitted = (1 << kGwasSsfColOmitted),
kfGwasSsfColsetA1freq = (1 << kGwasSsfColA1freq),
kfGwasSsfColsetTest = (1 << kGwasSsfColTest),
kfGwasSsfColsetObsCt = (1 << kGwasSsfColObsCt),
kfGwasSsfColsetBetaOr = (1 << kGwasSsfColBetaOr),
kfGwasSsfColsetSe = (1 << kGwasSsfColSe),
kfGwasSsfColsetCiLower = (1 << kGwasSsfColCiLower),
kfGwasSsfColsetCiUpper = (1 << kGwasSsfColCiUpper),
kfGwasSsfColsetP = (1 << kGwasSsfColP),
kfGwasSsfColsetRequired = kfGwasSsfColsetPos | kfGwasSsfColsetRef | kfGwasSsfColsetAlt | kfGwasSsfColsetA1 | kfGwasSsfColsetA1freq | kfGwasSsfColsetTest | kfGwasSsfColsetObsCt | kfGwasSsfColsetBetaOr | kfGwasSsfColsetSe | kfGwasSsfColsetP
FLAGSET_DEF_END(GwasSsfColFlags);
// this is likely to become a library function. possible todos: benchmark
// against bool_table, vectorized code for large allele_code_slen
uint32_t AllACGT(const char* allele_code, uint32_t allele_code_slen) {
for (uint32_t pos = 0; pos != allele_code_slen; ++pos) {
uint32_t uii = ctou32(allele_code[pos]);
uii -= 64;
if ((uii > 31) || (!((0x10008a >> uii) & 1))) {
return 0;
}
}
return 1;
}
// Excludes integers >> 2^64.
uint32_t IsRsid(const char* variant_id, uint32_t variant_id_slen) {
if ((!StrStartsWith(variant_id, "rs", variant_id_slen)) || (variant_id_slen > 22)) {
return 0;
}
uint32_t uii = strlen("rs");
for (; uii != variant_id_slen; ++uii) {
if (!IsDigit(variant_id[uii])) {
return 0;
}
}
return 1;
}
// If rsid_mode == kGwasSsfRsidModeInfer and force_rsid is false, we peek at
// the second input line and proceed under the assumption that rsID is absent
// if that doesn't have a rsID. Then, if/when we encounter a later rsID (this
// should happen quickly if rsIDs are present at all), we return kPglRetRetry,
// and the caller retries with force_rsid true.
//
// Similarly, if the PROVISIONAL_REF? column is present, we proceed under the
// assumption that all values are 'Y' if that's true on the second line, and
// retry if we encounter an exception.
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) {
unsigned char* bigstack_mark = g_bigstack_base;
char* cswritep = nullptr;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
CompressStreamState css;
PreinitCstream(&css);
{
char* line_iter = TextLineEnd(txsp);
++line_idx;
if (!TextGetUnsafe2(txsp, &line_iter)) {
if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s is empty.\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
goto GwasSsfInternal_ret_TSTREAM_FAIL;
}
uint32_t col_skips[kGwasSsfColNull];
GwasSsfColidx col_types[kGwasSsfColNull];
char* first_token_end = FirstSpaceOrEoln(line_iter);
const uint32_t first_token_slen = first_token_end - line_iter;
GwasSsfColFlags header_cols = kfGwasSsfColset0;
uint32_t relevant_postchr_col_ct = 0;
uint32_t is_odds_ratio = 0;
uint32_t is_neglog10_p = 0;
if (unlikely(!strequal_k(line_iter, "#CHROM", first_token_slen))) {
if (strequal_k(line_iter, "#POS", first_token_slen) ||
strequal_k(line_iter, "#ID", first_token_slen)) {
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not have a #CHROM column.\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
if (strequal_k(line_iter, "CHR", first_token_slen)) {
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);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not appear to be a PLINK 2 --glm output file.\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
const char* token_end = first_token_end;
for (uint32_t col_idx = 1; ; ++col_idx) {
const char* linebuf_iter = FirstNonTspace(token_end);
if (IsEolnKns(*linebuf_iter)) {
break;
}
token_end = CurTokenEnd(linebuf_iter);
const uint32_t token_slen = token_end - linebuf_iter;
GwasSsfColidx cur_colidx = kGwasSsfColNull;
if (token_slen <= 3) {
if (token_slen == 3) {
if (memequal_sk(linebuf_iter, "POS")) {
cur_colidx = kGwasSsfColPos;
} else if (memequal_sk(linebuf_iter, "REF")) {
cur_colidx = kGwasSsfColRef;
} else if (memequal_sk(linebuf_iter, "ALT")) {
cur_colidx = kGwasSsfColAlt;
} else if (IsDigit(linebuf_iter[1]) && IsDigit(linebuf_iter[2])) {
if (linebuf_iter[0] == 'L') {
cur_colidx = kGwasSsfColCiLower;
} else if (linebuf_iter[0] == 'U') {
cur_colidx = kGwasSsfColCiUpper;
}
}
} else if (token_slen == 2) {
if (memequal_sk(linebuf_iter, "ID")) {
cur_colidx = kGwasSsfColId;
} else if (memequal_sk(linebuf_iter, "A1")) {
cur_colidx = kGwasSsfColA1;
} else if (memequal_sk(linebuf_iter, "OR")) {
cur_colidx = kGwasSsfColBetaOr;
is_odds_ratio = 1;
} else if (memequal_sk(linebuf_iter, "SE")) {
cur_colidx = kGwasSsfColSe;
}
} else if (strequal_k(linebuf_iter, "P", token_slen)) {
cur_colidx = kGwasSsfColP;
}
} else if (strequal_k(linebuf_iter, "PROVISIONAL_REF?", token_slen)) {
cur_colidx = kGwasSsfColProvref;
} else if (strequal_k(linebuf_iter, "OMITTED", token_slen)) {
cur_colidx = kGwasSsfColOmitted;
} else if (strequal_k(linebuf_iter, "A1_FREQ", token_slen)) {
cur_colidx = kGwasSsfColA1freq;
} else if (strequal_k(linebuf_iter, "TEST", token_slen)) {
cur_colidx = kGwasSsfColTest;
} else if (strequal_k(linebuf_iter, "OBS_CT", token_slen)) {
cur_colidx = kGwasSsfColObsCt;
} else if (strequal_k(linebuf_iter, "BETA", token_slen)) {
cur_colidx = kGwasSsfColBetaOr;
} else if (strequal_k(linebuf_iter, "LOG(OR)_SE", token_slen)) {
cur_colidx = kGwasSsfColSe;
} else if (strequal_k(linebuf_iter, "LOG10_P", token_slen) || strequal_k(linebuf_iter, "NEG_LOG10_P", token_slen)) {
cur_colidx = kGwasSsfColP;
is_neglog10_p = 1;
}
if (cur_colidx != kGwasSsfColNull) {
const GwasSsfColFlags cur_colset = S_CAST(GwasSsfColFlags, 1U << cur_colidx);
if (unlikely(header_cols & cur_colset)) {
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: Conflicting columns in header line of %s .\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
header_cols |= cur_colset;
col_skips[relevant_postchr_col_ct] = col_idx;
col_types[relevant_postchr_col_ct++] = cur_colidx;
}
}
if (unlikely((header_cols & kfGwasSsfColsetRequired) != kfGwasSsfColsetRequired)) {
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);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
// static-cast to remove gcc 4.4 warning
GwasSsfRsidMode rsid_mode = (*force_rsidp)? S_CAST(GwasSsfRsidMode, kGwasSsfRsidModeYes) : gsip->rsid_mode;
if (unlikely((rsid_mode != kGwasSsfRsidModeNo) && (!(header_cols & kfGwasSsfColsetId)))) {
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s does not have an ID column, and rsid=no was not specified.\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
// Peek at second line to make informed rsid_mode and ref_mode guesses.
++line_idx;
line_iter = AdvPastDelim(line_iter, '\n');
if (!TextGetUnsafe2(txsp, &line_iter)) {
if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
snprintf(g_logbuf, kLogbufSize, "Error: --gwas-ssf: %s only has a header line.\n", in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
goto GwasSsfInternal_ret_TSTREAM_FAIL;
}
// col_skips has not been finalized yet, it still contains raw column
// indices.
if (rsid_mode == kGwasSsfRsidModeInfer) {
const char* variant_id = NextTokenMult(line_iter, col_skips[kGwasSsfColId]);
if (unlikely(variant_id == nullptr)) {
goto GwasSsfInternal_ret_MISSING_TOKENS;
}
const uint32_t variant_id_slen = CurTokenEnd(variant_id) - variant_id;
if (IsRsid(variant_id, variant_id_slen)) {
*force_rsidp = 1;
rsid_mode = kGwasSsfRsidModeYes;
}
}
const uint32_t rsid_col = (rsid_mode == kGwasSsfRsidModeYes);
uint32_t real_ref_found = (*force_refp) || (gsip->flags & kfGwasSsfRealRefAlleles);
if ((!real_ref_found) && (header_cols & kfGwasSsfColsetProvref)) {
const char* provref_str = NextTokenMult(line_iter, col_skips[kGwasSsfColProvref]);
if (unlikely(provref_str == nullptr)) {
goto GwasSsfInternal_ret_MISSING_TOKENS;
}
if ((provref_str[0] == 'N') && IsSpaceOrEoln(provref_str[1])) {
*force_refp = 1;
real_ref_found = 1;
}
}
// Ok, now we can finalize col_skips.
for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) {
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
}
const uint32_t output_zst = (gsip->flags / kfGwasSsfZs) & 1;
// Output line length won't be more than ~2x input line length.
// (It can be close to 2x if REF allele is very long and isn't A1.)
const uintptr_t overflow_buf_size = kCompressStreamBlock + 512 + ((2 * k1LU) * max_line_blen);
reterr = InitCstreamAlloc(out_fname, 0, output_zst, MAXV(1, max_thread_ct - 1), overflow_buf_size, &css, &cswritep);
if (unlikely(reterr)) {
goto GwasSsfInternal_ret_1;
}
cswritep = strcpya_k(cswritep, "chromosome\tbase_pair_location\teffect_allele\tother_allele\t");
if (!is_odds_ratio) {
cswritep = strcpya_k(cswritep, "beta");
} else {
cswritep = strcpya_k(cswritep, "odds_ratio");
}
cswritep = strcpya_k(cswritep, "\tstandard_error\teffect_allele_frequency\t");
if (is_neglog10_p) {
cswritep = strcpya(cswritep, "neg_log_10_");
}
cswritep = strcpya(cswritep, "p_value");
if (real_ref_found) {
cswritep = strcpya_k(cswritep, "\tvariant_id");
}
if (rsid_col) {
cswritep = strcpya_k(cswritep, "\trsid");
}
if (header_cols & kfGwasSsfColsetCiUpper) {
cswritep = strcpya_k(cswritep, "\tci_upper");
}
if (header_cols & kfGwasSsfColsetCiLower) {
cswritep = strcpya_k(cswritep, "\tci_lower");
}
cswritep = strcpya_k(cswritep, "\tn");
if (real_ref_found) {
cswritep = strcpya_k(cswritep, "\tref_allele");
}
AppendBinaryEoln(&cswritep);
// X, XY, PAR1, PAR2 -> 23
// Y -> 24
// MT -> 25, not 26
const unsigned char gwas_ssf_chr_remap[6] = {23, 24, 23, 25, 23, 23};
const double a1freq_lower_limit = gsip->a1freq_lower_limit;
const uint32_t allow_ambiguous_indels = (gsip->flags / kfGwasSsfAllowAmbiguousIndels) & 1;
char a1freq_lower_limit_str[16]; // > kMaxDoubleGSlen
uint32_t a1freq_lower_limit_slen = 0;
if (a1freq_lower_limit > 0.0) {
char* a1freq_lower_limit_end = dtoa_g(a1freq_lower_limit, a1freq_lower_limit_str);
a1freq_lower_limit_slen = a1freq_lower_limit_end - a1freq_lower_limit_str;
}
// If there is no provref column, and the user did not specify
// 'real-ref-alleles' on the command line, treat all REF alleles as
// provisional for the ambiguous-indel check.
uint32_t provref = (!(gsip->flags & kfGwasSsfRealRefAlleles)) && (!(header_cols & kfGwasSsfColsetProvref));
goto GwasSsfInternal_main_loop_start;
for (; TextGetUnsafe2(txsp, &line_iter); ++line_idx) {
if (IsEolnKns(*line_iter)) {
goto GwasSsfInternal_ret_MISSING_TOKENS;
}
GwasSsfInternal_main_loop_start:
;
const uint32_t chr_code_raw = GetChrCodeRaw(line_iter);
if ((!chr_code_raw) || ((chr_code_raw > 26) && (chr_code_raw < kMaxContigs))) {
line_iter = AdvPastDelim(line_iter, '\n');
continue;
}
char* token_ptrs[kGwasSsfColNull];
uint32_t token_slens[kGwasSsfColNull];
line_iter = TokenLex(line_iter, R_CAST(uint32_t*, col_types), col_skips, relevant_postchr_col_ct, token_ptrs, token_slens);
if (unlikely(!line_iter)) {
goto GwasSsfInternal_ret_MISSING_TOKENS;
}
line_iter = AdvPastDelim(line_iter, '\n');
// skip if TEST isn't ADD, or result is NA, or effect/other allele has
// non-ACGT character, or OMITTED column is absent and variant is
// multiallelic
if (!strequal_k(token_ptrs[kGwasSsfColTest], "ADD", token_slens[kGwasSsfColTest])) {
continue;
}
if ((token_ptrs[kGwasSsfColP][0] & 0xdf) == 'N') {
continue;
}
const char* effect_allele = token_ptrs[kGwasSsfColA1];
const uint32_t effect_allele_slen = token_slens[kGwasSsfColA1];
if (!AllACGT(effect_allele, effect_allele_slen)) {
continue;
}
const char* ref_allele = token_ptrs[kGwasSsfColRef];
uint32_t ref_allele_slen = token_slens[kGwasSsfColRef];
const char* other_allele;
uint32_t other_allele_slen;
uint32_t ref_allele_match; // 0 = effect, 1 = other, 2 = neither
if (header_cols & kfGwasSsfColsetOmitted) {
other_allele = token_ptrs[kGwasSsfColOmitted];
other_allele_slen = token_slens[kGwasSsfColOmitted];
if (!AllACGT(other_allele, other_allele_slen)) {
continue;
}
if ((ref_allele_slen == effect_allele_slen) && memequal(ref_allele, effect_allele, ref_allele_slen)) {
ref_allele_match = 0;
} else if ((ref_allele_slen == other_allele_slen) && memequal(ref_allele, other_allele, ref_allele_slen)) {
ref_allele_match = 1;
} else {
ref_allele_match = 2;
}
} else {
const char* alt_str = token_ptrs[kGwasSsfColAlt];
const uint32_t alt_slen = token_slens[kGwasSsfColAlt];
if (memchr(alt_str, ',', alt_slen) != nullptr) {
continue;
}
// check for REF/ALT match, ALT first (much more likely), error out if
// neither.
if ((effect_allele_slen == alt_slen) && memequal(effect_allele, alt_str, effect_allele_slen)) {
other_allele = ref_allele;
other_allele_slen = ref_allele_slen;
ref_allele_match = 1;
} else if (likely((effect_allele_slen == ref_allele_slen) && memequal(effect_allele, ref_allele, effect_allele_slen))) {
other_allele = alt_str;
other_allele_slen = alt_slen;
ref_allele_match = 0;
} else {
snprintf(g_logbuf, kLogbufSize, "Error: A1 allele on line %" PRIuPTR " of %s matches neither REF nor ALT.\n", line_idx, in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
if (!AllACGT(other_allele, other_allele_slen)) {
continue;
}
}
uint32_t gwas_ssf_chr_code;
if (chr_code_raw < kMaxContigs) {
if (chr_code_raw < 25) {
gwas_ssf_chr_code = chr_code_raw;
} else if (chr_code_raw == 25) {
gwas_ssf_chr_code = 23;
} else {
gwas_ssf_chr_code = 25;
}
} else {
gwas_ssf_chr_code = gwas_ssf_chr_remap[chr_code_raw - kMaxContigs];
}
#ifdef __LP64__
char* outline_start = cswritep;
#endif
cswritep = u32toa_x(gwas_ssf_chr_code, '\t', cswritep);
// POS
const char* pos_str = token_ptrs[kGwasSsfColPos];
const uint32_t pos_slen = token_slens[kGwasSsfColPos];
cswritep = memcpyax(cswritep, pos_str, pos_slen, '\t');
// A1
cswritep = memcpyax(cswritep, effect_allele, effect_allele_slen, '\t');
// OMITTED
cswritep = memcpyax(cswritep, other_allele, other_allele_slen, '\t');
// BETA/OR
cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColBetaOr], token_slens[kGwasSsfColBetaOr], '\t');
// SE
cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColSe], token_slens[kGwasSsfColSe], '\t');
// A1_FREQ
const char* a1_freq_str = token_ptrs[kGwasSsfColA1freq];
if (a1freq_lower_limit == 0.0) {
cswritep = memcpya(cswritep, a1_freq_str, token_slens[kGwasSsfColA1freq]);
} else {
double a1_freq;
if (unlikely(!ScanadvDouble(a1_freq_str, &a1_freq))) {
snprintf(g_logbuf, kLogbufSize, "Error: Invalid A1_FREQ on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
if (a1_freq >= a1freq_lower_limit) {
cswritep = memcpya(cswritep, a1_freq_str, token_slens[kGwasSsfColA1freq]);
} else {
cswritep = memcpya(cswritep, a1freq_lower_limit_str, a1freq_lower_limit_slen);
}
}
*cswritep++ = '\t';
// P
cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColP], token_slens[kGwasSsfColP], '\t');
// C_P_R_A
if (header_cols & kfGwasSsfColsetProvref) {
const uint32_t provref_slen = token_slens[kGwasSsfColProvref];
const char provref_char = token_ptrs[kGwasSsfColProvref][0];
provref = (provref_char == 'Y');
if (unlikely((provref_slen != 1) || ((!provref) && (provref_char != 'N')))) {
snprintf(g_logbuf, kLogbufSize, "Error: Invalid PROVISIONAL_REF? column value on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
if ((!real_ref_found) && (!provref)) {
*force_refp = 1;
reterr = kPglRetRetry;
goto GwasSsfInternal_ret_1;
}
}
// Note that this doesn't catch all ambiguous variants. Specifically,
// when REF is neither the effect nor the other allele in a multiallelic
// variant, we technically need to know the length of the REF allele to
// disambiguate, and that is not currently recorded.
// But that's rare. This catches the most common problem case.
if (unlikely((!allow_ambiguous_indels) && (effect_allele_slen != other_allele_slen) && provref && (ref_allele_match != 2))) {
logerrprintfww("Error: --gwas-ssf: Indel with unknown REF allele on line %" PRIuPTR " of %s .\n", line_idx, in_fname);
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");
goto GwasSsfInternal_ret_MALFORMED_INPUT;
}
if (real_ref_found) {
if ((ref_allele_match == 2) || provref) {
// at least two ALTs relevant. As of this writing, the specification
// doesn't say what to do here.
cswritep = strcpya_k(cswritep, "#NA\t");
} else {
cswritep = u32toa_x(gwas_ssf_chr_code, '_', cswritep);
cswritep = memcpyax(cswritep, pos_str, pos_slen, '_');
cswritep = memcpyax(cswritep, ref_allele, ref_allele_slen, '_');
if (ref_allele_match == 0) {
cswritep = memcpya(cswritep, other_allele, other_allele_slen);
} else {
cswritep = memcpya(cswritep, effect_allele, effect_allele_slen);
}
*cswritep++ = '\t';
}
}
if (rsid_mode != kGwasSsfRsidModeNo) {
const char* variant_id = token_ptrs[kGwasSsfColId];
const uint32_t variant_id_slen = token_slens[kGwasSsfColId];
const uint32_t is_rsid = IsRsid(variant_id, variant_id_slen);
if (rsid_col) {
if (is_rsid) {
cswritep = memcpyax(cswritep, variant_id, variant_id_slen, '\t');
} else {
cswritep = strcpya_k(cswritep, "#NA\t");
}
} else if (is_rsid) {
*force_rsidp = 1;
reterr = kPglRetRetry;
goto GwasSsfInternal_ret_1;
}
}
if (header_cols & kfGwasSsfColsetCiUpper) {
cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColCiUpper], token_slens[kGwasSsfColCiUpper], '\t');
}
if (header_cols & kfGwasSsfColsetCiLower) {
cswritep = memcpyax(cswritep, token_ptrs[kGwasSsfColCiLower], token_slens[kGwasSsfColCiLower], '\t');
}
// OBS_CT
cswritep = memcpya(cswritep, token_ptrs[kGwasSsfColObsCt], token_slens[kGwasSsfColObsCt]);
if (real_ref_found) {
*cswritep++ = '\t';
if (provref || (ref_allele_match == 2)) {
cswritep = strcpya_k(cswritep, "#NA");
} else if (ref_allele_match == 1) {
cswritep = strcpya_k(cswritep, "OA");
} else {
cswritep = strcpya_k(cswritep, "EA");
}
}
AppendBinaryEoln(&cswritep);
#ifdef __LP64__
if (unlikely(S_CAST(uintptr_t, cswritep - outline_start) > kMaxLongLine)) {
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s is too long to process.\n", line_idx, in_fname);
goto GwasSsfInternal_ret_MALFORMED_INPUT_WW;
}
#endif
if (unlikely(Cswrite(&css, &cswritep))) {
goto GwasSsfInternal_ret_WRITE_FAIL;
}
}
if (unlikely(TextStreamErrcode2(txsp, &reterr))) {
goto GwasSsfInternal_ret_TSTREAM_FAIL;
}
if (unlikely(CswriteCloseNull(&css, cswritep))) {
goto GwasSsfInternal_ret_WRITE_FAIL;
}
reterr = kPglRetSuccess;
}
while (0) {
GwasSsfInternal_ret_TSTREAM_FAIL:
TextStreamErrPrint(in_fname, txsp);
break;
GwasSsfInternal_ret_WRITE_FAIL:
reterr = kPglRetWriteFail;
break;
GwasSsfInternal_ret_MISSING_TOKENS:
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, in_fname);
GwasSsfInternal_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
GwasSsfInternal_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
}
GwasSsfInternal_ret_1:
CswriteCloseCond(&css, cswritep);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr GwasSsfOneFile(const GwasSsfInfo* gsip, const char* in_fname, uint32_t max_thread_ct) {
unsigned char* bigstack_mark = g_bigstack_base;
char* out_fname = nullptr;
PglErr reterr = kPglRetSuccess;
TextStream txs;
PreinitTextStream(&txs);
{
uint32_t shared_fname_slen = strlen(in_fname);
if (StrEndsWith(in_fname, ".zst", shared_fname_slen)) {
shared_fname_slen -= 4;
}
// ".ssf.tsv.zst"
if (unlikely(bigstack_alloc_c(shared_fname_slen + 13, &out_fname))) {
goto GwasSsfOneFile_ret_NOMEM;
}
const uint32_t output_zst = (gsip->flags / kfGwasSsfZs) & 1;
char* out_fname_iter = memcpya(out_fname, in_fname, shared_fname_slen);
out_fname_iter = strcpya_k(out_fname_iter, ".ssf.tsv");
if (output_zst) {
out_fname_iter = strcpya_k(out_fname_iter, ".zst");
}
*out_fname_iter = '\0';
// /6 since output stream may require slightly over 4x this amount of
// memory with compression on
uint32_t max_line_blen;
if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 6, &max_line_blen))) {
goto GwasSsfOneFile_ret_NOMEM;
}
reterr = InitTextStream(in_fname, max_line_blen, output_zst? 1 : MAXV(1, max_thread_ct - 1), &txs);
if (unlikely(reterr)) {
goto GwasSsfOneFile_ret_TSTREAM_FAIL;
}
uint32_t force_rsid = 0;
uint32_t force_ref = 0;
do {
reterr = GwasSsfInternal(gsip, in_fname, out_fname, max_line_blen, max_thread_ct, &txs, &force_rsid, &force_ref);
} while (reterr == kPglRetRetry);
if (unlikely(reterr)) {
goto GwasSsfOneFile_ret_1;
}
logprintfww("--gwas-ssf: %s written.\n", out_fname);
}
while (0) {
GwasSsfOneFile_ret_NOMEM:
reterr = kPglRetNomem;
break;
GwasSsfOneFile_ret_TSTREAM_FAIL:
TextStreamErrPrint(in_fname, &txs);
break;
}
GwasSsfOneFile_ret_1:
CleanupTextStream2(in_fname, &txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
PglErr GwasSsfStandalone(const GwasSsfInfo* gsip, uint32_t max_thread_ct) {
unsigned char* bigstack_mark = g_bigstack_base;
PglErr reterr = kPglRetSuccess;
TextStream list_txs;
PreinitTextStream(&list_txs);
{
uintptr_t file_ct = 0;
if (gsip->fname) {
reterr = GwasSsfOneFile(gsip, gsip->fname, max_thread_ct);
if (unlikely(reterr)) {
goto GwasSsfStandalone_ret_1;
}
++file_ct;
}
if (gsip->list_fname) {
reterr = InitTextStream(gsip->list_fname, kTextStreamBlenFast, 1, &list_txs);
if (unlikely(reterr)) {
goto GwasSsfStandalone_ret_TSTREAM_FAIL;
}
while (1) {
char* first_token_start = TextGet(&list_txs);
if (!first_token_start) {
break;
}
if (IsSpaceOrEoln(*first_token_start)) {
continue;
}
char* first_token_end = CurTokenEnd(first_token_start);
*first_token_end = '\0';
reterr = GwasSsfOneFile(gsip, first_token_start, max_thread_ct);
if (unlikely(reterr)) {
goto GwasSsfStandalone_ret_1;
}
++file_ct;
}
if (unlikely(TextStreamErrcode2(&list_txs, &reterr))) {
goto GwasSsfStandalone_ret_TSTREAM_FAIL;
}
}
logprintf("--gwas-ssf file=/file-list=: %" PRIuPTR " file%s processed.\n", file_ct, (file_ct == 1)? "" : "s");
}
while (0) {
GwasSsfStandalone_ret_TSTREAM_FAIL:
TextStreamErrPrint(gsip->list_fname, &list_txs);
break;
}
GwasSsfStandalone_ret_1:
CleanupTextStream2(gsip->list_fname, &list_txs, &reterr);
BigstackReset(bigstack_mark);
return reterr;
}
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) {
unsigned char* bigstack_mark = g_bigstack_base;
unsigned char* bigstack_end_mark = g_bigstack_end;
uintptr_t line_idx = 0;
PglErr reterr = kPglRetSuccess;
const char* txs_fname = nullptr;
textFILE local_covar_txf;
TextStream txs;
PreinitTextFile(&local_covar_txf);
PreinitTextStream(&txs);
{
// 1. read .psam/.fam file, update sample_ct, initialize
// local_sample_uidx_order
uint32_t max_line_blen;
if (unlikely(StandardizeMaxLineBlen(bigstack_left() / 4, &max_line_blen))) {
goto GlmLocalOpen_ret_NOMEM;
}
txs_fname = local_psam_fname;
reterr = InitTextStreamEx(local_psam_fname, 1, kMaxLongLine, max_line_blen, 1, &txs);
if (unlikely(reterr)) {
goto GlmLocalOpen_ret_TSTREAM_FAIL;
}
XidMode xid_mode;
char* line_start;
reterr = LoadXidHeader("glm local-psam=", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start);
if (unlikely(reterr)) {
goto GlmLocalOpen_ret_TSTREAM_XID_FAIL;
}
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
const uint32_t orig_sample_ct = *sample_ct_ptr;
char* sorted_xidbox;
uint32_t* xid_map;
uintptr_t max_xid_blen;
// IID -> multiple IID+SID not supported for now, may want to add this
reterr = SortedXidboxInitAllocEnd(*sample_include_ptr, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen);
if (unlikely(reterr)) {
goto GlmLocalOpen_ret_1;
}
uintptr_t* new_sample_include;
char* idbuf;
if (unlikely(bigstack_end_calloc_w(raw_sample_ctl, &new_sample_include) ||
bigstack_end_alloc_c(max_xid_blen, &idbuf))) {
goto GlmLocalOpen_ret_NOMEM;
}
uint32_t* local_sample_uidx_order = R_CAST(uint32_t*, g_bigstack_base);
uintptr_t max_local_sample_ct = RoundDownPow2(bigstack_left(), kCacheline) / sizeof(int32_t);
#ifdef __LP64__
if (max_local_sample_ct > kMaxLongLine / 2) {
max_local_sample_ct = kMaxLongLine / 2;
}
#endif
uintptr_t local_sample_ct = 0;
if (line_start[0] == '#') {
++line_idx;
line_start = TextGet(&txs);
}
for (; line_start; ++local_sample_ct, ++line_idx, line_start = TextGet(&txs)) {
if (unlikely(line_start[0] == '#')) {
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);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
if (unlikely(local_sample_ct == max_local_sample_ct)) {
#ifdef __LP64__
if (local_sample_ct == kMaxLongLine / 2) {
snprintf(g_logbuf, kLogbufSize, "Error: Too many samples in %s.\n", local_psam_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
#endif
goto GlmLocalOpen_ret_NOMEM;
}
const char* read_ptr = line_start;
uint32_t sample_uidx;
if (!SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &read_ptr, &sample_uidx, idbuf)) {
if (unlikely(IsSet(new_sample_include, sample_uidx))) {
TabsToSpaces(idbuf);
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate sample ID \"%s\" in %s.\n", idbuf, local_psam_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
SetBit(sample_uidx, new_sample_include);
local_sample_uidx_order[local_sample_ct] = sample_uidx;
} else {
if (unlikely(!read_ptr)) {
snprintf(g_logbuf, kLogbufSize, "Error: Fewer tokens than expected on line %" PRIuPTR " of %s.\n", line_idx, local_psam_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
local_sample_uidx_order[local_sample_ct] = UINT32_MAX;
}
}
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto GlmLocalOpen_ret_TSTREAM_FAIL;
}
BigstackFinalizeU32(local_sample_uidx_order, local_sample_ct);
*local_sample_uidx_order_ptr = local_sample_uidx_order;
*local_sample_ct_ptr = local_sample_ct;
const uint32_t new_sample_ct = PopcountWords(new_sample_include, raw_sample_ctl);
assert(new_sample_ct <= orig_sample_ct);
if (new_sample_ct < orig_sample_ct) {
uintptr_t* sample_include_copy;
uintptr_t* sex_nm_copy;
uintptr_t* sex_male_copy;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include_copy) ||
bigstack_alloc_w(raw_sample_ctl, &sex_nm_copy) ||
bigstack_alloc_w(raw_sample_ctl, &sex_male_copy))) {
goto GlmLocalOpen_ret_NOMEM;
}
memcpy(sample_include_copy, new_sample_include, raw_sample_ctl * sizeof(intptr_t));
BitvecAndCopy(sample_include_copy, *sex_nm_ptr, raw_sample_ctl, sex_nm_copy);
*sex_nm_ptr = sex_nm_copy;
BitvecAndCopy(sample_include_copy, *sex_male_ptr, raw_sample_ctl, sex_male_copy);
*sex_male_ptr = sex_male_copy;
*sample_include_ptr = sample_include_copy;
*sample_ct_ptr = new_sample_ct;
}
BigstackEndReset(TextStreamMemStart(&txs));
// 2. if local-pvar= specified, read .pvar/.bim file, update variant_ct,
// initialize local_variant_ct/local_variant_include.
if (local_pvar_fname) {
reterr = TextRetarget(local_pvar_fname, &txs);
if (unlikely(reterr)) {
goto GlmLocalOpen_ret_TSTREAM_FAIL;
}
txs_fname = local_pvar_fname;
line_idx = 0;
uint32_t is_header_line;
do {
++line_idx;
line_start = TextGet(&txs);
if (unlikely(!line_start)) {
if (!TextStreamErrcode2(&txs, &reterr)) {
snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", local_pvar_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
goto GlmLocalOpen_ret_TSTREAM_FAIL;
}
is_header_line = (line_start[0] == '#');
} while (is_header_line && (!tokequal_k(line_start, "#CHROM")));
uint32_t col_skips[2];
uint32_t col_types[2];
// uint32_t relevant_postchr_col_ct = 2;
if (is_header_line) {
// parse header
// [-1] = #CHROM (must be first column)
// [0] = POS
// [1] = ID
// don't care about the rest
const char* token_end = &(line_start[6]);
uint32_t found_header_bitset = 0;
uint32_t relevant_postchr_col_ct = 0;
const char* linebuf_iter;
for (uint32_t col_idx = 1; ; ++col_idx) {
linebuf_iter = FirstNonTspace(token_end);
if (IsEolnKns(*linebuf_iter)) {
break;
}
token_end = CurTokenEnd(linebuf_iter);
const uint32_t token_slen = token_end - linebuf_iter;
uint32_t cur_col_type;
if (strequal_k(linebuf_iter, "POS", token_slen)) {
cur_col_type = 0;
} else if (strequal_k(linebuf_iter, "ID", token_slen)) {
cur_col_type = 1;
} else {
continue;
}
const uint32_t cur_col_type_shifted = 1 << cur_col_type;
if (unlikely(found_header_bitset & cur_col_type_shifted)) {
// Known column type, so length is limited and we don't have to
// worry about buffer overflow.
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '");
write_iter = memcpya(write_iter, linebuf_iter, token_slen);
write_iter = strcpya_k(write_iter, "' on line ");
write_iter = wtoa(line_idx, write_iter);
write_iter = strcpya_k(write_iter, " of ");
write_iter = strcpya(write_iter, local_pvar_fname);
memcpy_k(write_iter, ".\n\0", 4);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
found_header_bitset |= cur_col_type_shifted;
col_skips[relevant_postchr_col_ct] = col_idx;
col_types[relevant_postchr_col_ct++] = cur_col_type;
}
if (unlikely(found_header_bitset != 3)) {
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);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
for (uint32_t rpc_col_idx = relevant_postchr_col_ct - 1; rpc_col_idx; --rpc_col_idx) {
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1];
}
} else {
col_types[0] = 1;
col_types[1] = 0;
col_skips[0] = 1;
// CM column may be omitted
const char* linebuf_iter = NextTokenMult(line_start, 4);
if (unlikely(!linebuf_iter)) {
goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
}
linebuf_iter = NextToken(linebuf_iter);
if (!linebuf_iter) {
// #CHROM ID POS ALT REF
col_skips[1] = 1;
} else {
// #CHROM ID CM POS ALT REF
col_skips[1] = 2;
}
}
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct);
uintptr_t* new_variant_include;
if (unlikely(bigstack_end_calloc_w(raw_variant_ctl, &new_variant_include))) {
goto GlmLocalOpen_ret_NOMEM;
}
uint32_t max_local_variant_ct = kPglMaxVariantCt;
if (bigstack_left() < (0x80000000U / CHAR_BIT)) {
max_local_variant_ct = RoundDownPow2(bigstack_left(), kCacheline) * CHAR_BIT;
}
const uintptr_t* orig_variant_include = *variant_include_ptr;
uintptr_t* local_variant_include = R_CAST(uintptr_t*, g_bigstack_base);
*local_variant_include_ptr = local_variant_include;
uint32_t local_variant_ct = 0;
uint32_t new_variant_ct = 0;
uint32_t prev_variant_uidx = AdvTo1Bit(orig_variant_include, 0);
uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
uint32_t prev_chr_code = cip->chr_file_order[chr_fo_idx];
uint32_t prev_bp = variant_bps[prev_variant_uidx];
uint32_t chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
if (is_header_line) {
++line_idx;
line_start = TextGet(&txs);
}
for (; line_start; ++local_variant_ct, ++line_idx, line_start = TextGet(&txs)) {
if (unlikely(line_start[0] == '#')) {
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);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
if (unlikely(local_variant_ct == max_local_variant_ct)) {
if (max_local_variant_ct == kPglMaxVariantCt) {
snprintf(g_logbuf, kLogbufSize, "Error: Too many variants in %s.\n", local_pvar_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
goto GlmLocalOpen_ret_NOMEM;
}
if (!(local_variant_ct % kBitsPerWord)) {
local_variant_include[local_variant_ct / kBitsPerWord] = 0;
}
char* line_iter = CurTokenEnd(line_start);
// #CHROM
if (unlikely((*line_iter != '\t') && (*line_iter != ' '))) {
goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
}
const uint32_t cur_chr_code = GetChrCodeCounted(cip, line_iter - line_start, line_start);
if (IsI32Neg(cur_chr_code)) {
continue;
}
const uint32_t cur_chr_code_u = cur_chr_code;
if (cur_chr_code_u != prev_chr_code) {
const uint32_t first_variant_uidx_in_chr = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[cur_chr_code_u]];
if (first_variant_uidx_in_chr < prev_variant_uidx) {
if (unlikely(new_variant_ct)) {
// not worth the trouble of handling this
snprintf(g_logbuf, kLogbufSize, "Error: Chromosome order in %s is different from chromosome order in main dataset.\n", local_pvar_fname);
goto GlmLocalOpen_ret_INCONSISTENT_INPUT_WW;
}
continue;
}
prev_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, first_variant_uidx_in_chr, raw_variant_ct);
if (prev_variant_uidx == raw_variant_ct) {
break;
}
chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
prev_chr_code = cip->chr_file_order[chr_fo_idx];
prev_bp = variant_bps[prev_variant_uidx];
chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
if (cur_chr_code_u != prev_chr_code) {
continue;
}
}
char* token_ptrs[2];
uint32_t token_slens[2];
if (unlikely(!TokenLex(line_iter, col_types, col_skips, 2, token_ptrs, token_slens))) {
goto GlmLocalOpen_ret_MISSING_TOKENS_PVAR;
}
// POS
int32_t cur_bp;
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp))) {
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of %s.\n", line_idx, local_pvar_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
if (cur_bp < S_CAST(int32_t, prev_bp)) {
continue;
}
const uint32_t cur_bp_u = cur_bp;
if (cur_bp_u > prev_bp) {
do {
prev_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, prev_variant_uidx + 1, raw_variant_ct);
} while ((prev_variant_uidx < chr_end) && (cur_bp_u > variant_bps[prev_variant_uidx]));
if (prev_variant_uidx >= chr_end) {
goto GlmLocalOpen_skip_variant_and_update_chr;
}
prev_bp = variant_bps[prev_variant_uidx];
}
if (cur_bp_u == prev_bp) {
// ID
// note that if there are two same-position variants which appear in
// a different order in the main dataset and the local-pvar file, one
// will be skipped. (probably want to add a warning in this case.)
const uint32_t variant_id_slen = token_slens[1];
char* cur_variant_id = token_ptrs[1];
cur_variant_id[variant_id_slen] = '\0';
const uint32_t variant_id_blen = variant_id_slen + 1;
// bugfix (16 Mar 2022): if a variant filter was applied to the main
// dataset, the local-pvar entry corresponding to prev_variant_uidx
// may be on a later line, even if we fail to find an ID match for
// the current local-pvar ID.
// So we no longer advance prev_variant_uidx/prev_bp here under any
// circumstances. We just scan through the same-bp variant IDs,
// looking for a match, and then advance to the next local-pvar line
// with prev_variant_uidx/prev_bp unchanged.
uint32_t scan_variant_uidx = prev_variant_uidx;
uint32_t scan_bp;
do {
const char* loaded_variant_id = variant_ids[scan_variant_uidx];
if (memequal(cur_variant_id, loaded_variant_id, variant_id_blen)) {
if (unlikely(IsSet(new_variant_include, scan_variant_uidx))) {
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate ID (with duplicate CHROM/POS) '%s' in %s.\n", cur_variant_id, local_pvar_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
SetBit(scan_variant_uidx, new_variant_include);
++new_variant_ct;
SetBit(local_variant_ct, local_variant_include);
break;
}
scan_variant_uidx = AdvBoundedTo1Bit(orig_variant_include, scan_variant_uidx + 1, raw_variant_ct);
if (scan_variant_uidx >= chr_end) {
break;
}
scan_bp = variant_bps[scan_variant_uidx];
} while (cur_bp_u == scan_bp);
}
continue;
GlmLocalOpen_skip_variant_and_update_chr:
if (prev_variant_uidx == raw_variant_ct) {
break;
}
chr_fo_idx = GetVariantChrFoIdx(cip, prev_variant_uidx);
prev_chr_code = cip->chr_file_order[chr_fo_idx];
prev_bp = variant_bps[prev_variant_uidx];
chr_end = cip->chr_fo_vidx_start[cip->chr_idx_to_foidx[prev_chr_code] + 1];
}
if (!line_start) {
if (unlikely(TextStreamErrcode2(&txs, &reterr))) {
goto GlmLocalOpen_ret_TSTREAM_FAIL;
}
}
BigstackFinalizeW(local_variant_include, BitCtToWordCt(local_variant_ct));
*local_variant_ctl_ptr = BitCtToWordCt(local_variant_ct);
assert(new_variant_ct <= *variant_ct_ptr);
if (new_variant_ct < *variant_ct_ptr) {
uintptr_t* variant_include_copy;
if (unlikely(bigstack_alloc_w(raw_variant_ctl, &variant_include_copy))) {
goto GlmLocalOpen_ret_NOMEM;
}
memcpy(variant_include_copy, new_variant_include, raw_variant_ctl * sizeof(intptr_t));
*variant_include_ptr = variant_include_copy;
*variant_ct_ptr = new_variant_ct;
}
}
// 3. If not local-cats[0]=, scan first line of local-covar= file to
// determine covariate count.
if (CleanupTextStream2(local_pvar_fname, &txs, &reterr)) {
goto GlmLocalOpen_ret_1;
}
txs_fname = nullptr;
BigstackEndReset(bigstack_end_mark);
uintptr_t loadbuf_size = bigstack_left();
if (loadbuf_size > kMaxLongLine) {
loadbuf_size = kMaxLongLine;
} else if (unlikely(loadbuf_size < kDecompressMinCapacity)) {
// this shouldn't be possible
goto GlmLocalOpen_ret_NOMEM;
}
// don't formally allocate
char* dst = R_CAST(char*, g_bigstack_base);
reterr = TextFileOpenEx(local_covar_fname, kMaxLongLine, loadbuf_size, dst, &local_covar_txf);
if (unlikely(reterr)) {
goto GlmLocalOpen_ret_RFILE_FAIL;
}
const uint32_t local_sample_or_hap_ct = local_sample_ct << ((glm_info_ptr->flags / kfGlmLocalHaps) & 1);
const uint32_t skip_ct = glm_info_ptr->local_first_covar_col? (glm_info_ptr->local_first_covar_col - 1) : 0;
uint32_t local_covar_ct;
if (!glm_info_ptr->local_cat_ct) {
const uint32_t first_nonheader_line_idx = glm_info_ptr->local_header_line_ct + 1;
for (line_idx = 1; line_idx <= first_nonheader_line_idx; ++line_idx) {
line_start = TextFileGet(&local_covar_txf);
if (unlikely(!line_start)) {
if (!TextFileErrcode2(&local_covar_txf, &reterr)) {
snprintf(g_logbuf, kLogbufSize, "Error: %s is empty.\n", local_covar_fname);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
goto GlmLocalOpen_ret_RFILE_FAIL;
}
}
const uint32_t token_ct = CountTokens(line_start);
local_covar_ct = (token_ct - skip_ct) / local_sample_or_hap_ct;
if (unlikely((token_ct < skip_ct) || (local_covar_ct * local_sample_or_hap_ct + skip_ct != token_ct))) {
if (!skip_ct) {
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);
} else {
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);
}
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
if (glm_info_ptr->flags & kfGlmLocalOmitLast) {
if (unlikely(local_covar_ct == 1)) {
logerrputs("Error: --glm 'local-omit-last' modifier cannot be used when there is only one\nlocal covariate.\n");
goto GlmLocalOpen_ret_INCONSISTENT_INPUT;
}
logprintf("--glm local-covar=: %u local covariates present, %u used.\n", local_covar_ct, local_covar_ct - 1);
--local_covar_ct;
} else {
logprintf("--glm local-covar=: %u local covariate%s present.\n", local_covar_ct, (local_covar_ct == 1)? "" : "s");
}
} else {
local_covar_ct = glm_info_ptr->local_cat_ct - 1;
if (unlikely(local_covar_ct * S_CAST(uint64_t, local_sample_or_hap_ct) > (kMaxLongLine / 2) - skip_ct)) {
snprintf(g_logbuf, kLogbufSize, "Error: <# samples/haplotypes in %s> * <# categories - 1> too large (limited to %u).\n", local_covar_fname, kMaxLongLine / 2 - skip_ct);
goto GlmLocalOpen_ret_MALFORMED_INPUT_WW;
}
}
*local_covar_ct_ptr = local_covar_ct;
// 4. Initialize final local-covar reader.
// Quasi-bugfix (6 Jun 2020): even in local-cats case, a header line may
// have a floating point number per (sample, covariate) tuple.
// Permit 24 characters per floating point number instead of 16, since some
// tools dump 15-17 significant digits.
uint64_t enforced_max_line_blen = local_sample_or_hap_ct * 24LLU;
if (!glm_info_ptr->local_cat_ct) {
enforced_max_line_blen *= local_covar_ct + ((glm_info_ptr->flags / kfGlmLocalOmitLast) & 1);
} else {
// Separate ID per (sample, category) possible on header line here.
enforced_max_line_blen *= glm_info_ptr->local_cat_ct;
}
// \r\n
enforced_max_line_blen += 2;
if (unlikely(enforced_max_line_blen > kMaxLongLine)) {
logerrputs("Error: Too many samples/covariates for --glm local-covar=.\n");
goto GlmLocalOpen_ret_MALFORMED_INPUT;
}
if (enforced_max_line_blen < kDecompressMinBlen) {
enforced_max_line_blen = kDecompressMinBlen;
}
uint32_t dst_capacity = enforced_max_line_blen + kDecompressChunkSize;
if (TextFileLinebufLen(&local_covar_txf) > dst_capacity) {
dst_capacity = TextFileLinebufLen(&local_covar_txf);
}
dst_capacity = RoundUpPow2(dst_capacity, kCacheline);
if (bigstack_left() < dst_capacity) {
goto GlmLocalOpen_ret_NOMEM;
}
g_bigstack_base = R_CAST(unsigned char*, &(dst[dst_capacity]));
reterr = TextStreamOpenEx(nullptr, enforced_max_line_blen, dst_capacity, 1, &local_covar_txf, nullptr, local_covar_txsp);
if (unlikely(reterr)) {
TextStreamErrPrint(local_covar_fname, local_covar_txsp);
goto GlmLocalOpen_ret_1;
}
bigstack_mark = g_bigstack_base;
}
while (0) {
GlmLocalOpen_ret_NOMEM:
reterr = kPglRetNomem;
break;
GlmLocalOpen_ret_TSTREAM_XID_FAIL:
if (!TextStreamErrcode(&txs)) {
break;
}
GlmLocalOpen_ret_TSTREAM_FAIL:
TextStreamErrPrint(txs_fname, &txs);
break;
GlmLocalOpen_ret_RFILE_FAIL:
TextFileErrPrint(local_covar_fname, &local_covar_txf);
break;
GlmLocalOpen_ret_MALFORMED_INPUT_WW:
WordWrapB(0);
logerrputsb();
GlmLocalOpen_ret_MALFORMED_INPUT:
reterr = kPglRetMalformedInput;
break;
GlmLocalOpen_ret_MISSING_TOKENS_PVAR:
logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, local_pvar_fname);
reterr = kPglRetMalformedInput;
break;
GlmLocalOpen_ret_INCONSISTENT_INPUT_WW:
WordWrapB(0);
logerrputsb();
GlmLocalOpen_ret_INCONSISTENT_INPUT:
reterr = kPglRetInconsistentInput;
break;
}
GlmLocalOpen_ret_1:
if (txs_fname) {
CleanupTextStream2(txs_fname, &txs, &reterr);
}
CleanupTextFile2(local_covar_fname, &local_covar_txf, &reterr);
BigstackDoubleReset(bigstack_mark, bigstack_end_mark);
return reterr;
}
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) {
const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
double cur_covar_val = covar_vals[first_sample_uidx];
double ctrl_min;
double ctrl_max;
double case_min;
double case_max;
if (IsSet(pheno_cc, first_sample_uidx)) {
ctrl_min = DBL_MAX;
ctrl_max = -DBL_MAX;
case_min = cur_covar_val;
case_max = cur_covar_val;
} else {
ctrl_min = cur_covar_val;
ctrl_max = cur_covar_val;
case_min = DBL_MAX;
case_max = -DBL_MAX;
}
uintptr_t sample_uidx_base;
uintptr_t cur_bits;
BitIter1Start(cur_sample_include, first_sample_uidx + 1, &sample_uidx_base, &cur_bits);
for (uint32_t sample_idx = 1; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
cur_covar_val = covar_vals[sample_uidx];
if (IsSet(pheno_cc, sample_uidx)) {
if (cur_covar_val < case_min) {
if ((ctrl_min < case_max) && (cur_covar_val < ctrl_max)) {
return 0;
}
case_min = cur_covar_val;
} else if (cur_covar_val > case_max) {
if ((ctrl_max > case_min) && (cur_covar_val > ctrl_min)) {
return 0;
}
case_max = cur_covar_val;
}
} else {
if (cur_covar_val < ctrl_min) {
if ((case_min < ctrl_max) && (cur_covar_val < case_max)) {
return 0;
}
ctrl_min = cur_covar_val;
} else if (cur_covar_val > ctrl_max) {
if ((case_max > ctrl_min) && (cur_covar_val > case_min)) {
return 0;
}
ctrl_max = cur_covar_val;
}
}
}
if ((case_min > ctrl_max) || (ctrl_min > case_max)) {
return 2;
}
if (covar_val_keep_ptr) {
*covar_val_keep_ptr = (case_min == ctrl_max)? case_min : case_max;
}
return 1;
}
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) {
const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
const uint32_t nonnull_cat_ct = covar_col->nonnull_category_ct;
const uint32_t cur_word_ct = 1 + nonnull_cat_ct / kBitsPerWordD2;
ZeroWArr(cur_word_ct, cat_covar_wkspace);
const uint32_t* covar_cats = covar_col->data.cat;
// If no remaining categories have both cases and controls, we have complete
// separation.
// If some do and some do not, we have quasi-complete separation, and when
// performing ordinary logistic regression, we must remove samples in the
// all-case and/or all-control categories.
uintptr_t sample_uidx_base;
uintptr_t cur_bits;
BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
const uint32_t cur_cat_idx = covar_cats[sample_uidx];
// Odd bits represent presence of a case, even bits represent presence of a
// control.
const uint32_t is_case = IsSet(pheno_cc, sample_uidx);
SetBit(cur_cat_idx * 2 + is_case, cat_covar_wkspace);
}
uint32_t case_and_ctrl_cat_ct = 0;
uint32_t pheno_by_cat_ct = 0;
for (uint32_t widx = 0; widx != cur_word_ct; ++widx) {
const uintptr_t cur_word = cat_covar_wkspace[widx];
case_and_ctrl_cat_ct += Popcount01Word(Word11(cur_word));
pheno_by_cat_ct += PopcountWord(cur_word);
}
if (!case_and_ctrl_cat_ct) {
return 2;
}
if (case_and_ctrl_cat_ct * 2 == pheno_by_cat_ct) {
// all categories contain both cases and controls.
return 0;
}
if (case_and_ctrl_cat_ct_ptr) {
*case_and_ctrl_cat_ct_ptr = case_and_ctrl_cat_ct;
}
return 1;
}
// Returns 0 if not separated, 1 if quasi-separated, 2 if fully separated.
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) {
if (sample_ct < 2) {
return 2;
}
if (covar_col->type_code == kPhenoDtypeOther) {
// local covariate, no precomputation possible
return 0;
}
if (covar_col->type_code == kPhenoDtypeQt) {
return CheckForSeparatedQtCovar(pheno_cc, cur_sample_include, covar_col->data.qt, sample_ct, nullptr);
}
return CheckForSeparatedCatCovar(pheno_cc, cur_sample_include, covar_col, sample_ct, nullptr, cat_covar_wkspace);
}
// Returns 1 if phenotype fully separates the covariate, and the non-Firth
// logistic regression should be aborted.
// Otherwise, if we have quasi-separation, use Stata approach of throwing out
// the covariate, and keeping only samples which have the one covariate value
// present in both cases and controls.
// Note that covar_ct is not a parameter; caller is responsible for
// re-popcounting covar_include.
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) {
uint32_t sample_ct = *sample_ct_ptr;
if (sample_ct < 2) {
return 1;
}
const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
if (cur_covar_col->type_code == kPhenoDtypeOther) {
return 0;
}
const uint32_t first_sample_uidx = AdvTo1Bit(cur_sample_include, 0);
if (cur_covar_col->type_code == kPhenoDtypeQt) {
const double* covar_vals = cur_covar_col->data.qt;
double covar_val_keep;
const uint32_t separation_type = CheckForSeparatedQtCovar(pheno_cc, cur_sample_include, covar_vals, sample_ct, &covar_val_keep);
if (separation_type != 1) {
return separation_type / 2;
}
uintptr_t sample_uidx_base;
uintptr_t cur_bits;
BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
if (covar_vals[sample_uidx] != covar_val_keep) {
ClearBit(sample_uidx, cur_sample_include);
}
}
*sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
ClearBit(covar_uidx, covar_include);
return 0;
}
uint32_t case_and_ctrl_cat_ct;
const uint32_t separation_type = CheckForSeparatedCatCovar(pheno_cc, cur_sample_include, cur_covar_col, sample_ct, &case_and_ctrl_cat_ct, cat_covar_wkspace);
if (separation_type != 1) {
return separation_type / 2;
}
// more than one category contains both cases and controls (so we don't need
// to remove the categorical covariate), but at least one does not, so we
// still have to prune some samples.
const uint32_t nonnull_cat_ct = cur_covar_col->nonnull_category_ct;
const uint32_t cur_word_ct = 1 + nonnull_cat_ct / kBitsPerWordD2;
for (uint32_t widx = 0; widx != cur_word_ct; ++widx) {
const uintptr_t cur_word = cat_covar_wkspace[widx];
cat_covar_wkspace[widx] = Word11(cur_word);
}
uintptr_t sample_uidx_base;
uintptr_t cur_bits;
BitIter1Start(cur_sample_include, first_sample_uidx, &sample_uidx_base, &cur_bits);
const uint32_t* covar_cats = cur_covar_col->data.cat;
// bugfix (7 Jul 2018): this needs to check sample_idx, not sample_uidx
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uintptr_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_bits);
if (!IsSet(cat_covar_wkspace, covar_cats[sample_uidx] * 2)) {
ClearBit(sample_uidx, cur_sample_include);
}
}
*sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
if (case_and_ctrl_cat_ct == 1) {
ClearBit(covar_uidx, covar_include);
}
return 0;
}
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) {
unsigned char* bigstack_mark = g_bigstack_base;
BoolErr reterr = 0;
{
// bugfix (11 Mar 2020): if no covariates provided, covar_include ==
// nullptr is possible, and covar_include[0] dereference below is optimized
// out by some but not all compilers.
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct);
if (!covar_include) {
*sample_ct_ptr = PopcountWords(cur_sample_include, raw_sample_ctl);
goto GlmDetermineCovars_ret_NOCOVAR;
}
uintptr_t* sample_include_backup;
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include_backup))) {
goto GlmDetermineCovars_ret_NOMEM;
}
memcpy(sample_include_backup, cur_sample_include, raw_sample_ctl * sizeof(intptr_t));
memcpy(covar_include, initial_covar_include, raw_covar_ctl * sizeof(intptr_t));
// bugfix (28 Apr 2018): initial_covar_include can contain an extra sex set
// bit at the end.
if (PopcountWords(initial_covar_include, raw_covar_ctl) > initial_covar_ct) {
uintptr_t last_word = covar_include[raw_covar_ctl - 1];
const uint32_t highest_set_bit_idx = bsrw(last_word);
covar_include[raw_covar_ctl - 1] -= k1LU << highest_set_bit_idx;
}
// 1. Determine samples for which all phenotype/covariate values are
// present, then provisionally remove the covariates which are constant
// over that set in linear case, or produce separation in logistic case
uintptr_t covar_uidx_base = 0;
uintptr_t cur_bits = covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
if (covar_cols[covar_uidx].nonmiss) {
BitvecAnd(covar_cols[covar_uidx].nonmiss, raw_sample_ctl, cur_sample_include);
}
}
uint32_t prev_sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
covar_uidx_base = 0;
cur_bits = initial_covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
if ((covar_cols[covar_uidx].type_code != kPhenoDtypeOther) && IsConstCovar(&(covar_cols[covar_uidx]), cur_sample_include, raw_sample_ct)) {
ClearBit(covar_uidx, covar_include);
}
}
uint32_t covar_ct = PopcountWords(covar_include, raw_covar_ctl);
if (covar_ct != initial_covar_ct) {
// 2. If any covariates were removed, redetermine the samples for which
// all phenotype/covariate values are present. If there are more than
// before, add back any provisionally removed covariates which don't
// have any missing values in the new sample set, and are now
// nonconstant.
// Categorical covariates should behave just like they had been
// pre-split into n-1 0/1 indicator variables.
memcpy(cur_sample_include, sample_include_backup, raw_sample_ctl * sizeof(intptr_t));
covar_uidx_base = 0;
cur_bits = covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
if (covar_cols[covar_uidx].nonmiss) {
BitvecAnd(covar_cols[covar_uidx].nonmiss, raw_sample_ctl, cur_sample_include);
}
}
uint32_t new_sample_ct = PopcountWords(cur_sample_include, raw_sample_ctl);
if (new_sample_ct > prev_sample_ct) {
prev_sample_ct = new_sample_ct;
covar_uidx_base = 0;
cur_bits = initial_covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != initial_covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(initial_covar_include, &covar_uidx_base, &cur_bits);
if (!IsSet(covar_include, covar_uidx)) {
const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
if (PopcountWordsIntersect(cur_sample_include, cur_covar_col->nonmiss, raw_sample_ctl) == prev_sample_ct) {
if (!IsConstCovar(cur_covar_col, cur_sample_include, raw_sample_ct)) {
SetBit(covar_uidx, covar_include);
}
}
}
}
covar_ct = PopcountWords(covar_include, raw_covar_ctl);
}
}
if (!covar_ct) {
*sample_ct_ptr = prev_sample_ct;
goto GlmDetermineCovars_ret_NOCOVAR;
}
if (prev_sample_ct < 3) {
goto GlmDetermineCovars_ret_SKIP;
}
// 3. if quantitative trait, remove samples corresponding to single-element
// categories or constant-except-for-one-sample regular covariates.
uint32_t sample_ct = prev_sample_ct;
uint32_t extra_cat_ct = 0;
BigstackReset(sample_include_backup);
if (!pheno_cc) {
uintptr_t* cat_one_obs = nullptr;
uintptr_t* cat_two_or_more_obs = nullptr;
uint32_t* cat_first_sample_uidxs = nullptr;
if (covar_max_nonnull_cat_ct) {
const uint32_t max_cat_ctl = 1 + (covar_max_nonnull_cat_ct / kBitsPerWord);
if (unlikely(bigstack_alloc_w(max_cat_ctl, &cat_one_obs) ||
bigstack_alloc_w(max_cat_ctl, &cat_two_or_more_obs) ||
bigstack_alloc_u32(covar_max_nonnull_cat_ct + 1, &cat_first_sample_uidxs))) {
goto GlmDetermineCovars_ret_NOMEM;
}
}
do {
prev_sample_ct = sample_ct;
covar_uidx_base = 0;
cur_bits = covar_include[0];
extra_cat_ct = 0;
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
if (cur_covar_col->type_code == kPhenoDtypeOther) {
continue;
}
// bugfix (31 Aug 2018): sample_uidx_base/cur_sample_include_bits
// must be reset on each iteration
uintptr_t sample_uidx_base = 0;
uintptr_t cur_sample_include_bits = cur_sample_include[0];
if (cur_covar_col->type_code == kPhenoDtypeQt) {
const double* pheno_vals = cur_covar_col->data.qt;
const uint32_t first_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
double common_pheno_val = pheno_vals[first_sample_uidx];
const uint32_t second_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
const double second_pheno_val = pheno_vals[second_sample_uidx];
uint32_t sample_idx = 2;
uint32_t sample_uidx_remove;
if (second_pheno_val != common_pheno_val) {
sample_uidx_remove = second_sample_uidx;
const uint32_t third_sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
const double third_pheno_val = pheno_vals[third_sample_uidx];
if (third_pheno_val == second_pheno_val) {
common_pheno_val = second_pheno_val;
sample_uidx_remove = first_sample_uidx;
} else if (third_pheno_val != common_pheno_val) {
continue;
}
sample_idx = 3;
} else {
sample_uidx_remove = UINT32_MAX;
}
// minor bugfix (8 Jul 2018): forgot to increment sample_uidx on
// first loop iteration here
// sample_ct >= 3 guaranteed
for (; sample_idx != sample_ct; ++sample_idx) {
const uint32_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
if (pheno_vals[sample_uidx] != common_pheno_val) {
if (sample_uidx_remove == UINT32_MAX) {
sample_uidx_remove = sample_uidx;
} else {
break;
}
}
}
if (sample_idx == sample_ct) {
if (sample_uidx_remove != UINT32_MAX) {
if (--sample_ct == 2) {
goto GlmDetermineCovars_ret_SKIP;
}
ClearBit(sample_uidx_remove, cur_sample_include);
} else {
// constant covariate, remove it
ClearBit(covar_uidx, covar_include);
}
}
} else {
const uint32_t cur_nonnull_cat_ct = cur_covar_col->nonnull_category_ct;
const uint32_t cur_cat_ctl = 1 + (cur_nonnull_cat_ct / kBitsPerWord);
ZeroWArr(cur_cat_ctl, cat_one_obs);
ZeroWArr(cur_cat_ctl, cat_two_or_more_obs);
const uint32_t* pheno_vals = cur_covar_col->data.cat;
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) {
const uint32_t sample_uidx = BitIter1(cur_sample_include, &sample_uidx_base, &cur_sample_include_bits);
const uint32_t cur_cat_idx = pheno_vals[sample_uidx];
if (!IsSet(cat_two_or_more_obs, cur_cat_idx)) {
if (IsSet(cat_one_obs, cur_cat_idx)) {
SetBit(cur_cat_idx, cat_two_or_more_obs);
} else {
SetBit(cur_cat_idx, cat_one_obs);
cat_first_sample_uidxs[cur_cat_idx] = sample_uidx;
}
}
}
for (uint32_t widx = 0; widx != cur_cat_ctl; ++widx) {
uintptr_t cur_word = cat_one_obs[widx] & (~cat_two_or_more_obs[widx]);
if (cur_word) {
const uint32_t* cat_first_sample_uidxs_iter = &(cat_first_sample_uidxs[widx * kBitsPerWord]);
do {
const uint32_t cat_idx_lowbits = ctzw(cur_word);
// this could be moved out of the loop, but unlikely to be
// profitable...
--sample_ct;
ClearBit(cat_first_sample_uidxs_iter[cat_idx_lowbits], cur_sample_include);
cur_word &= cur_word - 1;
} while (cur_word);
}
}
if (sample_ct < 3) {
goto GlmDetermineCovars_ret_SKIP;
}
uint32_t remaining_cat_ct = PopcountWords(cat_two_or_more_obs, cur_cat_ctl);
if (remaining_cat_ct <= 1) {
// now a constant covariate, remove it
ClearBit(covar_uidx, covar_include);
} else {
extra_cat_ct += remaining_cat_ct - 2;
}
}
}
covar_ct = PopcountWords(covar_include, raw_covar_ctl);
} while (sample_ct < prev_sample_ct);
} else {
uintptr_t* cat_covar_wkspace;
if (unlikely(bigstack_alloc_w(1 + (covar_max_nonnull_cat_ct / kBitsPerWordD2), &cat_covar_wkspace))) {
goto GlmDetermineCovars_ret_NOMEM;
}
if (!is_always_firth) {
if (!is_sometimes_firth) {
do {
prev_sample_ct = sample_ct;
// bugfix (23 Nov 2023): these need to be reinitialized when the
// while condition is actually true
covar_uidx_base = 0;
cur_bits = covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
if (CheckForAndHandleSeparatedCovar(pheno_cc, covar_cols, raw_sample_ctl, covar_uidx, cur_sample_include, covar_include, &sample_ct, cat_covar_wkspace)) {
*separation_found_ptr = 1;
goto GlmDetermineCovars_ret_SKIP;
}
}
covar_ct = PopcountWords(covar_include, raw_covar_ctl);
} while (sample_ct < prev_sample_ct);
} else {
covar_uidx_base = 0;
cur_bits = covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
if (CheckForSeparatedCovar(pheno_cc, cur_sample_include, &(covar_cols[covar_uidx]), sample_ct, cat_covar_wkspace)) {
*separation_found_ptr = 1;
break;
}
}
}
}
// now count extra categories
covar_uidx_base = 0;
cur_bits = covar_include[0];
extra_cat_ct = 0;
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
const PhenoCol* cur_covar_col = &(covar_cols[covar_uidx]);
if (cur_covar_col->type_code == kPhenoDtypeCat) {
const uint32_t remaining_cat_ct = IdentifyRemainingCats(cur_sample_include, cur_covar_col, sample_ct, cat_covar_wkspace);
if (remaining_cat_ct > 2) {
extra_cat_ct += remaining_cat_ct - 2;
}
}
}
}
*sample_ct_ptr = sample_ct;
*covar_ct_ptr = covar_ct;
*extra_cat_ct_ptr = extra_cat_ct;
}
while (0) {
GlmDetermineCovars_ret_NOMEM:
reterr = 1;
break;
GlmDetermineCovars_ret_SKIP:
*sample_ct_ptr = 0;
GlmDetermineCovars_ret_NOCOVAR:
*covar_ct_ptr = 0;
break;
}
BigstackReset(bigstack_mark);
return reterr;
}
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) {
const uint32_t first_covar_pred_idx = 2 + domdev_present;
const uint32_t domdev_present_p1 = domdev_present + 1;
uint32_t first_interaction_pred_read_idx = 0;
uint32_t first_interaction_pred_write_idx = 0;
if (add_interactions) {
first_interaction_pred_read_idx = first_covar_pred_idx + raw_covar_ct;
first_interaction_pred_write_idx = first_covar_pred_idx + covar_ct;
}
const uint32_t write_idx_ct = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
const uint32_t write_idx_ctl = BitCtToWordCt(write_idx_ct);
ZeroWArr(write_idx_ctl, new_params_or_tests);
// intercept, additive, domdev
new_params_or_tests[0] = raw_params_or_tests[0] & (3 + 4 * domdev_present);
// bugfix (26 Jun 2019): covar_include == nullptr when covar_ct == 0
if (covar_ct) {
uintptr_t covar_uidx_base = 0;
uintptr_t cur_bits = covar_include[0];
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const uintptr_t covar_uidx = BitIter1(covar_include, &covar_uidx_base, &cur_bits);
if (IsSet(raw_params_or_tests, first_covar_pred_idx + covar_uidx)) {
SetBit(first_covar_pred_idx + covar_idx, new_params_or_tests);
}
if (add_interactions) {
if (IsSet(raw_params_or_tests, first_interaction_pred_read_idx + domdev_present_p1 * covar_uidx)) {
SetBit(first_interaction_pred_write_idx + domdev_present_p1 * covar_idx, new_params_or_tests);
}
if (domdev_present) {
if (IsSet(raw_params_or_tests, first_interaction_pred_read_idx + 2 * covar_uidx + 1)) {
SetBit(first_interaction_pred_write_idx + 2 * covar_idx + 1, new_params_or_tests);
}
}
}
}
}
return PopcountWords(new_params_or_tests, write_idx_ctl);
}
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) {
const GlmErrcode errcode = GetGlmErrCode(glm_err);
const char* msg_start = skip_invalid_pheno? "Note: Skipping " : "Error: Cannot proceed with ";
if (errcode == kGlmErrcodeUnstableScale) {
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" : "");
} else if (errcode == kGlmErrcodeVifInfinite) {
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.");
} else if (errcode == kGlmErrcodeLogisticConvergeFail) {
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);
} else if (errcode == kGlmErrcodeFirthConvergeFail) {
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);
} else {
const char* covar_name1 = covar_names[GetGlmErrArg1(glm_err) + local_covar_ct];
if (errcode == kGlmErrcodeVifTooHigh) {
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.");
} else {
const char* covar_name2 = covar_names[GetGlmErrArg2(glm_err) + local_covar_ct];
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.");
}
}
WordWrapB(0);
if (skip_invalid_pheno) {
logputsb();
} else {
logerrputsb();
}
}
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) {
const uint32_t model_dominant = (glm_flags / kfGlmDominant) & 1;
const uint32_t model_recessive = (glm_flags / kfGlmRecessive) & 1;
const uint32_t model_hetonly = (glm_flags / kfGlmHetonly) & 1;
const uint32_t is_hethom = (glm_flags / kfGlmHethom) & 1;
const uint32_t domdev_present = (glm_flags & kfGlmGenotypic) || is_hethom;
char main_effect[4];
if (model_dominant) {
memcpy(main_effect, "DOMx", 4);
} else if (model_recessive) {
memcpy(main_effect, "RECx", 4);
} else if (model_hetonly) {
memcpy(main_effect, "HETx", 4);
} else if (is_hethom) {
memcpy(main_effect, "HOMx", 4);
} else {
memcpy(main_effect, "ADDx", 4);
}
const uint32_t include_intercept = (glm_flags / kfGlmIntercept) & 1;
const uint32_t include_main_effect = (!parameter_subset) || IsSet(parameter_subset, 1);
char domdev_str[8];
uint32_t domdev_slen = 7;
if (!is_hethom) {
snprintf(domdev_str, 8, "DOMDEVx");
} else {
snprintf(domdev_str, 8, "HETx");
domdev_slen = 4;
}
const uint32_t joint_test = domdev_present || user_constraint_ct;
if (glm_flags & kfGlmHideCovar) {
const uint32_t biallelic_reported_test_ct = include_intercept + include_main_effect + domdev_present + joint_test;
char* test_name_buf_iter;
if (unlikely(bigstack_alloc_kcp(biallelic_reported_test_ct, cur_test_names_ptr) ||
bigstack_alloc_c(64, &test_name_buf_iter))) {
return 1;
}
const char** cur_test_names = *cur_test_names_ptr;
uint32_t write_idx = 0;
if (include_intercept) {
char* iter_next = memcpya_k(test_name_buf_iter, "INTERCEPT", 10);
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
if (include_main_effect) {
char* iter_next = memcpyax_k(test_name_buf_iter, main_effect, 3, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
if (domdev_present) {
char* iter_next = memcpyax(test_name_buf_iter, domdev_str, domdev_slen - 1, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
if (joint_test) {
if (user_constraint_ct) {
char* iter_next = strcpya_k(test_name_buf_iter, "USER_");
iter_next = u32toa(user_constraint_ct, iter_next);
snprintf(iter_next, 64 - 10 - 4 - 8 - 15, "DF");
} else {
snprintf(test_name_buf_iter, 64 - 10 - 4 - 8, "GENO_2DF");
}
cur_test_names[write_idx++] = test_name_buf_iter;
}
assert(write_idx == biallelic_reported_test_ct);
return 0;
}
const uint32_t add_interactions = (glm_flags / kfGlmInteraction) & 1;
const uint32_t domdev_present_p1 = domdev_present + 1;
uint32_t biallelic_predictor_ct_base = 2 + domdev_present + covar_ct * (1 + add_interactions * domdev_present_p1);
uint32_t biallelic_predictor_ct = biallelic_predictor_ct_base;
if (parameter_subset) {
biallelic_predictor_ct = PopcountWords(parameter_subset, BitCtToWordCt(biallelic_predictor_ct_base));
}
const uint32_t biallelic_reported_test_ct = biallelic_predictor_ct + joint_test + include_intercept - 1;
uintptr_t test_name_buf_alloc = 64;
if (add_interactions) {
// don't bother optimizing this for parameter_subset case for now
uintptr_t covar_name_total_blen = covar_ct;
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
covar_name_total_blen += strlen(covar_names[covar_idx]);
}
// ADDx[covar name], etc.
test_name_buf_alloc += 4 * covar_ct + covar_name_total_blen;
if (is_hethom) {
// HETx
test_name_buf_alloc += 4 * covar_ct + covar_name_total_blen;
} else if (domdev_present) {
// DOMDEVx
test_name_buf_alloc += 7 * covar_ct + covar_name_total_blen;
}
}
char* test_name_buf_iter;
if (unlikely(bigstack_alloc_kcp(biallelic_reported_test_ct, cur_test_names_ptr) ||
bigstack_alloc_c(test_name_buf_alloc, &test_name_buf_iter))) {
return 1;
}
const char** cur_test_names = *cur_test_names_ptr;
uint32_t write_idx = 0;
if (include_intercept) {
char* iter_next = memcpya_k(test_name_buf_iter, "INTERCEPT", 10);
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
if (include_main_effect) {
char* iter_next = memcpyax_k(test_name_buf_iter, main_effect, 3, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
if (domdev_present) {
char* iter_next = memcpyax(test_name_buf_iter, domdev_str, domdev_slen - 1, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
uint32_t pred_uidx = 2 + domdev_present;
// bugfix (16 Aug 2021): sex + interaction?
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx, ++pred_uidx) {
if (parameter_subset && (!IsSet(parameter_subset, pred_uidx))) {
continue;
}
// just point to the existing string, its lifetime is sufficient
cur_test_names[write_idx++] = covar_names[covar_idx];
}
if (add_interactions) {
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) {
const char* cur_covar_name = covar_names[covar_idx];
if ((!parameter_subset) || IsSet(parameter_subset, pred_uidx)) {
char* iter_next = memcpya(test_name_buf_iter, main_effect, 4);
iter_next = strcpyax(iter_next, cur_covar_name, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
++pred_uidx;
if (domdev_present) {
if ((!parameter_subset) || IsSet(parameter_subset, pred_uidx)) {
char* iter_next = memcpya(test_name_buf_iter, domdev_str, domdev_slen);
iter_next = strcpyax(iter_next, cur_covar_name, '\0');
cur_test_names[write_idx++] = test_name_buf_iter;
test_name_buf_iter = iter_next;
}
++pred_uidx;
}
}
}
if (joint_test) {
if (user_constraint_ct) {
char* iter_next = strcpya_k(test_name_buf_iter, "USER_");
iter_next = u32toa(user_constraint_ct, iter_next);
snprintf(iter_next, 64 - 10 - 4 - 8 - 15, "DF");
} else {
snprintf(test_name_buf_iter, 64 - 10 - 4 - 8, "GENO_2DF");
}
cur_test_names[write_idx++] = test_name_buf_iter;
}
assert(write_idx == biallelic_reported_test_ct);
return 0;
}
static const double kSexMaleToCovarD[2] = {2.0, 1.0};
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) {
ZeroWArr(biallelic_raw_predictor_ctl, parameter_subset_reshuffle_buf);
CopyBitarrRange(parameters_or_tests, 0, 0, first_interaction_pred_uidx - 1, parameter_subset_reshuffle_buf);
// bugfix (16 Aug 2021): raw_covar_ct includes sex
const uint32_t raw_nonsex_interaction_ct = (raw_covar_ct - 1) * (domdev_present + 1);
CopyBitarrRange(parameters_or_tests, first_interaction_pred_uidx - 1, first_interaction_pred_uidx, raw_nonsex_interaction_ct, parameter_subset_reshuffle_buf);
const uint32_t first_sex_parameter_idx = first_interaction_pred_uidx - 1 + raw_nonsex_interaction_ct;
if (IsSet(parameters_or_tests, first_sex_parameter_idx)) {
SetBit(first_interaction_pred_uidx - 1, parameter_subset_reshuffle_buf);
}
if (IsSet(parameters_or_tests, first_sex_parameter_idx + 1)) {
SetBit(first_sex_parameter_idx + 1, parameter_subset_reshuffle_buf);
}
if (domdev_present && IsSet(parameters_or_tests, first_sex_parameter_idx + 2)) {
SetBit(first_sex_parameter_idx + 2, parameter_subset_reshuffle_buf);
}
memcpy(parameters_or_tests, parameter_subset_reshuffle_buf, biallelic_raw_predictor_ctl * sizeof(intptr_t));
}
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) {
unsigned char* bigstack_mark = g_bigstack_base;
unsigned char* bigstack_end_mark = g_bigstack_end;
// We may temporarily clear the cip->haploid_mask bit for chrX if all samples
// are female. (This is only checked on function entry, it is not rechecked
// on a per-phenotype basis.) Track this here so we can reverse it on
// function exit.
uint32_t x_fully_diploid = 0;
LlStr* gwas_ssf_ll = nullptr;
PglErr reterr = kPglRetSuccess;
TextStream local_covar_txs;
TokenStream tks;
PreinitTextStream(&local_covar_txs);
PreinitTokenStream(&tks);
GlmCtx common;
GlmLogisticCtx logistic_ctx;
GlmLinearCtx linear_ctx;
logistic_ctx.common = &common;
linear_ctx.common = &common;
{
if (unlikely(!pheno_ct)) {
logerrputs("Error: No phenotypes loaded.\n");
goto GlmMain_ret_INCONSISTENT_INPUT;
}
if (unlikely(orig_sample_ct < 2)) {
logerrputs("Error: --glm requires at least two samples.\n");
goto GlmMain_ret_DEGENERATE_DATA;
}
assert(orig_variant_ct);
// common linear/logistic initialization
const GlmFlags glm_flags = glm_info_ptr->flags;
const uintptr_t* early_variant_include = orig_variant_include;
uint32_t* local_sample_uidx_order = nullptr;
uintptr_t* local_variant_include = nullptr;
uint32_t variant_ct = orig_variant_ct;
uint32_t local_sample_ct = 0;
uint32_t local_variant_ctl = 0;
uint32_t local_covar_ct = 0;
if (local_covar_fname) {
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);
if (unlikely(reterr)) {
goto GlmMain_ret_1;
}
}
common.glm_flags = glm_flags;
common.dosage_presents = nullptr;
common.dosage_mains = nullptr;
const uint32_t output_zst = (glm_flags / kfGlmZs) & 1;
const uint32_t perm_adapt = (glm_flags / kfGlmPerm) & 1;
const uint32_t perms_total = perm_adapt? aperm_ptr->max : glm_info_ptr->mperm_ct;
//