| 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 |
|
| 18 |
#include "include/plink2_stats.h" // HweThresh(), etc. |
| 19 |
#include "plink2_compress_stream.h" |
| 20 |
#include "plink2_filter.h" |
| 21 |
#include "plink2_random.h" |
| 22 |
|
| 23 |
#ifdef __cplusplus |
| 24 |
namespace plink2 { |
| 25 |
#endif |
| 26 |
|
| 27 |
void InitExtractColCond(ExtractColCondInfo* eccip) { |
| 28 |
eccip->params = nullptr; |
| 29 |
eccip->match_flattened = nullptr; |
| 30 |
eccip->mismatch_flattened = nullptr; |
| 31 |
eccip->match_substr = 0; |
| 32 |
eccip->min = 0.0; |
| 33 |
eccip->max = DBL_MAX; |
| 34 |
} |
| 35 |
|
| 36 |
void CleanupExtractColCond(ExtractColCondInfo* eccip) { |
| 37 |
free_cond(eccip->params); |
| 38 |
free_cond(eccip->match_flattened); |
| 39 |
free_cond(eccip->mismatch_flattened); |
| 40 |
} |
| 41 |
|
| 42 |
PglErr FromToFlag(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const char* varid_from, const char* varid_to, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, uintptr_t* variant_include, ChrInfo* cip, uint32_t* variant_ct_ptr) { |
| 43 |
PglErr reterr = kPglRetSuccess; |
| 44 |
{ |
| 45 |
if (!(*variant_ct_ptr)) { |
| 46 |
goto FromToFlag_ret_1; |
| 47 |
} |
| 48 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 49 |
uint32_t variant_uidx_start = UINT32_MAX; |
| 50 |
if (varid_from) { |
| 51 |
uint32_t cur_llidx; |
| 52 |
variant_uidx_start = VariantIdDupHtableFind(varid_from, variant_ids, variant_id_htable, htable_dup_base, strlen(varid_from), variant_id_htable_size, max_variant_id_slen, &cur_llidx); |
| 53 |
if (unlikely(variant_uidx_start == UINT32_MAX)) { |
| 54 |
snprintf(g_logbuf, kLogbufSize, "Error: --from variant '%s' not found.\n", varid_from); |
| 55 |
goto FromToFlag_ret_INCONSISTENT_INPUT_WW; |
| 56 |
} |
| 57 |
// do *not* check variant_include here. variant ID uniqueness should not |
| 58 |
// be dependent on the order in which filters are applied. |
| 59 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 60 |
snprintf(g_logbuf, kLogbufSize, "Error: --from variant ID '%s' appears multiple times.\n", varid_from); |
| 61 |
goto FromToFlag_ret_INCONSISTENT_INPUT_WW; |
| 62 |
} |
| 63 |
chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx_start); |
| 64 |
} |
| 65 |
uint32_t variant_uidx_end = 0; |
| 66 |
if (varid_to) { |
| 67 |
uint32_t cur_llidx; |
| 68 |
variant_uidx_end = VariantIdDupHtableFind(varid_to, variant_ids, variant_id_htable, htable_dup_base, strlen(varid_to), variant_id_htable_size, max_variant_id_slen, &cur_llidx); |
| 69 |
if (unlikely(variant_uidx_end == UINT32_MAX)) { |
| 70 |
snprintf(g_logbuf, kLogbufSize, "Error: --to variant '%s' not found.\n", varid_to); |
| 71 |
goto FromToFlag_ret_INCONSISTENT_INPUT_WW; |
| 72 |
} |
| 73 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 74 |
snprintf(g_logbuf, kLogbufSize, "Error: --to variant ID '%s' appears multiple times.\n", varid_to); |
| 75 |
goto FromToFlag_ret_INCONSISTENT_INPUT_WW; |
| 76 |
} |
| 77 |
uint32_t chr_fo_idx2 = GetVariantChrFoIdx(cip, variant_uidx_end); |
| 78 |
if (variant_uidx_start == UINT32_MAX) { |
| 79 |
chr_fo_idx = chr_fo_idx2; |
| 80 |
variant_uidx_start = cip->chr_fo_vidx_start[chr_fo_idx]; |
| 81 |
} else { |
| 82 |
if (unlikely(chr_fo_idx != chr_fo_idx2)) { |
| 83 |
logerrputs("Error: --from and --to variants are not on the same chromosome.\n"); |
| 84 |
goto FromToFlag_ret_INCONSISTENT_INPUT; |
| 85 |
} |
| 86 |
if (variant_uidx_start > variant_uidx_end) { |
| 87 |
// permit order to be reversed |
| 88 |
uint32_t uii = variant_uidx_start; |
| 89 |
variant_uidx_start = variant_uidx_end; |
| 90 |
variant_uidx_end = uii; |
| 91 |
} |
| 92 |
} |
| 93 |
++variant_uidx_end; // convert to half-open interval |
| 94 |
} else { |
| 95 |
variant_uidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 96 |
} |
| 97 |
if (variant_uidx_start) { |
| 98 |
ClearBitsNz(0, variant_uidx_start, variant_include); |
| 99 |
} |
| 100 |
if (variant_uidx_end < raw_variant_ct) { |
| 101 |
ClearBitsNz(variant_uidx_end, raw_variant_ct, variant_include); |
| 102 |
} |
| 103 |
ZeroWArr(kChrMaskWords, cip->chr_mask); |
| 104 |
SetBit(cip->chr_file_order[chr_fo_idx], cip->chr_mask); |
| 105 |
const uint32_t new_variant_ct = PopcountBitRange(variant_include, variant_uidx_start, variant_uidx_end); |
| 106 |
logprintf("--from/--to: %u variant%s remaining.\n", new_variant_ct, (new_variant_ct == 1)? "" : "s"); |
| 107 |
*variant_ct_ptr = new_variant_ct; |
| 108 |
} |
| 109 |
while (0) { |
| 110 |
FromToFlag_ret_INCONSISTENT_INPUT_WW: |
| 111 |
WordWrapB(0); |
| 112 |
logerrputsb(); |
| 113 |
FromToFlag_ret_INCONSISTENT_INPUT: |
| 114 |
reterr = kPglRetInconsistentInput; |
| 115 |
break; |
| 116 |
} |
| 117 |
FromToFlag_ret_1: |
| 118 |
return reterr; |
| 119 |
} |
| 120 |
|
| 121 |
PglErr SnpFlag(const uint32_t* variant_bps, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const char* varid_snp, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, uint32_t do_exclude, int32_t window_bp, uintptr_t* variant_include, ChrInfo* cip, uint32_t* variant_ct_ptr) { |
| 122 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 123 |
PglErr reterr = kPglRetSuccess; |
| 124 |
{ |
| 125 |
if (!(*variant_ct_ptr)) { |
| 126 |
goto SnpFlag_ret_1; |
| 127 |
} |
| 128 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 129 |
uint32_t cur_llidx; |
| 130 |
uint32_t variant_uidx = VariantIdDupHtableFind(varid_snp, variant_ids, variant_id_htable, htable_dup_base, strlen(varid_snp), variant_id_htable_size, max_variant_id_slen, &cur_llidx); |
| 131 |
if (unlikely(variant_uidx == UINT32_MAX)) { |
| 132 |
snprintf(g_logbuf, kLogbufSize, "Error: --%ssnp variant '%s' not found.\n", do_exclude? "exclude-" : "", varid_snp); |
| 133 |
goto SnpFlag_ret_INCONSISTENT_INPUT_WW; |
| 134 |
} |
| 135 |
if (window_bp == -1) { |
| 136 |
// duplicates ok |
| 137 |
|
| 138 |
uintptr_t* seen_uidxs; |
| 139 |
// not actually necessary in --exclude-snp case, but this is still fast |
| 140 |
// enough relative to hash table construction that there's no point in |
| 141 |
// complicating the code further to conditionally optimize this out |
| 142 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &seen_uidxs))) { |
| 143 |
goto SnpFlag_ret_NOMEM; |
| 144 |
} |
| 145 |
for (; ; cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 146 |
SetBit(variant_uidx, seen_uidxs); |
| 147 |
if (cur_llidx == UINT32_MAX) { |
| 148 |
break; |
| 149 |
} |
| 150 |
variant_uidx = htable_dup_base[cur_llidx]; |
| 151 |
} |
| 152 |
if (do_exclude) { |
| 153 |
BitvecInvmask(seen_uidxs, raw_variant_ctl, variant_include); |
| 154 |
} else { |
| 155 |
BitvecAnd(seen_uidxs, raw_variant_ctl, variant_include); |
| 156 |
} |
| 157 |
} else { |
| 158 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 159 |
snprintf(g_logbuf, kLogbufSize, "Error: --%ssnp + --window central variant ID '%s' appears multiple times.\n", do_exclude? "exclude-" : "", varid_snp); |
| 160 |
goto SnpFlag_ret_INCONSISTENT_INPUT_WW; |
| 161 |
} |
| 162 |
const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx); |
| 163 |
const uint32_t chr_vidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 164 |
const uint32_t center_bp = variant_bps[variant_uidx]; |
| 165 |
const uint32_t window_bp_u = window_bp; |
| 166 |
uint32_t vidx_start = cip->chr_fo_vidx_start[chr_fo_idx]; |
| 167 |
if (center_bp > window_bp_u) { |
| 168 |
vidx_start = LowerBoundConstrainedNonemptyU32(variant_bps, vidx_start, chr_vidx_end, center_bp - window_bp_u); |
| 169 |
} |
| 170 |
const uint32_t bp_end = 1 + center_bp + window_bp_u; |
| 171 |
const uint32_t vidx_end = LowerBoundConstrainedNonemptyU32(variant_bps, vidx_start, chr_vidx_end, bp_end); |
| 172 |
if (do_exclude) { |
| 173 |
ClearBitsNz(vidx_start, vidx_end, variant_include); |
| 174 |
} else { |
| 175 |
if (vidx_start) { |
| 176 |
ClearBitsNz(0, vidx_start, variant_include); |
| 177 |
} |
| 178 |
if (vidx_end < raw_variant_ct) { |
| 179 |
ClearBitsNz(vidx_end, raw_variant_ct, variant_include); |
| 180 |
} |
| 181 |
ZeroWArr(kChrMaskWords, cip->chr_mask); |
| 182 |
SetBit(cip->chr_file_order[chr_fo_idx], cip->chr_mask); |
| 183 |
} |
| 184 |
} |
| 185 |
const uint32_t new_variant_ct = PopcountWords(variant_include, raw_variant_ctl); |
| 186 |
logprintf("--%ssnp%s: %u variant%s remaining.\n", do_exclude? "exclude-" : "", (window_bp == -1)? "" : " + --window", new_variant_ct, (new_variant_ct == 1)? "" : "s"); |
| 187 |
*variant_ct_ptr = new_variant_ct; |
| 188 |
} |
| 189 |
while (0) { |
| 190 |
SnpFlag_ret_NOMEM: |
| 191 |
reterr = kPglRetNomem; |
| 192 |
break; |
| 193 |
SnpFlag_ret_INCONSISTENT_INPUT_WW: |
| 194 |
WordWrapB(0); |
| 195 |
logerrputsb(); |
| 196 |
reterr = kPglRetInconsistentInput; |
| 197 |
break; |
| 198 |
} |
| 199 |
SnpFlag_ret_1: |
| 200 |
BigstackReset(bigstack_mark); |
| 201 |
return reterr; |
| 202 |
} |
| 203 |
|
| 204 |
PglErr InterpretVariantRangeList(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const RangeList* snps_range_list_ptr, const char* flagname, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, uintptr_t* seen_uidxs) { |
| 205 |
PglErr reterr = kPglRetSuccess; |
| 206 |
{ |
| 207 |
const char* varid_strbox = snps_range_list_ptr->names; |
| 208 |
const unsigned char* starts_range = snps_range_list_ptr->starts_range; |
| 209 |
const uint32_t varid_ct = snps_range_list_ptr->name_ct; |
| 210 |
const uintptr_t varid_max_blen = snps_range_list_ptr->name_max_blen; |
| 211 |
uint32_t range_start_vidx = UINT32_MAX; |
| 212 |
for (uint32_t varid_idx = 0; varid_idx != varid_ct; ++varid_idx) { |
| 213 |
const char* cur_varid = &(varid_strbox[varid_idx * varid_max_blen]); |
| 214 |
uint32_t cur_llidx; |
| 215 |
uint32_t variant_uidx = VariantIdDupHtableFind(cur_varid, variant_ids, variant_id_htable, htable_dup_base, strlen(cur_varid), variant_id_htable_size, max_variant_id_slen, &cur_llidx); |
| 216 |
if (unlikely(variant_uidx == UINT32_MAX)) { |
| 217 |
snprintf(g_logbuf, kLogbufSize, "Error: %s variant '%s' not found.\n", flagname, cur_varid); |
| 218 |
goto InterpretVariantRangeList_ret_INCONSISTENT_INPUT_WW; |
| 219 |
} |
| 220 |
if (starts_range[varid_idx]) { |
| 221 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 222 |
snprintf(g_logbuf, kLogbufSize, "Error: %s range-starting variant ID '%s' appears multiple times.\n", flagname, cur_varid); |
| 223 |
goto InterpretVariantRangeList_ret_INCONSISTENT_INPUT_WW; |
| 224 |
} |
| 225 |
range_start_vidx = variant_uidx; |
| 226 |
} else { |
| 227 |
if (range_start_vidx != UINT32_MAX) { |
| 228 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 229 |
snprintf(g_logbuf, kLogbufSize, "Error: %s range-ending variant ID '%s' appears multiple times.\n", flagname, cur_varid); |
| 230 |
goto InterpretVariantRangeList_ret_INCONSISTENT_INPUT_WW; |
| 231 |
} |
| 232 |
if (variant_uidx < range_start_vidx) { |
| 233 |
const uint32_t uii = variant_uidx; |
| 234 |
variant_uidx = range_start_vidx; |
| 235 |
range_start_vidx = uii; |
| 236 |
} |
| 237 |
FillBitsNz(range_start_vidx, variant_uidx + 1, seen_uidxs); |
| 238 |
} else { |
| 239 |
for (; ; cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 240 |
SetBit(variant_uidx, seen_uidxs); |
| 241 |
if (cur_llidx == UINT32_MAX) { |
| 242 |
break; |
| 243 |
} |
| 244 |
variant_uidx = htable_dup_base[cur_llidx]; |
| 245 |
} |
| 246 |
} |
| 247 |
range_start_vidx = UINT32_MAX; |
| 248 |
} |
| 249 |
} |
| 250 |
} |
| 251 |
while (0) { |
| 252 |
InterpretVariantRangeList_ret_INCONSISTENT_INPUT_WW: |
| 253 |
WordWrapB(0); |
| 254 |
logerrputsb(); |
| 255 |
reterr = kPglRetInconsistentInput; |
| 256 |
break; |
| 257 |
} |
| 258 |
return reterr; |
| 259 |
} |
| 260 |
|
| 261 |
PglErr SnpsFlag(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const RangeList* snps_range_list_ptr, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, uint32_t do_exclude, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 262 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 263 |
PglErr reterr = kPglRetSuccess; |
| 264 |
{ |
| 265 |
if (!(*variant_ct_ptr)) { |
| 266 |
goto SnpsFlag_ret_1; |
| 267 |
} |
| 268 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 269 |
uintptr_t* seen_uidxs; |
| 270 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &seen_uidxs))) { |
| 271 |
goto SnpsFlag_ret_NOMEM; |
| 272 |
} |
| 273 |
reterr = InterpretVariantRangeList(variant_ids, variant_id_htable, htable_dup_base, snps_range_list_ptr, do_exclude? "--exclude-snps" : "--snps", max_variant_id_slen, variant_id_htable_size, seen_uidxs); |
| 274 |
if (unlikely(reterr)) { |
| 275 |
goto SnpsFlag_ret_1; |
| 276 |
} |
| 277 |
if (do_exclude) { |
| 278 |
BitvecInvmask(seen_uidxs, raw_variant_ctl, variant_include); |
| 279 |
} else { |
| 280 |
BitvecAnd(seen_uidxs, raw_variant_ctl, variant_include); |
| 281 |
} |
| 282 |
const uint32_t new_variant_ct = PopcountWords(variant_include, raw_variant_ctl); |
| 283 |
logprintf("--%ssnps: %u variant%s remaining.\n", do_exclude? "exclude-" : "", new_variant_ct, (new_variant_ct == 1)? "" : "s"); |
| 284 |
*variant_ct_ptr = new_variant_ct; |
| 285 |
} |
| 286 |
while (0) { |
| 287 |
SnpsFlag_ret_NOMEM: |
| 288 |
reterr = kPglRetNomem; |
| 289 |
break; |
| 290 |
} |
| 291 |
SnpsFlag_ret_1: |
| 292 |
BigstackReset(bigstack_mark); |
| 293 |
return reterr; |
| 294 |
} |
| 295 |
|
| 296 |
void ExtractExcludeProcessTokens(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const char* shard_start, const char* shard_end, uint32_t variant_id_htable_size, uint32_t max_variant_id_slen, uintptr_t* already_seen) { |
| 297 |
const char* shard_iter = shard_start; |
| 298 |
while (1) { |
| 299 |
shard_iter = FirstPostspaceBounded(shard_iter, shard_end); |
| 300 |
if (shard_iter == shard_end) { |
| 301 |
return; |
| 302 |
} |
| 303 |
const char* token_end = CurTokenEnd(shard_iter); |
| 304 |
uint32_t cur_llidx; |
| 305 |
uint32_t variant_uidx = VariantIdDupHtableFind(shard_iter, variant_ids, variant_id_htable, htable_dup_base, token_end - shard_iter, variant_id_htable_size, max_variant_id_slen, &cur_llidx); |
| 306 |
shard_iter = token_end; |
| 307 |
if (variant_uidx == UINT32_MAX) { |
| 308 |
continue; |
| 309 |
} |
| 310 |
if (IsSet(already_seen, variant_uidx)) { |
| 311 |
continue; |
| 312 |
} |
| 313 |
for (; ; cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 314 |
SetBit(variant_uidx, already_seen); |
| 315 |
if (cur_llidx == UINT32_MAX) { |
| 316 |
break; |
| 317 |
} |
| 318 |
variant_uidx = htable_dup_base[cur_llidx]; |
| 319 |
} |
| 320 |
} |
| 321 |
} |
| 322 |
|
| 323 |
CONSTI32(kMaxExtractExcludeThreads, 8); |
| 324 |
|
| 325 |
typedef struct ExtractExcludeCtxStruct { |
| 326 |
const char* const* variant_ids; |
| 327 |
const uint32_t* variant_id_htable; |
| 328 |
const uint32_t* htable_dup_base; |
| 329 |
uintptr_t variant_id_htable_size; |
| 330 |
uint32_t max_variant_id_slen; |
| 331 |
|
| 332 |
char* shard_boundaries[kMaxExtractExcludeThreads + 1]; |
| 333 |
uintptr_t* already_seens[kMaxExtractExcludeThreads]; |
| 334 |
} ExtractExcludeCtx; |
| 335 |
|
| 336 |
THREAD_FUNC_DECL ExtractExcludeThread(void* raw_arg) { |
| 337 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 338 |
const uintptr_t tidx_p1 = arg->tidx + 1; |
| 339 |
ExtractExcludeCtx* ctx = S_CAST(ExtractExcludeCtx*, arg->sharedp->context); |
| 340 |
|
| 341 |
const char* const* variant_ids = ctx->variant_ids; |
| 342 |
const uint32_t* variant_id_htable = ctx->variant_id_htable; |
| 343 |
const uint32_t* htable_dup_base = ctx->htable_dup_base; |
| 344 |
const uintptr_t variant_id_htable_size = ctx->variant_id_htable_size; |
| 345 |
const uint32_t max_variant_id_slen = ctx->max_variant_id_slen; |
| 346 |
uintptr_t* already_seen = ctx->already_seens[tidx_p1]; |
| 347 |
do { |
| 348 |
ExtractExcludeProcessTokens(variant_ids, variant_id_htable, htable_dup_base, ctx->shard_boundaries[tidx_p1], ctx->shard_boundaries[tidx_p1 + 1], variant_id_htable_size, max_variant_id_slen, already_seen); |
| 349 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 350 |
THREAD_RETURN; |
| 351 |
} |
| 352 |
|
| 353 |
PglErr TokenExtractExclude(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const char* fnames, const char* flagname, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, VfilterType vft, uint32_t max_thread_ct, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 354 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 355 |
const char* fname_tks = nullptr; |
| 356 |
PglErr reterr = kPglRetSuccess; |
| 357 |
TokenStream tks; |
| 358 |
ThreadGroup tg; |
| 359 |
PreinitTokenStream(&tks); |
| 360 |
PreinitThreads(&tg); |
| 361 |
ExtractExcludeCtx ctx; |
| 362 |
{ |
| 363 |
const uint32_t calc_thread_ct_m1 = MINV(max_thread_ct, kMaxExtractExcludeThreads) - 1; |
| 364 |
if (unlikely(SetThreadCt0(calc_thread_ct_m1, &tg))) { |
| 365 |
goto ExtractExcludeFlagNorange_ret_NOMEM; |
| 366 |
} |
| 367 |
if (!(*variant_ct_ptr)) { |
| 368 |
goto ExtractExcludeFlagNorange_ret_1; |
| 369 |
} |
| 370 |
uint32_t decompress_thread_ct = 1; |
| 371 |
if (max_thread_ct > calc_thread_ct_m1 + 2) { |
| 372 |
decompress_thread_ct = max_thread_ct - calc_thread_ct_m1 - 1; |
| 373 |
} |
| 374 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 375 |
for (uint32_t tidx = 0; tidx <= calc_thread_ct_m1; ++tidx) { |
| 376 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &(ctx.already_seens[tidx])))) { |
| 377 |
goto ExtractExcludeFlagNorange_ret_NOMEM; |
| 378 |
} |
| 379 |
} |
| 380 |
if (calc_thread_ct_m1) { |
| 381 |
ctx.variant_ids = variant_ids; |
| 382 |
ctx.variant_id_htable = variant_id_htable; |
| 383 |
ctx.htable_dup_base = htable_dup_base; |
| 384 |
ctx.variant_id_htable_size = variant_id_htable_size; |
| 385 |
ctx.max_variant_id_slen = max_variant_id_slen; |
| 386 |
SetThreadFuncAndData(ExtractExcludeThread, &ctx, &tg); |
| 387 |
} |
| 388 |
const char* fnames_iter = fnames; |
| 389 |
do { |
| 390 |
if (fnames_iter == fnames) { |
| 391 |
fname_tks = fnames_iter; |
| 392 |
reterr = InitTokenStream(fnames_iter, decompress_thread_ct, &tks); |
| 393 |
if (unlikely(reterr)) { |
| 394 |
goto ExtractExcludeFlagNorange_ret_TKSTREAM_FAIL; |
| 395 |
} |
| 396 |
} else { |
| 397 |
reterr = TokenStreamRetarget(fnames_iter, &tks); |
| 398 |
if (unlikely(reterr)) { |
| 399 |
goto ExtractExcludeFlagNorange_ret_TKSTREAM_FAIL; |
| 400 |
} |
| 401 |
fname_tks = fnames_iter; |
| 402 |
} |
| 403 |
while (1) { |
| 404 |
reterr = TksNext(&tks, calc_thread_ct_m1 + 1, ctx.shard_boundaries); |
| 405 |
if (reterr) { |
| 406 |
break; |
| 407 |
} |
| 408 |
if (calc_thread_ct_m1) { |
| 409 |
if (unlikely(SpawnThreads(&tg))) { |
| 410 |
goto ExtractExcludeFlagNorange_ret_THREAD_CREATE_FAIL; |
| 411 |
} |
| 412 |
} |
| 413 |
ExtractExcludeProcessTokens(variant_ids, variant_id_htable, htable_dup_base, ctx.shard_boundaries[0], ctx.shard_boundaries[1], variant_id_htable_size, max_variant_id_slen, ctx.already_seens[0]); |
| 414 |
JoinThreads0(&tg); |
| 415 |
} |
| 416 |
if (unlikely(reterr != kPglRetEof)) { |
| 417 |
goto ExtractExcludeFlagNorange_ret_TKSTREAM_FAIL; |
| 418 |
} |
| 419 |
if (vft == kVfilterExtractIntersect) { |
| 420 |
for (uint32_t tidx = 1; tidx <= calc_thread_ct_m1; ++tidx) { |
| 421 |
BitvecOr(ctx.already_seens[tidx], raw_variant_ctl, ctx.already_seens[0]); |
| 422 |
ZeroWArr(raw_variant_ctl, ctx.already_seens[tidx]); |
| 423 |
} |
| 424 |
BitvecAnd(ctx.already_seens[0], raw_variant_ctl, variant_include); |
| 425 |
ZeroWArr(raw_variant_ctl, ctx.already_seens[0]); |
| 426 |
} |
| 427 |
fnames_iter = strnul(fnames_iter); |
| 428 |
++fnames_iter; |
| 429 |
} while (*fnames_iter); |
| 430 |
reterr = kPglRetSuccess; |
| 431 |
if (vft == kVfilterExclude) { |
| 432 |
for (uint32_t tidx = 1; tidx <= calc_thread_ct_m1; ++tidx) { |
| 433 |
BitvecOr(ctx.already_seens[tidx], raw_variant_ctl, ctx.already_seens[0]); |
| 434 |
} |
| 435 |
BitvecInvmask(ctx.already_seens[0], raw_variant_ctl, variant_include); |
| 436 |
} else if (vft == kVfilterExtract) { |
| 437 |
for (uint32_t tidx = 1; tidx <= calc_thread_ct_m1; ++tidx) { |
| 438 |
BitvecOr(ctx.already_seens[tidx], raw_variant_ctl, ctx.already_seens[0]); |
| 439 |
} |
| 440 |
BitvecAnd(ctx.already_seens[0], raw_variant_ctl, variant_include); |
| 441 |
} |
| 442 |
const uint32_t new_variant_ct = PopcountWords(variant_include, raw_variant_ctl); |
| 443 |
logprintf("--%s: %u variant%s remaining.\n", flagname, new_variant_ct, (new_variant_ct == 1)? "" : "s"); |
| 444 |
*variant_ct_ptr = new_variant_ct; |
| 445 |
} |
| 446 |
while (0) { |
| 447 |
ExtractExcludeFlagNorange_ret_NOMEM: |
| 448 |
reterr = kPglRetNomem; |
| 449 |
break; |
| 450 |
ExtractExcludeFlagNorange_ret_TKSTREAM_FAIL: |
| 451 |
TokenStreamErrPrint(fname_tks, &tks); |
| 452 |
break; |
| 453 |
ExtractExcludeFlagNorange_ret_THREAD_CREATE_FAIL: |
| 454 |
reterr = kPglRetThreadCreateFail; |
| 455 |
} |
| 456 |
ExtractExcludeFlagNorange_ret_1: |
| 457 |
CleanupThreads(&tg); |
| 458 |
if (fname_tks) { |
| 459 |
CleanupTokenStream2(fname_tks, &tks, &reterr); |
| 460 |
} |
| 461 |
BigstackReset(bigstack_mark); |
| 462 |
return reterr; |
| 463 |
} |
| 464 |
|
| 465 |
PglErr ExtractColCond(const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const ExtractColCondInfo* eccip, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t htable_size, uint32_t max_thread_ct, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 466 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 467 |
uintptr_t line_idx = 0; |
| 468 |
PglErr reterr = kPglRetSuccess; |
| 469 |
TextStream txs; |
| 470 |
PreinitTextStream(&txs); |
| 471 |
{ |
| 472 |
// Very similar to e.g. UpdateVarBps(). |
| 473 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 474 |
uintptr_t* variant_include_new; |
| 475 |
uintptr_t* already_seen; |
| 476 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &variant_include_new) || |
| 477 |
bigstack_calloc_w(raw_variant_ctl, &already_seen))) { |
| 478 |
goto ExtractColCond_ret_NOMEM; |
| 479 |
} |
| 480 |
char* match_strbox = nullptr; |
| 481 |
uint32_t match_str_ct = 0; |
| 482 |
uintptr_t max_match_blen = 0; |
| 483 |
// We don't actually need to sort in the substring-match case, but |
| 484 |
// additional cost is negligible. |
| 485 |
if (eccip->match_flattened) { |
| 486 |
if (unlikely(MultistrToStrboxDedupAlloc(eccip->match_flattened, &match_strbox, &match_str_ct, &max_match_blen))) { |
| 487 |
goto ExtractColCond_ret_NOMEM; |
| 488 |
} |
| 489 |
} |
| 490 |
char* mismatch_strbox = nullptr; |
| 491 |
uint32_t mismatch_str_ct = 0; |
| 492 |
uintptr_t max_mismatch_blen = 0; |
| 493 |
if (eccip->mismatch_flattened) { |
| 494 |
if (unlikely(MultistrToStrboxDedupAlloc(eccip->mismatch_flattened, &mismatch_strbox, &mismatch_str_ct, &max_mismatch_blen))) { |
| 495 |
goto ExtractColCond_ret_NOMEM; |
| 496 |
} |
| 497 |
} |
| 498 |
reterr = SizeAndInitTextStream(eccip->params->fname, bigstack_left(), MAXV(max_thread_ct - 1, 1), &txs); |
| 499 |
if (unlikely(reterr)) { |
| 500 |
goto ExtractColCond_ret_TSTREAM_FAIL; |
| 501 |
} |
| 502 |
reterr = TextSkip(eccip->params->skip_ct, &txs); |
| 503 |
if (unlikely(reterr)) { |
| 504 |
if (reterr == kPglRetEof) { |
| 505 |
logerrputs("Error: Fewer lines than expected in --extract-col-cond file.\n"); |
| 506 |
goto ExtractColCond_ret_INCONSISTENT_INPUT; |
| 507 |
} |
| 508 |
goto ExtractColCond_ret_TSTREAM_FAIL; |
| 509 |
} |
| 510 |
line_idx = eccip->params->skip_ct; |
| 511 |
const uint32_t colid_first = (eccip->params->colid < eccip->params->colx); |
| 512 |
uint32_t colmin; |
| 513 |
uint32_t coldiff; |
| 514 |
if (colid_first) { |
| 515 |
colmin = eccip->params->colid - 1; |
| 516 |
coldiff = eccip->params->colx - eccip->params->colid; |
| 517 |
} else { |
| 518 |
colmin = eccip->params->colx - 1; |
| 519 |
coldiff = eccip->params->colid - eccip->params->colx; |
| 520 |
} |
| 521 |
const char skipchar = eccip->params->skipchar; |
| 522 |
const uint32_t match_substr = eccip->match_substr; |
| 523 |
double val_min = eccip->min; |
| 524 |
double val_max = eccip->max; |
| 525 |
uintptr_t miss_ct = 0; |
| 526 |
while (1) { |
| 527 |
++line_idx; |
| 528 |
char* line_start = TextGet(&txs); |
| 529 |
if (!line_start) { |
| 530 |
if (likely(!TextStreamErrcode2(&txs, &reterr))) { |
| 531 |
break; |
| 532 |
} |
| 533 |
goto ExtractColCond_ret_TSTREAM_FAIL; |
| 534 |
} |
| 535 |
char cc = *line_start; |
| 536 |
if (cc == skipchar) { |
| 537 |
continue; |
| 538 |
} |
| 539 |
char* colid_ptr; |
| 540 |
char* colval_ptr; |
| 541 |
if (colid_first) { |
| 542 |
colid_ptr = NextTokenMult0(line_start, colmin); |
| 543 |
colval_ptr = NextTokenMult(colid_ptr, coldiff); |
| 544 |
if (unlikely(!colval_ptr)) { |
| 545 |
goto ExtractColCond_ret_MISSING_TOKENS; |
| 546 |
} |
| 547 |
} else { |
| 548 |
colval_ptr = NextTokenMult0(line_start, colmin); |
| 549 |
colid_ptr = NextTokenMult(colval_ptr, coldiff); |
| 550 |
if (unlikely(!colid_ptr)) { |
| 551 |
goto ExtractColCond_ret_MISSING_TOKENS; |
| 552 |
} |
| 553 |
} |
| 554 |
const uint32_t varid_slen = strlen_se(colid_ptr); |
| 555 |
uint32_t cur_llidx; |
| 556 |
uint32_t variant_uidx = VariantIdDupHtableFind(colid_ptr, variant_ids, variant_id_htable, htable_dup_base, varid_slen, htable_size, max_variant_id_slen, &cur_llidx); |
| 557 |
if (variant_uidx == UINT32_MAX) { |
| 558 |
++miss_ct; |
| 559 |
continue; |
| 560 |
} |
| 561 |
const char* cur_var_id = variant_ids[variant_uidx]; |
| 562 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 563 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --extract-col-cond file.\n", cur_var_id); |
| 564 |
goto ExtractColCond_ret_INCONSISTENT_INPUT_WW; |
| 565 |
} |
| 566 |
SetBit(variant_uidx, already_seen); |
| 567 |
if (mismatch_str_ct) { |
| 568 |
char* token_end = CurTokenEnd(colval_ptr); |
| 569 |
if (!match_substr) { |
| 570 |
const int32_t ii = bsearch_strbox(colval_ptr, mismatch_strbox, token_end - colval_ptr, max_mismatch_blen, mismatch_str_ct); |
| 571 |
if (ii != -1) { |
| 572 |
continue; |
| 573 |
} |
| 574 |
} else { |
| 575 |
// todo: benchmark memmem, use it when it's available and better |
| 576 |
*token_end = '\0'; |
| 577 |
uint32_t uii = 0; |
| 578 |
for (; uii != mismatch_str_ct; ++uii) { |
| 579 |
if (strstr(colval_ptr, &(mismatch_strbox[uii * max_mismatch_blen]))) { |
| 580 |
break; |
| 581 |
} |
| 582 |
} |
| 583 |
if (uii != mismatch_str_ct) { |
| 584 |
continue; |
| 585 |
} |
| 586 |
if (match_str_ct) { |
| 587 |
for (uii = 0; uii != match_str_ct; ++uii) { |
| 588 |
if (strstr(colval_ptr, &(match_strbox[uii * max_match_blen]))) { |
| 589 |
break; |
| 590 |
} |
| 591 |
} |
| 592 |
if (uii == match_str_ct) { |
| 593 |
continue; |
| 594 |
} |
| 595 |
} |
| 596 |
} |
| 597 |
} else if (match_str_ct) { |
| 598 |
// --extract-col-cond-match |
| 599 |
char* token_end = CurTokenEnd(colval_ptr); |
| 600 |
if (!match_substr) { |
| 601 |
const int32_t ii = bsearch_strbox(colval_ptr, match_strbox, token_end - colval_ptr, max_match_blen, match_str_ct); |
| 602 |
if (ii == -1) { |
| 603 |
continue; |
| 604 |
} |
| 605 |
} else { |
| 606 |
*token_end = '\0'; |
| 607 |
uint32_t uii = 0; |
| 608 |
for (; uii != match_str_ct; ++uii) { |
| 609 |
if (strstr(colval_ptr, &(match_strbox[uii * max_match_blen]))) { |
| 610 |
break; |
| 611 |
} |
| 612 |
} |
| 613 |
if (uii == match_str_ct) { |
| 614 |
continue; |
| 615 |
} |
| 616 |
} |
| 617 |
} else { |
| 618 |
// min-max |
| 619 |
double val; |
| 620 |
if ((!ScantokDouble(colval_ptr, &val)) || (val < val_min) || (val > val_max)) { |
| 621 |
continue; |
| 622 |
} |
| 623 |
} |
| 624 |
for (; ; cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 625 |
SetBit(variant_uidx, variant_include_new); |
| 626 |
if (cur_llidx == UINT32_MAX) { |
| 627 |
break; |
| 628 |
} |
| 629 |
variant_uidx = htable_dup_base[cur_llidx]; |
| 630 |
} |
| 631 |
} |
| 632 |
BitvecAnd(variant_include_new, raw_variant_ctl, variant_include); |
| 633 |
const uint32_t new_variant_ct = PopcountWords(variant_include, raw_variant_ctl); |
| 634 |
if (miss_ct) { |
| 635 |
logprintfww("--extract-col-cond: %u variant%s remaining, %" PRIuPTR " ID%s missing.\n", new_variant_ct, (new_variant_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 636 |
} else { |
| 637 |
logprintf("--extract-col-cond: %u variant%s remaining.\n", new_variant_ct, (new_variant_ct == 1)? "" : "s"); |
| 638 |
} |
| 639 |
*variant_ct_ptr = new_variant_ct; |
| 640 |
} |
| 641 |
while (0) { |
| 642 |
ExtractColCond_ret_NOMEM: |
| 643 |
reterr = kPglRetNomem; |
| 644 |
break; |
| 645 |
ExtractColCond_ret_TSTREAM_FAIL: |
| 646 |
TextStreamErrPrint(eccip->params->fname, &txs); |
| 647 |
break; |
| 648 |
ExtractColCond_ret_MISSING_TOKENS: |
| 649 |
logerrprintfww("Error: Line %" PRIuPTR " of --extract-col-cond file has fewer tokens than expected.\n", line_idx); |
| 650 |
reterr = kPglRetMalformedInput; |
| 651 |
break; |
| 652 |
ExtractColCond_ret_INCONSISTENT_INPUT_WW: |
| 653 |
WordWrapB(0); |
| 654 |
logerrputsb(); |
| 655 |
ExtractColCond_ret_INCONSISTENT_INPUT: |
| 656 |
reterr = kPglRetInconsistentInput; |
| 657 |
break; |
| 658 |
} |
| 659 |
CleanupTextStream2(eccip->params->fname, &txs, &reterr); |
| 660 |
BigstackReset(bigstack_mark); |
| 661 |
return reterr; |
| 662 |
} |
| 663 |
|
| 664 |
// could permit split-chromosome here |
| 665 |
PglErr RmDup(const uintptr_t* sample_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* pvar_qual_present, const float* pvar_quals, const uintptr_t* pvar_filter_present, const uintptr_t* pvar_filter_npass, const char* const* pvar_filter_storage, const char* pvar_info_reload, const double* variant_cms, const char* missing_varid_match, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uintptr_t variant_id_htable_size, uint32_t orig_dup_ct, RmDupMode rmdup_mode, uint32_t save_list, uint32_t max_thread_ct, PgenReader* simple_pgrp, uintptr_t* variant_include, uint32_t* variant_ct_ptr, char* outname, char* outname_end) { |
| 666 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 667 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 668 |
TextStream pvar_txs; |
| 669 |
PreinitTextStream(&pvar_txs); |
| 670 |
FILE* list_file = nullptr; |
| 671 |
FILE* mismatch_file = nullptr; |
| 672 |
PglErr reterr = kPglRetSuccess; |
| 673 |
{ |
| 674 |
if (!orig_dup_ct) { |
| 675 |
logputs("Note: Skipping --rm-dup since no duplicate IDs are present.\n"); |
| 676 |
goto RmDup_ret_1; |
| 677 |
} |
| 678 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 679 |
uintptr_t* orig_dups; |
| 680 |
uintptr_t* already_seen; |
| 681 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &orig_dups) || |
| 682 |
bigstack_calloc_w(raw_variant_ctl, &already_seen))) { |
| 683 |
goto RmDup_ret_NOMEM; |
| 684 |
} |
| 685 |
// variant_id_htable + htable_dup_base is structured as follows: |
| 686 |
// - Empty cells in variant_id_htable are represented by UINT32_MAX. |
| 687 |
// - Non-duplicate variant IDs are usually stored at |
| 688 |
// variant_id_htable[hash(ID)]. Collisions are resolved with linear |
| 689 |
// probing. |
| 690 |
// - Duplicate IDs are represented by a (2^31 + HALF the first |
| 691 |
// htable_dup_base cell index) entry in variant_id_htable[hash(ID)]. |
| 692 |
// - A htable_dup_base cell contains two parts: |
| 693 |
// - First element (array index [k]) is a variant_uidx. |
| 694 |
// - Second element (array index [k+1]) is another htable_dup_base cell |
| 695 |
// index (not halved), or UINT32_MAX if we've reached the last ID. |
| 696 |
// Thus, we can initialize a bitarray with just the positions correspond to |
| 697 |
// duplicate-ID variant_uidxs set by looking at just the even entries of |
| 698 |
// htable_dup_base[]. (The bitarray may have some false positives from |
| 699 |
// recently-filtered variants and/or the missing-ID code.) |
| 700 |
for (uint32_t uii = 0; uii != orig_dup_ct; ++uii) { |
| 701 |
SetBit(htable_dup_base[uii * 2], orig_dups); |
| 702 |
} |
| 703 |
const uint32_t orig_variant_ct = *variant_ct_ptr; |
| 704 |
uint32_t dup_recheck_needed = 0; |
| 705 |
if (orig_variant_ct != raw_variant_ct) { |
| 706 |
BitvecAnd(variant_include, raw_variant_ctl, orig_dups); |
| 707 |
const uint32_t subsetted_dup_ct = PopcountWords(orig_dups, raw_variant_ctl); |
| 708 |
if (subsetted_dup_ct != orig_dup_ct) { |
| 709 |
if (!subsetted_dup_ct) { |
| 710 |
logputs("Note: Skipping --rm-dup since no duplicate IDs remain.\n"); |
| 711 |
goto RmDup_ret_1; |
| 712 |
} |
| 713 |
orig_dup_ct = subsetted_dup_ct; |
| 714 |
dup_recheck_needed = 1; |
| 715 |
} |
| 716 |
} |
| 717 |
if (!missing_varid_match) { |
| 718 |
missing_varid_match = &(g_one_char_strs[92]); |
| 719 |
} |
| 720 |
const uint32_t missing_varid_blen = strlen(missing_varid_match) + 1; |
| 721 |
uint32_t* orig_dups_cumulative_popcounts = nullptr; |
| 722 |
// Load all relevant INFO lines before main loop, since main loop can |
| 723 |
// perform out-of-order lookups. |
| 724 |
const char** dup_info_strs = nullptr; |
| 725 |
if (pvar_info_reload && (rmdup_mode < kRmDupExcludeAll)) { |
| 726 |
if (unlikely(bigstack_alloc_u32(raw_variant_ctl, &orig_dups_cumulative_popcounts) || |
| 727 |
bigstack_alloc_kcp(orig_dup_ct, &dup_info_strs))) { |
| 728 |
goto RmDup_ret_NOMEM; |
| 729 |
} |
| 730 |
FillCumulativePopcounts(orig_dups, raw_variant_ctl, orig_dups_cumulative_popcounts); |
| 731 |
unsigned char* bigstack_mark2 = g_bigstack_base; |
| 732 |
const uint32_t decompress_thread_ct = ClipU32(max_thread_ct - 1, 1, 4); |
| 733 |
reterr = SizeAndInitTextStream(pvar_info_reload, bigstack_left() / 4, decompress_thread_ct, &pvar_txs); |
| 734 |
if (unlikely(reterr)) { |
| 735 |
goto RmDup_ret_TSTREAM_FAIL; |
| 736 |
} |
| 737 |
logputs("--rm-dup: Loading INFO field... "); |
| 738 |
fflush(stdout); |
| 739 |
unsigned char* tmp_alloc_end = g_bigstack_end; |
| 740 |
char* line_iter; |
| 741 |
// if INFO column exists, #CHROM header line guaranteed |
| 742 |
do { |
| 743 |
reterr = TextNextLineLstrip(&pvar_txs, &line_iter); |
| 744 |
if (unlikely(reterr)) { |
| 745 |
goto RmDup_ret_TSTREAM_FAIL; |
| 746 |
} |
| 747 |
} while (!tokequal_k(line_iter, "#CHROM")); |
| 748 |
uint32_t info_col_idx = 1; |
| 749 |
{ |
| 750 |
line_iter = &(line_iter[6]); |
| 751 |
for (; ; ++info_col_idx) { |
| 752 |
char* token_start = FirstNonTspace(line_iter); |
| 753 |
if (IsEolnKns(*token_start)) { |
| 754 |
reterr = kPglRetRewindFail; |
| 755 |
logerrprintfww(kErrprintfRewind, pvar_info_reload); |
| 756 |
goto RmDup_ret_1; |
| 757 |
} |
| 758 |
line_iter = CurTokenEnd(token_start); |
| 759 |
if (strequal_k(token_start, "INFO", line_iter - token_start)) { |
| 760 |
break; |
| 761 |
} |
| 762 |
} |
| 763 |
} |
| 764 |
unsigned char* tmp_alloc_base = g_bigstack_base; |
| 765 |
uint32_t dup_variant_idx = 0; |
| 766 |
for (uint32_t variant_uidx = 0; ; ++variant_uidx) { |
| 767 |
reterr = TextNextLineLstrip(&pvar_txs, &line_iter); |
| 768 |
if (unlikely(reterr)) { |
| 769 |
goto RmDup_ret_TSTREAM_FAIL; |
| 770 |
} |
| 771 |
if (IsSet(orig_dups, variant_uidx)) { |
| 772 |
if (!memequal(variant_ids[variant_uidx], missing_varid_match, missing_varid_blen)) { |
| 773 |
char* info_start = NextTokenMult(line_iter, info_col_idx); |
| 774 |
line_iter = CurTokenEnd(info_start); |
| 775 |
const uint32_t info_slen = line_iter - info_start; |
| 776 |
if (StoreStringAtEndK(tmp_alloc_base, info_start, info_slen, &tmp_alloc_end, &(dup_info_strs[dup_variant_idx]))) { |
| 777 |
goto RmDup_ret_NOMEM; |
| 778 |
} |
| 779 |
} |
| 780 |
++dup_variant_idx; |
| 781 |
if (dup_variant_idx == orig_dup_ct) { |
| 782 |
break; |
| 783 |
} |
| 784 |
} |
| 785 |
} |
| 786 |
if (CleanupTextStream2(pvar_info_reload, &pvar_txs, &reterr)) { |
| 787 |
goto RmDup_ret_1; |
| 788 |
} |
| 789 |
logputs("done.\n"); |
| 790 |
BigstackEndSet(tmp_alloc_end); |
| 791 |
BigstackReset(bigstack_mark2); |
| 792 |
} |
| 793 |
char* list_write_iter = g_textbuf; |
| 794 |
char* list_flush = &(list_write_iter[kMaxMediumLine]); |
| 795 |
char* mismatch_write_iter = nullptr; |
| 796 |
char* mismatch_flush = nullptr; |
| 797 |
if (rmdup_mode < kRmDupExcludeMismatch) { |
| 798 |
if (unlikely(bigstack_alloc_c(kMaxMediumLine + kMaxIdBlen, &mismatch_write_iter))) { |
| 799 |
goto RmDup_ret_NOMEM; |
| 800 |
} |
| 801 |
mismatch_flush = &(mismatch_write_iter[kMaxMediumLine]); |
| 802 |
} |
| 803 |
uintptr_t variant_uidx_base = 0; |
| 804 |
uintptr_t cur_bits = orig_dups[0]; |
| 805 |
uint32_t duplicate_ct = 0; |
| 806 |
uint32_t mismatch_ct = 0; |
| 807 |
uint32_t first_allele_ct = 2; |
| 808 |
uint32_t first_qual_is_present = 0; |
| 809 |
float first_qual = 0.0; |
| 810 |
uint32_t first_filter_is_present = 0; |
| 811 |
uint32_t first_filter_npass = 0; |
| 812 |
const char* first_filter_str = nullptr; |
| 813 |
const char* first_info_str = nullptr; |
| 814 |
double first_cm = 0.0; |
| 815 |
|
| 816 |
const uint32_t sample_ctb2 = NypCtToWordCt(sample_ct) * sizeof(intptr_t); |
| 817 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 818 |
const uint32_t sample_ctb = sample_ctl * sizeof(intptr_t); |
| 819 |
PgenVariant first_pgv; |
| 820 |
PreinitPgv(&first_pgv); |
| 821 |
PgenVariant cur_pgv; |
| 822 |
PreinitPgv(&cur_pgv); |
| 823 |
PgrSampleSubsetIndex pssi; |
| 824 |
if (simple_pgrp && (rmdup_mode < kRmDupExcludeAll)) { |
| 825 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 826 |
uint32_t* sample_include_cumulative_popcounts; |
| 827 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 828 |
BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, PgrGetGflags(simple_pgrp), &first_pgv) || |
| 829 |
BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, PgrGetGflags(simple_pgrp), &cur_pgv))) { |
| 830 |
goto RmDup_ret_NOMEM; |
| 831 |
} |
| 832 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 833 |
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi); |
| 834 |
} else { |
| 835 |
PgrClearSampleSubsetIndex(simple_pgrp, &pssi); |
| 836 |
} |
| 837 |
uint32_t missing_ct = 0; |
| 838 |
for (uint32_t variant_idx = 0; variant_idx != orig_dup_ct; ++variant_idx) { |
| 839 |
const uint32_t variant_uidx = BitIter1(orig_dups, &variant_uidx_base, &cur_bits); |
| 840 |
if (IsSet(already_seen, variant_uidx)) { |
| 841 |
continue; |
| 842 |
} |
| 843 |
const char* cur_id = variant_ids[variant_uidx]; |
| 844 |
if (memequal(cur_id, missing_varid_match, missing_varid_blen)) { |
| 845 |
++missing_ct; |
| 846 |
continue; |
| 847 |
} |
| 848 |
uint32_t first_llidx; |
| 849 |
const uint32_t variant_uidx_ll_first = VariantIdDupHtableFind(cur_id, variant_ids, variant_id_htable, htable_dup_base, strlen(cur_id), variant_id_htable_size, max_variant_id_slen, &first_llidx); |
| 850 |
assert(first_llidx != UINT32_MAX); |
| 851 |
// 1. Verify this is still a duplicate in the current filtering state. |
| 852 |
// 2. If exclude-all or force-first mode, we're done; otherwise: |
| 853 |
// 3. Load variant information and genotype data for variant_uidx. |
| 854 |
// 4. Check for inequality. If any inequality found, write variant ID |
| 855 |
// to {output prefix}.rmdup.mismatch (lazy-opening the file before |
| 856 |
// first write) if not in exclude-mismatch mode. |
| 857 |
if (dup_recheck_needed) { |
| 858 |
uint32_t is_still_dup = 0; |
| 859 |
uint32_t dupcheck_llidx = first_llidx; |
| 860 |
for (uint32_t dupcheck_vidx = variant_uidx_ll_first; ; dupcheck_llidx = htable_dup_base[dupcheck_llidx + 1]) { |
| 861 |
if ((dupcheck_vidx != variant_uidx) && IsSet(orig_dups, dupcheck_vidx)) { |
| 862 |
is_still_dup = 1; |
| 863 |
break; |
| 864 |
} |
| 865 |
if (dupcheck_llidx == UINT32_MAX) { |
| 866 |
break; |
| 867 |
} |
| 868 |
dupcheck_vidx = htable_dup_base[dupcheck_llidx]; |
| 869 |
} |
| 870 |
if (!is_still_dup) { |
| 871 |
continue; |
| 872 |
} |
| 873 |
} |
| 874 |
if (save_list) { |
| 875 |
if (!list_file) { |
| 876 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".rmdup.list"); |
| 877 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &list_file))) { |
| 878 |
goto RmDup_ret_OPEN_FAIL; |
| 879 |
} |
| 880 |
} |
| 881 |
list_write_iter = strcpya(list_write_iter, variant_ids[variant_uidx]); |
| 882 |
AppendBinaryEoln(&list_write_iter); |
| 883 |
if (unlikely(fwrite_ck(list_flush, list_file, &list_write_iter))) { |
| 884 |
goto RmDup_ret_WRITE_FAIL; |
| 885 |
} |
| 886 |
} |
| 887 |
++duplicate_ct; |
| 888 |
if (rmdup_mode >= kRmDupExcludeAll) { |
| 889 |
uint32_t dupset_vidx = variant_uidx_ll_first; |
| 890 |
for (uint32_t cur_llidx = first_llidx; ; cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 891 |
SetBit(dupset_vidx, already_seen); |
| 892 |
ClearBit(dupset_vidx, variant_include); |
| 893 |
if (cur_llidx == UINT32_MAX) { |
| 894 |
break; |
| 895 |
} |
| 896 |
dupset_vidx = htable_dup_base[cur_llidx]; |
| 897 |
} |
| 898 |
if (rmdup_mode == kRmDupForceFirst) { |
| 899 |
SetBit(variant_uidx, variant_include); |
| 900 |
} |
| 901 |
continue; |
| 902 |
} |
| 903 |
const uint32_t first_chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx); |
| 904 |
const uint32_t first_bp = variant_bps[variant_uidx]; |
| 905 |
uintptr_t allele_idx_offset_base; |
| 906 |
if (!allele_idx_offsets) { |
| 907 |
allele_idx_offset_base = 2 * variant_uidx; |
| 908 |
} else { |
| 909 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 910 |
first_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 911 |
} |
| 912 |
const char* const* first_alleles = &(allele_storage[allele_idx_offset_base]); |
| 913 |
if (pvar_qual_present) { |
| 914 |
first_qual_is_present = IsSet(pvar_qual_present, variant_uidx); |
| 915 |
if (first_qual_is_present) { |
| 916 |
first_qual = pvar_quals[variant_uidx]; |
| 917 |
} |
| 918 |
} |
| 919 |
if (pvar_filter_present) { |
| 920 |
first_filter_is_present = IsSet(pvar_filter_present, variant_uidx); |
| 921 |
if (first_filter_is_present) { |
| 922 |
first_filter_npass = IsSet(pvar_filter_npass, variant_uidx); |
| 923 |
if (first_filter_npass) { |
| 924 |
first_filter_str = pvar_filter_storage[variant_uidx]; |
| 925 |
} |
| 926 |
} |
| 927 |
} |
| 928 |
if (dup_info_strs) { |
| 929 |
const uint32_t subsetted_idx = RawToSubsettedPos(orig_dups, orig_dups_cumulative_popcounts, variant_uidx); |
| 930 |
first_info_str = dup_info_strs[subsetted_idx]; |
| 931 |
} |
| 932 |
if (variant_cms) { |
| 933 |
first_cm = variant_cms[variant_uidx]; |
| 934 |
} |
| 935 |
|
| 936 |
uint32_t cur_llidx = first_llidx; |
| 937 |
uint32_t is_mismatch = 0; |
| 938 |
for (uint32_t ll_variant_uidx = variant_uidx_ll_first; ; ll_variant_uidx = htable_dup_base[cur_llidx], cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 939 |
if ((variant_uidx != ll_variant_uidx) && IsSet(orig_dups, ll_variant_uidx)) { |
| 940 |
SetBit(ll_variant_uidx, already_seen); |
| 941 |
ClearBit(ll_variant_uidx, variant_include); |
| 942 |
if (is_mismatch) { |
| 943 |
continue; |
| 944 |
} |
| 945 |
// Check .pvar fields for equality. |
| 946 |
is_mismatch = 1; |
| 947 |
if ((GetVariantChrFoIdx(cip, ll_variant_uidx) != first_chr_fo_idx) || |
| 948 |
(variant_bps[ll_variant_uidx] != first_bp)) { |
| 949 |
continue; |
| 950 |
} |
| 951 |
if (!allele_idx_offsets) { |
| 952 |
allele_idx_offset_base = 2 * ll_variant_uidx; |
| 953 |
} else { |
| 954 |
allele_idx_offset_base = allele_idx_offsets[ll_variant_uidx]; |
| 955 |
if (first_allele_ct != allele_idx_offsets[ll_variant_uidx + 1] - allele_idx_offset_base) { |
| 956 |
continue; |
| 957 |
} |
| 958 |
} |
| 959 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 960 |
uint32_t aidx = 0; |
| 961 |
for (; aidx != first_allele_ct; ++aidx) { |
| 962 |
if (!strequal_overread(first_alleles[aidx], cur_alleles[aidx])) { |
| 963 |
break; |
| 964 |
} |
| 965 |
} |
| 966 |
if (aidx != first_allele_ct) { |
| 967 |
continue; |
| 968 |
} |
| 969 |
if (pvar_qual_present) { |
| 970 |
if ((IsSet(pvar_qual_present, ll_variant_uidx) != first_qual_is_present) || (first_qual_is_present && (pvar_quals[ll_variant_uidx] != first_qual))) { |
| 971 |
continue; |
| 972 |
} |
| 973 |
} |
| 974 |
if (pvar_filter_present) { |
| 975 |
if (IsSet(pvar_filter_present, ll_variant_uidx) != first_filter_is_present) { |
| 976 |
continue; |
| 977 |
} |
| 978 |
if (first_filter_is_present) { |
| 979 |
if (IsSet(pvar_filter_npass, ll_variant_uidx) != first_filter_npass) { |
| 980 |
continue; |
| 981 |
} |
| 982 |
if (first_filter_npass && (!strequal_overread(first_filter_str, pvar_filter_storage[ll_variant_uidx]))) { |
| 983 |
continue; |
| 984 |
} |
| 985 |
} |
| 986 |
} |
| 987 |
if (first_info_str) { |
| 988 |
const uint32_t subsetted_idx = RawToSubsettedPos(orig_dups, orig_dups_cumulative_popcounts, ll_variant_uidx); |
| 989 |
if (!strequal_overread(first_info_str, dup_info_strs[subsetted_idx])) { |
| 990 |
continue; |
| 991 |
} |
| 992 |
} |
| 993 |
if (variant_cms) { |
| 994 |
if (variant_cms[ll_variant_uidx] != first_cm) { |
| 995 |
continue; |
| 996 |
} |
| 997 |
} |
| 998 |
is_mismatch = 0; |
| 999 |
} |
| 1000 |
if (cur_llidx == UINT32_MAX) { |
| 1001 |
break; |
| 1002 |
} |
| 1003 |
} |
| 1004 |
if ((!is_mismatch) && first_pgv.genovec) { |
| 1005 |
// Avoid loading genotypes when possible. |
| 1006 |
reterr = PgrGetMDp(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &first_pgv); |
| 1007 |
if (unlikely(reterr)) { |
| 1008 |
PgenErrPrintNV(reterr, variant_uidx); |
| 1009 |
goto RmDup_ret_1; |
| 1010 |
} |
| 1011 |
ZeroTrailingNyps(sample_ct, first_pgv.genovec); |
| 1012 |
if (first_pgv.phasepresent_ct) { |
| 1013 |
BitvecAnd(first_pgv.phasepresent, sample_ctl, first_pgv.phaseinfo); |
| 1014 |
} |
| 1015 |
cur_llidx = first_llidx; |
| 1016 |
is_mismatch = 1; |
| 1017 |
for (uint32_t ll_variant_uidx = variant_uidx_ll_first; ; ll_variant_uidx = htable_dup_base[cur_llidx], cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 1018 |
if ((variant_uidx != ll_variant_uidx) && IsSet(orig_dups, ll_variant_uidx)) { |
| 1019 |
reterr = PgrGetMDp(sample_include, pssi, sample_ct, ll_variant_uidx, simple_pgrp, &cur_pgv); |
| 1020 |
if (unlikely(reterr)) { |
| 1021 |
PgenErrPrintNV(reterr, ll_variant_uidx); |
| 1022 |
goto RmDup_ret_1; |
| 1023 |
} |
| 1024 |
// todo: multidosage, multidphase |
| 1025 |
if ((first_pgv.patch_01_ct != cur_pgv.patch_01_ct) || |
| 1026 |
(first_pgv.patch_10_ct != cur_pgv.patch_10_ct) || |
| 1027 |
(first_pgv.phasepresent_ct != cur_pgv.phasepresent_ct) || |
| 1028 |
(first_pgv.dosage_ct != cur_pgv.dosage_ct) || |
| 1029 |
(first_pgv.dphase_ct != cur_pgv.dphase_ct)) { |
| 1030 |
break; |
| 1031 |
} |
| 1032 |
ZeroTrailingNyps(sample_ct, cur_pgv.genovec); |
| 1033 |
if (!memequal(first_pgv.genovec, cur_pgv.genovec, sample_ctb2)) { |
| 1034 |
break; |
| 1035 |
} |
| 1036 |
if (first_pgv.patch_01_ct) { |
| 1037 |
if ((!memequal(first_pgv.patch_01_set, cur_pgv.patch_01_set, sample_ctb)) || |
| 1038 |
(!memequal(first_pgv.patch_01_vals, cur_pgv.patch_01_vals, first_pgv.patch_01_ct * sizeof(AlleleCode)))) { |
| 1039 |
break; |
| 1040 |
} |
| 1041 |
} |
| 1042 |
if (first_pgv.patch_10_ct) { |
| 1043 |
if ((!memequal(first_pgv.patch_10_set, cur_pgv.patch_10_set, sample_ctb)) || |
| 1044 |
(!memequal(first_pgv.patch_10_vals, cur_pgv.patch_10_vals, first_pgv.patch_10_ct * sizeof(AlleleCode) * 2))) { |
| 1045 |
break; |
| 1046 |
} |
| 1047 |
} |
| 1048 |
if (first_pgv.phasepresent_ct) { |
| 1049 |
BitvecAnd(cur_pgv.phasepresent, sample_ctl, cur_pgv.phaseinfo); |
| 1050 |
if ((!memequal(first_pgv.phasepresent, cur_pgv.phasepresent, sample_ctb)) || |
| 1051 |
(!memequal(first_pgv.phaseinfo, cur_pgv.phaseinfo, sample_ctb))) { |
| 1052 |
break; |
| 1053 |
} |
| 1054 |
} |
| 1055 |
if (first_pgv.dosage_ct) { |
| 1056 |
if ((!memequal(first_pgv.dosage_present, cur_pgv.dosage_present, sample_ctb)) || |
| 1057 |
(!memequal(first_pgv.dosage_main, cur_pgv.dosage_main, first_pgv.dosage_ct * sizeof(Dosage)))) { |
| 1058 |
break; |
| 1059 |
} |
| 1060 |
if (first_pgv.dphase_ct) { |
| 1061 |
if ((!memequal(first_pgv.dphase_present, cur_pgv.dphase_present, sample_ctb)) || |
| 1062 |
(!memequal(first_pgv.dphase_delta, cur_pgv.dphase_delta, first_pgv.dphase_ct * sizeof(SDosage)))) { |
| 1063 |
break; |
| 1064 |
} |
| 1065 |
} |
| 1066 |
} |
| 1067 |
} |
| 1068 |
if (cur_llidx == UINT32_MAX) { |
| 1069 |
is_mismatch = 0; |
| 1070 |
break; |
| 1071 |
} |
| 1072 |
} |
| 1073 |
} |
| 1074 |
if (is_mismatch) { |
| 1075 |
++mismatch_ct; |
| 1076 |
if (rmdup_mode == kRmDupExcludeMismatch) { |
| 1077 |
ClearBit(variant_uidx, variant_include); |
| 1078 |
} else { |
| 1079 |
if (rmdup_mode == kRmDupRetainMismatch) { |
| 1080 |
cur_llidx = first_llidx; |
| 1081 |
for (uint32_t ll_variant_uidx = variant_uidx_ll_first; ; ll_variant_uidx = htable_dup_base[cur_llidx], cur_llidx = htable_dup_base[cur_llidx + 1]) { |
| 1082 |
if ((variant_uidx != ll_variant_uidx) && IsSet(orig_dups, ll_variant_uidx)) { |
| 1083 |
SetBit(ll_variant_uidx, variant_include); |
| 1084 |
} |
| 1085 |
if (cur_llidx == UINT32_MAX) { |
| 1086 |
break; |
| 1087 |
} |
| 1088 |
} |
| 1089 |
} |
| 1090 |
if (mismatch_file == nullptr) { |
| 1091 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".rmdup.mismatch"); |
| 1092 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &mismatch_file))) { |
| 1093 |
goto RmDup_ret_OPEN_FAIL; |
| 1094 |
} |
| 1095 |
} |
| 1096 |
mismatch_write_iter = strcpya(mismatch_write_iter, variant_ids[variant_uidx]); |
| 1097 |
AppendBinaryEoln(&mismatch_write_iter); |
| 1098 |
if (unlikely(fwrite_ck(mismatch_flush, mismatch_file, &mismatch_write_iter))) { |
| 1099 |
goto RmDup_ret_WRITE_FAIL; |
| 1100 |
} |
| 1101 |
} |
| 1102 |
} |
| 1103 |
} |
| 1104 |
if (missing_ct) { |
| 1105 |
logprintf("--rm-dup: %u missing-ID variant%s skipped.\n", missing_ct, (missing_ct == 1)? "" : "s"); |
| 1106 |
} |
| 1107 |
if (mismatch_file != nullptr) { |
| 1108 |
if (unlikely(fclose_flush_null(mismatch_flush, mismatch_write_iter, &mismatch_file))) { |
| 1109 |
goto RmDup_ret_WRITE_FAIL; |
| 1110 |
} |
| 1111 |
logerrprintfww("%s: %u duplicate ID%s with inconsistent %svariant information detected by --rm-dup; see %s .\n", (rmdup_mode == kRmDupError)? "Error" : "Warning", mismatch_ct, (mismatch_ct == 1)? "" : "s", simple_pgrp? "genotype data or " : "", outname); |
| 1112 |
if (rmdup_mode == kRmDupError) { |
| 1113 |
reterr = kPglRetInconsistentInput; |
| 1114 |
goto RmDup_ret_1; |
| 1115 |
} |
| 1116 |
} else if (mismatch_ct) { |
| 1117 |
logprintfww("Note: %u duplicate ID%s with inconsistent %svariant information detected by --rm-dup exclude-mismatch; all copies removed.\n", mismatch_ct, (mismatch_ct == 1)? "" : "s", simple_pgrp? "genotype data or " : ""); |
| 1118 |
} |
| 1119 |
*variant_ct_ptr = PopcountWords(variant_include, raw_variant_ctl); |
| 1120 |
const uint32_t removed_variant_ct = orig_variant_ct - (*variant_ct_ptr); |
| 1121 |
logprintfww("--rm-dup: %u duplicated ID%s, %u variant%s removed.\n", duplicate_ct, (duplicate_ct == 1)? "" : "s", removed_variant_ct, (removed_variant_ct == 1)? "" : "s"); |
| 1122 |
if (list_file != nullptr) { |
| 1123 |
if (unlikely(fclose_flush_null(list_flush, list_write_iter, &list_file))) { |
| 1124 |
goto RmDup_ret_WRITE_FAIL; |
| 1125 |
} |
| 1126 |
*outname_end = '\0'; |
| 1127 |
logprintfww("Full duplicate ID list written to %s.rmdup.list .\n", outname); |
| 1128 |
} |
| 1129 |
} |
| 1130 |
while (0) { |
| 1131 |
RmDup_ret_NOMEM: |
| 1132 |
reterr = kPglRetNomem; |
| 1133 |
break; |
| 1134 |
RmDup_ret_OPEN_FAIL: |
| 1135 |
reterr = kPglRetOpenFail; |
| 1136 |
break; |
| 1137 |
RmDup_ret_TSTREAM_FAIL: |
| 1138 |
TextStreamErrPrint(pvar_info_reload, &pvar_txs); |
| 1139 |
break; |
| 1140 |
RmDup_ret_WRITE_FAIL: |
| 1141 |
reterr = kPglRetWriteFail; |
| 1142 |
break; |
| 1143 |
} |
| 1144 |
RmDup_ret_1: |
| 1145 |
fclose_cond(mismatch_file); |
| 1146 |
fclose_cond(list_file); |
| 1147 |
CleanupTextStream2(pvar_info_reload, &pvar_txs, &reterr); |
| 1148 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 1149 |
return reterr; |
| 1150 |
} |
| 1151 |
|
| 1152 |
void RandomThinProb(const char* flagname_p, const char* unitname, double thin_keep_prob, uint32_t raw_item_ct, sfmt_t* sfmtp, uintptr_t* item_include, uint32_t* item_ct_ptr) { |
| 1153 |
// possible todo: try using truncated geometric distribution, like --dummy |
| 1154 |
// can also parallelize this |
| 1155 |
const uint32_t orig_item_ct = *item_ct_ptr; |
| 1156 |
if (!orig_item_ct) { |
| 1157 |
return; |
| 1158 |
} |
| 1159 |
const uint32_t uint32_thresh = S_CAST(uint32_t, thin_keep_prob * 4294967296.0 + 0.5); |
| 1160 |
uintptr_t item_widx = 0; |
| 1161 |
uintptr_t cur_bits = item_include[0]; |
| 1162 |
for (uint32_t item_idx = 0; item_idx != orig_item_ct; ++item_idx) { |
| 1163 |
const uintptr_t lowbit = BitIter1y(item_include, &item_widx, &cur_bits); |
| 1164 |
if (sfmt_genrand_uint32(sfmtp) >= uint32_thresh) { |
| 1165 |
item_include[item_widx] ^= lowbit; |
| 1166 |
} |
| 1167 |
} |
| 1168 |
const uint32_t new_item_ct = PopcountWords(item_include, BitCtToWordCt(raw_item_ct)); |
| 1169 |
*item_ct_ptr = new_item_ct; |
| 1170 |
const uint32_t removed_ct = orig_item_ct - new_item_ct; |
| 1171 |
logprintf("--%s: %u %s%s removed (%u remaining).\n", flagname_p, removed_ct, unitname, (removed_ct == 1)? "" : "s", new_item_ct); |
| 1172 |
return; |
| 1173 |
} |
| 1174 |
|
| 1175 |
PglErr RandomThinCt(const char* flagname_p, const char* unitname, uint32_t thin_keep_ct, uint32_t raw_item_ct, sfmt_t* sfmtp, uintptr_t* item_include, uint32_t* item_ct_ptr) { |
| 1176 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1177 |
PglErr reterr = kPglRetSuccess; |
| 1178 |
{ |
| 1179 |
const uint32_t orig_item_ct = *item_ct_ptr; |
| 1180 |
if (thin_keep_ct >= orig_item_ct) { |
| 1181 |
logerrprintf("Warning: --%s parameter exceeds # of remaining %ss; skipping.\n", flagname_p, unitname); |
| 1182 |
goto RandomThinCt_ret_1; |
| 1183 |
} |
| 1184 |
const uint32_t removed_ct = orig_item_ct - thin_keep_ct; |
| 1185 |
const uint32_t raw_item_ctl = BitCtToWordCt(raw_item_ct); |
| 1186 |
uintptr_t* perm_buf; |
| 1187 |
uintptr_t* new_item_include; |
| 1188 |
if (unlikely(bigstack_alloc_w(BitCtToWordCt(orig_item_ct), &perm_buf) || |
| 1189 |
bigstack_alloc_w(raw_item_ctl, &new_item_include))) { |
| 1190 |
goto RandomThinCt_ret_NOMEM; |
| 1191 |
} |
| 1192 |
// no actual interleaving here, but may as well use this function |
| 1193 |
// note that this requires marker_ct >= 2 |
| 1194 |
GeneratePerm1Interleaved(orig_item_ct, thin_keep_ct, 0, 1, perm_buf, sfmtp); |
| 1195 |
ExpandBytearr(perm_buf, item_include, raw_item_ctl, orig_item_ct, 0, new_item_include); |
| 1196 |
memcpy(item_include, new_item_include, raw_item_ctl * sizeof(intptr_t)); |
| 1197 |
*item_ct_ptr = thin_keep_ct; |
| 1198 |
logprintf("--%s: %u %s%s removed (%u remaining).\n", flagname_p, removed_ct, unitname, (removed_ct == 1)? "" : "s", thin_keep_ct); |
| 1199 |
} |
| 1200 |
while (0) { |
| 1201 |
RandomThinCt_ret_NOMEM: |
| 1202 |
reterr = kPglRetNomem; |
| 1203 |
break; |
| 1204 |
} |
| 1205 |
RandomThinCt_ret_1: |
| 1206 |
BigstackReset(bigstack_mark); |
| 1207 |
return reterr; |
| 1208 |
} |
| 1209 |
|
| 1210 |
static const char kKeepRemoveFlagStrs[4][11] = {"keep", "remove", "keep-fam", "remove-fam"}; |
| 1211 |
|
| 1212 |
PglErr KeepOrRemove(const char* fnames, const SampleIdInfo* siip, uint32_t raw_sample_ct, KeepFlags flags, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1213 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1214 |
PglErr reterr = kPglRetSuccess; |
| 1215 |
{ |
| 1216 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 1217 |
if (!orig_sample_ct) { |
| 1218 |
goto KeepOrRemove_ret_1; |
| 1219 |
} |
| 1220 |
const char* flag_name = kKeepRemoveFlagStrs[flags % 4]; |
| 1221 |
const LoadSampleIdsFlags load_sample_ids_flags = (flags & kfKeepFam)? (kfLoadSampleIdsMultifile | kfLoadSampleIdsFamOnly) : kfLoadSampleIdsMultifile; |
| 1222 |
uintptr_t* seen_uidxs; |
| 1223 |
uint32_t duplicate_ct; |
| 1224 |
reterr = LoadSampleIds(fnames, sample_include, siip, flag_name, raw_sample_ct, orig_sample_ct, load_sample_ids_flags, &seen_uidxs, &duplicate_ct); |
| 1225 |
if (unlikely(reterr)) { |
| 1226 |
goto KeepOrRemove_ret_1; |
| 1227 |
} |
| 1228 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1229 |
if (flags & kfKeepRemove) { |
| 1230 |
BitvecInvmask(seen_uidxs, raw_sample_ctl, sample_include); |
| 1231 |
} else { |
| 1232 |
memcpy(sample_include, seen_uidxs, raw_sample_ctl * sizeof(intptr_t)); |
| 1233 |
} |
| 1234 |
const uint32_t sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 1235 |
*sample_ct_ptr = sample_ct; |
| 1236 |
logprintf("--%s: %u sample%s remaining.\n", flag_name, sample_ct, (sample_ct == 1)? "" : "s"); |
| 1237 |
if (duplicate_ct) { |
| 1238 |
// "At least" since this does not count duplicate IDs absent from the |
| 1239 |
// .fam. |
| 1240 |
logerrprintf("Warning: At least %" PRIuPTR " duplicate ID%s in --%s file(s).\n", duplicate_ct, (duplicate_ct == 1)? "" : "s", flag_name); |
| 1241 |
} |
| 1242 |
} |
| 1243 |
KeepOrRemove_ret_1: |
| 1244 |
BigstackReset(bigstack_mark); |
| 1245 |
return reterr; |
| 1246 |
} |
| 1247 |
|
| 1248 |
static_assert(kTextbufSize >= 2 * kMaxIdBlen, "KeepOneId() needs to be updated."); |
| 1249 |
void KeepOneId(const char* sample_id_flattened, const SampleIdInfo* siip, uint32_t raw_sample_ct, uint32_t iid_sid, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1250 |
// Assumes sample_id_flattened is a multistr (sequence of nonempty |
| 1251 |
// null-terminated strings, end-of-sequence is denoted by an empty string) |
| 1252 |
// with 1-3 parts. |
| 1253 |
// If it has 1 part, interpret as an IID, setting FID to 0. |
| 1254 |
// If it has 2 parts, interpret as FID-IID unless iid_sid is true. |
| 1255 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1256 |
{ |
| 1257 |
const char* cur_sid = nullptr; |
| 1258 |
uintptr_t cur_sid_blen = 0; |
| 1259 |
const char* cur_fid_iid; |
| 1260 |
uintptr_t cur_fid_iid_blen; |
| 1261 |
{ |
| 1262 |
const char* part1_start = sample_id_flattened; |
| 1263 |
const uint32_t part1_blen = strlen(part1_start) + 1; |
| 1264 |
const char* part2_start = &(part1_start[part1_blen]); |
| 1265 |
char* fid_iid_write_iter = g_textbuf; |
| 1266 |
if (!(*part2_start)) { |
| 1267 |
fid_iid_write_iter = strcpya_k(fid_iid_write_iter, "0\t"); |
| 1268 |
fid_iid_write_iter = memcpya(fid_iid_write_iter, part1_start, part1_blen); |
| 1269 |
} else { |
| 1270 |
const uint32_t part2_blen = strlen(part2_start) + 1; |
| 1271 |
const char* sid_start = &(part2_start[part2_blen]); |
| 1272 |
if (!(*sid_start)) { |
| 1273 |
if (!iid_sid) { |
| 1274 |
fid_iid_write_iter = memcpyax(fid_iid_write_iter, part1_start, part1_blen - 1, '\t'); |
| 1275 |
fid_iid_write_iter = memcpya(fid_iid_write_iter, part2_start, part2_blen); |
| 1276 |
|
| 1277 |
} else { |
| 1278 |
fid_iid_write_iter = strcpya_k(fid_iid_write_iter, "0\t"); |
| 1279 |
fid_iid_write_iter = memcpya(fid_iid_write_iter, part1_start, part1_blen); |
| 1280 |
cur_sid = part2_start; |
| 1281 |
cur_sid_blen = part2_blen; |
| 1282 |
} |
| 1283 |
} else { |
| 1284 |
fid_iid_write_iter = memcpyax(fid_iid_write_iter, part1_start, part1_blen - 1, '\t'); |
| 1285 |
fid_iid_write_iter = memcpya(fid_iid_write_iter, part2_start, part2_blen); |
| 1286 |
cur_sid = sid_start; |
| 1287 |
cur_sid_blen = strlen(sid_start) + 1; |
| 1288 |
} |
| 1289 |
} |
| 1290 |
cur_fid_iid_blen = fid_iid_write_iter - g_textbuf; |
| 1291 |
cur_fid_iid = g_textbuf; |
| 1292 |
} |
| 1293 |
const char* sids = siip->sids; |
| 1294 |
if (cur_sid) { |
| 1295 |
if (!sids) { |
| 1296 |
// No per-sample SID comparisons. Either SID is always ok, or it never |
| 1297 |
// is and we can immediately return sample_ct = 0. |
| 1298 |
if ((siip->flags & kfSampleIdStrictSid0) && (!strequal_k_unsafe(cur_sid, "0"))) { |
| 1299 |
goto KeepOneId_match_none; |
| 1300 |
} |
| 1301 |
cur_sid = nullptr; |
| 1302 |
cur_sid_blen = 0; |
| 1303 |
} |
| 1304 |
} else { |
| 1305 |
if (sids) { |
| 1306 |
cur_sid = &(g_one_char_strs[96]); // "0" |
| 1307 |
cur_sid_blen = 2; |
| 1308 |
} |
| 1309 |
} |
| 1310 |
const char* sample_ids = siip->sample_ids; |
| 1311 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 1312 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 1313 |
if ((cur_fid_iid_blen > max_sample_id_blen) || (cur_sid_blen > max_sid_blen)) { |
| 1314 |
goto KeepOneId_match_none; |
| 1315 |
} |
| 1316 |
uint32_t new_sample_ct = 0; |
| 1317 |
for (uint32_t widx = 0; widx != raw_sample_ctl; ++widx) { |
| 1318 |
uintptr_t cur_word = sample_include[widx]; |
| 1319 |
if (cur_word) { |
| 1320 |
const uintptr_t sample_uidx_base = widx * kBitsPerWord; |
| 1321 |
uintptr_t new_word = 0; |
| 1322 |
do { |
| 1323 |
const uint32_t sample_uidx_lowbits = ctzw(cur_word); |
| 1324 |
const uintptr_t sample_uidx = sample_uidx_base + sample_uidx_lowbits; |
| 1325 |
if (memequal(&(sample_ids[sample_uidx * max_sample_id_blen]), cur_fid_iid, cur_fid_iid_blen) && |
| 1326 |
((!cur_sid) || memequal(&(sids[sample_uidx * max_sid_blen]), cur_sid, cur_sid_blen))) { |
| 1327 |
new_word |= k1LU << sample_uidx_lowbits; |
| 1328 |
++new_sample_ct; |
| 1329 |
} |
| 1330 |
cur_word &= cur_word - 1; |
| 1331 |
} while (cur_word); |
| 1332 |
sample_include[widx] = new_word; |
| 1333 |
} |
| 1334 |
} |
| 1335 |
logprintf("--indv: %u sample%s remaining.\n", new_sample_ct, (new_sample_ct == 1)? "" : "s"); |
| 1336 |
*sample_ct_ptr = new_sample_ct; |
| 1337 |
return; |
| 1338 |
} |
| 1339 |
KeepOneId_match_none: |
| 1340 |
ZeroWArr(raw_sample_ctl, sample_include); |
| 1341 |
*sample_ct_ptr = 0; |
| 1342 |
logputs("--indv: 0 samples remaining.\n"); |
| 1343 |
} |
| 1344 |
|
| 1345 |
// Minor extension of PLINK 1.x --filter. (Renamed since --filter is not |
| 1346 |
// sufficiently self-describing; PLINK has lots of other filters on both |
| 1347 |
// samples and variants. --filter is automatically converted to |
| 1348 |
// --keep-col-match for backward compatibility, though.) |
| 1349 |
PglErr KeepColMatch(const char* fname, const SampleIdInfo* siip, const char* strs_flattened, const char* col_name, uint32_t raw_sample_ct, uint32_t col_num, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1350 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1351 |
uintptr_t line_idx = 0; |
| 1352 |
PglErr reterr = kPglRetSuccess; |
| 1353 |
TextStream txs; |
| 1354 |
PreinitTextStream(&txs); |
| 1355 |
{ |
| 1356 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 1357 |
if (!orig_sample_ct) { |
| 1358 |
goto KeepColMatch_ret_1; |
| 1359 |
} |
| 1360 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1361 |
uintptr_t* seen_xid_idxs; |
| 1362 |
uintptr_t* keep_uidxs; |
| 1363 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(orig_sample_ct), &seen_xid_idxs) || |
| 1364 |
bigstack_calloc_w(raw_sample_ctl, &keep_uidxs))) { |
| 1365 |
goto KeepColMatch_ret_NOMEM; |
| 1366 |
} |
| 1367 |
|
| 1368 |
char* sorted_strbox; |
| 1369 |
uintptr_t max_str_blen; |
| 1370 |
uint32_t str_ct; |
| 1371 |
if (unlikely(MultistrToStrboxDedupAlloc(strs_flattened, &sorted_strbox, &str_ct, &max_str_blen))) { |
| 1372 |
goto KeepColMatch_ret_NOMEM; |
| 1373 |
} |
| 1374 |
|
| 1375 |
reterr = SizeAndInitTextStream(fname, bigstack_left() - (bigstack_left() / 4), 1, &txs); |
| 1376 |
if (unlikely(reterr)) { |
| 1377 |
goto KeepColMatch_ret_TSTREAM_FAIL; |
| 1378 |
} |
| 1379 |
char* line_start; |
| 1380 |
XidMode xid_mode; |
| 1381 |
reterr = LoadXidHeader("keep-col-match", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeaderFixedWidth : kfXidHeaderFixedWidthIgnoreSid, &line_idx, &txs, &xid_mode, &line_start); |
| 1382 |
if (unlikely(reterr)) { |
| 1383 |
if (reterr == kPglRetEof) { |
| 1384 |
logerrputs("Error: Empty --keep-col-match file.\n"); |
| 1385 |
goto KeepColMatch_ret_MALFORMED_INPUT; |
| 1386 |
} |
| 1387 |
goto KeepColMatch_ret_TSTREAM_XID_FAIL; |
| 1388 |
} |
| 1389 |
const uint32_t id_col_ct = GetXidColCt(xid_mode); |
| 1390 |
uint32_t postid_col_idx = 0; |
| 1391 |
if (!col_name) { |
| 1392 |
if (!col_num) { |
| 1393 |
if (unlikely(id_col_ct == 3)) { |
| 1394 |
logerrputs("Error: You must specify a --keep-col-match column with --keep-col-match-name or\n--keep-col-match-num.\n"); |
| 1395 |
goto KeepColMatch_ret_INCONSISTENT_INPUT; |
| 1396 |
} |
| 1397 |
col_num = 3; |
| 1398 |
} |
| 1399 |
if (unlikely(id_col_ct >= col_num)) { |
| 1400 |
logerrputs("Error: --keep-col-match-num parameter too small (it refers to a sample ID\ncolumn in the --keep-col-match file).\n"); |
| 1401 |
goto KeepColMatch_ret_INCONSISTENT_INPUT; |
| 1402 |
} |
| 1403 |
postid_col_idx = col_num - id_col_ct; |
| 1404 |
} else { |
| 1405 |
if (unlikely(*line_start != '#')) { |
| 1406 |
logerrputs("Error: --keep-col-match-name requires the --keep-col-match file to have a\nheader line starting with #FID or #IID.\n"); |
| 1407 |
goto KeepColMatch_ret_INCONSISTENT_INPUT; |
| 1408 |
} |
| 1409 |
const char* linebuf_iter = NextTokenMult(line_start, id_col_ct); |
| 1410 |
if (unlikely(!linebuf_iter)) { |
| 1411 |
logerrputs("Error: --keep-col-match-name column not found in --keep-col-match file.\n"); |
| 1412 |
goto KeepColMatch_ret_INCONSISTENT_INPUT; |
| 1413 |
} |
| 1414 |
const uint32_t col_name_slen = strlen(col_name); |
| 1415 |
uint32_t cur_col_idx = 0; |
| 1416 |
do { |
| 1417 |
++cur_col_idx; |
| 1418 |
const char* token_end = CurTokenEnd(linebuf_iter); |
| 1419 |
if ((S_CAST(uintptr_t, token_end - linebuf_iter) == col_name_slen) && memequal(linebuf_iter, col_name, col_name_slen)) { |
| 1420 |
if (unlikely(postid_col_idx)) { |
| 1421 |
snprintf(g_logbuf, kLogbufSize, "Error: Multiple columns in --keep-col-match file are named '%s'.\n", col_name); |
| 1422 |
goto KeepColMatch_ret_INCONSISTENT_INPUT_WW; |
| 1423 |
} |
| 1424 |
postid_col_idx = cur_col_idx; |
| 1425 |
} |
| 1426 |
linebuf_iter = FirstNonTspace(token_end); |
| 1427 |
} while (!IsEolnKns(*linebuf_iter)); |
| 1428 |
if (unlikely(!postid_col_idx)) { |
| 1429 |
logerrputs("Error: --keep-col-match-name column not found in --keep-col-match file.\n"); |
| 1430 |
goto KeepColMatch_ret_INCONSISTENT_INPUT; |
| 1431 |
} |
| 1432 |
} |
| 1433 |
uint32_t* xid_map = nullptr; |
| 1434 |
char* sorted_xidbox = nullptr; |
| 1435 |
uintptr_t max_xid_blen; |
| 1436 |
reterr = SortedXidboxInitAlloc(sample_include, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 1437 |
if (unlikely(reterr)) { |
| 1438 |
goto KeepColMatch_ret_1; |
| 1439 |
} |
| 1440 |
char* idbuf = nullptr; |
| 1441 |
if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) { |
| 1442 |
goto KeepColMatch_ret_NOMEM; |
| 1443 |
} |
| 1444 |
if (*line_start == '#') { |
| 1445 |
++line_idx; |
| 1446 |
line_start = TextGet(&txs); |
| 1447 |
} |
| 1448 |
for (; line_start; ++line_idx, line_start = TextGet(&txs)) { |
| 1449 |
const char* linebuf_iter = line_start; |
| 1450 |
uint32_t xid_idx_start; |
| 1451 |
uint32_t xid_idx_end; |
| 1452 |
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx_start, &xid_idx_end, idbuf)) { |
| 1453 |
if (unlikely(!linebuf_iter)) { |
| 1454 |
goto KeepColMatch_ret_MISSING_TOKENS; |
| 1455 |
} |
| 1456 |
continue; |
| 1457 |
} |
| 1458 |
if (unlikely(IsSet(seen_xid_idxs, xid_idx_start))) { |
| 1459 |
logerrprintfww("Error: Sample ID on line %" PRIuPTR " of --keep-col-match file duplicates one earlier in the file.\n", line_idx); |
| 1460 |
goto KeepColMatch_ret_MALFORMED_INPUT; |
| 1461 |
} |
| 1462 |
SetBit(xid_idx_start, seen_xid_idxs); |
| 1463 |
linebuf_iter = NextTokenMult(linebuf_iter, postid_col_idx); |
| 1464 |
if (unlikely(!linebuf_iter)) { |
| 1465 |
goto KeepColMatch_ret_MISSING_TOKENS; |
| 1466 |
} |
| 1467 |
const char* token_end = CurTokenEnd(linebuf_iter); |
| 1468 |
const int32_t ii = bsearch_strbox(linebuf_iter, sorted_strbox, token_end - linebuf_iter, max_str_blen, str_ct); |
| 1469 |
if (ii != -1) { |
| 1470 |
for (; xid_idx_start != xid_idx_end; ++xid_idx_start) { |
| 1471 |
const uint32_t sample_uidx = xid_map[xid_idx_start]; |
| 1472 |
SetBit(sample_uidx, keep_uidxs); |
| 1473 |
} |
| 1474 |
} |
| 1475 |
} |
| 1476 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 1477 |
goto KeepColMatch_ret_TSTREAM_FAIL; |
| 1478 |
} |
| 1479 |
memcpy(sample_include, keep_uidxs, raw_sample_ctl * sizeof(intptr_t)); |
| 1480 |
const uint32_t sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 1481 |
*sample_ct_ptr = sample_ct; |
| 1482 |
logprintf("--keep-col-match: %u sample%s remaining.\n", sample_ct, (sample_ct == 1)? "" : "s"); |
| 1483 |
} |
| 1484 |
while (0) { |
| 1485 |
KeepColMatch_ret_NOMEM: |
| 1486 |
reterr = kPglRetNomem; |
| 1487 |
break; |
| 1488 |
KeepColMatch_ret_TSTREAM_XID_FAIL: |
| 1489 |
if (!TextStreamErrcode(&txs)) { |
| 1490 |
break; |
| 1491 |
} |
| 1492 |
KeepColMatch_ret_TSTREAM_FAIL: |
| 1493 |
TextStreamErrPrint("--keep-col-match file", &txs); |
| 1494 |
break; |
| 1495 |
KeepColMatch_ret_MALFORMED_INPUT: |
| 1496 |
reterr = kPglRetMalformedInput; |
| 1497 |
break; |
| 1498 |
KeepColMatch_ret_MISSING_TOKENS: |
| 1499 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --keep-col-match file has fewer tokens than expected.\n", line_idx); |
| 1500 |
KeepColMatch_ret_INCONSISTENT_INPUT_WW: |
| 1501 |
WordWrapB(0); |
| 1502 |
logerrputsb(); |
| 1503 |
KeepColMatch_ret_INCONSISTENT_INPUT: |
| 1504 |
reterr = kPglRetInconsistentInput; |
| 1505 |
break; |
| 1506 |
} |
| 1507 |
KeepColMatch_ret_1: |
| 1508 |
BigstackReset(bigstack_mark); |
| 1509 |
CleanupTextStream2("--keep-col-match file", &txs, &reterr); |
| 1510 |
return reterr; |
| 1511 |
} |
| 1512 |
|
| 1513 |
PglErr RequirePheno(const PhenoCol* pheno_cols, const char* pheno_names, const char* require_pheno_flattened, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t is_covar, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1514 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1515 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 1516 |
PglErr reterr = kPglRetSuccess; |
| 1517 |
{ |
| 1518 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 1519 |
if (!orig_sample_ct) { |
| 1520 |
goto RequirePheno_ret_1; |
| 1521 |
} |
| 1522 |
uint32_t required_pheno_ct = 0; |
| 1523 |
uintptr_t max_required_pheno_blen = 2; |
| 1524 |
uintptr_t* matched_phenos = nullptr; |
| 1525 |
char* sorted_required_pheno_names = nullptr; |
| 1526 |
if (require_pheno_flattened) { |
| 1527 |
if (unlikely(MultistrToStrboxDedupAlloc(require_pheno_flattened, &sorted_required_pheno_names, &required_pheno_ct, &max_required_pheno_blen))) { |
| 1528 |
goto RequirePheno_ret_NOMEM; |
| 1529 |
} |
| 1530 |
if (unlikely(bigstack_calloc_w(1 + (required_pheno_ct / kBitsPerWord), &matched_phenos))) { |
| 1531 |
goto RequirePheno_ret_NOMEM; |
| 1532 |
} |
| 1533 |
} else { |
| 1534 |
if (!pheno_ct) { |
| 1535 |
logerrputs(is_covar? "Warning: No covariates loaded; ignoring --require-covar.\n" : "Warning: No phenotypes loaded; ignoring --require-pheno.\n"); |
| 1536 |
goto RequirePheno_ret_1; |
| 1537 |
} |
| 1538 |
required_pheno_ct = pheno_ct; |
| 1539 |
} |
| 1540 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1541 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1542 |
if (sorted_required_pheno_names) { |
| 1543 |
const char* cur_pheno_name = &(pheno_names[pheno_idx * max_pheno_name_blen]); |
| 1544 |
const int32_t ii = bsearch_strbox(cur_pheno_name, sorted_required_pheno_names, strlen(cur_pheno_name), max_required_pheno_blen, required_pheno_ct); |
| 1545 |
if (ii == -1) { |
| 1546 |
continue; |
| 1547 |
} |
| 1548 |
SetBitI(ii, matched_phenos); |
| 1549 |
} |
| 1550 |
BitvecAnd(pheno_cols[pheno_idx].nonmiss, raw_sample_ctl, sample_include); |
| 1551 |
} |
| 1552 |
if (matched_phenos) { |
| 1553 |
const uint32_t first_unmatched_idx = AdvTo0Bit(matched_phenos, 0); |
| 1554 |
if (unlikely(first_unmatched_idx < required_pheno_ct)) { |
| 1555 |
logerrprintfww("Error: --require-%s '%s' not loaded.\n", is_covar? "covar covariate" : "pheno phenotype", &(sorted_required_pheno_names[first_unmatched_idx * max_required_pheno_blen])); |
| 1556 |
goto RequirePheno_ret_INCONSISTENT_INPUT; |
| 1557 |
} |
| 1558 |
} |
| 1559 |
const uint32_t new_sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 1560 |
const uint32_t removed_sample_ct = orig_sample_ct - new_sample_ct; |
| 1561 |
logprintf("--require-%s: %u sample%s removed.\n", is_covar? "covar" : "pheno", removed_sample_ct, (removed_sample_ct == 1)? "" : "s"); |
| 1562 |
*sample_ct_ptr = new_sample_ct; |
| 1563 |
} |
| 1564 |
while (0) { |
| 1565 |
RequirePheno_ret_NOMEM: |
| 1566 |
reterr = kPglRetNomem; |
| 1567 |
break; |
| 1568 |
RequirePheno_ret_INCONSISTENT_INPUT: |
| 1569 |
reterr = kPglRetInconsistentInput; |
| 1570 |
break; |
| 1571 |
} |
| 1572 |
RequirePheno_ret_1: |
| 1573 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 1574 |
return reterr; |
| 1575 |
} |
| 1576 |
|
| 1577 |
PglErr KeepRemoveIf(const CmpExpr* cmp_expr, const PhenoCol* pheno_cols, const char* pheno_names, const PhenoCol* covar_cols, const char* covar_names, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t covar_ct, uintptr_t max_covar_name_blen, uint32_t affection_01, uint32_t is_remove, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1578 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1579 |
PglErr reterr = kPglRetSuccess; |
| 1580 |
{ |
| 1581 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 1582 |
if (!orig_sample_ct) { |
| 1583 |
goto KeepRemoveIf_ret_1; |
| 1584 |
} |
| 1585 |
const char* cur_name = cmp_expr->pheno_name; |
| 1586 |
const uintptr_t name_blen = 1 + strlen(cur_name); |
| 1587 |
const PhenoCol* cur_pheno_col = nullptr; |
| 1588 |
if (name_blen <= max_pheno_name_blen) { |
| 1589 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1590 |
if (memequal(cur_name, &(pheno_names[pheno_idx * max_pheno_name_blen]), name_blen)) { |
| 1591 |
cur_pheno_col = &(pheno_cols[pheno_idx]); |
| 1592 |
break; |
| 1593 |
} |
| 1594 |
} |
| 1595 |
} |
| 1596 |
if (!cur_pheno_col) { |
| 1597 |
if (name_blen <= max_covar_name_blen) { |
| 1598 |
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) { |
| 1599 |
if (memequal(cur_name, &(covar_names[covar_idx * max_covar_name_blen]), name_blen)) { |
| 1600 |
cur_pheno_col = &(covar_cols[covar_idx]); |
| 1601 |
break; |
| 1602 |
} |
| 1603 |
} |
| 1604 |
} |
| 1605 |
} |
| 1606 |
if (unlikely(!cur_pheno_col)) { |
| 1607 |
// could no-op for --remove-if? don't implement that unless/until |
| 1608 |
// someone asks for it, though. |
| 1609 |
snprintf(g_logbuf, kLogbufSize, "Error: --%s-if phenotype/covariate not loaded.\n", is_remove? "remove" : "keep"); |
| 1610 |
goto KeepRemoveIf_ret_INCONSISTENT_INPUT_2; |
| 1611 |
} |
| 1612 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1613 |
CmpBinaryOp binary_op = cmp_expr->binary_op; |
| 1614 |
const uint32_t pheno_must_exist = is_remove ^ (binary_op != kCmpOperatorNoteq); |
| 1615 |
const uintptr_t* pheno_nm = cur_pheno_col->nonmiss; |
| 1616 |
if (pheno_must_exist) { |
| 1617 |
BitvecAnd(pheno_nm, raw_sample_ctl, sample_include); |
| 1618 |
} |
| 1619 |
uintptr_t* sample_include_intersect; |
| 1620 |
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include_intersect))) { |
| 1621 |
goto KeepRemoveIf_ret_NOMEM; |
| 1622 |
} |
| 1623 |
memcpy(sample_include_intersect, sample_include, raw_sample_ctl * sizeof(intptr_t)); |
| 1624 |
if (!pheno_must_exist) { |
| 1625 |
BitvecAnd(pheno_nm, raw_sample_ctl, sample_include_intersect); |
| 1626 |
} |
| 1627 |
const uint32_t sample_intersect_ct = PopcountWords(sample_include_intersect, raw_sample_ctl); |
| 1628 |
const char* cur_val_str = &(cur_name[name_blen]); |
| 1629 |
const uint32_t val_slen = strlen(cur_val_str); |
| 1630 |
if (cur_pheno_col->type_code == kPhenoDtypeQt) { |
| 1631 |
double val; |
| 1632 |
if (unlikely(!ScantokDouble(cur_val_str, &val))) { |
| 1633 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s-if value (finite number expected).\n", is_remove? "remove" : "keep"); |
| 1634 |
goto KeepRemoveIf_ret_INCONSISTENT_INPUT_2; |
| 1635 |
} |
| 1636 |
if (is_remove) { |
| 1637 |
binary_op = S_CAST(CmpBinaryOp, kCmpOperatorEq - S_CAST(uint32_t, binary_op)); |
| 1638 |
} |
| 1639 |
const double* pheno_vals = cur_pheno_col->data.qt; |
| 1640 |
uintptr_t sample_uidx_base = 0; |
| 1641 |
uintptr_t cur_bits = sample_include_intersect[0]; |
| 1642 |
switch (binary_op) { |
| 1643 |
case kCmpOperatorNoteq: |
| 1644 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1645 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1646 |
if (pheno_vals[sample_uidx] == val) { |
| 1647 |
ClearBit(sample_uidx, sample_include); |
| 1648 |
} |
| 1649 |
} |
| 1650 |
break; |
| 1651 |
case kCmpOperatorLe: |
| 1652 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1653 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1654 |
if (pheno_vals[sample_uidx] >= val) { |
| 1655 |
ClearBit(sample_uidx, sample_include); |
| 1656 |
} |
| 1657 |
} |
| 1658 |
break; |
| 1659 |
case kCmpOperatorLeq: |
| 1660 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1661 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1662 |
if (pheno_vals[sample_uidx] > val) { |
| 1663 |
ClearBit(sample_uidx, sample_include); |
| 1664 |
} |
| 1665 |
} |
| 1666 |
break; |
| 1667 |
case kCmpOperatorGe: |
| 1668 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1669 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1670 |
if (pheno_vals[sample_uidx] <= val) { |
| 1671 |
ClearBit(sample_uidx, sample_include); |
| 1672 |
} |
| 1673 |
} |
| 1674 |
break; |
| 1675 |
case kCmpOperatorGeq: |
| 1676 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1677 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1678 |
if (pheno_vals[sample_uidx] < val) { |
| 1679 |
ClearBit(sample_uidx, sample_include); |
| 1680 |
} |
| 1681 |
} |
| 1682 |
break; |
| 1683 |
case kCmpOperatorEq: |
| 1684 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1685 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1686 |
if (pheno_vals[sample_uidx] != val) { |
| 1687 |
ClearBit(sample_uidx, sample_include); |
| 1688 |
} |
| 1689 |
} |
| 1690 |
break; |
| 1691 |
} |
| 1692 |
} else { |
| 1693 |
if (unlikely((binary_op != kCmpOperatorNoteq) && (binary_op != kCmpOperatorEq))) { |
| 1694 |
snprintf(g_logbuf, kLogbufSize, "Error: --%s-if operator type mismatch (binary and categorical phenotypes only support == and !=).\n", is_remove? "remove" : "keep"); |
| 1695 |
goto KeepRemoveIf_ret_INCONSISTENT_INPUT_WW; |
| 1696 |
} |
| 1697 |
if (cur_pheno_col->type_code == kPhenoDtypeCc) { |
| 1698 |
uint32_t val_12 = 0; // 1 = control, 2 = case |
| 1699 |
if (val_slen == 1) { |
| 1700 |
val_12 = affection_01 + ctou32(cur_val_str[0]) - 48; |
| 1701 |
if ((val_12 != 1) && (val_12 != 2)) { |
| 1702 |
val_12 = 0; |
| 1703 |
} |
| 1704 |
} else if (val_slen == 4) { |
| 1705 |
if (MatchUpperK(cur_val_str, "CASE")) { |
| 1706 |
val_12 = 2; |
| 1707 |
} else if (MatchUpperK(cur_val_str, "CTRL")) { |
| 1708 |
val_12 = 1; |
| 1709 |
} |
| 1710 |
} else if (MatchUpperKLen(cur_val_str, "CONTROL", val_slen)) { |
| 1711 |
val_12 = 1; |
| 1712 |
} |
| 1713 |
if (unlikely(!val_12)) { |
| 1714 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s-if value ('case'/'%c' or 'control'/'ctrl'/'%c' expected).\n", is_remove? "remove" : "keep", '2' - affection_01, '1' - affection_01); |
| 1715 |
goto KeepRemoveIf_ret_INCONSISTENT_INPUT_WW; |
| 1716 |
} |
| 1717 |
if (is_remove ^ (val_12 == 2)) { |
| 1718 |
BitvecAnd(cur_pheno_col->data.cc, raw_sample_ctl, sample_include); |
| 1719 |
} else { |
| 1720 |
BitvecInvmask(cur_pheno_col->data.cc, raw_sample_ctl, sample_include); |
| 1721 |
} |
| 1722 |
} else { |
| 1723 |
assert(cur_pheno_col->type_code == kPhenoDtypeCat); |
| 1724 |
const uint32_t nonnull_cat_ct = cur_pheno_col->nonnull_category_ct; |
| 1725 |
const uint32_t cat_idx = 1 + bsearch_strptr_natural(cur_val_str, &(cur_pheno_col->category_names[1]), nonnull_cat_ct); |
| 1726 |
if (!cat_idx) { |
| 1727 |
double dxx; |
| 1728 |
if (unlikely(ScanadvDouble(cur_val_str, &dxx))) { |
| 1729 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s-if value (category name expected).\n", is_remove? "remove" : "keep"); |
| 1730 |
goto KeepRemoveIf_ret_INCONSISTENT_INPUT_2; |
| 1731 |
} |
| 1732 |
// tolerate this, there are legitimate reasons for empty categories |
| 1733 |
// to exist |
| 1734 |
logerrprintfww("Warning: Categorical phenotype/covariate '%s' does not have a category named '%s'.\n", cur_name, cur_val_str); |
| 1735 |
if (pheno_must_exist) { |
| 1736 |
ZeroWArr(raw_sample_ctl, sample_include); |
| 1737 |
} |
| 1738 |
} else { |
| 1739 |
const uint32_t* cur_cats = cur_pheno_col->data.cat; |
| 1740 |
uintptr_t sample_uidx_base = 0; |
| 1741 |
uintptr_t cur_bits = sample_include_intersect[0]; |
| 1742 |
if (pheno_must_exist) { |
| 1743 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1744 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1745 |
if (cur_cats[sample_uidx] != cat_idx) { |
| 1746 |
ClearBit(sample_uidx, sample_include); |
| 1747 |
} |
| 1748 |
} |
| 1749 |
} else { |
| 1750 |
for (uint32_t sample_idx = 0; sample_idx != sample_intersect_ct; ++sample_idx) { |
| 1751 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &cur_bits); |
| 1752 |
if (cur_cats[sample_uidx] == cat_idx) { |
| 1753 |
ClearBit(sample_uidx, sample_include); |
| 1754 |
} |
| 1755 |
} |
| 1756 |
} |
| 1757 |
} |
| 1758 |
} |
| 1759 |
} |
| 1760 |
|
| 1761 |
const uint32_t new_sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 1762 |
const uint32_t removed_sample_ct = orig_sample_ct - new_sample_ct; |
| 1763 |
logprintf("--%s-if: %u sample%s removed.\n", is_remove? "remove" : "keep", removed_sample_ct, (removed_sample_ct == 1)? "" : "s"); |
| 1764 |
*sample_ct_ptr = new_sample_ct; |
| 1765 |
} |
| 1766 |
while (0) { |
| 1767 |
KeepRemoveIf_ret_NOMEM: |
| 1768 |
reterr = kPglRetNomem; |
| 1769 |
break; |
| 1770 |
KeepRemoveIf_ret_INCONSISTENT_INPUT_WW: |
| 1771 |
WordWrapB(0); |
| 1772 |
KeepRemoveIf_ret_INCONSISTENT_INPUT_2: |
| 1773 |
logerrputsb(); |
| 1774 |
reterr = kPglRetInconsistentInput; |
| 1775 |
break; |
| 1776 |
} |
| 1777 |
KeepRemoveIf_ret_1: |
| 1778 |
BigstackReset(bigstack_mark); |
| 1779 |
return reterr; |
| 1780 |
} |
| 1781 |
|
| 1782 |
PglErr KeepRemoveCatsInternal(const PhenoCol* cur_pheno_col, const char* cats_fname, const char* cat_names_flattened, uint32_t raw_sample_ct, uint32_t is_remove, uint32_t max_thread_ct, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1783 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1784 |
char file_descrip[32]; |
| 1785 |
if (is_remove) { |
| 1786 |
strcpy_k(file_descrip, "--remove-cats file"); |
| 1787 |
} else { |
| 1788 |
strcpy_k(file_descrip, "--keep-cats file"); |
| 1789 |
} |
| 1790 |
TokenStream tks; |
| 1791 |
PreinitTokenStream(&tks); |
| 1792 |
PglErr reterr = kPglRetSuccess; |
| 1793 |
{ |
| 1794 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 1795 |
if (!orig_sample_ct) { |
| 1796 |
goto KeepRemoveCatsInternal_ret_1; |
| 1797 |
} |
| 1798 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 1799 |
const uint32_t cat_ct = cur_pheno_col->nonnull_category_ct + 1; |
| 1800 |
const uint32_t cat_ctl = BitCtToWordCt(cat_ct); |
| 1801 |
uintptr_t* affected_samples; |
| 1802 |
uintptr_t* cat_include; |
| 1803 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &affected_samples) || |
| 1804 |
bigstack_alloc_w(cat_ctl, &cat_include))) { |
| 1805 |
goto KeepRemoveCatsInternal_ret_NOMEM; |
| 1806 |
} |
| 1807 |
SetAllBits(cat_ct, cat_include); |
| 1808 |
const char* const* category_names = cur_pheno_col->category_names; |
| 1809 |
uint32_t* cat_id_htable; |
| 1810 |
uint32_t id_htable_size; |
| 1811 |
reterr = AllocAndPopulateIdHtableMt(cat_include, category_names, cat_ct, 0, max_thread_ct, &cat_id_htable, nullptr, &id_htable_size, nullptr); |
| 1812 |
if (unlikely(reterr)) { |
| 1813 |
goto KeepRemoveCatsInternal_ret_1; |
| 1814 |
} |
| 1815 |
ZeroWArr(cat_ctl, cat_include); |
| 1816 |
if (cats_fname) { |
| 1817 |
reterr = InitTokenStream(cats_fname, MAXV(max_thread_ct - 1, 1), &tks); |
| 1818 |
if (unlikely(reterr)) { |
| 1819 |
goto KeepRemoveCatsInternal_ret_TKSTREAM_FAIL; |
| 1820 |
} |
| 1821 |
uintptr_t skip_ct = 0; |
| 1822 |
while (1) { |
| 1823 |
char* shard_boundaries[2]; |
| 1824 |
reterr = TksNext(&tks, 1, shard_boundaries); |
| 1825 |
if (reterr) { |
| 1826 |
break; |
| 1827 |
} |
| 1828 |
char* shard_iter = shard_boundaries[0]; |
| 1829 |
char* shard_end = shard_boundaries[1]; |
| 1830 |
while (1) { |
| 1831 |
shard_iter = FirstPostspaceBounded(shard_iter, shard_end); |
| 1832 |
if (shard_iter == shard_end) { |
| 1833 |
break; |
| 1834 |
} |
| 1835 |
char* token_end = CurTokenEnd(shard_iter); |
| 1836 |
*token_end = '\0'; |
| 1837 |
// can't overread, category_names not in main workspace |
| 1838 |
const uint32_t cur_cat_idx = IdHtableFind(shard_iter, category_names, cat_id_htable, token_end - shard_iter, id_htable_size); |
| 1839 |
if (cur_cat_idx == UINT32_MAX) { |
| 1840 |
++skip_ct; |
| 1841 |
} else { |
| 1842 |
SetBit(cur_cat_idx, cat_include); |
| 1843 |
} |
| 1844 |
shard_iter = token_end; |
| 1845 |
} |
| 1846 |
} |
| 1847 |
if (unlikely(reterr != kPglRetEof)) { |
| 1848 |
goto KeepRemoveCatsInternal_ret_TKSTREAM_FAIL; |
| 1849 |
} |
| 1850 |
if (CleanupTokenStream3(file_descrip, &tks, &reterr)) { |
| 1851 |
goto KeepRemoveCatsInternal_ret_1; |
| 1852 |
} |
| 1853 |
if (skip_ct) { |
| 1854 |
logerrprintf("Warning: %" PRIuPTR " --%s-cats categor%s not present.\n", skip_ct, is_remove? "remove" : "keep", (skip_ct == 1)? "y" : "ies"); |
| 1855 |
} |
| 1856 |
} |
| 1857 |
if (cat_names_flattened) { |
| 1858 |
uint32_t skip_ct = 0; |
| 1859 |
const char* cat_names_iter = cat_names_flattened; |
| 1860 |
do { |
| 1861 |
const uint32_t cat_name_slen = strlen(cat_names_iter); |
| 1862 |
const uint32_t cur_cat_idx = IdHtableFind(cat_names_iter, category_names, cat_id_htable, cat_name_slen, id_htable_size); |
| 1863 |
if (cur_cat_idx == UINT32_MAX) { |
| 1864 |
++skip_ct; |
| 1865 |
} else { |
| 1866 |
SetBit(cur_cat_idx, cat_include); |
| 1867 |
} |
| 1868 |
cat_names_iter = &(cat_names_iter[cat_name_slen + 1]); |
| 1869 |
} while (*cat_names_iter); |
| 1870 |
if (skip_ct) { |
| 1871 |
logerrprintf("Warning: %u --%s-cat-names categor%s not present.\n", skip_ct, is_remove? "remove" : "keep", (skip_ct == 1)? "y" : "ies"); |
| 1872 |
} |
| 1873 |
} |
| 1874 |
const uint32_t selected_cat_ct = PopcountWords(cat_include, cat_ctl); |
| 1875 |
if (!selected_cat_ct) { |
| 1876 |
logerrprintf("Warning: No matching --%s-cat-names category names.\n", is_remove? "remove-cats/--remove" : "keep-cats/--keep"); |
| 1877 |
} else { |
| 1878 |
const uint32_t* cur_cats = cur_pheno_col->data.cat; |
| 1879 |
uintptr_t sample_uidx_base = 0; |
| 1880 |
uintptr_t cur_bits = sample_include[0]; |
| 1881 |
for (uint32_t sample_idx = 0; sample_idx != orig_sample_ct; ++sample_idx) { |
| 1882 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 1883 |
const uint32_t cur_cat_idx = cur_cats[sample_uidx]; |
| 1884 |
if (IsSet(cat_include, cur_cat_idx)) { |
| 1885 |
SetBit(sample_uidx, affected_samples); |
| 1886 |
} |
| 1887 |
} |
| 1888 |
if (is_remove) { |
| 1889 |
BitvecInvmask(affected_samples, raw_sample_ctl, sample_include); |
| 1890 |
} else { |
| 1891 |
BitvecAnd(affected_samples, raw_sample_ctl, sample_include); |
| 1892 |
} |
| 1893 |
const uint32_t new_sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 1894 |
const uint32_t removed_sample_ct = orig_sample_ct - new_sample_ct; |
| 1895 |
logprintfww("--%s-cat-names: %u categor%s selected, %u sample%s removed.\n", is_remove? "remove-cats/--remove" : "keep-cats/--keep", selected_cat_ct, (selected_cat_ct == 1)? "y" : "ies", removed_sample_ct, (removed_sample_ct == 1)? "" : "s"); |
| 1896 |
*sample_ct_ptr = new_sample_ct; |
| 1897 |
} |
| 1898 |
} |
| 1899 |
while (0) { |
| 1900 |
KeepRemoveCatsInternal_ret_NOMEM: |
| 1901 |
reterr = kPglRetNomem; |
| 1902 |
break; |
| 1903 |
KeepRemoveCatsInternal_ret_TKSTREAM_FAIL: |
| 1904 |
TokenStreamErrPrint(file_descrip, &tks); |
| 1905 |
break; |
| 1906 |
} |
| 1907 |
KeepRemoveCatsInternal_ret_1: |
| 1908 |
CleanupTokenStream2(file_descrip, &tks, &reterr); |
| 1909 |
BigstackReset(bigstack_mark); |
| 1910 |
return reterr; |
| 1911 |
} |
| 1912 |
|
| 1913 |
PglErr KeepRemoveCats(const char* cats_fname, const char* cat_names_flattened, const char* cat_phenoname, const PhenoCol* pheno_cols, const char* pheno_names, const PhenoCol* covar_cols, const char* covar_names, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t covar_ct, uintptr_t max_covar_name_blen, uint32_t is_remove, uint32_t max_thread_ct, uintptr_t* sample_include, uint32_t* sample_ct_ptr) { |
| 1914 |
PglErr reterr = kPglRetSuccess; |
| 1915 |
{ |
| 1916 |
if (!(*sample_ct_ptr)) { |
| 1917 |
goto KeepRemoveCats_ret_1; |
| 1918 |
} |
| 1919 |
if (!cat_phenoname) { |
| 1920 |
// Default behavior: |
| 1921 |
// 1. If at least one categorical phenotype exists, fail on >= 2, select |
| 1922 |
// it if one. |
| 1923 |
// 2. Otherwise, fail if 0 or >= 2 categorical covariates, select the |
| 1924 |
// categorical covariate if there's exactly one. |
| 1925 |
uint32_t cat_pheno_idx = UINT32_MAX; |
| 1926 |
const PhenoCol* cur_pheno_col = nullptr; |
| 1927 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1928 |
if (pheno_cols[pheno_idx].type_code == kPhenoDtypeCat) { |
| 1929 |
if (unlikely(cat_pheno_idx != UINT32_MAX)) { |
| 1930 |
snprintf(g_logbuf, kLogbufSize, "Error: Multiple categorical phenotypes present. Use --%s-cat-pheno to specify which phenotype/covariate you want to filter on.\n", is_remove? "remove" : "keep"); |
| 1931 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_WW; |
| 1932 |
} |
| 1933 |
cat_pheno_idx = pheno_idx; |
| 1934 |
} |
| 1935 |
} |
| 1936 |
if (cat_pheno_idx != UINT32_MAX) { |
| 1937 |
cur_pheno_col = &(pheno_cols[cat_pheno_idx]); |
| 1938 |
} else { |
| 1939 |
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) { |
| 1940 |
if (covar_cols[covar_idx].type_code == kPhenoDtypeCat) { |
| 1941 |
if (unlikely(cat_pheno_idx != UINT32_MAX)) { |
| 1942 |
snprintf(g_logbuf, kLogbufSize, "Error: Multiple categorical covariates and no categorical phenotype present. Use --%s-cat-pheno to specify which phenotype/covariate you want to filter on.\n", is_remove? "remove" : "keep"); |
| 1943 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_WW; |
| 1944 |
} |
| 1945 |
cat_pheno_idx = covar_idx; |
| 1946 |
} |
| 1947 |
} |
| 1948 |
if (unlikely(cat_pheno_idx == UINT32_MAX)) { |
| 1949 |
snprintf(g_logbuf, kLogbufSize, "Error: --%s-cat-names requires a categorical phenotype or covariate.\n", is_remove? "remove-cats/--remove" : "keep-cats/--keep"); |
| 1950 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_WW; |
| 1951 |
} |
| 1952 |
cur_pheno_col = &(covar_cols[cat_pheno_idx]); |
| 1953 |
} |
| 1954 |
reterr = KeepRemoveCatsInternal(cur_pheno_col, cats_fname, cat_names_flattened, raw_sample_ct, is_remove, max_thread_ct, sample_include, sample_ct_ptr); |
| 1955 |
if (unlikely(reterr)) { |
| 1956 |
goto KeepRemoveCats_ret_1; |
| 1957 |
} |
| 1958 |
} else { |
| 1959 |
const uintptr_t name_blen = 1 + strlen(cat_phenoname); |
| 1960 |
uint32_t success = 0; |
| 1961 |
if (name_blen <= max_pheno_name_blen) { |
| 1962 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 1963 |
if (memequal(cat_phenoname, &(pheno_names[pheno_idx * max_pheno_name_blen]), name_blen)) { |
| 1964 |
const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]); |
| 1965 |
if (unlikely(cur_pheno_col->type_code != kPhenoDtypeCat)) { |
| 1966 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a categorical phenotype.\n", cat_phenoname); |
| 1967 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_WW; |
| 1968 |
} |
| 1969 |
reterr = KeepRemoveCatsInternal(cur_pheno_col, cats_fname, cat_names_flattened, raw_sample_ct, is_remove, max_thread_ct, sample_include, sample_ct_ptr); |
| 1970 |
if (unlikely(reterr)) { |
| 1971 |
goto KeepRemoveCats_ret_1; |
| 1972 |
} |
| 1973 |
success = 1; |
| 1974 |
break; |
| 1975 |
} |
| 1976 |
} |
| 1977 |
} |
| 1978 |
if (name_blen <= max_covar_name_blen) { |
| 1979 |
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) { |
| 1980 |
if (memequal(cat_phenoname, &(covar_names[covar_idx * max_covar_name_blen]), name_blen)) { |
| 1981 |
const PhenoCol* cur_pheno_col = &(covar_cols[covar_idx]); |
| 1982 |
if (unlikely(cur_pheno_col->type_code != kPhenoDtypeCat)) { |
| 1983 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a categorical covariate.\n", cat_phenoname); |
| 1984 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_WW; |
| 1985 |
} |
| 1986 |
reterr = KeepRemoveCatsInternal(cur_pheno_col, cats_fname, cat_names_flattened, raw_sample_ct, is_remove, max_thread_ct, sample_include, sample_ct_ptr); |
| 1987 |
if (unlikely(reterr)) { |
| 1988 |
goto KeepRemoveCats_ret_1; |
| 1989 |
} |
| 1990 |
success = 1; |
| 1991 |
break; |
| 1992 |
} |
| 1993 |
} |
| 1994 |
} |
| 1995 |
if (unlikely(!success)) { |
| 1996 |
snprintf(g_logbuf, kLogbufSize, "Error: --%s-cat-pheno phenotype/covariate not loaded.\n", is_remove? "remove" : "keep"); |
| 1997 |
goto KeepRemoveCats_ret_INCONSISTENT_INPUT_2; |
| 1998 |
} |
| 1999 |
} |
| 2000 |
} |
| 2001 |
while (0) { |
| 2002 |
KeepRemoveCats_ret_INCONSISTENT_INPUT_WW: |
| 2003 |
WordWrapB(0); |
| 2004 |
KeepRemoveCats_ret_INCONSISTENT_INPUT_2: |
| 2005 |
logerrputsb(); |
| 2006 |
reterr = kPglRetInconsistentInput; |
| 2007 |
break; |
| 2008 |
} |
| 2009 |
KeepRemoveCats_ret_1: |
| 2010 |
return reterr; |
| 2011 |
} |
| 2012 |
|
| 2013 |
void ComputeAlleleFreqs(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const uint64_t* founder_allele_ddosages, uint32_t variant_ct, double af_pseudocount, double* allele_freqs) { |
| 2014 |
// ok for maj_alleles or allele_freqs to be nullptr |
| 2015 |
// note that founder_allele_ddosages is in 32768ths |
| 2016 |
// could multithread this, but not a high priority since it would only tend |
| 2017 |
// to reduce wall-clock time by a fraction of a second |
| 2018 |
const double af_pseudocount_ddosage = af_pseudocount * u31tod(kDosageMax); |
| 2019 |
uint32_t cur_allele_ct = 2; |
| 2020 |
uintptr_t variant_uidx_base = 0; |
| 2021 |
uintptr_t cur_bits = variant_include[0]; |
| 2022 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 2023 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 2024 |
uintptr_t allele_idx_offset_base; |
| 2025 |
if (!allele_idx_offsets) { |
| 2026 |
allele_idx_offset_base = 2 * variant_uidx; |
| 2027 |
} else { |
| 2028 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 2029 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 2030 |
} |
| 2031 |
const uint64_t* cur_founder_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]); |
| 2032 |
uint64_t tot_ddosage = 0; |
| 2033 |
for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) { |
| 2034 |
tot_ddosage += cur_founder_allele_ddosages[allele_idx]; |
| 2035 |
} |
| 2036 |
double* cur_allele_freqs_base = &(allele_freqs[allele_idx_offset_base - variant_uidx]); |
| 2037 |
const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1; |
| 2038 |
if (!tot_ddosage) { |
| 2039 |
const double cur_allele_ct_m1_recip = 1.0 / u31tod(cur_allele_ct); |
| 2040 |
for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct_m1; ++allele_idx) { |
| 2041 |
cur_allele_freqs_base[allele_idx] = cur_allele_ct_m1_recip; |
| 2042 |
} |
| 2043 |
} else { |
| 2044 |
const double adj_tot_ddosage_recip = 1.0 / (u63tod(tot_ddosage) + af_pseudocount_ddosage * u31tod(cur_allele_ct)); |
| 2045 |
for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct_m1; ++allele_idx) { |
| 2046 |
const double cur_ddosage = u63tod(cur_founder_allele_ddosages[allele_idx]) + af_pseudocount_ddosage; |
| 2047 |
cur_allele_freqs_base[allele_idx] = cur_ddosage * adj_tot_ddosage_recip; |
| 2048 |
} |
| 2049 |
} |
| 2050 |
} |
| 2051 |
} |
| 2052 |
|
| 2053 |
CONSTI32(kMaxReadFreqAlleles, 255); |
| 2054 |
|
| 2055 |
// relevant column types: |
| 2056 |
// 0: variant ID |
| 2057 |
// 1: ref allele code |
| 2058 |
// 2: all alt allele codes (potentially just alt1) |
| 2059 |
// |
| 2060 |
// (3-4 are --freq only) |
| 2061 |
// 3: ref freq/count |
| 2062 |
// 4: either all freqs/counts, or all-but-ref |
| 2063 |
// |
| 2064 |
// 5: obs ct (only relevant for --freq, but can be in --geno-counts) |
| 2065 |
// |
| 2066 |
// (6-11 are --geno-counts/--freqx only) |
| 2067 |
// 6: hom-ref count |
| 2068 |
// 7: het ref-alt counts (worst case, just ref-alt1) |
| 2069 |
// 8: altx-alty counts (worst case, just hom-alt1), or all pairs |
| 2070 |
// 9: hap-ref count |
| 2071 |
// 10: hap-alt counts (worst case, just hap-alt1), or all hap counts |
| 2072 |
// 11: --geno-counts numeq (if present, ignore 6..10) |
| 2073 |
// |
| 2074 |
// overrideable: |
| 2075 |
// 12->2: ALT1 |
| 2076 |
// 13->4: ALT1_FREQ/ALT1_CT |
| 2077 |
// 14->7: HET_REF_ALT1_CT |
| 2078 |
// 15->8: HOM_ALT1_CT |
| 2079 |
// 16->10: HAP_ALT1_CT |
| 2080 |
ENUM_U31_DEF_START() |
| 2081 |
kReadFreqColVarId = 0, |
| 2082 |
kReadFreqColRefAllele, |
| 2083 |
kReadFreqColAltAlleles, |
| 2084 |
|
| 2085 |
kReadFreqColRefFreq, |
| 2086 |
kReadFreqColAltFreqs, |
| 2087 |
|
| 2088 |
kReadFreqColObsCt, |
| 2089 |
|
| 2090 |
kReadFreqColHomRefCt, |
| 2091 |
kReadFreqColHetRefAltCts, |
| 2092 |
kReadFreqColNonrefDiploidCts, |
| 2093 |
kReadFreqColHapRefCt, |
| 2094 |
kReadFreqColHapAltCts, |
| 2095 |
kReadFreqColGenoCtNumeq, |
| 2096 |
|
| 2097 |
kReadFreqColAlt1Allele, |
| 2098 |
kReadFreqColAlt1Freq, |
| 2099 |
kReadFreqColHetRefAlt1Ct, |
| 2100 |
kReadFreqColHomAlt1Ct, |
| 2101 |
kReadFreqColHapAlt1Ct, |
| 2102 |
|
| 2103 |
kReadFreqColNull |
| 2104 |
ENUM_U31_DEF_END(ReadFreqColidx); |
| 2105 |
|
| 2106 |
FLAGSET_DEF_START() |
| 2107 |
kfReadFreqColset0, |
| 2108 |
kfReadFreqColsetVarId = (1 << kReadFreqColVarId), |
| 2109 |
kfReadFreqColsetRefAllele = (1 << kReadFreqColRefAllele), |
| 2110 |
kfReadFreqColsetAltAlleles = (1 << kReadFreqColAltAlleles), |
| 2111 |
kfReadFreqColsetBase = (kfReadFreqColsetVarId | kfReadFreqColsetRefAllele | kfReadFreqColsetAltAlleles), |
| 2112 |
|
| 2113 |
kfReadFreqColsetRefFreq = (1 << kReadFreqColRefFreq), |
| 2114 |
kfReadFreqColsetAltFreqs = (1 << kReadFreqColAltFreqs), |
| 2115 |
kfReadFreqColsetAfreqOnly = (kfReadFreqColsetRefFreq | kfReadFreqColsetAltFreqs), |
| 2116 |
|
| 2117 |
kfReadFreqColsetObsCt = (1 << kReadFreqColObsCt), |
| 2118 |
|
| 2119 |
kfReadFreqColsetHomRefCt = (1 << kReadFreqColHomRefCt), |
| 2120 |
kfReadFreqColsetHetRefAltCts = (1 << kReadFreqColHetRefAltCts), |
| 2121 |
kfReadFreqColsetNonrefDiploidCts = (1 << kReadFreqColNonrefDiploidCts), |
| 2122 |
kfReadFreqColsetHapRefCt = (1 << kReadFreqColHapRefCt), |
| 2123 |
kfReadFreqColsetHapAltCts = (1 << kReadFreqColHapAltCts), |
| 2124 |
kfReadFreqColsetGcountDefault = ((kfReadFreqColsetHapAltCts * 2) - kfReadFreqColsetHomRefCt), |
| 2125 |
|
| 2126 |
kfReadFreqColsetGenoCtNumeq = (1 << kReadFreqColGenoCtNumeq), |
| 2127 |
kfReadFreqColsetGcountOnly = (kfReadFreqColsetGcountDefault | kfReadFreqColsetGenoCtNumeq), |
| 2128 |
|
| 2129 |
kfReadFreqColsetAlt1Allele = (1 << kReadFreqColAlt1Allele), |
| 2130 |
kfReadFreqColsetAlt1Freq = (1 << kReadFreqColAlt1Freq), |
| 2131 |
kfReadFreqColsetHetRefAlt1Ct = (1 << kReadFreqColHetRefAlt1Ct), |
| 2132 |
kfReadFreqColsetHomAlt1Ct = (1 << kReadFreqColHomAlt1Ct), |
| 2133 |
kfReadFreqColsetHapAlt1Ct = (1 << kReadFreqColHapAlt1Ct) |
| 2134 |
FLAGSET_DEF_END(ReadFreqColFlags); |
| 2135 |
|
| 2136 |
// Support exact reconstruction of original allele frequencies in --freq counts |
| 2137 |
// case. |
| 2138 |
static inline double ForceCountToDosage(double raw_count) { |
| 2139 |
return u63tod(S_CAST(int64_t, raw_count * kDosageMax + 0.5)) * kRecipDosageMax; |
| 2140 |
} |
| 2141 |
|
| 2142 |
PglErr ReadAlleleFreqs(const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const char* read_freq_fname, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_variant_id_slen, uint32_t max_allele_slen, double af_pseudocount, uint32_t max_thread_ct, double* allele_freqs, uintptr_t** variant_afreqcalcp) { |
| 2143 |
// support PLINK 1.9 --freq/--freqx, and 2.0 --freq/--geno-counts. |
| 2144 |
// GCTA-format no longer supported since it inhibits the allele consistency |
| 2145 |
// check. |
| 2146 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 2147 |
uintptr_t line_idx = 0; |
| 2148 |
PglErr reterr = kPglRetSuccess; |
| 2149 |
TextStream read_freq_txs; |
| 2150 |
PreinitTextStream(&read_freq_txs); |
| 2151 |
{ |
| 2152 |
if (!variant_ct) { |
| 2153 |
logerrputs("Warning: Skipping --read-freq since no variants remain.\n"); |
| 2154 |
goto ReadAlleleFreqs_ret_1; |
| 2155 |
} |
| 2156 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 2157 |
double* cur_allele_freqs; |
| 2158 |
uintptr_t* matched_loaded_alleles = nullptr; // spurious g++ 4.8 warning |
| 2159 |
uintptr_t* matched_internal_alleles = nullptr; |
| 2160 |
uint32_t* loaded_to_internal_allele_idx; |
| 2161 |
uintptr_t* already_seen; |
| 2162 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, variant_afreqcalcp) || |
| 2163 |
bigstack_calloc_d(kMaxReadFreqAlleles, &cur_allele_freqs) || |
| 2164 |
bigstack_alloc_w(BitCtToWordCt(kMaxReadFreqAlleles), &matched_loaded_alleles) || |
| 2165 |
bigstack_alloc_w(BitCtToWordCt(max_allele_ct), &matched_internal_alleles) || |
| 2166 |
bigstack_alloc_u32(kMaxReadFreqAlleles, &loaded_to_internal_allele_idx) || |
| 2167 |
bigstack_calloc_w(raw_variant_ctl, &already_seen))) { |
| 2168 |
goto ReadAlleleFreqs_ret_NOMEM; |
| 2169 |
} |
| 2170 |
bigstack_mark = R_CAST(unsigned char*, cur_allele_freqs); |
| 2171 |
|
| 2172 |
reterr = SizeAndInitTextStream(read_freq_fname, bigstack_left() / 8, MAXV(max_thread_ct - 1, 1), &read_freq_txs); |
| 2173 |
if (unlikely(reterr)) { |
| 2174 |
goto ReadAlleleFreqs_ret_TSTREAM_FAIL; |
| 2175 |
} |
| 2176 |
uint32_t* variant_id_htable = nullptr; |
| 2177 |
uint32_t variant_id_htable_size; |
| 2178 |
reterr = AllocAndPopulateIdHtableMt(variant_include, variant_ids, variant_ct, 0, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr); |
| 2179 |
if (unlikely(reterr)) { |
| 2180 |
goto ReadAlleleFreqs_ret_1; |
| 2181 |
} |
| 2182 |
char* line_start; |
| 2183 |
do { |
| 2184 |
++line_idx; |
| 2185 |
line_start = TextGet(&read_freq_txs); |
| 2186 |
if (unlikely(!line_start)) { |
| 2187 |
if (!TextStreamErrcode2(&read_freq_txs, &reterr)) { |
| 2188 |
logerrputs("Error: Empty --read-freq file.\n"); |
| 2189 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2190 |
} |
| 2191 |
goto ReadAlleleFreqs_ret_TSTREAM_FAIL; |
| 2192 |
} |
| 2193 |
// automatically skip header lines that start with '##' or '# ' |
| 2194 |
} while ((*line_start == '#') && (ctou32(line_start[1]) <= '#')); |
| 2195 |
uint32_t col_skips[kReadFreqColNull]; |
| 2196 |
ReadFreqColidx col_types[kReadFreqColNull]; |
| 2197 |
uint32_t overrideable_pos[kReadFreqColNull - kReadFreqColAlt1Allele]; |
| 2198 |
uint32_t geno_counts = 0; |
| 2199 |
uint32_t main_eq = 0; |
| 2200 |
uint32_t is_numeq = 0; |
| 2201 |
uint32_t use_obs_ct = 0; |
| 2202 |
uint32_t infer_one_freq = 0; |
| 2203 |
uint32_t infer_freq_loaded_idx = 0; |
| 2204 |
uint32_t relevant_col_ct = 0; |
| 2205 |
|
| 2206 |
// interpretation of ColAltAlleles |
| 2207 |
uint32_t allele_list_just_alt1 = 1; |
| 2208 |
|
| 2209 |
uint32_t is_frac = 0; // if true, one frequency can be missing |
| 2210 |
// could add consistency check (can't mix FREQ and CT) |
| 2211 |
|
| 2212 |
// interpretation of ColAltFreqs and ColNonrefDiploidCts |
| 2213 |
uint32_t main_allele_idx_start = 1; |
| 2214 |
uint32_t main_list_just_alt1 = 1; |
| 2215 |
|
| 2216 |
// interpretation of ColHapAltCts |
| 2217 |
uint32_t hap_allele_idx_start = 1; |
| 2218 |
uint32_t hap_list_just_alt1 = 1; |
| 2219 |
|
| 2220 |
uint32_t het_list_just_alt1 = 1; // ColHetRefAltCts |
| 2221 |
|
| 2222 |
uint32_t biallelic_only = 0; |
| 2223 |
|
| 2224 |
ReadFreqColFlags header_cols = kfReadFreqColset0; |
| 2225 |
uint32_t skip_header = 1; |
| 2226 |
if (*line_start == '#') { |
| 2227 |
// PLINK 2.0 |
| 2228 |
// guaranteed nonspace |
| 2229 |
const char* linebuf_iter = &(line_start[1]); |
| 2230 |
|
| 2231 |
uint32_t col_idx = 0; |
| 2232 |
while (1) { |
| 2233 |
const char* token_end = CurTokenEnd(linebuf_iter); |
| 2234 |
const uint32_t token_slen = token_end - linebuf_iter; |
| 2235 |
ReadFreqColidx cur_colidx = kReadFreqColNull; |
| 2236 |
if (token_slen <= 4) { |
| 2237 |
if (strequal_k(linebuf_iter, "ID", token_slen)) { |
| 2238 |
cur_colidx = kReadFreqColVarId; |
| 2239 |
} else if (token_slen == 3) { |
| 2240 |
if (memequal_sk(linebuf_iter, "REF")) { |
| 2241 |
cur_colidx = kReadFreqColRefAllele; |
| 2242 |
} else if (memequal_sk(linebuf_iter, "ALT")) { |
| 2243 |
cur_colidx = kReadFreqColAltAlleles; |
| 2244 |
if (allele_list_just_alt1) { |
| 2245 |
header_cols &= ~kfReadFreqColsetAlt1Allele; |
| 2246 |
allele_list_just_alt1 = 0; |
| 2247 |
} |
| 2248 |
} else if (memequal_sk(linebuf_iter, "CTS")) { |
| 2249 |
goto ReadAlleleFreqs_freqmain_found1; |
| 2250 |
} |
| 2251 |
} else if (strequal_k(linebuf_iter, "ALT1", token_slen) && allele_list_just_alt1) { |
| 2252 |
cur_colidx = kReadFreqColAlt1Allele; |
| 2253 |
} |
| 2254 |
} else if (strequal_k(linebuf_iter, "REF_FREQ", token_slen) || |
| 2255 |
strequal_k(linebuf_iter, "REF_CT", token_slen)) { |
| 2256 |
cur_colidx = kReadFreqColRefFreq; |
| 2257 |
if (linebuf_iter[4] == 'F') { |
| 2258 |
is_frac = 1; |
| 2259 |
} |
| 2260 |
} else if ((strequal_k(linebuf_iter, "ALT1_FREQ", token_slen) || |
| 2261 |
strequal_k(linebuf_iter, "ALT1_CT", token_slen)) && |
| 2262 |
main_list_just_alt1) { |
| 2263 |
cur_colidx = kReadFreqColAlt1Freq; |
| 2264 |
if (linebuf_iter[5] == 'F') { |
| 2265 |
is_frac = 1; |
| 2266 |
} |
| 2267 |
} else if (strequal_k(linebuf_iter, "ALT_FREQS", token_slen) || |
| 2268 |
strequal_k(linebuf_iter, "ALT_CTS", token_slen)) { |
| 2269 |
if (linebuf_iter[4] == 'F') { |
| 2270 |
is_frac = 1; |
| 2271 |
} |
| 2272 |
goto ReadAlleleFreqs_freqmain_found2; |
| 2273 |
} else if (strequal_k(linebuf_iter, "FREQS", token_slen)) { |
| 2274 |
is_frac = 1; |
| 2275 |
goto ReadAlleleFreqs_freqmain_found1; |
| 2276 |
} else if (strequal_k(linebuf_iter, "ALT_NUM_FREQS", token_slen) || |
| 2277 |
strequal_k(linebuf_iter, "ALT_NUM_CTS", token_slen)) { |
| 2278 |
is_numeq = 1; |
| 2279 |
goto ReadAlleleFreqs_freqmain_found2; |
| 2280 |
} else if (strequal_k(linebuf_iter, "NUM_FREQS", token_slen) || |
| 2281 |
strequal_k(linebuf_iter, "NUM_CTS", token_slen)) { |
| 2282 |
is_numeq = 1; |
| 2283 |
ReadAlleleFreqs_freqmain_found1: |
| 2284 |
main_allele_idx_start = 0; |
| 2285 |
ReadAlleleFreqs_freqmain_found2: |
| 2286 |
cur_colidx = kReadFreqColAltFreqs; |
| 2287 |
if (main_list_just_alt1) { |
| 2288 |
header_cols &= ~kfReadFreqColsetAlt1Freq; |
| 2289 |
main_list_just_alt1 = 0; |
| 2290 |
} |
| 2291 |
} else if (strequal_k(linebuf_iter, "OBS_CT", token_slen)) { |
| 2292 |
cur_colidx = kReadFreqColObsCt; |
| 2293 |
} else if (strequal_k(linebuf_iter, "HOM_REF_CT", token_slen)) { |
| 2294 |
cur_colidx = kReadFreqColHomRefCt; |
| 2295 |
} else if (strequal_k(linebuf_iter, "HET_REF_ALT1_CT", token_slen) && het_list_just_alt1) { |
| 2296 |
cur_colidx = kReadFreqColHetRefAlt1Ct; |
| 2297 |
} else if (strequal_k(linebuf_iter, "HET_REF_ALT_CTS", token_slen)) { |
| 2298 |
cur_colidx = kReadFreqColHetRefAltCts; |
| 2299 |
if (het_list_just_alt1) { |
| 2300 |
header_cols &= ~kfReadFreqColsetHetRefAlt1Ct; |
| 2301 |
het_list_just_alt1 = 0; |
| 2302 |
} |
| 2303 |
} else if (strequal_k(linebuf_iter, "HOM_ALT1_CT", token_slen) && main_list_just_alt1) { |
| 2304 |
cur_colidx = kReadFreqColHomAlt1Ct; |
| 2305 |
} else if (strequal_k(linebuf_iter, "TWO_ALT_GENO_CTS", token_slen) || |
| 2306 |
strequal_k(linebuf_iter, "NONREF_DIPLOID_GENO_CTS", token_slen)) { |
| 2307 |
goto ReadAlleleFreqs_countmain_found; |
| 2308 |
} else if (strequal_k(linebuf_iter, "DIPLOID_GENO_CTS", token_slen)) { |
| 2309 |
main_allele_idx_start = 0; |
| 2310 |
ReadAlleleFreqs_countmain_found: |
| 2311 |
cur_colidx = kReadFreqColNonrefDiploidCts; |
| 2312 |
if (main_list_just_alt1) { |
| 2313 |
header_cols &= ~kfReadFreqColsetHomAlt1Ct; |
| 2314 |
// could make this use a different variable than FREQS does |
| 2315 |
main_list_just_alt1 = 0; |
| 2316 |
} |
| 2317 |
} else if (strequal_k(linebuf_iter, "HAP_REF_CT", token_slen)) { |
| 2318 |
cur_colidx = kReadFreqColHapRefCt; |
| 2319 |
} else if (strequal_k(linebuf_iter, "HAP_ALT1_CT", token_slen) && hap_list_just_alt1) { |
| 2320 |
cur_colidx = kReadFreqColHapAlt1Ct; |
| 2321 |
} else if (strequal_k(linebuf_iter, "HAP_ALT_CTS", token_slen)) { |
| 2322 |
goto ReadAlleleFreqs_hapmain_found; |
| 2323 |
} else if (strequal_k(linebuf_iter, "HAP_CTS", token_slen)) { |
| 2324 |
hap_allele_idx_start = 0; |
| 2325 |
ReadAlleleFreqs_hapmain_found: |
| 2326 |
cur_colidx = kReadFreqColHapAltCts; |
| 2327 |
if (hap_list_just_alt1) { |
| 2328 |
header_cols &= ~kfReadFreqColsetHapAlt1Ct; |
| 2329 |
hap_list_just_alt1 = 0; |
| 2330 |
} |
| 2331 |
} else if (strequal_k(linebuf_iter, "GENO_NUM_CTS", token_slen)) { |
| 2332 |
cur_colidx = kReadFreqColGenoCtNumeq; |
| 2333 |
is_numeq = 1; |
| 2334 |
} |
| 2335 |
if (cur_colidx != kReadFreqColNull) { |
| 2336 |
const ReadFreqColFlags cur_colset = S_CAST(ReadFreqColFlags, 1U << cur_colidx); |
| 2337 |
if (unlikely(header_cols & cur_colset)) { |
| 2338 |
logerrputs("Error: Conflicting columns in header line of --read-freq file.\n"); |
| 2339 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2340 |
} |
| 2341 |
if (cur_colidx >= kReadFreqColAlt1Allele) { |
| 2342 |
overrideable_pos[cur_colidx - kReadFreqColAlt1Allele] = relevant_col_ct; |
| 2343 |
} |
| 2344 |
header_cols |= cur_colset; |
| 2345 |
col_skips[relevant_col_ct] = col_idx; |
| 2346 |
col_types[relevant_col_ct++] = cur_colidx; |
| 2347 |
} |
| 2348 |
linebuf_iter = FirstNonTspace(token_end); |
| 2349 |
if (IsEolnKns(*linebuf_iter)) { |
| 2350 |
break; |
| 2351 |
} |
| 2352 |
++col_idx; |
| 2353 |
} |
| 2354 |
ReadFreqColFlags semifinal_header_cols = header_cols; |
| 2355 |
if (header_cols & kfReadFreqColsetAlt1Allele) { |
| 2356 |
header_cols ^= kfReadFreqColsetAltAlleles | kfReadFreqColsetAlt1Allele; |
| 2357 |
col_types[overrideable_pos[0]] = kReadFreqColAltAlleles; |
| 2358 |
} |
| 2359 |
if (header_cols & kfReadFreqColsetAlt1Freq) { |
| 2360 |
header_cols ^= kfReadFreqColsetAltFreqs | kfReadFreqColsetAlt1Freq; |
| 2361 |
col_types[overrideable_pos[kReadFreqColAlt1Freq - kReadFreqColAlt1Allele]] = kReadFreqColAltFreqs; |
| 2362 |
} |
| 2363 |
if (header_cols & kfReadFreqColsetHetRefAlt1Ct) { |
| 2364 |
header_cols ^= kfReadFreqColsetHetRefAltCts | kfReadFreqColsetHetRefAlt1Ct; |
| 2365 |
col_types[overrideable_pos[kReadFreqColHetRefAlt1Ct - kReadFreqColAlt1Allele]] = kReadFreqColHetRefAltCts; |
| 2366 |
} |
| 2367 |
if (header_cols & kfReadFreqColsetHomAlt1Ct) { |
| 2368 |
header_cols ^= kfReadFreqColsetNonrefDiploidCts | kfReadFreqColsetHomAlt1Ct; |
| 2369 |
col_types[overrideable_pos[kReadFreqColHomAlt1Ct - kReadFreqColAlt1Allele]] = kReadFreqColNonrefDiploidCts; |
| 2370 |
} |
| 2371 |
if (header_cols & kfReadFreqColsetHapAlt1Ct) { |
| 2372 |
header_cols ^= kfReadFreqColsetHapAltCts | kfReadFreqColsetHapAlt1Ct; |
| 2373 |
col_types[overrideable_pos[kReadFreqColHapAlt1Ct - kReadFreqColAlt1Allele]] = kReadFreqColHapAltCts; |
| 2374 |
} |
| 2375 |
if ((semifinal_header_cols != header_cols) && (!(header_cols & kfReadFreqColsetGenoCtNumeq))) { |
| 2376 |
// we're treating at least one ALT1 column as if it spoke for all ALT |
| 2377 |
// alleles |
| 2378 |
biallelic_only = 1; |
| 2379 |
} |
| 2380 |
|
| 2381 |
main_eq = is_numeq; |
| 2382 |
semifinal_header_cols = header_cols; |
| 2383 |
if (header_cols & kfReadFreqColsetAfreqOnly) { |
| 2384 |
if (unlikely(header_cols & kfReadFreqColsetGcountOnly)) { |
| 2385 |
logerrputs("Error: Conflicting columns in header line of --read-freq file (--freq and\n--geno-counts values mixed together).\n"); |
| 2386 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2387 |
} |
| 2388 |
ReadFreqColFlags header_cols_exempt = kfReadFreqColset0; |
| 2389 |
if ((header_cols & kfReadFreqColsetAltFreqs) && (!is_numeq)) { |
| 2390 |
// [ALT_]FREQS can be formatted as either |
| 2391 |
// 0.5,0,0.2 |
| 2392 |
// or |
| 2393 |
// A=0.5,G=0.2 |
| 2394 |
// Look at the first nonheader line to distinguish between these two. |
| 2395 |
++line_idx; |
| 2396 |
line_start = TextGet(&read_freq_txs); |
| 2397 |
if (unlikely(!line_start)) { |
| 2398 |
if (!TextStreamErrcode2(&read_freq_txs, &reterr)) { |
| 2399 |
logerrputs("Error: Empty --read-freq file.\n"); |
| 2400 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2401 |
} |
| 2402 |
goto ReadAlleleFreqs_ret_TSTREAM_FAIL; |
| 2403 |
} |
| 2404 |
linebuf_iter = line_start; |
| 2405 |
const char* alt_freq_str = nullptr; |
| 2406 |
for (uint32_t relevant_col_idx = 0; relevant_col_idx != relevant_col_ct; ++relevant_col_idx) { |
| 2407 |
if (col_types[relevant_col_idx] == kReadFreqColAltFreqs) { |
| 2408 |
alt_freq_str = NextTokenMult0(linebuf_iter, col_skips[relevant_col_idx]); |
| 2409 |
break; |
| 2410 |
} |
| 2411 |
} |
| 2412 |
if (unlikely(!alt_freq_str)) { |
| 2413 |
goto ReadAlleleFreqs_ret_MISSING_TOKENS; |
| 2414 |
} |
| 2415 |
const uint32_t alt_freq_slen = CurTokenEnd(alt_freq_str) - alt_freq_str; |
| 2416 |
// bare '.' can only appear in eq formats |
| 2417 |
main_eq = ((alt_freq_slen == 1) && (*alt_freq_str == '.')) || (memchr(alt_freq_str, '=', alt_freq_slen) != nullptr); |
| 2418 |
if (main_eq) { |
| 2419 |
header_cols_exempt = kfReadFreqColsetAltAlleles; |
| 2420 |
if (!main_allele_idx_start) { |
| 2421 |
header_cols_exempt |= kfReadFreqColsetRefAllele; |
| 2422 |
} |
| 2423 |
header_cols &= ~header_cols_exempt; |
| 2424 |
} |
| 2425 |
skip_header = 0; |
| 2426 |
} |
| 2427 |
if (unlikely(((header_cols & kfReadFreqColsetBase) | header_cols_exempt) != kfReadFreqColsetBase)) { |
| 2428 |
logerrputs("Error: Missing column(s) in --read-freq file (ID, REF, ALT[1] usually\nrequired).\n"); |
| 2429 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2430 |
} |
| 2431 |
if (!main_allele_idx_start) { |
| 2432 |
header_cols &= ~kfReadFreqColsetRefFreq; |
| 2433 |
} else { |
| 2434 |
if ((header_cols & (kfReadFreqColsetRefFreq | kfReadFreqColsetAltFreqs)) != (kfReadFreqColsetRefFreq | kfReadFreqColsetAltFreqs)) { |
| 2435 |
if (main_list_just_alt1) { |
| 2436 |
biallelic_only = 1; |
| 2437 |
} |
| 2438 |
infer_one_freq = 1; |
| 2439 |
infer_freq_loaded_idx = (header_cols / kfReadFreqColsetRefFreq) & 1; |
| 2440 |
if (!is_frac) { |
| 2441 |
if (unlikely(!(header_cols & kfReadFreqColsetObsCt))) { |
| 2442 |
logerrputs("Error: Missing column(s) in --read-freq file (at least two of {REF_CT, ALT1_CT,\nALT_CTS, OBS_CT} must be present).\n"); |
| 2443 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2444 |
} |
| 2445 |
use_obs_ct = 1; |
| 2446 |
} |
| 2447 |
} |
| 2448 |
} |
| 2449 |
logputs("--read-freq: PLINK 2 --freq file detected.\n"); |
| 2450 |
} else if (likely(header_cols & kfReadFreqColsetGcountOnly)) { |
| 2451 |
if (unlikely((header_cols & kfReadFreqColsetBase) != kfReadFreqColsetBase)) { |
| 2452 |
logerrputs("Error: Missing column(s) in --read-freq file (ID, REF, ALT[1] required).\n"); |
| 2453 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2454 |
} |
| 2455 |
// possible todo: allow one frequency/count to be missing. (not really |
| 2456 |
// necessary since PLINK 1.9 --freqx does not leave anything out, |
| 2457 |
// unlike PLINK 1.x --freq) |
| 2458 |
if (header_cols & kfReadFreqColsetGenoCtNumeq) { |
| 2459 |
// don't need anything but GENO_NUM_CTS |
| 2460 |
header_cols &= ~kfReadFreqColsetGcountDefault; |
| 2461 |
} else { |
| 2462 |
// require both diploid and haploid columns for now. (could |
| 2463 |
// conditionally drop one of these requirements later.) |
| 2464 |
if (unlikely(!(header_cols & kfReadFreqColsetNonrefDiploidCts))) { |
| 2465 |
logerrputs("Error: Missing column(s) in --read-freq file (HOM_ALT1_CT,\nTWO_ALT_GENO_CTS, or DIPLOID_GENO_CTS required).\n"); |
| 2466 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2467 |
} |
| 2468 |
if (!main_allele_idx_start) { |
| 2469 |
header_cols &= ~(kfReadFreqColsetHomRefCt | kfReadFreqColsetHetRefAltCts); |
| 2470 |
} else if (unlikely((header_cols & (kfReadFreqColsetHomRefCt | kfReadFreqColsetHetRefAltCts)) != (kfReadFreqColsetHomRefCt | kfReadFreqColsetHetRefAltCts))) { |
| 2471 |
logerrputs("Error: Missing column(s) in --read-freq file (HOM_REF_CT, HET_REF_ALT1_CT, or\nHET_REF_ALT_CTS required unless {DIPLOID_}GENO_CTS present).\n"); |
| 2472 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2473 |
} |
| 2474 |
if (unlikely(!(header_cols & kfReadFreqColsetHapAltCts))) { |
| 2475 |
logerrputs("Error: Missing column(s) in --read-freq file (HAP_ALT1_CT, HAP_ALT_CTS, or\nHAP_CTS required).\n"); |
| 2476 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2477 |
} |
| 2478 |
if (!hap_allele_idx_start) { |
| 2479 |
header_cols &= ~kfReadFreqColsetHapRefCt; |
| 2480 |
} else if (unlikely(!(header_cols & kfReadFreqColsetHapRefCt))) { |
| 2481 |
logerrputs("Error: Missing column(s) in --read-freq file (HAP_REF_CT required unless\nHAP_CTS or GENO_CTS present).\n"); |
| 2482 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2483 |
} |
| 2484 |
} |
| 2485 |
geno_counts = 1; |
| 2486 |
logputs("--read-freq: PLINK 2 --geno-counts file detected.\n"); |
| 2487 |
} else { |
| 2488 |
logerrputs("Error: Missing column(s) in --read-freq file (no frequencies/counts).\n"); |
| 2489 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT; |
| 2490 |
} |
| 2491 |
if (!use_obs_ct) { |
| 2492 |
header_cols &= ~kfReadFreqColsetObsCt; |
| 2493 |
} |
| 2494 |
if (semifinal_header_cols != header_cols) { |
| 2495 |
// remove redundant columns |
| 2496 |
uint32_t relevant_col_idx_read = 0; |
| 2497 |
while ((S_CAST(uint32_t, header_cols) >> col_types[relevant_col_idx_read]) & 1) { |
| 2498 |
++relevant_col_idx_read; |
| 2499 |
} |
| 2500 |
uint32_t relevant_col_idx_write = relevant_col_idx_read++; |
| 2501 |
for (; relevant_col_idx_read != relevant_col_ct; ++relevant_col_idx_read) { |
| 2502 |
const ReadFreqColidx cur_colidx = col_types[relevant_col_idx_read]; |
| 2503 |
if ((S_CAST(uint32_t, header_cols) >> cur_colidx) & 1) { |
| 2504 |
col_types[relevant_col_idx_write] = cur_colidx; |
| 2505 |
col_skips[relevant_col_idx_write] = col_skips[relevant_col_idx_read]; |
| 2506 |
++relevant_col_idx_write; |
| 2507 |
} |
| 2508 |
} |
| 2509 |
relevant_col_ct = relevant_col_idx_write; |
| 2510 |
} |
| 2511 |
for (uint32_t uii = relevant_col_ct - 1; uii; --uii) { |
| 2512 |
col_skips[uii] -= col_skips[uii - 1]; |
| 2513 |
} |
| 2514 |
} else { |
| 2515 |
// PLINK 1.x |
| 2516 |
// .frq: CHR SNP A1 A2 MAF NCHROBS |
| 2517 |
// .frq.count: CHR SNP A1 A2 C1 C2 G0 |
| 2518 |
// .frqx: CHR SNP A1 A2 C(HOM A1) C(HET) C(HOM A2) C(HAP A1) |
| 2519 |
// C(HAP A2) C(MISSING) |
| 2520 |
// (yeah, the spaces in the .frqx header were a mistake, should have used |
| 2521 |
// underscores. oh well, live and learn.) |
| 2522 |
col_skips[0] = 1; |
| 2523 |
col_skips[1] = 1; |
| 2524 |
col_skips[2] = 1; |
| 2525 |
col_skips[3] = 1; |
| 2526 |
|
| 2527 |
col_types[0] = kReadFreqColVarId; |
| 2528 |
// doesn't matter if we treat A1 or A2 as ref |
| 2529 |
col_types[1] = kReadFreqColRefAllele; |
| 2530 |
col_types[2] = kReadFreqColAltAlleles; |
| 2531 |
biallelic_only = 1; |
| 2532 |
if (StrStartsWithUnsafe(line_start, "CHR\tSNP\tA1\tA2\tC(HOM A1)\tC(HET)\tC(HOM A2)\tC(HAP A1)\tC(HAP A2)\tC(MISSING)")) { |
| 2533 |
col_skips[4] = 1; |
| 2534 |
col_skips[5] = 1; |
| 2535 |
col_skips[6] = 1; |
| 2536 |
col_skips[7] = 1; |
| 2537 |
|
| 2538 |
col_types[3] = kReadFreqColHomRefCt; |
| 2539 |
col_types[4] = kReadFreqColHetRefAltCts; |
| 2540 |
col_types[5] = kReadFreqColNonrefDiploidCts; |
| 2541 |
col_types[6] = kReadFreqColHapRefCt; |
| 2542 |
col_types[7] = kReadFreqColHapAltCts; |
| 2543 |
header_cols = kfReadFreqColsetBase | kfReadFreqColsetGcountOnly; |
| 2544 |
geno_counts = 1; |
| 2545 |
relevant_col_ct = 8; |
| 2546 |
logputs("--read-freq: PLINK 1.9 --freqx file detected.\n"); |
| 2547 |
} else { |
| 2548 |
if (unlikely(!tokequal_k(line_start, "CHR"))) { |
| 2549 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2550 |
} |
| 2551 |
const char* linebuf_iter = FirstNonTspace(&(line_start[3])); |
| 2552 |
if (unlikely(!tokequal_k(linebuf_iter, "SNP"))) { |
| 2553 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2554 |
} |
| 2555 |
linebuf_iter = FirstNonTspace(&(linebuf_iter[3])); |
| 2556 |
if (unlikely(!tokequal_k(linebuf_iter, "A1"))) { |
| 2557 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2558 |
} |
| 2559 |
linebuf_iter = FirstNonTspace(&(linebuf_iter[2])); |
| 2560 |
if (unlikely(!tokequal_k(linebuf_iter, "A2"))) { |
| 2561 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2562 |
} |
| 2563 |
linebuf_iter = FirstNonTspace(&(linebuf_iter[2])); |
| 2564 |
col_types[3] = kReadFreqColRefFreq; |
| 2565 |
if (tokequal_k(linebuf_iter, "MAF")) { |
| 2566 |
is_frac = 1; |
| 2567 |
infer_one_freq = 1; |
| 2568 |
infer_freq_loaded_idx = 1; |
| 2569 |
header_cols = kfReadFreqColsetBase | kfReadFreqColsetRefFreq; |
| 2570 |
relevant_col_ct = 4; |
| 2571 |
logputs("--read-freq: PLINK 1.x --freq file detected.\n"); |
| 2572 |
} else { |
| 2573 |
if (unlikely(!tokequal_k(linebuf_iter, "C1"))) { |
| 2574 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2575 |
} |
| 2576 |
linebuf_iter = FirstNonTspace(&(linebuf_iter[2])); |
| 2577 |
if (unlikely(!tokequal_k(linebuf_iter, "C2"))) { |
| 2578 |
goto ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER; |
| 2579 |
} |
| 2580 |
col_skips[4] = 1; |
| 2581 |
col_types[4] = kReadFreqColAltFreqs; |
| 2582 |
header_cols = kfReadFreqColsetBase | kfReadFreqColsetAfreqOnly; |
| 2583 |
relevant_col_ct = 5; |
| 2584 |
logputs("--read-freq: PLINK 1.x '--freq counts' file detected.\n"); |
| 2585 |
} |
| 2586 |
} |
| 2587 |
} |
| 2588 |
assert(relevant_col_ct <= 8); |
| 2589 |
|
| 2590 |
double freq_max = 4294967295.0; |
| 2591 |
if (is_frac) { |
| 2592 |
af_pseudocount = 0.0; |
| 2593 |
freq_max = 1.0; |
| 2594 |
} |
| 2595 |
uintptr_t skipped_variant_ct = 0; |
| 2596 |
uint32_t loaded_variant_ct = 0; |
| 2597 |
uint32_t cur_allele_ct = 2; |
| 2598 |
uint32_t variant_uidx = 0; |
| 2599 |
char* line_iter = line_start; |
| 2600 |
if (skip_header) { |
| 2601 |
line_iter = TextLineEnd(&read_freq_txs); |
| 2602 |
++line_idx; |
| 2603 |
} |
| 2604 |
for (; TextGetUnsafe2(&read_freq_txs, &line_iter); ++line_idx) { |
| 2605 |
{ |
| 2606 |
// not const since tokens may be null-terminated or comma-terminated |
| 2607 |
// later |
| 2608 |
char* token_ptrs[12]; |
| 2609 |
uint32_t token_slens[12]; |
| 2610 |
line_iter = TokenLex0(line_iter, R_CAST(uint32_t*, col_types), col_skips, relevant_col_ct, token_ptrs, token_slens); |
| 2611 |
if (unlikely(!line_iter)) { |
| 2612 |
goto ReadAlleleFreqs_ret_MISSING_TOKENS; |
| 2613 |
} |
| 2614 |
// characters may be modified, so better find the \n now just in case |
| 2615 |
// it gets clobbered |
| 2616 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 2617 |
const char* variant_id_start = token_ptrs[kReadFreqColVarId]; |
| 2618 |
const uint32_t variant_id_slen = token_slens[kReadFreqColVarId]; |
| 2619 |
variant_uidx = VariantIdDupflagHtableFind(variant_id_start, variant_ids, variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen); |
| 2620 |
if (variant_uidx >> 31) { |
| 2621 |
if (likely(variant_uidx == UINT32_MAX)) { |
| 2622 |
++skipped_variant_ct; |
| 2623 |
continue; |
| 2624 |
} |
| 2625 |
snprintf(g_logbuf, kLogbufSize, "Error: --read-freq variant ID '%s' appears multiple times in main dataset.\n", variant_ids[variant_uidx & 0x7fffffff]); |
| 2626 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_WW; |
| 2627 |
} |
| 2628 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 2629 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --read-freq file.\n", variant_ids[variant_uidx]); |
| 2630 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_WW; |
| 2631 |
} |
| 2632 |
SetBit(variant_uidx, already_seen); |
| 2633 |
|
| 2634 |
uintptr_t allele_idx_offset_base; |
| 2635 |
if (!allele_idx_offsets) { |
| 2636 |
allele_idx_offset_base = variant_uidx * 2; |
| 2637 |
} else { |
| 2638 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 2639 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 2640 |
if (biallelic_only) { |
| 2641 |
goto ReadAlleleFreqs_skip_variant; |
| 2642 |
} |
| 2643 |
} |
| 2644 |
ZeroWArr(BitCtToWordCt(cur_allele_ct), matched_internal_alleles); |
| 2645 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 2646 |
uint32_t loaded_allele_idx_end = 0; |
| 2647 |
{ |
| 2648 |
uint32_t unmatched_allele_ct = cur_allele_ct; |
| 2649 |
uint32_t cur_loaded_allele_code_slen; |
| 2650 |
char* cur_loaded_allele_code; |
| 2651 |
char* loaded_allele_code_iter; |
| 2652 |
char* loaded_allele_code_end; |
| 2653 |
if (header_cols & kfReadFreqColsetRefAllele) { |
| 2654 |
cur_loaded_allele_code_slen = token_slens[kReadFreqColRefAllele]; |
| 2655 |
cur_loaded_allele_code = token_ptrs[kReadFreqColRefAllele]; |
| 2656 |
// No special handling of missing allele code needed (if the |
| 2657 |
// fileset is valid). |
| 2658 |
cur_loaded_allele_code[cur_loaded_allele_code_slen] = '\0'; |
| 2659 |
if (header_cols & kfReadFreqColsetAltAlleles) { |
| 2660 |
loaded_allele_code_iter = token_ptrs[kReadFreqColAltAlleles]; |
| 2661 |
loaded_allele_code_end = &(loaded_allele_code_iter[token_slens[kReadFreqColAltAlleles]]); |
| 2662 |
*loaded_allele_code_end++ = ','; |
| 2663 |
} else { |
| 2664 |
// special case: with --freq alteq or alteqz column, we only need |
| 2665 |
// to scrape REF here |
| 2666 |
loaded_allele_code_iter = &(cur_loaded_allele_code[cur_loaded_allele_code_slen + 1]); |
| 2667 |
loaded_allele_code_end = loaded_allele_code_iter; |
| 2668 |
} |
| 2669 |
} else { |
| 2670 |
// no REF, only ALT. skip the first iteration of the loop. |
| 2671 |
loaded_allele_code_iter = token_ptrs[kReadFreqColAltAlleles]; |
| 2672 |
loaded_allele_code_end = &(loaded_allele_code_iter[token_slens[kReadFreqColAltAlleles]]); |
| 2673 |
*loaded_allele_code_end++ = ','; |
| 2674 |
|
| 2675 |
cur_loaded_allele_code = loaded_allele_code_iter; |
| 2676 |
loaded_allele_code_iter = S_CAST(char*, memchr(loaded_allele_code_iter, ',', loaded_allele_code_end - cur_loaded_allele_code)); |
| 2677 |
cur_loaded_allele_code_slen = loaded_allele_code_iter - cur_loaded_allele_code; |
| 2678 |
*loaded_allele_code_iter++ = '\0'; |
| 2679 |
loaded_allele_idx_end = 1; |
| 2680 |
matched_loaded_alleles[0] = 0; |
| 2681 |
} |
| 2682 |
uint32_t widx = 0; |
| 2683 |
while (1) { |
| 2684 |
if (!(loaded_allele_idx_end % kBitsPerWord)) { |
| 2685 |
widx = loaded_allele_idx_end / kBitsPerWord; |
| 2686 |
matched_loaded_alleles[widx] = 0; |
| 2687 |
} |
| 2688 |
if (cur_loaded_allele_code_slen <= max_allele_slen) { |
| 2689 |
const uint32_t cur_blen = cur_loaded_allele_code_slen + 1; |
| 2690 |
uintptr_t internal_allele_idx_base = 0; |
| 2691 |
uintptr_t cur_inv_bits = ~matched_internal_alleles[0]; |
| 2692 |
for (uint32_t unmatched_allele_idx = 0; unmatched_allele_idx != unmatched_allele_ct; ++unmatched_allele_idx) { |
| 2693 |
const uintptr_t internal_allele_idx = BitIter0(matched_internal_alleles, &internal_allele_idx_base, &cur_inv_bits); |
| 2694 |
if (memequal(cur_loaded_allele_code, cur_alleles[internal_allele_idx], cur_blen)) { |
| 2695 |
if (unlikely(IsSet(matched_internal_alleles, internal_allele_idx))) { |
| 2696 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate allele code on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 2697 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 2698 |
} |
| 2699 |
SetBit(internal_allele_idx, matched_internal_alleles); |
| 2700 |
SetBit(loaded_allele_idx_end, matched_loaded_alleles); |
| 2701 |
loaded_to_internal_allele_idx[loaded_allele_idx_end] = internal_allele_idx; |
| 2702 |
break; |
| 2703 |
} |
| 2704 |
} |
| 2705 |
} |
| 2706 |
++loaded_allele_idx_end; |
| 2707 |
if (loaded_allele_code_iter == loaded_allele_code_end) { |
| 2708 |
break; |
| 2709 |
} |
| 2710 |
if (unlikely(loaded_allele_idx_end == kMaxReadFreqAlleles)) { |
| 2711 |
snprintf(g_logbuf, kLogbufSize, "Error: --read-freq file entry for variant ID '%s' has more than %u ALT alleles.\n", variant_ids[variant_uidx], kMaxReadFreqAlleles - 1); |
| 2712 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_WW; |
| 2713 |
} |
| 2714 |
cur_loaded_allele_code = loaded_allele_code_iter; |
| 2715 |
loaded_allele_code_iter = S_CAST(char*, memchr(loaded_allele_code_iter, ',', loaded_allele_code_end - cur_loaded_allele_code)); |
| 2716 |
cur_loaded_allele_code_slen = loaded_allele_code_iter - cur_loaded_allele_code; |
| 2717 |
*loaded_allele_code_iter++ = '\0'; |
| 2718 |
} |
| 2719 |
} |
| 2720 |
// bugfix (31 May 2023): forgot to skip variant when not enough alleles |
| 2721 |
// were loaded. |
| 2722 |
{ |
| 2723 |
const uint32_t matched_allele_ct = PopcountWords(matched_loaded_alleles, BitCtToWordCt(loaded_allele_idx_end)); |
| 2724 |
if (matched_allele_ct != cur_allele_ct) { |
| 2725 |
assert(matched_allele_ct < cur_allele_ct); |
| 2726 |
goto ReadAlleleFreqs_skip_variant; |
| 2727 |
} |
| 2728 |
} |
| 2729 |
|
| 2730 |
double* allele_freqs_write = &(allele_freqs[allele_idx_offset_base - variant_uidx]); |
| 2731 |
if (geno_counts) { |
| 2732 |
ZeroDArr(cur_allele_ct, cur_allele_freqs); |
| 2733 |
if (is_numeq) { |
| 2734 |
const uint32_t full_slen = token_slens[kReadFreqColGenoCtNumeq]; |
| 2735 |
char* geno_num_cts = token_ptrs[kReadFreqColGenoCtNumeq]; |
| 2736 |
if (full_slen > 1) { |
| 2737 |
geno_num_cts[full_slen] = ','; |
| 2738 |
const char* geno_num_cts_iter = geno_num_cts; |
| 2739 |
const char* geno_num_cts_end = &(geno_num_cts[full_slen]); |
| 2740 |
#ifndef __LP64__ |
| 2741 |
const uint32_t cap_div_10 = (loaded_allele_idx_end - 1) / 10; |
| 2742 |
const uint32_t cap_mod_10 = (loaded_allele_idx_end - 1) % 10; |
| 2743 |
#endif |
| 2744 |
while (1) { |
| 2745 |
uint32_t second_loaded_allele_idx = UINT32_MAX; |
| 2746 |
uint32_t first_loaded_allele_idx; |
| 2747 |
#ifdef __LP64__ |
| 2748 |
if (unlikely(ScanmovUintCapped(loaded_allele_idx_end - 1, &geno_num_cts_iter, &first_loaded_allele_idx))) { |
| 2749 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2750 |
} |
| 2751 |
if (*geno_num_cts_iter == '/') { |
| 2752 |
++geno_num_cts_iter; |
| 2753 |
if (unlikely(ScanmovUintCapped(loaded_allele_idx_end - 1, &geno_num_cts_iter, &second_loaded_allele_idx))) { |
| 2754 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2755 |
} |
| 2756 |
} |
| 2757 |
#else |
| 2758 |
if (unlikely(ScanmovUintCapped32(cap_div_10, cap_mod_10, &geno_num_cts_iter, &first_loaded_allele_idx))) { |
| 2759 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2760 |
} |
| 2761 |
if (*geno_num_cts_iter == '/') { |
| 2762 |
++geno_num_cts_iter; |
| 2763 |
if (unlikely(ScanmovUintCapped32(cap_div_10, cap_mod_10, &geno_num_cts_iter, &second_loaded_allele_idx))) { |
| 2764 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2765 |
} |
| 2766 |
} |
| 2767 |
#endif |
| 2768 |
if (unlikely(*geno_num_cts_iter != '=')) { |
| 2769 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2770 |
} |
| 2771 |
++geno_num_cts_iter; |
| 2772 |
double dxx; |
| 2773 |
const char* cur_ct_end = ScanadvDouble(geno_num_cts_iter, &dxx); |
| 2774 |
if (unlikely((!cur_ct_end) || (*cur_ct_end != ',') || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2775 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2776 |
} |
| 2777 |
dxx = ForceCountToDosage(dxx); |
| 2778 |
if (IsSet(matched_loaded_alleles, first_loaded_allele_idx)) { |
| 2779 |
cur_allele_freqs[loaded_to_internal_allele_idx[first_loaded_allele_idx]] += dxx; |
| 2780 |
} |
| 2781 |
if ((second_loaded_allele_idx != UINT32_MAX) && IsSet(matched_loaded_alleles, second_loaded_allele_idx)) { |
| 2782 |
cur_allele_freqs[loaded_to_internal_allele_idx[second_loaded_allele_idx]] += dxx; |
| 2783 |
} |
| 2784 |
geno_num_cts_iter = cur_ct_end; |
| 2785 |
if (geno_num_cts_iter == geno_num_cts_end) { |
| 2786 |
break; |
| 2787 |
} |
| 2788 |
++geno_num_cts_iter; |
| 2789 |
} |
| 2790 |
} else if (unlikely(*geno_num_cts != '.')) { |
| 2791 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2792 |
} |
| 2793 |
} else { |
| 2794 |
const uint32_t internal0 = IsSet(matched_loaded_alleles, 0)? loaded_to_internal_allele_idx[0] : UINT32_MAX; |
| 2795 |
if (header_cols & kfReadFreqColsetHomRefCt) { |
| 2796 |
if (internal0 != UINT32_MAX) { |
| 2797 |
const char* hom_ref_str = token_ptrs[kReadFreqColHomRefCt]; |
| 2798 |
double dxx; |
| 2799 |
const char* hom_ref_end = ScantokDouble(hom_ref_str, &dxx); |
| 2800 |
if (unlikely((!hom_ref_end) || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2801 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2802 |
} |
| 2803 |
dxx = ForceCountToDosage(dxx); |
| 2804 |
cur_allele_freqs[internal0] += 2 * dxx; |
| 2805 |
} |
| 2806 |
|
| 2807 |
char* het_refalt = token_ptrs[kReadFreqColHetRefAltCts]; |
| 2808 |
const uint32_t het_refalt_slen = token_slens[kReadFreqColHetRefAltCts]; |
| 2809 |
het_refalt[het_refalt_slen] = ','; |
| 2810 |
const char* het_refalt_iter = het_refalt; |
| 2811 |
const char* het_refalt_end = &(het_refalt[het_refalt_slen]); |
| 2812 |
for (uint32_t alt_allele_idx = 1; alt_allele_idx != cur_allele_ct; ++alt_allele_idx) { |
| 2813 |
if (unlikely(het_refalt_iter >= het_refalt_end)) { |
| 2814 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2815 |
} |
| 2816 |
double dxx; |
| 2817 |
const char* cur_entry_end = ScanadvDouble(het_refalt_iter, &dxx); |
| 2818 |
if (unlikely((!cur_entry_end) || (*cur_entry_end != ',') || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2819 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2820 |
} |
| 2821 |
dxx = ForceCountToDosage(dxx); |
| 2822 |
if (internal0 != UINT32_MAX) { |
| 2823 |
cur_allele_freqs[internal0] += dxx; |
| 2824 |
} |
| 2825 |
if (IsSet(matched_loaded_alleles, alt_allele_idx)) { |
| 2826 |
cur_allele_freqs[loaded_to_internal_allele_idx[alt_allele_idx]] += dxx; |
| 2827 |
} |
| 2828 |
het_refalt_iter = &(cur_entry_end[1]); |
| 2829 |
} |
| 2830 |
} |
| 2831 |
// ColNonrefDiploidCts required |
| 2832 |
char* diploid_cts = token_ptrs[kReadFreqColNonrefDiploidCts]; |
| 2833 |
const uint32_t diploid_cts_slen = token_slens[kReadFreqColNonrefDiploidCts]; |
| 2834 |
diploid_cts[diploid_cts_slen] = ','; |
| 2835 |
const char* diploid_cts_iter = diploid_cts; |
| 2836 |
const char* diploid_cts_end = &(diploid_cts[diploid_cts_slen]); |
| 2837 |
for (uint32_t second_allele_idx = main_allele_idx_start; second_allele_idx != cur_allele_ct; ++second_allele_idx) { |
| 2838 |
uint32_t internalx = UINT32_MAX; |
| 2839 |
if (IsSet(matched_loaded_alleles, second_allele_idx)) { |
| 2840 |
internalx = loaded_to_internal_allele_idx[second_allele_idx]; |
| 2841 |
} |
| 2842 |
// 1/1, 1/2, 2/2, 1/3, ... |
| 2843 |
for (uint32_t first_allele_idx = main_allele_idx_start; first_allele_idx <= second_allele_idx; ++first_allele_idx) { |
| 2844 |
if (unlikely(diploid_cts_iter >= diploid_cts_end)) { |
| 2845 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2846 |
} |
| 2847 |
double dxx; |
| 2848 |
const char* cur_entry_end = ScanadvDouble(diploid_cts_iter, &dxx); |
| 2849 |
if (unlikely((!cur_entry_end) || (*cur_entry_end != ',') || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2850 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2851 |
} |
| 2852 |
dxx = ForceCountToDosage(dxx); |
| 2853 |
if (IsSet(matched_loaded_alleles, first_allele_idx)) { |
| 2854 |
cur_allele_freqs[loaded_to_internal_allele_idx[first_allele_idx]] += dxx; |
| 2855 |
} |
| 2856 |
if (internalx != UINT32_MAX) { |
| 2857 |
cur_allele_freqs[internalx] += dxx; |
| 2858 |
} |
| 2859 |
diploid_cts_iter = &(cur_entry_end[1]); |
| 2860 |
} |
| 2861 |
} |
| 2862 |
|
| 2863 |
if ((header_cols & kfReadFreqColsetHapRefCt) && (internal0 != UINT32_MAX)) { |
| 2864 |
const char* hap_ref_str = token_ptrs[kReadFreqColHapRefCt]; |
| 2865 |
double dxx; |
| 2866 |
const char* hap_ref_end = ScantokDouble(hap_ref_str, &dxx); |
| 2867 |
if (unlikely((!hap_ref_end) || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2868 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2869 |
} |
| 2870 |
dxx = ForceCountToDosage(dxx); |
| 2871 |
cur_allele_freqs[internal0] += dxx; |
| 2872 |
} |
| 2873 |
// ColHapAltCts required |
| 2874 |
char* hap_alt = token_ptrs[kReadFreqColHapAltCts]; |
| 2875 |
const uint32_t hap_alt_slen = token_slens[kReadFreqColHapAltCts]; |
| 2876 |
hap_alt[hap_alt_slen] = ','; |
| 2877 |
const char* hap_alt_iter = hap_alt; |
| 2878 |
const char* hap_alt_end = &(hap_alt[hap_alt_slen]); |
| 2879 |
for (uint32_t alt_allele_idx = 1; alt_allele_idx != cur_allele_ct; ++alt_allele_idx) { |
| 2880 |
if (unlikely(hap_alt_iter >= hap_alt_end)) { |
| 2881 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2882 |
} |
| 2883 |
double dxx; |
| 2884 |
const char* cur_entry_end = ScanadvDouble(hap_alt_iter, &dxx); |
| 2885 |
if (unlikely((!cur_entry_end) || (*cur_entry_end != ',') || (dxx < 0.0) || (dxx > 4294967295.0))) { |
| 2886 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2887 |
} |
| 2888 |
if (IsSet(matched_loaded_alleles, alt_allele_idx)) { |
| 2889 |
dxx = ForceCountToDosage(dxx); |
| 2890 |
cur_allele_freqs[loaded_to_internal_allele_idx[alt_allele_idx]] += dxx; |
| 2891 |
} |
| 2892 |
hap_alt_iter = &(cur_entry_end[1]); |
| 2893 |
} |
| 2894 |
} |
| 2895 |
} else { |
| 2896 |
if ((header_cols & kfReadFreqColsetRefFreq) && IsSet(matched_loaded_alleles, 0)) { |
| 2897 |
const char* ref_freq_str = token_ptrs[kReadFreqColRefFreq]; |
| 2898 |
double dxx; |
| 2899 |
if (!ScantokDouble(ref_freq_str, &dxx)) { |
| 2900 |
if (likely(IsNanStr(ref_freq_str, token_slens[kReadFreqColRefFreq]))) { |
| 2901 |
goto ReadAlleleFreqs_skip_variant; |
| 2902 |
} |
| 2903 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid REF frequency/count on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 2904 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_WW; |
| 2905 |
} |
| 2906 |
if (unlikely((dxx < 0.0) || (dxx > freq_max))) { |
| 2907 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid REF frequency/count on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 2908 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_WW; |
| 2909 |
} |
| 2910 |
if (!is_frac) { |
| 2911 |
dxx = ForceCountToDosage(dxx); |
| 2912 |
} |
| 2913 |
cur_allele_freqs[loaded_to_internal_allele_idx[0]] = dxx; |
| 2914 |
} |
| 2915 |
if (header_cols & kfReadFreqColsetAltFreqs) { |
| 2916 |
const uint32_t full_slen = token_slens[kReadFreqColAltFreqs]; |
| 2917 |
char* alt_freq_start = token_ptrs[kReadFreqColAltFreqs]; |
| 2918 |
alt_freq_start[full_slen] = ','; |
| 2919 |
if (!main_eq) { |
| 2920 |
const char* alt_freq_iter = alt_freq_start; |
| 2921 |
const char* alt_freq_end = &(alt_freq_start[full_slen]); |
| 2922 |
for (uint32_t allele_idx = main_allele_idx_start; allele_idx != loaded_allele_idx_end; ++allele_idx, ++alt_freq_iter) { |
| 2923 |
if (unlikely(alt_freq_iter >= alt_freq_end)) { |
| 2924 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2925 |
} |
| 2926 |
if (!IsSet(matched_loaded_alleles, allele_idx)) { |
| 2927 |
alt_freq_iter = AdvToDelim(alt_freq_iter, ','); |
| 2928 |
continue; |
| 2929 |
} |
| 2930 |
double dxx; |
| 2931 |
const char* cur_freq_end = ScanadvDouble(alt_freq_iter, &dxx); |
| 2932 |
if (!cur_freq_end) { |
| 2933 |
cur_freq_end = AdvToDelim(alt_freq_iter, ','); |
| 2934 |
if (likely(IsNanStr(alt_freq_iter, cur_freq_end - alt_freq_iter))) { |
| 2935 |
goto ReadAlleleFreqs_skip_variant; |
| 2936 |
} |
| 2937 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2938 |
} |
| 2939 |
if (unlikely((*cur_freq_end != ',') || (dxx < 0.0) || (dxx > freq_max))) { |
| 2940 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2941 |
} |
| 2942 |
if (!is_frac) { |
| 2943 |
dxx = ForceCountToDosage(dxx); |
| 2944 |
} |
| 2945 |
alt_freq_iter = cur_freq_end; |
| 2946 |
cur_allele_freqs[loaded_to_internal_allele_idx[allele_idx]] = dxx; |
| 2947 |
} |
| 2948 |
} else { |
| 2949 |
ZeroDArr(cur_allele_ct, cur_allele_freqs); |
| 2950 |
if ((full_slen > 1) || (*alt_freq_start != '.')) { |
| 2951 |
if (is_numeq) { |
| 2952 |
const char* alt_freq_iter = alt_freq_start; |
| 2953 |
const char* alt_freq_end = &(alt_freq_start[full_slen]); |
| 2954 |
#ifndef __LP64__ |
| 2955 |
const uint32_t cap_div_10 = (loaded_allele_idx_end - 1) / 10; |
| 2956 |
const uint32_t cap_mod_10 = (loaded_allele_idx_end - 1) % 10; |
| 2957 |
#endif |
| 2958 |
while (1) { |
| 2959 |
const char* cur_entry_end = AdvToDelim(alt_freq_iter, ','); |
| 2960 |
uint32_t loaded_allele_idx; |
| 2961 |
#ifdef __LP64__ |
| 2962 |
if (unlikely(ScanmovUintCapped(loaded_allele_idx_end - 1, &alt_freq_iter, &loaded_allele_idx))) { |
| 2963 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2964 |
} |
| 2965 |
#else |
| 2966 |
if (unlikely(ScanmovUintCapped32(cap_div_10, cap_mod_10, &alt_freq_iter, &loaded_allele_idx))) { |
| 2967 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2968 |
} |
| 2969 |
#endif |
| 2970 |
if (unlikely(*alt_freq_iter != '=')) { |
| 2971 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2972 |
} |
| 2973 |
if (IsSet(matched_loaded_alleles, loaded_allele_idx)) { |
| 2974 |
const uint32_t internal_allele_idx = loaded_to_internal_allele_idx[loaded_allele_idx]; |
| 2975 |
if (unlikely(cur_allele_freqs[internal_allele_idx] != 0.0)) { |
| 2976 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate entry on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 2977 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 2978 |
} |
| 2979 |
++alt_freq_iter; |
| 2980 |
double dxx; |
| 2981 |
const char* cur_freq_end = ScantokDouble(alt_freq_iter, &dxx); |
| 2982 |
if (!cur_freq_end) { |
| 2983 |
if (likely(IsNanStr(alt_freq_iter, cur_entry_end - alt_freq_iter))) { |
| 2984 |
goto ReadAlleleFreqs_skip_variant; |
| 2985 |
} |
| 2986 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2987 |
} |
| 2988 |
if (unlikely((dxx < 0.0) || (dxx > freq_max))) { |
| 2989 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 2990 |
} |
| 2991 |
if (!is_frac) { |
| 2992 |
dxx = ForceCountToDosage(dxx); |
| 2993 |
} |
| 2994 |
cur_allele_freqs[internal_allele_idx] = dxx; |
| 2995 |
} |
| 2996 |
alt_freq_iter = cur_entry_end; |
| 2997 |
if (alt_freq_iter == alt_freq_end) { |
| 2998 |
break; |
| 2999 |
} |
| 3000 |
++alt_freq_iter; |
| 3001 |
} |
| 3002 |
} else { |
| 3003 |
char* alt_freq_iter = alt_freq_start; |
| 3004 |
char* alt_freq_end = &(alt_freq_start[full_slen]); |
| 3005 |
while (1) { |
| 3006 |
char* cur_entry_end = AdvToDelim(alt_freq_iter, ','); |
| 3007 |
const uint32_t cur_entry_slen = cur_entry_end - alt_freq_iter; |
| 3008 |
char* eq_ptr = S_CAST(char*, memchr(alt_freq_iter, '=', cur_entry_slen)); |
| 3009 |
if (unlikely(!eq_ptr)) { |
| 3010 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 3011 |
} |
| 3012 |
|
| 3013 |
// necessary for string comparison |
| 3014 |
*eq_ptr++ = '\0'; |
| 3015 |
|
| 3016 |
const uint32_t cur_blen = eq_ptr - alt_freq_iter; |
| 3017 |
// O(n^2), may want to replace with O(n log n) |
| 3018 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct; ++internal_allele_idx) { |
| 3019 |
if (memequal(alt_freq_iter, cur_alleles[internal_allele_idx], cur_blen)) { |
| 3020 |
if (unlikely(cur_allele_freqs[internal_allele_idx] != 0.0)) { |
| 3021 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate entry on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 3022 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 3023 |
} |
| 3024 |
alt_freq_iter = eq_ptr; |
| 3025 |
double dxx; |
| 3026 |
const char* cur_freq_end = ScantokDouble(alt_freq_iter, &dxx); |
| 3027 |
if (!cur_freq_end) { |
| 3028 |
if (likely(IsNanStr(alt_freq_iter, cur_entry_end - alt_freq_iter))) { |
| 3029 |
goto ReadAlleleFreqs_skip_variant; |
| 3030 |
} |
| 3031 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 3032 |
} |
| 3033 |
if (unlikely((dxx < 0.0) || (dxx > freq_max))) { |
| 3034 |
goto ReadAlleleFreqs_ret_INVALID_FREQS; |
| 3035 |
} |
| 3036 |
if (!is_frac) { |
| 3037 |
dxx = ForceCountToDosage(dxx); |
| 3038 |
} |
| 3039 |
cur_allele_freqs[internal_allele_idx] = dxx; |
| 3040 |
break; |
| 3041 |
} |
| 3042 |
} |
| 3043 |
alt_freq_iter = cur_entry_end; |
| 3044 |
if (alt_freq_iter == alt_freq_end) { |
| 3045 |
break; |
| 3046 |
} |
| 3047 |
++alt_freq_iter; |
| 3048 |
} |
| 3049 |
} |
| 3050 |
} |
| 3051 |
} |
| 3052 |
} |
| 3053 |
} |
| 3054 |
// The IsSet condition is false when the following happens: |
| 3055 |
// - --read-freq file has multiple ALT alleles. |
| 3056 |
// - These ALT alleles collectively match *all* alleles in the main |
| 3057 |
// dataset's version of the variant, including the main dataset's |
| 3058 |
// REF. The --read-freq file's REF allele is not in the main |
| 3059 |
// dataset at all. |
| 3060 |
// - So, while we normally infer the REF frequency by subtracting the |
| 3061 |
// sum of the other frequencies from 1, in this subcase there is |
| 3062 |
// nothing to infer. |
| 3063 |
if (infer_one_freq && IsSet(matched_loaded_alleles, infer_freq_loaded_idx)) { |
| 3064 |
double adj_obs_ct_recip = 1.0; |
| 3065 |
if (header_cols & kfReadFreqColsetObsCt) { |
| 3066 |
uint32_t obs_ct_raw; |
| 3067 |
if (unlikely(ScanUintCapped(token_ptrs[kReadFreqColObsCt], UINT32_MAX, &obs_ct_raw))) { |
| 3068 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid allele count on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 3069 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 3070 |
} |
| 3071 |
if ((!obs_ct_raw) && (af_pseudocount == 0.0)) { |
| 3072 |
goto ReadAlleleFreqs_skip_variant; |
| 3073 |
} |
| 3074 |
adj_obs_ct_recip = 1.0 / (u63tod(obs_ct_raw) + af_pseudocount * cur_allele_ct); |
| 3075 |
} |
| 3076 |
const uint32_t infer_freq_internal_idx = loaded_to_internal_allele_idx[infer_freq_loaded_idx]; |
| 3077 |
if (cur_allele_ct == 2) { |
| 3078 |
// optimize common case |
| 3079 |
double known_freq_d = cur_allele_freqs[1 - infer_freq_internal_idx] + af_pseudocount; |
| 3080 |
double known_scaled_freq = known_freq_d * adj_obs_ct_recip; |
| 3081 |
if (known_scaled_freq <= 1.0) { |
| 3082 |
if (infer_freq_internal_idx) { |
| 3083 |
allele_freqs_write[0] = known_scaled_freq; |
| 3084 |
} else { |
| 3085 |
allele_freqs_write[0] = 1.0 - known_scaled_freq; |
| 3086 |
} |
| 3087 |
} else if (likely(known_scaled_freq < ((1.0 + kSmallEpsilon) / 0.99))) { |
| 3088 |
if (infer_freq_internal_idx) { |
| 3089 |
allele_freqs_write[0] = 1.0; |
| 3090 |
} else { |
| 3091 |
allele_freqs_write[0] = 0.0; |
| 3092 |
} |
| 3093 |
} else { |
| 3094 |
snprintf(g_logbuf, kLogbufSize, "Error: Frequency/count too large on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 3095 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 3096 |
} |
| 3097 |
} else { |
| 3098 |
if (af_pseudocount != 0.0) { |
| 3099 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct; ++internal_allele_idx) { |
| 3100 |
cur_allele_freqs[internal_allele_idx] += af_pseudocount; |
| 3101 |
} |
| 3102 |
} |
| 3103 |
cur_allele_freqs[infer_freq_internal_idx] = 0.0; |
| 3104 |
double known_freq_sum_d = 0.0; |
| 3105 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct; ++internal_allele_idx) { |
| 3106 |
known_freq_sum_d += cur_allele_freqs[internal_allele_idx]; |
| 3107 |
} |
| 3108 |
double known_scaled_freq_sum = known_freq_sum_d * adj_obs_ct_recip; |
| 3109 |
if (likely(known_scaled_freq_sum < ((1.0 + kSmallEpsilon) / 0.99))) { |
| 3110 |
if (known_scaled_freq_sum > 1.0) { |
| 3111 |
// possible rounding error, rescale |
| 3112 |
adj_obs_ct_recip = 1.0 / known_scaled_freq_sum; |
| 3113 |
known_scaled_freq_sum = 1.0; |
| 3114 |
} |
| 3115 |
const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1; |
| 3116 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct_m1; ++internal_allele_idx) { |
| 3117 |
double dxx; |
| 3118 |
if (internal_allele_idx == infer_freq_internal_idx) { |
| 3119 |
dxx = 1.0 - known_scaled_freq_sum; |
| 3120 |
} else { |
| 3121 |
dxx = adj_obs_ct_recip * cur_allele_freqs[internal_allele_idx]; |
| 3122 |
} |
| 3123 |
allele_freqs_write[internal_allele_idx] = dxx; |
| 3124 |
} |
| 3125 |
} else { |
| 3126 |
snprintf(g_logbuf, kLogbufSize, "Error: Frequency/count too large on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 3127 |
goto ReadAlleleFreqs_ret_MALFORMED_INPUT_2; |
| 3128 |
} |
| 3129 |
} |
| 3130 |
} else { |
| 3131 |
// complete frequency or count data |
| 3132 |
if (af_pseudocount != 0.0) { |
| 3133 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct; ++internal_allele_idx) { |
| 3134 |
cur_allele_freqs[internal_allele_idx] += af_pseudocount; |
| 3135 |
} |
| 3136 |
} |
| 3137 |
double tot_freq = 0.0; |
| 3138 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct; ++internal_allele_idx) { |
| 3139 |
tot_freq += cur_allele_freqs[internal_allele_idx]; |
| 3140 |
} |
| 3141 |
if (tot_freq == 0.0) { |
| 3142 |
goto ReadAlleleFreqs_skip_variant; |
| 3143 |
} |
| 3144 |
const double tot_freq_recip = 1.0 / tot_freq; |
| 3145 |
const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1; |
| 3146 |
for (uint32_t internal_allele_idx = 0; internal_allele_idx != cur_allele_ct_m1; ++internal_allele_idx) { |
| 3147 |
allele_freqs_write[internal_allele_idx] = tot_freq_recip * cur_allele_freqs[internal_allele_idx]; |
| 3148 |
} |
| 3149 |
} |
| 3150 |
|
| 3151 |
++loaded_variant_ct; |
| 3152 |
if (!(loaded_variant_ct % 10000)) { |
| 3153 |
printf("\r--read-freq: Frequencies for %uk variants loaded.", loaded_variant_ct / 1000); |
| 3154 |
fflush(stdout); |
| 3155 |
} |
| 3156 |
} |
| 3157 |
while (0) { |
| 3158 |
ReadAlleleFreqs_skip_variant: |
| 3159 |
SetBit(variant_uidx, *variant_afreqcalcp); |
| 3160 |
++skipped_variant_ct; |
| 3161 |
} |
| 3162 |
} |
| 3163 |
if (unlikely(TextStreamErrcode2(&read_freq_txs, &reterr))) { |
| 3164 |
goto ReadAlleleFreqs_ret_TSTREAM_FAIL; |
| 3165 |
} |
| 3166 |
// Set variant_afreqcalc to the set of variants in variant_include, but |
| 3167 |
// without loaded frequencies. |
| 3168 |
BitvecInvertAndMask(variant_include, raw_variant_ctl, already_seen); |
| 3169 |
// already_seen is now the set of remaining variants that *weren't* seen, |
| 3170 |
// and variant_afreqcalc is the set of variants which were seen but |
| 3171 |
// skipped due to incomplete information. |
| 3172 |
BitvecOr(already_seen, raw_variant_ctl, *variant_afreqcalcp); |
| 3173 |
putc_unlocked('\r', stdout); |
| 3174 |
logprintf("--read-freq: Frequencies for %u variant%s loaded.\n", loaded_variant_ct, (loaded_variant_ct == 1)? "" : "s"); |
| 3175 |
if (skipped_variant_ct) { |
| 3176 |
logerrprintfww("Warning: %" PRIuPTR " entr%s skipped due to missing variant IDs, mismatching allele codes, and/or zero observations.\n", skipped_variant_ct, (skipped_variant_ct == 1)? "y" : "ies"); |
| 3177 |
} |
| 3178 |
} |
| 3179 |
while (0) { |
| 3180 |
ReadAlleleFreqs_ret_TSTREAM_FAIL: |
| 3181 |
TextStreamErrPrint("--read-freq file", &read_freq_txs); |
| 3182 |
break; |
| 3183 |
ReadAlleleFreqs_ret_NOMEM: |
| 3184 |
reterr = kPglRetNomem; |
| 3185 |
break; |
| 3186 |
ReadAlleleFreqs_ret_UNRECOGNIZED_HEADER: |
| 3187 |
logerrputs("Error: Unrecognized header line in --read-freq file.\n"); |
| 3188 |
reterr = kPglRetMalformedInput; |
| 3189 |
break; |
| 3190 |
ReadAlleleFreqs_ret_MISSING_TOKENS: |
| 3191 |
logerrprintfww("Error: Line %" PRIuPTR " of --read-freq file has fewer tokens than expected.\n", line_idx); |
| 3192 |
reterr = kPglRetMalformedInput; |
| 3193 |
break; |
| 3194 |
ReadAlleleFreqs_ret_INVALID_FREQS: |
| 3195 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid frequencies/counts on line %" PRIuPTR " of --read-freq file.\n", line_idx); |
| 3196 |
ReadAlleleFreqs_ret_MALFORMED_INPUT_WW: |
| 3197 |
WordWrapB(0); |
| 3198 |
ReadAlleleFreqs_ret_MALFORMED_INPUT_2: |
| 3199 |
logputs("\n"); |
| 3200 |
logerrputsb(); |
| 3201 |
ReadAlleleFreqs_ret_MALFORMED_INPUT: |
| 3202 |
reterr = kPglRetMalformedInput; |
| 3203 |
break; |
| 3204 |
} |
| 3205 |
ReadAlleleFreqs_ret_1: |
| 3206 |
CleanupTextStream2("--read-freq file", &read_freq_txs, &reterr); |
| 3207 |
BigstackReset(bigstack_mark); |
| 3208 |
return reterr; |
| 3209 |
} |
| 3210 |
|
| 3211 |
void ComputeMajAlleles(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const double* allele_freqs, uint32_t variant_ct, AlleleCode* maj_alleles) { |
| 3212 |
uint32_t cur_allele_ct = 2; |
| 3213 |
uintptr_t variant_uidx_base = 0; |
| 3214 |
uintptr_t cur_bits = variant_include[0]; |
| 3215 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 3216 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3217 |
uintptr_t allele_idx_base; |
| 3218 |
if (!allele_idx_offsets) { |
| 3219 |
allele_idx_base = variant_uidx; |
| 3220 |
} else { |
| 3221 |
allele_idx_base = allele_idx_offsets[variant_uidx]; |
| 3222 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_base; |
| 3223 |
allele_idx_base -= variant_uidx; |
| 3224 |
} |
| 3225 |
maj_alleles[variant_uidx] = GetMajIdx(&(allele_freqs[allele_idx_base]), cur_allele_ct); |
| 3226 |
} |
| 3227 |
} |
| 3228 |
|
| 3229 |
PglErr MindFilter(const uint32_t* sample_missing_cts, const uint32_t* sample_hethap_cts, const SampleIdInfo* siip, uint32_t raw_sample_ct, uint32_t variant_ct, uint32_t variant_ct_y, double mind_thresh, uintptr_t* sample_include, uintptr_t* sex_male, uint32_t* sample_ct_ptr, char* outname, char* outname_end) { |
| 3230 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3231 |
PglErr reterr = kPglRetSuccess; |
| 3232 |
{ |
| 3233 |
const uint32_t orig_sample_ct = *sample_ct_ptr; |
| 3234 |
if (!orig_sample_ct) { |
| 3235 |
goto MindFilter_ret_1; |
| 3236 |
} |
| 3237 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 3238 |
|
| 3239 |
uint32_t max_missing_cts[2]; |
| 3240 |
mind_thresh *= 1 + kSmallEpsilon; |
| 3241 |
max_missing_cts[0] = S_CAST(int32_t, u31tod(variant_ct - variant_ct_y) * mind_thresh); |
| 3242 |
max_missing_cts[1] = S_CAST(int32_t, u31tod(variant_ct) * mind_thresh); |
| 3243 |
uintptr_t* newly_excluded; |
| 3244 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &newly_excluded))) { |
| 3245 |
goto MindFilter_ret_NOMEM; |
| 3246 |
} |
| 3247 |
uintptr_t sample_uidx_base = 0; |
| 3248 |
uintptr_t cur_bits = sample_include[0]; |
| 3249 |
for (uint32_t sample_idx = 0; sample_idx != orig_sample_ct; ++sample_idx) { |
| 3250 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 3251 |
uint32_t cur_missing_geno_ct = sample_missing_cts[sample_uidx]; |
| 3252 |
if (sample_hethap_cts) { |
| 3253 |
cur_missing_geno_ct += sample_hethap_cts[sample_uidx]; |
| 3254 |
} |
| 3255 |
if (cur_missing_geno_ct > max_missing_cts[IsSet(sex_male, sample_uidx)]) { |
| 3256 |
SetBit(sample_uidx, newly_excluded); |
| 3257 |
} |
| 3258 |
} |
| 3259 |
const uint32_t removed_ct = PopcountWords(newly_excluded, raw_sample_ctl); |
| 3260 |
// don't bother with allow_no_samples check here, better to have that in |
| 3261 |
// just one place |
| 3262 |
logprintf("%u sample%s removed due to missing genotype data (--mind).\n", removed_ct, (removed_ct == 1)? "" : "s"); |
| 3263 |
if (removed_ct) { |
| 3264 |
BitvecInvmask(newly_excluded, raw_sample_ctl, sample_include); |
| 3265 |
BitvecInvmask(newly_excluded, raw_sample_ctl, sex_male); |
| 3266 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".mindrem.id"); |
| 3267 |
reterr = WriteSampleIds(newly_excluded, siip, outname, removed_ct); |
| 3268 |
if (unlikely(reterr)) { |
| 3269 |
goto MindFilter_ret_1; |
| 3270 |
} |
| 3271 |
logprintfww("ID%s written to %s .\n", (removed_ct == 1)? "" : "s", outname); |
| 3272 |
*sample_ct_ptr -= removed_ct; |
| 3273 |
} |
| 3274 |
} |
| 3275 |
while (0) { |
| 3276 |
MindFilter_ret_NOMEM: |
| 3277 |
reterr = kPglRetNomem; |
| 3278 |
break; |
| 3279 |
} |
| 3280 |
MindFilter_ret_1: |
| 3281 |
BigstackReset(bigstack_mark); |
| 3282 |
return reterr; |
| 3283 |
} |
| 3284 |
|
| 3285 |
void EnforceGenoThresh(const ChrInfo* cip, const uint32_t* variant_missing_cts, const uint32_t* variant_hethap_cts, uint32_t sample_ct, uint32_t male_ct, uint32_t first_hap_uidx, double geno_thresh, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 3286 |
const uint32_t prefilter_variant_ct = *variant_ct_ptr; |
| 3287 |
geno_thresh *= 1 + kSmallEpsilon; |
| 3288 |
const uint32_t missing_max_ct_nony = S_CAST(int32_t, geno_thresh * u31tod(sample_ct)); |
| 3289 |
const uint32_t missing_max_ct_y = S_CAST(int32_t, geno_thresh * u31tod(male_ct)); |
| 3290 |
uint32_t cur_missing_max_ct = missing_max_ct_nony; |
| 3291 |
uint32_t removed_ct = 0; |
| 3292 |
uint32_t y_thresh = UINT32_MAX; |
| 3293 |
uint32_t y_end = UINT32_MAX; |
| 3294 |
uint32_t y_code; |
| 3295 |
if (XymtExists(cip, kChrOffsetY, &y_code)) { |
| 3296 |
const uint32_t y_chr_fo_idx = cip->chr_idx_to_foidx[y_code]; |
| 3297 |
y_thresh = cip->chr_fo_vidx_start[y_chr_fo_idx]; |
| 3298 |
y_end = cip->chr_fo_vidx_start[y_chr_fo_idx + 1]; |
| 3299 |
} |
| 3300 |
uintptr_t variant_uidx_base = 0; |
| 3301 |
uintptr_t cur_bits = variant_include[0]; |
| 3302 |
for (uint32_t variant_idx = 0; variant_idx != prefilter_variant_ct; ++variant_idx) { |
| 3303 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3304 |
if (variant_uidx >= y_thresh) { |
| 3305 |
if (variant_uidx < y_end) { |
| 3306 |
y_thresh = y_end; |
| 3307 |
cur_missing_max_ct = missing_max_ct_y; |
| 3308 |
} else { |
| 3309 |
y_thresh = UINT32_MAX; |
| 3310 |
cur_missing_max_ct = missing_max_ct_nony; |
| 3311 |
} |
| 3312 |
} |
| 3313 |
uint32_t cur_missing_ct = variant_missing_cts[variant_uidx]; |
| 3314 |
if (variant_uidx >= first_hap_uidx) { |
| 3315 |
cur_missing_ct += variant_hethap_cts[variant_uidx - first_hap_uidx]; |
| 3316 |
} |
| 3317 |
if (cur_missing_ct > cur_missing_max_ct) { |
| 3318 |
ClearBit(variant_uidx, variant_include); |
| 3319 |
++removed_ct; |
| 3320 |
} |
| 3321 |
} |
| 3322 |
logprintf("--geno: %u variant%s removed due to missing genotype data.\n", removed_ct, (removed_ct == 1)? "" : "s"); |
| 3323 |
*variant_ct_ptr -= removed_ct; |
| 3324 |
} |
| 3325 |
|
| 3326 |
void EnforceHweThresh(const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, autosomal_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts), const double* hwe_x_ln_pvals, MiscFlags misc_flags, double hwe_ln_thresh_base, double hwe_sample_size_term, uint32_t nonfounders, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 3327 |
uint32_t prefilter_variant_ct = *variant_ct_ptr; |
| 3328 |
const uint32_t midp = (misc_flags / kfMiscHweMidp) & 1; |
| 3329 |
const uint32_t keep_fewhet = (misc_flags / kfMiscHweKeepFewhet) & 1; |
| 3330 |
hwe_ln_thresh_base *= 1 + kSmallEpsilon; |
| 3331 |
const double hwe_sample_size_coeff = (hwe_sample_size_term <= 0)? 0 : (hwe_sample_size_term * (-kLn10)); |
| 3332 |
uint32_t removed_ct = 0; |
| 3333 |
uint32_t min_obs = UINT32_MAX; |
| 3334 |
uint32_t max_obs = 0; |
| 3335 |
uint32_t male_a1_ct = 0; |
| 3336 |
uint32_t male_ax_ct = 0; |
| 3337 |
const double* hwe_x_ln_pvals_iter = hwe_x_ln_pvals; |
| 3338 |
uintptr_t autosomal_xgeno_idx = 0; |
| 3339 |
uintptr_t x_xgeno_idx = 0; |
| 3340 |
uint32_t x_skip_code = UINT32_MAX; |
| 3341 |
uint32_t x_start = 0; |
| 3342 |
uint32_t x_code; |
| 3343 |
if (XymtExists(cip, kChrOffsetX, &x_code)) { |
| 3344 |
const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 3345 |
x_start = cip->chr_fo_vidx_start[x_chr_fo_idx]; |
| 3346 |
if (!hwe_x_ln_pvals) { |
| 3347 |
x_skip_code = x_code; // only set this if we're skipping chrX |
| 3348 |
prefilter_variant_ct -= PopcountBitRange(variant_include, x_start, cip->chr_fo_vidx_start[x_chr_fo_idx + 1]); |
| 3349 |
} |
| 3350 |
} |
| 3351 |
// bugfix (2 Apr 2019): wasn't skipping chrY/chrM properly |
| 3352 |
uint32_t y_code; |
| 3353 |
if (XymtExists(cip, kChrOffsetY, &y_code)) { |
| 3354 |
prefilter_variant_ct -= CountChrVariantsUnsafe(variant_include, cip, y_code); |
| 3355 |
} |
| 3356 |
uint32_t mt_code; |
| 3357 |
if (XymtExists(cip, kChrOffsetMT, &mt_code)) { |
| 3358 |
prefilter_variant_ct -= CountChrVariantsUnsafe(variant_include, cip, mt_code); |
| 3359 |
} |
| 3360 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 3361 |
uint32_t chr_end = 0; |
| 3362 |
uint32_t is_x = 0; |
| 3363 |
uintptr_t variant_uidx_base = 0; |
| 3364 |
uintptr_t variant_include_bits = variant_include[0]; |
| 3365 |
uint32_t xallele_ct = 0; |
| 3366 |
for (uint32_t variant_idx = 0; variant_idx != prefilter_variant_ct; ++variant_idx) { |
| 3367 |
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 3368 |
if (variant_uidx >= chr_end) { |
| 3369 |
uint32_t chr_idx; |
| 3370 |
do { |
| 3371 |
++chr_fo_idx; |
| 3372 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 3373 |
chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 3374 |
} while ((variant_uidx >= chr_end) || (chr_idx == y_code) || (chr_idx == mt_code) || (chr_idx == x_skip_code)); |
| 3375 |
BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &variant_include_bits); |
| 3376 |
variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 3377 |
is_x = (chr_idx == x_code); |
| 3378 |
} |
| 3379 |
STD_ARRAY_KREF(uint32_t, 3) cur_geno_cts = founder_raw_geno_cts[variant_uidx]; |
| 3380 |
if (allele_idx_offsets) { |
| 3381 |
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 3382 |
xallele_ct = (allele_ct == 2)? 0 : (allele_ct - 1); |
| 3383 |
} |
| 3384 |
uint32_t hom_a1_ct = cur_geno_cts[0]; |
| 3385 |
uint32_t het_a1_ct = cur_geno_cts[1]; |
| 3386 |
uint32_t two_ax_ct = cur_geno_cts[2]; |
| 3387 |
uint32_t test_failed = 0; |
| 3388 |
uint32_t pval_computed = 0; |
| 3389 |
uint32_t cur_obs_ct; |
| 3390 |
if (!is_x) { |
| 3391 |
cur_obs_ct = hom_a1_ct + het_a1_ct + two_ax_ct; |
| 3392 |
if (!cur_obs_ct) { |
| 3393 |
if (xallele_ct) { |
| 3394 |
autosomal_xgeno_idx += xallele_ct; |
| 3395 |
} |
| 3396 |
continue; |
| 3397 |
} |
| 3398 |
const double hwe_ln_thresh = hwe_ln_thresh_base + u31tod(cur_obs_ct) * hwe_sample_size_coeff; |
| 3399 |
const double hwe_thresh = exp(hwe_ln_thresh); |
| 3400 |
for (uint32_t xallele_idx = 0; ; ++xallele_idx) { |
| 3401 |
if (keep_fewhet) { |
| 3402 |
if (het_a1_ct * S_CAST(uint64_t, het_a1_ct) <= (4LLU * hom_a1_ct) * two_ax_ct) { |
| 3403 |
goto EnforceHweThresh_skip_autosomal; |
| 3404 |
} |
| 3405 |
} |
| 3406 |
pval_computed = 1; |
| 3407 |
test_failed = HweThreshLn(het_a1_ct, hom_a1_ct, two_ax_ct, midp, hwe_thresh, hwe_ln_thresh); |
| 3408 |
if (test_failed) { |
| 3409 |
break; |
| 3410 |
} |
| 3411 |
EnforceHweThresh_skip_autosomal: |
| 3412 |
if (xallele_idx == xallele_ct) { |
| 3413 |
break; |
| 3414 |
} |
| 3415 |
STD_ARRAY_KREF(uint32_t, 2) cur_xgeno_cts = autosomal_xgeno_cts[autosomal_xgeno_idx + xallele_idx]; |
| 3416 |
hom_a1_ct = cur_xgeno_cts[0]; |
| 3417 |
het_a1_ct = cur_xgeno_cts[1]; |
| 3418 |
two_ax_ct = cur_obs_ct - hom_a1_ct - het_a1_ct; |
| 3419 |
} |
| 3420 |
autosomal_xgeno_idx += xallele_ct; |
| 3421 |
} else { |
| 3422 |
if (founder_x_male_geno_cts) { |
| 3423 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = founder_x_male_geno_cts[variant_uidx - x_start]; |
| 3424 |
male_a1_ct = cur_male_geno_cts[0]; |
| 3425 |
hom_a1_ct -= male_a1_ct; |
| 3426 |
het_a1_ct -= cur_male_geno_cts[1]; |
| 3427 |
male_ax_ct = cur_male_geno_cts[2]; |
| 3428 |
two_ax_ct -= male_ax_ct; |
| 3429 |
} |
| 3430 |
if (founder_x_nosex_geno_cts) { |
| 3431 |
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = founder_x_nosex_geno_cts[variant_uidx - x_start]; |
| 3432 |
hom_a1_ct -= cur_nosex_geno_cts[0]; |
| 3433 |
het_a1_ct -= cur_nosex_geno_cts[1]; |
| 3434 |
two_ax_ct -= cur_nosex_geno_cts[2]; |
| 3435 |
} |
| 3436 |
const uint32_t female_obs_ct = hom_a1_ct + het_a1_ct + two_ax_ct; |
| 3437 |
cur_obs_ct = female_obs_ct + male_a1_ct + male_ax_ct; |
| 3438 |
const double hwe_ln_thresh = hwe_ln_thresh_base + u31tod(cur_obs_ct) * hwe_sample_size_coeff; |
| 3439 |
pval_computed = 1; |
| 3440 |
double joint_ln_pval = *hwe_x_ln_pvals_iter++; |
| 3441 |
for (uint32_t xallele_idx = 0; ; ++xallele_idx) { |
| 3442 |
test_failed = (joint_ln_pval < hwe_ln_thresh); |
| 3443 |
if (test_failed && keep_fewhet && (het_a1_ct * S_CAST(uint64_t, het_a1_ct) < (4LLU * hom_a1_ct) * two_ax_ct)) { |
| 3444 |
// In chrX keep_fewhet case, we only keep a |
| 3445 |
// Graffelman/Weir-test-failing variant if there are few female hets, |
| 3446 |
// *and* the male/female allele-frequency imbalance isn't severe |
| 3447 |
// enough to make the G/W test fail on its own. |
| 3448 |
joint_ln_pval = joint_ln_pval - hwe_ln_thresh; |
| 3449 |
test_failed = !HweThreshLn(het_a1_ct, hom_a1_ct, two_ax_ct, midp, exp(joint_ln_pval), joint_ln_pval); |
| 3450 |
} |
| 3451 |
// bugfix (27 Jun 2020): don't clobber previous allele-test failure if |
| 3452 |
// variant is multiallelic |
| 3453 |
if (test_failed || (xallele_idx == xallele_ct)) { |
| 3454 |
break; |
| 3455 |
} |
| 3456 |
STD_ARRAY_KREF(uint32_t, 2) cur_xgeno_cts = x_knownsex_xgeno_cts[x_xgeno_idx + xallele_idx]; |
| 3457 |
hom_a1_ct = cur_xgeno_cts[0]; |
| 3458 |
het_a1_ct = cur_xgeno_cts[1]; |
| 3459 |
if (x_male_xgeno_cts) { |
| 3460 |
STD_ARRAY_KREF(uint32_t, 2) cur_male_xgeno_cts = x_male_xgeno_cts[x_xgeno_idx + xallele_idx]; |
| 3461 |
hom_a1_ct -= cur_male_xgeno_cts[0]; |
| 3462 |
het_a1_ct -= cur_male_xgeno_cts[1]; |
| 3463 |
} |
| 3464 |
two_ax_ct = female_obs_ct - hom_a1_ct - het_a1_ct; |
| 3465 |
joint_ln_pval = hwe_x_ln_pvals_iter[xallele_idx]; |
| 3466 |
} |
| 3467 |
x_xgeno_idx += xallele_ct; |
| 3468 |
hwe_x_ln_pvals_iter = &(hwe_x_ln_pvals_iter[xallele_ct]); |
| 3469 |
} |
| 3470 |
if (test_failed) { |
| 3471 |
ClearBit(variant_uidx, variant_include); |
| 3472 |
++removed_ct; |
| 3473 |
} |
| 3474 |
if (pval_computed) { |
| 3475 |
if (cur_obs_ct < min_obs) { |
| 3476 |
min_obs = cur_obs_ct; |
| 3477 |
} |
| 3478 |
if (cur_obs_ct > max_obs) { |
| 3479 |
max_obs = cur_obs_ct; |
| 3480 |
} |
| 3481 |
} |
| 3482 |
} |
| 3483 |
// Greer et al. "A reassessment of Hardy-Weinberg equilibrium filtering in |
| 3484 |
// large sample Genomic studies" preprint recommends |
| 3485 |
// hwe_sample_size_term=0.001. If neither hwe_sample_size_term nor |
| 3486 |
// 'keep-fewhet' were specified, warn if the filter is effectively more than |
| 3487 |
// twice as stringent. |
| 3488 |
if ((hwe_sample_size_term == -1) && (!keep_fewhet) && (u31tod(max_obs) * 0.0005 * (-kLn10) < hwe_ln_thresh_base)) { |
| 3489 |
logerrputs("Warning: --hwe filter is suspiciously strict for the sample size; you may be\nfiltering out many variants with association signals.\n"); |
| 3490 |
logerrprintfww("If you are performing routine QC, consider using --hwe with a sample-size term (e.g. \"--hwe 1e-5 0.001%s\" results in a threshold of 1e-6 with 1000 observations, 1e-7 with 2000 observations, etc.), and/or specifying 'keep-fewhet' to remove only variants with heterozygosity excess.\n", midp? " midp" : ""); |
| 3491 |
logerrputs("Alternatively, if the strictness is intentional (e.g. you are preparing data\nfor a method that requires variants to be near Hardy-Weinberg equilibrium),\nexplicitly specify a sample-size term of 0.\nThis warning will be upgraded to an error in a future build.\n"); |
| 3492 |
} else if ((hwe_sample_size_term <= 0) && (S_CAST(uint64_t, max_obs) * 9 > S_CAST(uint64_t, min_obs) * 10)) { |
| 3493 |
logerrprintfww("Warning: --hwe observation counts vary by more than 10%. Consider using --hwe with a sample-size term (e.g. \"--hwe 1e-5 0.001%s%s\" results in a threshold of 1e-6 with 1000 observations, 1e-7 with 2000 observations, etc.), and/or filtering out high-missingness variants with --geno.\n", midp? " midp" : "", keep_fewhet? " keep-fewhet" : ""); |
| 3494 |
} |
| 3495 |
logprintfww("--hwe%s%s: %u variant%s removed due to Hardy-Weinberg exact test (%s).\n", midp? " midp" : "", keep_fewhet? " keep-fewhet" : "", removed_ct, (removed_ct == 1)? "" : "s", nonfounders? "all samples" : "founders only"); |
| 3496 |
*variant_ct_ptr -= removed_ct; |
| 3497 |
} |
| 3498 |
|
| 3499 |
double GetTypedFreq(const double* cur_allele_freqs, uint32_t allele_ct, FreqFilterMode mode) { |
| 3500 |
if ((allele_ct == 2) || (mode == kFreqFilterNref)) { |
| 3501 |
const double ref_freq = cur_allele_freqs[0]; |
| 3502 |
const double nonref_freq = 1.0 - ref_freq; |
| 3503 |
if (mode & (kFreqFilterNref | kFreqFilterAlt1)) { |
| 3504 |
return nonref_freq; |
| 3505 |
} |
| 3506 |
return MINV(nonref_freq, ref_freq); |
| 3507 |
} |
| 3508 |
if (mode == kFreqFilterAlt1) { |
| 3509 |
return cur_allele_freqs[1]; |
| 3510 |
} |
| 3511 |
double tot_nonlast_freq = cur_allele_freqs[0]; |
| 3512 |
const uint32_t allele_ct_m1 = allele_ct - 1; |
| 3513 |
if (mode == kFreqFilterNonmajor) { |
| 3514 |
double max_freq = tot_nonlast_freq; |
| 3515 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct_m1; ++allele_idx) { |
| 3516 |
const double cur_alt_freq = cur_allele_freqs[allele_idx]; |
| 3517 |
tot_nonlast_freq += cur_alt_freq; |
| 3518 |
if (cur_alt_freq > max_freq) { |
| 3519 |
max_freq = cur_alt_freq; |
| 3520 |
} |
| 3521 |
} |
| 3522 |
const double nonmajor_freq = 1.0 - max_freq; |
| 3523 |
return MINV(nonmajor_freq, tot_nonlast_freq); |
| 3524 |
} |
| 3525 |
// minor |
| 3526 |
double min_freq = tot_nonlast_freq; |
| 3527 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct_m1; ++allele_idx) { |
| 3528 |
const double cur_alt_freq = cur_allele_freqs[allele_idx]; |
| 3529 |
tot_nonlast_freq += cur_alt_freq; |
| 3530 |
if (cur_alt_freq < min_freq) { |
| 3531 |
min_freq = cur_alt_freq; |
| 3532 |
} |
| 3533 |
} |
| 3534 |
const double last_freq = MAXV(0.0, 1.0 - tot_nonlast_freq); |
| 3535 |
return MINV(min_freq, last_freq); |
| 3536 |
} |
| 3537 |
|
| 3538 |
uint64_t GetTypedDdosage(const uint64_t* cur_allele_ddosages, uint32_t allele_ct, FreqFilterMode mode) { |
| 3539 |
if (mode == kFreqFilterAlt1) { |
| 3540 |
return cur_allele_ddosages[1]; |
| 3541 |
} |
| 3542 |
if (mode == kFreqFilterNref) { |
| 3543 |
uint64_t nref_ddosage = cur_allele_ddosages[1]; |
| 3544 |
for (uint32_t allele_idx = 2; allele_idx != allele_ct; ++allele_idx) { |
| 3545 |
nref_ddosage += cur_allele_ddosages[allele_idx]; |
| 3546 |
} |
| 3547 |
return nref_ddosage; |
| 3548 |
} |
| 3549 |
if (allele_ct == 2) { |
| 3550 |
return MINV(cur_allele_ddosages[0], cur_allele_ddosages[1]); |
| 3551 |
} |
| 3552 |
if (mode == kFreqFilterNonmajor) { |
| 3553 |
uint64_t max_ddosage = cur_allele_ddosages[0]; |
| 3554 |
uint64_t tot_ddosage = max_ddosage; |
| 3555 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 3556 |
const uint64_t cur_ddosage = cur_allele_ddosages[allele_idx]; |
| 3557 |
tot_ddosage += cur_ddosage; |
| 3558 |
if (cur_ddosage > max_ddosage) { |
| 3559 |
max_ddosage = cur_ddosage; |
| 3560 |
} |
| 3561 |
} |
| 3562 |
return (tot_ddosage - max_ddosage); |
| 3563 |
} |
| 3564 |
// minor |
| 3565 |
uint64_t min_ddosage = cur_allele_ddosages[0]; |
| 3566 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 3567 |
const uint64_t cur_ddosage = cur_allele_ddosages[allele_idx]; |
| 3568 |
if (cur_ddosage < min_ddosage) { |
| 3569 |
min_ddosage = cur_ddosage; |
| 3570 |
} |
| 3571 |
} |
| 3572 |
return min_ddosage; |
| 3573 |
} |
| 3574 |
|
| 3575 |
void EnforceFreqConstraints(const uintptr_t* allele_idx_offsets, const uint64_t* founder_allele_ddosages, const double* allele_freqs, STD_ARRAY_KREF(FreqFilterMode, 4) filter_modes, double min_maf, double max_maf, uint64_t min_allele_ddosage, uint64_t max_allele_ddosage, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 3576 |
const uint32_t prefilter_variant_ct = *variant_ct_ptr; |
| 3577 |
uint32_t removed_ct = 0; |
| 3578 |
if ((min_maf != 0.0) || (max_maf != 1.0)) { |
| 3579 |
// defend against floating point error |
| 3580 |
min_maf *= 1.0 - kSmallEpsilon; |
| 3581 |
max_maf *= 1.0 + kSmallEpsilon; |
| 3582 |
} else { |
| 3583 |
allele_freqs = nullptr; |
| 3584 |
} |
| 3585 |
const uint32_t dosage_filter = min_allele_ddosage || (max_allele_ddosage != (~0LLU)); |
| 3586 |
|
| 3587 |
uintptr_t variant_uidx_base = 0; |
| 3588 |
uintptr_t cur_bits = variant_include[0]; |
| 3589 |
uint32_t allele_ct = 2; |
| 3590 |
for (uint32_t variant_idx = 0; variant_idx != prefilter_variant_ct; ++variant_idx) { |
| 3591 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3592 |
uintptr_t allele_idx_offset_base; |
| 3593 |
if (!allele_idx_offsets) { |
| 3594 |
allele_idx_offset_base = 2 * variant_uidx; |
| 3595 |
} else { |
| 3596 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3597 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 3598 |
} |
| 3599 |
if (allele_freqs) { |
| 3600 |
const double* cur_allele_freqs = &(allele_freqs[allele_idx_offset_base - variant_uidx]); |
| 3601 |
if (min_maf != 0.0) { |
| 3602 |
const double cur_typed_freq = GetTypedFreq(cur_allele_freqs, allele_ct, filter_modes[0]); |
| 3603 |
if (cur_typed_freq < min_maf) { |
| 3604 |
goto EnforceFreqConstraints_remove; |
| 3605 |
} |
| 3606 |
} |
| 3607 |
if (max_maf < 1.0) { |
| 3608 |
// technically a bit inefficient |
| 3609 |
const double cur_typed_freq = GetTypedFreq(cur_allele_freqs, allele_ct, filter_modes[1]); |
| 3610 |
if (cur_typed_freq > max_maf) { |
| 3611 |
goto EnforceFreqConstraints_remove; |
| 3612 |
} |
| 3613 |
} |
| 3614 |
} |
| 3615 |
if (dosage_filter) { |
| 3616 |
const uint64_t* cur_founder_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]); |
| 3617 |
if (min_allele_ddosage) { |
| 3618 |
const uint64_t cur_typed_ddosage = GetTypedDdosage(cur_founder_allele_ddosages, allele_ct, filter_modes[2]); |
| 3619 |
if (cur_typed_ddosage < min_allele_ddosage) { |
| 3620 |
goto EnforceFreqConstraints_remove; |
| 3621 |
} |
| 3622 |
} |
| 3623 |
if (max_allele_ddosage != (~0LLU)) { |
| 3624 |
const uint64_t cur_typed_ddosage = GetTypedDdosage(cur_founder_allele_ddosages, allele_ct, filter_modes[3]); |
| 3625 |
if (cur_typed_ddosage > max_allele_ddosage) { |
| 3626 |
goto EnforceFreqConstraints_remove; |
| 3627 |
} |
| 3628 |
} |
| 3629 |
} |
| 3630 |
continue; |
| 3631 |
EnforceFreqConstraints_remove: |
| 3632 |
ClearBit(variant_uidx, variant_include); |
| 3633 |
++removed_ct; |
| 3634 |
} |
| 3635 |
logprintfww("%u variant%s removed due to allele frequency threshold(s) (--maf/--max-maf/--mac/--max-mac).\n", removed_ct, (removed_ct == 1)? "" : "s"); |
| 3636 |
*variant_ct_ptr -= removed_ct; |
| 3637 |
} |
| 3638 |
|
| 3639 |
void EnforceImpR2Thresh(const ChrInfo* cip, const double* imp_r2_vals, double imp_r2_min, double imp_r2_max, uint32_t is_minimac3_r2, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 3640 |
const uint32_t prefilter_variant_ct = *variant_ct_ptr; |
| 3641 |
imp_r2_min *= 1 - kSmallishEpsilon; |
| 3642 |
imp_r2_max *= 1 + kSmallishEpsilon; |
| 3643 |
uint32_t removed_ct = 0; |
| 3644 |
uint32_t relevant_variant_ct = prefilter_variant_ct; |
| 3645 |
// skip X, MT |
| 3646 |
uint32_t x_code; |
| 3647 |
if (XymtExists(cip, kChrOffsetX, &x_code)) { |
| 3648 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 3649 |
relevant_variant_ct -= PopcountBitRange(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1]); |
| 3650 |
} |
| 3651 |
uint32_t mt_code; |
| 3652 |
if (XymtExists(cip, kChrOffsetMT, &mt_code)) { |
| 3653 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[mt_code]; |
| 3654 |
relevant_variant_ct -= PopcountBitRange(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1]); |
| 3655 |
} |
| 3656 |
uintptr_t variant_uidx_base = 0; |
| 3657 |
uintptr_t cur_bits = variant_include[0]; |
| 3658 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 3659 |
uint32_t chr_end = 0; |
| 3660 |
for (uint32_t variant_idx = 0; variant_idx != relevant_variant_ct; ++variant_idx) { |
| 3661 |
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3662 |
if (variant_uidx >= chr_end) { |
| 3663 |
do { |
| 3664 |
uint32_t chr_idx; |
| 3665 |
do { |
| 3666 |
chr_idx = cip->chr_file_order[++chr_fo_idx]; |
| 3667 |
// bugfix (9 Jul 2018): this boolean condition was reversed |
| 3668 |
} while ((chr_idx == x_code) || (chr_idx == mt_code)); |
| 3669 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 3670 |
variant_uidx = AdvBoundedTo1Bit(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], chr_end); |
| 3671 |
} while (variant_uidx >= chr_end); |
| 3672 |
const uint32_t variant_widx = variant_uidx / kBitsPerWord; |
| 3673 |
variant_uidx_base = variant_widx * kBitsPerWord; |
| 3674 |
cur_bits = variant_include[variant_widx] & ((~k1LU) << (variant_uidx % kBitsPerWord)); |
| 3675 |
} |
| 3676 |
const double cur_imp_r2 = imp_r2_vals[variant_uidx]; |
| 3677 |
// er, we *don't* want to filter out NaN here, those variants may be worth |
| 3678 |
// filtering but not on imputation quality grounds |
| 3679 |
if ((cur_imp_r2 < imp_r2_min) || (cur_imp_r2 > imp_r2_max)) { |
| 3680 |
ClearBit(variant_uidx, variant_include); |
| 3681 |
++removed_ct; |
| 3682 |
} |
| 3683 |
} |
| 3684 |
logprintf("--%s-r2-filter: %u variant%s removed.\n", is_minimac3_r2? "minimac3" : "mach", removed_ct, (removed_ct == 1)? "" : "s"); |
| 3685 |
*variant_ct_ptr -= removed_ct; |
| 3686 |
} |
| 3687 |
|
| 3688 |
void EnforceMinBpSpace(const ChrInfo* cip, const uint32_t* variant_bps, uint32_t min_bp_space, uintptr_t* variant_include, uint32_t* variant_ct_ptr) { |
| 3689 |
const uint32_t orig_variant_ct = *variant_ct_ptr; |
| 3690 |
uintptr_t variant_uidx_base = 0; |
| 3691 |
uintptr_t cur_bits = variant_include[0]; |
| 3692 |
uint32_t chr_fo_idx_p1 = 0; |
| 3693 |
uint32_t chr_end = 0; |
| 3694 |
uint32_t last_bp = 0; |
| 3695 |
uint32_t removed_ct = 0; |
| 3696 |
for (uint32_t variant_idx = 0; variant_idx != orig_variant_ct; ++variant_idx) { |
| 3697 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3698 |
const uint32_t cur_bp = variant_bps[variant_uidx]; |
| 3699 |
if (variant_uidx >= chr_end) { |
| 3700 |
do { |
| 3701 |
chr_end = cip->chr_fo_vidx_start[++chr_fo_idx_p1]; |
| 3702 |
} while (variant_uidx >= chr_end); |
| 3703 |
last_bp = cur_bp; |
| 3704 |
} else { |
| 3705 |
if (cur_bp < last_bp + min_bp_space) { |
| 3706 |
ClearBit(variant_uidx, variant_include); |
| 3707 |
++removed_ct; |
| 3708 |
} else { |
| 3709 |
last_bp = cur_bp; |
| 3710 |
} |
| 3711 |
} |
| 3712 |
} |
| 3713 |
const uint32_t new_variant_ct = orig_variant_ct - removed_ct; |
| 3714 |
logprintf("--bp-space: %u variant%s removed (%u remaining).\n", removed_ct, (removed_ct == 1)? "" : "s", new_variant_ct); |
| 3715 |
*variant_ct_ptr = new_variant_ct; |
| 3716 |
} |
| 3717 |
|
| 3718 |
// Generalization of plink 1.9 load_ax_alleles(). |
| 3719 |
// |
| 3720 |
// Note that, when a variant has 2 (or more) nonmissing allele codes, we print |
| 3721 |
// a warning if the loaded allele doesn't match one of them (and the variant is |
| 3722 |
// unchanged). However, if the variant is biallelic with one or two missing |
| 3723 |
// allele codes, a missing allele code is filled in. This maintains |
| 3724 |
// compatibility with plink 1.9 --a1-allele/--a2-allele's behavior, and is good |
| 3725 |
// enough for most real-world use cases; however, it's a bit annoying to be |
| 3726 |
// unable to e.g. add the ref allele when dealing with a single-sample file |
| 3727 |
// with a het alt1/alt2 call. |
| 3728 |
// (Workaround for that case when merge is implemented: generate a |
| 3729 |
// single-sample file with all the right reference alleles, and merge with |
| 3730 |
// that.) |
| 3731 |
PglErr SetRefalt1FromFile(const uintptr_t* variant_include, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const TwoColParams* allele_flag_info, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_variant_id_slen, uint32_t max_allele_ct, Refalt1Mode refalt1_mode, uint32_t force, char input_missing_geno_char, uint32_t max_thread_ct, const char** allele_storage, uint32_t* max_allele_slen_ptr, AlleleCode* allele_permute, uintptr_t* nonref_flags, uintptr_t* previously_seen) { |
| 3732 |
// temporary allocations on bottom, "permanent" allocations on top (so we |
| 3733 |
// don't reset g_bigstack_end). |
| 3734 |
// previously_seen[] should be preallocated iff both --ref-allele and |
| 3735 |
// --alt[1]-allele are present in the same run. when it is, this errors out |
| 3736 |
// when the flags produce conflicting results. |
| 3737 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3738 |
|
| 3739 |
// unaligned in middle of loop |
| 3740 |
unsigned char* bigstack_end = g_bigstack_end; |
| 3741 |
|
| 3742 |
const uint32_t is_alt_or_alt1 = (refalt1_mode != kRefalt1ModeRef); |
| 3743 |
const uint32_t is_alt1 = (refalt1_mode == kRefalt1ModeAlt1); |
| 3744 |
const char* flagstr; |
| 3745 |
if (refalt1_mode == kRefalt1ModeRef) { |
| 3746 |
flagstr = "--ref-allele"; |
| 3747 |
} else if (refalt1_mode == kRefalt1ModeAlt) { |
| 3748 |
flagstr = "--alt-allele"; |
| 3749 |
} else { |
| 3750 |
flagstr = "--alt1-allele"; |
| 3751 |
} |
| 3752 |
uintptr_t line_idx = 0; |
| 3753 |
PglErr reterr = kPglRetSuccess; |
| 3754 |
TextStream txs; |
| 3755 |
PreinitTextStream(&txs); |
| 3756 |
{ |
| 3757 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 3758 |
const uint32_t max_allele_ctl = BitCtToWordCt(max_allele_ct); |
| 3759 |
uintptr_t* already_seen; |
| 3760 |
AlleleCode* loaded_ac_order; |
| 3761 |
uintptr_t* alleles_seen; |
| 3762 |
if (unlikely(bigstack_calloc_w(raw_variant_ctl, &already_seen) || |
| 3763 |
bigstack_alloc_ac(max_allele_ct, &loaded_ac_order) || |
| 3764 |
bigstack_alloc_w(max_allele_ctl, &alleles_seen))) { |
| 3765 |
goto SetRefalt1FromFile_ret_NOMEM; |
| 3766 |
} |
| 3767 |
reterr = SizeAndInitTextStream(allele_flag_info->fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs); |
| 3768 |
if (unlikely(reterr)) { |
| 3769 |
goto SetRefalt1FromFile_ret_TSTREAM_FAIL; |
| 3770 |
} |
| 3771 |
const uint32_t skip_ct = allele_flag_info->skip_ct; |
| 3772 |
reterr = TextSkip(skip_ct, &txs); |
| 3773 |
if (unlikely(reterr)) { |
| 3774 |
if (reterr == kPglRetEof) { |
| 3775 |
snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", allele_flag_info->fname); |
| 3776 |
goto SetRefalt1FromFile_ret_INCONSISTENT_INPUT_WW; |
| 3777 |
} |
| 3778 |
goto SetRefalt1FromFile_ret_TSTREAM_FAIL; |
| 3779 |
} |
| 3780 |
uint32_t* variant_id_htable = nullptr; |
| 3781 |
uint32_t variant_id_htable_size; |
| 3782 |
reterr = AllocAndPopulateIdHtableMt(variant_include, variant_ids, variant_ct, bigstack_left() / 8, max_thread_ct, &variant_id_htable, nullptr, &variant_id_htable_size, nullptr); |
| 3783 |
if (unlikely(reterr)) { |
| 3784 |
goto SetRefalt1FromFile_ret_1; |
| 3785 |
} |
| 3786 |
unsigned char* main_bigstack_base = g_bigstack_base; |
| 3787 |
|
| 3788 |
const uint32_t colid_first = (allele_flag_info->colid < allele_flag_info->colx); |
| 3789 |
const char skipchar = allele_flag_info->skipchar; |
| 3790 |
uint32_t colmin; |
| 3791 |
uint32_t coldiff; |
| 3792 |
if (colid_first) { |
| 3793 |
colmin = allele_flag_info->colid - 1; |
| 3794 |
coldiff = allele_flag_info->colx - allele_flag_info->colid; |
| 3795 |
} else { |
| 3796 |
colmin = allele_flag_info->colx - 1; |
| 3797 |
coldiff = allele_flag_info->colid - allele_flag_info->colx; |
| 3798 |
} |
| 3799 |
line_idx = allele_flag_info->skip_ct; |
| 3800 |
uintptr_t skipped_variant_ct = 0; |
| 3801 |
uintptr_t missing_allele_ct = 0; |
| 3802 |
uint32_t allele_mismatch_warning_ct = 0; |
| 3803 |
uint32_t permuted_variant_ct = 0; |
| 3804 |
uint32_t fillin_variant_ct = 0; |
| 3805 |
uint32_t max_allele_blen = 1 + (*max_allele_slen_ptr); |
| 3806 |
uint32_t cur_allele_ct = 2; |
| 3807 |
while (1) { |
| 3808 |
++line_idx; |
| 3809 |
char* line_start = TextGet(&txs); |
| 3810 |
if (!line_start) { |
| 3811 |
if (likely(!TextStreamErrcode2(&txs, &reterr))) { |
| 3812 |
break; |
| 3813 |
} |
| 3814 |
goto SetRefalt1FromFile_ret_TSTREAM_FAIL; |
| 3815 |
} |
| 3816 |
char cc = *line_start; |
| 3817 |
if (cc == skipchar) { |
| 3818 |
continue; |
| 3819 |
} |
| 3820 |
// er, replace this with TokenLex0()... |
| 3821 |
char* variant_id_start; |
| 3822 |
char* allele_start; |
| 3823 |
if (colid_first) { |
| 3824 |
variant_id_start = NextTokenMult0(line_start, colmin); |
| 3825 |
allele_start = NextTokenMult(variant_id_start, coldiff); |
| 3826 |
if (unlikely(!allele_start)) { |
| 3827 |
goto SetRefalt1FromFile_ret_MISSING_TOKENS; |
| 3828 |
} |
| 3829 |
} else { |
| 3830 |
allele_start = NextTokenMult0(line_start, colmin); |
| 3831 |
variant_id_start = NextTokenMult(allele_start, coldiff); |
| 3832 |
if (unlikely(!variant_id_start)) { |
| 3833 |
goto SetRefalt1FromFile_ret_MISSING_TOKENS; |
| 3834 |
} |
| 3835 |
} |
| 3836 |
char* token_end = CurTokenEnd(variant_id_start); |
| 3837 |
const uint32_t variant_id_slen = token_end - variant_id_start; |
| 3838 |
const uint32_t variant_uidx = VariantIdDupflagHtableFind(variant_id_start, variant_ids, variant_id_htable, variant_id_slen, variant_id_htable_size, max_variant_id_slen); |
| 3839 |
if (variant_uidx >> 31) { |
| 3840 |
if (likely(variant_uidx == UINT32_MAX)) { |
| 3841 |
++skipped_variant_ct; |
| 3842 |
continue; |
| 3843 |
} |
| 3844 |
snprintf(g_logbuf, kLogbufSize, "Error: %s variant ID '%s' appears multiple times in main dataset.\n", flagstr, variant_ids[variant_uidx & 0x7fffffff]); |
| 3845 |
goto SetRefalt1FromFile_ret_MALFORMED_INPUT_WW; |
| 3846 |
} |
| 3847 |
token_end = CurTokenEnd(allele_start); |
| 3848 |
const uint32_t allele_col_slen = token_end - allele_start; |
| 3849 |
if (allele_col_slen == 1) { |
| 3850 |
const char allele_char = *allele_start; |
| 3851 |
// don't overwrite anything with missing code |
| 3852 |
if ((allele_char == '.') || (allele_char == input_missing_geno_char)) { |
| 3853 |
++missing_allele_ct; |
| 3854 |
continue; |
| 3855 |
} |
| 3856 |
} |
| 3857 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 3858 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate variant ID '%s' in %s file.\n", variant_ids[variant_uidx], flagstr); |
| 3859 |
goto SetRefalt1FromFile_ret_MALFORMED_INPUT_WW; |
| 3860 |
} |
| 3861 |
SetBit(variant_uidx, already_seen); |
| 3862 |
if (unlikely((refalt1_mode != kRefalt1ModeAlt) && memchr(allele_start, ',', allele_col_slen))) { |
| 3863 |
snprintf(g_logbuf, kLogbufSize, "Error: %s: Multiple alleles on line %" PRIuPTR ".%s\n", flagstr, line_idx, is_alt1? " (Did you mean --alt-allele?)" : ""); |
| 3864 |
goto SetRefalt1FromFile_ret_MALFORMED_INPUT_WW; |
| 3865 |
} |
| 3866 |
uintptr_t allele_idx_offset_base; |
| 3867 |
if (!allele_idx_offsets) { |
| 3868 |
allele_idx_offset_base = variant_uidx * 2; |
| 3869 |
} else { |
| 3870 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3871 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 3872 |
} |
| 3873 |
const char** cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 3874 |
ZeroWArr(max_allele_ctl, alleles_seen); |
| 3875 |
// --ref-allele and --alt1-allele: There must be exactly one allele here. |
| 3876 |
// --alt-allele: There can be anywhere from 1 to (cur_allele_ct - 1) |
| 3877 |
// alleles here. If less than (cur_allele_ct - 1), |
| 3878 |
// remaining alleles retain original order. |
| 3879 |
// TODO: For cur_allele_ct > 20 or so, construct hash table |
| 3880 |
// instead of performing O(n^2) comparisons. |
| 3881 |
uint32_t loaded_allele_ct = 0; |
| 3882 |
uint32_t last_allele_blen; |
| 3883 |
for (char* allele_iter = allele_start; ; ) { |
| 3884 |
char* allele_end = AdvToDelimOrEnd(allele_iter, token_end, ','); |
| 3885 |
*allele_end = '\0'; |
| 3886 |
last_allele_blen = 1 + S_CAST(uintptr_t, allele_end - allele_iter); |
| 3887 |
for (uint32_t allele_idx = 0; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3888 |
if (memequal(allele_iter, cur_alleles[allele_idx], last_allele_blen)) { |
| 3889 |
if (unlikely(IsSet(alleles_seen, allele_idx))) { |
| 3890 |
snprintf(g_logbuf, kLogbufSize, "Error: --alt-allele: Duplicate allele on line %" PRIuPTR ".\n", line_idx); |
| 3891 |
goto SetRefalt1FromFile_ret_MALFORMED_INPUT_2; |
| 3892 |
} |
| 3893 |
SetBit(allele_idx, alleles_seen); |
| 3894 |
loaded_ac_order[loaded_allele_ct] = allele_idx; |
| 3895 |
++loaded_allele_ct; |
| 3896 |
break; |
| 3897 |
} |
| 3898 |
} |
| 3899 |
if (allele_end == token_end) { |
| 3900 |
break; |
| 3901 |
} |
| 3902 |
allele_iter = &(allele_end[1]); |
| 3903 |
} |
| 3904 |
if (unlikely(loaded_allele_ct == cur_allele_ct)) { |
| 3905 |
snprintf(g_logbuf, kLogbufSize, "Error: --alt-allele: All alleles appear on line %" PRIuPTR "; nothing left over to assign to REF.\n", line_idx); |
| 3906 |
goto SetRefalt1FromFile_ret_MALFORMED_INPUT_2; |
| 3907 |
} |
| 3908 |
// Note that when both --ref-allele and --alt[1]-allele are present in |
| 3909 |
// the same run, --alt[1]-allele must deal with the possibility of a |
| 3910 |
// pre-altered allele_permute[]. |
| 3911 |
AlleleCode* cur_allele_permute = &(allele_permute[allele_idx_offset_base]); |
| 3912 |
// This is usually 0 for --ref-allele, and 1 for --alt[1]-allele. |
| 3913 |
// The exception is when --alt[1]-allele is being resolved after |
| 3914 |
// --ref-allele swapped alleles: then it's 0. |
| 3915 |
const uint32_t orig_main_allele_idx = cur_allele_permute[is_alt_or_alt1]; |
| 3916 |
|
| 3917 |
if (loaded_allele_ct == 0) { |
| 3918 |
if (cur_allele_ct > 2) { |
| 3919 |
// could happen millions of times, so micromanage this instead of |
| 3920 |
// using logpreprintfww() |
| 3921 |
char* write_iter = strcpya_k(g_logbuf, "Warning: "); |
| 3922 |
// strlen("--ref-allele") == strlen("--alt-allele")== 12, |
| 3923 |
// strlen("--alt1-allele") == 13 |
| 3924 |
write_iter = memcpya(write_iter, flagstr, 12 + is_alt1); |
| 3925 |
write_iter = strcpya_k(write_iter, " mismatch for multiallelic variant"); |
| 3926 |
// If we put this all on one line, its length would be |
| 3927 |
// 60 + is_alt_or_alt1 + variant_id_slen. Split into two if this is |
| 3928 |
// >79. |
| 3929 |
*write_iter++ = (variant_id_slen + is_alt1 < 20)? ' ' : '\n'; |
| 3930 |
*write_iter++ = '\''; |
| 3931 |
write_iter = memcpya(write_iter, variant_ids[variant_uidx], variant_id_slen); |
| 3932 |
strcpy_k(write_iter, "'.\n"); |
| 3933 |
if (allele_mismatch_warning_ct < 3) { |
| 3934 |
logerrputsb(); |
| 3935 |
} else { |
| 3936 |
logputs_silent(g_logbuf); |
| 3937 |
} |
| 3938 |
++allele_mismatch_warning_ct; |
| 3939 |
continue; |
| 3940 |
} |
| 3941 |
const char** new_allele_ptr = &(cur_alleles[orig_main_allele_idx]); |
| 3942 |
const char* main_allele = *new_allele_ptr; |
| 3943 |
const uint32_t multi_alt = (last_allele_blen <= allele_col_slen); |
| 3944 |
uint32_t is_ref_changing = 1 - orig_main_allele_idx; |
| 3945 |
// If main allele is missing, we fill it in (unless there were multiple |
| 3946 |
// comma-separated ALT values). |
| 3947 |
if ((!strequal_k_unsafe(main_allele, ".")) || multi_alt) { |
| 3948 |
new_allele_ptr = &(cur_alleles[1 - orig_main_allele_idx]); |
| 3949 |
const char* other_allele = *new_allele_ptr; |
| 3950 |
if ((!strequal_k_unsafe(other_allele, ".")) || multi_alt) { |
| 3951 |
char* write_iter = strcpya_k(g_logbuf, "Warning: "); |
| 3952 |
write_iter = memcpya(write_iter, flagstr, 12 + is_alt1); |
| 3953 |
write_iter = strcpya_k(write_iter, " mismatch for biallelic variant '"); |
| 3954 |
write_iter = strcpya(write_iter, variant_ids[variant_uidx]); |
| 3955 |
strcpy_k(write_iter, "'.\n"); |
| 3956 |
if (allele_mismatch_warning_ct < 3) { |
| 3957 |
logerrputsb(); |
| 3958 |
} else { |
| 3959 |
logputs_silent(g_logbuf); |
| 3960 |
} |
| 3961 |
++allele_mismatch_warning_ct; |
| 3962 |
continue; |
| 3963 |
} |
| 3964 |
// If we get here during --ref-allele processing, that means REF is |
| 3965 |
// nonmissing and unequal, and ALT is missing. Fill ALT and then |
| 3966 |
// swap REF/ALT. |
| 3967 |
// If we get here during --alt[1]-allele processing: |
| 3968 |
// * If --ref-allele previously swapped the alleles, that would mean |
| 3969 |
// REF is nonmissing and unequal, and ALT is simultaneously missing |
| 3970 |
// and equal to a nonmissing --ref-allele setting... impossible. |
| 3971 |
// * So that didn't happen; instead, ALT is nonmissing and unequal, |
| 3972 |
// and REF is missing. Fill REF and then swap REF/ALT. Also |
| 3973 |
// (bugfix, 3 Jul 2024) set nonref_flags bit unless --ref-allele |
| 3974 |
// explicitly agreed with the ALT allele. |
| 3975 |
cur_allele_permute[0] = 1; |
| 3976 |
cur_allele_permute[1] = 0; |
| 3977 |
++permuted_variant_ct; |
| 3978 |
is_ref_changing = 1; |
| 3979 |
} |
| 3980 |
if (is_ref_changing) { |
| 3981 |
if (!is_alt_or_alt1) { |
| 3982 |
if (!IsSet(nonref_flags, variant_uidx)) { |
| 3983 |
if (unlikely(!force)) { |
| 3984 |
goto SetRefalt1FromFile_ret_NOFORCE; |
| 3985 |
} |
| 3986 |
} else { |
| 3987 |
ClearBit(variant_uidx, nonref_flags); |
| 3988 |
} |
| 3989 |
} else { |
| 3990 |
// If --ref-allele had something to say about this variant, |
| 3991 |
// --alt[1]-allele 'force' should not apply, and we should not set |
| 3992 |
// a nonref_flags bit. |
| 3993 |
// Otherwise, both are in play. |
| 3994 |
if ((!previously_seen) || (!IsSet(previously_seen, variant_uidx))) { |
| 3995 |
if (!IsSet(nonref_flags, variant_uidx)) { |
| 3996 |
if (unlikely(!force)) { |
| 3997 |
goto SetRefalt1FromFile_ret_NOFORCE; |
| 3998 |
} |
| 3999 |
SetBit(variant_uidx, nonref_flags); |
| 4000 |
} |
| 4001 |
} |
| 4002 |
} |
| 4003 |
} |
| 4004 |
if (last_allele_blen == 2) { |
| 4005 |
*new_allele_ptr = &(g_one_char_strs[2 * ctou32(allele_start[0])]); |
| 4006 |
} else { |
| 4007 |
// No in-place-overwrite case here since |
| 4008 |
// 1. *new_allele_ptr was always '.' |
| 4009 |
// 2. More importantly, when --loop-cats is used, |
| 4010 |
// allele_storage_backup[n] must point to the unaltered original |
| 4011 |
// string. |
| 4012 |
if (unlikely(S_CAST(uintptr_t, bigstack_end - main_bigstack_base) < last_allele_blen)) { |
| 4013 |
goto SetRefalt1FromFile_ret_NOMEM; |
| 4014 |
} |
| 4015 |
if (last_allele_blen > max_allele_blen) { |
| 4016 |
max_allele_blen = last_allele_blen; |
| 4017 |
} |
| 4018 |
bigstack_end -= last_allele_blen; |
| 4019 |
memcpy(bigstack_end, allele_start, last_allele_blen); |
| 4020 |
*new_allele_ptr = R_CAST(const char*, bigstack_end); |
| 4021 |
} |
| 4022 |
++fillin_variant_ct; |
| 4023 |
continue; |
| 4024 |
} |
| 4025 |
const uint32_t first_allele_idx = loaded_ac_order[0]; |
| 4026 |
if (first_allele_idx == orig_main_allele_idx) { |
| 4027 |
uint32_t mismatch_found = 0; |
| 4028 |
for (uint32_t alt_idx = 1; alt_idx != loaded_allele_ct; ++alt_idx) { |
| 4029 |
if (loaded_ac_order[alt_idx] != cur_allele_permute[alt_idx + 1]) { |
| 4030 |
mismatch_found = 1; |
| 4031 |
} |
| 4032 |
} |
| 4033 |
if (!mismatch_found) { |
| 4034 |
continue; |
| 4035 |
} |
| 4036 |
} |
| 4037 |
// We're permuting some alleles. |
| 4038 |
if (is_alt_or_alt1 && previously_seen && IsSet(previously_seen, variant_uidx)) { |
| 4039 |
if (unlikely(IsSet(alleles_seen, cur_allele_permute[0]))) { |
| 4040 |
// both --ref-allele and --alt[1]-allele in current run, and they |
| 4041 |
// contradict each other. error out instead of producing a |
| 4042 |
// order-of-operations dependent result. |
| 4043 |
snprintf(g_logbuf, kLogbufSize, "Error: --ref-allele and --alt[1]-allele assignments conflict for variant '%s'.\n", variant_ids[variant_uidx]); |
| 4044 |
goto SetRefalt1FromFile_ret_INCONSISTENT_INPUT_WW; |
| 4045 |
} |
| 4046 |
// minor bugfix (3 Jul 2024): do not perform further nonref_flags |
| 4047 |
// check; only --ref-allele 'force' setting should apply. |
| 4048 |
} else { |
| 4049 |
// * If !is_alt_or_alt1, we are directly changing the REF allele. |
| 4050 |
// * If IsSet(alleles_seen, 0), we're processing --alt[1]-allele |
| 4051 |
// without a --ref-allele observation at this variant, and the REF |
| 4052 |
// allele also has to change. We set it to the first free ALT |
| 4053 |
// allele, and mark it as provisional-reference. |
| 4054 |
if ((!is_alt_or_alt1) || IsSet(alleles_seen, 0)) { |
| 4055 |
if (!IsSet(nonref_flags, variant_uidx)) { |
| 4056 |
if (unlikely(!force)) { |
| 4057 |
goto SetRefalt1FromFile_ret_NOFORCE; |
| 4058 |
} |
| 4059 |
} else if (!is_alt_or_alt1) { |
| 4060 |
ClearBit(variant_uidx, nonref_flags); |
| 4061 |
} |
| 4062 |
if (is_alt_or_alt1) { |
| 4063 |
const uint32_t first_free_ac = AdvTo0Bit(alleles_seen, 0); |
| 4064 |
cur_allele_permute[0] = first_free_ac; |
| 4065 |
SetBit(variant_uidx, nonref_flags); |
| 4066 |
} |
| 4067 |
} |
| 4068 |
} |
| 4069 |
if (!is_alt_or_alt1) { |
| 4070 |
cur_allele_permute[0] = first_allele_idx; |
| 4071 |
for (uint32_t write_ac = 0; write_ac != first_allele_idx; ++write_ac) { |
| 4072 |
cur_allele_permute[1 + write_ac] = write_ac; |
| 4073 |
} |
| 4074 |
} else { |
| 4075 |
memcpy(&(cur_allele_permute[1]), loaded_ac_order, loaded_allele_ct * sizeof(AlleleCode)); |
| 4076 |
if (loaded_allele_ct + 1 != cur_allele_ct) { |
| 4077 |
SetBit(cur_allele_permute[0], alleles_seen); |
| 4078 |
|
| 4079 |
// No need to update final unobserved alleles, if any. |
| 4080 |
const uint32_t write_aidx_stop = FindLast1BitBefore(alleles_seen, cur_allele_ct) + 1; |
| 4081 |
|
| 4082 |
uintptr_t allele_idx_base = 0; |
| 4083 |
uintptr_t cur_inv_bits = ~alleles_seen[0]; |
| 4084 |
for (uint32_t write_aidx = loaded_allele_ct + 1; write_aidx != write_aidx_stop; ++write_aidx) { |
| 4085 |
const uintptr_t ac = BitIter0(alleles_seen, &allele_idx_base, &cur_inv_bits); |
| 4086 |
cur_allele_permute[write_aidx] = ac; |
| 4087 |
} |
| 4088 |
} |
| 4089 |
} |
| 4090 |
++permuted_variant_ct; |
| 4091 |
} |
| 4092 |
if (allele_mismatch_warning_ct > 3) { |
| 4093 |
fprintf(stderr, "%u more allele-mismatch warning%s: see log file.\n", allele_mismatch_warning_ct - 3, (allele_mismatch_warning_ct == 4)? "" : "s"); |
| 4094 |
} |
| 4095 |
if (fillin_variant_ct) { |
| 4096 |
if (permuted_variant_ct) { |
| 4097 |
logprintfww("%s: %u set%s of allele codes permuted, %u allele code%s filled in.\n", flagstr, permuted_variant_ct, (permuted_variant_ct == 1)? "" : "s", fillin_variant_ct, (fillin_variant_ct == 1)? "" : "s"); |
| 4098 |
} else { |
| 4099 |
logprintf("%s: %u allele code%s filled in.\n", flagstr, fillin_variant_ct, (fillin_variant_ct == 1)? "" : "s"); |
| 4100 |
} |
| 4101 |
} else if (permuted_variant_ct) { |
| 4102 |
logprintf("%s: %u set%s of allele codes permuted.\n", flagstr, permuted_variant_ct, (permuted_variant_ct == 1)? "" : "s"); |
| 4103 |
} else { |
| 4104 |
logprintf("%s: No variants changed.\n", flagstr); |
| 4105 |
} |
| 4106 |
if (skipped_variant_ct) { |
| 4107 |
logerrprintfww("Warning: %" PRIuPTR " variant ID%s in %s file missing from main dataset.\n", skipped_variant_ct, (skipped_variant_ct == 1)? "" : "s", flagstr); |
| 4108 |
} |
| 4109 |
if (missing_allele_ct) { |
| 4110 |
logerrprintfww("Warning: %" PRIuPTR " allele code%s in %s file were missing (%s skipped).\n", missing_allele_ct, (missing_allele_ct == 1)? "" : "s", flagstr, (missing_allele_ct == 1)? "this entry was" : "these entries were"); |
| 4111 |
} |
| 4112 |
if (previously_seen && (!is_alt_or_alt1)) { |
| 4113 |
memcpy(previously_seen, already_seen, raw_variant_ctl * sizeof(intptr_t)); |
| 4114 |
} |
| 4115 |
// bugfix (19 Jun 2018): forgot to update max_allele_slen. |
| 4116 |
*max_allele_slen_ptr = max_allele_blen - 1; |
| 4117 |
} |
| 4118 |
while (0) { |
| 4119 |
SetRefalt1FromFile_ret_NOMEM: |
| 4120 |
reterr = kPglRetNomem; |
| 4121 |
break; |
| 4122 |
SetRefalt1FromFile_ret_TSTREAM_FAIL: |
| 4123 |
{ |
| 4124 |
char file_descrip_buf[32]; |
| 4125 |
snprintf(file_descrip_buf, 32, "%s file", flagstr); |
| 4126 |
TextStreamErrPrint(file_descrip_buf, &txs); |
| 4127 |
} |
| 4128 |
break; |
| 4129 |
SetRefalt1FromFile_ret_MISSING_TOKENS: |
| 4130 |
logerrprintfww("Error: Line %" PRIuPTR " of %s file has fewer tokens than expected.\n", line_idx, flagstr); |
| 4131 |
reterr = kPglRetMalformedInput; |
| 4132 |
break; |
| 4133 |
SetRefalt1FromFile_ret_MALFORMED_INPUT_WW: |
| 4134 |
WordWrapB(0); |
| 4135 |
SetRefalt1FromFile_ret_MALFORMED_INPUT_2: |
| 4136 |
logerrputsb(); |
| 4137 |
reterr = kPglRetMalformedInput; |
| 4138 |
break; |
| 4139 |
SetRefalt1FromFile_ret_NOFORCE: |
| 4140 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of %s file contradicts 'known' reference allele. Add the 'force' modifier to %s to force an allele swap anyway.\n", line_idx, flagstr, flagstr); |
| 4141 |
SetRefalt1FromFile_ret_INCONSISTENT_INPUT_WW: |
| 4142 |
WordWrapB(0); |
| 4143 |
logerrputsb(); |
| 4144 |
reterr = kPglRetInconsistentInput; |
| 4145 |
break; |
| 4146 |
} |
| 4147 |
SetRefalt1FromFile_ret_1: |
| 4148 |
if (CleanupTextStream(&txs, &reterr)) { |
| 4149 |
logerrprintfww("Error: %s file read failure: %s.\n", flagstr, rstrerror(errno)); |
| 4150 |
} |
| 4151 |
BigstackReset(bigstack_mark); |
| 4152 |
BigstackEndSet(bigstack_end); |
| 4153 |
return reterr; |
| 4154 |
} |
| 4155 |
|
| 4156 |
PglErr MakeFounders(const uintptr_t* sample_include, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t require_two, PedigreeIdInfo* piip, uintptr_t* founder_info) { |
| 4157 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 4158 |
PglErr reterr = kPglRetSuccess; |
| 4159 |
{ |
| 4160 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 4161 |
const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen; |
| 4162 |
char* idbuf; |
| 4163 |
uintptr_t* nf_bitvec; |
| 4164 |
if (bigstack_alloc_c(max_sample_id_blen, &idbuf) || |
| 4165 |
bigstack_alloc_w(raw_sample_ctl, &nf_bitvec)) { |
| 4166 |
goto MakeFounders_ret_NOMEM; |
| 4167 |
} |
| 4168 |
BitvecInvmaskCopy(sample_include, founder_info, raw_sample_ctl, nf_bitvec); |
| 4169 |
uint32_t sample_uidx = AdvBoundedTo1Bit(nf_bitvec, 0, raw_sample_ct); |
| 4170 |
if (sample_uidx == raw_sample_ct) { |
| 4171 |
logputs("Note: Skipping --make-founders since there are no nonfounders.\n"); |
| 4172 |
goto MakeFounders_ret_1; |
| 4173 |
} |
| 4174 |
const char* sample_ids = piip->sii.sample_ids; |
| 4175 |
uint32_t* id_htable; |
| 4176 |
uint32_t id_htable_size; |
| 4177 |
if (unlikely(HtableGoodSizeAlloc(sample_ct, bigstack_left(), &id_htable, &id_htable_size))) { |
| 4178 |
goto MakeFounders_ret_NOMEM; |
| 4179 |
} |
| 4180 |
PopulateStrboxSubsetHtableDup(sample_ids, sample_include, sample_ct, max_sample_id_blen, id_htable_size, id_htable); |
| 4181 |
const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen; |
| 4182 |
const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen; |
| 4183 |
char* paternal_ids = piip->parental_id_info.paternal_ids; |
| 4184 |
char* maternal_ids = piip->parental_id_info.maternal_ids; |
| 4185 |
uint32_t new_founder_ct = 0; |
| 4186 |
do { |
| 4187 |
const char* fid_start = &(sample_ids[sample_uidx * max_sample_id_blen]); |
| 4188 |
const char* fid_postend = AdvPastDelim(fid_start, '\t'); |
| 4189 |
const uint32_t fid_blen = fid_postend - fid_start; |
| 4190 |
char* iid_write_start = memcpya(idbuf, fid_start, fid_blen); |
| 4191 |
|
| 4192 |
uint32_t missing_parent_ct = 0; |
| 4193 |
char* pat_ptr = &(paternal_ids[sample_uidx * max_paternal_id_blen]); |
| 4194 |
const uint32_t pat_slen = strlen(pat_ptr); |
| 4195 |
if (fid_blen + pat_slen >= max_sample_id_blen) { |
| 4196 |
++missing_parent_ct; |
| 4197 |
} else { |
| 4198 |
memcpy(iid_write_start, pat_ptr, pat_slen + 1); |
| 4199 |
const uint32_t uii = StrboxHtableFind(idbuf, sample_ids, id_htable, max_sample_id_blen, fid_blen + pat_slen, id_htable_size); |
| 4200 |
if (uii == UINT32_MAX) { |
| 4201 |
++missing_parent_ct; |
| 4202 |
} |
| 4203 |
} |
| 4204 |
char* mat_ptr = &(maternal_ids[sample_uidx * max_maternal_id_blen]); |
| 4205 |
const uint32_t mat_slen = strlen(mat_ptr); |
| 4206 |
if (fid_blen + mat_slen >= max_sample_id_blen) { |
| 4207 |
++missing_parent_ct; |
| 4208 |
} else { |
| 4209 |
memcpy(iid_write_start, mat_ptr, mat_slen + 1); |
| 4210 |
const uint32_t uii = StrboxHtableFind(idbuf, sample_ids, id_htable, max_sample_id_blen, fid_blen + mat_slen, id_htable_size); |
| 4211 |
if (uii == UINT32_MAX) { |
| 4212 |
++missing_parent_ct; |
| 4213 |
} |
| 4214 |
} |
| 4215 |
if (missing_parent_ct > require_two) { |
| 4216 |
SetBit(sample_uidx, founder_info); |
| 4217 |
strcpy_k(pat_ptr, "0"); |
| 4218 |
strcpy_k(mat_ptr, "0"); |
| 4219 |
++new_founder_ct; |
| 4220 |
} |
| 4221 |
sample_uidx = AdvBoundedTo1Bit(nf_bitvec, sample_uidx + 1, raw_sample_ct); |
| 4222 |
} while (sample_uidx != raw_sample_ct); |
| 4223 |
logprintf("--make-founders: %u sample%s affected.\n", new_founder_ct, (new_founder_ct == 1)? "" : "s"); |
| 4224 |
} |
| 4225 |
while (0) { |
| 4226 |
MakeFounders_ret_NOMEM: |
| 4227 |
reterr = kPglRetNomem; |
| 4228 |
break; |
| 4229 |
} |
| 4230 |
MakeFounders_ret_1: |
| 4231 |
BigstackReset(bigstack_mark); |
| 4232 |
return reterr; |
| 4233 |
} |
| 4234 |
|
| 4235 |
static_assert(sizeof(Dosage) + sizeof(AlleleCode) <= 4, "MajRef() needs to be updated."); |
| 4236 |
PglErr MajRef(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, const uint64_t* main_allele_ddosages, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t skip_real_ref, AlleleCode* allele_permute, uintptr_t* nonref_flags) { |
| 4237 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 4238 |
PglErr reterr = kPglRetSuccess; |
| 4239 |
{ |
| 4240 |
uint64_t* sortbuf = nullptr; |
| 4241 |
if (allele_idx_offsets) { |
| 4242 |
if (unlikely(bigstack_alloc_u64(max_allele_ct, &sortbuf))) { |
| 4243 |
goto MajRef_ret_NOMEM; |
| 4244 |
} |
| 4245 |
} |
| 4246 |
// todo: multithread this |
| 4247 |
uintptr_t variant_uidx_base = 0; |
| 4248 |
uintptr_t cur_bits = variant_include[0]; |
| 4249 |
uint32_t allele_ct = 2; |
| 4250 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 4251 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4252 |
// bugfix (25 Jun 2024): nonref_flags check was backwards |
| 4253 |
if (skip_real_ref && (!IsSet(nonref_flags, variant_uidx))) { |
| 4254 |
continue; |
| 4255 |
} |
| 4256 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 4257 |
if (allele_idx_offsets) { |
| 4258 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 4259 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 4260 |
} |
| 4261 |
const uint64_t* cur_allele_ddosages = &(main_allele_ddosages[allele_idx_offset_base]); |
| 4262 |
if (allele_ct == 2) { |
| 4263 |
if (cur_allele_ddosages[1] > cur_allele_ddosages[0]) { |
| 4264 |
allele_permute[allele_idx_offset_base] = 1; |
| 4265 |
allele_permute[allele_idx_offset_base + 1] = 0; |
| 4266 |
if (nonref_flags) { |
| 4267 |
SetBit(variant_uidx, nonref_flags); |
| 4268 |
} |
| 4269 |
} |
| 4270 |
continue; |
| 4271 |
} |
| 4272 |
// Sort by allele frequency, breaking ties in favor of lower aidx. |
| 4273 |
// sortbuf entries have a (shared) multiple of the allele frequency in |
| 4274 |
// high bits, and (kPglMaxAlleleCt - aidx) in low bits. |
| 4275 |
for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) { |
| 4276 |
sortbuf[aidx] = cur_allele_ddosages[aidx] * (kPglMaxAlleleCt + 1) + kPglMaxAlleleCt - aidx; |
| 4277 |
} |
| 4278 |
STD_SORT(allele_ct, u64cmp, sortbuf); |
| 4279 |
AlleleCode* cur_allele_permute = &(allele_permute[allele_idx_offset_base]); |
| 4280 |
const uint32_t allele_ct_m1 = allele_ct - 1; |
| 4281 |
for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) { |
| 4282 |
cur_allele_permute[aidx] = kPglMaxAlleleCt - S_CAST(AlleleCode, sortbuf[allele_ct_m1 - aidx]); |
| 4283 |
} |
| 4284 |
if (nonref_flags && cur_allele_permute[0]) { |
| 4285 |
SetBit(variant_uidx, nonref_flags); |
| 4286 |
} |
| 4287 |
} |
| 4288 |
} |
| 4289 |
while (0) { |
| 4290 |
MajRef_ret_NOMEM: |
| 4291 |
reterr = kPglRetNomem; |
| 4292 |
break; |
| 4293 |
} |
| 4294 |
BigstackReset(bigstack_mark); |
| 4295 |
return reterr; |
| 4296 |
} |
| 4297 |
|
| 4298 |
#ifdef __cplusplus |
| 4299 |
} // namespace plink2 |
| 4300 |
#endif |