| 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" |
| 19 |
#include "plink2_compress_stream.h" |
| 20 |
#include "plink2_data.h" |
| 21 |
#include "plink2_misc.h" |
| 22 |
|
| 23 |
#ifdef __cplusplus |
| 24 |
namespace plink2 { |
| 25 |
#endif |
| 26 |
|
| 27 |
void InitUpdateAlleles(UpdateAllelesInfo* update_alleles_info_ptr) { |
| 28 |
update_alleles_info_ptr->flags = kfUpdateAlleles0; |
| 29 |
update_alleles_info_ptr->fname = nullptr; |
| 30 |
} |
| 31 |
|
| 32 |
void CleanupUpdateAlleles(UpdateAllelesInfo* update_alleles_info_ptr) { |
| 33 |
free_cond(update_alleles_info_ptr->fname); |
| 34 |
} |
| 35 |
|
| 36 |
void InitUpdateSex(UpdateSexInfo* update_sex_info_ptr) { |
| 37 |
update_sex_info_ptr->flags = kfUpdateSex0; |
| 38 |
update_sex_info_ptr->col_num = 0; |
| 39 |
update_sex_info_ptr->fname = nullptr; |
| 40 |
} |
| 41 |
|
| 42 |
void CleanupUpdateSex(UpdateSexInfo* update_sex_info_ptr) { |
| 43 |
free_cond(update_sex_info_ptr->fname); |
| 44 |
} |
| 45 |
|
| 46 |
void InitSdiff(SdiffInfo* sdiff_info_ptr) { |
| 47 |
sdiff_info_ptr->flags = kfSdiff0; |
| 48 |
sdiff_info_ptr->dosage_hap_tol = kDosageMissing; |
| 49 |
sdiff_info_ptr->fname_id_delim = '\0'; |
| 50 |
sdiff_info_ptr->other_id_ct = 0; |
| 51 |
sdiff_info_ptr->first_id_or_fname = nullptr; |
| 52 |
sdiff_info_ptr->other_ids_flattened = nullptr; |
| 53 |
} |
| 54 |
|
| 55 |
void CleanupSdiff(SdiffInfo* sdiff_info_ptr) { |
| 56 |
free_cond(sdiff_info_ptr->first_id_or_fname); |
| 57 |
free_cond(sdiff_info_ptr->other_ids_flattened); |
| 58 |
} |
| 59 |
|
| 60 |
void InitFst(FstInfo* fst_info_ptr) { |
| 61 |
fst_info_ptr->flags = kfFst0; |
| 62 |
fst_info_ptr->blocksize = 0; |
| 63 |
fst_info_ptr->pheno_name = nullptr; |
| 64 |
fst_info_ptr->first_id_or_fname = nullptr; |
| 65 |
fst_info_ptr->other_ids_flattened = nullptr; |
| 66 |
} |
| 67 |
|
| 68 |
void CleanupFst(FstInfo* fst_info_ptr) { |
| 69 |
free_cond(fst_info_ptr->pheno_name); |
| 70 |
free_cond(fst_info_ptr->first_id_or_fname); |
| 71 |
free_cond(fst_info_ptr->other_ids_flattened); |
| 72 |
} |
| 73 |
|
| 74 |
void InitCheckSex(CheckSexInfo* check_sex_info_ptr) { |
| 75 |
check_sex_info_ptr->flags = kfCheckSex0; |
| 76 |
check_sex_info_ptr->max_female_xf = -1.0; |
| 77 |
check_sex_info_ptr->min_male_xf = -1.0; |
| 78 |
check_sex_info_ptr->max_female_ycount = UINT32_MAX; |
| 79 |
check_sex_info_ptr->min_male_ycount = UINT32_MAX; |
| 80 |
check_sex_info_ptr->max_female_yrate = -1.0; |
| 81 |
check_sex_info_ptr->min_male_yrate = -1.0; |
| 82 |
} |
| 83 |
|
| 84 |
PglErr UpdateVarBps(const ChrInfo* cip, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const TwoColParams* params, uint32_t sort_vars_in_cmd, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uint32_t htable_size, uint32_t max_thread_ct, uintptr_t* variant_include, uint32_t* __restrict variant_bps, uint32_t* __restrict variant_ct_ptr, UnsortedVar* vpos_sortstatusp) { |
| 85 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 86 |
uintptr_t line_idx = 0; |
| 87 |
PglErr reterr = kPglRetSuccess; |
| 88 |
TextStream txs; |
| 89 |
PreinitTextStream(&txs); |
| 90 |
{ |
| 91 |
uintptr_t* already_seen; |
| 92 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) { |
| 93 |
goto UpdateVarBps_ret_NOMEM; |
| 94 |
} |
| 95 |
// This could be pointed at a file containing allele codes, so don't limit |
| 96 |
// line length to minimum value. |
| 97 |
reterr = SizeAndInitTextStream(params->fname, bigstack_left(), MAXV(max_thread_ct - 1, 1), &txs); |
| 98 |
if (unlikely(reterr)) { |
| 99 |
goto UpdateVarBps_ret_TSTREAM_FAIL; |
| 100 |
} |
| 101 |
reterr = TextSkip(params->skip_ct, &txs); |
| 102 |
if (unlikely(reterr)) { |
| 103 |
if (reterr == kPglRetEof) { |
| 104 |
snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", params->fname); |
| 105 |
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW; |
| 106 |
} |
| 107 |
goto UpdateVarBps_ret_TSTREAM_FAIL; |
| 108 |
} |
| 109 |
line_idx = params->skip_ct; |
| 110 |
const uint32_t colid_first = (params->colid < params->colx); |
| 111 |
uint32_t variant_ct = *variant_ct_ptr; |
| 112 |
uint32_t colmin; |
| 113 |
uint32_t coldiff; |
| 114 |
if (colid_first) { |
| 115 |
colmin = params->colid - 1; |
| 116 |
coldiff = params->colx - params->colid; |
| 117 |
} else { |
| 118 |
colmin = params->colx - 1; |
| 119 |
coldiff = params->colid - params->colx; |
| 120 |
} |
| 121 |
const char skipchar = params->skipchar; |
| 122 |
uintptr_t miss_ct = 0; |
| 123 |
uint32_t hit_ct = 0; |
| 124 |
while (1) { |
| 125 |
++line_idx; |
| 126 |
const char* line_start = TextGet(&txs); |
| 127 |
if (!line_start) { |
| 128 |
if (likely(!TextStreamErrcode2(&txs, &reterr))) { |
| 129 |
break; |
| 130 |
} |
| 131 |
goto UpdateVarBps_ret_TSTREAM_FAIL; |
| 132 |
} |
| 133 |
char cc = *line_start; |
| 134 |
if (cc == skipchar) { |
| 135 |
continue; |
| 136 |
} |
| 137 |
const char* colid_ptr; |
| 138 |
const char* colbp_ptr; |
| 139 |
if (colid_first) { |
| 140 |
colid_ptr = NextTokenMult0(line_start, colmin); |
| 141 |
colbp_ptr = NextTokenMult(colid_ptr, coldiff); |
| 142 |
if (unlikely(!colbp_ptr)) { |
| 143 |
goto UpdateVarBps_ret_MISSING_TOKENS; |
| 144 |
} |
| 145 |
} else { |
| 146 |
colbp_ptr = NextTokenMult0(line_start, colmin); |
| 147 |
colid_ptr = NextTokenMult(colbp_ptr, coldiff); |
| 148 |
if (unlikely(!colid_ptr)) { |
| 149 |
goto UpdateVarBps_ret_MISSING_TOKENS; |
| 150 |
} |
| 151 |
} |
| 152 |
const uint32_t varid_slen = strlen_se(colid_ptr); |
| 153 |
uint32_t cur_llidx; |
| 154 |
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); |
| 155 |
if (variant_uidx == UINT32_MAX) { |
| 156 |
++miss_ct; |
| 157 |
continue; |
| 158 |
} |
| 159 |
const char* cur_var_id = variant_ids[variant_uidx]; |
| 160 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 161 |
// we could check if some copies have been filtered out after hash |
| 162 |
// table construction? |
| 163 |
snprintf(g_logbuf, kLogbufSize, "Error: --update-map variant ID '%s' appears multiple times in dataset.\n", cur_var_id); |
| 164 |
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW; |
| 165 |
} |
| 166 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 167 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-map file.\n", cur_var_id); |
| 168 |
goto UpdateVarBps_ret_INCONSISTENT_INPUT_WW; |
| 169 |
} |
| 170 |
SetBit(variant_uidx, already_seen); |
| 171 |
if (!IsSet(variant_include, variant_uidx)) { |
| 172 |
continue; |
| 173 |
} |
| 174 |
int32_t bp_coord; |
| 175 |
if (ScanIntAbsDefcap(colbp_ptr, &bp_coord)) { |
| 176 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of --update-map file.\n", line_idx); |
| 177 |
goto UpdateVarBps_ret_MALFORMED_INPUT; |
| 178 |
} |
| 179 |
if (bp_coord < 0) { |
| 180 |
ClearBit(variant_uidx, variant_include); |
| 181 |
--variant_ct; |
| 182 |
} else { |
| 183 |
variant_bps[variant_uidx] = bp_coord; |
| 184 |
} |
| 185 |
++hit_ct; |
| 186 |
} |
| 187 |
if (miss_ct) { |
| 188 |
snprintf(g_logbuf, kLogbufSize, "--update-map: %u value%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 189 |
} else { |
| 190 |
snprintf(g_logbuf, kLogbufSize, "--update-map: %u value%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 191 |
} |
| 192 |
logputsb(); |
| 193 |
|
| 194 |
UnsortedVar vpos_sortstatus = (*vpos_sortstatusp) & (~kfUnsortedVarBp); |
| 195 |
if (!(vpos_sortstatus & kfUnsortedVarSplitChr)) { |
| 196 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 197 |
uint32_t chr_end = 0; |
| 198 |
uint32_t last_bp = 0; |
| 199 |
uintptr_t variant_uidx_base = 0; |
| 200 |
uintptr_t cur_bits = variant_include[0]; |
| 201 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 202 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 203 |
if (variant_uidx >= chr_end) { |
| 204 |
do { |
| 205 |
++chr_fo_idx; |
| 206 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 207 |
} while (variant_uidx >= chr_end); |
| 208 |
last_bp = 0; |
| 209 |
} |
| 210 |
const uint32_t cur_bp = variant_bps[variant_uidx]; |
| 211 |
if (last_bp > cur_bp) { |
| 212 |
vpos_sortstatus |= kfUnsortedVarBp; |
| 213 |
if (!((*vpos_sortstatusp) & kfUnsortedVarBp)) { |
| 214 |
if (sort_vars_in_cmd) { |
| 215 |
logerrputs("Note: Base-pair positions are now unsorted.\n"); |
| 216 |
} else { |
| 217 |
logerrputs("Warning: Base-pair positions are now unsorted!\n"); |
| 218 |
} |
| 219 |
} |
| 220 |
break; |
| 221 |
} |
| 222 |
last_bp = cur_bp; |
| 223 |
} |
| 224 |
if (((*vpos_sortstatusp) & kfUnsortedVarBp) && (!(vpos_sortstatus & kfUnsortedVarBp))) { |
| 225 |
logputs("Base-pair positions are now sorted.\n"); |
| 226 |
} |
| 227 |
*vpos_sortstatusp = vpos_sortstatus; |
| 228 |
} |
| 229 |
} |
| 230 |
while (0) { |
| 231 |
UpdateVarBps_ret_NOMEM: |
| 232 |
reterr = kPglRetNomem; |
| 233 |
break; |
| 234 |
UpdateVarBps_ret_TSTREAM_FAIL: |
| 235 |
TextStreamErrPrint("--update-map file", &txs); |
| 236 |
break; |
| 237 |
UpdateVarBps_ret_MISSING_TOKENS: |
| 238 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-map file has fewer tokens than expected.\n", line_idx); |
| 239 |
UpdateVarBps_ret_INCONSISTENT_INPUT_WW: |
| 240 |
WordWrapB(0); |
| 241 |
logerrputsb(); |
| 242 |
reterr = kPglRetInconsistentInput; |
| 243 |
break; |
| 244 |
UpdateVarBps_ret_MALFORMED_INPUT: |
| 245 |
reterr = kPglRetMalformedInput; |
| 246 |
break; |
| 247 |
} |
| 248 |
CleanupTextStream2("--update-map file", &txs, &reterr); |
| 249 |
BigstackReset(bigstack_mark); |
| 250 |
return reterr; |
| 251 |
} |
| 252 |
|
| 253 |
PglErr UpdateVarNames(const uintptr_t* variant_include, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const TwoColParams* params, uint32_t raw_variant_ct, uint32_t htable_size, uint32_t max_thread_ct, char** variant_ids, uint32_t* max_variant_id_slen_ptr) { |
| 254 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 255 |
uintptr_t line_idx = 0; |
| 256 |
PglErr reterr = kPglRetSuccess; |
| 257 |
TextStream txs; |
| 258 |
PreinitTextStream(&txs); |
| 259 |
{ |
| 260 |
const uint32_t orig_max_variant_id_slen = *max_variant_id_slen_ptr; |
| 261 |
uint32_t max_variant_id_slen = orig_max_variant_id_slen; |
| 262 |
char** variant_ids_copy; |
| 263 |
uintptr_t* already_seen; |
| 264 |
if (unlikely(bigstack_alloc_cp(raw_variant_ct, &variant_ids_copy) || |
| 265 |
bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &already_seen))) { |
| 266 |
goto UpdateVarNames_ret_NOMEM; |
| 267 |
} |
| 268 |
memcpy(variant_ids_copy, variant_ids, raw_variant_ct * sizeof(intptr_t)); |
| 269 |
// This could be pointed at a file containing allele codes, so don't limit |
| 270 |
// line length to minimum value. |
| 271 |
// On the other hand, new variant IDs are allocated off the end of |
| 272 |
// bigstack, and that could result in a lot of memory pressure. |
| 273 |
reterr = SizeAndInitTextStream(params->fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs); |
| 274 |
if (unlikely(reterr)) { |
| 275 |
goto UpdateVarNames_ret_TSTREAM_FAIL; |
| 276 |
} |
| 277 |
reterr = TextSkip(params->skip_ct, &txs); |
| 278 |
if (unlikely(reterr)) { |
| 279 |
if (reterr == kPglRetEof) { |
| 280 |
snprintf(g_logbuf, kLogbufSize, "Error: Fewer lines than expected in %s.\n", params->fname); |
| 281 |
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW; |
| 282 |
} |
| 283 |
goto UpdateVarNames_ret_TSTREAM_FAIL; |
| 284 |
} |
| 285 |
line_idx = params->skip_ct; |
| 286 |
const uint32_t colold_first = (params->colid < params->colx); |
| 287 |
uint32_t colmin; |
| 288 |
uint32_t coldiff; |
| 289 |
if (colold_first) { |
| 290 |
colmin = params->colid - 1; |
| 291 |
coldiff = params->colx - params->colid; |
| 292 |
} else { |
| 293 |
colmin = params->colx - 1; |
| 294 |
coldiff = params->colid - params->colx; |
| 295 |
} |
| 296 |
const char skipchar = params->skipchar; |
| 297 |
char* alloc_base = R_CAST(char*, g_bigstack_base); |
| 298 |
char* alloc_end = R_CAST(char*, g_bigstack_end); |
| 299 |
uintptr_t miss_ct = 0; |
| 300 |
uint32_t hit_ct = 0; |
| 301 |
while (1) { |
| 302 |
++line_idx; |
| 303 |
const char* line_start = TextGet(&txs); |
| 304 |
if (!line_start) { |
| 305 |
// bugfix (7 Jun 2023): this condition was flipped |
| 306 |
if (likely(!TextStreamErrcode2(&txs, &reterr))) { |
| 307 |
break; |
| 308 |
} |
| 309 |
goto UpdateVarNames_ret_TSTREAM_FAIL; |
| 310 |
} |
| 311 |
char cc = *line_start; |
| 312 |
if (cc == skipchar) { |
| 313 |
continue; |
| 314 |
} |
| 315 |
const char* colold_ptr; |
| 316 |
const char* colnew_ptr; |
| 317 |
if (colold_first) { |
| 318 |
colold_ptr = NextTokenMult0(line_start, colmin); |
| 319 |
colnew_ptr = NextTokenMult(colold_ptr, coldiff); |
| 320 |
if (unlikely(!colnew_ptr)) { |
| 321 |
goto UpdateVarNames_ret_MISSING_TOKENS; |
| 322 |
} |
| 323 |
} else { |
| 324 |
colnew_ptr = NextTokenMult0(line_start, colmin); |
| 325 |
colold_ptr = NextTokenMult(colnew_ptr, coldiff); |
| 326 |
if (unlikely(!colold_ptr)) { |
| 327 |
goto UpdateVarNames_ret_MISSING_TOKENS; |
| 328 |
} |
| 329 |
} |
| 330 |
const uint32_t colold_slen = strlen_se(colold_ptr); |
| 331 |
uint32_t cur_llidx; |
| 332 |
uint32_t variant_uidx = VariantIdDupHtableFind(colold_ptr, TO_CONSTCPCONSTP(variant_ids_copy), variant_id_htable, htable_dup_base, colold_slen, htable_size, orig_max_variant_id_slen, &cur_llidx); |
| 333 |
if (variant_uidx == UINT32_MAX) { |
| 334 |
++miss_ct; |
| 335 |
continue; |
| 336 |
} |
| 337 |
const char* cur_var_id = variant_ids_copy[variant_uidx]; |
| 338 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 339 |
// we could check if some copies have been filtered out after hash |
| 340 |
// table construction? |
| 341 |
snprintf(g_logbuf, kLogbufSize, "Error: --update-name variant ID '%s' appears multiple times in dataset.\n", cur_var_id); |
| 342 |
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW; |
| 343 |
} |
| 344 |
if (!IsSet(variant_include, variant_uidx)) { |
| 345 |
continue; |
| 346 |
} |
| 347 |
if (unlikely(IsSet(already_seen, variant_uidx))) { |
| 348 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-name file.\n", cur_var_id); |
| 349 |
goto UpdateVarNames_ret_INCONSISTENT_INPUT_WW; |
| 350 |
} |
| 351 |
SetBit(variant_uidx, already_seen); |
| 352 |
++hit_ct; |
| 353 |
const uint32_t colnew_slen = strlen_se(colnew_ptr); |
| 354 |
if (colnew_slen <= colold_slen) { |
| 355 |
const uint32_t colold_blen = colold_slen + 1; |
| 356 |
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < colold_blen)) { |
| 357 |
goto UpdateVarNames_ret_NOMEM; |
| 358 |
} |
| 359 |
memcpy(alloc_base, cur_var_id, colold_blen); |
| 360 |
variant_ids_copy[variant_uidx] = alloc_base; |
| 361 |
alloc_base = &(alloc_base[colold_blen]); |
| 362 |
memcpyx(variant_ids[variant_uidx], colnew_ptr, colnew_slen, '\0'); |
| 363 |
} else { |
| 364 |
if (colnew_slen > max_variant_id_slen) { |
| 365 |
max_variant_id_slen = colnew_slen; |
| 366 |
} |
| 367 |
const uint32_t colnew_blen = colnew_slen + 1; |
| 368 |
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < colnew_blen)) { |
| 369 |
goto UpdateVarNames_ret_NOMEM; |
| 370 |
} |
| 371 |
alloc_end -= colnew_blen; |
| 372 |
memcpyx(alloc_end, colnew_ptr, colnew_slen, '\0'); |
| 373 |
variant_ids[variant_uidx] = alloc_end; |
| 374 |
} |
| 375 |
} |
| 376 |
BigstackEndSet(alloc_end); |
| 377 |
if (miss_ct) { |
| 378 |
snprintf(g_logbuf, kLogbufSize, "--update-name: %u value%s updated, %" PRIuPTR " variant ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 379 |
} else { |
| 380 |
snprintf(g_logbuf, kLogbufSize, "--update-name: %u value%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 381 |
} |
| 382 |
logputsb(); |
| 383 |
*max_variant_id_slen_ptr = max_variant_id_slen; |
| 384 |
} |
| 385 |
while (0) { |
| 386 |
UpdateVarNames_ret_NOMEM: |
| 387 |
reterr = kPglRetNomem; |
| 388 |
break; |
| 389 |
UpdateVarNames_ret_TSTREAM_FAIL: |
| 390 |
TextStreamErrPrint("--update-name file", &txs); |
| 391 |
break; |
| 392 |
UpdateVarNames_ret_MISSING_TOKENS: |
| 393 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-name file has fewer tokens than expected.\n", line_idx); |
| 394 |
UpdateVarNames_ret_INCONSISTENT_INPUT_WW: |
| 395 |
WordWrapB(0); |
| 396 |
logerrputsb(); |
| 397 |
reterr = kPglRetInconsistentInput; |
| 398 |
break; |
| 399 |
} |
| 400 |
CleanupTextStream2("--update-name file", &txs, &reterr); |
| 401 |
BigstackReset(bigstack_mark); |
| 402 |
return reterr; |
| 403 |
} |
| 404 |
|
| 405 |
static_assert(kPglMaxAlleleCt <= 65535, "UpdateVarAlleles() must be updated."); |
| 406 |
PglErr UpdateVarAlleles(const uintptr_t* variant_include, const char* const* variant_ids, const uint32_t* variant_id_htable, const uint32_t* htable_dup_base, const uintptr_t* allele_idx_offsets, const UpdateAllelesInfo* update_alleles_info_ptr, uint32_t raw_variant_ct, uint32_t max_variant_id_slen, uint32_t htable_size, uint32_t max_allele_ct, char input_missing_geno_char, uint32_t max_thread_ct, char** allele_storage_mutable, uint32_t* max_allele_slen_ptr, char* outname, char* outname_end) { |
| 407 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 408 |
// Set this to 65536 even though kPglMaxAlleleCt is only 255 as of this |
| 409 |
// writing, since VCF variants with >255 alleles are out there and we don't |
| 410 |
// want to crash when partial-match is a possibility. |
| 411 |
const uint32_t max_impl_input_allele_ct = 65536; |
| 412 |
uintptr_t line_idx = 0; |
| 413 |
FILE* errfile = nullptr; |
| 414 |
PglErr reterr = kPglRetSuccess; |
| 415 |
TextStream txs; |
| 416 |
PreinitTextStream(&txs); |
| 417 |
{ |
| 418 |
const uint32_t max_allele_ctl = BitCtToWordCt(max_allele_ct); |
| 419 |
char** input_allele_starts; |
| 420 |
uint32_t* input_allele_slens; |
| 421 |
const char** orig_alleles_sorted; |
| 422 |
uint32_t* sorted_to_orig_idx; |
| 423 |
uint16_t* orig_to_input_idx; |
| 424 |
uintptr_t* alleles_seen; |
| 425 |
uintptr_t* variants_seen; |
| 426 |
unsigned char* sort_wkspace; |
| 427 |
if (unlikely(bigstack_alloc_cp(max_impl_input_allele_ct, &input_allele_starts) || |
| 428 |
bigstack_alloc_u32(max_impl_input_allele_ct, &input_allele_slens) || |
| 429 |
bigstack_alloc_kcp(max_allele_ct, &orig_alleles_sorted) || |
| 430 |
bigstack_alloc_u32(max_allele_ct, &sorted_to_orig_idx) || |
| 431 |
bigstack_alloc_u16(max_allele_ct, &orig_to_input_idx) || |
| 432 |
bigstack_alloc_w(max_allele_ctl, &alleles_seen) || |
| 433 |
bigstack_calloc_w(BitCtToWordCt(raw_variant_ct), &variants_seen) || |
| 434 |
bigstack_alloc_uc(max_allele_ct * sizeof(StrSortIndexedDeref), &sort_wkspace))) { |
| 435 |
goto UpdateVarAlleles_ret_NOMEM; |
| 436 |
} |
| 437 |
reterr = SizeAndInitTextStream(update_alleles_info_ptr->fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs); |
| 438 |
if (unlikely(reterr)) { |
| 439 |
goto UpdateVarAlleles_ret_TSTREAM_FAIL; |
| 440 |
} |
| 441 |
const uint32_t allow_mismatch = (update_alleles_info_ptr->flags / kfUpdateAllelesAllowMismatch) & 1; |
| 442 |
const uint32_t strict_missing = (update_alleles_info_ptr->flags / kfUpdateAllelesStrictMissing) & 1; |
| 443 |
const char* std_input_missing_geno = &(g_one_char_strs[92]); |
| 444 |
unsigned char* tmp_alloc_base = g_bigstack_base; |
| 445 |
unsigned char* tmp_alloc_end = g_bigstack_end; |
| 446 |
uintptr_t miss_ct = 0; |
| 447 |
uintptr_t err_ct = 0; |
| 448 |
uint32_t hit_ct = 0; |
| 449 |
uint32_t is_3col = 2; // 0 = orig format, 1 = 3col, 2 = not determined yet |
| 450 |
uint32_t max_allele_slen = *max_allele_slen_ptr; |
| 451 |
uint32_t cur_input_allele_ct = 2; |
| 452 |
uint32_t cur_allele_ct = 2; |
| 453 |
char* line_iter = TextLineEnd(&txs); |
| 454 |
++line_idx; |
| 455 |
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 456 |
char* varid_start = line_iter; |
| 457 |
char* varid_end = CurTokenEnd(varid_start); |
| 458 |
uint32_t cur_llidx; |
| 459 |
uint32_t variant_uidx = VariantIdDupHtableFind(varid_start, variant_ids, variant_id_htable, htable_dup_base, varid_end - varid_start, htable_size, max_variant_id_slen, &cur_llidx); |
| 460 |
if (variant_uidx == UINT32_MAX) { |
| 461 |
line_iter = varid_end; |
| 462 |
++miss_ct; |
| 463 |
continue; |
| 464 |
} |
| 465 |
const char* varid = variant_ids[variant_uidx]; |
| 466 |
if (unlikely(cur_llidx != UINT32_MAX)) { |
| 467 |
snprintf(g_logbuf, kLogbufSize, "Error: --update-alleles variant ID '%s' appears multiple times in dataset.\n", varid); |
| 468 |
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW; |
| 469 |
} |
| 470 |
if (unlikely(IsSet(variants_seen, variant_uidx))) { |
| 471 |
snprintf(g_logbuf, kLogbufSize, "Error: Variant ID '%s' appears multiple times in --update-alleles file.\n", varid); |
| 472 |
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW; |
| 473 |
} |
| 474 |
SetBit(variant_uidx, variants_seen); |
| 475 |
if (!IsSet(variant_include, variant_uidx)) { |
| 476 |
line_iter = varid_end; |
| 477 |
++miss_ct; |
| 478 |
continue; |
| 479 |
} |
| 480 |
|
| 481 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 482 |
if (allele_idx_offsets) { |
| 483 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 484 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 485 |
} |
| 486 |
char** orig_alleles = &(allele_storage_mutable[allele_idx_offset_base]); |
| 487 |
|
| 488 |
char* col2_start = FirstNonTspace(varid_end); |
| 489 |
char* col2_end = FirstSpaceOrEoln(col2_start); |
| 490 |
char* col3_start = FirstNonTspace(col2_end); |
| 491 |
if (unlikely(IsEolnKns(*col3_start))) { |
| 492 |
goto UpdateVarAlleles_ret_MISSING_TOKENS; |
| 493 |
} |
| 494 |
char* col3_end = FirstSpaceOrEoln(col3_start); |
| 495 |
if (is_3col == 2) { |
| 496 |
is_3col = (NextToken(col3_end) == nullptr); |
| 497 |
} |
| 498 |
char* new_alleles_start = col3_start; |
| 499 |
if (is_3col) { |
| 500 |
cur_input_allele_ct = 0; |
| 501 |
for (char* col2_iter = col2_start; ; ) { |
| 502 |
char* input_allele_end = AdvToDelimOrEnd(col2_iter, col2_end, ','); |
| 503 |
input_allele_starts[cur_input_allele_ct] = col2_iter; |
| 504 |
input_allele_slens[cur_input_allele_ct] = input_allele_end - col2_iter; |
| 505 |
++cur_input_allele_ct; |
| 506 |
// Null-terminate to set up bsearch_strptr_overread(). |
| 507 |
*input_allele_end = '\0'; |
| 508 |
if (input_allele_end == col2_end) { |
| 509 |
break; |
| 510 |
} |
| 511 |
if (unlikely(cur_input_allele_ct == max_impl_input_allele_ct)) { |
| 512 |
goto UpdateVarAlleles_ret_TOO_MANY_ALLELES; |
| 513 |
} |
| 514 |
col2_iter = &(input_allele_end[1]); |
| 515 |
} |
| 516 |
if ((cur_input_allele_ct > cur_allele_ct) && (!allow_mismatch)) { |
| 517 |
UpdateVarAlleles_errfile: |
| 518 |
if (!err_ct) { |
| 519 |
strcpy_k(outname_end, ".allele.no.snp"); |
| 520 |
if (fopen_checked(outname, FOPEN_WB, &errfile)) { |
| 521 |
goto UpdateVarAlleles_ret_OPEN_FAIL; |
| 522 |
} |
| 523 |
} |
| 524 |
// variant ID, expected allele 1, remaining comma-separated expected |
| 525 |
// alleles |
| 526 |
// not optimized for now, could explicitly manage a write buffer if |
| 527 |
// it ever matters |
| 528 |
fputs(varid, errfile); |
| 529 |
putc_unlocked('\t', errfile); |
| 530 |
fwrite(input_allele_starts[0], input_allele_slens[0], 1, errfile); |
| 531 |
putc_unlocked('\t', errfile); |
| 532 |
if (cur_input_allele_ct == 1) { |
| 533 |
putc_unlocked('.', errfile); |
| 534 |
} else { |
| 535 |
for (uint32_t aidx = 1; ; ) { |
| 536 |
fwrite(input_allele_starts[aidx], input_allele_slens[aidx], 1, errfile); |
| 537 |
++aidx; |
| 538 |
if (aidx == cur_input_allele_ct) { |
| 539 |
break; |
| 540 |
} |
| 541 |
putc_unlocked(',', errfile); |
| 542 |
} |
| 543 |
} |
| 544 |
#ifdef _WIN32 |
| 545 |
putc_unlocked('\r', errfile); |
| 546 |
#endif |
| 547 |
if (unlikely(putc_checked('\n', errfile))) { |
| 548 |
goto UpdateVarAlleles_ret_WRITE_FAIL; |
| 549 |
} |
| 550 |
++err_ct; |
| 551 |
continue; |
| 552 |
} |
| 553 |
} else { |
| 554 |
// cur_input_allele_ct == 2 |
| 555 |
new_alleles_start = FirstNonTspace(col3_end); |
| 556 |
input_allele_starts[0] = col2_start; |
| 557 |
input_allele_starts[1] = col3_start; |
| 558 |
input_allele_slens[0] = col2_end - col2_start; |
| 559 |
input_allele_slens[1] = col3_end - col3_start; |
| 560 |
*col2_end = '\0'; |
| 561 |
*col3_end = '\0'; |
| 562 |
} |
| 563 |
uint32_t wildcard_idx = UINT32_MAX; |
| 564 |
// safe to assume preexisting allele codes are distinct since |
| 565 |
// CheckAlleleUniqueness() was run. |
| 566 |
if (cur_allele_ct == 2) { |
| 567 |
if (strcmp_overread_lt(orig_alleles[0], orig_alleles[1])) { |
| 568 |
sorted_to_orig_idx[0] = 0; |
| 569 |
sorted_to_orig_idx[1] = 1; |
| 570 |
} else { |
| 571 |
sorted_to_orig_idx[0] = 1; |
| 572 |
sorted_to_orig_idx[1] = 0; |
| 573 |
} |
| 574 |
orig_alleles_sorted[0] = orig_alleles[sorted_to_orig_idx[0]]; |
| 575 |
orig_alleles_sorted[1] = orig_alleles[sorted_to_orig_idx[1]]; |
| 576 |
if (!strict_missing) { |
| 577 |
for (uint32_t uii = 0; uii != 2; ++uii) { |
| 578 |
if (memequal(orig_alleles_sorted[uii], std_input_missing_geno, 2)) { |
| 579 |
wildcard_idx = sorted_to_orig_idx[uii]; |
| 580 |
break; |
| 581 |
} |
| 582 |
} |
| 583 |
} |
| 584 |
} else { |
| 585 |
memcpy(orig_alleles_sorted, orig_alleles, cur_allele_ct * sizeof(intptr_t)); |
| 586 |
SortStrptrArrIndexed2(cur_allele_ct, 0, 1, 0, orig_alleles_sorted, sorted_to_orig_idx, nullptr, sort_wkspace); |
| 587 |
} |
| 588 |
ZeroWArr(max_allele_ctl, alleles_seen); |
| 589 |
for (uint32_t old_idx = 0; old_idx != cur_input_allele_ct; ++old_idx) { |
| 590 |
const char* old_allele = input_allele_starts[old_idx]; |
| 591 |
uint32_t old_slen = input_allele_slens[old_idx]; |
| 592 |
// standardize missing allele codes |
| 593 |
if ((old_slen == 1) && (old_allele[0] == input_missing_geno_char)) { |
| 594 |
old_allele = std_input_missing_geno; |
| 595 |
} |
| 596 |
const int32_t sorted_orig_idx = bsearch_strptr_overread(old_allele, orig_alleles_sorted, cur_allele_ct); |
| 597 |
if (sorted_orig_idx != -1) { |
| 598 |
const uint32_t orig_idx = sorted_to_orig_idx[sorted_orig_idx]; |
| 599 |
if (IsSet(alleles_seen, orig_idx)) { |
| 600 |
goto UpdateVarAlleles_ret_DUPLICATE_INPUT_ALLELE_CODE; |
| 601 |
} |
| 602 |
SetBit(orig_idx, alleles_seen); |
| 603 |
orig_to_input_idx[orig_idx] = old_idx; |
| 604 |
} |
| 605 |
} |
| 606 |
if ((wildcard_idx != UINT32_MAX) && (alleles_seen[0] == 2 - wildcard_idx) && (cur_input_allele_ct == 2)) { |
| 607 |
// Biallelic variant with one missing allele code, only non-missing |
| 608 |
// allele has been matched, exactly two input alleles. |
| 609 |
// Match the other old input allele with the original missing allele. |
| 610 |
alleles_seen[0] = 3; |
| 611 |
orig_to_input_idx[wildcard_idx] = 1 - orig_to_input_idx[1 - wildcard_idx]; |
| 612 |
} |
| 613 |
const uint32_t seen_ct = PopcountWords(alleles_seen, max_allele_ctl); |
| 614 |
if ((!seen_ct) || ((!allow_mismatch) && (seen_ct < cur_input_allele_ct))) { |
| 615 |
goto UpdateVarAlleles_errfile; |
| 616 |
} |
| 617 |
|
| 618 |
if (is_3col) { |
| 619 |
uint32_t new_input_allele_idx = 0; |
| 620 |
for (char* col3_iter = col3_start; ; ) { |
| 621 |
char* input_allele_end = AdvToDelimOrEnd(col3_iter, col3_end, ','); |
| 622 |
input_allele_starts[new_input_allele_idx] = col3_iter; |
| 623 |
input_allele_slens[new_input_allele_idx] = input_allele_end - col3_iter; |
| 624 |
// No need to null-terminate this time. (And if we did, we'd need to |
| 625 |
// handle the case where *col3_end was '\n'.) |
| 626 |
++new_input_allele_idx; |
| 627 |
if (input_allele_end == col3_end) { |
| 628 |
if (unlikely(new_input_allele_idx != cur_input_allele_ct)) { |
| 629 |
snprintf(g_logbuf, kLogbufSize, "Error: Too few new alleles on line %" PRIuPTR " of --update-alleles file.\n", line_idx); |
| 630 |
goto UpdateVarAlleles_ret_MALFORMED_INPUT_WW; |
| 631 |
} |
| 632 |
break; |
| 633 |
} |
| 634 |
if (unlikely(new_input_allele_idx == cur_input_allele_ct)) { |
| 635 |
snprintf(g_logbuf, kLogbufSize, "Error: Too many new alleles on line %" PRIuPTR " of --update-alleles file.\n", line_idx); |
| 636 |
goto UpdateVarAlleles_ret_MALFORMED_INPUT_WW; |
| 637 |
} |
| 638 |
col3_iter = &(input_allele_end[1]); |
| 639 |
} |
| 640 |
} else { |
| 641 |
char* col4_end = FirstSpaceOrEoln(new_alleles_start); |
| 642 |
char* col5_start = FirstNonTspace(col4_end); |
| 643 |
if (unlikely(IsEolnKns(*col5_start))) { |
| 644 |
goto UpdateVarAlleles_ret_MISSING_TOKENS; |
| 645 |
} |
| 646 |
char* col5_end = FirstSpaceOrEoln(col5_start); |
| 647 |
input_allele_starts[0] = new_alleles_start; |
| 648 |
input_allele_starts[1] = col5_start; |
| 649 |
input_allele_slens[0] = col4_end - new_alleles_start; |
| 650 |
input_allele_slens[1] = col5_end - col5_start; |
| 651 |
} |
| 652 |
|
| 653 |
uintptr_t aidx_base = 0; |
| 654 |
uintptr_t cur_bits = alleles_seen[0]; |
| 655 |
for (uint32_t seen_idx = 0; seen_idx != seen_ct; ++seen_idx) { |
| 656 |
const uint32_t aidx = BitIter1(alleles_seen, &aidx_base, &cur_bits); |
| 657 |
const uint32_t new_idx = orig_to_input_idx[aidx]; |
| 658 |
const char* new_allele_start = input_allele_starts[new_idx]; |
| 659 |
const uint32_t new_slen = input_allele_slens[new_idx]; |
| 660 |
if (new_slen == 1) { |
| 661 |
char cc = new_allele_start[0]; |
| 662 |
if (cc == input_missing_geno_char) { |
| 663 |
cc = '.'; |
| 664 |
} |
| 665 |
orig_alleles[aidx] = K_CAST(char*, &(g_one_char_strs[ctou32(cc) * 2])); |
| 666 |
} else { |
| 667 |
// reuse old storage if we can, allocate when we must |
| 668 |
if (strlen(orig_alleles[aidx]) < new_slen) { |
| 669 |
if (PtrWSubCk(tmp_alloc_base, new_slen + 1, &tmp_alloc_end)) { |
| 670 |
goto UpdateVarAlleles_ret_NOMEM; |
| 671 |
} |
| 672 |
orig_alleles[aidx] = R_CAST(char*, tmp_alloc_end); |
| 673 |
} |
| 674 |
memcpyx(orig_alleles[aidx], new_allele_start, new_slen, '\0'); |
| 675 |
} |
| 676 |
} |
| 677 |
|
| 678 |
// Confirm there are no duplicate allele codes after the change. |
| 679 |
if (cur_allele_ct == 2) { |
| 680 |
if (unlikely(strequal_overread(orig_alleles[0], orig_alleles[1]))) { |
| 681 |
goto UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE; |
| 682 |
} |
| 683 |
} else { |
| 684 |
memcpy(orig_alleles_sorted, orig_alleles, cur_allele_ct * sizeof(intptr_t)); |
| 685 |
SortStrptrArrIndexed2(cur_allele_ct, 0, 1, 0, orig_alleles_sorted, sorted_to_orig_idx, nullptr, sort_wkspace); |
| 686 |
const char* prev_allele = orig_alleles_sorted[0]; |
| 687 |
for (uint32_t aidx = 1; aidx != cur_allele_ct; ++aidx) { |
| 688 |
const char* cur_allele = orig_alleles_sorted[aidx]; |
| 689 |
if (unlikely(strequal_overread(prev_allele, cur_allele))) { |
| 690 |
goto UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE; |
| 691 |
} |
| 692 |
prev_allele = cur_allele; |
| 693 |
} |
| 694 |
// For multiallelic variants, also confirm missing allele code is not |
| 695 |
// present. |
| 696 |
if (unlikely(bsearch_strptr_overread(std_input_missing_geno, orig_alleles_sorted, cur_allele_ct) != -1)) { |
| 697 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-alleles file results in a missing allele code in a multiallelic variant.\n", line_idx); |
| 698 |
goto UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW; |
| 699 |
} |
| 700 |
} |
| 701 |
++hit_ct; |
| 702 |
} |
| 703 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 704 |
goto UpdateVarAlleles_ret_TSTREAM_FAIL; |
| 705 |
} |
| 706 |
*max_allele_slen_ptr = max_allele_slen; |
| 707 |
if (miss_ct) { |
| 708 |
snprintf(g_logbuf, kLogbufSize, "--update-alleles: %u variant%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 709 |
} else { |
| 710 |
snprintf(g_logbuf, kLogbufSize, "--update-alleles: %u variant%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 711 |
} |
| 712 |
logputsb(); |
| 713 |
if (err_ct) { |
| 714 |
logprintfww("%" PRIuPTR " update failure%s logged to %s .\n", err_ct, (err_ct == 1)? "" : "s", outname); |
| 715 |
} |
| 716 |
BigstackEndSet(tmp_alloc_end); |
| 717 |
} |
| 718 |
while (0) { |
| 719 |
UpdateVarAlleles_ret_NOMEM: |
| 720 |
reterr = kPglRetNomem; |
| 721 |
break; |
| 722 |
UpdateVarAlleles_ret_OPEN_FAIL: |
| 723 |
reterr = kPglRetOpenFail; |
| 724 |
break; |
| 725 |
UpdateVarAlleles_ret_WRITE_FAIL: |
| 726 |
reterr = kPglRetWriteFail; |
| 727 |
break; |
| 728 |
UpdateVarAlleles_ret_TSTREAM_FAIL: |
| 729 |
TextStreamErrPrint("--update-alleles file", &txs); |
| 730 |
break; |
| 731 |
UpdateVarAlleles_ret_MISSING_TOKENS: |
| 732 |
logerrprintfww("Error: Line %" PRIuPTR " of --update-alleles file has fewer tokens than expected.\n", line_idx); |
| 733 |
reterr = kPglRetMalformedInput; |
| 734 |
break; |
| 735 |
UpdateVarAlleles_ret_TOO_MANY_ALLELES: |
| 736 |
logerrprintfww("Error: Line %" PRIuPTR " of --update-alleles file has too many alleles (this " PROG_NAME_STR " build is limited to %u).\n", line_idx, max_impl_input_allele_ct); |
| 737 |
reterr = kPglRetNotYetSupported; |
| 738 |
break; |
| 739 |
UpdateVarAlleles_ret_DUPLICATE_ALLELE_CODE_AFTER_UPDATE: |
| 740 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-alleles file results in a duplicated allele code.\n", line_idx); |
| 741 |
UpdateVarAlleles_ret_INCONSISTENT_INPUT_WW: |
| 742 |
WordWrapB(0); |
| 743 |
logerrputsb(); |
| 744 |
reterr = kPglRetInconsistentInput; |
| 745 |
break; |
| 746 |
UpdateVarAlleles_ret_DUPLICATE_INPUT_ALLELE_CODE: |
| 747 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate allele code on line %" PRIuPTR " of --update-alleles file.\n", line_idx); |
| 748 |
UpdateVarAlleles_ret_MALFORMED_INPUT_WW: |
| 749 |
WordWrapB(0); |
| 750 |
logerrputsb(); |
| 751 |
reterr = kPglRetMalformedInput; |
| 752 |
break; |
| 753 |
} |
| 754 |
fclose_cond(errfile); |
| 755 |
CleanupTextStream2("--update-alleles file", &txs, &reterr); |
| 756 |
BigstackReset(bigstack_mark); |
| 757 |
return reterr; |
| 758 |
} |
| 759 |
|
| 760 |
PglErr RecoverVarIds(const char* fname, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const char* missing_varid, uint32_t raw_variant_ct, uint32_t variant_ct, RecoverVarIdsFlags flags, uint32_t max_thread_ct, char** variant_ids, uint32_t* max_variant_id_slen_ptr, char* outname, char* outname_end) { |
| 761 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 762 |
char* alloc_end = R_CAST(char*, g_bigstack_end); |
| 763 |
uintptr_t line_idx = 0; |
| 764 |
FILE* errfile = nullptr; |
| 765 |
PglErr reterr = kPglRetSuccess; |
| 766 |
TextStream txs; |
| 767 |
PreinitTextStream(&txs); |
| 768 |
{ |
| 769 |
// Significant overlap with UpdateVarNames(). |
| 770 |
const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct; |
| 771 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 772 |
char** variant_ids_copy; |
| 773 |
uintptr_t* chr_already_seen; |
| 774 |
uintptr_t* already_seen; |
| 775 |
uintptr_t* conflict_bitarr; |
| 776 |
char** orig_alt_starts = nullptr; // spurious g++ 4.8 warning |
| 777 |
if (unlikely(bigstack_alloc_cp(raw_variant_ct, &variant_ids_copy) || |
| 778 |
bigstack_calloc_w(BitCtToWordCt(chr_code_end), &chr_already_seen) || |
| 779 |
bigstack_calloc_w(raw_variant_ctl, &already_seen) || |
| 780 |
bigstack_calloc_w(raw_variant_ctl, &conflict_bitarr) || |
| 781 |
bigstack_alloc_cp(kPglMaxAltAlleleCt, &orig_alt_starts))) { |
| 782 |
goto RecoverVarIds_ret_NOMEM; |
| 783 |
} |
| 784 |
// need this to be able to write original variant IDs in conflict case |
| 785 |
memcpy(variant_ids_copy, variant_ids, raw_variant_ct * sizeof(intptr_t)); |
| 786 |
|
| 787 |
reterr = SizeAndInitTextStream(fname, bigstack_left() / 4, MAXV(max_thread_ct - 1, 1), &txs); |
| 788 |
if (unlikely(reterr)) { |
| 789 |
goto RecoverVarIds_ret_TSTREAM_FAIL; |
| 790 |
} |
| 791 |
char* line_start; |
| 792 |
do { |
| 793 |
++line_idx; |
| 794 |
line_start = TextGet(&txs); |
| 795 |
if (unlikely(!line_start)) { |
| 796 |
if (!TextStreamErrcode2(&txs, &reterr)) { |
| 797 |
logerrputs("Error: Empty --recover-var-ids file.\n"); |
| 798 |
goto RecoverVarIds_ret_MALFORMED_INPUT; |
| 799 |
} |
| 800 |
goto RecoverVarIds_ret_TSTREAM_FAIL; |
| 801 |
} |
| 802 |
} while ((*line_start == '#') && (!tokequal_k(line_start, "#CHROM"))); |
| 803 |
// simplified copy of plink2_pvar code, probably want to write a library |
| 804 |
// function for this |
| 805 |
uint32_t col_skips[4]; |
| 806 |
uint32_t col_types[4]; |
| 807 |
uint32_t strict_allele_order = 1; |
| 808 |
const uint32_t is_bim = !(line_start[0] == '#'); |
| 809 |
char* line_iter = nullptr; |
| 810 |
if (!is_bim) { |
| 811 |
// parse header |
| 812 |
// [-1] = #CHROM (must be first column) |
| 813 |
// [0] = POS |
| 814 |
// [1] = ID |
| 815 |
// [2] = REF |
| 816 |
// [3] = ALT |
| 817 |
char* token_end = &(line_start[6]); |
| 818 |
uint32_t found_header_bitset = 0; |
| 819 |
uint32_t relevant_postchr_col_ct = 0; |
| 820 |
char* linebuf_iter; |
| 821 |
for (uint32_t col_idx = 1; ; ++col_idx) { |
| 822 |
linebuf_iter = FirstNonTspace(token_end); |
| 823 |
if (IsEolnKns(*linebuf_iter)) { |
| 824 |
break; |
| 825 |
} |
| 826 |
token_end = CurTokenEnd(linebuf_iter); |
| 827 |
const uint32_t token_slen = token_end - linebuf_iter; |
| 828 |
uint32_t cur_col_type; |
| 829 |
if (token_slen == 3) { |
| 830 |
if (memequal_sk(linebuf_iter, "POS")) { |
| 831 |
cur_col_type = 0; |
| 832 |
} else if (memequal_sk(linebuf_iter, "REF")) { |
| 833 |
cur_col_type = 2; |
| 834 |
} else if (memequal_sk(linebuf_iter, "ALT")) { |
| 835 |
cur_col_type = 3; |
| 836 |
} else { |
| 837 |
continue; |
| 838 |
} |
| 839 |
} else if (token_slen == 2) { |
| 840 |
if (memequal_sk(linebuf_iter, "ID")) { |
| 841 |
cur_col_type = 1; |
| 842 |
} else { |
| 843 |
continue; |
| 844 |
} |
| 845 |
} else { |
| 846 |
continue; |
| 847 |
} |
| 848 |
const uint32_t cur_col_type_shifted = 1 << cur_col_type; |
| 849 |
if (unlikely(found_header_bitset & cur_col_type_shifted)) { |
| 850 |
// known token, so no overflow danger |
| 851 |
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate column header '"); |
| 852 |
write_iter = memcpya(write_iter, linebuf_iter, token_slen); |
| 853 |
write_iter = strcpya_k(write_iter, "' on line "); |
| 854 |
write_iter = wtoa(line_idx, write_iter); |
| 855 |
strcpy_k(write_iter, " of --recover-var-ids file.\n"); |
| 856 |
goto RecoverVarIds_ret_MALFORMED_INPUT_WW; |
| 857 |
} |
| 858 |
found_header_bitset |= cur_col_type_shifted; |
| 859 |
col_skips[relevant_postchr_col_ct] = col_idx; |
| 860 |
col_types[relevant_postchr_col_ct++] = cur_col_type; |
| 861 |
} |
| 862 |
if (unlikely(relevant_postchr_col_ct != 4)) { |
| 863 |
snprintf(g_logbuf, kLogbufSize, "Error: Missing column header(s) on line %" PRIuPTR " of --recover-var-ids file. (POS, ID, REF, and ALT are required.)\n", line_idx); |
| 864 |
goto RecoverVarIds_ret_MALFORMED_INPUT_WW; |
| 865 |
} |
| 866 |
for (uint32_t rpc_col_idx = 3; rpc_col_idx; --rpc_col_idx) { |
| 867 |
col_skips[rpc_col_idx] -= col_skips[rpc_col_idx - 1]; |
| 868 |
} |
| 869 |
line_iter = AdvPastDelim(linebuf_iter, '\n'); |
| 870 |
} else { |
| 871 |
// .bim. Interpret as #CHROM ID POS ALT REF if there are exactly 5 |
| 872 |
// columns, otherwise #CHROM ID CM POS ALT REF. |
| 873 |
col_skips[0] = 1; |
| 874 |
col_skips[2] = 1; |
| 875 |
col_skips[3] = 1; |
| 876 |
col_types[0] = 1; |
| 877 |
col_types[1] = 0; |
| 878 |
col_types[2] = 3; |
| 879 |
col_types[3] = 2; |
| 880 |
char* linebuf_iter = NextTokenMult(line_start, 4); |
| 881 |
if (unlikely(!linebuf_iter)) { |
| 882 |
goto RecoverVarIds_ret_MISSING_TOKENS; |
| 883 |
} |
| 884 |
linebuf_iter = NextToken(linebuf_iter); |
| 885 |
if (!linebuf_iter) { |
| 886 |
col_skips[1] = 1; |
| 887 |
} else { |
| 888 |
col_skips[1] = 2; |
| 889 |
} |
| 890 |
strict_allele_order = (flags / kfRecoverVarIdsStrictBimOrder) & 1; |
| 891 |
line_iter = line_start; |
| 892 |
--line_idx; |
| 893 |
} |
| 894 |
// Only nonzero if we're actually replacing existing IDs with the missing |
| 895 |
// ID in the conflict case. |
| 896 |
uint32_t missing_varid_blen = 0; |
| 897 |
if (flags & kfRecoverVarIdsForce) { |
| 898 |
if (!missing_varid) { |
| 899 |
missing_varid = &(g_one_char_strs[92]); // '.' |
| 900 |
} |
| 901 |
missing_varid_blen = 1 + strlen(missing_varid); |
| 902 |
} |
| 903 |
const uint32_t is_rigid = (flags / kfRecoverVarIdsRigid) & 1; |
| 904 |
uint32_t max_variant_id_slen = *max_variant_id_slen_ptr; |
| 905 |
char* alloc_base = R_CAST(char*, g_bigstack_base); |
| 906 |
uint32_t is_unsorted = 0; |
| 907 |
uint32_t prev_chr = UINT32_MAX; |
| 908 |
uint32_t prev_chr_vidx_end = 0; |
| 909 |
uint32_t prev_chr_vidx_start = 0; |
| 910 |
uint32_t prev_bp = 0; |
| 911 |
uint32_t prev_vidx_start = 0; |
| 912 |
uint32_t prev_vidx_end = 0; |
| 913 |
uint32_t rm_dup_warning = 0; |
| 914 |
uintptr_t record_uidx = ~k0LU; // deliberate overflow |
| 915 |
uint32_t cur_allele_ct = 2; |
| 916 |
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n')) { |
| 917 |
if ((!(line_idx % 1000000)) && line_idx) { |
| 918 |
printf("\r--recover-var-ids: %" PRIuPTR "m lines scanned.", line_idx / 1000000); |
| 919 |
fflush(stdout); |
| 920 |
} |
| 921 |
++line_idx; |
| 922 |
line_start = line_iter; |
| 923 |
if (unlikely(line_start[0] == '#')) { |
| 924 |
putc_unlocked('\n', stdout); |
| 925 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --recover-var-ids file starts with a '#'. (This is only permitted before the first nonheader line, and if a #CHROM header line is present it must denote the end of the header block.)\n", line_idx); |
| 926 |
goto RecoverVarIds_ret_MALFORMED_INPUT_WW; |
| 927 |
} |
| 928 |
++record_uidx; |
| 929 |
line_iter = CurTokenEnd(line_start); |
| 930 |
uint32_t cur_chr_code = GetChrCodeCounted(cip, line_iter - line_start, line_start); |
| 931 |
if (IsI32Neg(cur_chr_code)) { |
| 932 |
continue; |
| 933 |
} |
| 934 |
// Could add some special handling of chrX/PAR1/PAR2(/XY?) later, if |
| 935 |
// that proves to be a pain point; this does operate on VCF input, |
| 936 |
// after all. It's a bit annoying to implement, though, so I'm |
| 937 |
// excluding it from the first version. |
| 938 |
if (cur_chr_code == prev_chr) { |
| 939 |
if (!prev_chr_vidx_end) { |
| 940 |
continue; |
| 941 |
} |
| 942 |
} else { |
| 943 |
prev_chr = cur_chr_code; |
| 944 |
if (!is_unsorted) { |
| 945 |
if (IsSet(chr_already_seen, cur_chr_code)) { |
| 946 |
is_unsorted = 1; |
| 947 |
} else { |
| 948 |
SetBit(cur_chr_code, chr_already_seen); |
| 949 |
prev_bp = 0; |
| 950 |
} |
| 951 |
} |
| 952 |
if (!IsSet(cip->chr_mask, cur_chr_code)) { |
| 953 |
prev_chr_vidx_end = 0; |
| 954 |
continue; |
| 955 |
} |
| 956 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[cur_chr_code]; |
| 957 |
prev_chr_vidx_start = cip->chr_fo_vidx_start[chr_fo_idx]; |
| 958 |
prev_chr_vidx_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 959 |
prev_vidx_start = prev_chr_vidx_start; |
| 960 |
prev_vidx_end = prev_chr_vidx_start; |
| 961 |
} |
| 962 |
char* token_ptrs[4]; |
| 963 |
uint32_t token_slens[4]; |
| 964 |
line_iter = TokenLex(line_iter, col_types, col_skips, 4, token_ptrs, token_slens); |
| 965 |
if (unlikely(!line_iter)) { |
| 966 |
putc_unlocked('\n', stdout); |
| 967 |
goto RecoverVarIds_ret_MISSING_TOKENS; |
| 968 |
} |
| 969 |
// Usually, everything is sorted by position, so we use exponential |
| 970 |
// search over binary search unless we've detected unsorted data. |
| 971 |
int32_t cur_bp_signed; |
| 972 |
if (unlikely(ScanIntAbsDefcap(token_ptrs[0], &cur_bp_signed))) { |
| 973 |
putc_unlocked('\n', stdout); |
| 974 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid bp coordinate on line %" PRIuPTR " of --recover-var-ids file.\n", line_idx); |
| 975 |
goto RecoverVarIds_ret_MALFORMED_INPUT_WW; |
| 976 |
} |
| 977 |
if (cur_bp_signed < 0) { |
| 978 |
continue; |
| 979 |
} |
| 980 |
const uint32_t cur_bp = cur_bp_signed; |
| 981 |
if (cur_bp < prev_bp) { |
| 982 |
is_unsorted = 1; |
| 983 |
} |
| 984 |
if (!is_unsorted) { |
| 985 |
if (is_rigid || (cur_bp > prev_bp)) { |
| 986 |
const uint32_t arr_length = prev_chr_vidx_end - prev_vidx_end; |
| 987 |
const uint32_t incr = Expsearch0U32(&(variant_bps[prev_vidx_end]), arr_length, cur_bp); |
| 988 |
if (incr == arr_length) { |
| 989 |
prev_vidx_end = prev_chr_vidx_end; |
| 990 |
continue; |
| 991 |
} |
| 992 |
prev_vidx_start = incr + prev_vidx_end; |
| 993 |
} |
| 994 |
prev_bp = cur_bp; |
| 995 |
} else { |
| 996 |
const uint32_t arr_length = prev_chr_vidx_end - prev_chr_vidx_start; |
| 997 |
const uint32_t incr = LowerBoundNonemptyU32(&(variant_bps[prev_chr_vidx_start]), arr_length, cur_bp); |
| 998 |
if (incr == arr_length) { |
| 999 |
continue; |
| 1000 |
} |
| 1001 |
prev_vidx_start = incr + prev_chr_vidx_start; |
| 1002 |
} |
| 1003 |
prev_vidx_start = AdvBoundedTo1Bit(variant_include, prev_vidx_start, prev_chr_vidx_end); |
| 1004 |
|
| 1005 |
// variant_bps[prev_vidx_start] is the first element >= cur_bp that |
| 1006 |
// hasn't been filtered out. |
| 1007 |
if (variant_bps[prev_vidx_start] != cur_bp) { |
| 1008 |
prev_vidx_end = prev_vidx_start; |
| 1009 |
continue; |
| 1010 |
} |
| 1011 |
if (is_rigid) { |
| 1012 |
if (unlikely(record_uidx >= raw_variant_ct)) { |
| 1013 |
putc_unlocked('\n', stdout); |
| 1014 |
logerrputs("Error: \"--recover-var-ids rigid\" file does not match the main dataset.\n"); |
| 1015 |
goto RecoverVarIds_ret_INCONSISTENT_INPUT; |
| 1016 |
} |
| 1017 |
if (!IsSet(variant_include, record_uidx)) { |
| 1018 |
continue; |
| 1019 |
} |
| 1020 |
if (record_uidx != prev_vidx_start) { |
| 1021 |
putc_unlocked('\n', stdout); |
| 1022 |
logerrputs("Error: \"--recover-var-ids rigid\" file does not match the main dataset.\n"); |
| 1023 |
goto RecoverVarIds_ret_INCONSISTENT_INPUT; |
| 1024 |
} |
| 1025 |
} |
| 1026 |
char* orig_alt_start = token_ptrs[3]; |
| 1027 |
const uint32_t orig_alt_slen = token_slens[3]; |
| 1028 |
const uint32_t extra_orig_alt_ct = CountByte(orig_alt_start, ',', orig_alt_slen); |
| 1029 |
if (unlikely(extra_orig_alt_ct && is_bim)) { |
| 1030 |
// probably want to enforce this in main .pvar loader too... |
| 1031 |
putc_unlocked('\n', stdout); |
| 1032 |
snprintf(g_logbuf, kLogbufSize, "Error: Multiple ALT alleles on line %" PRIuPTR " of headerless --recover-var-ids file.\n", line_idx); |
| 1033 |
goto RecoverVarIds_ret_MALFORMED_INPUT_WW; |
| 1034 |
} |
| 1035 |
// Null-terminate all allele codes so we can use strequal_overread(); |
| 1036 |
// and make sure to reset the final null terminator so that unsafe |
| 1037 |
// line_iter advancement works. |
| 1038 |
const char line_iter_char = *line_iter; |
| 1039 |
char* orig_ref_start = token_ptrs[2]; |
| 1040 |
orig_ref_start[token_slens[2]] = '\0'; |
| 1041 |
{ |
| 1042 |
char* orig_alt_iter = orig_alt_start; |
| 1043 |
for (uint32_t alt_idx = 0; alt_idx != extra_orig_alt_ct; ++alt_idx) { |
| 1044 |
orig_alt_starts[alt_idx] = orig_alt_iter; |
| 1045 |
orig_alt_iter = AdvToDelim(orig_alt_iter, ','); |
| 1046 |
*orig_alt_iter++ = '\0'; |
| 1047 |
} |
| 1048 |
orig_alt_starts[extra_orig_alt_ct] = orig_alt_iter; |
| 1049 |
} |
| 1050 |
char* orig_alt_end = &(orig_alt_start[orig_alt_slen]); |
| 1051 |
*orig_alt_end = '\0'; |
| 1052 |
const uint32_t orig_alt_ct = extra_orig_alt_ct + 1; |
| 1053 |
|
| 1054 |
uint32_t cur_vidx = prev_vidx_start; |
| 1055 |
// Multiple variants in the current dataset may have this position; |
| 1056 |
// check them all for allele-code concordance. If there are multiple |
| 1057 |
// matches, allow this but print a warning suggesting --rm-dup. In the |
| 1058 |
// usual subcase where there are multiple instances in the original |
| 1059 |
// file, we'll error out instead unless 'force' was specified. |
| 1060 |
uint32_t already_matched = 0; |
| 1061 |
goto RecoverVarIds_first_iter; |
| 1062 |
for (; (!is_rigid) && (cur_vidx != prev_chr_vidx_end) && (variant_bps[cur_vidx] == cur_bp); cur_vidx = AdvBoundedTo1Bit(variant_include, cur_vidx + 1, prev_chr_vidx_end)) { |
| 1063 |
RecoverVarIds_first_iter: ; |
| 1064 |
uintptr_t allele_idx_offset_base = cur_vidx * 2; |
| 1065 |
if (allele_idx_offsets) { |
| 1066 |
allele_idx_offset_base = allele_idx_offsets[cur_vidx]; |
| 1067 |
cur_allele_ct = allele_idx_offsets[cur_vidx + 1] - allele_idx_offset_base; |
| 1068 |
} |
| 1069 |
if (cur_allele_ct != orig_alt_ct + 1) { |
| 1070 |
continue; |
| 1071 |
} |
| 1072 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 1073 |
const char* ref_allele = cur_alleles[0]; |
| 1074 |
if (strict_allele_order) { |
| 1075 |
if (!strequal_overread(ref_allele, orig_ref_start)) { |
| 1076 |
continue; |
| 1077 |
} |
| 1078 |
const char* const* cur_alt_alleles = &(cur_alleles[1]); |
| 1079 |
uint32_t alt_idx = 0; |
| 1080 |
for (; alt_idx != orig_alt_ct; ++alt_idx) { |
| 1081 |
if (!strequal_overread(cur_alt_alleles[alt_idx], orig_alt_starts[alt_idx])) { |
| 1082 |
break; |
| 1083 |
} |
| 1084 |
} |
| 1085 |
if (alt_idx != orig_alt_ct) { |
| 1086 |
continue; |
| 1087 |
} |
| 1088 |
} else { |
| 1089 |
// cur_allele_ct == 2 guaranteed. |
| 1090 |
const char* other_allele = cur_alleles[1]; |
| 1091 |
if (!strequal_overread(ref_allele, orig_ref_start)) { |
| 1092 |
if ((!strequal_overread(ref_allele, orig_alt_start)) || (!strequal_overread(other_allele, orig_ref_start))) { |
| 1093 |
continue; |
| 1094 |
} |
| 1095 |
} else if (!strequal_overread(other_allele, orig_alt_start)) { |
| 1096 |
continue; |
| 1097 |
} |
| 1098 |
} |
| 1099 |
char* old_id = variant_ids[cur_vidx]; |
| 1100 |
const uint32_t old_id_slen = strlen(old_id); |
| 1101 |
const char* new_id = token_ptrs[1]; |
| 1102 |
const uint32_t new_id_slen = token_slens[1]; |
| 1103 |
if (IsSet(already_seen, cur_vidx)) { |
| 1104 |
if ((new_id_slen != old_id_slen) || (!memequal(new_id, old_id, old_id_slen))) { |
| 1105 |
SetBit(cur_vidx, conflict_bitarr); |
| 1106 |
rm_dup_warning = 1; |
| 1107 |
} |
| 1108 |
continue; |
| 1109 |
} |
| 1110 |
// Okay, chr/pos/alleles match, and there's no conflict with a |
| 1111 |
// previous entry. Update the variant ID. |
| 1112 |
SetBit(cur_vidx, already_seen); |
| 1113 |
if (new_id_slen <= old_id_slen) { |
| 1114 |
const uint32_t old_id_blen = old_id_slen + 1; |
| 1115 |
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < old_id_blen)) { |
| 1116 |
goto RecoverVarIds_ret_NOMEM; |
| 1117 |
} |
| 1118 |
memcpy(alloc_base, old_id, old_id_blen); |
| 1119 |
variant_ids_copy[cur_vidx] = alloc_base; |
| 1120 |
alloc_base = &(alloc_base[old_id_blen]); |
| 1121 |
memcpyx(old_id, new_id, new_id_slen, '\0'); |
| 1122 |
} else { |
| 1123 |
if (new_id_slen > max_variant_id_slen) { |
| 1124 |
max_variant_id_slen = new_id_slen; |
| 1125 |
} |
| 1126 |
const uint32_t new_id_blen = new_id_slen + 1; |
| 1127 |
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < new_id_blen)) { |
| 1128 |
goto RecoverVarIds_ret_NOMEM; |
| 1129 |
} |
| 1130 |
alloc_end -= new_id_blen; |
| 1131 |
memcpyx(alloc_end, new_id, new_id_slen, '\0'); |
| 1132 |
variant_ids[cur_vidx] = alloc_end; |
| 1133 |
} |
| 1134 |
rm_dup_warning |= already_matched; |
| 1135 |
already_matched = 1; |
| 1136 |
} |
| 1137 |
*line_iter = line_iter_char; |
| 1138 |
prev_vidx_end = cur_vidx; |
| 1139 |
} |
| 1140 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 1141 |
goto RecoverVarIds_ret_TSTREAM_FAIL; |
| 1142 |
} |
| 1143 |
putc_unlocked('\r', stdout); |
| 1144 |
logprintf("--recover-var-ids: %" PRIuPTR " line%s scanned.\n", line_idx, (line_idx == 1)? "" : "s"); |
| 1145 |
const uint32_t conflict_ct = PopcountWords(conflict_bitarr, raw_variant_ctl); |
| 1146 |
if (conflict_ct) { |
| 1147 |
strcpy_k(outname_end, ".recoverid.dup"); |
| 1148 |
if (fopen_checked(outname, FOPEN_WB, &errfile)) { |
| 1149 |
goto RecoverVarIds_ret_OPEN_FAIL; |
| 1150 |
} |
| 1151 |
// Simply a list of affected variant IDs, one per line, sorted |
| 1152 |
// in order of original-file appearance. |
| 1153 |
// The reported variant IDs will usually be duplicated, since |
| 1154 |
// --set-all-var-ids makes them a function of CHROM/POS/REF/ALT, and |
| 1155 |
// that's what old-variant-ID recovery is based on. (But one could e.g. |
| 1156 |
// set the IDs to zero-based indexes before calling --recover-var-ids, if |
| 1157 |
// they wanted every .recoverid.dup entry to be unambiguous.) |
| 1158 |
char* textbuf = g_textbuf; |
| 1159 |
char* textbuf_flush = &(textbuf[kMaxMediumLine]); |
| 1160 |
char* write_iter = textbuf; |
| 1161 |
uintptr_t variant_uidx_base = 0; |
| 1162 |
uintptr_t cur_bits = conflict_bitarr[0]; |
| 1163 |
for (uint32_t conflict_idx = 0; conflict_idx != conflict_ct; ++conflict_idx) { |
| 1164 |
const uint32_t variant_uidx = BitIter1(conflict_bitarr, &variant_uidx_base, &cur_bits); |
| 1165 |
write_iter = strcpya(write_iter, variant_ids_copy[variant_uidx]); |
| 1166 |
AppendBinaryEoln(&write_iter); |
| 1167 |
if (unlikely(fwrite_ck(textbuf_flush, errfile, &write_iter))) { |
| 1168 |
goto RecoverVarIds_ret_WRITE_FAIL; |
| 1169 |
} |
| 1170 |
if (missing_varid_blen) { |
| 1171 |
char* cur_id = variant_ids[variant_uidx]; |
| 1172 |
const uint32_t cur_id_slen = strlen(cur_id); |
| 1173 |
if (missing_varid_blen <= cur_id_slen + 1) { |
| 1174 |
memcpy(cur_id, missing_varid, missing_varid_blen); |
| 1175 |
} else { |
| 1176 |
if (unlikely(S_CAST(uintptr_t, alloc_end - alloc_base) < missing_varid_blen)) { |
| 1177 |
goto RecoverVarIds_ret_NOMEM; |
| 1178 |
} |
| 1179 |
alloc_end -= missing_varid_blen; |
| 1180 |
memcpy(alloc_end, missing_varid, missing_varid_blen); |
| 1181 |
variant_ids[variant_uidx] = alloc_end; |
| 1182 |
} |
| 1183 |
} |
| 1184 |
} |
| 1185 |
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &errfile))) { |
| 1186 |
goto RecoverVarIds_ret_WRITE_FAIL; |
| 1187 |
} |
| 1188 |
if (!missing_varid_blen) { |
| 1189 |
// not really unlikely, conditional on being in this branch... |
| 1190 |
snprintf(g_logbuf, kLogbufSize, "Error: %u variant%s had conflicting matching-position-and-alleles records in the --recover-var-ids file; affected ID%s been written to %s . (Add the 'force' modifier if you just want to set %s to the missing code.)\n", conflict_ct, (conflict_ct == 1)? "" : "s", (conflict_ct == 1)? "" : "s", outname, (conflict_ct == 1)? "it" : "them"); |
| 1191 |
goto RecoverVarIds_ret_INCONSISTENT_INPUT_WW; |
| 1192 |
} |
| 1193 |
logerrprintfww("Warning: %u variant ID%s set to '%s' by \"--recover-var-ids force\". Previous ID%s been written to %s .\n", conflict_ct, (conflict_ct == 1)? "" : "s", missing_varid, (conflict_ct == 1)? " has" : "s have", outname); |
| 1194 |
} |
| 1195 |
const uint32_t update_ct = PopcountWords(already_seen, raw_variant_ctl); |
| 1196 |
const uint32_t unupdated_ct = variant_ct - update_ct; |
| 1197 |
if (unupdated_ct && (!(flags & kfRecoverVarIdsPartial))) { |
| 1198 |
snprintf(g_logbuf, kLogbufSize, "Error: %u/%u variant%s had no matching-position-and-alleles records in the --recover-var-ids file. (Add the 'partial' modifier when this is expected.)\n", unupdated_ct, variant_ct, (unupdated_ct == 1)? "" : "s"); |
| 1199 |
goto RecoverVarIds_ret_INCONSISTENT_INPUT_WW; |
| 1200 |
} |
| 1201 |
logprintf("--recover-var-ids: %u/%u ID%s updated.\n", update_ct, variant_ct, (update_ct == 1)? "" : "s"); |
| 1202 |
if (rm_dup_warning) { |
| 1203 |
logerrputs("Warning: Some variants had identical positions and alleles, and therefore were\nassigned the same ID. Consider deduplicating your data with --rm-dup.\n"); |
| 1204 |
} |
| 1205 |
*max_variant_id_slen_ptr = max_variant_id_slen; |
| 1206 |
} |
| 1207 |
while (0) { |
| 1208 |
RecoverVarIds_ret_NOMEM: |
| 1209 |
reterr = kPglRetNomem; |
| 1210 |
break; |
| 1211 |
RecoverVarIds_ret_OPEN_FAIL: |
| 1212 |
reterr = kPglRetOpenFail; |
| 1213 |
break; |
| 1214 |
RecoverVarIds_ret_WRITE_FAIL: |
| 1215 |
reterr = kPglRetWriteFail; |
| 1216 |
break; |
| 1217 |
RecoverVarIds_ret_TSTREAM_FAIL: |
| 1218 |
putc_unlocked('\n', stdout); |
| 1219 |
TextStreamErrPrint("--recover-var-ids file", &txs); |
| 1220 |
break; |
| 1221 |
RecoverVarIds_ret_MISSING_TOKENS: |
| 1222 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --recover-var-ids file has fewer tokens than expected.\n", line_idx); |
| 1223 |
RecoverVarIds_ret_MALFORMED_INPUT_WW: |
| 1224 |
WordWrapB(0); |
| 1225 |
logerrputsb(); |
| 1226 |
RecoverVarIds_ret_MALFORMED_INPUT: |
| 1227 |
reterr = kPglRetMalformedInput; |
| 1228 |
break; |
| 1229 |
RecoverVarIds_ret_INCONSISTENT_INPUT_WW: |
| 1230 |
WordWrapB(0); |
| 1231 |
logerrputsb(); |
| 1232 |
RecoverVarIds_ret_INCONSISTENT_INPUT: |
| 1233 |
reterr = kPglRetInconsistentInput; |
| 1234 |
break; |
| 1235 |
} |
| 1236 |
CleanupTextStream2("--recover-var-ids file", &txs, &reterr); |
| 1237 |
fclose_cond(errfile); |
| 1238 |
|
| 1239 |
// doesn't hurt to ensure all replaced variant_ids[] entries are valid in the |
| 1240 |
// error case... |
| 1241 |
BigstackEndSet(alloc_end); |
| 1242 |
BigstackReset(bigstack_mark); |
| 1243 |
return reterr; |
| 1244 |
} |
| 1245 |
|
| 1246 |
PglErr Plink1ClusterImport(const char* within_fname, const char* catpheno_name, const char* family_missing_catname, const uintptr_t* sample_include, const char* sample_ids, const char* missing_catname, uint32_t raw_sample_ct, uint32_t sample_ct, uintptr_t max_sample_id_blen, uint32_t mwithin_val, uint32_t max_thread_ct, PhenoCol** pheno_cols_ptr, char** pheno_names_ptr, uint32_t* pheno_ct_ptr, uintptr_t* max_pheno_name_blen_ptr) { |
| 1247 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1248 |
uintptr_t line_idx = 0; |
| 1249 |
PglErr reterr = kPglRetSuccess; |
| 1250 |
TextStream within_txs; |
| 1251 |
PreinitTextStream(&within_txs); |
| 1252 |
{ |
| 1253 |
if (!sample_ct) { |
| 1254 |
goto Plink1ClusterImport_ret_1; |
| 1255 |
} |
| 1256 |
const char catpheno_name_default[] = "CATPHENO"; |
| 1257 |
uint32_t catpheno_name_blen; |
| 1258 |
if (!catpheno_name) { |
| 1259 |
catpheno_name = catpheno_name_default; |
| 1260 |
catpheno_name_blen = 9; |
| 1261 |
} else { |
| 1262 |
catpheno_name_blen = 1 + strlen(catpheno_name); |
| 1263 |
} |
| 1264 |
const uintptr_t old_max_pheno_name_blen = *max_pheno_name_blen_ptr; |
| 1265 |
const uint32_t old_pheno_ct = *pheno_ct_ptr; |
| 1266 |
const char* old_pheno_names = *pheno_names_ptr; |
| 1267 |
uintptr_t new_max_pheno_name_blen; |
| 1268 |
if (old_pheno_names && (catpheno_name_blen <= old_max_pheno_name_blen)) { |
| 1269 |
new_max_pheno_name_blen = old_max_pheno_name_blen; |
| 1270 |
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) { |
| 1271 |
if (unlikely(memequal(catpheno_name, &(old_pheno_names[pheno_idx * old_max_pheno_name_blen]), catpheno_name_blen))) { |
| 1272 |
snprintf(g_logbuf, kLogbufSize, "Error: Cannot create a new categorical phenotype named '%s', since another phenotype of the same name already exists.\n", catpheno_name); |
| 1273 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT_WW; |
| 1274 |
} |
| 1275 |
} |
| 1276 |
} else { |
| 1277 |
new_max_pheno_name_blen = catpheno_name_blen; |
| 1278 |
} |
| 1279 |
const uint32_t new_pheno_ct = old_pheno_ct + 1; |
| 1280 |
uintptr_t new_pheno_names_byte_ct = new_pheno_ct * new_max_pheno_name_blen; |
| 1281 |
char* pheno_names; |
| 1282 |
if (unlikely(pgl_malloc(new_pheno_names_byte_ct, &pheno_names))) { |
| 1283 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1284 |
} |
| 1285 |
if (old_pheno_names && (old_max_pheno_name_blen == new_max_pheno_name_blen)) { |
| 1286 |
memcpy(pheno_names, old_pheno_names, old_pheno_ct * new_max_pheno_name_blen); |
| 1287 |
} else { |
| 1288 |
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) { |
| 1289 |
strcpy(&(pheno_names[pheno_idx * new_max_pheno_name_blen]), &(old_pheno_names[pheno_idx * old_max_pheno_name_blen])); |
| 1290 |
} |
| 1291 |
} |
| 1292 |
memcpy(&(pheno_names[old_pheno_ct * new_max_pheno_name_blen]), catpheno_name, catpheno_name_blen); |
| 1293 |
free_cond(old_pheno_names); |
| 1294 |
*pheno_names_ptr = pheno_names; |
| 1295 |
|
| 1296 |
PhenoCol* new_pheno_cols = S_CAST(PhenoCol*, realloc(*pheno_cols_ptr, new_pheno_ct * sizeof(PhenoCol))); |
| 1297 |
if (unlikely(!new_pheno_cols)) { |
| 1298 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1299 |
} |
| 1300 |
*pheno_cols_ptr = new_pheno_cols; |
| 1301 |
*pheno_ct_ptr = new_pheno_ct; |
| 1302 |
*max_pheno_name_blen_ptr = new_max_pheno_name_blen; |
| 1303 |
new_pheno_cols[old_pheno_ct].nonmiss = nullptr; |
| 1304 |
new_pheno_cols[old_pheno_ct].type_code = S_CAST(PhenoDtype, kPhenoDtypeCat); |
| 1305 |
|
| 1306 |
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct); |
| 1307 |
uintptr_t* cat_nm = nullptr; |
| 1308 |
uint32_t* cat_idxs = nullptr; |
| 1309 |
if (!within_fname) { |
| 1310 |
if (unlikely(bigstack_alloc_w(raw_sample_ctaw, &cat_nm) || |
| 1311 |
bigstack_calloc_u32(raw_sample_ct, &cat_idxs))) { |
| 1312 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1313 |
} |
| 1314 |
memcpy(cat_nm, sample_include, raw_sample_ctaw * sizeof(intptr_t)); |
| 1315 |
} |
| 1316 |
uint32_t* cat_htable; |
| 1317 |
uint32_t cat_htable_size; |
| 1318 |
if (unlikely(HtableGoodSizeAlloc(sample_ct + 2, bigstack_left() / 4, &cat_htable, &cat_htable_size))) { |
| 1319 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1320 |
} |
| 1321 |
SetAllU32Arr(cat_htable_size, cat_htable); |
| 1322 |
const uintptr_t data_vec_ct = Int32CtToVecCt(raw_sample_ct); |
| 1323 |
const uint32_t missing_catname_slen = strlen(missing_catname); |
| 1324 |
const uint32_t missing_catname_hval = Hashceil(missing_catname, missing_catname_slen, cat_htable_size); |
| 1325 |
if (within_fname) { |
| 1326 |
uintptr_t* already_seen; |
| 1327 |
uint32_t* sorted_cat_idxs; |
| 1328 |
char* idbuf; |
| 1329 |
const char** cur_cat_names; |
| 1330 |
if (unlikely(bigstack_calloc_w(BitCtToWordCt(sample_ct), &already_seen) || |
| 1331 |
bigstack_calloc_u32(sample_ct, &sorted_cat_idxs) || |
| 1332 |
bigstack_alloc_c(max_sample_id_blen, &idbuf) || |
| 1333 |
bigstack_alloc_kcp(sample_ct + 2, &cur_cat_names))) { |
| 1334 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1335 |
} |
| 1336 |
cat_htable[missing_catname_hval] = 0; |
| 1337 |
cur_cat_names[0] = missing_catname; |
| 1338 |
const char na_str[] = "NA"; |
| 1339 |
uint32_t na_hashval = Hashceil(na_str, 2, cat_htable_size); |
| 1340 |
if (na_hashval == missing_catname_hval) { |
| 1341 |
if (++na_hashval == cat_htable_size) { |
| 1342 |
na_hashval = 0; |
| 1343 |
} |
| 1344 |
} |
| 1345 |
cat_htable[na_hashval] = sample_ct + 1; |
| 1346 |
cur_cat_names[sample_ct + 1] = na_str; |
| 1347 |
|
| 1348 |
uint32_t* id_map; |
| 1349 |
char* sorted_idbox; |
| 1350 |
if (unlikely(CopySortStrboxSubset(sample_include, sample_ids, sample_ct, max_sample_id_blen, 0, 0, &sorted_idbox, &id_map))) { |
| 1351 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1352 |
} |
| 1353 |
reterr = SizeAndInitTextStream(within_fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &within_txs); |
| 1354 |
if (unlikely(reterr)) { |
| 1355 |
goto Plink1ClusterImport_ret_TSTREAM_FAIL; |
| 1356 |
} |
| 1357 |
char* cat_name_write_start = R_CAST(char*, g_bigstack_base); |
| 1358 |
char* cat_name_iter = cat_name_write_start; |
| 1359 |
char* cat_name_write_max = R_CAST(char*, BigstackEndRoundedDown()); |
| 1360 |
|
| 1361 |
uint32_t nonnull_cat_ct = 0; |
| 1362 |
uintptr_t miss_ct = 0; |
| 1363 |
uintptr_t duplicate_ct = 0; |
| 1364 |
for (char* line_iter = &(TextLineEnd(&within_txs)[-1]); ; line_iter = AdvToDelim(line_iter, '\n')) { |
| 1365 |
// need this since we may clobber \n |
| 1366 |
Plink1ClusterImport_LINE_ITER_ALREADY_ADVANCED: |
| 1367 |
++line_iter; |
| 1368 |
++line_idx; |
| 1369 |
if (!TextGetUnsafe2(&within_txs, &line_iter)) { |
| 1370 |
if (likely(!TextStreamErrcode2(&within_txs, &reterr))) { |
| 1371 |
break; |
| 1372 |
} |
| 1373 |
goto Plink1ClusterImport_ret_TSTREAM_FAIL; |
| 1374 |
} |
| 1375 |
char* fid_start = line_iter; |
| 1376 |
char* fid_end = CurTokenEnd(fid_start); |
| 1377 |
char* iid_start = FirstNonTspace(fid_end); |
| 1378 |
if (unlikely(IsEolnKns(*iid_start))) { |
| 1379 |
goto Plink1ClusterImport_ret_MISSING_TOKENS; |
| 1380 |
} |
| 1381 |
char* iid_end = CurTokenEnd(iid_start); |
| 1382 |
const uint32_t fid_slen = fid_end - fid_start; |
| 1383 |
const uint32_t iid_slen = iid_end - iid_start; |
| 1384 |
const uint32_t id_blen = fid_slen + iid_slen + 2; |
| 1385 |
if (id_blen > max_sample_id_blen) { |
| 1386 |
++miss_ct; |
| 1387 |
line_iter = iid_end; |
| 1388 |
continue; |
| 1389 |
} |
| 1390 |
char* idbuf_iter = memcpyax(idbuf, fid_start, fid_slen, '\t'); |
| 1391 |
idbuf_iter = memcpya(idbuf_iter, iid_start, iid_slen); |
| 1392 |
*idbuf_iter = '\0'; |
| 1393 |
uint32_t lb_idx = bsearch_strbox_lb(idbuf, sorted_idbox, id_blen, max_sample_id_blen, sample_ct); |
| 1394 |
*idbuf_iter = ' '; |
| 1395 |
const uint32_t ub_idx = bsearch_strbox_lb(idbuf, sorted_idbox, id_blen, max_sample_id_blen, sample_ct); |
| 1396 |
if (ub_idx == lb_idx) { |
| 1397 |
++miss_ct; |
| 1398 |
line_iter = iid_end; |
| 1399 |
continue; |
| 1400 |
} |
| 1401 |
char* main_token_start = NextTokenMult(iid_end, mwithin_val); |
| 1402 |
if (unlikely(!main_token_start)) { |
| 1403 |
goto Plink1ClusterImport_ret_MISSING_TOKENS; |
| 1404 |
} |
| 1405 |
char* main_token_end = CurTokenEnd(main_token_start); |
| 1406 |
line_iter = AdvToDelim(line_iter, '\n'); |
| 1407 |
*main_token_end = '\0'; |
| 1408 |
const uint32_t main_token_slen = main_token_end - main_token_start; |
| 1409 |
if (unlikely(main_token_slen > kMaxIdSlen)) { |
| 1410 |
logerrputs("Error: Category names are limited to " MAX_ID_SLEN_STR " characters.\n"); |
| 1411 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1412 |
} |
| 1413 |
uint32_t cur_cat_idx = IdHtableAdd(main_token_start, cur_cat_names, main_token_slen, cat_htable_size, nonnull_cat_ct + 1, cat_htable); |
| 1414 |
if (cur_cat_idx == UINT32_MAX) { |
| 1415 |
if (unlikely(main_token_slen >= S_CAST(uintptr_t, cat_name_write_max - cat_name_iter))) { |
| 1416 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1417 |
} |
| 1418 |
char* cat_name_start = cat_name_iter; |
| 1419 |
cat_name_iter = memcpya(cat_name_iter, main_token_start, main_token_slen + 1); |
| 1420 |
// bugfix (5 May 2021): dropped this increment in mid-Jan refactor |
| 1421 |
++nonnull_cat_ct; |
| 1422 |
cur_cat_idx = nonnull_cat_ct; |
| 1423 |
cur_cat_names[cur_cat_idx] = cat_name_start; |
| 1424 |
} |
| 1425 |
// permit duplicates if category is identical |
| 1426 |
if (IsSet(already_seen, lb_idx)) { |
| 1427 |
const uint32_t existing_cat_idx = sorted_cat_idxs[lb_idx]; |
| 1428 |
if (unlikely(existing_cat_idx != cur_cat_idx)) { |
| 1429 |
idbuf[fid_slen] = ' '; |
| 1430 |
logpreprintfww("Error: Duplicate sample ID \"%s\" with conflicting category assignments in --within file.\n", idbuf); |
| 1431 |
goto Plink1ClusterImport_ret_MALFORMED_INPUT_2; |
| 1432 |
} |
| 1433 |
++duplicate_ct; |
| 1434 |
} else { |
| 1435 |
SetBit(lb_idx, already_seen); |
| 1436 |
for (; lb_idx != ub_idx; ++lb_idx) { |
| 1437 |
sorted_cat_idxs[lb_idx] = cur_cat_idx; |
| 1438 |
} |
| 1439 |
} |
| 1440 |
goto Plink1ClusterImport_LINE_ITER_ALREADY_ADVANCED; |
| 1441 |
} |
| 1442 |
if (unlikely(!nonnull_cat_ct)) { |
| 1443 |
if (line_idx == miss_ct + 1) { |
| 1444 |
// could be fancy and only print the last part of this message if |
| 1445 |
// all FIDs are 0 |
| 1446 |
logerrputs("Error: No sample IDs in --within file are in the main dataset. Compare it with\nyour .fam/.psam file; note that if the latter has no FID column at all, that\ncorresponds to FIDs of '0', not FIDs equal to the IIDs.\n"); |
| 1447 |
} else { |
| 1448 |
logerrputs("Error: All --within categories are null.\n"); |
| 1449 |
} |
| 1450 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1451 |
} |
| 1452 |
double dxx; |
| 1453 |
const uint32_t prepend_c = (ScanadvDouble(cur_cat_names[1], &dxx) != nullptr); |
| 1454 |
if (prepend_c) { |
| 1455 |
for (uint32_t catname_idx = 2; catname_idx <= nonnull_cat_ct; ++catname_idx) { |
| 1456 |
if (unlikely(!ScanadvDouble(cur_cat_names[catname_idx], &dxx))) { |
| 1457 |
logerrputs("Error: Either all non-null --within categories must be numeric, or none can be.\n"); |
| 1458 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1459 |
} |
| 1460 |
} |
| 1461 |
logputs("Note: Prepending 'C' to all --within category names.\n"); |
| 1462 |
} else { |
| 1463 |
for (uint32_t catname_idx = 2; catname_idx <= nonnull_cat_ct; ++catname_idx) { |
| 1464 |
if (unlikely(ScanadvDouble(cur_cat_names[catname_idx], &dxx))) { |
| 1465 |
logerrputs("Error: Either all non-null --within categories must be numeric, or none can be.\n"); |
| 1466 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1467 |
} |
| 1468 |
} |
| 1469 |
} |
| 1470 |
// see end of e.g. LoadPsam() |
| 1471 |
BigstackBaseSet(cat_name_write_start); |
| 1472 |
uint32_t* old_cat_idxs_to_new; |
| 1473 |
if (unlikely(bigstack_alloc_u32(nonnull_cat_ct + 1, &old_cat_idxs_to_new))) { |
| 1474 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1475 |
} |
| 1476 |
const uintptr_t catname_vec_ct = WordCtToVecCt(nonnull_cat_ct + 1); |
| 1477 |
const uintptr_t total_catname_blen = (prepend_c * nonnull_cat_ct) + S_CAST(uintptr_t, cat_name_iter - cat_name_write_start); |
| 1478 |
const uintptr_t catname_storage_vec_ct = DivUp(total_catname_blen, kBytesPerVec); |
| 1479 |
if (unlikely(vecaligned_malloc((raw_sample_ctaw * kWordsPerVec + data_vec_ct + catname_vec_ct + catname_storage_vec_ct) * kBytesPerVec, &(new_pheno_cols[old_pheno_ct].nonmiss)))) { |
| 1480 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1481 |
} |
| 1482 |
new_pheno_cols[old_pheno_ct].nonnull_category_ct = nonnull_cat_ct; |
| 1483 |
uintptr_t* catdata_iter = new_pheno_cols[old_pheno_ct].nonmiss; |
| 1484 |
cat_nm = catdata_iter; |
| 1485 |
ZeroWArr(raw_sample_ctaw, cat_nm); |
| 1486 |
catdata_iter = &(catdata_iter[raw_sample_ctaw]); |
| 1487 |
|
| 1488 |
cat_idxs = R_CAST(uint32_t*, catdata_iter); |
| 1489 |
ZeroU32Arr(raw_sample_ct, cat_idxs); |
| 1490 |
new_pheno_cols[old_pheno_ct].data.cat = cat_idxs; |
| 1491 |
catdata_iter = &(catdata_iter[data_vec_ct * kWordsPerVec]); |
| 1492 |
|
| 1493 |
const char** cur_name_ptrs = R_CAST(const char**, catdata_iter); |
| 1494 |
new_pheno_cols[old_pheno_ct].category_names = cur_name_ptrs; |
| 1495 |
*cur_name_ptrs++ = missing_catname; |
| 1496 |
char* name_storage_iter = R_CAST(char*, &(catdata_iter[catname_vec_ct * kWordsPerVec])); |
| 1497 |
cat_name_iter = cat_name_write_start; |
| 1498 |
for (uint32_t uii = 0; uii != nonnull_cat_ct; ++uii) { |
| 1499 |
char* cur_name_start = name_storage_iter; |
| 1500 |
if (prepend_c) { |
| 1501 |
*name_storage_iter++ = 'C'; |
| 1502 |
} |
| 1503 |
const uint32_t cur_catname_blen = 1 + strlen(cat_name_iter); |
| 1504 |
name_storage_iter = memcpya(name_storage_iter, cat_name_iter, cur_catname_blen); |
| 1505 |
*cur_name_ptrs++ = cur_name_start; |
| 1506 |
cat_name_iter = &(cat_name_iter[cur_catname_blen]); |
| 1507 |
} |
| 1508 |
if (unlikely(SortStrptrArrIndexed(nonnull_cat_ct + 1, 1, 0, 1, new_pheno_cols[old_pheno_ct].category_names, nullptr, old_cat_idxs_to_new))) { |
| 1509 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1510 |
} |
| 1511 |
for (uint32_t sorted_sample_idx = 0; sorted_sample_idx != sample_ct; ++sorted_sample_idx) { |
| 1512 |
const uint32_t cur_sample_uidx = id_map[sorted_sample_idx]; |
| 1513 |
uint32_t cur_cat_idx = sorted_cat_idxs[sorted_sample_idx]; |
| 1514 |
if (cur_cat_idx > sample_ct) { |
| 1515 |
cur_cat_idx = 0; |
| 1516 |
} |
| 1517 |
if (cur_cat_idx) { |
| 1518 |
SetBit(cur_sample_uidx, cat_nm); |
| 1519 |
} |
| 1520 |
cat_idxs[cur_sample_uidx] = old_cat_idxs_to_new[cur_cat_idx]; |
| 1521 |
} |
| 1522 |
|
| 1523 |
if (duplicate_ct) { |
| 1524 |
logprintfww("Note: %" PRIuPTR " duplicate sample ID%s) in --within file.\n", duplicate_ct, (duplicate_ct == 1)? " (with a consistent category assignment" : "s (with consistent category assignments"); |
| 1525 |
} |
| 1526 |
if (miss_ct) { |
| 1527 |
snprintf(g_logbuf, kLogbufSize, "--within: %u non-null categor%s present, %" PRIuPTR " sample ID%s skipped.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies", miss_ct, (miss_ct == 1)? "" : "s"); |
| 1528 |
WordWrapB(0); |
| 1529 |
} else { |
| 1530 |
snprintf(g_logbuf, kLogbufSize, "--within: %u non-null categor%s present.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies"); |
| 1531 |
} |
| 1532 |
logputsb(); |
| 1533 |
} else { |
| 1534 |
// --family |
| 1535 |
cat_htable[missing_catname_hval] = 0xfffffffdU; |
| 1536 |
uintptr_t total_catname_blen = 0; // does not need to include 'NONE' |
| 1537 |
uint32_t family_missing_catname_slen = 0; |
| 1538 |
if (family_missing_catname) { |
| 1539 |
family_missing_catname_slen = strlen(family_missing_catname); |
| 1540 |
uint32_t family_missing_catname_hval = Hashceil(family_missing_catname, family_missing_catname_slen, cat_htable_size); |
| 1541 |
if (cat_htable[family_missing_catname_hval] == UINT32_MAX) { |
| 1542 |
cat_htable[family_missing_catname_hval] = UINT32_MAXM1; |
| 1543 |
} else if ((missing_catname_slen != family_missing_catname_slen) || (!memequal(family_missing_catname, missing_catname, missing_catname_slen))) { |
| 1544 |
if (++family_missing_catname_hval == cat_htable_size) { |
| 1545 |
family_missing_catname_hval = 0; |
| 1546 |
} |
| 1547 |
cat_htable[family_missing_catname_hval] = UINT32_MAXM1; |
| 1548 |
} |
| 1549 |
} |
| 1550 |
// guaranteed to have enough space, otherwise HtableGoodSizeAlloc would |
| 1551 |
// have failed |
| 1552 |
uint32_t* cat_idx_m1_to_first_sample_uidx = R_CAST(uint32_t*, g_bigstack_base); |
| 1553 |
uintptr_t sample_uidx_base = 0; |
| 1554 |
uintptr_t cur_bits = sample_include[0]; |
| 1555 |
uint32_t nonnull_cat_ct = 0; |
| 1556 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 1557 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 1558 |
const char* cur_fid = &(sample_ids[sample_uidx * max_sample_id_blen]); |
| 1559 |
const char* cur_fid_end = AdvToDelim(cur_fid, '\t'); |
| 1560 |
const uint32_t slen = cur_fid_end - cur_fid; |
| 1561 |
const uint32_t blen = slen + 1; |
| 1562 |
for (uint32_t hashval = Hashceil(cur_fid, slen, cat_htable_size); ; ) { |
| 1563 |
const uint32_t cur_htable_entry = cat_htable[hashval]; |
| 1564 |
if (cur_htable_entry >= 0xfffffffdU) { |
| 1565 |
if (cur_htable_entry == UINT32_MAX) { |
| 1566 |
cat_htable[hashval] = sample_uidx; |
| 1567 |
total_catname_blen += blen; |
| 1568 |
cat_idx_m1_to_first_sample_uidx[nonnull_cat_ct] = sample_uidx; |
| 1569 |
cat_idxs[sample_uidx] = ++nonnull_cat_ct; |
| 1570 |
break; |
| 1571 |
} else if (cur_htable_entry == UINT32_MAXM1) { |
| 1572 |
if ((slen == family_missing_catname_slen) && memequal(cur_fid, family_missing_catname, family_missing_catname_slen)) { |
| 1573 |
ClearBit(sample_uidx, cat_nm); |
| 1574 |
cat_idxs[sample_uidx] = 0; |
| 1575 |
break; |
| 1576 |
} |
| 1577 |
} else { |
| 1578 |
if ((slen == missing_catname_slen) && memequal(cur_fid, missing_catname, missing_catname_slen)) { |
| 1579 |
ClearBit(sample_uidx, cat_nm); |
| 1580 |
cat_idxs[sample_uidx] = 0; |
| 1581 |
break; |
| 1582 |
} |
| 1583 |
} |
| 1584 |
} else { |
| 1585 |
if (memequal(cur_fid, &(sample_ids[cur_htable_entry * max_sample_id_blen]), blen)) { |
| 1586 |
cat_idxs[sample_uidx] = cat_idxs[cur_htable_entry]; |
| 1587 |
break; |
| 1588 |
} |
| 1589 |
} |
| 1590 |
if (++hashval == cat_htable_size) { |
| 1591 |
hashval = 0; |
| 1592 |
} |
| 1593 |
} |
| 1594 |
} |
| 1595 |
if (unlikely(!nonnull_cat_ct)) { |
| 1596 |
logerrputs("Error: All --family FIDs are null.\n"); |
| 1597 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1598 |
} |
| 1599 |
// add 'C' prefixes? |
| 1600 |
double dxx; |
| 1601 |
const uint32_t prepend_c = (ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[0] * max_sample_id_blen]), &dxx) != nullptr); |
| 1602 |
if (prepend_c) { |
| 1603 |
for (uint32_t uii = 1; uii != nonnull_cat_ct; ++uii) { |
| 1604 |
if (unlikely(!ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]), &dxx))) { |
| 1605 |
logerrputs("Error: Either all non-null --family FIDs must be numeric, or none can be.\n"); |
| 1606 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1607 |
} |
| 1608 |
} |
| 1609 |
logputs("Note: Prepending 'C' to all --family category names.\n"); |
| 1610 |
total_catname_blen += nonnull_cat_ct; |
| 1611 |
} else { |
| 1612 |
for (uint32_t uii = 1; uii != nonnull_cat_ct; ++uii) { |
| 1613 |
if (unlikely(ScanadvDouble(&(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]), &dxx))) { |
| 1614 |
logerrputs("Error: Either all non-null --family FIDs must be numeric, or none can be.\n"); |
| 1615 |
goto Plink1ClusterImport_ret_INCONSISTENT_INPUT; |
| 1616 |
} |
| 1617 |
} |
| 1618 |
} |
| 1619 |
// see end of e.g. LoadPsam() |
| 1620 |
BigstackFinalizeU32(cat_idx_m1_to_first_sample_uidx, nonnull_cat_ct); |
| 1621 |
uint32_t* old_cat_idxs_to_new; |
| 1622 |
if (unlikely(bigstack_alloc_u32(nonnull_cat_ct + 1, &old_cat_idxs_to_new))) { |
| 1623 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1624 |
} |
| 1625 |
const uintptr_t catname_vec_ct = WordCtToVecCt(nonnull_cat_ct + 1); |
| 1626 |
const uintptr_t catname_storage_vec_ct = DivUp(total_catname_blen, kBytesPerVec); |
| 1627 |
if (unlikely(vecaligned_malloc((raw_sample_ctaw * kWordsPerVec + data_vec_ct + catname_vec_ct + catname_storage_vec_ct) * kBytesPerVec, &(new_pheno_cols[old_pheno_ct].nonmiss)))) { |
| 1628 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1629 |
} |
| 1630 |
new_pheno_cols[old_pheno_ct].nonnull_category_ct = nonnull_cat_ct; |
| 1631 |
uintptr_t* catdata_iter = new_pheno_cols[old_pheno_ct].nonmiss; |
| 1632 |
memcpy(catdata_iter, cat_nm, raw_sample_ctaw * sizeof(intptr_t)); |
| 1633 |
catdata_iter = &(catdata_iter[raw_sample_ctaw]); |
| 1634 |
|
| 1635 |
uint32_t* cat_idx_dst = R_CAST(uint32_t*, catdata_iter); |
| 1636 |
new_pheno_cols[old_pheno_ct].data.cat = cat_idx_dst; |
| 1637 |
catdata_iter = &(catdata_iter[data_vec_ct * kWordsPerVec]); |
| 1638 |
|
| 1639 |
const char** cur_name_ptrs = R_CAST(const char**, catdata_iter); |
| 1640 |
new_pheno_cols[old_pheno_ct].category_names = cur_name_ptrs; |
| 1641 |
*cur_name_ptrs++ = missing_catname; |
| 1642 |
char* name_storage_iter = R_CAST(char*, &(catdata_iter[catname_vec_ct * kWordsPerVec])); |
| 1643 |
for (uint32_t uii = 0; uii != nonnull_cat_ct; ++uii) { |
| 1644 |
char* cur_name_start = name_storage_iter; |
| 1645 |
if (prepend_c) { |
| 1646 |
*name_storage_iter++ = 'C'; |
| 1647 |
} |
| 1648 |
const char* cur_fid = &(sample_ids[cat_idx_m1_to_first_sample_uidx[uii] * max_sample_id_blen]); |
| 1649 |
const char* cur_fid_end = AdvToDelim(cur_fid, '\t'); |
| 1650 |
name_storage_iter = memcpyax(name_storage_iter, cur_fid, cur_fid_end - cur_fid, '\0'); |
| 1651 |
*cur_name_ptrs++ = cur_name_start; |
| 1652 |
} |
| 1653 |
if (unlikely(SortStrptrArrIndexed(nonnull_cat_ct + 1, 1, 0, 1, new_pheno_cols[old_pheno_ct].category_names, nullptr, old_cat_idxs_to_new))) { |
| 1654 |
goto Plink1ClusterImport_ret_NOMEM; |
| 1655 |
} |
| 1656 |
sample_uidx_base = 0; |
| 1657 |
cur_bits = sample_include[0]; |
| 1658 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 1659 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 1660 |
cat_idx_dst[sample_uidx] = old_cat_idxs_to_new[cat_idxs[sample_uidx]]; |
| 1661 |
} |
| 1662 |
logprintf("--family: %u non-null categor%s present.\n", nonnull_cat_ct, (nonnull_cat_ct == 1)? "y" : "ies"); |
| 1663 |
} |
| 1664 |
} |
| 1665 |
while (0) { |
| 1666 |
Plink1ClusterImport_ret_NOMEM: |
| 1667 |
reterr = kPglRetNomem; |
| 1668 |
break; |
| 1669 |
Plink1ClusterImport_ret_TSTREAM_FAIL: |
| 1670 |
TextStreamErrPrint("--within file", &within_txs); |
| 1671 |
break; |
| 1672 |
Plink1ClusterImport_ret_MISSING_TOKENS: |
| 1673 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --within file has fewer tokens than expected.\n", line_idx); |
| 1674 |
Plink1ClusterImport_ret_MALFORMED_INPUT_2: |
| 1675 |
logerrputsb(); |
| 1676 |
reterr = kPglRetMalformedInput; |
| 1677 |
break; |
| 1678 |
Plink1ClusterImport_ret_INCONSISTENT_INPUT_WW: |
| 1679 |
WordWrapB(0); |
| 1680 |
logerrputsb(); |
| 1681 |
Plink1ClusterImport_ret_INCONSISTENT_INPUT: |
| 1682 |
reterr = kPglRetInconsistentInput; |
| 1683 |
break; |
| 1684 |
} |
| 1685 |
Plink1ClusterImport_ret_1: |
| 1686 |
CleanupTextStream2("--within file", &within_txs, &reterr); |
| 1687 |
BigstackReset(bigstack_mark); |
| 1688 |
if (reterr) { |
| 1689 |
if (*pheno_names_ptr) { |
| 1690 |
free(*pheno_names_ptr); |
| 1691 |
*pheno_names_ptr = nullptr; |
| 1692 |
} |
| 1693 |
CleanupPhenoCols(*pheno_ct_ptr, *pheno_cols_ptr); |
| 1694 |
*pheno_ct_ptr = 0; |
| 1695 |
*pheno_cols_ptr = nullptr; |
| 1696 |
} |
| 1697 |
return reterr; |
| 1698 |
} |
| 1699 |
|
| 1700 |
PglErr PrescanSampleIds(const char* fname, SampleIdInfo* siip) { |
| 1701 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1702 |
uintptr_t line_idx = 0; |
| 1703 |
PglErr reterr = kPglRetSuccess; |
| 1704 |
TextStream txs; |
| 1705 |
PreinitTextStream(&txs); |
| 1706 |
{ |
| 1707 |
reterr = ForceNonFifo(fname); |
| 1708 |
if (unlikely(reterr)) { |
| 1709 |
if (reterr == kPglRetOpenFail) { |
| 1710 |
logerrprintfww(kErrprintfFopen, "--update-ids file", strerror(errno)); |
| 1711 |
} else { |
| 1712 |
logerrprintfww(kErrprintfRewind, "--update-ids file"); |
| 1713 |
} |
| 1714 |
goto PrescanSampleIds_ret_1; |
| 1715 |
} |
| 1716 |
reterr = InitTextStream(fname, kTextStreamBlenFast, 1, &txs); |
| 1717 |
if (unlikely(reterr)) { |
| 1718 |
goto PrescanSampleIds_ret_TSTREAM_FAIL; |
| 1719 |
} |
| 1720 |
uint32_t is_header_line; |
| 1721 |
const char* line_iter; |
| 1722 |
do { |
| 1723 |
++line_idx; |
| 1724 |
line_iter = TextGet(&txs); |
| 1725 |
if (!line_iter) { |
| 1726 |
reterr = TextStreamRawErrcode(&txs); |
| 1727 |
if (likely(reterr == kPglRetEof)) { |
| 1728 |
// permit empty file here, but signal this to caller |
| 1729 |
// (reterr == kPglRetSuccess when file is nonempty, so we can detect |
| 1730 |
// rewind-fail) |
| 1731 |
goto PrescanSampleIds_ret_1; |
| 1732 |
} |
| 1733 |
goto PrescanSampleIds_ret_TSTREAM_FAIL; |
| 1734 |
} |
| 1735 |
is_header_line = (*line_iter == '#'); |
| 1736 |
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "OLD_FID")) && (!tokequal_k(&(line_iter[1]), "OLD_IID"))); |
| 1737 |
uint32_t old_fid_present = 0; |
| 1738 |
uint32_t old_sid_present = 0; |
| 1739 |
uint32_t new_fid_present = 0; |
| 1740 |
uint32_t new_sid_present = 0; |
| 1741 |
if (is_header_line) { |
| 1742 |
if (line_iter[5] == 'F') { |
| 1743 |
old_fid_present = 1; |
| 1744 |
line_iter = FirstNonTspace(&(line_iter[8])); |
| 1745 |
if (unlikely(!tokequal_k(line_iter, "OLD_IID"))) { |
| 1746 |
logerrputs("Error: Invalid --update-ids file (second header column must be OLD_IID when\nfirst is #OLD_FID).\n"); |
| 1747 |
goto PrescanSampleIds_ret_MALFORMED_INPUT; |
| 1748 |
} |
| 1749 |
} |
| 1750 |
line_iter = FirstNonTspace(CurTokenEnd(line_iter)); |
| 1751 |
if (tokequal_k(line_iter, "OLD_SID")) { |
| 1752 |
old_sid_present = 1; |
| 1753 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 1754 |
} |
| 1755 |
if (tokequal_k(line_iter, "NEW_FID")) { |
| 1756 |
new_fid_present = 1; |
| 1757 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 1758 |
} |
| 1759 |
if (unlikely(!tokequal_k(line_iter, "NEW_IID"))) { |
| 1760 |
logerrputs("Error: Invalid --update-ids file (no NEW_IID column in expected position).\n"); |
| 1761 |
goto PrescanSampleIds_ret_MALFORMED_INPUT; |
| 1762 |
} |
| 1763 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 1764 |
if (tokequal_k(line_iter, "NEW_SID")) { |
| 1765 |
new_sid_present = 1; |
| 1766 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 1767 |
} |
| 1768 |
if (unlikely(!IsSpaceOrEoln(*line_iter))) { |
| 1769 |
// Unlike --update-parents/--update-sex, there's no clear benefit to |
| 1770 |
// tolerating extra columns, so let's keep this simple. |
| 1771 |
logerrputs("Error: Invalid --update-ids file main header line (only permitted columns are\nOLD_FID, OLD_IID, OLD_SID, NEW_FID, NEW_IID, and NEW_SID, in that order).\n"); |
| 1772 |
goto PrescanSampleIds_ret_MALFORMED_INPUT; |
| 1773 |
} |
| 1774 |
} else { |
| 1775 |
const uint32_t token_ct = CountTokens(line_iter); |
| 1776 |
if (token_ct == 4) { |
| 1777 |
old_fid_present = 1; |
| 1778 |
new_fid_present = 1; |
| 1779 |
} else if (unlikely(token_ct != 2)) { |
| 1780 |
logerrputs("Error: Invalid --update-ids file (with no #OLD_FID or #OLD_IID header line, 2\nor 4 columns expected).\n"); |
| 1781 |
goto PrescanSampleIds_ret_MALFORMED_INPUT; |
| 1782 |
} |
| 1783 |
} |
| 1784 |
const uint32_t initial_skip_ct = 1 + old_fid_present + old_sid_present; |
| 1785 |
uintptr_t max_sample_id_blen = 0; |
| 1786 |
uintptr_t max_sid_blen = 0; |
| 1787 |
if (is_header_line) { |
| 1788 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 1789 |
++line_idx; |
| 1790 |
} |
| 1791 |
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 1792 |
line_iter = NextTokenMult(line_iter, initial_skip_ct); |
| 1793 |
if (unlikely(!line_iter)) { |
| 1794 |
goto PrescanSampleIds_ret_MISSING_TOKENS; |
| 1795 |
} |
| 1796 |
const char* id_start = line_iter; |
| 1797 |
line_iter = CurTokenEnd(id_start); |
| 1798 |
uintptr_t cur_sample_id_blen = 1 + S_CAST(uintptr_t, line_iter - id_start); |
| 1799 |
if (new_fid_present) { |
| 1800 |
const char* iid_start = FirstNonTspace(line_iter); |
| 1801 |
if (unlikely(IsEolnKns(*iid_start))) { |
| 1802 |
goto PrescanSampleIds_ret_MISSING_TOKENS; |
| 1803 |
} |
| 1804 |
line_iter = CurTokenEnd(iid_start); |
| 1805 |
cur_sample_id_blen += 1 + S_CAST(uintptr_t, line_iter - iid_start); |
| 1806 |
} else { |
| 1807 |
// bugfix (23 Sep 2020): forgot to add 2 for implicit FID=0 |
| 1808 |
cur_sample_id_blen += 2; |
| 1809 |
} |
| 1810 |
if (cur_sample_id_blen > max_sample_id_blen) { |
| 1811 |
max_sample_id_blen = cur_sample_id_blen; |
| 1812 |
} |
| 1813 |
if (new_sid_present) { |
| 1814 |
const char* sid_start = FirstNonTspace(line_iter); |
| 1815 |
if (unlikely(IsEolnKns(*sid_start))) { |
| 1816 |
goto PrescanSampleIds_ret_MISSING_TOKENS; |
| 1817 |
} |
| 1818 |
line_iter = CurTokenEnd(sid_start); |
| 1819 |
const uintptr_t sid_slen = line_iter - sid_start; |
| 1820 |
if (sid_slen >= max_sid_blen) { |
| 1821 |
max_sid_blen = sid_slen + 1; |
| 1822 |
} |
| 1823 |
} |
| 1824 |
if (unlikely(!IsEolnKns(*line_iter))) { |
| 1825 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-ids file has more tokens than expected.\n", line_idx); |
| 1826 |
goto PrescanSampleIds_ret_MALFORMED_INPUT_WW; |
| 1827 |
} |
| 1828 |
} |
| 1829 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 1830 |
goto PrescanSampleIds_ret_TSTREAM_FAIL; |
| 1831 |
} |
| 1832 |
reterr = kPglRetSuccess; |
| 1833 |
siip->max_sample_id_blen = max_sample_id_blen; |
| 1834 |
if (new_sid_present) { |
| 1835 |
siip->max_sid_blen = max_sid_blen; |
| 1836 |
} |
| 1837 |
} |
| 1838 |
while (0) { |
| 1839 |
PrescanSampleIds_ret_TSTREAM_FAIL: |
| 1840 |
TextStreamErrPrint("--update-ids file", &txs); |
| 1841 |
break; |
| 1842 |
PrescanSampleIds_ret_MISSING_TOKENS: |
| 1843 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-ids file has fewer tokens than expected.\n", line_idx); |
| 1844 |
PrescanSampleIds_ret_MALFORMED_INPUT_WW: |
| 1845 |
WordWrapB(0); |
| 1846 |
logerrputsb(); |
| 1847 |
PrescanSampleIds_ret_MALFORMED_INPUT: |
| 1848 |
reterr = kPglRetMalformedInput; |
| 1849 |
break; |
| 1850 |
} |
| 1851 |
PrescanSampleIds_ret_1: |
| 1852 |
CleanupTextStream2("--update-ids file", &txs, &reterr); |
| 1853 |
BigstackReset(bigstack_mark); |
| 1854 |
return reterr; |
| 1855 |
} |
| 1856 |
|
| 1857 |
PglErr PrescanParentalIds(const char* fname, uint32_t max_thread_ct, ParentalIdInfo* parental_id_infop) { |
| 1858 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1859 |
uintptr_t line_idx = 0; |
| 1860 |
PglErr reterr = kPglRetSuccess; |
| 1861 |
TextStream txs; |
| 1862 |
PreinitTextStream(&txs); |
| 1863 |
{ |
| 1864 |
reterr = ForceNonFifo(fname); |
| 1865 |
if (unlikely(reterr)) { |
| 1866 |
if (reterr == kPglRetOpenFail) { |
| 1867 |
logerrprintfww(kErrprintfFopen, "--update-parents file", strerror(errno)); |
| 1868 |
} else { |
| 1869 |
logerrprintfww(kErrprintfRewind, "--update-parents file"); |
| 1870 |
} |
| 1871 |
goto PrescanParentalIds_ret_1; |
| 1872 |
} |
| 1873 |
// don't use LoadXidHeader since we can ignore sample ID on this pass |
| 1874 |
// permit very long lines since this can be pointed at .ped files |
| 1875 |
// possible minor todo: could save longest line length for later reference |
| 1876 |
reterr = SizeAndInitTextStream(fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs); |
| 1877 |
if (unlikely(reterr)) { |
| 1878 |
goto PrescanParentalIds_ret_TSTREAM_FAIL; |
| 1879 |
} |
| 1880 |
|
| 1881 |
uint32_t is_header_line; |
| 1882 |
const char* line_iter; |
| 1883 |
do { |
| 1884 |
++line_idx; |
| 1885 |
line_iter = TextGet(&txs); |
| 1886 |
if (!line_iter) { |
| 1887 |
reterr = TextStreamRawErrcode(&txs); |
| 1888 |
if (likely(reterr == kPglRetEof)) { |
| 1889 |
// permit empty file here, but signal this to caller |
| 1890 |
// (reterr == kPglRetSuccess when file is nonempty, so we can detect |
| 1891 |
// rewind-fail) |
| 1892 |
goto PrescanParentalIds_ret_1; |
| 1893 |
} |
| 1894 |
goto PrescanParentalIds_ret_TSTREAM_FAIL; |
| 1895 |
} |
| 1896 |
is_header_line = (*line_iter == '#'); |
| 1897 |
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "FID")) && (!tokequal_k(&(line_iter[1]), "IID"))); |
| 1898 |
uint32_t pat_col_idx; |
| 1899 |
if (is_header_line) { |
| 1900 |
// Search for 'PAT' column. Require all-caps. |
| 1901 |
pat_col_idx = 0; |
| 1902 |
line_iter = &(line_iter[4]); |
| 1903 |
while (1) { |
| 1904 |
++pat_col_idx; |
| 1905 |
const char* token_start = FirstNonTspace(line_iter); |
| 1906 |
if (unlikely(IsEolnKns(*token_start))) { |
| 1907 |
logerrputs("Error: Invalid --update-parents file (no PAT column).\n"); |
| 1908 |
goto PrescanParentalIds_ret_MALFORMED_INPUT; |
| 1909 |
} |
| 1910 |
line_iter = CurTokenEnd(token_start); |
| 1911 |
if (strequal_k(token_start, "PAT", line_iter - token_start)) { |
| 1912 |
break; |
| 1913 |
} |
| 1914 |
} |
| 1915 |
// Require immediately-following column to be 'MAT'. |
| 1916 |
const char* token_start = FirstNonTspace(line_iter); |
| 1917 |
line_iter = FirstSpaceOrEoln(token_start); |
| 1918 |
if (unlikely(!strequal_k(token_start, "MAT", line_iter - token_start))) { |
| 1919 |
logerrputs("Error: Invalid --update-parents file (no MAT column immediately following PAT\ncolumn).\n"); |
| 1920 |
goto PrescanParentalIds_ret_MALFORMED_INPUT; |
| 1921 |
} |
| 1922 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 1923 |
++line_idx; |
| 1924 |
} else { |
| 1925 |
const uint32_t token_ct = CountTokens(line_iter); |
| 1926 |
if (unlikely(token_ct < 3)) { |
| 1927 |
logerrputs("Error: Invalid --update-parents file (3+ columns expected).\n"); |
| 1928 |
goto PrescanParentalIds_ret_MALFORMED_INPUT; |
| 1929 |
} |
| 1930 |
pat_col_idx = (token_ct == 3)? 1 : 2; |
| 1931 |
} |
| 1932 |
uintptr_t max_paternal_id_blen = 0; |
| 1933 |
uintptr_t max_maternal_id_blen = 0; |
| 1934 |
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 1935 |
line_iter = NextTokenMult(line_iter, pat_col_idx); |
| 1936 |
if (unlikely(!line_iter)) { |
| 1937 |
goto PrescanParentalIds_ret_MISSING_TOKENS; |
| 1938 |
} |
| 1939 |
const char* pat_start = line_iter; |
| 1940 |
line_iter = CurTokenEnd(pat_start); |
| 1941 |
const uintptr_t cur_paternal_id_slen = line_iter - pat_start; |
| 1942 |
if (cur_paternal_id_slen >= max_paternal_id_blen) { |
| 1943 |
max_paternal_id_blen = cur_paternal_id_slen + 1; |
| 1944 |
} |
| 1945 |
const char* mat_start = FirstNonTspace(line_iter); |
| 1946 |
if (unlikely(IsEolnKns(*mat_start))) { |
| 1947 |
goto PrescanParentalIds_ret_MISSING_TOKENS; |
| 1948 |
} |
| 1949 |
line_iter = CurTokenEnd(mat_start); |
| 1950 |
uintptr_t cur_maternal_id_slen = line_iter - mat_start; |
| 1951 |
if (cur_maternal_id_slen >= max_maternal_id_blen) { |
| 1952 |
max_maternal_id_blen = cur_maternal_id_slen + 1; |
| 1953 |
} |
| 1954 |
} |
| 1955 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 1956 |
goto PrescanParentalIds_ret_TSTREAM_FAIL; |
| 1957 |
} |
| 1958 |
reterr = kPglRetSuccess; |
| 1959 |
parental_id_infop->max_paternal_id_blen = max_paternal_id_blen; |
| 1960 |
parental_id_infop->max_maternal_id_blen = max_maternal_id_blen; |
| 1961 |
} |
| 1962 |
while (0) { |
| 1963 |
PrescanParentalIds_ret_TSTREAM_FAIL: |
| 1964 |
TextStreamErrPrint("--update-parents file", &txs); |
| 1965 |
break; |
| 1966 |
PrescanParentalIds_ret_MISSING_TOKENS: |
| 1967 |
snprintf(g_logbuf, kLogbufSize, "Error: Line %" PRIuPTR " of --update-parents file has fewer tokens than expected.\n", line_idx); |
| 1968 |
WordWrapB(0); |
| 1969 |
logerrputsb(); |
| 1970 |
PrescanParentalIds_ret_MALFORMED_INPUT: |
| 1971 |
reterr = kPglRetMalformedInput; |
| 1972 |
break; |
| 1973 |
} |
| 1974 |
PrescanParentalIds_ret_1: |
| 1975 |
CleanupTextStream2("--update-parents file", &txs, &reterr); |
| 1976 |
BigstackReset(bigstack_mark); |
| 1977 |
return reterr; |
| 1978 |
} |
| 1979 |
|
| 1980 |
PglErr UpdateSampleIds(const char* fname, const uintptr_t* sample_include, uint32_t raw_sample_ct, uintptr_t sample_ct, SampleIdInfo* siip) { |
| 1981 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 1982 |
uintptr_t line_idx = 0; |
| 1983 |
PglErr reterr = kPglRetSuccess; |
| 1984 |
TextStream txs; |
| 1985 |
PreinitTextStream(&txs); |
| 1986 |
{ |
| 1987 |
if (!sample_ct) { |
| 1988 |
goto UpdateSampleIds_ret_1; |
| 1989 |
} |
| 1990 |
// probable todo: deduplicate shared code with PrescanSampleIds |
| 1991 |
reterr = InitTextStream(fname, kTextStreamBlenFast, 1, &txs); |
| 1992 |
if (unlikely(reterr)) { |
| 1993 |
goto UpdateSampleIds_ret_TSTREAM_FAIL; |
| 1994 |
} |
| 1995 |
const char* line_iter; |
| 1996 |
uint32_t is_header_line; |
| 1997 |
do { |
| 1998 |
++line_idx; |
| 1999 |
line_iter = TextGet(&txs); |
| 2000 |
if (unlikely(!line_iter)) { |
| 2001 |
reterr = TextStreamRawErrcode(&txs); |
| 2002 |
// This function is no longer called when the original file is empty. |
| 2003 |
goto UpdateSampleIds_ret_TSTREAM_FAIL; |
| 2004 |
} |
| 2005 |
is_header_line = (*line_iter == '#'); |
| 2006 |
} while (is_header_line && (!tokequal_k(&(line_iter[1]), "OLD_FID")) && (!tokequal_k(&(line_iter[1]), "OLD_IID"))); |
| 2007 |
uint32_t old_fid_present = 0; |
| 2008 |
uint32_t old_sid_present = 0; |
| 2009 |
uint32_t new_fid_present = 0; |
| 2010 |
uint32_t new_sid_present = 0; |
| 2011 |
if (is_header_line) { |
| 2012 |
if (line_iter[5] == 'F') { |
| 2013 |
old_fid_present = 1; |
| 2014 |
line_iter = FirstNonTspace(&(line_iter[8])); |
| 2015 |
if (unlikely(!tokequal_k(line_iter, "OLD_IID"))) { |
| 2016 |
goto UpdateSampleIds_ret_REWIND_FAIL; |
| 2017 |
} |
| 2018 |
} |
| 2019 |
line_iter = FirstNonTspace(CurTokenEnd(line_iter)); |
| 2020 |
if (tokequal_k(line_iter, "OLD_SID")) { |
| 2021 |
old_sid_present = 1; |
| 2022 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 2023 |
} |
| 2024 |
if (tokequal_k(line_iter, "NEW_FID")) { |
| 2025 |
new_fid_present = 1; |
| 2026 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 2027 |
} |
| 2028 |
if (unlikely(!tokequal_k(line_iter, "NEW_IID"))) { |
| 2029 |
goto UpdateSampleIds_ret_REWIND_FAIL; |
| 2030 |
} |
| 2031 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 2032 |
if (tokequal_k(line_iter, "NEW_SID")) { |
| 2033 |
new_sid_present = 1; |
| 2034 |
line_iter = FirstNonTspace(&(line_iter[7])); |
| 2035 |
} |
| 2036 |
if (unlikely(!IsSpaceOrEoln(*line_iter))) { |
| 2037 |
goto UpdateSampleIds_ret_REWIND_FAIL; |
| 2038 |
} |
| 2039 |
} else { |
| 2040 |
const uint32_t token_ct = CountTokens(line_iter); |
| 2041 |
if (token_ct == 4) { |
| 2042 |
old_fid_present = 1; |
| 2043 |
new_fid_present = 1; |
| 2044 |
} else if (unlikely(token_ct != 2)) { |
| 2045 |
goto UpdateSampleIds_ret_REWIND_FAIL; |
| 2046 |
} |
| 2047 |
} |
| 2048 |
XidMode xid_mode; |
| 2049 |
if (old_fid_present) { |
| 2050 |
xid_mode = old_sid_present? kfXidModeFidIidSid : kfXidModeFidIid; |
| 2051 |
} else { |
| 2052 |
xid_mode = old_sid_present? kfXidModeIidSid : kfXidModeIid; |
| 2053 |
} |
| 2054 |
if (new_fid_present) { |
| 2055 |
// bugfix (14 Jan 2021) |
| 2056 |
siip->flags |= kfSampleIdFidPresent; |
| 2057 |
} |
| 2058 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 2059 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 2060 |
uint32_t* xid_map = nullptr; |
| 2061 |
char* sorted_xidbox = nullptr; |
| 2062 |
uintptr_t max_xid_blen; |
| 2063 |
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 2064 |
if (unlikely(reterr)) { |
| 2065 |
goto UpdateSampleIds_ret_1; |
| 2066 |
} |
| 2067 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 2068 |
uintptr_t* already_seen; |
| 2069 |
char* idbuf; |
| 2070 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) || |
| 2071 |
bigstack_alloc_c(max_xid_blen, &idbuf))) { |
| 2072 |
goto UpdateSampleIds_ret_NOMEM; |
| 2073 |
} |
| 2074 |
uint32_t hit_ct = 0; |
| 2075 |
uintptr_t miss_ct = 0; |
| 2076 |
if (is_header_line) { |
| 2077 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 2078 |
++line_idx; |
| 2079 |
} |
| 2080 |
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 2081 |
const char* linebuf_iter = line_iter; |
| 2082 |
uint32_t xid_idx; |
| 2083 |
uint32_t xid_idx_end; |
| 2084 |
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx, &xid_idx_end, idbuf)) { |
| 2085 |
if (unlikely(!linebuf_iter)) { |
| 2086 |
goto UpdateSampleIds_ret_REWIND_FAIL; |
| 2087 |
} |
| 2088 |
++miss_ct; |
| 2089 |
continue; |
| 2090 |
} |
| 2091 |
uint32_t sample_uidx = xid_map[xid_idx]; |
| 2092 |
if (unlikely(IsSet(already_seen, sample_uidx))) { |
| 2093 |
// possible todo: tolerate duplicates if payload matches, like |
| 2094 |
// --update-sex does |
| 2095 |
logerrprintfww("Error: Sample ID on line %" PRIuPTR " of --update-ids file duplicates one earlier in the file.\n", line_idx); |
| 2096 |
goto UpdateSampleIds_ret_MALFORMED_INPUT; |
| 2097 |
} |
| 2098 |
SetBit(sample_uidx, already_seen); |
| 2099 |
char* new_sample_id = &(siip->sample_ids[sample_uidx * max_sample_id_blen]); |
| 2100 |
char* new_sample_id_iter = new_sample_id; |
| 2101 |
if (new_fid_present) { |
| 2102 |
const char* sample_id_start = FirstNonTspace(linebuf_iter); |
| 2103 |
linebuf_iter = CurTokenEnd(sample_id_start); |
| 2104 |
new_sample_id_iter = memcpya(new_sample_id_iter, sample_id_start, linebuf_iter - sample_id_start); |
| 2105 |
} else { |
| 2106 |
*new_sample_id_iter++ = '0'; |
| 2107 |
} |
| 2108 |
*new_sample_id_iter++ = '\t'; |
| 2109 |
const char* iid_start = FirstNonTspace(linebuf_iter); |
| 2110 |
linebuf_iter = CurTokenEnd(iid_start); |
| 2111 |
new_sample_id_iter = memcpyax(new_sample_id_iter, iid_start, linebuf_iter - iid_start, '\0'); |
| 2112 |
char* new_sid = nullptr; |
| 2113 |
uint32_t new_sid_blen = 0; |
| 2114 |
if (new_sid_present) { |
| 2115 |
new_sid = &(siip->sids[sample_uidx * max_sid_blen]); |
| 2116 |
const char* sid_start = FirstNonTspace(linebuf_iter); |
| 2117 |
linebuf_iter = CurTokenEnd(sid_start); |
| 2118 |
const uint32_t new_sid_slen = linebuf_iter - sid_start; |
| 2119 |
memcpyx(new_sid, sid_start, new_sid_slen, '\0'); |
| 2120 |
new_sid_blen = new_sid_slen + 1; |
| 2121 |
} |
| 2122 |
line_iter = linebuf_iter; |
| 2123 |
hit_ct += xid_idx_end - xid_idx; |
| 2124 |
if (++xid_idx != xid_idx_end) { |
| 2125 |
uintptr_t new_sample_id_blen = new_sample_id_iter - new_sample_id; |
| 2126 |
do { |
| 2127 |
sample_uidx = xid_map[xid_idx]; |
| 2128 |
memcpy(&(siip->sample_ids[sample_uidx * max_sample_id_blen]), new_sample_id, new_sample_id_blen); |
| 2129 |
if (new_sid) { |
| 2130 |
// now possible since NEW_SID may be present without OLD_SID |
| 2131 |
memcpy(&(siip->sids[sample_uidx * max_sid_blen]), new_sid, new_sid_blen); |
| 2132 |
} |
| 2133 |
} while (++xid_idx != xid_idx_end); |
| 2134 |
} |
| 2135 |
} |
| 2136 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 2137 |
goto UpdateSampleIds_ret_TSTREAM_FAIL; |
| 2138 |
} |
| 2139 |
if (miss_ct) { |
| 2140 |
snprintf(g_logbuf, kLogbufSize, "--update-ids: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 2141 |
} else { |
| 2142 |
snprintf(g_logbuf, kLogbufSize, "--update-ids: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 2143 |
} |
| 2144 |
logputsb(); |
| 2145 |
reterr = CheckXidUniqueness(sample_include, siip, " from --update-ids", sample_ct); |
| 2146 |
if (unlikely(reterr)) { |
| 2147 |
goto UpdateSampleIds_ret_1; |
| 2148 |
} |
| 2149 |
} |
| 2150 |
while (0) { |
| 2151 |
UpdateSampleIds_ret_NOMEM: |
| 2152 |
reterr = kPglRetNomem; |
| 2153 |
break; |
| 2154 |
UpdateSampleIds_ret_TSTREAM_FAIL: |
| 2155 |
TextStreamErrPrint("--update-ids file", &txs); |
| 2156 |
break; |
| 2157 |
UpdateSampleIds_ret_REWIND_FAIL: |
| 2158 |
logerrprintfww(kErrprintfRewind, "--update-ids file"); |
| 2159 |
reterr = kPglRetRewindFail; |
| 2160 |
break; |
| 2161 |
UpdateSampleIds_ret_MALFORMED_INPUT: |
| 2162 |
reterr = kPglRetMalformedInput; |
| 2163 |
break; |
| 2164 |
} |
| 2165 |
UpdateSampleIds_ret_1: |
| 2166 |
CleanupTextStream2("--update-ids file", &txs, &reterr); |
| 2167 |
BigstackReset(bigstack_mark); |
| 2168 |
return reterr; |
| 2169 |
} |
| 2170 |
|
| 2171 |
PglErr UpdateSampleParents(const char* fname, const SampleIdInfo* siip, const uintptr_t* sample_include, uint32_t raw_sample_ct, uintptr_t sample_ct, uint32_t max_thread_ct, ParentalIdInfo* parental_id_infop, uintptr_t* founder_info) { |
| 2172 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 2173 |
uintptr_t line_idx = 0; |
| 2174 |
PglErr reterr = kPglRetSuccess; |
| 2175 |
TextStream txs; |
| 2176 |
PreinitTextStream(&txs); |
| 2177 |
{ |
| 2178 |
if (!sample_ct) { |
| 2179 |
goto UpdateSampleParents_ret_1; |
| 2180 |
} |
| 2181 |
// permit very long lines since this can be pointed at .ped files |
| 2182 |
reterr = SizeAndInitTextStream(fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs); |
| 2183 |
if (unlikely(reterr)) { |
| 2184 |
goto UpdateSampleParents_ret_TSTREAM_FAIL; |
| 2185 |
} |
| 2186 |
|
| 2187 |
const char* line_iter; |
| 2188 |
XidMode xid_mode; |
| 2189 |
{ |
| 2190 |
char* line_start; |
| 2191 |
reterr = LoadXidHeader("update-parents", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeader0 : kfXidHeaderIgnoreSid, &line_idx, &txs, &xid_mode, &line_start); |
| 2192 |
if (unlikely(reterr)) { |
| 2193 |
if (reterr == kPglRetEof) { |
| 2194 |
goto UpdateSampleParents_ret_REWIND_FAIL; |
| 2195 |
} |
| 2196 |
goto UpdateSampleParents_ret_TSTREAM_XID_FAIL; |
| 2197 |
} |
| 2198 |
line_iter = line_start; |
| 2199 |
} |
| 2200 |
uint32_t postid_pat_col_idx = 1; |
| 2201 |
if (*line_iter == '#') { |
| 2202 |
const uint32_t id_col_ct = GetXidColCt(xid_mode); |
| 2203 |
const char* token_end = CurTokenEnd(NextTokenMult0(line_iter, id_col_ct - 1)); |
| 2204 |
while (1) { |
| 2205 |
const char* token_start = FirstNonTspace(token_end); |
| 2206 |
if (unlikely(IsEolnKns(*token_start))) { |
| 2207 |
goto UpdateSampleParents_ret_REWIND_FAIL; |
| 2208 |
} |
| 2209 |
token_end = CurTokenEnd(token_start); |
| 2210 |
if (strequal_k(token_start, "PAT", token_end - token_start)) { |
| 2211 |
break; |
| 2212 |
} |
| 2213 |
++postid_pat_col_idx; |
| 2214 |
} |
| 2215 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 2216 |
++line_idx; |
| 2217 |
} else { |
| 2218 |
const uint32_t token_ct = CountTokens(line_iter); |
| 2219 |
if (unlikely(token_ct < 3)) { |
| 2220 |
goto UpdateSampleParents_ret_REWIND_FAIL; |
| 2221 |
} |
| 2222 |
xid_mode = (token_ct == 3)? kfXidModeIid : kfXidModeFidIid; |
| 2223 |
} |
| 2224 |
|
| 2225 |
uint32_t* xid_map = nullptr; |
| 2226 |
char* sorted_xidbox = nullptr; |
| 2227 |
uintptr_t max_xid_blen; |
| 2228 |
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 2229 |
if (unlikely(reterr)) { |
| 2230 |
goto UpdateSampleParents_ret_1; |
| 2231 |
} |
| 2232 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 2233 |
uintptr_t* already_seen; |
| 2234 |
char* idbuf; |
| 2235 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) || |
| 2236 |
bigstack_alloc_c(max_xid_blen, &idbuf))) { |
| 2237 |
goto UpdateSampleParents_ret_NOMEM; |
| 2238 |
} |
| 2239 |
const uintptr_t max_paternal_id_blen = parental_id_infop->max_paternal_id_blen; |
| 2240 |
const uintptr_t max_maternal_id_blen = parental_id_infop->max_maternal_id_blen; |
| 2241 |
char* paternal_ids = parental_id_infop->paternal_ids; |
| 2242 |
char* maternal_ids = parental_id_infop->maternal_ids; |
| 2243 |
uint32_t hit_ct = 0; |
| 2244 |
uintptr_t miss_ct = 0; |
| 2245 |
for (; TextGetUnsafe2K(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 2246 |
const char* linebuf_iter = line_iter; |
| 2247 |
uint32_t xid_idx; |
| 2248 |
uint32_t xid_idx_end; |
| 2249 |
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx, &xid_idx_end, idbuf)) { |
| 2250 |
if (unlikely(!linebuf_iter)) { |
| 2251 |
goto UpdateSampleParents_ret_REWIND_FAIL; |
| 2252 |
} |
| 2253 |
++miss_ct; |
| 2254 |
continue; |
| 2255 |
} |
| 2256 |
uint32_t sample_uidx = xid_map[xid_idx]; |
| 2257 |
if (unlikely(IsSet(already_seen, sample_uidx))) { |
| 2258 |
// possible todo: tolerate duplicates if payload matches, like |
| 2259 |
// --update-sex does |
| 2260 |
logerrprintfww("Error: Sample ID on line %" PRIuPTR " of --update-parents file duplicates one earlier in the file.\n", line_idx); |
| 2261 |
goto UpdateSampleParents_ret_MALFORMED_INPUT; |
| 2262 |
} |
| 2263 |
SetBit(sample_uidx, already_seen); |
| 2264 |
const char* pat_start = NextTokenMult(linebuf_iter, postid_pat_col_idx); |
| 2265 |
const char* pat_end = CurTokenEnd(pat_start); |
| 2266 |
const char* mat_start = FirstNonTspace(pat_end); |
| 2267 |
line_iter = CurTokenEnd(mat_start); |
| 2268 |
const uint32_t plen = pat_end - pat_start; |
| 2269 |
const uint32_t mlen = line_iter - mat_start; |
| 2270 |
const uint32_t is_founder = (plen == 1) && (*pat_start == '0') && (mlen == 1) && (*mat_start == '0'); |
| 2271 |
hit_ct += xid_idx_end - xid_idx; |
| 2272 |
while (1) { |
| 2273 |
memcpyx(&(paternal_ids[sample_uidx * max_paternal_id_blen]), pat_start, plen, '\0'); |
| 2274 |
memcpyx(&(maternal_ids[sample_uidx * max_maternal_id_blen]), mat_start, mlen, '\0'); |
| 2275 |
AssignBit(sample_uidx, is_founder, founder_info); |
| 2276 |
if (++xid_idx == xid_idx_end) { |
| 2277 |
break; |
| 2278 |
} |
| 2279 |
sample_uidx = xid_map[xid_idx]; |
| 2280 |
} |
| 2281 |
} |
| 2282 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 2283 |
goto UpdateSampleParents_ret_REWIND_FAIL; |
| 2284 |
} |
| 2285 |
reterr = kPglRetSuccess; |
| 2286 |
if (miss_ct) { |
| 2287 |
snprintf(g_logbuf, kLogbufSize, "--update-parents: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 2288 |
} else { |
| 2289 |
snprintf(g_logbuf, kLogbufSize, "--update-parents: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 2290 |
} |
| 2291 |
logputsb(); |
| 2292 |
} |
| 2293 |
while (0) { |
| 2294 |
UpdateSampleParents_ret_NOMEM: |
| 2295 |
reterr = kPglRetNomem; |
| 2296 |
break; |
| 2297 |
UpdateSampleParents_ret_TSTREAM_XID_FAIL: |
| 2298 |
if (!TextStreamErrcode(&txs)) { |
| 2299 |
break; |
| 2300 |
} |
| 2301 |
UpdateSampleParents_ret_TSTREAM_FAIL: |
| 2302 |
TextStreamErrPrint("--update-parents file", &txs); |
| 2303 |
break; |
| 2304 |
UpdateSampleParents_ret_REWIND_FAIL: |
| 2305 |
logerrprintfww(kErrprintfRewind, "--update-parents file"); |
| 2306 |
reterr = kPglRetRewindFail; |
| 2307 |
break; |
| 2308 |
UpdateSampleParents_ret_MALFORMED_INPUT: |
| 2309 |
reterr = kPglRetMalformedInput; |
| 2310 |
break; |
| 2311 |
} |
| 2312 |
UpdateSampleParents_ret_1: |
| 2313 |
CleanupTextStream2("--update-parents file", &txs, &reterr); |
| 2314 |
BigstackReset(bigstack_mark); |
| 2315 |
return reterr; |
| 2316 |
} |
| 2317 |
|
| 2318 |
PglErr UpdateSampleSexes(const uintptr_t* sample_include, const SampleIdInfo* siip, const UpdateSexInfo* update_sex_info_ptr, uint32_t raw_sample_ct, uintptr_t sample_ct, uint32_t max_thread_ct, uintptr_t* sex_nm, uintptr_t* sex_male) { |
| 2319 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 2320 |
uintptr_t line_idx = 0; |
| 2321 |
PglErr reterr = kPglRetSuccess; |
| 2322 |
TextStream txs; |
| 2323 |
PreinitTextStream(&txs); |
| 2324 |
{ |
| 2325 |
if (!sample_ct) { |
| 2326 |
goto UpdateSampleSexes_ret_1; |
| 2327 |
} |
| 2328 |
// permit very long lines since this can be pointed at .ped files |
| 2329 |
reterr = SizeAndInitTextStream(update_sex_info_ptr->fname, bigstack_left() - (bigstack_left() / 4), MAXV(max_thread_ct - 1, 1), &txs); |
| 2330 |
if (unlikely(reterr)) { |
| 2331 |
goto UpdateSampleSexes_ret_TSTREAM_FAIL; |
| 2332 |
} |
| 2333 |
|
| 2334 |
// (Much of this boilerplate is shared with e.g. KeepColMatch(); it |
| 2335 |
// probably belongs in its own function.) |
| 2336 |
char* line_start; |
| 2337 |
XidMode xid_mode; |
| 2338 |
reterr = LoadXidHeader("update-sex", (siip->sids || (siip->flags & kfSampleIdStrictSid0))? kfXidHeaderFixedWidth : kfXidHeaderFixedWidthIgnoreSid, &line_idx, &txs, &xid_mode, &line_start); |
| 2339 |
if (reterr) { |
| 2340 |
if (likely(reterr == kPglRetEof)) { |
| 2341 |
reterr = kPglRetSuccess; |
| 2342 |
logputs("--update-sex: 0 samples updated.\n"); |
| 2343 |
goto UpdateSampleSexes_ret_1; |
| 2344 |
} |
| 2345 |
goto UpdateSampleSexes_ret_TSTREAM_XID_FAIL; |
| 2346 |
} |
| 2347 |
const uint32_t id_col_ct = GetXidColCt(xid_mode); |
| 2348 |
uint32_t col_num = update_sex_info_ptr->col_num; |
| 2349 |
uint32_t postid_col_idx = 0; |
| 2350 |
if ((*line_start == '#') && (!col_num)) { |
| 2351 |
// search for 'SEX' column (any capitalization) |
| 2352 |
const char* token_end = CurTokenEnd(NextTokenMult0(line_start, id_col_ct - 1)); |
| 2353 |
while (1) { |
| 2354 |
++postid_col_idx; |
| 2355 |
const char* linebuf_iter = FirstNonTspace(token_end); |
| 2356 |
if (unlikely(IsEolnKns(*linebuf_iter))) { |
| 2357 |
logerrputs("Error: No 'SEX' column in --update-sex file, and no column number specified.\n"); |
| 2358 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT; |
| 2359 |
} |
| 2360 |
token_end = CurTokenEnd(linebuf_iter); |
| 2361 |
if (MatchUpperKLen(linebuf_iter, "SEX", token_end - linebuf_iter)) { |
| 2362 |
break; |
| 2363 |
} |
| 2364 |
} |
| 2365 |
} else { |
| 2366 |
if (!col_num) { |
| 2367 |
if (unlikely(id_col_ct == 3)) { |
| 2368 |
logerrputs("Error: You must use 'col-num=' to specify the position of the sex column in the\n--update-sex file.\n"); |
| 2369 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT; |
| 2370 |
} |
| 2371 |
col_num = 3; |
| 2372 |
} |
| 2373 |
if (unlikely(id_col_ct >= col_num)) { |
| 2374 |
logerrputs("Error: --update-sex 'col-num=' argument too small (it refers to a sample ID\ncolumn).\n"); |
| 2375 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT; |
| 2376 |
} |
| 2377 |
postid_col_idx = col_num - id_col_ct; |
| 2378 |
} |
| 2379 |
|
| 2380 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 2381 |
uint32_t* xid_map = nullptr; |
| 2382 |
char* sorted_xidbox = nullptr; |
| 2383 |
uintptr_t max_xid_blen; |
| 2384 |
reterr = SortedXidboxInitAlloc(sample_include, siip, sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 2385 |
if (unlikely(reterr)) { |
| 2386 |
goto UpdateSampleSexes_ret_1; |
| 2387 |
} |
| 2388 |
uintptr_t* already_seen; |
| 2389 |
char* idbuf; |
| 2390 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &already_seen) || |
| 2391 |
bigstack_alloc_c(max_xid_blen, &idbuf))) { |
| 2392 |
goto UpdateSampleSexes_ret_NOMEM; |
| 2393 |
} |
| 2394 |
|
| 2395 |
const uint32_t male0 = (update_sex_info_ptr->flags / kfUpdateSexMale0) & 1; |
| 2396 |
uint32_t hit_ct = 0; |
| 2397 |
uintptr_t miss_ct = 0; |
| 2398 |
uintptr_t duplicate_ct = 0; |
| 2399 |
if (*line_start == '#') { |
| 2400 |
++line_idx; |
| 2401 |
line_start = TextGet(&txs); |
| 2402 |
} |
| 2403 |
for (; line_start; ++line_idx, line_start = TextGet(&txs)) { |
| 2404 |
const char* linebuf_iter = line_start; |
| 2405 |
uint32_t xid_idx_start; |
| 2406 |
uint32_t xid_idx_end; |
| 2407 |
if (SortedXidboxReadMultifind(sorted_xidbox, max_xid_blen, sample_ct, 0, xid_mode, &linebuf_iter, &xid_idx_start, &xid_idx_end, idbuf)) { |
| 2408 |
if (unlikely(!linebuf_iter)) { |
| 2409 |
goto UpdateSampleSexes_ret_MISSING_TOKENS; |
| 2410 |
} |
| 2411 |
++miss_ct; |
| 2412 |
continue; |
| 2413 |
} |
| 2414 |
const char* sex_start = NextTokenMult(linebuf_iter, postid_col_idx); |
| 2415 |
if (unlikely(!sex_start)) { |
| 2416 |
goto UpdateSampleSexes_ret_MISSING_TOKENS; |
| 2417 |
} |
| 2418 |
uint32_t sexval = ctou32(*sex_start); |
| 2419 |
const uint32_t ujj = sexval & 0xdfU; |
| 2420 |
sexval -= 48; |
| 2421 |
if (sexval > 2) { |
| 2422 |
if (ujj == 77) { |
| 2423 |
// 'M'/'m' |
| 2424 |
sexval = 1; |
| 2425 |
} else if (ujj == 70) { |
| 2426 |
// 'F'/'f' |
| 2427 |
sexval = 2; |
| 2428 |
} else if (unlikely((!male0) && (sexval != 30) && (ujj != 85))) { |
| 2429 |
// allow 'N' = missing to make 1/2/NA work |
| 2430 |
// allow 'U'/'u' since this is actually being used by Illumina |
| 2431 |
// GenCall and Affymetrix APT |
| 2432 |
// don't permit 'n' for now |
| 2433 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid sex value on line %" PRIuPTR " of --update-sex file. (Acceptable values: 1/M/m = male, 2/F/f = female, 0/N/U = missing.)\n", line_idx); |
| 2434 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW; |
| 2435 |
} else { |
| 2436 |
// with 'male0', everything else is treated as missing |
| 2437 |
sexval = 0; |
| 2438 |
} |
| 2439 |
} else if (male0) { |
| 2440 |
if (unlikely(sexval == 2)) { |
| 2441 |
snprintf(g_logbuf, kLogbufSize, "Error: Invalid sex value on line %" PRIuPTR " of --update-sex file. ('2' is prohibited when the 'male0' modifier is present.)\n", line_idx); |
| 2442 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW; |
| 2443 |
} |
| 2444 |
++sexval; |
| 2445 |
} |
| 2446 |
uint32_t sample_uidx = xid_map[xid_idx_start]; |
| 2447 |
if (IsSet(already_seen, sample_uidx)) { |
| 2448 |
// permit duplicates iff sex value is identical |
| 2449 |
const uint32_t old_sexval = IsSet(sex_nm, sample_uidx) * (2 - IsSet(sex_male, sample_uidx)); |
| 2450 |
if (unlikely(sexval != old_sexval)) { |
| 2451 |
snprintf(g_logbuf, kLogbufSize, "Error: Sample ID on line %" PRIuPTR " of --update-sex file duplicates one earlier in the file, and sex values don't match.\n", line_idx); |
| 2452 |
goto UpdateSampleSexes_ret_MALFORMED_INPUT_WW; |
| 2453 |
} |
| 2454 |
++duplicate_ct; |
| 2455 |
continue; |
| 2456 |
} |
| 2457 |
SetBit(sample_uidx, already_seen); |
| 2458 |
hit_ct += xid_idx_end - xid_idx_start; |
| 2459 |
for (uint32_t xid_idx = xid_idx_start; ; sample_uidx = xid_map[xid_idx]) { |
| 2460 |
if (sexval) { |
| 2461 |
SetBit(sample_uidx, sex_nm); |
| 2462 |
if (sexval == 1) { |
| 2463 |
SetBit(sample_uidx, sex_male); |
| 2464 |
} else { |
| 2465 |
ClearBit(sample_uidx, sex_male); |
| 2466 |
} |
| 2467 |
} else { |
| 2468 |
ClearBit(sample_uidx, sex_nm); |
| 2469 |
ClearBit(sample_uidx, sex_male); |
| 2470 |
} |
| 2471 |
if (++xid_idx == xid_idx_end) { |
| 2472 |
break; |
| 2473 |
} |
| 2474 |
} |
| 2475 |
} |
| 2476 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 2477 |
goto UpdateSampleSexes_ret_TSTREAM_FAIL; |
| 2478 |
} |
| 2479 |
if (duplicate_ct) { |
| 2480 |
logprintfww("Note: %" PRIuPTR " duplicate sample ID%s) in --update-sex file.\n", duplicate_ct, (duplicate_ct == 1)? " (with a consistent sex assignment" : "s (with consistent sex assignments"); |
| 2481 |
} |
| 2482 |
if (miss_ct) { |
| 2483 |
snprintf(g_logbuf, kLogbufSize, "--update-sex: %u sample%s updated, %" PRIuPTR " ID%s not present.\n", hit_ct, (hit_ct == 1)? "" : "s", miss_ct, (miss_ct == 1)? "" : "s"); |
| 2484 |
} else { |
| 2485 |
snprintf(g_logbuf, kLogbufSize, "--update-sex: %u sample%s updated.\n", hit_ct, (hit_ct == 1)? "" : "s"); |
| 2486 |
} |
| 2487 |
logputsb(); |
| 2488 |
} |
| 2489 |
while (0) { |
| 2490 |
UpdateSampleSexes_ret_TSTREAM_XID_FAIL: |
| 2491 |
if (!TextStreamErrcode(&txs)) { |
| 2492 |
break; |
| 2493 |
} |
| 2494 |
UpdateSampleSexes_ret_TSTREAM_FAIL: |
| 2495 |
TextStreamErrPrint("--update-sex file", &txs); |
| 2496 |
break; |
| 2497 |
UpdateSampleSexes_ret_NOMEM: |
| 2498 |
reterr = kPglRetNomem; |
| 2499 |
break; |
| 2500 |
UpdateSampleSexes_ret_MALFORMED_INPUT_WW: |
| 2501 |
WordWrapB(0); |
| 2502 |
logerrputsb(); |
| 2503 |
UpdateSampleSexes_ret_MALFORMED_INPUT: |
| 2504 |
reterr = kPglRetMalformedInput; |
| 2505 |
break; |
| 2506 |
UpdateSampleSexes_ret_MISSING_TOKENS: |
| 2507 |
logerrprintf("Error: Line %" PRIuPTR " of --update-sex file has fewer tokens than expected.\n", line_idx); |
| 2508 |
reterr = kPglRetMalformedInput; |
| 2509 |
break; |
| 2510 |
} |
| 2511 |
UpdateSampleSexes_ret_1: |
| 2512 |
CleanupTextStream2("--update-sex file", &txs, &reterr); |
| 2513 |
BigstackReset(bigstack_mark); |
| 2514 |
return reterr; |
| 2515 |
} |
| 2516 |
|
| 2517 |
PglErr SplitCatPheno(const char* split_cat_phenonames_flattened, const uintptr_t* sample_include, uint32_t raw_sample_ct, PhenoTransformFlags pheno_transform_flags, PhenoCol** pheno_cols_ptr, char** pheno_names_ptr, uint32_t* pheno_ct_ptr, uintptr_t* max_pheno_name_blen_ptr, PhenoCol** covar_cols_ptr, char** covar_names_ptr, uint32_t* covar_ct_ptr, uintptr_t* max_covar_name_blen_ptr) { |
| 2518 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 2519 |
const char* doomed_pheno_names = nullptr; |
| 2520 |
PhenoCol* doomed_pheno_cols = nullptr; |
| 2521 |
uint32_t doomed_pheno_ct = 0; |
| 2522 |
PglErr reterr = kPglRetSuccess; |
| 2523 |
{ |
| 2524 |
const uint32_t is_omit = ((pheno_transform_flags & (kfPhenoTransformSplitCatOmitMost | kfPhenoTransformSplitCatOmitLast)) != 0); |
| 2525 |
const uint32_t omit_most = (pheno_transform_flags / kfPhenoTransformSplitCatOmitMost) & 1; |
| 2526 |
uint32_t qt_12 = 0; |
| 2527 |
uint32_t at_least_one_cat_pheno_processed = 0; |
| 2528 |
for (uint32_t is_covar = 0; is_covar != 2; ++is_covar) { |
| 2529 |
PhenoCol** xpheno_cols_ptr; |
| 2530 |
char** xpheno_names_ptr; |
| 2531 |
uint32_t* xpheno_ct_ptr; |
| 2532 |
uintptr_t* max_xpheno_name_blen_ptr; |
| 2533 |
if (!is_covar) { |
| 2534 |
xpheno_cols_ptr = pheno_cols_ptr; |
| 2535 |
xpheno_names_ptr = pheno_names_ptr; |
| 2536 |
xpheno_ct_ptr = pheno_ct_ptr; |
| 2537 |
max_xpheno_name_blen_ptr = max_pheno_name_blen_ptr; |
| 2538 |
} else { |
| 2539 |
if (!split_cat_phenonames_flattened) { |
| 2540 |
break; |
| 2541 |
} |
| 2542 |
BigstackReset(bigstack_mark); |
| 2543 |
xpheno_cols_ptr = covar_cols_ptr; |
| 2544 |
xpheno_names_ptr = covar_names_ptr; |
| 2545 |
xpheno_ct_ptr = covar_ct_ptr; |
| 2546 |
max_xpheno_name_blen_ptr = max_covar_name_blen_ptr; |
| 2547 |
qt_12 = !(pheno_transform_flags & kfPhenoTransformSplitCatCovar01); |
| 2548 |
} |
| 2549 |
const uint32_t old_pheno_ct = *xpheno_ct_ptr; |
| 2550 |
if (!old_pheno_ct) { |
| 2551 |
continue; |
| 2552 |
} |
| 2553 |
const uint32_t old_pheno_ctl = BitCtToWordCt(old_pheno_ct); |
| 2554 |
const uintptr_t old_max_pheno_name_blen = *max_xpheno_name_blen_ptr; |
| 2555 |
PhenoCol* old_pheno_cols = *xpheno_cols_ptr; |
| 2556 |
const char* old_pheno_names = *xpheno_names_ptr; |
| 2557 |
uintptr_t* phenos_to_split; |
| 2558 |
if (unlikely(bigstack_calloc_w(old_pheno_ctl, &phenos_to_split))) { |
| 2559 |
goto SplitCatPheno_ret_NOMEM; |
| 2560 |
} |
| 2561 |
if (!split_cat_phenonames_flattened) { |
| 2562 |
for (uint32_t pheno_idx = 0; pheno_idx != old_pheno_ct; ++pheno_idx) { |
| 2563 |
const PhenoCol* cur_pheno_col = &(old_pheno_cols[pheno_idx]); |
| 2564 |
if (cur_pheno_col->type_code == kPhenoDtypeCat) { |
| 2565 |
if (unlikely(strchr(&(old_pheno_names[pheno_idx * old_max_pheno_name_blen]), '='))) { |
| 2566 |
logerrputs("Error: --split-cat-pheno cannot be used on phenotypes containing the '='\ncharacter.\n"); |
| 2567 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT; |
| 2568 |
} |
| 2569 |
SetBit(pheno_idx, phenos_to_split); |
| 2570 |
} |
| 2571 |
} |
| 2572 |
} else { |
| 2573 |
uint32_t* id_htable; |
| 2574 |
uint32_t id_htable_size; |
| 2575 |
if (unlikely(HtableGoodSizeAlloc(old_pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) { |
| 2576 |
goto SplitCatPheno_ret_NOMEM; |
| 2577 |
} |
| 2578 |
// shouldn't be possible for this to fail |
| 2579 |
PopulateStrboxHtable(old_pheno_names, old_pheno_ct, old_max_pheno_name_blen, id_htable_size, id_htable); |
| 2580 |
const char* split_cat_phenonames_iter = split_cat_phenonames_flattened; |
| 2581 |
do { |
| 2582 |
const uint32_t cur_phenoname_slen = strlen(split_cat_phenonames_iter); |
| 2583 |
if (cur_phenoname_slen < old_max_pheno_name_blen) { |
| 2584 |
uint32_t pheno_idx = StrboxHtableFind(split_cat_phenonames_iter, old_pheno_names, id_htable, old_max_pheno_name_blen, cur_phenoname_slen, id_htable_size); |
| 2585 |
if (pheno_idx != UINT32_MAX) { |
| 2586 |
if (unlikely(old_pheno_cols[pheno_idx].type_code != kPhenoDtypeCat)) { |
| 2587 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a categorical %s.\n", split_cat_phenonames_iter, is_covar? "covariate" : "phenotype"); |
| 2588 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT_WW; |
| 2589 |
} |
| 2590 |
SetBit(pheno_idx, phenos_to_split); |
| 2591 |
} |
| 2592 |
} |
| 2593 |
split_cat_phenonames_iter = &(split_cat_phenonames_iter[cur_phenoname_slen + 1]); |
| 2594 |
} while (*split_cat_phenonames_iter); |
| 2595 |
BigstackReset(id_htable); |
| 2596 |
} |
| 2597 |
const uint32_t split_pheno_ct = PopcountWords(phenos_to_split, old_pheno_ctl); |
| 2598 |
if (!split_pheno_ct) { |
| 2599 |
continue; |
| 2600 |
} |
| 2601 |
at_least_one_cat_pheno_processed = 1; |
| 2602 |
// first pass: determine new memory allocation sizes |
| 2603 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 2604 |
uintptr_t new_max_pheno_name_blen = old_max_pheno_name_blen; |
| 2605 |
|
| 2606 |
// excludes null; also excludes one other category if omit-most/omit-last |
| 2607 |
uint32_t* observed_cat_cts; |
| 2608 |
|
| 2609 |
uintptr_t** observed_cats; |
| 2610 |
uintptr_t* sample_include_intersect; |
| 2611 |
if (unlikely(bigstack_alloc_u32(split_pheno_ct, &observed_cat_cts) || |
| 2612 |
bigstack_alloc_wp(split_pheno_ct, &observed_cats) || |
| 2613 |
bigstack_alloc_w(raw_sample_ctl, &sample_include_intersect))) { |
| 2614 |
goto SplitCatPheno_ret_NOMEM; |
| 2615 |
} |
| 2616 |
uint32_t* omitted_cat_uidxs = nullptr; |
| 2617 |
if (is_omit) { |
| 2618 |
if (unlikely(bigstack_alloc_u32(split_pheno_ct, &omitted_cat_uidxs))) { |
| 2619 |
goto SplitCatPheno_ret_NOMEM; |
| 2620 |
} |
| 2621 |
} |
| 2622 |
uint32_t* cat_obs_buf = nullptr; |
| 2623 |
uintptr_t create_pheno_ct = 0; |
| 2624 |
uintptr_t split_pheno_uidx_base = 0; |
| 2625 |
uintptr_t phenos_to_split_bits = phenos_to_split[0]; |
| 2626 |
uint32_t max_cat_uidx = 0; |
| 2627 |
for (uint32_t split_pheno_idx = 0; split_pheno_idx != split_pheno_ct; ++split_pheno_idx) { |
| 2628 |
const uintptr_t split_pheno_uidx = BitIter1(phenos_to_split, &split_pheno_uidx_base, &phenos_to_split_bits); |
| 2629 |
const PhenoCol* cur_pheno_col = &(old_pheno_cols[split_pheno_uidx]); |
| 2630 |
BitvecAndCopy(sample_include, cur_pheno_col->nonmiss, raw_sample_ctl, sample_include_intersect); |
| 2631 |
const uint32_t cur_cat_ct = cur_pheno_col->nonnull_category_ct + 1; |
| 2632 |
const uint32_t cur_cat_ctl = BitCtToWordCt(cur_cat_ct); |
| 2633 |
uintptr_t* cur_observed_cats; |
| 2634 |
if (unlikely(bigstack_alloc_w(cur_cat_ctl, &cur_observed_cats))) { |
| 2635 |
goto SplitCatPheno_ret_NOMEM; |
| 2636 |
} |
| 2637 |
if (omit_most) { |
| 2638 |
if (unlikely(bigstack_alloc_u32(cur_cat_ct, &cat_obs_buf))) { |
| 2639 |
goto SplitCatPheno_ret_NOMEM; |
| 2640 |
} |
| 2641 |
} |
| 2642 |
observed_cats[split_pheno_idx] = cur_observed_cats; |
| 2643 |
const uint32_t cur_nmiss_ct = PopcountWords(sample_include_intersect, raw_sample_ctl); |
| 2644 |
uint32_t cur_observed_cat_ct; |
| 2645 |
if (!omit_most) { |
| 2646 |
cur_observed_cat_ct = IdentifyRemainingCats(sample_include_intersect, cur_pheno_col, cur_nmiss_ct, cur_observed_cats); |
| 2647 |
if (is_omit && cur_observed_cat_ct) { |
| 2648 |
const uint32_t last_cat_uidx = FindLast1BitBefore(cur_observed_cats, cur_cat_ct + 1); |
| 2649 |
omitted_cat_uidxs[split_pheno_idx] = last_cat_uidx; |
| 2650 |
ClearBit(last_cat_uidx, cur_observed_cats); |
| 2651 |
--cur_observed_cat_ct; |
| 2652 |
} |
| 2653 |
} else { |
| 2654 |
const uint32_t largest_cat_uidx = IdentifyRemainingCatsAndMostCommon(sample_include_intersect, cur_pheno_col, cur_nmiss_ct, cur_observed_cats, cat_obs_buf); |
| 2655 |
cur_observed_cat_ct = PopcountWords(cur_observed_cats, cur_cat_ctl); |
| 2656 |
if (cur_observed_cat_ct) { |
| 2657 |
omitted_cat_uidxs[split_pheno_idx] = largest_cat_uidx; |
| 2658 |
ClearBit(largest_cat_uidx, cur_observed_cats); |
| 2659 |
--cur_observed_cat_ct; |
| 2660 |
} |
| 2661 |
} |
| 2662 |
if (cur_observed_cat_ct) { |
| 2663 |
// old phenotype name, '=' character, null terminator |
| 2664 |
const uintptr_t blen_base = strlen(&(old_pheno_names[split_pheno_uidx * old_max_pheno_name_blen])) + 2; |
| 2665 |
const char* const* cat_names = cur_pheno_col->category_names; |
| 2666 |
uintptr_t cat_uidx_base = 0; |
| 2667 |
uintptr_t cur_observed_cats_bits = cur_observed_cats[0]; |
| 2668 |
uint32_t cat_uidx = 0; |
| 2669 |
for (uint32_t cat_idx = 0; cat_idx != cur_observed_cat_ct; ++cat_idx) { |
| 2670 |
cat_uidx = BitIter1(cur_observed_cats, &cat_uidx_base, &cur_observed_cats_bits); |
| 2671 |
const char* cur_cat_name = cat_names[cat_uidx]; |
| 2672 |
const uint32_t cur_slen = strlen(cur_cat_name); |
| 2673 |
if (unlikely(memchr(cur_cat_name, '=', cur_slen))) { |
| 2674 |
logerrputs("Error: --split-cat-pheno category names may not contain the '=' character.\n"); |
| 2675 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT; |
| 2676 |
} |
| 2677 |
const uintptr_t total_blen = cur_slen + blen_base; |
| 2678 |
if (total_blen > new_max_pheno_name_blen) { |
| 2679 |
new_max_pheno_name_blen = total_blen; |
| 2680 |
} |
| 2681 |
} |
| 2682 |
if (cat_uidx > max_cat_uidx) { |
| 2683 |
max_cat_uidx = cat_uidx; |
| 2684 |
} |
| 2685 |
} |
| 2686 |
observed_cat_cts[split_pheno_idx] = cur_observed_cat_ct; |
| 2687 |
create_pheno_ct += cur_observed_cat_ct; |
| 2688 |
if (cat_obs_buf) { |
| 2689 |
BigstackReset(cat_obs_buf); |
| 2690 |
} |
| 2691 |
} |
| 2692 |
if (unlikely(new_max_pheno_name_blen > kMaxIdBlen)) { |
| 2693 |
logerrputs("Error: New --split-cat-pheno phenotype name too long. Shorten your phenotype\nor your category names.\n"); |
| 2694 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT; |
| 2695 |
} |
| 2696 |
const uint32_t copy_pheno_ct = old_pheno_ct - split_pheno_ct; |
| 2697 |
// before new_pheno_ct variable definition due to potential integer |
| 2698 |
// overflow |
| 2699 |
if (unlikely(create_pheno_ct + copy_pheno_ct > kMaxPhenoCt)) { |
| 2700 |
logerrputs("Error: --split-cat-pheno would create too many phenotypes (" PROG_NAME_STR " is limited to\n" MAX_PHENO_CT_STR ").\n"); |
| 2701 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT; |
| 2702 |
} |
| 2703 |
const uint32_t new_pheno_ct = create_pheno_ct + copy_pheno_ct; |
| 2704 |
uintptr_t** write_data_ptrs; |
| 2705 |
if (unlikely(bigstack_alloc_wp(max_cat_uidx + 1, &write_data_ptrs))) { |
| 2706 |
goto SplitCatPheno_ret_NOMEM; |
| 2707 |
} |
| 2708 |
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct); |
| 2709 |
uint32_t new_data_word_ct = raw_sample_ctaw; |
| 2710 |
if (is_covar) { |
| 2711 |
new_data_word_ct = DblCtToVecCt(raw_sample_ct) * kWordsPerVec; |
| 2712 |
} |
| 2713 |
uintptr_t* omit_dummy = nullptr; |
| 2714 |
if (is_omit) { |
| 2715 |
if (unlikely(bigstack_alloc_w(new_data_word_ct, &omit_dummy))) { |
| 2716 |
goto SplitCatPheno_ret_NOMEM; |
| 2717 |
} |
| 2718 |
} |
| 2719 |
|
| 2720 |
// second pass: allocate memory and actually create the new phenotypes |
| 2721 |
char* new_pheno_names; |
| 2722 |
if (unlikely(pgl_malloc(new_pheno_ct * new_max_pheno_name_blen, &new_pheno_names))) { |
| 2723 |
goto SplitCatPheno_ret_NOMEM; |
| 2724 |
} |
| 2725 |
doomed_pheno_names = old_pheno_names; |
| 2726 |
*xpheno_names_ptr = new_pheno_names; |
| 2727 |
PhenoCol* new_pheno_cols; |
| 2728 |
if (unlikely(pgl_malloc(new_pheno_ct * sizeof(PhenoCol), &new_pheno_cols))) { |
| 2729 |
goto SplitCatPheno_ret_NOMEM; |
| 2730 |
} |
| 2731 |
doomed_pheno_cols = old_pheno_cols; |
| 2732 |
doomed_pheno_ct = old_pheno_ct; |
| 2733 |
*xpheno_cols_ptr = new_pheno_cols; |
| 2734 |
*xpheno_ct_ptr = new_pheno_ct; |
| 2735 |
*max_xpheno_name_blen_ptr = new_max_pheno_name_blen; |
| 2736 |
uintptr_t pheno_read_idx_base = 0; |
| 2737 |
uintptr_t phenos_to_split_inv_bits = ~phenos_to_split[0]; |
| 2738 |
for (uint32_t pheno_write_idx = 0; pheno_write_idx != copy_pheno_ct; ++pheno_write_idx) { |
| 2739 |
const uintptr_t pheno_read_idx = BitIter0(phenos_to_split, &pheno_read_idx_base, &phenos_to_split_inv_bits); |
| 2740 |
|
| 2741 |
// manually move this data |
| 2742 |
memcpy(&(new_pheno_cols[pheno_write_idx]), &(doomed_pheno_cols[pheno_read_idx]), sizeof(PhenoCol)); |
| 2743 |
doomed_pheno_cols[pheno_read_idx].nonmiss = nullptr; |
| 2744 |
|
| 2745 |
strcpy(&(new_pheno_names[pheno_write_idx * new_max_pheno_name_blen]), &(old_pheno_names[pheno_read_idx * old_max_pheno_name_blen])); |
| 2746 |
} |
| 2747 |
for (uint32_t pheno_write_idx = copy_pheno_ct; pheno_write_idx != new_pheno_ct; ++pheno_write_idx) { |
| 2748 |
new_pheno_cols[pheno_write_idx].nonmiss = nullptr; |
| 2749 |
} |
| 2750 |
|
| 2751 |
const uintptr_t new_pheno_bytes_req = (raw_sample_ctaw + new_data_word_ct) * sizeof(intptr_t); |
| 2752 |
uint32_t pheno_write_idx = copy_pheno_ct; |
| 2753 |
pheno_read_idx_base = 0; |
| 2754 |
phenos_to_split_bits = phenos_to_split[0]; |
| 2755 |
for (uint32_t split_pheno_idx = 0; split_pheno_idx != split_pheno_ct; ++split_pheno_idx) { |
| 2756 |
const uintptr_t pheno_read_idx = BitIter1(phenos_to_split, &pheno_read_idx_base, &phenos_to_split_bits); |
| 2757 |
const uint32_t cur_pheno_write_ct = observed_cat_cts[split_pheno_idx]; |
| 2758 |
if (!cur_pheno_write_ct) { |
| 2759 |
continue; |
| 2760 |
} |
| 2761 |
const uintptr_t* cur_observed_cats = observed_cats[split_pheno_idx]; |
| 2762 |
const PhenoCol* old_pheno_col = &(old_pheno_cols[pheno_read_idx]); |
| 2763 |
BitvecAndCopy(sample_include, old_pheno_col->nonmiss, raw_sample_ctaw, sample_include_intersect); |
| 2764 |
const char* old_pheno_name = &(old_pheno_names[pheno_read_idx * old_max_pheno_name_blen]); |
| 2765 |
const uint32_t old_pheno_name_slen = strlen(old_pheno_name); |
| 2766 |
const char* const* old_cat_names = old_pheno_col->category_names; |
| 2767 |
uintptr_t orig_cat_idx_base; |
| 2768 |
uintptr_t cur_observed_cats_bits; |
| 2769 |
BitIter1Start(cur_observed_cats, 1, &orig_cat_idx_base, &cur_observed_cats_bits); |
| 2770 |
for (uint32_t uii = 0; uii != cur_pheno_write_ct; ++uii, ++pheno_write_idx) { |
| 2771 |
const uintptr_t orig_cat_idx = BitIter1(cur_observed_cats, &orig_cat_idx_base, &cur_observed_cats_bits); |
| 2772 |
uintptr_t* new_pheno_data_iter; |
| 2773 |
if (unlikely(vecaligned_malloc(new_pheno_bytes_req, &new_pheno_data_iter))) { |
| 2774 |
goto SplitCatPheno_ret_NOMEM; |
| 2775 |
} |
| 2776 |
char* new_phenoname_write_iter = memcpyax(&(new_pheno_names[pheno_write_idx * new_max_pheno_name_blen]), old_pheno_name, old_pheno_name_slen, '='); |
| 2777 |
strcpy(new_phenoname_write_iter, old_cat_names[orig_cat_idx]); |
| 2778 |
PhenoCol* pheno_write_col = &(new_pheno_cols[pheno_write_idx]); |
| 2779 |
pheno_write_col->nonmiss = new_pheno_data_iter; |
| 2780 |
pheno_write_col->category_names = nullptr; |
| 2781 |
pheno_write_col->type_code = S_CAST(PhenoDtype, is_covar); |
| 2782 |
pheno_write_col->nonnull_category_ct = 0; |
| 2783 |
memcpy(new_pheno_data_iter, sample_include_intersect, raw_sample_ctaw * sizeof(intptr_t)); |
| 2784 |
new_pheno_data_iter = &(new_pheno_data_iter[raw_sample_ctaw]); |
| 2785 |
write_data_ptrs[orig_cat_idx] = new_pheno_data_iter; |
| 2786 |
// assigning to one element of a union and reading from another with |
| 2787 |
// a different type is undefined behavior in C++11 |
| 2788 |
if (!is_covar) { |
| 2789 |
pheno_write_col->data.cc = new_pheno_data_iter; |
| 2790 |
ZeroWArr(raw_sample_ctaw, new_pheno_data_iter); |
| 2791 |
} else { |
| 2792 |
double* pheno_qt = R_CAST(double*, new_pheno_data_iter); |
| 2793 |
pheno_write_col->data.qt = pheno_qt; |
| 2794 |
if (qt_12) { |
| 2795 |
for (uint32_t ujj = 0; ujj != raw_sample_ct; ++ujj) { |
| 2796 |
pheno_qt[ujj] = 1.0; |
| 2797 |
} |
| 2798 |
} else { |
| 2799 |
ZeroDArr(raw_sample_ct, pheno_qt); |
| 2800 |
} |
| 2801 |
} |
| 2802 |
} |
| 2803 |
if (is_omit) { |
| 2804 |
write_data_ptrs[omitted_cat_uidxs[split_pheno_idx]] = omit_dummy; |
| 2805 |
} |
| 2806 |
|
| 2807 |
const uint32_t cur_nmiss_ct = PopcountWords(sample_include_intersect, raw_sample_ctl); |
| 2808 |
const uint32_t* cur_cats = old_pheno_col->data.cat; |
| 2809 |
uintptr_t sample_uidx_base = 0; |
| 2810 |
uintptr_t sample_include_intersect_bits = sample_include_intersect[0]; |
| 2811 |
if (!is_covar) { |
| 2812 |
for (uint32_t sample_idx = 0; sample_idx != cur_nmiss_ct; ++sample_idx) { |
| 2813 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &sample_include_intersect_bits); |
| 2814 |
SetBit(sample_uidx, write_data_ptrs[cur_cats[sample_uidx]]); |
| 2815 |
} |
| 2816 |
} else { |
| 2817 |
double** write_qt_ptrs = R_CAST(double**, write_data_ptrs); |
| 2818 |
const double write_val = u31tod(1 + qt_12); |
| 2819 |
for (uint32_t sample_idx = 0; sample_idx != cur_nmiss_ct; ++sample_idx) { |
| 2820 |
const uintptr_t sample_uidx = BitIter1(sample_include_intersect, &sample_uidx_base, &sample_include_intersect_bits); |
| 2821 |
write_qt_ptrs[cur_cats[sample_uidx]][sample_uidx] = write_val; |
| 2822 |
} |
| 2823 |
} |
| 2824 |
} |
| 2825 |
|
| 2826 |
// if any preexisting phenotype names contain a single copy of the '=' |
| 2827 |
// character, verify that we didn't create any duplicate IDs |
| 2828 |
for (uint32_t pheno_idx = 0; pheno_idx != copy_pheno_ct; ++pheno_idx) { |
| 2829 |
const char* first_eq = strchr(&(new_pheno_names[pheno_idx * new_max_pheno_name_blen]), '='); |
| 2830 |
if (first_eq && (!strchr(&(first_eq[1]), '='))) { |
| 2831 |
uint32_t* id_htable; |
| 2832 |
uint32_t id_htable_size; |
| 2833 |
if (unlikely(HtableGoodSizeAlloc(new_pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) { |
| 2834 |
goto SplitCatPheno_ret_NOMEM; |
| 2835 |
} |
| 2836 |
uint32_t duplicate_idx = PopulateStrboxHtable(new_pheno_names, new_pheno_ct, new_max_pheno_name_blen, id_htable_size, id_htable); |
| 2837 |
if (unlikely(duplicate_idx)) { |
| 2838 |
snprintf(g_logbuf, kLogbufSize, "Error: Duplicate %s '%s' created by --split-cat-pheno.\n", is_covar? "covariate" : "phenotype", &(new_pheno_names[duplicate_idx * new_max_pheno_name_blen])); |
| 2839 |
goto SplitCatPheno_ret_INCONSISTENT_INPUT_WW; |
| 2840 |
} |
| 2841 |
break; |
| 2842 |
} |
| 2843 |
} |
| 2844 |
|
| 2845 |
free_const(doomed_pheno_names); |
| 2846 |
doomed_pheno_names = nullptr; |
| 2847 |
CleanupPhenoCols(doomed_pheno_ct, doomed_pheno_cols); |
| 2848 |
doomed_pheno_cols = nullptr; |
| 2849 |
|
| 2850 |
logprintfww("--split-cat-pheno: %u categorical %s%s converted to %" PRIuPTR " %s%s.\n", split_pheno_ct, is_covar? "covariate" : "phenotype", (split_pheno_ct == 1)? "" : "s", create_pheno_ct, is_covar? "covariate" : "phenotype", (create_pheno_ct == 1)? "" : "s"); |
| 2851 |
} |
| 2852 |
if (!at_least_one_cat_pheno_processed) { |
| 2853 |
logerrprintf("Warning: No categorical phenotypes%s processed by --split-cat-pheno.\n", (split_cat_phenonames_flattened && (!(*covar_ct_ptr)))? "/covariates" : ""); |
| 2854 |
} |
| 2855 |
} |
| 2856 |
while (0) { |
| 2857 |
SplitCatPheno_ret_NOMEM: |
| 2858 |
reterr = kPglRetNomem; |
| 2859 |
break; |
| 2860 |
SplitCatPheno_ret_INCONSISTENT_INPUT_WW: |
| 2861 |
WordWrapB(0); |
| 2862 |
logerrputsb(); |
| 2863 |
SplitCatPheno_ret_INCONSISTENT_INPUT: |
| 2864 |
reterr = kPglRetInconsistentInput; |
| 2865 |
break; |
| 2866 |
} |
| 2867 |
BigstackReset(bigstack_mark); |
| 2868 |
free_cond(doomed_pheno_names); |
| 2869 |
CleanupPhenoCols(doomed_pheno_ct, doomed_pheno_cols); |
| 2870 |
if (reterr) { |
| 2871 |
if (*pheno_names_ptr) { |
| 2872 |
free(*pheno_names_ptr); |
| 2873 |
*pheno_names_ptr = nullptr; |
| 2874 |
} |
| 2875 |
CleanupPhenoCols(*pheno_ct_ptr, *pheno_cols_ptr); |
| 2876 |
*pheno_ct_ptr = 0; |
| 2877 |
*pheno_cols_ptr = nullptr; |
| 2878 |
if (*covar_names_ptr) { |
| 2879 |
free(*covar_names_ptr); |
| 2880 |
*covar_names_ptr = nullptr; |
| 2881 |
} |
| 2882 |
CleanupPhenoCols(*covar_ct_ptr, *covar_cols_ptr); |
| 2883 |
*covar_ct_ptr = 0; |
| 2884 |
*covar_cols_ptr = nullptr; |
| 2885 |
} |
| 2886 |
return reterr; |
| 2887 |
} |
| 2888 |
|
| 2889 |
PglErr PhenoVarianceStandardize(const char* vstd_flattened, const uintptr_t* sample_include, const char* pheno_names, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t is_covar, uint32_t is_covar_flag, PhenoCol* pheno_cols) { |
| 2890 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 2891 |
PglErr reterr = kPglRetSuccess; |
| 2892 |
{ |
| 2893 |
if (!pheno_ct) { |
| 2894 |
goto PhenoVarianceStandardize_ret_SKIP; |
| 2895 |
} |
| 2896 |
const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct); |
| 2897 |
uintptr_t* phenos_to_transform; |
| 2898 |
if (unlikely(bigstack_calloc_w(pheno_ctl, &phenos_to_transform))) { |
| 2899 |
goto PhenoVarianceStandardize_ret_NOMEM; |
| 2900 |
} |
| 2901 |
if (!vstd_flattened) { |
| 2902 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 2903 |
const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]); |
| 2904 |
if (cur_pheno_col->type_code == kPhenoDtypeQt) { |
| 2905 |
SetBit(pheno_idx, phenos_to_transform); |
| 2906 |
} |
| 2907 |
} |
| 2908 |
} else { |
| 2909 |
uint32_t* id_htable; |
| 2910 |
uint32_t id_htable_size; |
| 2911 |
if (unlikely(HtableGoodSizeAlloc(pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) { |
| 2912 |
goto PhenoVarianceStandardize_ret_NOMEM; |
| 2913 |
} |
| 2914 |
PopulateStrboxHtable(pheno_names, pheno_ct, max_pheno_name_blen, id_htable_size, id_htable); |
| 2915 |
const char* vstd_phenonames_iter = vstd_flattened; |
| 2916 |
do { |
| 2917 |
const uint32_t cur_phenoname_slen = strlen(vstd_phenonames_iter); |
| 2918 |
if (cur_phenoname_slen < max_pheno_name_blen) { |
| 2919 |
uint32_t pheno_idx = StrboxHtableFind(vstd_phenonames_iter, pheno_names, id_htable, max_pheno_name_blen, cur_phenoname_slen, id_htable_size); |
| 2920 |
if (pheno_idx != UINT32_MAX) { |
| 2921 |
if (unlikely(pheno_cols[pheno_idx].type_code != kPhenoDtypeQt)) { |
| 2922 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a quantitative %s.\n", vstd_phenonames_iter, is_covar? "covariate" : "phenotype"); |
| 2923 |
goto PhenoVarianceStandardize_ret_INCONSISTENT_INPUT_WW; |
| 2924 |
} |
| 2925 |
SetBit(pheno_idx, phenos_to_transform); |
| 2926 |
} |
| 2927 |
} |
| 2928 |
vstd_phenonames_iter = &(vstd_phenonames_iter[cur_phenoname_slen + 1]); |
| 2929 |
} while (*vstd_phenonames_iter); |
| 2930 |
BigstackReset(id_htable); |
| 2931 |
} |
| 2932 |
const uint32_t pheno_transform_ct = PopcountWords(phenos_to_transform, pheno_ctl); |
| 2933 |
if (!pheno_transform_ct) { |
| 2934 |
goto PhenoVarianceStandardize_ret_SKIP; |
| 2935 |
} |
| 2936 |
double* shifted_pheno_qt; |
| 2937 |
if (unlikely(bigstack_alloc_d(raw_sample_ct, &shifted_pheno_qt))) { |
| 2938 |
goto PhenoVarianceStandardize_ret_NOMEM; |
| 2939 |
} |
| 2940 |
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct); |
| 2941 |
uintptr_t pheno_uidx_base = 0; |
| 2942 |
uintptr_t phenos_to_transform_bits = phenos_to_transform[0]; |
| 2943 |
for (uint32_t pheno_transform_idx = 0; pheno_transform_idx != pheno_transform_ct; ++pheno_transform_idx) { |
| 2944 |
const uintptr_t pheno_uidx = BitIter1(phenos_to_transform, &pheno_uidx_base, &phenos_to_transform_bits); |
| 2945 |
PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]); |
| 2946 |
uintptr_t* pheno_nm = cur_pheno_col->nonmiss; |
| 2947 |
BitvecAnd(sample_include, raw_sample_ctaw, pheno_nm); |
| 2948 |
const uint32_t cur_sample_ct = PopcountWords(pheno_nm, raw_sample_ctaw); |
| 2949 |
if (cur_sample_ct < 2) { |
| 2950 |
if (cur_sample_ct) { |
| 2951 |
logerrprintfww("Warning: Exactly one value present for %s '%s'; standardizing to missing.\n", is_covar? "covariate" : "quantitative phenotype", &(pheno_names[pheno_uidx * max_pheno_name_blen])); |
| 2952 |
ZeroWArr(raw_sample_ctaw, pheno_nm); |
| 2953 |
} |
| 2954 |
continue; |
| 2955 |
} |
| 2956 |
double* pheno_qt = cur_pheno_col->data.qt; |
| 2957 |
double shifted_pheno_sum = 0.0; |
| 2958 |
double shifted_pheno_ssq = 0.0; |
| 2959 |
const uint32_t first_sample_uidx = AdvTo1Bit(pheno_nm, 0); |
| 2960 |
shifted_pheno_qt[first_sample_uidx] = 0.0; |
| 2961 |
const double pheno_shift = pheno_qt[first_sample_uidx]; |
| 2962 |
uintptr_t sample_uidx_base; |
| 2963 |
uintptr_t pheno_nm_bits; |
| 2964 |
BitIter1Start(pheno_nm, first_sample_uidx + 1, &sample_uidx_base, &pheno_nm_bits); |
| 2965 |
for (uint32_t sample_idx = 1; sample_idx != cur_sample_ct; ++sample_idx) { |
| 2966 |
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits); |
| 2967 |
const double cur_shifted_pheno_val = pheno_qt[sample_uidx] - pheno_shift; |
| 2968 |
shifted_pheno_sum += cur_shifted_pheno_val; |
| 2969 |
shifted_pheno_ssq += cur_shifted_pheno_val * cur_shifted_pheno_val; |
| 2970 |
shifted_pheno_qt[sample_uidx] = cur_shifted_pheno_val; |
| 2971 |
} |
| 2972 |
const double cur_shifted_mean = shifted_pheno_sum / u31tod(cur_sample_ct); |
| 2973 |
const double variance_numer = shifted_pheno_ssq - shifted_pheno_sum * cur_shifted_mean; |
| 2974 |
if (!(variance_numer > 0.0)) { |
| 2975 |
logerrprintfww("Warning: %s '%s' is constant; standardizing to all-missing.\n", is_covar? "Covariate" : "Quantitative phenotype", &(pheno_names[pheno_uidx * max_pheno_name_blen])); |
| 2976 |
ZeroWArr(raw_sample_ctaw, pheno_nm); |
| 2977 |
continue; |
| 2978 |
} |
| 2979 |
const double cur_stdev_recip = sqrt(u31tod(cur_sample_ct - 1) / variance_numer); |
| 2980 |
BitIter1Start(pheno_nm, first_sample_uidx, &sample_uidx_base, &pheno_nm_bits); |
| 2981 |
for (uint32_t sample_idx = 0; sample_idx != cur_sample_ct; ++sample_idx) { |
| 2982 |
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits); |
| 2983 |
pheno_qt[sample_uidx] = (shifted_pheno_qt[sample_uidx] - cur_shifted_mean) * cur_stdev_recip; |
| 2984 |
} |
| 2985 |
} |
| 2986 |
// could reduce the reported number when all values were originally missing |
| 2987 |
logprintf("--%svariance-standardize: %u %s%s transformed.\n", is_covar_flag? "covar-" : "", pheno_transform_ct, is_covar? "covariate" : "phenotype", (pheno_transform_ct == 1)? "" : "s"); |
| 2988 |
} |
| 2989 |
while (0) { |
| 2990 |
PhenoVarianceStandardize_ret_NOMEM: |
| 2991 |
reterr = kPglRetNomem; |
| 2992 |
break; |
| 2993 |
PhenoVarianceStandardize_ret_INCONSISTENT_INPUT_WW: |
| 2994 |
WordWrapB(0); |
| 2995 |
logerrputsb(); |
| 2996 |
reterr = kPglRetInconsistentInput; |
| 2997 |
break; |
| 2998 |
PhenoVarianceStandardize_ret_SKIP: |
| 2999 |
logprintf("--%svariance-standardize: No %s affected.\n", is_covar_flag? "covar-" : "", is_covar? "covariates" : "quantitative phenotypes"); |
| 3000 |
break; |
| 3001 |
} |
| 3002 |
BigstackReset(bigstack_mark); |
| 3003 |
return reterr; |
| 3004 |
} |
| 3005 |
|
| 3006 |
typedef struct DblIndexStruct { |
| 3007 |
double dxx; |
| 3008 |
uint32_t uii; |
| 3009 |
#ifdef __cplusplus |
| 3010 |
bool operator<(const struct DblIndexStruct& rhs) const { |
| 3011 |
return dxx < rhs.dxx; |
| 3012 |
} |
| 3013 |
#endif |
| 3014 |
} DblIndex; |
| 3015 |
|
| 3016 |
PglErr PhenoQuantileNormalize(const char* quantnorm_flattened, const uintptr_t* sample_include, const char* pheno_names, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t is_covar, uint32_t is_subset_flag, PhenoCol* pheno_cols) { |
| 3017 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3018 |
const char* flag_prefix = is_subset_flag? (is_covar? "covar-" : "pheno-") : ""; |
| 3019 |
PglErr reterr = kPglRetSuccess; |
| 3020 |
{ |
| 3021 |
if ((!pheno_ct) || (!sample_ct)) { |
| 3022 |
goto PhenoQuantileNormalize_ret_SKIP; |
| 3023 |
} |
| 3024 |
// this boilerplate probably belongs in its own function |
| 3025 |
const uint32_t pheno_ctl = BitCtToWordCt(pheno_ct); |
| 3026 |
uintptr_t* phenos_to_transform; |
| 3027 |
if (unlikely(bigstack_calloc_w(pheno_ctl, &phenos_to_transform))) { |
| 3028 |
goto PhenoQuantileNormalize_ret_NOMEM; |
| 3029 |
} |
| 3030 |
if (!quantnorm_flattened) { |
| 3031 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 3032 |
const PhenoCol* cur_pheno_col = &(pheno_cols[pheno_idx]); |
| 3033 |
if (cur_pheno_col->type_code == kPhenoDtypeQt) { |
| 3034 |
SetBit(pheno_idx, phenos_to_transform); |
| 3035 |
} |
| 3036 |
} |
| 3037 |
} else { |
| 3038 |
uint32_t* id_htable; |
| 3039 |
uint32_t id_htable_size; |
| 3040 |
if (unlikely(HtableGoodSizeAlloc(pheno_ct, bigstack_left(), &id_htable, &id_htable_size))) { |
| 3041 |
goto PhenoQuantileNormalize_ret_NOMEM; |
| 3042 |
} |
| 3043 |
PopulateStrboxHtable(pheno_names, pheno_ct, max_pheno_name_blen, id_htable_size, id_htable); |
| 3044 |
const char* quantnorm_phenonames_iter = quantnorm_flattened; |
| 3045 |
do { |
| 3046 |
const uint32_t cur_phenoname_slen = strlen(quantnorm_phenonames_iter); |
| 3047 |
if (cur_phenoname_slen < max_pheno_name_blen) { |
| 3048 |
uint32_t pheno_idx = StrboxHtableFind(quantnorm_phenonames_iter, pheno_names, id_htable, max_pheno_name_blen, cur_phenoname_slen, id_htable_size); |
| 3049 |
if (pheno_idx != UINT32_MAX) { |
| 3050 |
if (unlikely(pheno_cols[pheno_idx].type_code != kPhenoDtypeQt)) { |
| 3051 |
snprintf(g_logbuf, kLogbufSize, "Error: '%s' is not a quantitative %s.\n", quantnorm_phenonames_iter, is_covar? "covariate" : "phenotype"); |
| 3052 |
goto PhenoQuantileNormalize_ret_INCONSISTENT_INPUT_WW; |
| 3053 |
} |
| 3054 |
SetBit(pheno_idx, phenos_to_transform); |
| 3055 |
} |
| 3056 |
} |
| 3057 |
quantnorm_phenonames_iter = &(quantnorm_phenonames_iter[cur_phenoname_slen + 1]); |
| 3058 |
} while (*quantnorm_phenonames_iter); |
| 3059 |
BigstackReset(id_htable); |
| 3060 |
} |
| 3061 |
const uint32_t pheno_transform_ct = PopcountWords(phenos_to_transform, pheno_ctl); |
| 3062 |
if (!pheno_transform_ct) { |
| 3063 |
goto PhenoQuantileNormalize_ret_SKIP; |
| 3064 |
} |
| 3065 |
DblIndex* tagged_raw_pheno_vals; |
| 3066 |
if (unlikely(BIGSTACK_ALLOC_X(DblIndex, sample_ct, &tagged_raw_pheno_vals))) { |
| 3067 |
goto PhenoQuantileNormalize_ret_NOMEM; |
| 3068 |
} |
| 3069 |
const uint32_t raw_sample_ctaw = BitCtToAlignedWordCt(raw_sample_ct); |
| 3070 |
uintptr_t pheno_uidx_base = 0; |
| 3071 |
uintptr_t phenos_to_transform_bits = phenos_to_transform[0]; |
| 3072 |
for (uint32_t pheno_transform_idx = 0; pheno_transform_idx != pheno_transform_ct; ++pheno_transform_idx) { |
| 3073 |
const uintptr_t pheno_uidx = BitIter1(phenos_to_transform, &pheno_uidx_base, &phenos_to_transform_bits); |
| 3074 |
PhenoCol* cur_pheno_col = &(pheno_cols[pheno_uidx]); |
| 3075 |
uintptr_t* pheno_nm = cur_pheno_col->nonmiss; |
| 3076 |
BitvecAnd(sample_include, raw_sample_ctaw, pheno_nm); |
| 3077 |
const uint32_t cur_sample_ct = PopcountWords(pheno_nm, raw_sample_ctaw); |
| 3078 |
if (!cur_sample_ct) { |
| 3079 |
continue; |
| 3080 |
} |
| 3081 |
double* pheno_qt = cur_pheno_col->data.qt; |
| 3082 |
uintptr_t sample_uidx_base = 0; |
| 3083 |
uintptr_t pheno_nm_bits = pheno_nm[0]; |
| 3084 |
for (uint32_t sample_idx = 0; sample_idx != cur_sample_ct; ++sample_idx) { |
| 3085 |
// bugfix (1 Sep 2017): this needs to iterate over pheno_nm, not |
| 3086 |
// sample_include |
| 3087 |
const uintptr_t sample_uidx = BitIter1(pheno_nm, &sample_uidx_base, &pheno_nm_bits); |
| 3088 |
tagged_raw_pheno_vals[sample_idx].dxx = pheno_qt[sample_uidx]; |
| 3089 |
tagged_raw_pheno_vals[sample_idx].uii = sample_uidx; |
| 3090 |
} |
| 3091 |
STD_SORT_PAR_UNSEQ(cur_sample_ct, double_cmp, tagged_raw_pheno_vals); |
| 3092 |
const double sample_ct_x2_recip = 1.0 / S_CAST(double, 2 * cur_sample_ct); |
| 3093 |
for (uint32_t sample_idx_start = 0; sample_idx_start != cur_sample_ct; ) { |
| 3094 |
const double cur_raw_pheno = tagged_raw_pheno_vals[sample_idx_start].dxx; |
| 3095 |
uint32_t sample_idx_end = sample_idx_start + 1; |
| 3096 |
for (; sample_idx_end != cur_sample_ct; ++sample_idx_end) { |
| 3097 |
if (tagged_raw_pheno_vals[sample_idx_end].dxx != cur_raw_pheno) { |
| 3098 |
break; |
| 3099 |
} |
| 3100 |
} |
| 3101 |
const double cur_zscore = QuantileToZscore(S_CAST(double, sample_idx_start + sample_idx_end) * sample_ct_x2_recip); |
| 3102 |
for (; sample_idx_start != sample_idx_end; ++sample_idx_start) { |
| 3103 |
pheno_qt[tagged_raw_pheno_vals[sample_idx_start].uii] = cur_zscore; |
| 3104 |
} |
| 3105 |
} |
| 3106 |
} |
| 3107 |
logprintf("--%squantile-normalize: %u %s%s transformed.\n", flag_prefix, pheno_transform_ct, is_covar? "covariate" : "phenotype", (pheno_transform_ct == 1)? "" : "s"); |
| 3108 |
} |
| 3109 |
while (0) { |
| 3110 |
PhenoQuantileNormalize_ret_NOMEM: |
| 3111 |
reterr = kPglRetNomem; |
| 3112 |
break; |
| 3113 |
PhenoQuantileNormalize_ret_INCONSISTENT_INPUT_WW: |
| 3114 |
WordWrapB(0); |
| 3115 |
logerrputsb(); |
| 3116 |
reterr = kPglRetInconsistentInput; |
| 3117 |
break; |
| 3118 |
PhenoQuantileNormalize_ret_SKIP: |
| 3119 |
logprintf("--%squantile-normalize: No %s affected.\n", flag_prefix, is_covar? "covariates" : "quantitative phenotypes"); |
| 3120 |
break; |
| 3121 |
} |
| 3122 |
BigstackReset(bigstack_mark); |
| 3123 |
return reterr; |
| 3124 |
} |
| 3125 |
|
| 3126 |
|
| 3127 |
PglErr ProcessBoundaryToken(const char* tok_start, const char* tok_end, const char* token_source_str, uint32_t max_boundary_ct, PglErr err_type, double* prev_boundary_ptr, uint32_t* boundary_ct_ptr, double** freq_bounds_ptr, uint64_t** ddosage_bounds_ptr) { |
| 3128 |
double cur_boundary; |
| 3129 |
const char* scan_end = ScanadvDouble(tok_start, &cur_boundary); |
| 3130 |
if (unlikely((!scan_end) || (scan_end != tok_end))) { |
| 3131 |
logerrprintf("Error: Invalid token in %s.\n", token_source_str); |
| 3132 |
return err_type; |
| 3133 |
} |
| 3134 |
if (unlikely(cur_boundary <= (*prev_boundary_ptr))) { |
| 3135 |
logerrputs("Error: Invalid bin boundary sequence (must be strictly increasing, and start\nwith a positive number).\n"); |
| 3136 |
return err_type; |
| 3137 |
} |
| 3138 |
uint32_t boundary_ct = *boundary_ct_ptr; |
| 3139 |
if (unlikely(boundary_ct == max_boundary_ct)) { |
| 3140 |
#ifdef __LP64__ |
| 3141 |
if (max_boundary_ct == 0x40000000) { |
| 3142 |
logerrputs("Error: Too many bin boundaries.\n"); |
| 3143 |
return err_type; |
| 3144 |
} |
| 3145 |
#endif |
| 3146 |
return kPglRetNomem; |
| 3147 |
} |
| 3148 |
if (freq_bounds_ptr) { |
| 3149 |
if (unlikely(cur_boundary > 1.0)) { |
| 3150 |
logerrputs("Error: --freq bin boundary too large (must be <= 1).\n"); |
| 3151 |
return err_type; |
| 3152 |
} |
| 3153 |
// strictly-greater-than comparisons |
| 3154 |
(*freq_bounds_ptr)[boundary_ct] = cur_boundary * (1 - kSmallEpsilon); |
| 3155 |
} else { |
| 3156 |
// max 2^31 - 3 variants |
| 3157 |
if (unlikely(cur_boundary > 4294967290.0)) { |
| 3158 |
logerrputs("Error: --freq counts bin boundary too large.\n"); |
| 3159 |
return err_type; |
| 3160 |
} |
| 3161 |
// due to the use of strictly-greater-than for comparison, we round |
| 3162 |
// exact multiples of 1/32768 down |
| 3163 |
const int64_t int_part = S_CAST(int64_t, cur_boundary); |
| 3164 |
const double cur_boundary_frac_part = cur_boundary - int_part; |
| 3165 |
const int64_t int_part_scaled = int_part * kDosageMax; |
| 3166 |
if (cur_boundary_frac_part == 0.0) { |
| 3167 |
(*ddosage_bounds_ptr)[boundary_ct] = int_part_scaled - 1; |
| 3168 |
} else { |
| 3169 |
(*ddosage_bounds_ptr)[boundary_ct] = int_part_scaled + S_CAST(int64_t, cur_boundary_frac_part * (kDosageMax * (1 - kSmallEpsilon))); |
| 3170 |
} |
| 3171 |
} |
| 3172 |
*prev_boundary_ptr = cur_boundary; |
| 3173 |
*boundary_ct_ptr = boundary_ct + 1; |
| 3174 |
return kPglRetSuccess; |
| 3175 |
} |
| 3176 |
|
| 3177 |
PglErr InitHistogramFromFileOrCommalist(const char* binstr, uint32_t is_fname, double** freq_bounds_ptr, uint64_t** ddosage_bounds_ptr, uint32_t* boundary_ct_ptr, uint32_t** histogram_ptr) { |
| 3178 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 3179 |
TokenStream tks; |
| 3180 |
PreinitTokenStream(&tks); |
| 3181 |
uint32_t max_boundary_ct = 0; |
| 3182 |
PglErr reterr = kPglRetSuccess; |
| 3183 |
{ |
| 3184 |
if (is_fname) { |
| 3185 |
// we want to accept >100000 numbers on a single line. this will reject |
| 3186 |
// "000...{a million more zeroes}...1"; pretty sure that's okay. |
| 3187 |
reterr = InitTokenStreamEx(binstr, 1, 1, &tks); |
| 3188 |
if (unlikely(reterr)) { |
| 3189 |
goto InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL; |
| 3190 |
} |
| 3191 |
} |
| 3192 |
uintptr_t ulii = RoundDownPow2(bigstack_left(), kCacheline); |
| 3193 |
if (unlikely(ulii < 2 * kCacheline)) { |
| 3194 |
goto InitHistogramFromFileOrCommalist_ret_NOMEM; |
| 3195 |
} |
| 3196 |
// 12 = 8 bytes for boundary value + 4 bytes for histogram entry |
| 3197 |
ulii = (ulii - 2 * kCacheline) / 12; |
| 3198 |
#ifdef __LP64__ |
| 3199 |
max_boundary_ct = MINV(ulii, 0x40000000); |
| 3200 |
#else |
| 3201 |
max_boundary_ct = ulii; |
| 3202 |
#endif |
| 3203 |
if (freq_bounds_ptr) { |
| 3204 |
*freq_bounds_ptr = R_CAST(double*, g_bigstack_base); |
| 3205 |
} else { |
| 3206 |
*ddosage_bounds_ptr = R_CAST(uint64_t*, g_bigstack_base); |
| 3207 |
} |
| 3208 |
uint32_t boundary_ct = 0; |
| 3209 |
double prev_boundary = 0.0; |
| 3210 |
if (is_fname) { |
| 3211 |
while (1) { |
| 3212 |
char* shard_boundaries[2]; |
| 3213 |
reterr = TksNext(&tks, 1, shard_boundaries); |
| 3214 |
if (reterr) { |
| 3215 |
break; |
| 3216 |
} |
| 3217 |
char* shard_iter = shard_boundaries[0]; |
| 3218 |
char* shard_end = shard_boundaries[1]; |
| 3219 |
while (1) { |
| 3220 |
shard_iter = FirstPostspaceBounded(shard_iter, shard_end); |
| 3221 |
if (shard_iter == shard_end) { |
| 3222 |
break; |
| 3223 |
} |
| 3224 |
char* token_end = CurTokenEnd(shard_iter); |
| 3225 |
reterr = ProcessBoundaryToken(shard_iter, token_end, binstr, max_boundary_ct, kPglRetMalformedInput, &prev_boundary, &boundary_ct, freq_bounds_ptr, ddosage_bounds_ptr); |
| 3226 |
if (unlikely(reterr)) { |
| 3227 |
goto InitHistogramFromFileOrCommalist_ret_1; |
| 3228 |
} |
| 3229 |
shard_iter = token_end; |
| 3230 |
} |
| 3231 |
} |
| 3232 |
if (unlikely(reterr != kPglRetEof)) { |
| 3233 |
goto InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL; |
| 3234 |
} |
| 3235 |
if (CleanupTokenStream3("--freq {ref|alt1}bins-file= file", &tks, &reterr)) { |
| 3236 |
goto InitHistogramFromFileOrCommalist_ret_1; |
| 3237 |
} |
| 3238 |
} else { |
| 3239 |
const char* binstr_iter = binstr; |
| 3240 |
while (1) { |
| 3241 |
const char* tok_end = strchrnul(binstr_iter, ','); |
| 3242 |
reterr = ProcessBoundaryToken(binstr_iter, tok_end, "--freq {ref,alt1}bins= list", max_boundary_ct, kPglRetInvalidCmdline, &prev_boundary, &boundary_ct, freq_bounds_ptr, ddosage_bounds_ptr); |
| 3243 |
if (unlikely(reterr)) { |
| 3244 |
goto InitHistogramFromFileOrCommalist_ret_1; |
| 3245 |
} |
| 3246 |
if (!(*tok_end)) { |
| 3247 |
break; |
| 3248 |
} |
| 3249 |
binstr_iter = &(tok_end[1]); |
| 3250 |
} |
| 3251 |
} |
| 3252 |
*boundary_ct_ptr = boundary_ct; |
| 3253 |
g_bigstack_base += RoundUpPow2(boundary_ct * (8 * k1LU), kCacheline); |
| 3254 |
*histogram_ptr = S_CAST(uint32_t*, bigstack_alloc_raw_rd((boundary_ct + 1) * sizeof(int32_t))); |
| 3255 |
ZeroU32Arr(boundary_ct + 1, *histogram_ptr); |
| 3256 |
} |
| 3257 |
while (0) { |
| 3258 |
InitHistogramFromFileOrCommalist_ret_NOMEM: |
| 3259 |
reterr = kPglRetNomem; |
| 3260 |
break; |
| 3261 |
InitHistogramFromFileOrCommalist_ret_TKSTREAM_FAIL: |
| 3262 |
TokenStreamErrPrint("--freq {ref|alt1}bins-file= file", &tks); |
| 3263 |
break; |
| 3264 |
} |
| 3265 |
InitHistogramFromFileOrCommalist_ret_1: |
| 3266 |
CleanupTokenStream2("--freq {ref|alt1}bins-file= file", &tks, &reterr); |
| 3267 |
BigstackEndReset(bigstack_end_mark); |
| 3268 |
return reterr; |
| 3269 |
} |
| 3270 |
|
| 3271 |
PglErr WriteAlleleFreqs(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const uint64_t* founder_allele_ddosages, const double* imp_r2_vals, const char* ref_binstr, const char* alt1_binstr, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_allele_slen, PgenGlobalFlags gflags, FreqRptFlags freq_rpt_flags, uint32_t max_thread_ct, uint32_t nonfounders, char* outname, char* outname_end) { |
| 3272 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3273 |
FILE* outfile = nullptr; |
| 3274 |
char* cswritep = nullptr; |
| 3275 |
CompressStreamState css; |
| 3276 |
PglErr reterr = kPglRetSuccess; |
| 3277 |
PreinitCstream(&css); |
| 3278 |
{ |
| 3279 |
const uint32_t counts = (freq_rpt_flags / kfAlleleFreqCounts) & 1; |
| 3280 |
if (counts) { |
| 3281 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".acount"); |
| 3282 |
} else { |
| 3283 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".afreq"); |
| 3284 |
} |
| 3285 |
if (!(freq_rpt_flags & kfAlleleFreqBinsOnly)) { |
| 3286 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 3287 |
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + max_allele_ct * (24 * k1LU) + 2 * max_allele_slen; |
| 3288 |
const uint32_t output_zst = freq_rpt_flags & kfAlleleFreqZs; |
| 3289 |
if (output_zst) { |
| 3290 |
snprintf(&(outname_end[6 + counts]), kMaxOutfnameExtBlen - 7, ".zst"); |
| 3291 |
} |
| 3292 |
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep); |
| 3293 |
if (unlikely(reterr)) { |
| 3294 |
goto WriteAlleleFreqs_ret_1; |
| 3295 |
} |
| 3296 |
*cswritep++ = '#'; |
| 3297 |
const uint32_t chr_col = freq_rpt_flags & kfAlleleFreqColChrom; |
| 3298 |
|
| 3299 |
// includes trailing tab |
| 3300 |
char* chr_buf; |
| 3301 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 3302 |
goto WriteAlleleFreqs_ret_NOMEM; |
| 3303 |
} |
| 3304 |
if (chr_col) { |
| 3305 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 3306 |
} |
| 3307 |
if (freq_rpt_flags & kfAlleleFreqColPos) { |
| 3308 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 3309 |
} else { |
| 3310 |
variant_bps = nullptr; |
| 3311 |
} |
| 3312 |
cswritep = strcpya_k(cswritep, "ID"); |
| 3313 |
const uint32_t ref_col = freq_rpt_flags & kfAlleleFreqColRef; |
| 3314 |
if (ref_col) { |
| 3315 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 3316 |
} |
| 3317 |
const uint32_t alt1_col = freq_rpt_flags & kfAlleleFreqColAlt1; |
| 3318 |
if (alt1_col) { |
| 3319 |
cswritep = strcpya_k(cswritep, "\tALT1"); |
| 3320 |
} |
| 3321 |
const uint32_t alt_col = freq_rpt_flags & kfAlleleFreqColAlt; |
| 3322 |
if (alt_col) { |
| 3323 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 3324 |
} |
| 3325 |
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 3326 |
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, freq_rpt_flags / kfAlleleFreqColMaybeprovref, raw_variant_ct, all_nonref); |
| 3327 |
if (provref_col) { |
| 3328 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 3329 |
} |
| 3330 |
const uint32_t reffreq_col = freq_rpt_flags & kfAlleleFreqColReffreq; |
| 3331 |
if (reffreq_col) { |
| 3332 |
cswritep = strcpya_k(cswritep, "\tREF_"); |
| 3333 |
if (counts) { |
| 3334 |
cswritep = strcpya_k(cswritep, "CT"); |
| 3335 |
} else { |
| 3336 |
cswritep = strcpya_k(cswritep, "FREQ"); |
| 3337 |
} |
| 3338 |
} |
| 3339 |
const uint32_t alt1freq_col = freq_rpt_flags & kfAlleleFreqColAlt1freq; |
| 3340 |
if (alt1freq_col) { |
| 3341 |
cswritep = strcpya_k(cswritep, "\tALT1_"); |
| 3342 |
if (counts) { |
| 3343 |
cswritep = strcpya_k(cswritep, "CT"); |
| 3344 |
} else { |
| 3345 |
cswritep = strcpya_k(cswritep, "FREQ"); |
| 3346 |
} |
| 3347 |
} |
| 3348 |
const uint32_t freq_col = freq_rpt_flags & (kfAlleleFreqColFreq | kfAlleleFreqColAltfreq); |
| 3349 |
const uint32_t commalist_exclude_ref = (freq_rpt_flags & (kfAlleleFreqColAltfreq | kfAlleleFreqColAlteq | kfAlleleFreqColAlteqz | kfAlleleFreqColAltnumeq))? 1 : 0; |
| 3350 |
const uint32_t eq_col = freq_rpt_flags & (kfAlleleFreqColEq | kfAlleleFreqColEqz | kfAlleleFreqColAlteq | kfAlleleFreqColAlteqz | kfAlleleFreqColNumeq | kfAlleleFreqColAltnumeq); |
| 3351 |
const uint32_t eq_includez = freq_rpt_flags & (kfAlleleFreqColEqz | kfAlleleFreqColAlteqz); |
| 3352 |
const uint32_t eq_num = freq_rpt_flags & (kfAlleleFreqColNumeq | kfAlleleFreqColAltnumeq); |
| 3353 |
if (freq_col || eq_col) { |
| 3354 |
*cswritep++ = '\t'; |
| 3355 |
if (commalist_exclude_ref) { |
| 3356 |
cswritep = strcpya_k(cswritep, "ALT_"); |
| 3357 |
} |
| 3358 |
if (eq_num) { |
| 3359 |
cswritep = strcpya_k(cswritep, "NUM_"); |
| 3360 |
} |
| 3361 |
if (counts) { |
| 3362 |
cswritep = strcpya_k(cswritep, "CTS"); |
| 3363 |
} else { |
| 3364 |
cswritep = strcpya_k(cswritep, "FREQS"); |
| 3365 |
} |
| 3366 |
} |
| 3367 |
const uint32_t imp_r2_col = freq_rpt_flags & (kfAlleleFreqColMachR2 | kfAlleleFreqColMinimac3R2); |
| 3368 |
if (imp_r2_col) { |
| 3369 |
// These two columns are currently mutually exclusive. |
| 3370 |
if (freq_rpt_flags & kfAlleleFreqColMachR2) { |
| 3371 |
cswritep = strcpya_k(cswritep, "\tMACH_R2"); |
| 3372 |
} else { |
| 3373 |
cswritep = strcpya_k(cswritep, "\tMINIMAC3_R2"); |
| 3374 |
} |
| 3375 |
} |
| 3376 |
const uint32_t nobs_col = freq_rpt_flags & kfAlleleFreqColNobs; |
| 3377 |
if (nobs_col) { |
| 3378 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 3379 |
} |
| 3380 |
AppendBinaryEoln(&cswritep); |
| 3381 |
|
| 3382 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 3383 |
const uint32_t mt_code = cip->xymt_codes[kChrOffsetMT]; |
| 3384 |
uintptr_t variant_uidx_base = 0; |
| 3385 |
uintptr_t cur_bits = variant_include[0]; |
| 3386 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 3387 |
uint32_t chr_end = 0; |
| 3388 |
uint32_t chr_buf_blen = 0; |
| 3389 |
uint32_t suppress_imp_r2 = 0; |
| 3390 |
uint32_t pct = 0; |
| 3391 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 3392 |
uint32_t cur_allele_ct = 2; |
| 3393 |
printf("--freq%s%s: 0%%", output_zst? " zs" : "", counts? " counts" : ""); |
| 3394 |
fflush(stdout); |
| 3395 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 3396 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3397 |
if (variant_uidx >= chr_end) { |
| 3398 |
do { |
| 3399 |
++chr_fo_idx; |
| 3400 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 3401 |
} while (variant_uidx >= chr_end); |
| 3402 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 3403 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 3404 |
suppress_imp_r2 = (chr_idx == x_code) || (chr_idx == mt_code); |
| 3405 |
*chr_name_end = '\t'; |
| 3406 |
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf); |
| 3407 |
} |
| 3408 |
if (chr_col) { |
| 3409 |
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen); |
| 3410 |
} |
| 3411 |
if (variant_bps) { |
| 3412 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 3413 |
} |
| 3414 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 3415 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 3416 |
if (allele_idx_offsets) { |
| 3417 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3418 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 3419 |
} |
| 3420 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 3421 |
if (ref_col) { |
| 3422 |
*cswritep++ = '\t'; |
| 3423 |
cswritep = strcpya(cswritep, cur_alleles[0]); |
| 3424 |
} |
| 3425 |
if (alt1_col) { |
| 3426 |
*cswritep++ = '\t'; |
| 3427 |
cswritep = strcpya(cswritep, cur_alleles[1]); |
| 3428 |
} |
| 3429 |
if (alt_col) { |
| 3430 |
*cswritep++ = '\t'; |
| 3431 |
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3432 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 3433 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3434 |
} |
| 3435 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 3436 |
} |
| 3437 |
--cswritep; |
| 3438 |
} |
| 3439 |
if (provref_col) { |
| 3440 |
*cswritep++ = '\t'; |
| 3441 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N'; |
| 3442 |
} |
| 3443 |
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]); |
| 3444 |
uint64_t tot_allele_ddosage = cur_allele_ddosages[0]; |
| 3445 |
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3446 |
tot_allele_ddosage += cur_allele_ddosages[allele_idx]; |
| 3447 |
} |
| 3448 |
double tot_allele_ddosage_recip = 0.0; |
| 3449 |
if (!counts) { |
| 3450 |
tot_allele_ddosage_recip = 1.0 / u63tod(tot_allele_ddosage); |
| 3451 |
} |
| 3452 |
if (reffreq_col) { |
| 3453 |
*cswritep++ = '\t'; |
| 3454 |
const uint64_t ref_ddosage = cur_allele_ddosages[0]; |
| 3455 |
if (counts) { |
| 3456 |
// update (22 Nov 2019): we want --read-freq to be able to exactly |
| 3457 |
// replicate the original frequency. dosagetoa() is not good |
| 3458 |
// enough for this purpose. |
| 3459 |
cswritep = ddosagetoa_full(ref_ddosage, cswritep); |
| 3460 |
} else { |
| 3461 |
cswritep = dtoa_g(u63tod(ref_ddosage) * tot_allele_ddosage_recip, cswritep); |
| 3462 |
} |
| 3463 |
} |
| 3464 |
if (alt1freq_col) { |
| 3465 |
*cswritep++ = '\t'; |
| 3466 |
const uint64_t alt1_ddosage = cur_allele_ddosages[1]; |
| 3467 |
if (counts) { |
| 3468 |
cswritep = ddosagetoa_full(alt1_ddosage, cswritep); |
| 3469 |
} else { |
| 3470 |
cswritep = dtoa_g(u63tod(alt1_ddosage) * tot_allele_ddosage_recip, cswritep); |
| 3471 |
} |
| 3472 |
} |
| 3473 |
if (freq_col) { |
| 3474 |
*cswritep++ = '\t'; |
| 3475 |
for (uint32_t allele_idx = commalist_exclude_ref; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3476 |
const uint64_t cur_allele_ddosage = cur_allele_ddosages[allele_idx]; |
| 3477 |
if (counts) { |
| 3478 |
cswritep = ddosagetoa_full(cur_allele_ddosage, cswritep); |
| 3479 |
} else { |
| 3480 |
cswritep = dtoa_g(u63tod(cur_allele_ddosage) * tot_allele_ddosage_recip, cswritep); |
| 3481 |
} |
| 3482 |
*cswritep++ = ','; |
| 3483 |
} |
| 3484 |
--cswritep; |
| 3485 |
} else if (eq_col) { |
| 3486 |
*cswritep++ = '\t'; |
| 3487 |
uint32_t at_least_one_entry = 0; |
| 3488 |
for (uint32_t allele_idx = commalist_exclude_ref; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3489 |
const uint64_t cur_allele_ddosage = cur_allele_ddosages[allele_idx]; |
| 3490 |
if (eq_includez || cur_allele_ddosage) { |
| 3491 |
if (eq_num) { |
| 3492 |
cswritep = u32toa(allele_idx, cswritep); |
| 3493 |
} else { |
| 3494 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 3495 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3496 |
} |
| 3497 |
const char* cur_allele = cur_alleles[allele_idx]; |
| 3498 |
const char* cur_allele_end_or_eq = strchrnul(cur_allele, '='); |
| 3499 |
if (unlikely(*cur_allele_end_or_eq == '=')) { |
| 3500 |
logerrputs("Error: --freq's 'eq', 'eqz', 'alteq', and 'alteqz' columns cannot be requested\nwhen an allele code contains a '='.\n"); |
| 3501 |
goto WriteAlleleFreqs_ret_INCONSISTENT_INPUT; |
| 3502 |
} |
| 3503 |
cswritep = memcpya(cswritep, cur_allele, cur_allele_end_or_eq - cur_allele); |
| 3504 |
} |
| 3505 |
*cswritep++ = '='; |
| 3506 |
if (counts) { |
| 3507 |
cswritep = ddosagetoa_full(cur_allele_ddosage, cswritep); |
| 3508 |
} else { |
| 3509 |
cswritep = dtoa_g(u63tod(cur_allele_ddosage) * tot_allele_ddosage_recip, cswritep); |
| 3510 |
} |
| 3511 |
*cswritep++ = ','; |
| 3512 |
at_least_one_entry = 1; |
| 3513 |
} |
| 3514 |
} |
| 3515 |
if (at_least_one_entry) { |
| 3516 |
--cswritep; |
| 3517 |
} else { |
| 3518 |
*cswritep++ = '.'; |
| 3519 |
} |
| 3520 |
} |
| 3521 |
if (imp_r2_col) { |
| 3522 |
*cswritep++ = '\t'; |
| 3523 |
if (!suppress_imp_r2) { |
| 3524 |
cswritep = dtoa_g(imp_r2_vals[variant_uidx], cswritep); |
| 3525 |
} else { |
| 3526 |
cswritep = strcpya_k(cswritep, "NA"); |
| 3527 |
} |
| 3528 |
} |
| 3529 |
if (nobs_col) { |
| 3530 |
*cswritep++ = '\t'; |
| 3531 |
cswritep = u32toa(tot_allele_ddosage / kDosageMax, cswritep); |
| 3532 |
} |
| 3533 |
AppendBinaryEoln(&cswritep); |
| 3534 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 3535 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3536 |
} |
| 3537 |
if (variant_idx >= next_print_variant_idx) { |
| 3538 |
if (pct > 10) { |
| 3539 |
putc_unlocked('\b', stdout); |
| 3540 |
} |
| 3541 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 3542 |
printf("\b\b%u%%", pct++); |
| 3543 |
fflush(stdout); |
| 3544 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 3545 |
} |
| 3546 |
} |
| 3547 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 3548 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3549 |
} |
| 3550 |
putc_unlocked('\r', stdout); |
| 3551 |
logprintfww("--freq%s%s: Allele %s (%s) written to %s .\n", output_zst? " zs" : "", counts? " counts" : "", counts? "counts" : "frequencies", nonfounders? "all samples" : "founders only", outname); |
| 3552 |
} |
| 3553 |
|
| 3554 |
if (ref_binstr || alt1_binstr) { |
| 3555 |
BigstackReset(bigstack_mark); |
| 3556 |
double* ref_freq_bounds = nullptr; |
| 3557 |
uint64_t* ref_ddosage_bounds = nullptr; |
| 3558 |
uint32_t* ref_histogram = nullptr; |
| 3559 |
uint32_t ref_boundary_ct = 0; |
| 3560 |
if (ref_binstr) { |
| 3561 |
reterr = InitHistogramFromFileOrCommalist(ref_binstr, (freq_rpt_flags / kfAlleleFreqBinsRefFname) & 1, counts? nullptr : (&ref_freq_bounds), counts? (&ref_ddosage_bounds) : nullptr, &ref_boundary_ct, &ref_histogram); |
| 3562 |
if (unlikely(reterr)) { |
| 3563 |
goto WriteAlleleFreqs_ret_1; |
| 3564 |
} |
| 3565 |
} |
| 3566 |
double* alt1_freq_bounds = nullptr; |
| 3567 |
uint64_t* alt1_ddosage_bounds = nullptr; |
| 3568 |
uint32_t* alt1_histogram = nullptr; |
| 3569 |
uint32_t alt1_boundary_ct = 0; |
| 3570 |
if (alt1_binstr) { |
| 3571 |
reterr = InitHistogramFromFileOrCommalist(alt1_binstr, (freq_rpt_flags / kfAlleleFreqBinsAlt1Fname) & 1, counts? nullptr : (&alt1_freq_bounds), counts? (&alt1_ddosage_bounds) : nullptr, &alt1_boundary_ct, &alt1_histogram); |
| 3572 |
if (unlikely(reterr)) { |
| 3573 |
goto WriteAlleleFreqs_ret_1; |
| 3574 |
} |
| 3575 |
} |
| 3576 |
uintptr_t variant_uidx_base = 0; |
| 3577 |
uintptr_t cur_bits = variant_include[0]; |
| 3578 |
if (!counts) { |
| 3579 |
uint32_t cur_allele_ct = 2; |
| 3580 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 3581 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3582 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 3583 |
if (allele_idx_offsets) { |
| 3584 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3585 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 3586 |
} |
| 3587 |
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]); |
| 3588 |
const uint64_t ref_allele_ddosage = cur_allele_ddosages[0]; |
| 3589 |
const uint64_t alt1_allele_ddosage = cur_allele_ddosages[1]; |
| 3590 |
uint64_t tot_allele_ddosage = ref_allele_ddosage + alt1_allele_ddosage; |
| 3591 |
for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct; ++allele_idx) { |
| 3592 |
tot_allele_ddosage += cur_allele_ddosages[allele_idx]; |
| 3593 |
} |
| 3594 |
const double tot_allele_ddosage_recip = 1.0 / u63tod(tot_allele_ddosage); |
| 3595 |
if (ref_histogram) { |
| 3596 |
ref_histogram[LowerBoundNonemptyD(ref_freq_bounds, ref_boundary_ct, ref_allele_ddosage * tot_allele_ddosage_recip)] += 1; |
| 3597 |
} |
| 3598 |
if (alt1_histogram) { |
| 3599 |
alt1_histogram[LowerBoundNonemptyD(alt1_freq_bounds, alt1_boundary_ct, alt1_allele_ddosage * tot_allele_ddosage_recip)] += 1; |
| 3600 |
} |
| 3601 |
} |
| 3602 |
} else { |
| 3603 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 3604 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3605 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 3606 |
if (allele_idx_offsets) { |
| 3607 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3608 |
} |
| 3609 |
const uint64_t* cur_allele_ddosages = &(founder_allele_ddosages[allele_idx_offset_base]); |
| 3610 |
if (ref_histogram) { |
| 3611 |
ref_histogram[LowerBoundNonemptyU64(ref_ddosage_bounds, ref_boundary_ct, cur_allele_ddosages[0])] += 1; |
| 3612 |
} |
| 3613 |
if (alt1_histogram) { |
| 3614 |
alt1_histogram[LowerBoundNonemptyU64(alt1_ddosage_bounds, alt1_boundary_ct, cur_allele_ddosages[1])] += 1; |
| 3615 |
} |
| 3616 |
} |
| 3617 |
} |
| 3618 |
for (uint32_t is_alt1 = 0; is_alt1 != 2; ++is_alt1) { |
| 3619 |
const uint32_t* cur_histogram = is_alt1? alt1_histogram : ref_histogram; |
| 3620 |
if (!cur_histogram) { |
| 3621 |
continue; |
| 3622 |
} |
| 3623 |
char* outname_end2 = &(outname_end[6 + counts]); |
| 3624 |
if (!is_alt1) { |
| 3625 |
outname_end2 = strcpya_k(outname_end2, ".ref"); |
| 3626 |
} else { |
| 3627 |
outname_end2 = strcpya_k(outname_end2, ".alt1"); |
| 3628 |
} |
| 3629 |
snprintf(outname_end2, kMaxOutfnameExtBlen - 12, ".bins"); |
| 3630 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) { |
| 3631 |
goto WriteAlleleFreqs_ret_OPEN_FAIL; |
| 3632 |
} |
| 3633 |
char* textbuf = g_textbuf; |
| 3634 |
char* textbuf_flush = &(textbuf[kMaxMediumLine]); |
| 3635 |
char* write_iter = strcpya_k(textbuf, "#BIN_START\tOBS_CT" EOLN_STR); |
| 3636 |
const uint32_t cur_boundary_ct = is_alt1? alt1_boundary_ct : ref_boundary_ct; |
| 3637 |
if (!counts) { |
| 3638 |
const double* cur_freq_bounds = is_alt1? alt1_freq_bounds : ref_freq_bounds; |
| 3639 |
for (uint32_t bin_idx = 0; bin_idx <= cur_boundary_ct; ++bin_idx) { |
| 3640 |
if (!bin_idx) { |
| 3641 |
*write_iter++ = '0'; |
| 3642 |
} else { |
| 3643 |
write_iter = dtoa_g(cur_freq_bounds[bin_idx - 1] * (1.0 / (1 - kSmallEpsilon)), write_iter); |
| 3644 |
} |
| 3645 |
*write_iter++ = '\t'; |
| 3646 |
write_iter = u32toa(cur_histogram[bin_idx], write_iter); |
| 3647 |
AppendBinaryEoln(&write_iter); |
| 3648 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 3649 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3650 |
} |
| 3651 |
} |
| 3652 |
} else { |
| 3653 |
const uint64_t* cur_ddosage_bounds = is_alt1? alt1_ddosage_bounds : ref_ddosage_bounds; |
| 3654 |
for (uint32_t bin_idx = 0; bin_idx <= cur_boundary_ct; ++bin_idx) { |
| 3655 |
if (!bin_idx) { |
| 3656 |
*write_iter++ = '0'; |
| 3657 |
} else { |
| 3658 |
write_iter = ddosagetoa(1 + cur_ddosage_bounds[bin_idx - 1], write_iter); |
| 3659 |
} |
| 3660 |
*write_iter++ = '\t'; |
| 3661 |
write_iter = u32toa(cur_histogram[bin_idx], write_iter); |
| 3662 |
AppendBinaryEoln(&write_iter); |
| 3663 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 3664 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3665 |
} |
| 3666 |
} |
| 3667 |
} |
| 3668 |
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) { |
| 3669 |
goto WriteAlleleFreqs_ret_WRITE_FAIL; |
| 3670 |
} |
| 3671 |
const uint32_t cur_is_file = freq_rpt_flags & (is_alt1? kfAlleleFreqBinsAlt1Fname : kfAlleleFreqBinsRefFname); |
| 3672 |
logprintfww("--freq%s %sbins%s=: Histogram written to %s .\n", counts? " counts" : "", is_alt1? "alt1" : "ref", cur_is_file? "-file" : "", outname); |
| 3673 |
} |
| 3674 |
} |
| 3675 |
} |
| 3676 |
while (0) { |
| 3677 |
WriteAlleleFreqs_ret_NOMEM: |
| 3678 |
reterr = kPglRetNomem; |
| 3679 |
break; |
| 3680 |
WriteAlleleFreqs_ret_OPEN_FAIL: |
| 3681 |
reterr = kPglRetOpenFail; |
| 3682 |
break; |
| 3683 |
WriteAlleleFreqs_ret_WRITE_FAIL: |
| 3684 |
reterr = kPglRetWriteFail; |
| 3685 |
break; |
| 3686 |
WriteAlleleFreqs_ret_INCONSISTENT_INPUT: |
| 3687 |
reterr = kPglRetInconsistentInput; |
| 3688 |
break; |
| 3689 |
} |
| 3690 |
WriteAlleleFreqs_ret_1: |
| 3691 |
CswriteCloseCond(&css, cswritep); |
| 3692 |
fclose_cond(outfile); |
| 3693 |
BigstackReset(bigstack_mark); |
| 3694 |
return reterr; |
| 3695 |
} |
| 3696 |
|
| 3697 |
PglErr WriteGenoCounts(const uintptr_t* sample_include, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const STD_ARRAY_PTR_DECL(uint32_t, 3, raw_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, x_male_geno_cts), uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t male_ct, uint32_t nosex_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t x_start, uint32_t max_allele_slen, PgenGlobalFlags gflags, GenoCountsFlags geno_counts_flags, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) { |
| 3698 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 3699 |
char* cswritep = nullptr; |
| 3700 |
CompressStreamState css; |
| 3701 |
PglErr reterr = kPglRetSuccess; |
| 3702 |
PreinitCstream(&css); |
| 3703 |
{ |
| 3704 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 3705 |
char* chr_buf; |
| 3706 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 3707 |
goto WriteGenoCounts_ret_NOMEM; |
| 3708 |
} |
| 3709 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 3710 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 3711 |
const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp); |
| 3712 |
uint32_t* sample_include_cumulative_popcounts = nullptr; |
| 3713 |
uintptr_t* sex_male_collapsed = nullptr; // chrX |
| 3714 |
const uintptr_t* sex_nonfemale = sex_male; |
| 3715 |
uint32_t* sex_nonfemale_cumulative_popcounts = nullptr; // chrY |
| 3716 |
PgenVariant pgv; |
| 3717 |
pgv.genovec = nullptr; |
| 3718 |
pgv.patch_01_set = nullptr; |
| 3719 |
pgv.patch_01_vals = nullptr; |
| 3720 |
pgv.patch_10_set = nullptr; |
| 3721 |
pgv.patch_10_vals = nullptr; |
| 3722 |
uint32_t* diploid_pair_cts = nullptr; |
| 3723 |
uint32_t* hap_cts = nullptr; |
| 3724 |
const uint32_t more_counts_needed = (max_allele_ct > 2) && (geno_counts_flags & (kfGenoCountsColRefalt1 | kfGenoCountsColRefalt | kfGenoCountsColHomalt1 | kfGenoCountsColAltxy | kfGenoCountsColXy | kfGenoCountsColHapalt1 | kfGenoCountsColHapalt | kfGenoCountsColHap | kfGenoCountsColNumeq)); |
| 3725 |
const uint32_t nonfemale_ct = male_ct + nosex_ct; |
| 3726 |
if (more_counts_needed) { |
| 3727 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 3728 |
bigstack_alloc_w(sample_ctl, &sex_male_collapsed) || |
| 3729 |
bigstack_alloc_u32(raw_sample_ctl, &sex_nonfemale_cumulative_popcounts) || |
| 3730 |
bigstack_alloc_w(NypCtToWordCt(raw_sample_ct), &pgv.genovec) || |
| 3731 |
bigstack_alloc_w(sample_ctl, &pgv.patch_01_set) || |
| 3732 |
bigstack_alloc_ac(sample_ct, &pgv.patch_01_vals) || |
| 3733 |
bigstack_alloc_w(sample_ctl, &pgv.patch_10_set) || |
| 3734 |
bigstack_alloc_ac(2 * sample_ct, &pgv.patch_10_vals) || |
| 3735 |
bigstack_alloc_u32(max_allele_ct * max_allele_ct, &diploid_pair_cts) || |
| 3736 |
bigstack_alloc_u32(max_allele_ct, &hap_cts))) { |
| 3737 |
goto WriteGenoCounts_ret_NOMEM; |
| 3738 |
} |
| 3739 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 3740 |
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed); |
| 3741 |
if (nosex_ct) { |
| 3742 |
uintptr_t* nonfemale_tmp; |
| 3743 |
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &nonfemale_tmp))) { |
| 3744 |
goto WriteGenoCounts_ret_NOMEM; |
| 3745 |
} |
| 3746 |
AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, nonfemale_tmp); |
| 3747 |
sex_nonfemale = nonfemale_tmp; |
| 3748 |
} |
| 3749 |
FillCumulativePopcounts(sex_nonfemale, raw_sample_ctl, sex_nonfemale_cumulative_popcounts); |
| 3750 |
} |
| 3751 |
// Will need to remove quadratic dependency on max_allele_ct if |
| 3752 |
// sizeof(AlleleCode) > 1. |
| 3753 |
// The actual number of numeq and {alt}xy entries is roughly half of |
| 3754 |
// allele_ct^2, so 12 * allele_ct^2 allows 20 bytes per entry when both |
| 3755 |
// fields are present simultaneously, which is more than enough. (The |
| 3756 |
// surplus and the 512 constant are enough to cover the linearly-growing |
| 3757 |
// fields.) |
| 3758 |
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + max_allele_ct * max_allele_ct * 20 + 2 * max_allele_slen; |
| 3759 |
const uint32_t output_zst = geno_counts_flags & kfGenoCountsZs; |
| 3760 |
OutnameZstSet(".gcount", output_zst, outname_end); |
| 3761 |
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep); |
| 3762 |
if (unlikely(reterr)) { |
| 3763 |
goto WriteGenoCounts_ret_1; |
| 3764 |
} |
| 3765 |
*cswritep++ = '#'; |
| 3766 |
const uint32_t chr_col = geno_counts_flags & kfGenoCountsColChrom; |
| 3767 |
|
| 3768 |
// includes trailing tab |
| 3769 |
if (chr_col) { |
| 3770 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 3771 |
} |
| 3772 |
if (geno_counts_flags & kfGenoCountsColPos) { |
| 3773 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 3774 |
} else { |
| 3775 |
variant_bps = nullptr; |
| 3776 |
} |
| 3777 |
cswritep = strcpya_k(cswritep, "ID"); |
| 3778 |
const uint32_t ref_col = geno_counts_flags & kfGenoCountsColRef; |
| 3779 |
if (ref_col) { |
| 3780 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 3781 |
} |
| 3782 |
const uint32_t alt1_col = geno_counts_flags & kfGenoCountsColAlt1; |
| 3783 |
if (alt1_col) { |
| 3784 |
cswritep = strcpya_k(cswritep, "\tALT1"); |
| 3785 |
} |
| 3786 |
const uint32_t alt_col = geno_counts_flags & kfGenoCountsColAlt; |
| 3787 |
if (alt_col) { |
| 3788 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 3789 |
} |
| 3790 |
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 3791 |
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, geno_counts_flags / kfGenoCountsColMaybeprovref, raw_variant_ct, all_nonref); |
| 3792 |
if (provref_col) { |
| 3793 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 3794 |
} |
| 3795 |
const uint32_t homref_col = geno_counts_flags & kfGenoCountsColHomref; |
| 3796 |
if (homref_col) { |
| 3797 |
cswritep = strcpya_k(cswritep, "\tHOM_REF_CT"); |
| 3798 |
} |
| 3799 |
const uint32_t refalt1_col = geno_counts_flags & kfGenoCountsColRefalt1; |
| 3800 |
if (refalt1_col) { |
| 3801 |
cswritep = strcpya_k(cswritep, "\tHET_REF_ALT1_CT"); |
| 3802 |
} |
| 3803 |
const uint32_t refalt_col = geno_counts_flags & kfGenoCountsColRefalt; |
| 3804 |
if (refalt_col) { |
| 3805 |
cswritep = strcpya_k(cswritep, "\tHET_REF_ALT_CTS"); |
| 3806 |
} |
| 3807 |
const uint32_t homalt1_col = geno_counts_flags & kfGenoCountsColHomalt1; |
| 3808 |
if (homalt1_col) { |
| 3809 |
cswritep = strcpya_k(cswritep, "\tHOM_ALT1_CT"); |
| 3810 |
} |
| 3811 |
const uint32_t xy_col = geno_counts_flags & (kfGenoCountsColAltxy | kfGenoCountsColXy); |
| 3812 |
const uint32_t xy_col_altonly = (geno_counts_flags / kfGenoCountsColAltxy) & 1; |
| 3813 |
if (xy_col) { |
| 3814 |
*cswritep++ = '\t'; |
| 3815 |
if (xy_col_altonly) { |
| 3816 |
cswritep = strcpya_k(cswritep, "TWO_ALT_GENO_CTS"); |
| 3817 |
} else { |
| 3818 |
cswritep = strcpya_k(cswritep, "DIPLOID_GENO_CTS"); |
| 3819 |
} |
| 3820 |
} |
| 3821 |
const uint32_t hapref_col = geno_counts_flags & kfGenoCountsColHapref; |
| 3822 |
if (hapref_col) { |
| 3823 |
cswritep = strcpya_k(cswritep, "\tHAP_REF_CT"); |
| 3824 |
} |
| 3825 |
const uint32_t hapalt1_col = geno_counts_flags & kfGenoCountsColHapalt1; |
| 3826 |
if (hapalt1_col) { |
| 3827 |
cswritep = strcpya_k(cswritep, "\tHAP_ALT1_CT"); |
| 3828 |
} |
| 3829 |
const uint32_t hap_col = geno_counts_flags & (kfGenoCountsColHapalt | kfGenoCountsColHap); |
| 3830 |
const uint32_t hap_col_altonly = (geno_counts_flags / kfGenoCountsColHapalt) & 1; |
| 3831 |
if (hap_col) { |
| 3832 |
if (hap_col_altonly) { |
| 3833 |
cswritep = strcpya_k(cswritep, "\tHAP_ALT_CTS"); |
| 3834 |
} else { |
| 3835 |
cswritep = strcpya_k(cswritep, "\tHAP_CTS"); |
| 3836 |
} |
| 3837 |
} |
| 3838 |
const uint32_t numeq_col = geno_counts_flags & kfGenoCountsColNumeq; |
| 3839 |
if (numeq_col) { |
| 3840 |
cswritep = strcpya_k(cswritep, "\tGENO_NUM_CTS"); |
| 3841 |
} |
| 3842 |
const uint32_t missing_col = geno_counts_flags & kfGenoCountsColMissing; |
| 3843 |
if (missing_col) { |
| 3844 |
cswritep = strcpya_k(cswritep, "\tMISSING_CT"); |
| 3845 |
} |
| 3846 |
const uint32_t nobs_col = geno_counts_flags & kfGenoCountsColNobs; |
| 3847 |
if (nobs_col) { |
| 3848 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 3849 |
} |
| 3850 |
AppendBinaryEoln(&cswritep); |
| 3851 |
|
| 3852 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 3853 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 3854 |
const uintptr_t* cur_sample_include = nullptr; |
| 3855 |
uintptr_t variant_uidx_base = 0; |
| 3856 |
uintptr_t cur_bits = variant_include[0]; |
| 3857 |
uint32_t is_autosomal_diploid = 0; |
| 3858 |
uint32_t is_x = 0; |
| 3859 |
uint32_t is_y = 0; |
| 3860 |
uint32_t nobs_base = 0; |
| 3861 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 3862 |
uint32_t chr_end = 0; |
| 3863 |
uint32_t chr_buf_blen = 0; |
| 3864 |
uint32_t homref_ct = 0; |
| 3865 |
uint32_t het_ct = 0; |
| 3866 |
uint32_t homalt1_ct = 0; |
| 3867 |
uint32_t hapref_ct = 0; |
| 3868 |
uint32_t hapalt1_ct = 0; |
| 3869 |
uint32_t pct = 0; |
| 3870 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 3871 |
printf("--geno-counts%s: 0%%", output_zst? " zs" : ""); |
| 3872 |
fflush(stdout); |
| 3873 |
PgrSampleSubsetIndex pssi; |
| 3874 |
PgrClearSampleSubsetIndex(simple_pgrp, &pssi); |
| 3875 |
uint32_t allele_ct = 2; |
| 3876 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 3877 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 3878 |
if (variant_uidx >= chr_end) { |
| 3879 |
do { |
| 3880 |
++chr_fo_idx; |
| 3881 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 3882 |
} while (variant_uidx >= chr_end); |
| 3883 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 3884 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 3885 |
*chr_name_end = '\t'; |
| 3886 |
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf); |
| 3887 |
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx); |
| 3888 |
nobs_base = sample_ct; |
| 3889 |
is_x = (chr_idx == x_code); |
| 3890 |
is_y = (chr_idx == y_code); |
| 3891 |
cur_sample_include = sample_include; |
| 3892 |
const uint32_t* cur_cumulative_popcounts = sample_include_cumulative_popcounts; |
| 3893 |
if (!is_autosomal_diploid) { |
| 3894 |
if (is_y) { |
| 3895 |
cur_sample_include = sex_nonfemale; |
| 3896 |
cur_cumulative_popcounts = sex_nonfemale_cumulative_popcounts; |
| 3897 |
nobs_base = nonfemale_ct; |
| 3898 |
} |
| 3899 |
} |
| 3900 |
PgrSetSampleSubsetIndex(cur_cumulative_popcounts, simple_pgrp, &pssi); |
| 3901 |
homref_ct = 0; |
| 3902 |
het_ct = 0; |
| 3903 |
homalt1_ct = 0; |
| 3904 |
hapref_ct = 0; |
| 3905 |
hapalt1_ct = 0; |
| 3906 |
} |
| 3907 |
if (chr_col) { |
| 3908 |
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen); |
| 3909 |
} |
| 3910 |
if (variant_bps) { |
| 3911 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 3912 |
} |
| 3913 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 3914 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 3915 |
if (allele_idx_offsets) { |
| 3916 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 3917 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 3918 |
} |
| 3919 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 3920 |
if (ref_col) { |
| 3921 |
*cswritep++ = '\t'; |
| 3922 |
cswritep = strcpya(cswritep, cur_alleles[0]); |
| 3923 |
} |
| 3924 |
if (alt1_col) { |
| 3925 |
*cswritep++ = '\t'; |
| 3926 |
cswritep = strcpya(cswritep, cur_alleles[1]); |
| 3927 |
} |
| 3928 |
if (alt_col) { |
| 3929 |
*cswritep++ = '\t'; |
| 3930 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 3931 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 3932 |
goto WriteGenoCounts_ret_WRITE_FAIL; |
| 3933 |
} |
| 3934 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 3935 |
} |
| 3936 |
--cswritep; |
| 3937 |
} |
| 3938 |
if (provref_col) { |
| 3939 |
*cswritep++ = '\t'; |
| 3940 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N'; |
| 3941 |
} |
| 3942 |
STD_ARRAY_KREF(uint32_t, 3) cur_raw_geno_cts = raw_geno_cts[variant_uidx]; |
| 3943 |
uint32_t missing_ct; |
| 3944 |
if ((allele_ct == 2) || (!more_counts_needed)) { |
| 3945 |
if (is_autosomal_diploid) { |
| 3946 |
homref_ct = cur_raw_geno_cts[0]; |
| 3947 |
het_ct = cur_raw_geno_cts[1]; |
| 3948 |
homalt1_ct = cur_raw_geno_cts[2]; |
| 3949 |
missing_ct = nobs_base - homref_ct - het_ct - homalt1_ct; |
| 3950 |
} else { |
| 3951 |
if (is_x) { |
| 3952 |
// bugfix (8 Oct 2017): don't set these in haploid case |
| 3953 |
homref_ct = cur_raw_geno_cts[0]; |
| 3954 |
het_ct = cur_raw_geno_cts[1]; |
| 3955 |
homalt1_ct = cur_raw_geno_cts[2]; |
| 3956 |
if (x_male_geno_cts) { |
| 3957 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = x_male_geno_cts[variant_uidx - x_start]; |
| 3958 |
hapref_ct = cur_male_geno_cts[0]; |
| 3959 |
homref_ct -= hapref_ct; |
| 3960 |
het_ct -= cur_male_geno_cts[1]; |
| 3961 |
hapalt1_ct = cur_male_geno_cts[2]; |
| 3962 |
homalt1_ct -= hapalt1_ct; |
| 3963 |
} |
| 3964 |
missing_ct = nobs_base - homref_ct - het_ct - homalt1_ct - hapref_ct - hapalt1_ct; |
| 3965 |
} else { |
| 3966 |
// chrY or other pure-haploid; hethap treated as missing |
| 3967 |
hapref_ct = cur_raw_geno_cts[0]; |
| 3968 |
hapalt1_ct = cur_raw_geno_cts[2]; |
| 3969 |
missing_ct = nobs_base - hapref_ct - hapalt1_ct; |
| 3970 |
} |
| 3971 |
} |
| 3972 |
if (homref_col) { |
| 3973 |
*cswritep++ = '\t'; |
| 3974 |
cswritep = u32toa(homref_ct, cswritep); |
| 3975 |
} |
| 3976 |
if (refalt1_col) { |
| 3977 |
*cswritep++ = '\t'; |
| 3978 |
cswritep = u32toa(het_ct, cswritep); |
| 3979 |
} |
| 3980 |
if (refalt_col) { |
| 3981 |
*cswritep++ = '\t'; |
| 3982 |
cswritep = u32toa(het_ct, cswritep); |
| 3983 |
} |
| 3984 |
if (homalt1_col) { |
| 3985 |
*cswritep++ = '\t'; |
| 3986 |
cswritep = u32toa(homalt1_ct, cswritep); |
| 3987 |
} |
| 3988 |
if (xy_col_altonly) { |
| 3989 |
*cswritep++ = '\t'; |
| 3990 |
cswritep = u32toa(homalt1_ct, cswritep); |
| 3991 |
} else if (xy_col) { |
| 3992 |
*cswritep++ = '\t'; |
| 3993 |
cswritep = u32toa_x(homref_ct, ',', cswritep); |
| 3994 |
cswritep = u32toa_x(het_ct, ',', cswritep); |
| 3995 |
cswritep = u32toa(homalt1_ct, cswritep); |
| 3996 |
} |
| 3997 |
if (hapref_col) { |
| 3998 |
*cswritep++ = '\t'; |
| 3999 |
cswritep = u32toa(hapref_ct, cswritep); |
| 4000 |
} |
| 4001 |
if (hapalt1_col) { |
| 4002 |
*cswritep++ = '\t'; |
| 4003 |
cswritep = u32toa(hapalt1_ct, cswritep); |
| 4004 |
} |
| 4005 |
if (hap_col) { |
| 4006 |
*cswritep++ = '\t'; |
| 4007 |
if (!hap_col_altonly) { |
| 4008 |
cswritep = u32toa_x(hapref_ct, ',', cswritep); |
| 4009 |
} |
| 4010 |
cswritep = u32toa(hapalt1_ct, cswritep); |
| 4011 |
} |
| 4012 |
if (numeq_col) { |
| 4013 |
*cswritep++ = '\t'; |
| 4014 |
if (homref_ct) { |
| 4015 |
cswritep = strcpya_k(cswritep, "0/0="); |
| 4016 |
cswritep = u32toa_x(homref_ct, ',', cswritep); |
| 4017 |
} |
| 4018 |
if (het_ct) { |
| 4019 |
cswritep = strcpya_k(cswritep, "0/1="); |
| 4020 |
cswritep = u32toa_x(het_ct, ',', cswritep); |
| 4021 |
} |
| 4022 |
if (homalt1_ct) { |
| 4023 |
cswritep = strcpya_k(cswritep, "1/1="); |
| 4024 |
cswritep = u32toa_x(homalt1_ct, ',', cswritep); |
| 4025 |
} |
| 4026 |
if (hapref_ct) { |
| 4027 |
cswritep = strcpya_k(cswritep, "0="); |
| 4028 |
cswritep = u32toa_x(hapref_ct, ',', cswritep); |
| 4029 |
} |
| 4030 |
if (hapalt1_ct) { |
| 4031 |
cswritep = strcpya_k(cswritep, "1="); |
| 4032 |
cswritep = u32toa_x(hapalt1_ct, ',', cswritep); |
| 4033 |
} |
| 4034 |
if (missing_ct != nobs_base) { |
| 4035 |
--cswritep; |
| 4036 |
} else { |
| 4037 |
*cswritep++ = '.'; |
| 4038 |
} |
| 4039 |
} |
| 4040 |
} else { |
| 4041 |
reterr = PgrGetM(cur_sample_include, pssi, nobs_base, variant_uidx, simple_pgrp, &pgv); |
| 4042 |
if (unlikely(reterr)) { |
| 4043 |
PgenErrPrintNV(reterr, variant_uidx); |
| 4044 |
goto WriteGenoCounts_ret_1; |
| 4045 |
} |
| 4046 |
// Usually don't care about contents of genovec, patch_01_set, and |
| 4047 |
// patch_10_set, but chrX is an exception. |
| 4048 |
// Need to have an alternate strategy once sizeof(AlleleCode) > 1. |
| 4049 |
ZeroU32Arr(allele_ct * allele_ct, diploid_pair_cts); |
| 4050 |
diploid_pair_cts[0] = cur_raw_geno_cts[0]; |
| 4051 |
// lo_idx * allele_ct + hi_idx |
| 4052 |
diploid_pair_cts[1] = cur_raw_geno_cts[1] - pgv.patch_01_ct; |
| 4053 |
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) { |
| 4054 |
diploid_pair_cts[pgv.patch_01_vals[uii]] += 1; |
| 4055 |
} |
| 4056 |
const uintptr_t allele_ctp1 = allele_ct + 1; |
| 4057 |
diploid_pair_cts[allele_ctp1] = cur_raw_geno_cts[2] - pgv.patch_10_ct; |
| 4058 |
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) { |
| 4059 |
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii]; |
| 4060 |
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1]; |
| 4061 |
diploid_pair_cts[lo_code * allele_ct + hi_code] += 1; |
| 4062 |
} |
| 4063 |
if (is_autosomal_diploid) { |
| 4064 |
homref_ct = cur_raw_geno_cts[0]; |
| 4065 |
homalt1_ct = diploid_pair_cts[allele_ctp1]; |
| 4066 |
missing_ct = nobs_base - cur_raw_geno_cts[0] - cur_raw_geno_cts[1] - cur_raw_geno_cts[2]; |
| 4067 |
hap_cts[0] = 0; |
| 4068 |
hap_cts[1] = 0; |
| 4069 |
} else { |
| 4070 |
if (is_x) { |
| 4071 |
missing_ct = nobs_base - cur_raw_geno_cts[0] - cur_raw_geno_cts[1] - cur_raw_geno_cts[2]; |
| 4072 |
ZeroU32Arr(allele_ct, hap_cts); |
| 4073 |
if (x_male_geno_cts) { |
| 4074 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = x_male_geno_cts[variant_uidx - x_start]; |
| 4075 |
hap_cts[0] = cur_male_geno_cts[0]; |
| 4076 |
diploid_pair_cts[0] -= cur_male_geno_cts[0]; |
| 4077 |
// possible todo: try making two disjoint PgrGetM calls instead. |
| 4078 |
// don't expect that to be better, though. |
| 4079 |
uintptr_t sample_widx = 0; |
| 4080 |
uintptr_t cur_patch_bits = pgv.patch_01_set[0]; |
| 4081 |
uint32_t male_patch_01_ct = 0; |
| 4082 |
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) { |
| 4083 |
const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_patch_bits); |
| 4084 |
if (sex_male_collapsed[sample_widx] & lowbit) { |
| 4085 |
diploid_pair_cts[pgv.patch_01_vals[uii]] -= 1; |
| 4086 |
++male_patch_01_ct; |
| 4087 |
} |
| 4088 |
} |
| 4089 |
missing_ct += male_patch_01_ct; |
| 4090 |
diploid_pair_cts[1] -= cur_male_geno_cts[1] - male_patch_01_ct; |
| 4091 |
sample_widx = 0; |
| 4092 |
cur_patch_bits = pgv.patch_10_set[0]; |
| 4093 |
uint32_t* hap_cts_offset1 = &(hap_cts[1]); |
| 4094 |
uint32_t male_patch_10_ct = 0; |
| 4095 |
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) { |
| 4096 |
const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_patch_bits); |
| 4097 |
if (sex_male_collapsed[sample_widx] & lowbit) { |
| 4098 |
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii]; |
| 4099 |
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1]; |
| 4100 |
diploid_pair_cts[lo_code * allele_ct + hi_code] -= 1; |
| 4101 |
++male_patch_10_ct; |
| 4102 |
if (lo_code == hi_code) { |
| 4103 |
hap_cts_offset1[lo_code] += 1; |
| 4104 |
} |
| 4105 |
} |
| 4106 |
} |
| 4107 |
missing_ct += male_patch_10_ct; |
| 4108 |
hap_cts[1] = cur_male_geno_cts[2] - male_patch_10_ct; |
| 4109 |
diploid_pair_cts[allele_ctp1] -= hap_cts[1]; |
| 4110 |
for (uint32_t aidx = 2; aidx != allele_ct; ++aidx) { |
| 4111 |
// subtract male rarehoms |
| 4112 |
missing_ct -= hap_cts[aidx]; |
| 4113 |
} |
| 4114 |
} |
| 4115 |
homref_ct = diploid_pair_cts[0]; |
| 4116 |
homalt1_ct = diploid_pair_cts[allele_ctp1]; |
| 4117 |
} else { |
| 4118 |
// chrY or other pure-haploid; hethap treated as missing |
| 4119 |
uint32_t nonmissing_ct = 0; |
| 4120 |
for (uintptr_t aidx = 0; aidx != allele_ct; ++aidx) { |
| 4121 |
const uint32_t cur_ct = diploid_pair_cts[aidx * allele_ctp1]; |
| 4122 |
hap_cts[aidx] = cur_ct; |
| 4123 |
nonmissing_ct += cur_ct; |
| 4124 |
} |
| 4125 |
missing_ct = nobs_base - nonmissing_ct; |
| 4126 |
} |
| 4127 |
} |
| 4128 |
if (homref_col) { |
| 4129 |
*cswritep++ = '\t'; |
| 4130 |
cswritep = u32toa(homref_ct, cswritep); |
| 4131 |
} |
| 4132 |
if (refalt1_col) { |
| 4133 |
if (is_autosomal_diploid || is_x) { |
| 4134 |
*cswritep++ = '\t'; |
| 4135 |
cswritep = u32toa(diploid_pair_cts[1], cswritep); |
| 4136 |
} else { |
| 4137 |
cswritep = strcpya_k(cswritep, "\t0"); |
| 4138 |
} |
| 4139 |
} |
| 4140 |
if (refalt_col) { |
| 4141 |
*cswritep++ = '\t'; |
| 4142 |
if (is_autosomal_diploid || is_x) { |
| 4143 |
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) { |
| 4144 |
cswritep = u32toa_x(diploid_pair_cts[aidx], ',', cswritep); |
| 4145 |
} |
| 4146 |
--cswritep; |
| 4147 |
} else { |
| 4148 |
// repeat "0," |
| 4149 |
cswritep = u16setsa(cswritep, 0x2c30, allele_ct - 2); |
| 4150 |
*cswritep++ = '0'; |
| 4151 |
} |
| 4152 |
} |
| 4153 |
if (homalt1_col) { |
| 4154 |
*cswritep++ = '\t'; |
| 4155 |
cswritep = u32toa(homalt1_ct, cswritep); |
| 4156 |
} |
| 4157 |
if (xy_col) { |
| 4158 |
*cswritep++ = '\t'; |
| 4159 |
if (is_autosomal_diploid || is_x) { |
| 4160 |
for (uint32_t aidx_hi = xy_col_altonly; aidx_hi != allele_ct; ++aidx_hi) { |
| 4161 |
for (uint32_t aidx_lo = xy_col_altonly; aidx_lo <= aidx_hi; ++aidx_lo) { |
| 4162 |
cswritep = u32toa_x(diploid_pair_cts[aidx_lo * allele_ct + aidx_hi], ',', cswritep); |
| 4163 |
} |
| 4164 |
} |
| 4165 |
--cswritep; |
| 4166 |
} else { |
| 4167 |
const uint32_t triangle_base = allele_ct - xy_col_altonly; |
| 4168 |
cswritep = u16setsa(cswritep, 0x2c30, (triangle_base * (triangle_base + 1) / 2) - 1); |
| 4169 |
*cswritep++ = '0'; |
| 4170 |
} |
| 4171 |
} |
| 4172 |
if (hapref_col) { |
| 4173 |
*cswritep++ = '\t'; |
| 4174 |
cswritep = u32toa(hap_cts[0], cswritep); |
| 4175 |
} |
| 4176 |
if (hapalt1_col) { |
| 4177 |
*cswritep++ = '\t'; |
| 4178 |
cswritep = u32toa(hap_cts[1], cswritep); |
| 4179 |
} |
| 4180 |
if (hap_col) { |
| 4181 |
*cswritep++ = '\t'; |
| 4182 |
if (!is_autosomal_diploid) { |
| 4183 |
for (uint32_t aidx = hap_col_altonly; aidx != allele_ct; ++aidx) { |
| 4184 |
cswritep = u32toa_x(hap_cts[aidx], ',', cswritep); |
| 4185 |
} |
| 4186 |
--cswritep; |
| 4187 |
} else { |
| 4188 |
cswritep = u16setsa(cswritep, 0x2c30, allele_ct - hap_col_altonly - 1); |
| 4189 |
*cswritep++ = '0'; |
| 4190 |
} |
| 4191 |
} |
| 4192 |
if (numeq_col) { |
| 4193 |
*cswritep++ = '\t'; |
| 4194 |
if (is_autosomal_diploid || is_x) { |
| 4195 |
for (uint32_t aidx_hi = 0; aidx_hi != allele_ct; ++aidx_hi) { |
| 4196 |
for (uint32_t aidx_lo = 0; aidx_lo <= aidx_hi; ++aidx_lo) { |
| 4197 |
const uint32_t cur_ct = diploid_pair_cts[aidx_lo * allele_ct + aidx_hi]; |
| 4198 |
if (cur_ct) { |
| 4199 |
cswritep = u32toa_x(aidx_lo, '/', cswritep); |
| 4200 |
cswritep = u32toa_x(aidx_hi, '=', cswritep); |
| 4201 |
cswritep = u32toa_x(cur_ct, ',', cswritep); |
| 4202 |
} |
| 4203 |
} |
| 4204 |
} |
| 4205 |
} |
| 4206 |
if (!is_autosomal_diploid) { |
| 4207 |
for (uint32_t aidx = 0; aidx != allele_ct; ++aidx) { |
| 4208 |
const uint32_t cur_ct = hap_cts[aidx]; |
| 4209 |
if (cur_ct) { |
| 4210 |
cswritep = u32toa_x(aidx, '=', cswritep); |
| 4211 |
cswritep = u32toa_x(cur_ct, ',', cswritep); |
| 4212 |
} |
| 4213 |
} |
| 4214 |
} |
| 4215 |
if (missing_ct != nobs_base) { |
| 4216 |
--cswritep; |
| 4217 |
} else { |
| 4218 |
*cswritep++ = '.'; |
| 4219 |
} |
| 4220 |
} |
| 4221 |
} |
| 4222 |
if (missing_col) { |
| 4223 |
*cswritep++ = '\t'; |
| 4224 |
cswritep = u32toa(missing_ct, cswritep); |
| 4225 |
} |
| 4226 |
if (nobs_col) { |
| 4227 |
*cswritep++ = '\t'; |
| 4228 |
cswritep = u32toa(nobs_base - missing_ct, cswritep); |
| 4229 |
} |
| 4230 |
AppendBinaryEoln(&cswritep); |
| 4231 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4232 |
goto WriteGenoCounts_ret_WRITE_FAIL; |
| 4233 |
} |
| 4234 |
if (variant_idx >= next_print_variant_idx) { |
| 4235 |
if (pct > 10) { |
| 4236 |
putc_unlocked('\b', stdout); |
| 4237 |
} |
| 4238 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 4239 |
printf("\b\b%u%%", pct++); |
| 4240 |
fflush(stdout); |
| 4241 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 4242 |
} |
| 4243 |
} |
| 4244 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 4245 |
goto WriteGenoCounts_ret_WRITE_FAIL; |
| 4246 |
} |
| 4247 |
putc_unlocked('\r', stdout); |
| 4248 |
logprintfww("--geno-counts%s: Genotype counts written to %s .\n", output_zst? " zs" : "", outname); |
| 4249 |
} |
| 4250 |
while (0) { |
| 4251 |
WriteGenoCounts_ret_NOMEM: |
| 4252 |
reterr = kPglRetNomem; |
| 4253 |
break; |
| 4254 |
WriteGenoCounts_ret_WRITE_FAIL: |
| 4255 |
reterr = kPglRetWriteFail; |
| 4256 |
break; |
| 4257 |
} |
| 4258 |
WriteGenoCounts_ret_1: |
| 4259 |
CswriteCloseCond(&css, cswritep); |
| 4260 |
BigstackReset(bigstack_mark); |
| 4261 |
return reterr; |
| 4262 |
} |
| 4263 |
|
| 4264 |
PglErr WriteMissingnessReports(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uint32_t* sample_missing_hc_cts, const uint32_t* sample_missing_dosage_cts, const uint32_t* sample_hethap_cts, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const uint32_t* variant_missing_hc_cts, const uint32_t* variant_missing_dosage_cts, const uint32_t* variant_hethap_cts, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t variant_ct, uintptr_t max_allele_slen, uint32_t y_nosex_missing_stats, PgenGlobalFlags gflags, uint32_t first_hap_uidx, MissingRptFlags missing_rpt_flags, uint32_t max_thread_ct, char* outname, char* outname_end) { |
| 4265 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 4266 |
char* cswritep = nullptr; |
| 4267 |
CompressStreamState css; |
| 4268 |
PglErr reterr = kPglRetSuccess; |
| 4269 |
PreinitCstream(&css); |
| 4270 |
{ |
| 4271 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 4272 |
const uintptr_t* chry_missingstat_include = sex_male; |
| 4273 |
if (y_nosex_missing_stats) { |
| 4274 |
uintptr_t* nonfemale_tmp; |
| 4275 |
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &nonfemale_tmp))) { |
| 4276 |
goto WriteMissingnessReports_ret_NOMEM; |
| 4277 |
} |
| 4278 |
AlignedBitarrOrnotCopy(sex_male, sex_nm, raw_sample_ct, nonfemale_tmp); |
| 4279 |
chry_missingstat_include = nonfemale_tmp; |
| 4280 |
} |
| 4281 |
|
| 4282 |
const uint32_t chry_missingstat_sample_ct = PopcountWords(chry_missingstat_include, raw_sample_ctl); |
| 4283 |
const uint32_t output_zst = missing_rpt_flags & kfMissingRptZs; |
| 4284 |
if (!(missing_rpt_flags & kfMissingRptVariantOnly)) { |
| 4285 |
const uintptr_t overflow_buf_size = kCompressStreamBlock + kMaxMediumLine + pheno_ct * 2; |
| 4286 |
OutnameZstSet(".smiss", output_zst, outname_end); |
| 4287 |
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep); |
| 4288 |
if (unlikely(reterr)) { |
| 4289 |
goto WriteMissingnessReports_ret_1; |
| 4290 |
} |
| 4291 |
*cswritep++ = '#'; |
| 4292 |
const uint32_t scol_fid = FidColIsRequired(siip, missing_rpt_flags / kfMissingRptScolMaybefid); |
| 4293 |
if (scol_fid) { |
| 4294 |
cswritep = strcpya_k(cswritep, "FID\t"); |
| 4295 |
} |
| 4296 |
cswritep = strcpya_k(cswritep, "IID"); |
| 4297 |
const char* sample_ids = siip->sample_ids; |
| 4298 |
const char* sids = siip->sids; |
| 4299 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 4300 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 4301 |
const uint32_t scol_sid = SidColIsRequired(sids, missing_rpt_flags / kfMissingRptScolMaybesid); |
| 4302 |
if (scol_sid) { |
| 4303 |
cswritep = strcpya_k(cswritep, "\tSID"); |
| 4304 |
} |
| 4305 |
const uint32_t scol_empty_pheno = (missing_rpt_flags & kfMissingRptScolMisspheno1) && (!pheno_ct); |
| 4306 |
if (scol_empty_pheno) { |
| 4307 |
cswritep = strcpya_k(cswritep, "\tMISS_PHENO1"); |
| 4308 |
} |
| 4309 |
const uint32_t scol_phenos = (missing_rpt_flags & (kfMissingRptScolMisspheno1 | kfMissingRptScolMissphenos)) && pheno_ct; |
| 4310 |
if (scol_phenos) { |
| 4311 |
if (!(missing_rpt_flags & kfMissingRptScolMissphenos)) { |
| 4312 |
pheno_ct = 1; |
| 4313 |
} |
| 4314 |
for (uintptr_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 4315 |
*cswritep++ = '\t'; |
| 4316 |
cswritep = strcpya(cswritep, &(pheno_names[pheno_idx * max_pheno_name_blen])); |
| 4317 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4318 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4319 |
} |
| 4320 |
} |
| 4321 |
} |
| 4322 |
const uint32_t scol_nmiss_dosage = (missing_rpt_flags / kfMissingRptScolNmissDosage) & 1; |
| 4323 |
if (scol_nmiss_dosage) { |
| 4324 |
cswritep = strcpya_k(cswritep, "\tMISSING_DOSAGE_CT"); |
| 4325 |
} |
| 4326 |
const uint32_t scol_nmiss = (missing_rpt_flags / kfMissingRptScolNmiss) & 1; |
| 4327 |
if (scol_nmiss) { |
| 4328 |
cswritep = strcpya_k(cswritep, "\tMISSING_CT"); |
| 4329 |
} |
| 4330 |
const uint32_t scol_nmiss_hh = (missing_rpt_flags / kfMissingRptScolNmissHh) & 1; |
| 4331 |
if (scol_nmiss_hh) { |
| 4332 |
cswritep = strcpya_k(cswritep, "\tMISSING_AND_HETHAP_CT"); |
| 4333 |
} |
| 4334 |
const uint32_t scol_hethap = (missing_rpt_flags / kfMissingRptScolHethap) & 1; |
| 4335 |
if (scol_hethap) { |
| 4336 |
cswritep = strcpya_k(cswritep, "\tHETHAP_CT"); |
| 4337 |
} |
| 4338 |
const uint32_t scol_nobs = (missing_rpt_flags / kfMissingRptScolNobs) & 1; |
| 4339 |
if (scol_nobs) { |
| 4340 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 4341 |
} |
| 4342 |
const uint32_t scol_fmiss_dosage = (missing_rpt_flags / kfMissingRptScolFmissDosage) & 1; |
| 4343 |
if (scol_fmiss_dosage) { |
| 4344 |
cswritep = strcpya_k(cswritep, "\tF_MISS_DOSAGE"); |
| 4345 |
} |
| 4346 |
const uint32_t scol_fmiss = (missing_rpt_flags / kfMissingRptScolFmiss) & 1; |
| 4347 |
if (scol_fmiss) { |
| 4348 |
cswritep = strcpya_k(cswritep, "\tF_MISS"); |
| 4349 |
} |
| 4350 |
const uint32_t scol_fmiss_hh = (missing_rpt_flags / kfMissingRptScolFmissHh) & 1; |
| 4351 |
if (scol_fmiss_hh) { |
| 4352 |
cswritep = strcpya_k(cswritep, "\tF_MISS_AND_HETHAP"); |
| 4353 |
} |
| 4354 |
AppendBinaryEoln(&cswritep); |
| 4355 |
uint32_t variant_ct_y = 0; |
| 4356 |
uint32_t y_code; |
| 4357 |
if (XymtExists(cip, kChrOffsetY, &y_code)) { |
| 4358 |
variant_ct_y = CountChrVariantsUnsafe(variant_include, cip, y_code); |
| 4359 |
} |
| 4360 |
const uint32_t variant_ct_nony = variant_ct - variant_ct_y; |
| 4361 |
char nobs_strs[2][16]; |
| 4362 |
uint32_t nobs_slens[2]; |
| 4363 |
double variant_ct_recips[2]; |
| 4364 |
{ |
| 4365 |
char* write_iter = nobs_strs[0]; |
| 4366 |
*write_iter++ = '\t'; |
| 4367 |
write_iter = u32toa(variant_ct_nony, write_iter); |
| 4368 |
nobs_slens[0] = write_iter - nobs_strs[0]; |
| 4369 |
variant_ct_recips[0] = 1.0 / u31tod(variant_ct_nony); |
| 4370 |
write_iter = nobs_strs[1]; |
| 4371 |
*write_iter++ = '\t'; |
| 4372 |
write_iter = u32toa(variant_ct, write_iter); |
| 4373 |
nobs_slens[1] = write_iter - nobs_strs[1]; |
| 4374 |
} |
| 4375 |
variant_ct_recips[1] = 1.0 / u31tod(variant_ct); |
| 4376 |
uintptr_t sample_uidx_base = 0; |
| 4377 |
uintptr_t cur_bits = sample_include[0]; |
| 4378 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 4379 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 4380 |
cswritep = AppendXid(sample_ids, sids, scol_fid, scol_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep); |
| 4381 |
if (scol_phenos) { |
| 4382 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 4383 |
*cswritep++ = '\t'; |
| 4384 |
// 'Y' - 'N' == 11 |
| 4385 |
*cswritep++ = 'Y' - 11 * IsSet(pheno_cols[pheno_idx].nonmiss, sample_uidx); |
| 4386 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4387 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4388 |
} |
| 4389 |
} |
| 4390 |
} else { |
| 4391 |
if (scol_empty_pheno) { |
| 4392 |
cswritep = strcpya_k(cswritep, "\tY"); |
| 4393 |
} |
| 4394 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4395 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4396 |
} |
| 4397 |
} |
| 4398 |
if (scol_nmiss_dosage) { |
| 4399 |
*cswritep++ = '\t'; |
| 4400 |
cswritep = u32toa(sample_missing_dosage_cts[sample_uidx], cswritep); |
| 4401 |
} |
| 4402 |
const uint32_t cur_missing_hc_base = sample_missing_hc_cts[sample_uidx]; |
| 4403 |
if (scol_nmiss) { |
| 4404 |
*cswritep++ = '\t'; |
| 4405 |
cswritep = u32toa(cur_missing_hc_base, cswritep); |
| 4406 |
} |
| 4407 |
if (scol_nmiss_hh) { |
| 4408 |
*cswritep++ = '\t'; |
| 4409 |
cswritep = u32toa(cur_missing_hc_base + sample_hethap_cts[sample_uidx], cswritep); |
| 4410 |
} |
| 4411 |
if (scol_hethap) { |
| 4412 |
*cswritep++ = '\t'; |
| 4413 |
cswritep = u32toa(sample_hethap_cts[sample_uidx], cswritep); |
| 4414 |
} |
| 4415 |
const uint32_t chry_included = IsSet(chry_missingstat_include, sample_uidx); |
| 4416 |
if (scol_nobs) { |
| 4417 |
cswritep = memcpya(cswritep, nobs_strs[chry_included], nobs_slens[chry_included]); |
| 4418 |
} |
| 4419 |
const double cur_variant_ct_recip = variant_ct_recips[chry_included]; |
| 4420 |
if (scol_fmiss_dosage) { |
| 4421 |
*cswritep++ = '\t'; |
| 4422 |
cswritep = dtoa_g(u31tod(sample_missing_dosage_cts[sample_uidx]) * cur_variant_ct_recip, cswritep); |
| 4423 |
} |
| 4424 |
if (scol_fmiss) { |
| 4425 |
*cswritep++ = '\t'; |
| 4426 |
cswritep = dtoa_g(u31tod(cur_missing_hc_base) * cur_variant_ct_recip, cswritep); |
| 4427 |
} |
| 4428 |
if (scol_fmiss_hh) { |
| 4429 |
*cswritep++ = '\t'; |
| 4430 |
cswritep = dtoa_g(u31tod(cur_missing_hc_base + sample_hethap_cts[sample_uidx]) * cur_variant_ct_recip, cswritep); |
| 4431 |
} |
| 4432 |
AppendBinaryEoln(&cswritep); |
| 4433 |
} |
| 4434 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 4435 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4436 |
} |
| 4437 |
BigstackReset(bigstack_mark); |
| 4438 |
logprintfww("--missing: Sample missing data report written to %s .\n", outname); |
| 4439 |
} |
| 4440 |
if (!(missing_rpt_flags & kfMissingRptSampleOnly)) { |
| 4441 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 4442 |
char* chr_buf; // includes trailing tab |
| 4443 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 4444 |
goto WriteMissingnessReports_ret_NOMEM; |
| 4445 |
} |
| 4446 |
const uintptr_t overflow_buf_size = kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + 2 * max_allele_slen; |
| 4447 |
OutnameZstSet(".vmiss", output_zst, outname_end); |
| 4448 |
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, overflow_buf_size, &css, &cswritep); |
| 4449 |
if (unlikely(reterr)) { |
| 4450 |
goto WriteMissingnessReports_ret_1; |
| 4451 |
} |
| 4452 |
*cswritep++ = '#'; |
| 4453 |
const uint32_t chr_col = missing_rpt_flags & kfMissingRptVcolChrom; |
| 4454 |
|
| 4455 |
if (chr_col) { |
| 4456 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 4457 |
} |
| 4458 |
if (missing_rpt_flags & kfMissingRptVcolPos) { |
| 4459 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 4460 |
} else { |
| 4461 |
variant_bps = nullptr; |
| 4462 |
} |
| 4463 |
cswritep = strcpya_k(cswritep, "ID"); |
| 4464 |
const uint32_t ref_col = missing_rpt_flags & kfMissingRptVcolRef; |
| 4465 |
if (ref_col) { |
| 4466 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 4467 |
} |
| 4468 |
const uint32_t alt_col = missing_rpt_flags & kfMissingRptVcolAlt; |
| 4469 |
if (alt_col) { |
| 4470 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 4471 |
} |
| 4472 |
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 4473 |
const uint32_t provref_col = ref_col && ProvrefCol(variant_include, nonref_flags, missing_rpt_flags / kfMissingRptVcolMaybeprovref, raw_variant_ct, all_nonref); |
| 4474 |
if (provref_col) { |
| 4475 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 4476 |
} |
| 4477 |
const uint32_t nmiss_dosage_col = missing_rpt_flags & kfMissingRptVcolNmissDosage; |
| 4478 |
if (nmiss_dosage_col) { |
| 4479 |
cswritep = strcpya_k(cswritep, "\tMISSING_DOSAGE_CT"); |
| 4480 |
} |
| 4481 |
const uint32_t nmiss_col = (missing_rpt_flags / kfMissingRptVcolNmiss) & 1; |
| 4482 |
if (nmiss_col) { |
| 4483 |
cswritep = strcpya_k(cswritep, "\tMISSING_CT"); |
| 4484 |
} |
| 4485 |
const uint32_t nmiss_hh_col = (missing_rpt_flags / kfMissingRptVcolNmissHh) & 1; |
| 4486 |
if (nmiss_hh_col) { |
| 4487 |
cswritep = strcpya_k(cswritep, "\tMISSING_AND_HETHAP_CT"); |
| 4488 |
} |
| 4489 |
const uint32_t hethap_col = (missing_rpt_flags / kfMissingRptVcolHethap) & 1; |
| 4490 |
if (hethap_col) { |
| 4491 |
cswritep = strcpya_k(cswritep, "\tHETHAP_CT"); |
| 4492 |
} |
| 4493 |
const uint32_t nobs_col = (missing_rpt_flags / kfMissingRptVcolNobs) & 1; |
| 4494 |
if (nobs_col) { |
| 4495 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 4496 |
} |
| 4497 |
const uint32_t fmiss_dosage_col = missing_rpt_flags & kfMissingRptVcolFmissDosage; |
| 4498 |
if (fmiss_dosage_col) { |
| 4499 |
cswritep = strcpya_k(cswritep, "\tF_MISS_DOSAGE"); |
| 4500 |
} |
| 4501 |
const uint32_t fmiss_col = (missing_rpt_flags / kfMissingRptVcolFmiss) & 1; |
| 4502 |
if (fmiss_col) { |
| 4503 |
cswritep = strcpya_k(cswritep, "\tF_MISS"); |
| 4504 |
} |
| 4505 |
const uint32_t fmiss_hh_col = (missing_rpt_flags / kfMissingRptVcolFmissHh) & 1; |
| 4506 |
if (fmiss_hh_col) { |
| 4507 |
cswritep = strcpya_k(cswritep, "\tF_MISS_AND_HETHAP"); |
| 4508 |
} |
| 4509 |
const uint32_t fhethap_col = (missing_rpt_flags / kfMissingRptVcolFhethap) & 1; |
| 4510 |
if (fhethap_col) { |
| 4511 |
cswritep = strcpya_k(cswritep, "\tF_HETHAP"); |
| 4512 |
} |
| 4513 |
AppendBinaryEoln(&cswritep); |
| 4514 |
char nobs_str[16]; |
| 4515 |
nobs_str[0] = '\t'; |
| 4516 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 4517 |
uintptr_t variant_uidx_base = 0; |
| 4518 |
uintptr_t cur_bits = variant_include[0]; |
| 4519 |
uint32_t nobs_slen = 0; |
| 4520 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 4521 |
uint32_t chr_end = 0; |
| 4522 |
uint32_t chr_buf_blen = 0; |
| 4523 |
uint32_t pct = 0; |
| 4524 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 4525 |
uint32_t is_y = 2; |
| 4526 |
double nobs_recip = 0.0; |
| 4527 |
fputs("--missing variant report: 0%", stdout); |
| 4528 |
fflush(stdout); |
| 4529 |
uint32_t cur_allele_ct = 2; |
| 4530 |
uint32_t cur_missing_hc_ct = 0; |
| 4531 |
uint32_t cur_hethap_ct = 0; |
| 4532 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 4533 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4534 |
if (variant_uidx >= chr_end) { |
| 4535 |
do { |
| 4536 |
++chr_fo_idx; |
| 4537 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 4538 |
} while (variant_uidx >= chr_end); |
| 4539 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 4540 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 4541 |
*chr_name_end = '\t'; |
| 4542 |
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf); |
| 4543 |
const uint32_t new_is_y = (chr_idx == y_code); |
| 4544 |
if (new_is_y != is_y) { |
| 4545 |
is_y = new_is_y; |
| 4546 |
const uint32_t cur_nobs = is_y? chry_missingstat_sample_ct : sample_ct; |
| 4547 |
nobs_recip = 1.0 / u31tod(cur_nobs); |
| 4548 |
char* nobs_str_end = u32toa(cur_nobs, &(nobs_str[1])); |
| 4549 |
nobs_slen = nobs_str_end - nobs_str; |
| 4550 |
} |
| 4551 |
} |
| 4552 |
if (chr_col) { |
| 4553 |
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen); |
| 4554 |
} |
| 4555 |
if (variant_bps) { |
| 4556 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 4557 |
} |
| 4558 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 4559 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 4560 |
if (allele_idx_offsets) { |
| 4561 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 4562 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 4563 |
} |
| 4564 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 4565 |
if (ref_col) { |
| 4566 |
*cswritep++ = '\t'; |
| 4567 |
cswritep = strcpya(cswritep, cur_alleles[0]); |
| 4568 |
} |
| 4569 |
if (alt_col) { |
| 4570 |
*cswritep++ = '\t'; |
| 4571 |
for (uint32_t allele_idx = 1; allele_idx != cur_allele_ct; ++allele_idx) { |
| 4572 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4573 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4574 |
} |
| 4575 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 4576 |
} |
| 4577 |
--cswritep; |
| 4578 |
} |
| 4579 |
if (provref_col) { |
| 4580 |
*cswritep++ = '\t'; |
| 4581 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N'; |
| 4582 |
} |
| 4583 |
if (nmiss_dosage_col) { |
| 4584 |
*cswritep++ = '\t'; |
| 4585 |
cswritep = u32toa(variant_missing_dosage_cts[variant_uidx], cswritep); |
| 4586 |
} |
| 4587 |
if (variant_missing_hc_cts) { |
| 4588 |
cur_missing_hc_ct = variant_missing_hc_cts[variant_uidx]; |
| 4589 |
cur_hethap_ct = 0; |
| 4590 |
if (variant_uidx >= first_hap_uidx) { |
| 4591 |
cur_hethap_ct = variant_hethap_cts[variant_uidx - first_hap_uidx]; |
| 4592 |
} |
| 4593 |
if (nmiss_col) { |
| 4594 |
*cswritep++ = '\t'; |
| 4595 |
cswritep = u32toa(cur_missing_hc_ct, cswritep); |
| 4596 |
} |
| 4597 |
if (nmiss_hh_col) { |
| 4598 |
*cswritep++ = '\t'; |
| 4599 |
cswritep = u32toa(cur_missing_hc_ct + cur_hethap_ct, cswritep); |
| 4600 |
} |
| 4601 |
if (hethap_col) { |
| 4602 |
*cswritep++ = '\t'; |
| 4603 |
cswritep = u32toa(cur_hethap_ct, cswritep); |
| 4604 |
} |
| 4605 |
} |
| 4606 |
if (nobs_col) { |
| 4607 |
cswritep = memcpya(cswritep, nobs_str, nobs_slen); |
| 4608 |
} |
| 4609 |
if (fmiss_dosage_col) { |
| 4610 |
*cswritep++ = '\t'; |
| 4611 |
cswritep = dtoa_g(u31tod(variant_missing_dosage_cts[variant_uidx]) * nobs_recip, cswritep); |
| 4612 |
} |
| 4613 |
if (fmiss_col) { |
| 4614 |
*cswritep++ = '\t'; |
| 4615 |
cswritep = dtoa_g(u31tod(cur_missing_hc_ct) * nobs_recip, cswritep); |
| 4616 |
} |
| 4617 |
if (fmiss_hh_col) { |
| 4618 |
*cswritep++ = '\t'; |
| 4619 |
cswritep = dtoa_g(u31tod(cur_missing_hc_ct + cur_hethap_ct) * nobs_recip, cswritep); |
| 4620 |
} |
| 4621 |
if (fhethap_col) { |
| 4622 |
*cswritep++ = '\t'; |
| 4623 |
cswritep = dtoa_g(u31tod(cur_hethap_ct) * nobs_recip, cswritep); |
| 4624 |
} |
| 4625 |
AppendBinaryEoln(&cswritep); |
| 4626 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 4627 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4628 |
} |
| 4629 |
if (variant_idx >= next_print_variant_idx) { |
| 4630 |
if (pct > 10) { |
| 4631 |
putc_unlocked('\b', stdout); |
| 4632 |
} |
| 4633 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 4634 |
printf("\b\b%u%%", pct++); |
| 4635 |
fflush(stdout); |
| 4636 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 4637 |
} |
| 4638 |
} |
| 4639 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 4640 |
goto WriteMissingnessReports_ret_WRITE_FAIL; |
| 4641 |
} |
| 4642 |
putc_unlocked('\r', stdout); |
| 4643 |
logprintfww("--missing: Variant missing data report written to %s .\n", outname); |
| 4644 |
} |
| 4645 |
} |
| 4646 |
while (0) { |
| 4647 |
WriteMissingnessReports_ret_NOMEM: |
| 4648 |
reterr = kPglRetNomem; |
| 4649 |
break; |
| 4650 |
WriteMissingnessReports_ret_WRITE_FAIL: |
| 4651 |
reterr = kPglRetWriteFail; |
| 4652 |
break; |
| 4653 |
} |
| 4654 |
WriteMissingnessReports_ret_1: |
| 4655 |
BigstackReset(bigstack_mark); |
| 4656 |
CswriteCloseCond(&css, cswritep); |
| 4657 |
return reterr; |
| 4658 |
} |
| 4659 |
|
| 4660 |
PglErr GetMultiallelicMarginalCounts(const uintptr_t* founder_info, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_geno_cts), uint32_t raw_sample_ct, uint32_t autosomal_variant_ct, uint32_t autosomal_xallele_ct, uint32_t hwe_x_ct, uint32_t x_xallele_ct, PgenReader* simple_pgrp, STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts), STD_ARRAY_PTR_DECL(uint32_t, 2, autosomal_xgeno_cts), STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts)) { |
| 4661 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 4662 |
PglErr reterr = kPglRetSuccess; |
| 4663 |
{ |
| 4664 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 4665 |
uint32_t* cumulative_popcounts; |
| 4666 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &cumulative_popcounts))) { |
| 4667 |
goto GetMultiallelicMarginalCounts_ret_NOMEM; |
| 4668 |
} |
| 4669 |
FillCumulativePopcounts(founder_info, raw_sample_ctl, cumulative_popcounts); |
| 4670 |
const uint32_t founder_ct = cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(founder_info[raw_sample_ctl - 1]); |
| 4671 |
const uint32_t founder_ctl2 = NypCtToWordCt(founder_ct); |
| 4672 |
const uint32_t founder_ctl = BitCtToWordCt(founder_ct); |
| 4673 |
const uint32_t max_allele_ct = PgrGetMaxAlleleCt(simple_pgrp); |
| 4674 |
PgenVariant pgv; |
| 4675 |
uint32_t* one_cts; |
| 4676 |
uint32_t* two_cts; |
| 4677 |
if (unlikely(bigstack_alloc_w(founder_ctl2, &(pgv.genovec)) || |
| 4678 |
bigstack_alloc_w(founder_ctl, &(pgv.patch_01_set)) || |
| 4679 |
bigstack_alloc_ac(founder_ct, &(pgv.patch_01_vals)) || |
| 4680 |
bigstack_alloc_w(founder_ctl, &(pgv.patch_10_set)) || |
| 4681 |
bigstack_alloc_ac(2 * founder_ct, &(pgv.patch_10_vals)) || |
| 4682 |
bigstack_alloc_u32(max_allele_ct, &one_cts) || |
| 4683 |
bigstack_alloc_u32(max_allele_ct, &two_cts))) { |
| 4684 |
goto GetMultiallelicMarginalCounts_ret_NOMEM; |
| 4685 |
} |
| 4686 |
if (autosomal_xallele_ct) { |
| 4687 |
PgrSampleSubsetIndex pssi; |
| 4688 |
PgrSetSampleSubsetIndex(cumulative_popcounts, simple_pgrp, &pssi); |
| 4689 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 4690 |
uint32_t chr_end = 0; |
| 4691 |
uintptr_t variant_uidx_base = 0; |
| 4692 |
uintptr_t cur_bits = variant_include[0]; |
| 4693 |
uintptr_t xgeno_idx = 0; |
| 4694 |
for (uint32_t variant_idx = 0; variant_idx != autosomal_variant_ct; ++variant_idx) { |
| 4695 |
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4696 |
if (variant_uidx >= chr_end) { |
| 4697 |
uint32_t chr_idx; |
| 4698 |
do { |
| 4699 |
++chr_fo_idx; |
| 4700 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 4701 |
chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 4702 |
} while ((variant_uidx >= chr_end) || IsSet(cip->haploid_mask, chr_idx)); |
| 4703 |
BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &cur_bits); |
| 4704 |
variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4705 |
} |
| 4706 |
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 4707 |
if (allele_ct > 2) { |
| 4708 |
reterr = PgrGetM(founder_info, pssi, founder_ct, variant_uidx, simple_pgrp, &pgv); |
| 4709 |
if (unlikely(reterr)) { |
| 4710 |
PgenErrPrintNV(reterr, variant_uidx); |
| 4711 |
goto GetMultiallelicMarginalCounts_ret_1; |
| 4712 |
} |
| 4713 |
ZeroTrailingNyps(founder_ct, pgv.genovec); |
| 4714 |
ZeroU32Arr(allele_ct, one_cts); |
| 4715 |
ZeroU32Arr(allele_ct, two_cts); |
| 4716 |
// const uint32_t hom_ref_ct = hwe_geno_cts[variant_uidx][0]; |
| 4717 |
const uint32_t het_ref_ct = hwe_geno_cts[variant_uidx][1]; |
| 4718 |
const uint32_t altxy_ct = hwe_geno_cts[variant_uidx][2]; |
| 4719 |
// two_cts[0] = hom_ref_ct; |
| 4720 |
// one_cts[0] = het_ref_ct; |
| 4721 |
one_cts[1] = het_ref_ct - pgv.patch_01_ct; |
| 4722 |
two_cts[1] = altxy_ct - pgv.patch_10_ct; |
| 4723 |
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) { |
| 4724 |
one_cts[pgv.patch_01_vals[uii]] += 1; |
| 4725 |
} |
| 4726 |
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) { |
| 4727 |
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii]; |
| 4728 |
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1]; |
| 4729 |
if (lo_code == hi_code) { |
| 4730 |
two_cts[lo_code] += 1; |
| 4731 |
} else { |
| 4732 |
one_cts[lo_code] += 1; |
| 4733 |
one_cts[hi_code] += 1; |
| 4734 |
} |
| 4735 |
} |
| 4736 |
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) { |
| 4737 |
// This is currently inverted, to match how hwe_geno_cts represents |
| 4738 |
// REF allele counts. |
| 4739 |
autosomal_xgeno_cts[xgeno_idx][0] = two_cts[aidx]; |
| 4740 |
autosomal_xgeno_cts[xgeno_idx][1] = one_cts[aidx]; |
| 4741 |
++xgeno_idx; |
| 4742 |
} |
| 4743 |
} |
| 4744 |
} |
| 4745 |
} |
| 4746 |
if (x_xallele_ct) { |
| 4747 |
// Related to multiallelic-chrX --geno-counts implementation. |
| 4748 |
uintptr_t* founder_knownsex; |
| 4749 |
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &founder_knownsex))) { |
| 4750 |
goto GetMultiallelicMarginalCounts_ret_NOMEM; |
| 4751 |
} |
| 4752 |
BitvecAndCopy(founder_info, sex_nm, raw_sample_ctl, founder_knownsex); |
| 4753 |
FillCumulativePopcounts(founder_knownsex, raw_sample_ctl, cumulative_popcounts); |
| 4754 |
const uint32_t founder_x_ct = cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(founder_knownsex[raw_sample_ctl - 1]); |
| 4755 |
const uint32_t founder_x_ctaw = BitCtToAlignedWordCt(founder_x_ct); |
| 4756 |
PgrSampleSubsetIndex pssi; |
| 4757 |
PgrSetSampleSubsetIndex(cumulative_popcounts, simple_pgrp, &pssi); |
| 4758 |
uintptr_t* founder_male_collapsed; |
| 4759 |
uintptr_t* founder_male_interleaved_vec; |
| 4760 |
if (unlikely(bigstack_alloc_w(founder_x_ctaw, &founder_male_collapsed) || |
| 4761 |
bigstack_alloc_w(founder_x_ctaw, &founder_male_interleaved_vec))) { |
| 4762 |
goto GetMultiallelicMarginalCounts_ret_NOMEM; |
| 4763 |
} |
| 4764 |
CopyBitarrSubset(sex_male, founder_knownsex, founder_x_ct, founder_male_collapsed); |
| 4765 |
const uint32_t founder_x_ctl = BitCtToWordCt(founder_x_ct); |
| 4766 |
const uint32_t founder_male_ct = PopcountWords(founder_male_collapsed, founder_ctl); |
| 4767 |
ZeroWArr(founder_x_ctaw - founder_x_ctl, &(founder_male_collapsed[founder_x_ctl])); |
| 4768 |
FillInterleavedMaskVec(founder_male_collapsed, founder_x_ctaw / kWordsPerVec, founder_male_interleaved_vec); |
| 4769 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 4770 |
const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 4771 |
const uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx]; |
| 4772 |
uintptr_t variant_uidx_base; |
| 4773 |
uintptr_t cur_bits; |
| 4774 |
BitIter1Start(variant_include, x_start, &variant_uidx_base, &cur_bits); |
| 4775 |
uintptr_t xgeno_idx = 0; |
| 4776 |
for (uint32_t variant_idx = 0; variant_idx != hwe_x_ct; ++variant_idx) { |
| 4777 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4778 |
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 4779 |
if (allele_ct > 2) { |
| 4780 |
reterr = PgrGetM(founder_knownsex, pssi, founder_x_ct, variant_uidx, simple_pgrp, &pgv); |
| 4781 |
if (unlikely(reterr)) { |
| 4782 |
PgenErrPrintNV(reterr, variant_uidx); |
| 4783 |
goto GetMultiallelicMarginalCounts_ret_1; |
| 4784 |
} |
| 4785 |
ZeroTrailingNyps(founder_x_ct, pgv.genovec); |
| 4786 |
ZeroU32Arr(allele_ct, one_cts); |
| 4787 |
ZeroU32Arr(allele_ct, two_cts); |
| 4788 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 4789 |
GenoarrCountFreqsUnsafe(pgv.genovec, founder_x_ct, genocounts); |
| 4790 |
// const uint32_t hom_ref_ct = genocounts[0]; |
| 4791 |
const uint32_t het_ref_ct = genocounts[1]; |
| 4792 |
const uint32_t altxy_ct = genocounts[2]; |
| 4793 |
// two_cts[0] = hom_ref_ct; |
| 4794 |
// one_cts[0] = het_ref_ct; |
| 4795 |
one_cts[1] = het_ref_ct - pgv.patch_01_ct; |
| 4796 |
two_cts[1] = altxy_ct - pgv.patch_10_ct; |
| 4797 |
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) { |
| 4798 |
one_cts[pgv.patch_01_vals[uii]] += 1; |
| 4799 |
} |
| 4800 |
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) { |
| 4801 |
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii]; |
| 4802 |
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1]; |
| 4803 |
if (lo_code == hi_code) { |
| 4804 |
two_cts[lo_code] += 1; |
| 4805 |
} else { |
| 4806 |
one_cts[lo_code] += 1; |
| 4807 |
one_cts[hi_code] += 1; |
| 4808 |
} |
| 4809 |
} |
| 4810 |
uintptr_t knownsex_xgeno_idx = xgeno_idx; |
| 4811 |
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) { |
| 4812 |
x_knownsex_xgeno_cts[knownsex_xgeno_idx][0] = two_cts[aidx]; |
| 4813 |
x_knownsex_xgeno_cts[knownsex_xgeno_idx][1] = one_cts[aidx]; |
| 4814 |
++knownsex_xgeno_idx; |
| 4815 |
} |
| 4816 |
if (x_male_xgeno_cts) { |
| 4817 |
ZeroU32Arr(allele_ct, one_cts); |
| 4818 |
ZeroU32Arr(allele_ct, two_cts); |
| 4819 |
GenoarrCountSubsetFreqs(pgv.genovec, founder_male_interleaved_vec, founder_x_ct, founder_male_ct, genocounts); |
| 4820 |
const uint32_t male_het_ref_ct = genocounts[1]; |
| 4821 |
const uint32_t male_altxy_ct = genocounts[2]; |
| 4822 |
one_cts[1] = male_het_ref_ct; |
| 4823 |
two_cts[1] = male_altxy_ct; |
| 4824 |
uintptr_t sample_widx = 0; |
| 4825 |
uintptr_t cur_patch_bits = pgv.patch_01_set[0]; |
| 4826 |
uint32_t male_patch_01_ct = 0; |
| 4827 |
for (uint32_t uii = 0; uii != pgv.patch_01_ct; ++uii) { |
| 4828 |
const uintptr_t lowbit = BitIter1y(pgv.patch_01_set, &sample_widx, &cur_patch_bits); |
| 4829 |
if (founder_male_collapsed[sample_widx] & lowbit) { |
| 4830 |
++male_patch_01_ct; |
| 4831 |
one_cts[pgv.patch_01_vals[uii]] += 1; |
| 4832 |
} |
| 4833 |
} |
| 4834 |
one_cts[1] -= male_patch_01_ct; |
| 4835 |
sample_widx = 0; |
| 4836 |
cur_patch_bits = pgv.patch_10_set[0]; |
| 4837 |
uint32_t male_patch_10_ct = 0; |
| 4838 |
for (uint32_t uii = 0; uii != pgv.patch_10_ct; ++uii) { |
| 4839 |
const uintptr_t lowbit = BitIter1y(pgv.patch_10_set, &sample_widx, &cur_patch_bits); |
| 4840 |
if (founder_male_collapsed[sample_widx] & lowbit) { |
| 4841 |
++male_patch_10_ct; |
| 4842 |
const uintptr_t lo_code = pgv.patch_10_vals[2 * uii]; |
| 4843 |
const uintptr_t hi_code = pgv.patch_10_vals[2 * uii + 1]; |
| 4844 |
if (lo_code == hi_code) { |
| 4845 |
two_cts[lo_code] += 1; |
| 4846 |
} else { |
| 4847 |
one_cts[lo_code] += 1; |
| 4848 |
one_cts[hi_code] += 1; |
| 4849 |
} |
| 4850 |
} |
| 4851 |
} |
| 4852 |
two_cts[1] -= male_patch_10_ct; |
| 4853 |
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) { |
| 4854 |
x_male_xgeno_cts[xgeno_idx][0] = two_cts[aidx]; |
| 4855 |
x_male_xgeno_cts[xgeno_idx][1] = one_cts[aidx]; |
| 4856 |
++xgeno_idx; |
| 4857 |
} |
| 4858 |
} else { |
| 4859 |
xgeno_idx = knownsex_xgeno_idx; |
| 4860 |
} |
| 4861 |
} |
| 4862 |
} |
| 4863 |
} |
| 4864 |
} |
| 4865 |
while (0) { |
| 4866 |
GetMultiallelicMarginalCounts_ret_NOMEM: |
| 4867 |
reterr = kPglRetNomem; |
| 4868 |
break; |
| 4869 |
} |
| 4870 |
GetMultiallelicMarginalCounts_ret_1: |
| 4871 |
BigstackReset(bigstack_mark); |
| 4872 |
return reterr; |
| 4873 |
} |
| 4874 |
|
| 4875 |
typedef struct ComputeHweXLnPvalsCtxStruct { |
| 4876 |
const uintptr_t* variant_include; |
| 4877 |
const uintptr_t* allele_idx_offsets; |
| 4878 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts); |
| 4879 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts); |
| 4880 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts); |
| 4881 |
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts); |
| 4882 |
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts); |
| 4883 |
uint32_t* variant_uidx_starts; |
| 4884 |
uintptr_t* extra_aidx_starts; |
| 4885 |
uint32_t x_start; |
| 4886 |
uint32_t hwe_x_start; |
| 4887 |
uint32_t hwe_midp; |
| 4888 |
uint32_t hwe_x_ct; |
| 4889 |
|
| 4890 |
double* hwe_x_ln_pvals; |
| 4891 |
} ComputeHweXLnPvalsCtx; |
| 4892 |
|
| 4893 |
void ComputeHweXLnPvalsMain(uintptr_t tidx, uintptr_t thread_ct, ComputeHweXLnPvalsCtx* ctx) { |
| 4894 |
const uintptr_t* variant_include = ctx->variant_include; |
| 4895 |
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets; |
| 4896 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_raw_geno_cts) = ctx->founder_raw_geno_cts; |
| 4897 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_male_geno_cts) = ctx->founder_x_male_geno_cts; |
| 4898 |
const STD_ARRAY_PTR_DECL(uint32_t, 3, founder_x_nosex_geno_cts) = ctx->founder_x_nosex_geno_cts; |
| 4899 |
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_knownsex_xgeno_cts) = ctx->x_knownsex_xgeno_cts; |
| 4900 |
const STD_ARRAY_PTR_DECL(uint32_t, 2, x_male_xgeno_cts) = ctx->x_male_xgeno_cts; |
| 4901 |
const uint32_t x_start = ctx->x_start; |
| 4902 |
const uint32_t hwe_x_ct = ctx->hwe_x_ct; |
| 4903 |
const uint32_t hwe_midp = ctx->hwe_midp; |
| 4904 |
|
| 4905 |
// this needs to be aligned with ComputeUidxStartPartition() |
| 4906 |
const uint32_t variant_idx_end = (hwe_x_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct; |
| 4907 |
uint32_t variant_idx = (hwe_x_ct * S_CAST(uint64_t, tidx)) / thread_ct; |
| 4908 |
|
| 4909 |
uintptr_t xgeno_idx = ctx->extra_aidx_starts[tidx]; |
| 4910 |
double* hwe_x_ln_pvals_iter = &(ctx->hwe_x_ln_pvals[variant_idx + xgeno_idx]); |
| 4911 |
uintptr_t variant_uidx_base; |
| 4912 |
uintptr_t cur_bits; |
| 4913 |
BitIter1Start(variant_include, ctx->variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits); |
| 4914 |
uint32_t pct = 0; |
| 4915 |
uint32_t next_print_variant_idx = variant_idx_end; |
| 4916 |
if (!tidx) { |
| 4917 |
next_print_variant_idx = variant_idx_end / 100; |
| 4918 |
} |
| 4919 |
uint32_t male_1copy_ct = 0; |
| 4920 |
uint32_t male_hethap_ct = 0; |
| 4921 |
uint32_t male_0copy_ct = 0; |
| 4922 |
for (; variant_idx != variant_idx_end; ++variant_idx) { |
| 4923 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 4924 |
STD_ARRAY_KREF(uint32_t, 3) cur_raw_geno_cts = founder_raw_geno_cts[variant_uidx]; |
| 4925 |
uint32_t female_2copy_ct = cur_raw_geno_cts[0]; |
| 4926 |
uint32_t female_1copy_ct = cur_raw_geno_cts[1]; |
| 4927 |
uint32_t female_0copy_ct = cur_raw_geno_cts[2]; |
| 4928 |
if (founder_x_male_geno_cts) { |
| 4929 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = founder_x_male_geno_cts[variant_uidx - x_start]; |
| 4930 |
male_1copy_ct = cur_male_geno_cts[0]; |
| 4931 |
female_2copy_ct -= male_1copy_ct; |
| 4932 |
male_hethap_ct = cur_male_geno_cts[1]; |
| 4933 |
female_1copy_ct -= male_hethap_ct; |
| 4934 |
male_0copy_ct = cur_male_geno_cts[2]; |
| 4935 |
female_0copy_ct -= male_0copy_ct; |
| 4936 |
} |
| 4937 |
if (founder_x_nosex_geno_cts) { |
| 4938 |
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = founder_x_nosex_geno_cts[variant_uidx - x_start]; |
| 4939 |
female_2copy_ct -= cur_nosex_geno_cts[0]; |
| 4940 |
female_1copy_ct -= cur_nosex_geno_cts[1]; |
| 4941 |
female_0copy_ct -= cur_nosex_geno_cts[2]; |
| 4942 |
} |
| 4943 |
*hwe_x_ln_pvals_iter++ = HweXchrLnP(female_1copy_ct, female_2copy_ct, female_0copy_ct, male_1copy_ct, male_0copy_ct, hwe_midp); |
| 4944 |
if (allele_idx_offsets) { |
| 4945 |
const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 4946 |
if (allele_ct != 2) { |
| 4947 |
const uint32_t female_obs_ct = female_2copy_ct + female_1copy_ct + female_0copy_ct; |
| 4948 |
const uint32_t male_obs_ct = male_1copy_ct + male_hethap_ct + male_0copy_ct; |
| 4949 |
for (uint32_t aidx = 1; aidx != allele_ct; ++aidx) { |
| 4950 |
female_2copy_ct = x_knownsex_xgeno_cts[xgeno_idx][0]; |
| 4951 |
female_1copy_ct = x_knownsex_xgeno_cts[xgeno_idx][1]; |
| 4952 |
if (x_male_xgeno_cts) { |
| 4953 |
male_1copy_ct = x_male_xgeno_cts[xgeno_idx][0]; |
| 4954 |
female_2copy_ct -= male_1copy_ct; |
| 4955 |
male_hethap_ct = x_male_xgeno_cts[xgeno_idx][1]; |
| 4956 |
female_1copy_ct -= male_hethap_ct; |
| 4957 |
male_0copy_ct = male_obs_ct - male_1copy_ct - male_hethap_ct; |
| 4958 |
} |
| 4959 |
female_0copy_ct = female_obs_ct - female_2copy_ct - female_1copy_ct; |
| 4960 |
*hwe_x_ln_pvals_iter++ = HweXchrLnP(female_1copy_ct, female_2copy_ct, female_0copy_ct, male_1copy_ct, male_0copy_ct, hwe_midp); |
| 4961 |
++xgeno_idx; |
| 4962 |
} |
| 4963 |
} |
| 4964 |
} |
| 4965 |
if (variant_idx >= next_print_variant_idx) { |
| 4966 |
// only possible for tidx == 0 |
| 4967 |
if (pct > 10) { |
| 4968 |
putc_unlocked('\b', stdout); |
| 4969 |
} |
| 4970 |
pct = (variant_idx * 100LLU) / variant_idx_end; |
| 4971 |
printf("\b\b%u%%", pct++); |
| 4972 |
fflush(stdout); |
| 4973 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_idx_end)) / 100; |
| 4974 |
} |
| 4975 |
} |
| 4976 |
if (pct > 10) { |
| 4977 |
putc_unlocked('\b', stdout); |
| 4978 |
} |
| 4979 |
} |
| 4980 |
|
| 4981 |
THREAD_FUNC_DECL ComputeHweXLnPvalsThread(void* raw_arg) { |
| 4982 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 4983 |
ComputeHweXLnPvalsCtx* ctx = S_CAST(ComputeHweXLnPvalsCtx*, arg->sharedp->context); |
| 4984 |
ComputeHweXLnPvalsMain(arg->tidx, GetThreadCt(arg->sharedp) + 1, ctx); |
| 4985 |
THREAD_RETURN; |
| 4986 |
} |
| 4987 |
|
| 4988 |
PglErr ComputeHweXLnPvals(const uintptr_t* variant_include, 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, 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), uint32_t x_start, uint32_t hwe_x_ct, uintptr_t x_xallele_ct, uint32_t hwe_midp, uint32_t calc_thread_ct, double** hwe_x_ln_pvals_ptr) { |
| 4989 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 4990 |
PglErr reterr = kPglRetSuccess; |
| 4991 |
ThreadGroup tg; |
| 4992 |
PreinitThreads(&tg); |
| 4993 |
ComputeHweXLnPvalsCtx ctx; |
| 4994 |
{ |
| 4995 |
assert(hwe_x_ct); |
| 4996 |
if (unlikely(bigstack_alloc_d(hwe_x_ct + x_xallele_ct, hwe_x_ln_pvals_ptr))) { |
| 4997 |
goto ComputeHweXLnPvals_ret_NOMEM; |
| 4998 |
} |
| 4999 |
bigstack_mark = g_bigstack_base; |
| 5000 |
ctx.hwe_x_ln_pvals = *hwe_x_ln_pvals_ptr; |
| 5001 |
|
| 5002 |
if (calc_thread_ct > hwe_x_ct) { |
| 5003 |
calc_thread_ct = hwe_x_ct; |
| 5004 |
} |
| 5005 |
if (unlikely(SetThreadCt0(calc_thread_ct - 1, &tg) || |
| 5006 |
bigstack_alloc_u32(calc_thread_ct, &ctx.variant_uidx_starts) || |
| 5007 |
bigstack_alloc_w(calc_thread_ct, &ctx.extra_aidx_starts))) { |
| 5008 |
goto ComputeHweXLnPvals_ret_NOMEM; |
| 5009 |
} |
| 5010 |
// possible todo: extra-allele-based load balancer |
| 5011 |
ComputeUidxStartPartition(variant_include, hwe_x_ct, calc_thread_ct, x_start, ctx.variant_uidx_starts); |
| 5012 |
ctx.extra_aidx_starts[0] = 0; |
| 5013 |
uintptr_t extra_aidx = 0; |
| 5014 |
uint32_t prev_variant_uidx = ctx.variant_uidx_starts[0]; |
| 5015 |
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) { |
| 5016 |
const uint32_t cur_variant_uidx = ctx.variant_uidx_starts[tidx]; |
| 5017 |
extra_aidx += CountExtraAlleles(variant_include, allele_idx_offsets, prev_variant_uidx, cur_variant_uidx, 1); |
| 5018 |
ctx.extra_aidx_starts[tidx] = extra_aidx; |
| 5019 |
prev_variant_uidx = cur_variant_uidx; |
| 5020 |
} |
| 5021 |
ctx.variant_include = variant_include; |
| 5022 |
ctx.allele_idx_offsets = allele_idx_offsets; |
| 5023 |
ctx.founder_raw_geno_cts = founder_raw_geno_cts; |
| 5024 |
ctx.founder_x_male_geno_cts = founder_x_male_geno_cts; |
| 5025 |
ctx.founder_x_nosex_geno_cts = founder_x_nosex_geno_cts; |
| 5026 |
ctx.x_knownsex_xgeno_cts = x_knownsex_xgeno_cts; |
| 5027 |
ctx.x_male_xgeno_cts = x_male_xgeno_cts; |
| 5028 |
ctx.x_start = x_start; |
| 5029 |
ctx.hwe_x_ct = hwe_x_ct; |
| 5030 |
ctx.hwe_midp = hwe_midp; |
| 5031 |
logprintf("Computing chrX Hardy-Weinberg %sp-values... ", hwe_midp? "mid" : ""); |
| 5032 |
fputs("0%", stdout); |
| 5033 |
fflush(stdout); |
| 5034 |
if (calc_thread_ct > 1) { |
| 5035 |
SetThreadFuncAndData(ComputeHweXLnPvalsThread, &ctx, &tg); |
| 5036 |
DeclareLastThreadBlock(&tg); |
| 5037 |
if (unlikely(SpawnThreads(&tg))) { |
| 5038 |
goto ComputeHweXLnPvals_ret_THREAD_CREATE_FAIL; |
| 5039 |
} |
| 5040 |
} |
| 5041 |
ComputeHweXLnPvalsMain(calc_thread_ct - 1, calc_thread_ct, &ctx); |
| 5042 |
JoinThreads0(&tg); |
| 5043 |
fputs("\b\b", stdout); |
| 5044 |
logputs("done.\n"); |
| 5045 |
} |
| 5046 |
while (0) { |
| 5047 |
ComputeHweXLnPvals_ret_NOMEM: |
| 5048 |
reterr = kPglRetNomem; |
| 5049 |
break; |
| 5050 |
ComputeHweXLnPvals_ret_THREAD_CREATE_FAIL: |
| 5051 |
reterr = kPglRetThreadCreateFail; |
| 5052 |
break; |
| 5053 |
} |
| 5054 |
CleanupThreads(&tg); |
| 5055 |
BigstackReset(bigstack_mark); |
| 5056 |
return reterr; |
| 5057 |
} |
| 5058 |
|
| 5059 |
PglErr HardyReport(const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const uintptr_t* nonref_flags, const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 2, autosomal_xgeno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_x_male_geno_cts), const STD_ARRAY_PTR_DECL(uint32_t, 3, hwe_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, uint32_t variant_ct, uint32_t hwe_x_ct, uint32_t max_allele_slen, PgenGlobalFlags gflags, double output_min_ln, HardyFlags hardy_flags, uint32_t max_thread_ct, uint32_t nonfounders, char* outname, char* outname_end) { |
| 5060 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 5061 |
char* cswritep = nullptr; |
| 5062 |
CompressStreamState css; |
| 5063 |
PglErr reterr = kPglRetSuccess; |
| 5064 |
PreinitCstream(&css); |
| 5065 |
{ |
| 5066 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 5067 |
const uint32_t chr_code_end = cip->max_code + 1 + cip->name_ct; |
| 5068 |
const uint32_t chr_code_endl = BitCtToWordCt(chr_code_end); |
| 5069 |
const uintptr_t overflow_buf_size = RoundUpPow2(kCompressStreamBlock + max_chr_blen + kMaxIdSlen + 512 + 2 * max_allele_slen, kCacheline); |
| 5070 |
const uint32_t output_zst = hardy_flags & kfHardyZs; |
| 5071 |
uintptr_t overflow_buf_alloc = overflow_buf_size; |
| 5072 |
if (output_zst) { |
| 5073 |
overflow_buf_alloc += CstreamWkspaceReq(overflow_buf_size); |
| 5074 |
} |
| 5075 |
char* overflow_buf; |
| 5076 |
uintptr_t* chr_skips; |
| 5077 |
if (unlikely(bigstack_alloc_c(overflow_buf_alloc, &overflow_buf) || |
| 5078 |
bigstack_alloc_w(chr_code_endl, &chr_skips))) { |
| 5079 |
goto HardyReport_ret_NOMEM; |
| 5080 |
} |
| 5081 |
// skip chrX, chrY, chrM here |
| 5082 |
memcpy(chr_skips, cip->haploid_mask, chr_code_endl * sizeof(intptr_t)); |
| 5083 |
const uint32_t chr_skip_ct = PopcountWords(chr_skips, chr_code_endl); |
| 5084 |
uint32_t variant_skip_ct = 0; |
| 5085 |
uintptr_t chr_uidx_base = 0; |
| 5086 |
uintptr_t chr_skips_bits = chr_skips[0]; |
| 5087 |
for (uint32_t chr_skip_idx = 0; chr_skip_idx != chr_skip_ct; ++chr_skip_idx) { |
| 5088 |
const uintptr_t chr_uidx = BitIter1(chr_skips, &chr_uidx_base, &chr_skips_bits); |
| 5089 |
if (IsSet(cip->chr_mask, chr_uidx)) { |
| 5090 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[chr_uidx]; |
| 5091 |
variant_skip_ct += PopcountBitRange(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1]); |
| 5092 |
} |
| 5093 |
} |
| 5094 |
if (variant_skip_ct - hwe_x_ct) { |
| 5095 |
logprintf("--hardy: Skipping %u haploid variant%s.\n", variant_skip_ct - hwe_x_ct, (variant_skip_ct - hwe_x_ct == 1)? "" : "s"); |
| 5096 |
} |
| 5097 |
variant_ct -= variant_skip_ct; |
| 5098 |
const uint32_t midp = (hardy_flags / kfHardyMidp) & 1; |
| 5099 |
const uint32_t redundant = (hardy_flags / kfHardyRedundant) & 1; |
| 5100 |
const uint32_t chr_col = hardy_flags & kfHardyColChrom; |
| 5101 |
const uint32_t ref_col = hardy_flags & kfHardyColRef; |
| 5102 |
const uint32_t alt1_col = hardy_flags & kfHardyColAlt1; |
| 5103 |
const uint32_t alt_col = hardy_flags & kfHardyColAlt; |
| 5104 |
const uint32_t all_nonref = (gflags & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 5105 |
// customize this, since the standard calculation does not exclude haploid |
| 5106 |
// chromosomes |
| 5107 |
uint32_t provref_col = 0; |
| 5108 |
if (ref_col) { |
| 5109 |
if (hardy_flags & kfHardyColProvref) { |
| 5110 |
provref_col = 1; |
| 5111 |
} else if (!(hardy_flags & kfHardyColMaybeprovref)) { |
| 5112 |
// do nothing |
| 5113 |
} else if (!nonref_flags) { |
| 5114 |
provref_col = all_nonref; |
| 5115 |
} else { |
| 5116 |
const uint32_t chr_ct = cip->chr_ct; |
| 5117 |
for (uint32_t chr_fo_idx = 0; chr_fo_idx != chr_ct; ++chr_fo_idx) { |
| 5118 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 5119 |
if ((!IsSet(cip->chr_mask, chr_idx)) || IsSet(chr_skips, chr_idx)) { |
| 5120 |
continue; |
| 5121 |
} |
| 5122 |
if (!IntersectionRangeIsEmpty(variant_include, nonref_flags, cip->chr_fo_vidx_start[chr_fo_idx], cip->chr_fo_vidx_start[chr_fo_idx + 1])) { |
| 5123 |
provref_col = 1; |
| 5124 |
break; |
| 5125 |
} |
| 5126 |
} |
| 5127 |
} |
| 5128 |
} |
| 5129 |
const uint32_t report_neglog10p = (hardy_flags / kfHardyLog10) & 1; |
| 5130 |
const uint32_t ax_col = hardy_flags & kfHardyColAx; |
| 5131 |
const uint32_t gcounts = hardy_flags & (kfHardyColGcounts | kfHardyColGcount1col); |
| 5132 |
const uint32_t gcount_1col = hardy_flags & kfHardyColGcount1col; |
| 5133 |
const char gcount_delim = gcount_1col? ',' : '\t'; |
| 5134 |
const uint32_t hetfreq_cols = hardy_flags & kfHardyColHetfreq; |
| 5135 |
const uint32_t p_col = hardy_flags & kfHardyColP; |
| 5136 |
if (variant_ct) { |
| 5137 |
OutnameZstSet(".hardy", output_zst, outname_end); |
| 5138 |
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css); |
| 5139 |
if (unlikely(reterr)) { |
| 5140 |
goto HardyReport_ret_1; |
| 5141 |
} |
| 5142 |
cswritep = overflow_buf; |
| 5143 |
*cswritep++ = '#'; |
| 5144 |
|
| 5145 |
// includes trailing tab |
| 5146 |
char* chr_buf = nullptr; |
| 5147 |
if (chr_col) { |
| 5148 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 5149 |
goto HardyReport_ret_NOMEM; |
| 5150 |
} |
| 5151 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 5152 |
} |
| 5153 |
if (hardy_flags & kfHardyColPos) { |
| 5154 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 5155 |
} else { |
| 5156 |
variant_bps = nullptr; |
| 5157 |
} |
| 5158 |
cswritep = strcpya_k(cswritep, "ID"); |
| 5159 |
if (ref_col) { |
| 5160 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 5161 |
} |
| 5162 |
if (alt1_col) { |
| 5163 |
cswritep = strcpya_k(cswritep, "\tALT1"); |
| 5164 |
} |
| 5165 |
if (alt_col) { |
| 5166 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 5167 |
} |
| 5168 |
if (provref_col) { |
| 5169 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 5170 |
} |
| 5171 |
cswritep = strcpya_k(cswritep, "\tA1"); |
| 5172 |
if (ax_col) { |
| 5173 |
cswritep = strcpya_k(cswritep, "\tAX"); |
| 5174 |
} |
| 5175 |
if (gcounts) { |
| 5176 |
if (gcount_1col) { |
| 5177 |
cswritep = strcpya_k(cswritep, "\tGCOUNTS"); |
| 5178 |
} else { |
| 5179 |
cswritep = strcpya_k(cswritep, "\tHOM_A1_CT\tHET_A1_CT\tTWO_AX_CT"); |
| 5180 |
} |
| 5181 |
} |
| 5182 |
if (hetfreq_cols) { |
| 5183 |
cswritep = strcpya_k(cswritep, "\tO(HET_A1)\tE(HET_A1)"); |
| 5184 |
} |
| 5185 |
if (p_col) { |
| 5186 |
*cswritep++ = '\t'; |
| 5187 |
if (report_neglog10p) { |
| 5188 |
cswritep = strcpya_k(cswritep, "NEG_LOG10_"); |
| 5189 |
} |
| 5190 |
if (midp) { |
| 5191 |
cswritep = strcpya_k(cswritep, "MID"); |
| 5192 |
} |
| 5193 |
*cswritep++ = 'P'; |
| 5194 |
} |
| 5195 |
AppendBinaryEoln(&cswritep); |
| 5196 |
uintptr_t variant_uidx_base = 0; |
| 5197 |
uintptr_t variant_include_bits = variant_include[0]; |
| 5198 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 5199 |
uint32_t chr_end = 0; |
| 5200 |
uint32_t chr_buf_blen = 0; |
| 5201 |
uint32_t pct = 0; |
| 5202 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 5203 |
printf("--hardy%s%s: 0%%", output_zst? " zs" : "", midp? " midp" : ""); |
| 5204 |
fflush(stdout); |
| 5205 |
uintptr_t xgeno_idx = 0; |
| 5206 |
uint32_t allele_ct = 2; |
| 5207 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 5208 |
uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 5209 |
// bugfix (15 May 2018): this needs to happen even if we aren't |
| 5210 |
// printing #CHROM column |
| 5211 |
if (variant_uidx >= chr_end) { |
| 5212 |
uint32_t chr_idx; |
| 5213 |
do { |
| 5214 |
++chr_fo_idx; |
| 5215 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 5216 |
chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 5217 |
} while ((variant_uidx >= chr_end) || IsSet(chr_skips, chr_idx)); |
| 5218 |
BitIter1Start(variant_include, cip->chr_fo_vidx_start[chr_fo_idx], &variant_uidx_base, &variant_include_bits); |
| 5219 |
variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 5220 |
if (chr_col) { |
| 5221 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 5222 |
*chr_name_end = '\t'; |
| 5223 |
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf); |
| 5224 |
} |
| 5225 |
} |
| 5226 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 5227 |
if (allele_idx_offsets) { |
| 5228 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 5229 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 5230 |
} |
| 5231 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 5232 |
const uint32_t print_allele_ct = ((allele_ct == 2) && (!redundant))? 1 : allele_ct; |
| 5233 |
STD_ARRAY_KREF(uint32_t, 3) cur_geno_cts = hwe_geno_cts[variant_uidx]; |
| 5234 |
uint32_t het_a1_ct = cur_geno_cts[1]; |
| 5235 |
const uint32_t nonmissing_ct = cur_geno_cts[0] + het_a1_ct + cur_geno_cts[2]; |
| 5236 |
for (uint32_t a1_idx = 0; a1_idx != print_allele_ct; ++a1_idx) { |
| 5237 |
if (chr_col) { |
| 5238 |
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen); |
| 5239 |
} |
| 5240 |
if (variant_bps) { |
| 5241 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 5242 |
} |
| 5243 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 5244 |
if (ref_col) { |
| 5245 |
*cswritep++ = '\t'; |
| 5246 |
cswritep = strcpya(cswritep, cur_alleles[0]); |
| 5247 |
} |
| 5248 |
if (alt1_col) { |
| 5249 |
*cswritep++ = '\t'; |
| 5250 |
cswritep = strcpya(cswritep, cur_alleles[1]); |
| 5251 |
} |
| 5252 |
if (alt_col) { |
| 5253 |
*cswritep++ = '\t'; |
| 5254 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 5255 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5256 |
goto HardyReport_ret_WRITE_FAIL; |
| 5257 |
} |
| 5258 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 5259 |
} |
| 5260 |
--cswritep; |
| 5261 |
} |
| 5262 |
if (provref_col) { |
| 5263 |
*cswritep++ = '\t'; |
| 5264 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N'; |
| 5265 |
} |
| 5266 |
*cswritep++ = '\t'; |
| 5267 |
cswritep = strcpya(cswritep, cur_alleles[a1_idx]); |
| 5268 |
if (ax_col) { |
| 5269 |
*cswritep++ = '\t'; |
| 5270 |
for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) { |
| 5271 |
if (allele_idx == a1_idx) { |
| 5272 |
continue; |
| 5273 |
} |
| 5274 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5275 |
goto HardyReport_ret_WRITE_FAIL; |
| 5276 |
} |
| 5277 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 5278 |
} |
| 5279 |
--cswritep; |
| 5280 |
} |
| 5281 |
uint32_t hom_a1_ct; |
| 5282 |
uint32_t two_ax_ct; |
| 5283 |
if (!a1_idx) { |
| 5284 |
hom_a1_ct = cur_geno_cts[0]; |
| 5285 |
two_ax_ct = cur_geno_cts[2]; |
| 5286 |
} else if (allele_ct == 2) { |
| 5287 |
// special case, don't read from autosomal_xgeno_cts |
| 5288 |
hom_a1_ct = cur_geno_cts[2]; |
| 5289 |
two_ax_ct = cur_geno_cts[0]; |
| 5290 |
} else { |
| 5291 |
STD_ARRAY_KREF(uint32_t, 2) xgeno_cts = autosomal_xgeno_cts[xgeno_idx]; |
| 5292 |
hom_a1_ct = xgeno_cts[0]; |
| 5293 |
het_a1_ct = xgeno_cts[1]; |
| 5294 |
two_ax_ct = nonmissing_ct - hom_a1_ct - het_a1_ct; |
| 5295 |
++xgeno_idx; |
| 5296 |
} |
| 5297 |
if (gcounts) { |
| 5298 |
*cswritep++ = '\t'; |
| 5299 |
cswritep = u32toa_x(hom_a1_ct, gcount_delim, cswritep); |
| 5300 |
cswritep = u32toa_x(het_a1_ct, gcount_delim, cswritep); |
| 5301 |
cswritep = u32toa(two_ax_ct, cswritep); |
| 5302 |
} |
| 5303 |
if (hetfreq_cols) { |
| 5304 |
*cswritep++ = '\t'; |
| 5305 |
const double nonmissing_ct_recip = 1.0 / u31tod(nonmissing_ct); |
| 5306 |
cswritep = dtoa_g(u31tod(het_a1_ct) * nonmissing_ct_recip, cswritep); |
| 5307 |
*cswritep++ = '\t'; |
| 5308 |
const double dbl_maj_freq = (hom_a1_ct * 2 + het_a1_ct) * nonmissing_ct_recip; |
| 5309 |
// (1.0 - maj_freq) is vulnerable to catastrophic cancellation when |
| 5310 |
// maj_freq is 1 |
| 5311 |
if (hom_a1_ct == nonmissing_ct) { |
| 5312 |
*cswritep++ = '0'; |
| 5313 |
} else { |
| 5314 |
const double expected_het_freq = dbl_maj_freq * (1.0 - dbl_maj_freq * 0.5); |
| 5315 |
cswritep = dtoa_g(expected_het_freq, cswritep); |
| 5316 |
} |
| 5317 |
} |
| 5318 |
if (p_col) { |
| 5319 |
// possible todo: multithread this |
| 5320 |
*cswritep++ = '\t'; |
| 5321 |
const double hwe_ln_p = HweLnP(het_a1_ct, hom_a1_ct, two_ax_ct, midp); |
| 5322 |
if (report_neglog10p) { |
| 5323 |
const double reported_val = (-kRecipLn10) * hwe_ln_p; |
| 5324 |
cswritep = dtoa_g(reported_val, cswritep); |
| 5325 |
} else { |
| 5326 |
cswritep = lntoa_g(MAXV(hwe_ln_p, output_min_ln), cswritep); |
| 5327 |
} |
| 5328 |
} |
| 5329 |
AppendBinaryEoln(&cswritep); |
| 5330 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5331 |
goto HardyReport_ret_WRITE_FAIL; |
| 5332 |
} |
| 5333 |
} |
| 5334 |
if (variant_idx >= next_print_variant_idx) { |
| 5335 |
if (pct > 10) { |
| 5336 |
putc_unlocked('\b', stdout); |
| 5337 |
} |
| 5338 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 5339 |
printf("\b\b%u%%", pct++); |
| 5340 |
fflush(stdout); |
| 5341 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 5342 |
} |
| 5343 |
} |
| 5344 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 5345 |
goto HardyReport_ret_WRITE_FAIL; |
| 5346 |
} |
| 5347 |
putc_unlocked('\r', stdout); |
| 5348 |
logprintfww("--hardy%s%s: Autosomal Hardy-Weinberg report (%s) written to %s .\n", output_zst? " zs" : "", midp? " midp" : "", nonfounders? "all samples" : "founders only", outname); |
| 5349 |
} |
| 5350 |
if (hwe_x_ct) { |
| 5351 |
BigstackReset(chr_skips); |
| 5352 |
OutnameZstSet(".hardy.x", output_zst, outname_end); |
| 5353 |
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css); |
| 5354 |
if (unlikely(reterr)) { |
| 5355 |
goto HardyReport_ret_1; |
| 5356 |
} |
| 5357 |
cswritep = overflow_buf; |
| 5358 |
*cswritep++ = '#'; |
| 5359 |
|
| 5360 |
// includes trailing tab |
| 5361 |
char x_name_buf[8]; |
| 5362 |
uint32_t x_name_blen = 0; |
| 5363 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 5364 |
if (chr_col) { |
| 5365 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 5366 |
char* write_iter = chrtoa(cip, x_code, x_name_buf); |
| 5367 |
*write_iter++ = '\t'; |
| 5368 |
x_name_blen = write_iter - x_name_buf; |
| 5369 |
} |
| 5370 |
if (hardy_flags & kfHardyColPos) { |
| 5371 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 5372 |
} else { |
| 5373 |
variant_bps = nullptr; |
| 5374 |
} |
| 5375 |
cswritep = strcpya_k(cswritep, "ID"); |
| 5376 |
if (ref_col) { |
| 5377 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 5378 |
} |
| 5379 |
if (alt1_col) { |
| 5380 |
cswritep = strcpya_k(cswritep, "\tALT1"); |
| 5381 |
} |
| 5382 |
if (alt_col) { |
| 5383 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 5384 |
} |
| 5385 |
const uint32_t x_chr_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 5386 |
const uint32_t x_start = cip->chr_fo_vidx_start[x_chr_fo_idx]; |
| 5387 |
if (ref_col && ((hardy_flags & (kfHardyColMaybeprovref | kfHardyColProvref)) == kfHardyColMaybeprovref) && nonref_flags) { |
| 5388 |
provref_col = !IntersectionRangeIsEmpty(variant_include, nonref_flags, x_start, cip->chr_fo_vidx_start[x_chr_fo_idx + 1]); |
| 5389 |
} |
| 5390 |
if (provref_col) { |
| 5391 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 5392 |
} |
| 5393 |
cswritep = strcpya_k(cswritep, "\tA1"); |
| 5394 |
if (ax_col) { |
| 5395 |
cswritep = strcpya_k(cswritep, "\tAX"); |
| 5396 |
} |
| 5397 |
if (gcounts) { |
| 5398 |
if (gcount_1col) { |
| 5399 |
cswritep = strcpya_k(cswritep, "\tGCOUNTS"); |
| 5400 |
} else { |
| 5401 |
cswritep = strcpya_k(cswritep, "\tFEMALE_HOM_A1_CT\tFEMALE_HET_A1_CT\tFEMALE_TWO_AX_CT\tMALE_A1_CT\tMALE_AX_CT"); |
| 5402 |
} |
| 5403 |
} |
| 5404 |
if (hetfreq_cols) { |
| 5405 |
cswritep = strcpya_k(cswritep, "\tO(FEMALE_HET_A1)\tE(FEMALE_HET_A1)"); |
| 5406 |
} |
| 5407 |
const uint32_t sexaf_cols = hardy_flags & kfHardyColSexaf; |
| 5408 |
if (sexaf_cols) { |
| 5409 |
cswritep = strcpya_k(cswritep, "\tFEMALE_A1_FREQ\tMALE_A1_FREQ"); |
| 5410 |
} |
| 5411 |
const uint32_t femalep_col = hardy_flags & kfHardyColFemalep; |
| 5412 |
if (femalep_col) { |
| 5413 |
cswritep = strcpya_k(cswritep, "\tFEMALE_ONLY_"); |
| 5414 |
if (report_neglog10p) { |
| 5415 |
cswritep = strcpya_k(cswritep, "NEG_LOG10_"); |
| 5416 |
} |
| 5417 |
if (midp) { |
| 5418 |
cswritep = strcpya_k(cswritep, "MID"); |
| 5419 |
} |
| 5420 |
*cswritep++ = 'P'; |
| 5421 |
} |
| 5422 |
if (p_col) { |
| 5423 |
*cswritep++ = '\t'; |
| 5424 |
if (report_neglog10p) { |
| 5425 |
cswritep = strcpya_k(cswritep, "NEG_LOG10_"); |
| 5426 |
} |
| 5427 |
if (midp) { |
| 5428 |
cswritep = strcpya_k(cswritep, "MID"); |
| 5429 |
} |
| 5430 |
*cswritep++ = 'P'; |
| 5431 |
} |
| 5432 |
AppendBinaryEoln(&cswritep); |
| 5433 |
fputs("--hardy: Writing chrX results...", stdout); |
| 5434 |
fflush(stdout); |
| 5435 |
uintptr_t variant_uidx_base; |
| 5436 |
uintptr_t variant_include_bits; |
| 5437 |
BitIter1Start(variant_include, x_start, &variant_uidx_base, &variant_include_bits); |
| 5438 |
uintptr_t xgeno_idx = 0; |
| 5439 |
uint32_t allele_ct = 2; |
| 5440 |
uint32_t male_a1_ct = 0; |
| 5441 |
uint32_t male_ax_ct = 0; |
| 5442 |
for (uint32_t variant_idx = 0; variant_idx != hwe_x_ct; ++variant_idx) { |
| 5443 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 5444 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 5445 |
if (allele_idx_offsets) { |
| 5446 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 5447 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 5448 |
} |
| 5449 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 5450 |
const uint32_t print_allele_ct = ((allele_ct == 2) && (!redundant))? 1 : allele_ct; |
| 5451 |
STD_ARRAY_KREF(uint32_t, 3) cur_geno_cts = hwe_geno_cts[variant_uidx]; |
| 5452 |
uint32_t female_obs_ct = cur_geno_cts[0] + cur_geno_cts[1] + cur_geno_cts[2]; |
| 5453 |
if (hwe_x_nosex_geno_cts) { |
| 5454 |
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = hwe_x_nosex_geno_cts[variant_uidx - x_start]; |
| 5455 |
female_obs_ct -= cur_nosex_geno_cts[0] + cur_nosex_geno_cts[1] + cur_nosex_geno_cts[2]; |
| 5456 |
} |
| 5457 |
uint32_t male_obs_ct = 0; |
| 5458 |
if (hwe_x_male_geno_cts) { |
| 5459 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = hwe_x_male_geno_cts[variant_uidx - x_start]; |
| 5460 |
male_obs_ct = cur_male_geno_cts[0] + cur_male_geno_cts[1] + cur_male_geno_cts[2]; |
| 5461 |
female_obs_ct -= male_obs_ct; |
| 5462 |
} |
| 5463 |
for (uint32_t a1_idx = 0; a1_idx != print_allele_ct; ++a1_idx) { |
| 5464 |
cswritep = memcpya(cswritep, x_name_buf, x_name_blen); |
| 5465 |
if (variant_bps) { |
| 5466 |
cswritep = u32toa_x(variant_bps[variant_uidx], '\t', cswritep); |
| 5467 |
} |
| 5468 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 5469 |
if (ref_col) { |
| 5470 |
*cswritep++ = '\t'; |
| 5471 |
cswritep = strcpya(cswritep, cur_alleles[0]); |
| 5472 |
} |
| 5473 |
if (alt1_col) { |
| 5474 |
*cswritep++ = '\t'; |
| 5475 |
cswritep = strcpya(cswritep, cur_alleles[1]); |
| 5476 |
} |
| 5477 |
if (alt_col) { |
| 5478 |
*cswritep++ = '\t'; |
| 5479 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 5480 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5481 |
goto HardyReport_ret_WRITE_FAIL; |
| 5482 |
} |
| 5483 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 5484 |
} |
| 5485 |
--cswritep; |
| 5486 |
} |
| 5487 |
if (provref_col) { |
| 5488 |
*cswritep++ = '\t'; |
| 5489 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx)))? 'Y' : 'N'; |
| 5490 |
} |
| 5491 |
*cswritep++ = '\t'; |
| 5492 |
cswritep = strcpya(cswritep, cur_alleles[a1_idx]); |
| 5493 |
if (ax_col) { |
| 5494 |
*cswritep++ = '\t'; |
| 5495 |
for (uint32_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) { |
| 5496 |
if (allele_idx == a1_idx) { |
| 5497 |
continue; |
| 5498 |
} |
| 5499 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5500 |
goto HardyReport_ret_WRITE_FAIL; |
| 5501 |
} |
| 5502 |
cswritep = strcpyax(cswritep, cur_alleles[allele_idx], ','); |
| 5503 |
} |
| 5504 |
--cswritep; |
| 5505 |
} |
| 5506 |
uint32_t female_hom_a1_ct; |
| 5507 |
uint32_t female_het_a1_ct; |
| 5508 |
uint32_t female_two_ax_ct; |
| 5509 |
if ((!a1_idx) || (allele_ct == 2)) { |
| 5510 |
female_hom_a1_ct = cur_geno_cts[2 * a1_idx]; |
| 5511 |
female_het_a1_ct = cur_geno_cts[1]; |
| 5512 |
female_two_ax_ct = cur_geno_cts[2 - 2 * a1_idx]; |
| 5513 |
if (hwe_x_male_geno_cts) { |
| 5514 |
STD_ARRAY_KREF(uint32_t, 3) cur_male_geno_cts = hwe_x_male_geno_cts[variant_uidx - x_start]; |
| 5515 |
male_a1_ct = cur_male_geno_cts[2 * a1_idx]; |
| 5516 |
female_hom_a1_ct -= male_a1_ct; |
| 5517 |
female_het_a1_ct -= cur_male_geno_cts[1]; |
| 5518 |
male_ax_ct = cur_male_geno_cts[2 - 2 * a1_idx]; |
| 5519 |
female_two_ax_ct -= male_ax_ct; |
| 5520 |
} |
| 5521 |
if (hwe_x_nosex_geno_cts) { |
| 5522 |
STD_ARRAY_KREF(uint32_t, 3) cur_nosex_geno_cts = hwe_x_nosex_geno_cts[variant_uidx - x_start]; |
| 5523 |
female_hom_a1_ct -= cur_nosex_geno_cts[2 * a1_idx]; |
| 5524 |
female_het_a1_ct -= cur_nosex_geno_cts[1]; |
| 5525 |
female_two_ax_ct -= cur_nosex_geno_cts[2 - 2 * a1_idx]; |
| 5526 |
} |
| 5527 |
} else { |
| 5528 |
STD_ARRAY_KREF(uint32_t, 2) cur_knownsex_xgeno_cts = x_knownsex_xgeno_cts[xgeno_idx]; |
| 5529 |
female_hom_a1_ct = cur_knownsex_xgeno_cts[0]; |
| 5530 |
female_het_a1_ct = cur_knownsex_xgeno_cts[1]; |
| 5531 |
if (x_male_xgeno_cts) { |
| 5532 |
STD_ARRAY_KREF(uint32_t, 2) cur_male_xgeno_cts = x_male_xgeno_cts[xgeno_idx]; |
| 5533 |
male_a1_ct = cur_male_xgeno_cts[0]; |
| 5534 |
female_hom_a1_ct -= male_a1_ct; |
| 5535 |
const uint32_t male_hethap_ct = cur_male_xgeno_cts[1]; |
| 5536 |
female_het_a1_ct -= male_hethap_ct; |
| 5537 |
male_ax_ct = male_obs_ct - male_a1_ct - male_hethap_ct; |
| 5538 |
} |
| 5539 |
female_two_ax_ct = female_obs_ct - female_hom_a1_ct - female_het_a1_ct; |
| 5540 |
// Correct to increment this before looking up hwe_x_ln_pvals[] |
| 5541 |
// (and to not increment on a1_idx == 0). |
| 5542 |
++xgeno_idx; |
| 5543 |
} |
| 5544 |
if (gcounts) { |
| 5545 |
*cswritep++ = '\t'; |
| 5546 |
cswritep = u32toa_x(female_hom_a1_ct, gcount_delim, cswritep); |
| 5547 |
cswritep = u32toa_x(female_het_a1_ct, gcount_delim, cswritep); |
| 5548 |
cswritep = u32toa_x(female_two_ax_ct, gcount_delim, cswritep); |
| 5549 |
cswritep = u32toa_x(male_a1_ct, gcount_delim, cswritep); |
| 5550 |
cswritep = u32toa(male_ax_ct, cswritep); |
| 5551 |
} |
| 5552 |
if (hetfreq_cols || sexaf_cols) { |
| 5553 |
const double female_obs_ct_recip = 1.0 / u31tod(female_obs_ct); |
| 5554 |
const double dbl_a1_freq = (female_hom_a1_ct * 2 + female_het_a1_ct) * female_obs_ct_recip; |
| 5555 |
if (hetfreq_cols) { |
| 5556 |
*cswritep++ = '\t'; |
| 5557 |
cswritep = dtoa_g(u31tod(female_het_a1_ct) * female_obs_ct_recip, cswritep); |
| 5558 |
*cswritep++ = '\t'; |
| 5559 |
// (1.0 - a1_freq) is vulnerable to catastrophic cancellation |
| 5560 |
// when actual a1_freq is 1. |
| 5561 |
if (female_hom_a1_ct == female_obs_ct) { |
| 5562 |
*cswritep++ = '0'; |
| 5563 |
} else { |
| 5564 |
const double expected_het_freq = dbl_a1_freq * (1.0 - 0.5 * dbl_a1_freq); |
| 5565 |
cswritep = dtoa_g(expected_het_freq, cswritep); |
| 5566 |
} |
| 5567 |
} |
| 5568 |
if (sexaf_cols) { |
| 5569 |
*cswritep++ = '\t'; |
| 5570 |
cswritep = dtoa_g(dbl_a1_freq * 0.5, cswritep); |
| 5571 |
*cswritep++ = '\t'; |
| 5572 |
const double male_a1_freq = u31tod(male_a1_ct) / u31tod(male_a1_ct + male_ax_ct); |
| 5573 |
cswritep = dtoa_g(male_a1_freq, cswritep); |
| 5574 |
} |
| 5575 |
} |
| 5576 |
if (femalep_col) { |
| 5577 |
*cswritep++ = '\t'; |
| 5578 |
const double female_hwe_ln_p = HweLnP(female_het_a1_ct, female_hom_a1_ct, female_two_ax_ct, midp); |
| 5579 |
if (report_neglog10p) { |
| 5580 |
const double reported_val = (-kRecipLn10) * female_hwe_ln_p; |
| 5581 |
cswritep = dtoa_g(reported_val, cswritep); |
| 5582 |
} else { |
| 5583 |
cswritep = lntoa_g(MAXV(female_hwe_ln_p, output_min_ln), cswritep); |
| 5584 |
} |
| 5585 |
} |
| 5586 |
if (p_col) { |
| 5587 |
*cswritep++ = '\t'; |
| 5588 |
// bugfix (27 Jun 2020): forgot to correct this for multiallelic |
| 5589 |
// variants |
| 5590 |
const double ln_pval = hwe_x_ln_pvals[variant_idx + xgeno_idx]; |
| 5591 |
if (report_neglog10p) { |
| 5592 |
const double reported_val = (-kRecipLn10) * ln_pval; |
| 5593 |
cswritep = dtoa_g(reported_val, cswritep); |
| 5594 |
} else { |
| 5595 |
cswritep = lntoa_g(MAXV(ln_pval, output_min_ln), cswritep); |
| 5596 |
} |
| 5597 |
} |
| 5598 |
AppendBinaryEoln(&cswritep); |
| 5599 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 5600 |
goto HardyReport_ret_WRITE_FAIL; |
| 5601 |
} |
| 5602 |
} |
| 5603 |
} |
| 5604 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 5605 |
goto HardyReport_ret_WRITE_FAIL; |
| 5606 |
} |
| 5607 |
putc_unlocked('\r', stdout); |
| 5608 |
logprintfww("--hardy%s%s: chrX Hardy-Weinberg report (%s) written to %s .\n", output_zst? " zs" : "", midp? " midp" : "", nonfounders? "all samples" : "founders only", outname); |
| 5609 |
} |
| 5610 |
} |
| 5611 |
while (0) { |
| 5612 |
HardyReport_ret_NOMEM: |
| 5613 |
reterr = kPglRetNomem; |
| 5614 |
break; |
| 5615 |
HardyReport_ret_WRITE_FAIL: |
| 5616 |
reterr = kPglRetWriteFail; |
| 5617 |
break; |
| 5618 |
} |
| 5619 |
HardyReport_ret_1: |
| 5620 |
CswriteCloseCond(&css, cswritep); |
| 5621 |
BigstackReset(bigstack_mark); |
| 5622 |
return reterr; |
| 5623 |
} |
| 5624 |
|
| 5625 |
ENUM_U31_DEF_START() |
| 5626 |
kSubstCodeNonsnpsymb, |
| 5627 |
kSubstCodeSymbolic, |
| 5628 |
kSubstCodeTs, |
| 5629 |
kSubstCodeTv, |
| 5630 |
kSubstCodeWeirdSnp, |
| 5631 |
|
| 5632 |
kSubstCodeCt |
| 5633 |
ENUM_U31_DEF_END(SubstCode); |
| 5634 |
|
| 5635 |
SubstCode GetSubstCode(const char* ref, const char* alt) { |
| 5636 |
if (ref[1] || alt[1]) { |
| 5637 |
return (alt[0] == '<')? kSubstCodeSymbolic : kSubstCodeNonsnpsymb; |
| 5638 |
} |
| 5639 |
const unsigned char ref_upcase = ref[0] & 0xdf; |
| 5640 |
const unsigned char alt_upcase = alt[0] & 0xdf; |
| 5641 |
const unsigned char uchar_xor = ref_upcase ^ alt_upcase; |
| 5642 |
if ((ref_upcase == 'A') || (ref_upcase == 'G')) { |
| 5643 |
// 1 ^ 7 = 6 |
| 5644 |
if (uchar_xor == 6) { |
| 5645 |
return kSubstCodeTs; |
| 5646 |
} |
| 5647 |
// bcftools sample-stats treats all SNP non-transitions are |
| 5648 |
// transversions. Don't replicate that. |
| 5649 |
if ((alt_upcase == 'C') || (alt_upcase == 'T')) { |
| 5650 |
return kSubstCodeTv; |
| 5651 |
} |
| 5652 |
} else if ((ref_upcase == 'C') || (ref_upcase == 'T')) { |
| 5653 |
// 3 ^ 20 = 23 |
| 5654 |
if (uchar_xor == 23) { |
| 5655 |
return kSubstCodeTs; |
| 5656 |
} |
| 5657 |
if ((alt_upcase == 'A') || (alt_upcase == 'G')) { |
| 5658 |
return kSubstCodeTv; |
| 5659 |
} |
| 5660 |
} |
| 5661 |
return kSubstCodeWeirdSnp; |
| 5662 |
} |
| 5663 |
|
| 5664 |
// Assumes trailing bits have been zeroed or filled. |
| 5665 |
// Returns UINT32_MAX if no singleton. |
| 5666 |
uint32_t GetSingletonIdx(const uintptr_t* genovec, uint32_t sample_ct) { |
| 5667 |
const uint32_t word_ct = NypCtToWordCt(sample_ct); |
| 5668 |
uint32_t singleton_idx = UINT32_MAX; |
| 5669 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5670 |
uintptr_t geno_word = genovec[widx]; |
| 5671 |
if (!geno_word) { |
| 5672 |
continue; |
| 5673 |
} |
| 5674 |
geno_word = (geno_word ^ (geno_word >> 1)) & kMask5555; |
| 5675 |
if (!geno_word) { |
| 5676 |
continue; |
| 5677 |
} |
| 5678 |
if ((singleton_idx != UINT32_MAX) || (geno_word & (geno_word - 1))) { |
| 5679 |
return UINT32_MAX; |
| 5680 |
} |
| 5681 |
singleton_idx = widx * kBitsPerWordD2 + (ctzw(geno_word) / 2); |
| 5682 |
} |
| 5683 |
return singleton_idx; |
| 5684 |
} |
| 5685 |
|
| 5686 |
// If the ALT allele in a chrX biallelic variant is observed in one female and |
| 5687 |
// one male, bcftools counts it as a singleton for the female. Default to |
| 5688 |
// replicating this weird behavior. |
| 5689 |
void UpdateSampleDiploidSingletonCountX(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* diploid_singleton_cts) { |
| 5690 |
const uint32_t word_ct = NypCtToWordCt(sample_ct); |
| 5691 |
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male); |
| 5692 |
uint32_t singleton_idx = UINT32_MAX; |
| 5693 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5694 |
uintptr_t geno_word = genovec[widx]; |
| 5695 |
if (!geno_word) { |
| 5696 |
continue; |
| 5697 |
} |
| 5698 |
geno_word = (geno_word ^ (geno_word >> 1)) & kMask5555; |
| 5699 |
if (!geno_word) { |
| 5700 |
continue; |
| 5701 |
} |
| 5702 |
geno_word = geno_word & (~UnpackHalfwordToWord(sex_male_alias[widx])); |
| 5703 |
if (!geno_word) { |
| 5704 |
continue; |
| 5705 |
} |
| 5706 |
if ((singleton_idx != UINT32_MAX) || (geno_word & (geno_word - 1))) { |
| 5707 |
return; |
| 5708 |
} |
| 5709 |
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno_word) / 2; |
| 5710 |
} |
| 5711 |
if (singleton_idx != UINT32_MAX) { |
| 5712 |
diploid_singleton_cts[singleton_idx] += 1; |
| 5713 |
} |
| 5714 |
} |
| 5715 |
|
| 5716 |
void UpdateSampleSingletonCountX(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* singleton_cts) { |
| 5717 |
const uint32_t word_ct = NypCtToWordCt(sample_ct); |
| 5718 |
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male); |
| 5719 |
uint32_t singleton_idx = UINT32_MAX; |
| 5720 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5721 |
const uintptr_t geno_word = genovec[widx]; |
| 5722 |
if (!geno_word) { |
| 5723 |
continue; |
| 5724 |
} |
| 5725 |
const uintptr_t geno2_word = (~geno_word) & (geno_word >> 1) & kMask5555; |
| 5726 |
if (geno2_word) { |
| 5727 |
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) { |
| 5728 |
return; |
| 5729 |
} |
| 5730 |
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno2_word) / 2; |
| 5731 |
} |
| 5732 |
uintptr_t geno1_word = geno_word & (~(geno_word >> 1)) & kMask5555; |
| 5733 |
if (geno1_word) { |
| 5734 |
geno1_word = geno1_word & (~UnpackHalfwordToWord(sex_male_alias[widx])); |
| 5735 |
if (geno1_word) { |
| 5736 |
if ((singleton_idx != UINT32_MAX) || (geno1_word & (geno1_word - 1))) { |
| 5737 |
return; |
| 5738 |
} |
| 5739 |
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno1_word) / 2; |
| 5740 |
} |
| 5741 |
} |
| 5742 |
} |
| 5743 |
if (singleton_idx != UINT32_MAX) { |
| 5744 |
singleton_cts[singleton_idx] += 1; |
| 5745 |
} |
| 5746 |
} |
| 5747 |
|
| 5748 |
void UpdateSampleSingletonCountY(const uintptr_t* sex_male, const uintptr_t* genovec, uint32_t sample_ct, uint32_t* singleton_cts) { |
| 5749 |
const uint32_t word_ct = NypCtToWordCt(sample_ct); |
| 5750 |
const Halfword* sex_male_alias = R_CAST(const Halfword*, sex_male); |
| 5751 |
uint32_t singleton_idx = UINT32_MAX; |
| 5752 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5753 |
const uintptr_t geno_word = genovec[widx]; |
| 5754 |
if (!geno_word) { |
| 5755 |
continue; |
| 5756 |
} |
| 5757 |
uintptr_t geno2_word = (~geno_word) & (geno_word >> 1) & kMask5555; |
| 5758 |
if (geno2_word) { |
| 5759 |
geno2_word = geno2_word & UnpackHalfwordToWord(sex_male_alias[widx]); |
| 5760 |
if (geno2_word) { |
| 5761 |
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) { |
| 5762 |
return; |
| 5763 |
} |
| 5764 |
singleton_idx = widx * kBitsPerWordD2 + ctzw(geno2_word) / 2; |
| 5765 |
} |
| 5766 |
} |
| 5767 |
} |
| 5768 |
if (singleton_idx != UINT32_MAX) { |
| 5769 |
singleton_cts[singleton_idx] += 1; |
| 5770 |
} |
| 5771 |
} |
| 5772 |
|
| 5773 |
uint32_t GetSingletonIdxSparse(const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len) { |
| 5774 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 5775 |
uint32_t singleton_idx = UINT32_MAX; |
| 5776 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5777 |
uintptr_t raregeno_word = raregeno[widx]; |
| 5778 |
if (!raregeno_word) { |
| 5779 |
continue; |
| 5780 |
} |
| 5781 |
raregeno_word = (raregeno_word ^ (raregeno_word >> 1)) & kMask5555; |
| 5782 |
if (!raregeno_word) { |
| 5783 |
continue; |
| 5784 |
} |
| 5785 |
if ((singleton_idx != UINT32_MAX) || (raregeno_word & (raregeno_word - 1))) { |
| 5786 |
return UINT32_MAX; |
| 5787 |
} |
| 5788 |
singleton_idx = difflist_sample_ids[widx * kBitsPerWordD2 + (ctzw(raregeno_word) / 2)]; |
| 5789 |
} |
| 5790 |
return singleton_idx; |
| 5791 |
} |
| 5792 |
|
| 5793 |
void UpdateSampleDiploidSingletonCountSparseX(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* diploid_singleton_cts) { |
| 5794 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 5795 |
uint32_t singleton_idx = UINT32_MAX; |
| 5796 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5797 |
uintptr_t raregeno_word = raregeno[widx]; |
| 5798 |
if (!raregeno_word) { |
| 5799 |
continue; |
| 5800 |
} |
| 5801 |
raregeno_word = (raregeno_word ^ (raregeno_word >> 1)) & kMask5555; |
| 5802 |
if (!raregeno_word) { |
| 5803 |
continue; |
| 5804 |
} |
| 5805 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]); |
| 5806 |
do { |
| 5807 |
const uint32_t difflist_idx_lowbits = ctzw(raregeno_word) / 2; |
| 5808 |
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits]; |
| 5809 |
if (!IsSet(sex_male, sample_idx)) { |
| 5810 |
if (singleton_idx != UINT32_MAX) { |
| 5811 |
return; |
| 5812 |
} |
| 5813 |
singleton_idx = sample_idx; |
| 5814 |
} |
| 5815 |
raregeno_word = raregeno_word & (raregeno_word - 1); |
| 5816 |
} while (raregeno_word); |
| 5817 |
} |
| 5818 |
if (singleton_idx != UINT32_MAX) { |
| 5819 |
diploid_singleton_cts[singleton_idx] += 1; |
| 5820 |
} |
| 5821 |
} |
| 5822 |
|
| 5823 |
void UpdateSampleSingletonCountSparseX(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* singleton_cts) { |
| 5824 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 5825 |
uint32_t singleton_idx = UINT32_MAX; |
| 5826 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5827 |
const uintptr_t raregeno_word = raregeno[widx]; |
| 5828 |
if (!raregeno_word) { |
| 5829 |
continue; |
| 5830 |
} |
| 5831 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]); |
| 5832 |
const uintptr_t geno2_word = (~raregeno_word) & (raregeno_word >> 1) & kMask5555; |
| 5833 |
if (geno2_word) { |
| 5834 |
if ((singleton_idx != UINT32_MAX) || (geno2_word & (geno2_word - 1))) { |
| 5835 |
return; |
| 5836 |
} |
| 5837 |
singleton_idx = cur_difflist_sample_ids[ctzw(geno2_word) / 2]; |
| 5838 |
} |
| 5839 |
uintptr_t geno1_word = raregeno_word & (~(raregeno_word >> 1)) & kMask5555; |
| 5840 |
while (geno1_word) { |
| 5841 |
const uint32_t difflist_idx_lowbits = ctzw(geno1_word) / 2; |
| 5842 |
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits]; |
| 5843 |
if (!IsSet(sex_male, sample_idx)) { |
| 5844 |
if (singleton_idx != UINT32_MAX) { |
| 5845 |
return; |
| 5846 |
} |
| 5847 |
singleton_idx = sample_idx; |
| 5848 |
} |
| 5849 |
geno1_word = geno1_word & (geno1_word - 1); |
| 5850 |
} |
| 5851 |
} |
| 5852 |
if (singleton_idx != UINT32_MAX) { |
| 5853 |
singleton_cts[singleton_idx] += 1; |
| 5854 |
} |
| 5855 |
} |
| 5856 |
|
| 5857 |
void UpdateSampleSingletonCountSparseY(const uintptr_t* sex_male, const uintptr_t* raregeno, const uint32_t* difflist_sample_ids, uint32_t difflist_len, uint32_t* singleton_cts) { |
| 5858 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 5859 |
uint32_t singleton_idx = UINT32_MAX; |
| 5860 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 5861 |
uintptr_t raregeno_word = raregeno[widx]; |
| 5862 |
if (!raregeno_word) { |
| 5863 |
continue; |
| 5864 |
} |
| 5865 |
raregeno_word = (~raregeno_word) & (raregeno_word >> 1) & kMask5555; |
| 5866 |
if (!raregeno_word) { |
| 5867 |
continue; |
| 5868 |
} |
| 5869 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]); |
| 5870 |
do { |
| 5871 |
const uint32_t difflist_idx_lowbits = ctzw(raregeno_word) / 2; |
| 5872 |
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits]; |
| 5873 |
if (IsSet(sex_male, sample_idx)) { |
| 5874 |
if (singleton_idx != UINT32_MAX) { |
| 5875 |
return; |
| 5876 |
} |
| 5877 |
singleton_idx = sample_idx; |
| 5878 |
} |
| 5879 |
raregeno_word = raregeno_word & (raregeno_word - 1); |
| 5880 |
} while (raregeno_word); |
| 5881 |
} |
| 5882 |
if (singleton_idx != UINT32_MAX) { |
| 5883 |
singleton_cts[singleton_idx] += 1; |
| 5884 |
} |
| 5885 |
} |
| 5886 |
|
| 5887 |
void UpdateDenseSampleCounts3(const uintptr_t* genovec, uint32_t acc2_vec_ct, VecW* acc2_0, uint16_t* remainders) { |
| 5888 |
const VecW m1 = VCONST_W(kMask5555); |
| 5889 |
const VecW* genovvec = R_CAST(const VecW*, genovec); |
| 5890 |
VecW* acc2_2 = &(acc2_0[acc2_vec_ct * 23]); |
| 5891 |
VecW* acc2_1 = &(acc2_2[acc2_vec_ct * 23]); |
| 5892 |
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) { |
| 5893 |
// Tried iterating over word-indexes instead (since LEA instruction can |
| 5894 |
// only multiply by 1/2/4/8, not 16 or 32), but that doesn't help, it just |
| 5895 |
// makes the code messier. |
| 5896 |
const VecW vv = genovvec[vidx]; |
| 5897 |
const VecW vv_hi = vecw_srli(vv, 1); |
| 5898 |
const VecW vv_lo_0 = vecw_and_notfirst(vv, m1); |
| 5899 |
acc2_0[vidx] += vecw_and_notfirst(vv_hi, vv_lo_0); |
| 5900 |
acc2_2[vidx] += vv_lo_0 & vv_hi; |
| 5901 |
acc2_1[vidx] += vecw_and_notfirst(vv_hi, vv) & m1; |
| 5902 |
} |
| 5903 |
remainders[0] -= 1; |
| 5904 |
if (!remainders[0]) { |
| 5905 |
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]); |
| 5906 |
Vcount0Incr2To4(acc2_vec_ct, acc2_0, acc4_0); |
| 5907 |
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]); |
| 5908 |
Vcount0Incr2To4(acc2_vec_ct, acc2_2, acc4_2); |
| 5909 |
VecW* acc4_1 = &(acc2_1[acc2_vec_ct]); |
| 5910 |
Vcount0Incr2To4(acc2_vec_ct, acc2_1, acc4_1); |
| 5911 |
remainders[1] -= 1; |
| 5912 |
if (!remainders[1]) { |
| 5913 |
const uint32_t acc4_vec_ct = acc2_vec_ct * 2; |
| 5914 |
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]); |
| 5915 |
Vcount0Incr4To8(acc4_vec_ct, acc4_0, acc8_0); |
| 5916 |
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]); |
| 5917 |
Vcount0Incr4To8(acc4_vec_ct, acc4_2, acc8_2); |
| 5918 |
VecW* acc8_1 = &(acc4_1[acc4_vec_ct]); |
| 5919 |
Vcount0Incr4To8(acc4_vec_ct, acc4_1, acc8_1); |
| 5920 |
remainders[2] -= 1; |
| 5921 |
if (!remainders[2]) { |
| 5922 |
const uint32_t acc8_vec_ct = acc4_vec_ct * 2; |
| 5923 |
VecW* acc32_0 = &(acc8_0[acc8_vec_ct]); |
| 5924 |
Vcount0Incr8To32(acc8_vec_ct, acc8_0, acc32_0); |
| 5925 |
VecW* acc32_2 = &(acc8_2[acc8_vec_ct]); |
| 5926 |
Vcount0Incr8To32(acc8_vec_ct, acc8_2, acc32_2); |
| 5927 |
VecW* acc32_1 = &(acc8_1[acc8_vec_ct]); |
| 5928 |
Vcount0Incr8To32(acc8_vec_ct, acc8_1, acc32_1); |
| 5929 |
remainders[2] = 17; |
| 5930 |
} |
| 5931 |
remainders[1] = 5; |
| 5932 |
} |
| 5933 |
remainders[0] = 3; |
| 5934 |
} |
| 5935 |
} |
| 5936 |
|
| 5937 |
void UpdateDenseSampleCounts2(const uintptr_t* genovec, uint32_t acc2_vec_ct, VecW* acc2_0, uint16_t* remainders) { |
| 5938 |
const VecW m1 = VCONST_W(kMask5555); |
| 5939 |
const VecW* genovvec = R_CAST(const VecW*, genovec); |
| 5940 |
VecW* acc2_2 = &(acc2_0[acc2_vec_ct * 23]); |
| 5941 |
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) { |
| 5942 |
const VecW vv = genovvec[vidx]; |
| 5943 |
const VecW vv_hi = vecw_srli(vv, 1); |
| 5944 |
const VecW vv_lo_0 = vecw_and_notfirst(vv, m1); |
| 5945 |
acc2_0[vidx] += vecw_and_notfirst(vv_hi, vv_lo_0); |
| 5946 |
acc2_2[vidx] += vv_lo_0 & vv_hi; |
| 5947 |
} |
| 5948 |
remainders[0] -= 1; |
| 5949 |
if (!remainders[0]) { |
| 5950 |
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]); |
| 5951 |
Vcount0Incr2To4(acc2_vec_ct, acc2_0, acc4_0); |
| 5952 |
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]); |
| 5953 |
Vcount0Incr2To4(acc2_vec_ct, acc2_2, acc4_2); |
| 5954 |
remainders[1] -= 1; |
| 5955 |
if (!remainders[1]) { |
| 5956 |
const uint32_t acc4_vec_ct = acc2_vec_ct * 2; |
| 5957 |
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]); |
| 5958 |
Vcount0Incr4To8(acc4_vec_ct, acc4_0, acc8_0); |
| 5959 |
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]); |
| 5960 |
Vcount0Incr4To8(acc4_vec_ct, acc4_2, acc8_2); |
| 5961 |
remainders[2] -= 1; |
| 5962 |
if (!remainders[2]) { |
| 5963 |
const uint32_t acc8_vec_ct = acc4_vec_ct * 2; |
| 5964 |
VecW* acc32_0 = &(acc8_0[acc8_vec_ct]); |
| 5965 |
Vcount0Incr8To32(acc8_vec_ct, acc8_0, acc32_0); |
| 5966 |
VecW* acc32_2 = &(acc8_2[acc8_vec_ct]); |
| 5967 |
Vcount0Incr8To32(acc8_vec_ct, acc8_2, acc32_2); |
| 5968 |
remainders[2] = 17; |
| 5969 |
} |
| 5970 |
remainders[1] = 5; |
| 5971 |
} |
| 5972 |
remainders[0] = 3; |
| 5973 |
} |
| 5974 |
} |
| 5975 |
|
| 5976 |
// This shares a lot with LoadSampleMissingCts() in plink2_filter. Might want |
| 5977 |
// to merge this into a single driver function at some point, similar to how |
| 5978 |
// LoadAlleleAndGenoCounts() reduces duplication of variant-stat calculation. |
| 5979 |
typedef struct SampleCountsCtxStruct { |
| 5980 |
const uintptr_t* variant_include; |
| 5981 |
const ChrInfo* cip; |
| 5982 |
const uintptr_t* allele_idx_offsets; |
| 5983 |
const char* const* allele_storage; |
| 5984 |
const uintptr_t* sample_include; |
| 5985 |
uint32_t* sample_include_cumulative_popcounts; |
| 5986 |
uintptr_t* sex_male_collapsed; |
| 5987 |
uint32_t sample_ct; |
| 5988 |
uint32_t male_ct; |
| 5989 |
uint32_t y_nonmale_needed; |
| 5990 |
|
| 5991 |
PgenReader** pgr_ptrs; |
| 5992 |
uintptr_t** genovecs; |
| 5993 |
uintptr_t** thread_read_mhc; |
| 5994 |
uintptr_t** raregenos; |
| 5995 |
uint32_t** difflist_sample_id_bufs; |
| 5996 |
uint32_t* read_variant_uidx_starts; |
| 5997 |
uint32_t cur_block_size; |
| 5998 |
|
| 5999 |
uint64_t err_info; |
| 6000 |
|
| 6001 |
// top-level: length calc_thread_ct array |
| 6002 |
// second level: length-20 arrays, corresponding to the 20 chr_type x |
| 6003 |
// subst_code possibilities |
| 6004 |
// bottom level: acc2 partial counts, then acc4, then acc8, then acc32 for |
| 6005 |
// genotype=0. Then the same for genotype=2, and finally (in |
| 6006 |
// autosomal-diploid/chrX cases) genotype=1. |
| 6007 |
VecW*** thread_dense_counts; |
| 6008 |
|
| 6009 |
// top-level: length calc_thread_ct array |
| 6010 |
// second level: length-40 arrays, corresponding to chr_type x common_geno x |
| 6011 |
// subst_code possibilities |
| 6012 |
// bottom level: three vector-aligned length-sample_ct arrays, corresponding |
| 6013 |
// to the three ((common_geno ^ rare_geno) - 1) possibilities. |
| 6014 |
uint32_t*** thread_sparse_counts; |
| 6015 |
uint32_t** thread_sparse_common0_cts; |
| 6016 |
|
| 6017 |
uint32_t** thread_diploid_singleton_cts; |
| 6018 |
uint32_t** thread_singleton_cts; |
| 6019 |
|
| 6020 |
uint16_t** thread_alt_subst_codes; |
| 6021 |
// Multiallelic complications: geno=2 entries can correspond to het |
| 6022 |
// altx/alty, and subst_code can vary between alt alleles. We track the |
| 6023 |
// necessary adjustments with the het_rarealt_cts, het2alt_cts, |
| 6024 |
// hom_rarealt_cts, and hap_rarealt_cts arrays below. |
| 6025 |
// - het2alt_cts has 10 vector-aligned length-sample_ct arrays. The first |
| 6026 |
// five correspond to ALT1 subst_codes, and the last five correspond to the |
| 6027 |
// actually-observed-ALT subst_codes. The sum of the last five arrays is |
| 6028 |
// always twice that of the first five arrays, since each allele is counted |
| 6029 |
// separately. |
| 6030 |
// - het_rarealt_cts, hom_rarealt_cts and hap_rarealt_cts have 5 |
| 6031 |
// vector-aligned lenght-sample_ct arrays, corresponding to subst_code |
| 6032 |
// frequency deltas. |
| 6033 |
uint32_t** thread_het2alt_cts; |
| 6034 |
int32_t** thread_het_rarealt_cts; |
| 6035 |
int32_t** thread_hom_rarealt_cts; |
| 6036 |
int32_t** thread_hap_rarealt_cts; |
| 6037 |
} SampleCountsCtx; |
| 6038 |
|
| 6039 |
THREAD_FUNC_DECL SampleCountsThread(void* raw_arg) { |
| 6040 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 6041 |
const uintptr_t tidx = arg->tidx; |
| 6042 |
SampleCountsCtx* ctx = S_CAST(SampleCountsCtx*, arg->sharedp->context); |
| 6043 |
|
| 6044 |
const uintptr_t* variant_include = ctx->variant_include; |
| 6045 |
const ChrInfo* cip = ctx->cip; |
| 6046 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 6047 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 6048 |
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets; |
| 6049 |
const char* const* allele_storage = ctx->allele_storage; |
| 6050 |
const uintptr_t* sample_include = ctx->sample_include; |
| 6051 |
PgenReader* pgrp = ctx->pgr_ptrs[tidx]; |
| 6052 |
PgrSampleSubsetIndex pssi; |
| 6053 |
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi); |
| 6054 |
const uintptr_t* sex_male_collapsed = ctx->sex_male_collapsed; |
| 6055 |
const uintptr_t sample_ct = ctx->sample_ct; |
| 6056 |
const uint32_t male_ct = ctx->male_ct; |
| 6057 |
const uint32_t skip_y = (!male_ct) && (!ctx->y_nonmale_needed); |
| 6058 |
uintptr_t* genovec = ctx->genovecs[tidx]; |
| 6059 |
PgenVariant pgv; |
| 6060 |
pgv.genovec = genovec; |
| 6061 |
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv); |
| 6062 |
uintptr_t* raregeno = ctx->raregenos[tidx]; |
| 6063 |
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx]; |
| 6064 |
|
| 6065 |
// todo: tune this threshold |
| 6066 |
const uint32_t max_simple_difflist_len = sample_ct / 32; |
| 6067 |
|
| 6068 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 6069 |
const uint32_t acc2_vec_ct = NypCtToVecCt(sample_ct); |
| 6070 |
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23; |
| 6071 |
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp); |
| 6072 |
VecW** dense_counts = ctx->thread_dense_counts[tidx]; |
| 6073 |
// 4 chr_types, 3 remainders per variant_type |
| 6074 |
// uint16_t instead of uint8_t to avoid aliasing paranoia |
| 6075 |
uint16_t dense_remainders[12 * kSubstCodeCt]; |
| 6076 |
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) { |
| 6077 |
if (dense_counts[dense_vtype]) { |
| 6078 |
ZeroVecArr(dense_counts_vstride * (2 + (dense_vtype < 2 * kSubstCodeCt)), dense_counts[dense_vtype]); |
| 6079 |
dense_remainders[3 * dense_vtype] = 3; |
| 6080 |
dense_remainders[3 * dense_vtype + 1] = 5; |
| 6081 |
dense_remainders[3 * dense_vtype + 2] = 17; |
| 6082 |
} |
| 6083 |
} |
| 6084 |
|
| 6085 |
const uintptr_t sample_ct_i32av = RoundUpPow2(sample_ct, kInt32PerVec); |
| 6086 |
uint32_t** sparse_counts = ctx->thread_sparse_counts[tidx]; |
| 6087 |
// 4 chr_types * 2 common_geno |
| 6088 |
for (uint32_t uii = 0; uii != 8 * kSubstCodeCt; ++uii) { |
| 6089 |
if (sparse_counts[uii]) { |
| 6090 |
ZeroU32Arr(3 * sample_ct_i32av, sparse_counts[uii]); |
| 6091 |
} |
| 6092 |
} |
| 6093 |
uint32_t* sparse_common0_cts = ctx->thread_sparse_common0_cts[tidx]; |
| 6094 |
ZeroU32Arr(4 * kSubstCodeCt, sparse_common0_cts); |
| 6095 |
|
| 6096 |
uint32_t* diploid_singleton_cts = nullptr; |
| 6097 |
if (ctx->thread_diploid_singleton_cts) { |
| 6098 |
diploid_singleton_cts = ctx->thread_diploid_singleton_cts[tidx]; |
| 6099 |
ZeroU32Arr(sample_ct_i32av, diploid_singleton_cts); |
| 6100 |
} |
| 6101 |
uint32_t* singleton_cts = nullptr; |
| 6102 |
if (ctx->thread_singleton_cts) { |
| 6103 |
singleton_cts = ctx->thread_singleton_cts[tidx]; |
| 6104 |
ZeroU32Arr(sample_ct_i32av, singleton_cts); |
| 6105 |
} |
| 6106 |
|
| 6107 |
uint16_t* alt_subst_codes = nullptr; |
| 6108 |
uint32_t* het2alt_minus_cts = nullptr; |
| 6109 |
uint32_t* het2alt_plus_cts = nullptr; |
| 6110 |
int32_t* het_rarealt_cts = nullptr; |
| 6111 |
int32_t* hom_rarealt_cts = nullptr; |
| 6112 |
int32_t* hap_rarealt_cts = nullptr; |
| 6113 |
if (ctx->thread_alt_subst_codes) { |
| 6114 |
alt_subst_codes = ctx->thread_alt_subst_codes[tidx]; |
| 6115 |
|
| 6116 |
het2alt_minus_cts = ctx->thread_het2alt_cts[tidx]; |
| 6117 |
ZeroU32Arr(2 * kSubstCodeCt * sample_ct_i32av, het2alt_minus_cts); |
| 6118 |
het2alt_plus_cts = &(het2alt_minus_cts[kSubstCodeCt * sample_ct_i32av]); |
| 6119 |
het_rarealt_cts = ctx->thread_het_rarealt_cts[tidx]; |
| 6120 |
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, het_rarealt_cts); |
| 6121 |
hom_rarealt_cts = ctx->thread_hom_rarealt_cts[tidx]; |
| 6122 |
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, hom_rarealt_cts); |
| 6123 |
if (ctx->thread_hap_rarealt_cts) { |
| 6124 |
hap_rarealt_cts = ctx->thread_hap_rarealt_cts[tidx]; |
| 6125 |
ZeroI32Arr(kSubstCodeCt * sample_ct_i32av, hap_rarealt_cts); |
| 6126 |
} |
| 6127 |
} |
| 6128 |
|
| 6129 |
uint32_t cur_allele_ct = 2; |
| 6130 |
uint64_t new_err_info = 0; |
| 6131 |
do { |
| 6132 |
const uint32_t cur_block_size = ctx->cur_block_size; |
| 6133 |
const uint32_t cur_idx_ct = (((tidx + 1) * cur_block_size) / calc_thread_ct) - ((tidx * cur_block_size) / calc_thread_ct); |
| 6134 |
uintptr_t variant_uidx_base; |
| 6135 |
uintptr_t cur_bits; |
| 6136 |
BitIter1Start(variant_include, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits); |
| 6137 |
uint32_t chr_end = 0; |
| 6138 |
uint32_t chr_type = 0; |
| 6139 |
uint32_t is_haploid = 0; |
| 6140 |
uint32_t is_diploid_x = 0; |
| 6141 |
uint32_t is_y = 0; |
| 6142 |
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) { |
| 6143 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 6144 |
if (variant_uidx >= chr_end) { |
| 6145 |
const uint32_t chr_fo_idx = GetVariantChrFoIdx(cip, variant_uidx); |
| 6146 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 6147 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 6148 |
is_haploid = IsSet(cip->haploid_mask, chr_idx); |
| 6149 |
is_diploid_x = 0; |
| 6150 |
is_y = (chr_idx == y_code); |
| 6151 |
if (chr_idx == x_code) { |
| 6152 |
is_diploid_x = !IsSet(cip->haploid_mask, 0); |
| 6153 |
} |
| 6154 |
chr_type = 0; |
| 6155 |
if (is_haploid) { |
| 6156 |
if (is_diploid_x) { |
| 6157 |
if (!male_ct) { |
| 6158 |
// all-unknown-sex override |
| 6159 |
is_haploid = 0; |
| 6160 |
is_diploid_x = 0; |
| 6161 |
} else { |
| 6162 |
chr_type = 1; |
| 6163 |
} |
| 6164 |
} else if (is_y) { |
| 6165 |
chr_type = 2; |
| 6166 |
} else { |
| 6167 |
chr_type = 3; |
| 6168 |
} |
| 6169 |
} |
| 6170 |
} |
| 6171 |
if (is_y && skip_y) { |
| 6172 |
continue; |
| 6173 |
} |
| 6174 |
uintptr_t allele_idx_offset_base; |
| 6175 |
if (!allele_idx_offsets) { |
| 6176 |
allele_idx_offset_base = variant_uidx * 2; |
| 6177 |
} else { |
| 6178 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 6179 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 6180 |
} |
| 6181 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 6182 |
if (cur_allele_ct == 2) { |
| 6183 |
// Finally, a scenario where exposing this capability really pays off. |
| 6184 |
uint32_t difflist_common_geno; |
| 6185 |
uint32_t difflist_len; |
| 6186 |
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len); |
| 6187 |
if (unlikely(reterr)) { |
| 6188 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 6189 |
goto SampleCountsThread_err; |
| 6190 |
} |
| 6191 |
if (difflist_common_geno == 2) { |
| 6192 |
// Don't bother with sparse optimization here, should be rare and it |
| 6193 |
// complicates singleton-counting code |
| 6194 |
PgrDifflistToGenovecUnsafe(raregeno, difflist_sample_ids, difflist_common_geno, sample_ct, difflist_len, genovec); |
| 6195 |
difflist_common_geno = UINT32_MAX; |
| 6196 |
} |
| 6197 |
uint32_t subst_code = GetSubstCode(cur_alleles[0], cur_alleles[1]); |
| 6198 |
const uint32_t dense_vtype = chr_type * kSubstCodeCt + subst_code; |
| 6199 |
if (difflist_common_geno == UINT32_MAX) { |
| 6200 |
if (chr_type < 2) { |
| 6201 |
UpdateDenseSampleCounts3(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3])); |
| 6202 |
} else { |
| 6203 |
UpdateDenseSampleCounts2(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3])); |
| 6204 |
} |
| 6205 |
if (diploid_singleton_cts || singleton_cts) { |
| 6206 |
ZeroTrailingNyps(sample_ct, genovec); |
| 6207 |
if (is_haploid) { |
| 6208 |
if (is_diploid_x) { |
| 6209 |
if (diploid_singleton_cts) { |
| 6210 |
UpdateSampleDiploidSingletonCountX(sex_male_collapsed, genovec, sample_ct, diploid_singleton_cts); |
| 6211 |
} |
| 6212 |
if (singleton_cts) { |
| 6213 |
UpdateSampleSingletonCountX(sex_male_collapsed, genovec, sample_ct, singleton_cts); |
| 6214 |
} |
| 6215 |
continue; |
| 6216 |
} |
| 6217 |
if (!singleton_cts) { |
| 6218 |
continue; |
| 6219 |
} |
| 6220 |
if (is_y) { |
| 6221 |
UpdateSampleSingletonCountY(sex_male_collapsed, genovec, sample_ct, singleton_cts); |
| 6222 |
continue; |
| 6223 |
} |
| 6224 |
SetHetMissing(sample_ctl2, genovec); |
| 6225 |
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct); |
| 6226 |
if (singleton_idx != UINT32_MAX) { |
| 6227 |
singleton_cts[singleton_idx] += 1; |
| 6228 |
} |
| 6229 |
continue; |
| 6230 |
} |
| 6231 |
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct); |
| 6232 |
if (singleton_idx != UINT32_MAX) { |
| 6233 |
if (diploid_singleton_cts) { |
| 6234 |
diploid_singleton_cts[singleton_idx] += 1; |
| 6235 |
} |
| 6236 |
if (singleton_cts) { |
| 6237 |
singleton_cts[singleton_idx] += 1; |
| 6238 |
} |
| 6239 |
} |
| 6240 |
} |
| 6241 |
continue; |
| 6242 |
} |
| 6243 |
uint32_t vtrans_type = dense_vtype + chr_type * kSubstCodeCt; |
| 6244 |
if (!difflist_common_geno) { |
| 6245 |
sparse_common0_cts[dense_vtype] += 1; |
| 6246 |
} else { |
| 6247 |
vtrans_type += kSubstCodeCt; |
| 6248 |
} |
| 6249 |
if (!difflist_len) { |
| 6250 |
continue; |
| 6251 |
} |
| 6252 |
uint32_t* cur_sparse_cts = sparse_counts[vtrans_type]; |
| 6253 |
const uint32_t word_ct_m1 = (difflist_len - 1) / kBitsPerWordD2; |
| 6254 |
// difflist_common_geno_word == 0 if difflist_common_geno == 0, |
| 6255 |
// ~k0LU if difflist_common_geno == 3. |
| 6256 |
const uintptr_t difflist_common_geno_word = -S_CAST(uintptr_t, difflist_common_geno & 1); |
| 6257 |
uint32_t loop_len = kBitsPerWordD2; |
| 6258 |
for (uint32_t widx = 0; ; ++widx) { |
| 6259 |
if (widx >= word_ct_m1) { |
| 6260 |
if (widx > word_ct_m1) { |
| 6261 |
break; |
| 6262 |
} |
| 6263 |
loop_len = ModNz(difflist_len, kBitsPerWordD2); |
| 6264 |
} |
| 6265 |
uintptr_t raregeno_xor_word = raregeno[widx] ^ difflist_common_geno_word; |
| 6266 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]); |
| 6267 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 6268 |
const uintptr_t sample_idx = cur_difflist_sample_ids[uii]; |
| 6269 |
const uint32_t cur_geno_xor = raregeno_xor_word & 3; |
| 6270 |
cur_sparse_cts[(cur_geno_xor - 1) * sample_ct_i32av + sample_idx] += 1; |
| 6271 |
raregeno_xor_word = raregeno_xor_word >> 2; |
| 6272 |
} |
| 6273 |
} |
| 6274 |
if (diploid_singleton_cts || singleton_cts) { |
| 6275 |
ZeroTrailingNyps(difflist_len, raregeno); |
| 6276 |
if (is_haploid) { |
| 6277 |
if (is_diploid_x) { |
| 6278 |
if (diploid_singleton_cts) { |
| 6279 |
UpdateSampleDiploidSingletonCountSparseX(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, diploid_singleton_cts); |
| 6280 |
} |
| 6281 |
if (singleton_cts) { |
| 6282 |
UpdateSampleSingletonCountSparseX(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, singleton_cts); |
| 6283 |
} |
| 6284 |
continue; |
| 6285 |
} |
| 6286 |
if (!singleton_cts) { |
| 6287 |
continue; |
| 6288 |
} |
| 6289 |
if (is_y) { |
| 6290 |
UpdateSampleSingletonCountSparseY(sex_male_collapsed, raregeno, difflist_sample_ids, difflist_len, singleton_cts); |
| 6291 |
continue; |
| 6292 |
} |
| 6293 |
const uint32_t difflist_word_ct = NypCtToWordCt(difflist_len); |
| 6294 |
SetHetMissing(difflist_word_ct, raregeno); |
| 6295 |
const uint32_t singleton_idx = GetSingletonIdxSparse(raregeno, difflist_sample_ids, difflist_len); |
| 6296 |
if (singleton_idx != UINT32_MAX) { |
| 6297 |
singleton_cts[singleton_idx] += 1; |
| 6298 |
} |
| 6299 |
continue; |
| 6300 |
} |
| 6301 |
const uint32_t singleton_idx = GetSingletonIdxSparse(raregeno, difflist_sample_ids, difflist_len); |
| 6302 |
if (singleton_idx != UINT32_MAX) { |
| 6303 |
if (diploid_singleton_cts) { |
| 6304 |
diploid_singleton_cts[singleton_idx] += 1; |
| 6305 |
} |
| 6306 |
if (singleton_cts) { |
| 6307 |
singleton_cts[singleton_idx] += 1; |
| 6308 |
} |
| 6309 |
} |
| 6310 |
} |
| 6311 |
continue; |
| 6312 |
} |
| 6313 |
// Multiallelic case. |
| 6314 |
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv); |
| 6315 |
if (unlikely(reterr)) { |
| 6316 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 6317 |
goto SampleCountsThread_err; |
| 6318 |
} |
| 6319 |
const uint32_t subst_code1 = GetSubstCode(cur_alleles[0], cur_alleles[1]); |
| 6320 |
alt_subst_codes[1] = subst_code1; |
| 6321 |
uint32_t subst_codes_vary = 0; |
| 6322 |
for (uint32_t allele_idx = 2; allele_idx != cur_allele_ct; ++allele_idx) { |
| 6323 |
const uint32_t cur_subst_code = GetSubstCode(cur_alleles[0], cur_alleles[allele_idx]); |
| 6324 |
alt_subst_codes[allele_idx] = cur_subst_code; |
| 6325 |
subst_codes_vary |= (cur_subst_code != subst_code1); |
| 6326 |
} |
| 6327 |
const uint32_t dense_vtype = chr_type * kSubstCodeCt + subst_code1; |
| 6328 |
if (chr_type < 2) { |
| 6329 |
UpdateDenseSampleCounts3(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3])); |
| 6330 |
} else { |
| 6331 |
UpdateDenseSampleCounts2(genovec, acc2_vec_ct, dense_counts[dense_vtype], &(dense_remainders[dense_vtype * 3])); |
| 6332 |
} |
| 6333 |
const uint32_t patch_10_ct = pgv.patch_10_ct; |
| 6334 |
const uint32_t subst_code1_offset = subst_code1 * sample_ct_i32av; |
| 6335 |
if (!subst_codes_vary) { |
| 6336 |
if (patch_10_ct) { |
| 6337 |
const uintptr_t* patch_10_set = pgv.patch_10_set; |
| 6338 |
const AlleleCode* patch_10_vals = pgv.patch_10_vals; |
| 6339 |
uintptr_t sample_idx_base = 0; |
| 6340 |
uintptr_t sample_idx_bits = patch_10_set[0]; |
| 6341 |
if (!chr_type) { |
| 6342 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6343 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6344 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6345 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6346 |
if (a0 != a1) { |
| 6347 |
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1; |
| 6348 |
het2alt_plus_cts[subst_code1_offset + sample_idx] += 2; |
| 6349 |
} |
| 6350 |
} |
| 6351 |
} else if (chr_type == 1) { |
| 6352 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6353 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6354 |
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx); |
| 6355 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6356 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6357 |
if (a0 != a1) { |
| 6358 |
if (!is_male) { |
| 6359 |
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1; |
| 6360 |
het2alt_plus_cts[subst_code1_offset + sample_idx] += 2; |
| 6361 |
} else { |
| 6362 |
// het-haploid, treat as missing |
| 6363 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6364 |
} |
| 6365 |
} |
| 6366 |
} |
| 6367 |
} else { |
| 6368 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6369 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6370 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6371 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6372 |
if (a0 != a1) { |
| 6373 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6374 |
} |
| 6375 |
} |
| 6376 |
} |
| 6377 |
} |
| 6378 |
} else { // subst_codes_vary |
| 6379 |
if (chr_type < 2) { |
| 6380 |
const uint32_t patch_01_ct = pgv.patch_01_ct; |
| 6381 |
if (patch_01_ct) { |
| 6382 |
const uintptr_t* patch_01_set = pgv.patch_01_set; |
| 6383 |
const AlleleCode* patch_01_vals = pgv.patch_01_vals; |
| 6384 |
uintptr_t sample_idx_base = 0; |
| 6385 |
uintptr_t sample_idx_bits = patch_01_set[0]; |
| 6386 |
if (!chr_type) { |
| 6387 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 6388 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits); |
| 6389 |
const uint32_t cur_subst_code = alt_subst_codes[patch_01_vals[uii]]; |
| 6390 |
if (subst_code1 != cur_subst_code) { |
| 6391 |
het_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6392 |
het_rarealt_cts[cur_subst_code * sample_ct_i32av + sample_idx] += 1; |
| 6393 |
} |
| 6394 |
} |
| 6395 |
} else { |
| 6396 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 6397 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits); |
| 6398 |
// bugfix (9 Jan 2023): in male case, we will adjust hethap |
| 6399 |
// to missing later under the assumption that this genotype |
| 6400 |
// is ref/alt1. So, subst_code doesn't matter. |
| 6401 |
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx); |
| 6402 |
if (!is_male) { |
| 6403 |
const uint32_t cur_subst_code = alt_subst_codes[patch_01_vals[uii]]; |
| 6404 |
if (subst_code1 != cur_subst_code) { |
| 6405 |
het_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6406 |
het_rarealt_cts[cur_subst_code * sample_ct_i32av + sample_idx] += 1; |
| 6407 |
} |
| 6408 |
} |
| 6409 |
} |
| 6410 |
} |
| 6411 |
} |
| 6412 |
} |
| 6413 |
if (patch_10_ct) { |
| 6414 |
const uintptr_t* patch_10_set = pgv.patch_10_set; |
| 6415 |
const AlleleCode* patch_10_vals = pgv.patch_10_vals; |
| 6416 |
uintptr_t sample_idx_base = 0; |
| 6417 |
uintptr_t sample_idx_bits = patch_10_set[0]; |
| 6418 |
if (!chr_type) { |
| 6419 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6420 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6421 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6422 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6423 |
const uint32_t new_code0 = alt_subst_codes[a0]; |
| 6424 |
if (a0 != a1) { |
| 6425 |
const uint32_t new_code1 = alt_subst_codes[a1]; |
| 6426 |
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1; |
| 6427 |
het2alt_plus_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6428 |
het2alt_plus_cts[new_code1 * sample_ct_i32av + sample_idx] += 1; |
| 6429 |
} else if (new_code0 != subst_code1) { |
| 6430 |
hom_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6431 |
hom_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6432 |
} |
| 6433 |
} |
| 6434 |
} else if (chr_type == 1) { |
| 6435 |
// ugh |
| 6436 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6437 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6438 |
const uint32_t is_male = IsSet(sex_male_collapsed, sample_idx); |
| 6439 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6440 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6441 |
const uint32_t new_code0 = alt_subst_codes[a0]; |
| 6442 |
if (a0 != a1) { |
| 6443 |
if (!is_male) { |
| 6444 |
const uint32_t new_code1 = alt_subst_codes[a1]; |
| 6445 |
het2alt_minus_cts[subst_code1_offset + sample_idx] += 1; |
| 6446 |
het2alt_plus_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6447 |
het2alt_plus_cts[new_code1 * sample_ct_i32av + sample_idx] += 1; |
| 6448 |
} else { |
| 6449 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6450 |
} |
| 6451 |
} else if (new_code0 != subst_code1) { |
| 6452 |
if (!is_male) { |
| 6453 |
hom_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6454 |
hom_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6455 |
} else { |
| 6456 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6457 |
hap_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6458 |
} |
| 6459 |
} |
| 6460 |
} |
| 6461 |
} else { |
| 6462 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 6463 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 6464 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 6465 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 6466 |
const uint32_t new_code0 = alt_subst_codes[a0]; |
| 6467 |
if (a0 != a1) { |
| 6468 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6469 |
} else if (new_code0 != subst_code1) { |
| 6470 |
hap_rarealt_cts[subst_code1_offset + sample_idx] -= 1; |
| 6471 |
hap_rarealt_cts[new_code0 * sample_ct_i32av + sample_idx] += 1; |
| 6472 |
} |
| 6473 |
} |
| 6474 |
} |
| 6475 |
} |
| 6476 |
} |
| 6477 |
if (diploid_singleton_cts || singleton_cts) { |
| 6478 |
// this logic is completely unchanged, basic dense case should fall |
| 6479 |
// through to this? |
| 6480 |
ZeroTrailingNyps(sample_ct, genovec); |
| 6481 |
if (is_haploid) { |
| 6482 |
if (is_diploid_x) { |
| 6483 |
if (diploid_singleton_cts) { |
| 6484 |
UpdateSampleDiploidSingletonCountX(sex_male_collapsed, genovec, sample_ct, diploid_singleton_cts); |
| 6485 |
} |
| 6486 |
if (singleton_cts) { |
| 6487 |
UpdateSampleSingletonCountX(sex_male_collapsed, genovec, sample_ct, singleton_cts); |
| 6488 |
} |
| 6489 |
continue; |
| 6490 |
} |
| 6491 |
if (!singleton_cts) { |
| 6492 |
continue; |
| 6493 |
} |
| 6494 |
if (is_y) { |
| 6495 |
UpdateSampleSingletonCountY(sex_male_collapsed, genovec, sample_ct, singleton_cts); |
| 6496 |
continue; |
| 6497 |
} |
| 6498 |
SetHetMissing(sample_ctl2, genovec); |
| 6499 |
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct); |
| 6500 |
if (singleton_idx != UINT32_MAX) { |
| 6501 |
singleton_cts[singleton_idx] += 1; |
| 6502 |
} |
| 6503 |
continue; |
| 6504 |
} |
| 6505 |
const uint32_t singleton_idx = GetSingletonIdx(genovec, sample_ct); |
| 6506 |
if (singleton_idx != UINT32_MAX) { |
| 6507 |
if (diploid_singleton_cts) { |
| 6508 |
diploid_singleton_cts[singleton_idx] += 1; |
| 6509 |
} |
| 6510 |
if (singleton_cts) { |
| 6511 |
singleton_cts[singleton_idx] += 1; |
| 6512 |
} |
| 6513 |
} |
| 6514 |
} |
| 6515 |
} |
| 6516 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 6517 |
{ |
| 6518 |
const uintptr_t acc4_vec_ct = acc2_vec_ct * 2; |
| 6519 |
const uintptr_t acc8_vec_ct = acc2_vec_ct * 4; |
| 6520 |
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) { |
| 6521 |
VecW* acc2_0 = dense_counts[dense_vtype]; |
| 6522 |
if (acc2_0) { |
| 6523 |
VecW* acc4_0 = &(acc2_0[acc2_vec_ct]); |
| 6524 |
VcountIncr2To4(acc2_0, acc2_vec_ct, acc4_0); |
| 6525 |
VecW* acc8_0 = &(acc4_0[acc4_vec_ct]); |
| 6526 |
VcountIncr4To8(acc4_0, acc4_vec_ct, acc8_0); |
| 6527 |
VcountIncr8To32(acc8_0, acc8_vec_ct, &(acc8_0[acc8_vec_ct])); |
| 6528 |
|
| 6529 |
VecW* acc2_2 = &(acc2_0[dense_counts_vstride]); |
| 6530 |
VecW* acc4_2 = &(acc2_2[acc2_vec_ct]); |
| 6531 |
VcountIncr2To4(acc2_2, acc2_vec_ct, acc4_2); |
| 6532 |
VecW* acc8_2 = &(acc4_2[acc4_vec_ct]); |
| 6533 |
VcountIncr4To8(acc4_2, acc4_vec_ct, acc8_2); |
| 6534 |
VcountIncr8To32(acc8_2, acc8_vec_ct, &(acc8_2[acc8_vec_ct])); |
| 6535 |
|
| 6536 |
if (dense_vtype < 2 * kSubstCodeCt) { |
| 6537 |
VecW* acc2_1 = &(acc2_2[dense_counts_vstride]); |
| 6538 |
VecW* acc4_1 = &(acc2_1[acc2_vec_ct]); |
| 6539 |
VcountIncr2To4(acc2_1, acc2_vec_ct, acc4_1); |
| 6540 |
VecW* acc8_1 = &(acc4_1[acc4_vec_ct]); |
| 6541 |
VcountIncr4To8(acc4_1, acc4_vec_ct, acc8_1); |
| 6542 |
VcountIncr8To32(acc8_1, acc8_vec_ct, &(acc8_1[acc8_vec_ct])); |
| 6543 |
} |
| 6544 |
} |
| 6545 |
} |
| 6546 |
} |
| 6547 |
while (0) { |
| 6548 |
SampleCountsThread_err: |
| 6549 |
UpdateU64IfSmaller(new_err_info, &ctx->err_info); |
| 6550 |
THREAD_BLOCK_FINISH(arg); |
| 6551 |
break; |
| 6552 |
} |
| 6553 |
THREAD_RETURN; |
| 6554 |
} |
| 6555 |
|
| 6556 |
void Unscramble2(uint32_t sample_ct, uint32_t* dst, uint32_t* unscramble_buf) { |
| 6557 |
const uint32_t acc2_vec_ct = NypCtToWordCt(sample_ct); |
| 6558 |
memcpy(unscramble_buf, dst, acc2_vec_ct * 16 * kBytesPerVec); |
| 6559 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 6560 |
const uint32_t scrambled_idx = VcountScramble2(sample_idx); |
| 6561 |
dst[sample_idx] = unscramble_buf[scrambled_idx]; |
| 6562 |
} |
| 6563 |
} |
| 6564 |
|
| 6565 |
// diploid-only if haploid_counts_subst == nullptr |
| 6566 |
void IncrSubstType(const SampleCountsCtx* ctx, const uint32_t* const* diploid_counts_subst, const uint32_t* const* haploid_counts_subst, uint32_t sample_ct_i32v, uint32_t subst_code, uint32_t* dst) { |
| 6567 |
{ |
| 6568 |
const uint32_t* dip_src1 = diploid_counts_subst[1]; |
| 6569 |
const uint32_t* dip_src2 = diploid_counts_subst[2]; |
| 6570 |
U32CastVecAdd2(dip_src1, dip_src2, sample_ct_i32v, dst); |
| 6571 |
if (haploid_counts_subst) { |
| 6572 |
const uint32_t* hap_src = haploid_counts_subst[1]; |
| 6573 |
if (hap_src) { |
| 6574 |
U32CastVecAdd(hap_src, sample_ct_i32v, dst); |
| 6575 |
} |
| 6576 |
} |
| 6577 |
} |
| 6578 |
if (ctx->thread_het2alt_cts) { |
| 6579 |
const uintptr_t sample_ct_i32av = sample_ct_i32v * kInt32PerVec; |
| 6580 |
const uint32_t* sub_src = &(ctx->thread_het2alt_cts[0][subst_code * sample_ct_i32av]); |
| 6581 |
const uint32_t* add_src = &(sub_src[kSubstCodeCt * sample_ct_i32av]); |
| 6582 |
U32CastVecAddSub(add_src, sub_src, sample_ct_i32v, dst); |
| 6583 |
} |
| 6584 |
} |
| 6585 |
|
| 6586 |
uint32_t* AllocAndCountSubstType(const SampleCountsCtx* ctx, const uint32_t* const* diploid_counts_subst, const uint32_t* const* haploid_counts_subst, uint32_t sample_ct_i32v, uint32_t subst_code) { |
| 6587 |
uint32_t* dst = S_CAST(uint32_t*, bigstack_alloc(sample_ct_i32v * sizeof(VecU32))); |
| 6588 |
if (unlikely(!dst)) { |
| 6589 |
return nullptr; |
| 6590 |
} |
| 6591 |
ZeroU32Arr(sample_ct_i32v * kInt32PerVec, dst); |
| 6592 |
IncrSubstType(ctx, diploid_counts_subst, haploid_counts_subst, sample_ct_i32v, subst_code, dst); |
| 6593 |
return dst; |
| 6594 |
} |
| 6595 |
|
| 6596 |
ENUM_U31_DEF_START() |
| 6597 |
kSampleCountHom, |
| 6598 |
kSampleCountHomref, |
| 6599 |
kSampleCountHomalt, |
| 6600 |
kSampleCountHomaltSnp, |
| 6601 |
kSampleCountHet, |
| 6602 |
kSampleCountRefalt, |
| 6603 |
kSampleCountHet2alt, |
| 6604 |
|
| 6605 |
kSampleCountHetSnp, |
| 6606 |
kSampleCountDiploidTs, |
| 6607 |
kSampleCountTs, |
| 6608 |
kSampleCountDiploidTv, |
| 6609 |
kSampleCountTv, |
| 6610 |
kSampleCountDiploidNonsnpsymb, |
| 6611 |
kSampleCountNonsnpsymb, |
| 6612 |
kSampleCountSymbolic, |
| 6613 |
kSampleCountNonsnp, |
| 6614 |
|
| 6615 |
kSampleCountDiploidSingle, |
| 6616 |
kSampleCountSingle, |
| 6617 |
kSampleCountHaprefWithFemaleY, |
| 6618 |
kSampleCountHapref, |
| 6619 |
kSampleCountHapaltWithFemaleY, |
| 6620 |
kSampleCountHapalt, |
| 6621 |
kSampleCountMissingWithFemaleY, |
| 6622 |
kSampleCountMissing, |
| 6623 |
|
| 6624 |
kSampleCountTypeCt |
| 6625 |
ENUM_U31_DEF_END(SampleCountType); |
| 6626 |
|
| 6627 |
PglErr SampleCounts(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t male_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, SampleCountsFlags flags, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) { |
| 6628 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 6629 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 6630 |
const char sample_counts_headers[kSampleCountTypeCt][30] = { |
| 6631 |
"HOM_CT", |
| 6632 |
"HOM_REF_CT", |
| 6633 |
"HOM_ALT_CT", |
| 6634 |
"HOM_ALT_SNP_CT", |
| 6635 |
"HET_CT", |
| 6636 |
"HET_REF_ALT_CT", |
| 6637 |
"HET_2ALT_CT", |
| 6638 |
|
| 6639 |
"HET_SNP_CT", |
| 6640 |
"DIPLOID_TRANSITION_CT", |
| 6641 |
"TRANSITION_CT", |
| 6642 |
"DIPLOID_TRANSVERSION_CT", |
| 6643 |
"TRANSVERSION_CT", |
| 6644 |
"DIPLOID_NONSNP_NONSYMBOLIC_CT", |
| 6645 |
"NONSNP_NONSYMBOLIC_CT", |
| 6646 |
"SYMBOLIC_CT", |
| 6647 |
"NONSNP_CT", |
| 6648 |
|
| 6649 |
"DIPLOID_SINGLETON_CT", |
| 6650 |
"SINGLETON_CT", |
| 6651 |
"HAP_REF_INCL_FEMALE_Y_CT", |
| 6652 |
"HAP_REF_CT", |
| 6653 |
"HAP_ALT_INCL_FEMALE_Y_CT", |
| 6654 |
"HAP_ALT_CT", |
| 6655 |
"MISSING_INCL_FEMALE_Y_CT", |
| 6656 |
"MISSING_CT" |
| 6657 |
}; |
| 6658 |
char* cswritep = nullptr; |
| 6659 |
CompressStreamState css; |
| 6660 |
PglErr reterr = kPglRetSuccess; |
| 6661 |
PreinitCstream(&css); |
| 6662 |
ThreadGroup tg; |
| 6663 |
PreinitThreads(&tg); |
| 6664 |
SampleCountsCtx ctx; |
| 6665 |
{ |
| 6666 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 6667 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &ctx.sample_include_cumulative_popcounts))) { |
| 6668 |
goto SampleCounts_ret_NOMEM; |
| 6669 |
} |
| 6670 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, ctx.sample_include_cumulative_popcounts); |
| 6671 |
|
| 6672 |
// Biallelic variants are handled as follows: |
| 6673 |
// 1. Define four chromosome types (autosomal-diploid, chrX-diploid, chrY, |
| 6674 |
// and generic-haploid), and four substitution types (non-SNP, |
| 6675 |
// SNP-transition, SNP-transversion, non-ACGT 'SNP'). We compute |
| 6676 |
// per-sample 0/1/2 genotype counts for each (chromosome type, |
| 6677 |
// substitution type) pair. This is accelerated by distinguishing the |
| 6678 |
// dense- and sparse-storage cases, and also parallelized across |
| 6679 |
// variants. |
| 6680 |
// 2. Given these raw genotype counts, it is straightforward to build all |
| 6681 |
// of the supported columns, except for SINGLETON_CT. (MISSING_CT can |
| 6682 |
// be obtained by subtraction from the total number of variants, |
| 6683 |
// excluding chrY for nonmales.) |
| 6684 |
// 3. SINGLETON_CT gets its own logic in the main loop. |
| 6685 |
uint32_t chr_types = 0; |
| 6686 |
uint32_t diploid_chr_type_ct = 0; |
| 6687 |
if (IsAutosomalDiploidChrPresent(cip)) { |
| 6688 |
chr_types = 1; |
| 6689 |
++diploid_chr_type_ct; |
| 6690 |
} |
| 6691 |
uint32_t haploid_chr_type_ct = 0; |
| 6692 |
uint32_t y_variant_ct = 0; |
| 6693 |
uint32_t y_nonmale_needed = 0; |
| 6694 |
{ |
| 6695 |
uint32_t y_code; |
| 6696 |
if (XymtExists(cip, kChrOffsetY, &y_code)) { |
| 6697 |
y_variant_ct = CountChrVariantsUnsafe(variant_include, cip, y_code); |
| 6698 |
} |
| 6699 |
uintptr_t haploid_mask_lowbit = cip->haploid_mask[0] & 1; |
| 6700 |
// bugfix (28 Mar 2021): if chrX is present, no autosomal diploid |
| 6701 |
// chromosomes are present, and there are no males, we need to set the |
| 6702 |
// low bit of chr_types and increment diploid_chr_type_ct. |
| 6703 |
uint32_t x_code; |
| 6704 |
if ((!haploid_mask_lowbit) && XymtExists(cip, kChrOffsetX, &x_code)) { |
| 6705 |
if (male_ct) { |
| 6706 |
chr_types |= 2; |
| 6707 |
++diploid_chr_type_ct; |
| 6708 |
} else if (!chr_types) { |
| 6709 |
chr_types = 1; |
| 6710 |
++diploid_chr_type_ct; |
| 6711 |
} |
| 6712 |
} |
| 6713 |
if (y_variant_ct) { |
| 6714 |
y_nonmale_needed = ((flags & (kfSampleCountsColHaprefWithFemaleY | kfSampleCountsColHapaltWithFemaleY | kfSampleCountsColMissingWithFemaleY)) != 0); |
| 6715 |
if (male_ct || y_nonmale_needed) { |
| 6716 |
chr_types |= 4; |
| 6717 |
++haploid_chr_type_ct; |
| 6718 |
} |
| 6719 |
} |
| 6720 |
uint32_t mt_code; |
| 6721 |
if (haploid_mask_lowbit || XymtExists(cip, kChrOffsetMT, &mt_code)) { |
| 6722 |
chr_types |= 8; |
| 6723 |
++haploid_chr_type_ct; |
| 6724 |
} |
| 6725 |
} |
| 6726 |
assert(diploid_chr_type_ct + haploid_chr_type_ct); |
| 6727 |
// probable todo: for sample_ct > raw_sample_ct / 2 or so, may be better to |
| 6728 |
// perform un-subsetted computation and then subset the results? Benchmark |
| 6729 |
// this. |
| 6730 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 6731 |
if (chr_types & 6) { |
| 6732 |
if (unlikely(bigstack_alloc_w(sample_ctl, &ctx.sex_male_collapsed))) { |
| 6733 |
goto SampleCounts_ret_NOMEM; |
| 6734 |
} |
| 6735 |
CopyBitarrSubset(sex_male, sample_include, sample_ct, ctx.sex_male_collapsed); |
| 6736 |
} else { |
| 6737 |
ctx.sex_male_collapsed = nullptr; |
| 6738 |
} |
| 6739 |
|
| 6740 |
// don't subtract 1 after load-balancing is improved? |
| 6741 |
uint32_t calc_thread_ct = (max_thread_ct > 4)? (max_thread_ct - 1) : max_thread_ct; |
| 6742 |
if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.raregenos) || |
| 6743 |
bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs) || |
| 6744 |
bigstack_alloc_vpp(calc_thread_ct, &ctx.thread_dense_counts) || |
| 6745 |
bigstack_alloc_u32pp(calc_thread_ct, &ctx.thread_sparse_counts) || |
| 6746 |
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_sparse_common0_cts))) { |
| 6747 |
goto SampleCounts_ret_NOMEM; |
| 6748 |
} |
| 6749 |
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor); |
| 6750 |
|
| 6751 |
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec); |
| 6752 |
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec); |
| 6753 |
|
| 6754 |
const uintptr_t acc2_vec_ct = NypCtToVecCt(sample_ct); |
| 6755 |
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23; |
| 6756 |
// - need (0, 1, 2) genotype counts in diploid-chromosome case, only need |
| 6757 |
// (0, 1) for haploid |
| 6758 |
const uintptr_t dense_counts_bottom_vec_ct = kSubstCodeCt * (dense_counts_vstride * (3 * diploid_chr_type_ct + 2 * haploid_chr_type_ct)); |
| 6759 |
const uintptr_t dense_counts_middle_vec_ct = DivUp(4 * kSubstCodeCt, kWordsPerVec); |
| 6760 |
|
| 6761 |
const uintptr_t sample_ct_i32v = DivUp(sample_ct, kInt32PerVec); |
| 6762 |
// - x6 for 2 common_geno possibilities (0, 3), 3 common_geno -> rare_geno |
| 6763 |
// transitions per common_geno |
| 6764 |
const uintptr_t sparse_counts_bottom_vec_ct = 6 * kSubstCodeCt * sample_ct_i32v * (diploid_chr_type_ct + haploid_chr_type_ct); |
| 6765 |
const uintptr_t sample_ct_i32av = sample_ct_i32v * kInt32PerVec; |
| 6766 |
// - x8 for 4 chromosome types, 2 common_geno possibilities |
| 6767 |
const uintptr_t sparse_counts_middle_vec_ct = DivUp(8 * kSubstCodeCt, kWordsPerVec); |
| 6768 |
const uintptr_t sparse_common0_vec_ct = DivUp(4 * kSubstCodeCt, kInt32PerVec); |
| 6769 |
|
| 6770 |
uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + dense_counts_bottom_vec_ct + dense_counts_middle_vec_ct + sparse_counts_bottom_vec_ct + sparse_counts_middle_vec_ct + sparse_common0_vec_ct; |
| 6771 |
|
| 6772 |
ctx.thread_diploid_singleton_cts = nullptr; |
| 6773 |
if (flags & kfSampleCountsColDiploidSingle) { |
| 6774 |
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_diploid_singleton_cts))) { |
| 6775 |
goto SampleCounts_ret_NOMEM; |
| 6776 |
} |
| 6777 |
thread_xalloc_vec_ct += sample_ct_i32v; |
| 6778 |
} |
| 6779 |
ctx.thread_singleton_cts = nullptr; |
| 6780 |
if (flags & kfSampleCountsColSingle) { |
| 6781 |
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_singleton_cts))) { |
| 6782 |
goto SampleCounts_ret_NOMEM; |
| 6783 |
} |
| 6784 |
thread_xalloc_vec_ct += sample_ct_i32v; |
| 6785 |
} |
| 6786 |
// We support multiallelic variants by also tracking a few het_2alt, |
| 6787 |
// hom_rarealt, and hap_rarealt counts. |
| 6788 |
ctx.thread_alt_subst_codes = nullptr; |
| 6789 |
ctx.thread_het2alt_cts = nullptr; |
| 6790 |
ctx.thread_het_rarealt_cts = nullptr; |
| 6791 |
ctx.thread_hom_rarealt_cts = nullptr; |
| 6792 |
ctx.thread_hap_rarealt_cts = nullptr; |
| 6793 |
const uint32_t mhc_needed = (max_allele_ct > 2); |
| 6794 |
uintptr_t alt_subst_codes_vec_ct = 0; |
| 6795 |
uintptr_t het2alt_vec_ct = 0; |
| 6796 |
uintptr_t het_rarealt_vec_ct = 0; |
| 6797 |
uintptr_t hom_rarealt_vec_ct = 0; |
| 6798 |
uintptr_t hap_rarealt_vec_ct = 0; |
| 6799 |
if (mhc_needed) { |
| 6800 |
if (unlikely(bigstack_alloc_u16p(calc_thread_ct, &ctx.thread_alt_subst_codes) || |
| 6801 |
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_het2alt_cts) || |
| 6802 |
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_het_rarealt_cts) || |
| 6803 |
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_hom_rarealt_cts))) { |
| 6804 |
goto SampleCounts_ret_NOMEM; |
| 6805 |
} |
| 6806 |
alt_subst_codes_vec_ct = DivUp(kPglMaxAlleleCt, kInt16PerVec); |
| 6807 |
het2alt_vec_ct = sample_ct_i32v * 2 * kSubstCodeCt; |
| 6808 |
het_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt; |
| 6809 |
hom_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt; |
| 6810 |
thread_xalloc_vec_ct += alt_subst_codes_vec_ct + het2alt_vec_ct + het_rarealt_vec_ct + hom_rarealt_vec_ct; |
| 6811 |
if (chr_types & 14) { |
| 6812 |
if (unlikely(bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_hap_rarealt_cts))) { |
| 6813 |
goto SampleCounts_ret_NOMEM; |
| 6814 |
} |
| 6815 |
hap_rarealt_vec_ct = sample_ct_i32v * kSubstCodeCt; |
| 6816 |
thread_xalloc_vec_ct += hap_rarealt_vec_ct; |
| 6817 |
} |
| 6818 |
} |
| 6819 |
|
| 6820 |
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline); |
| 6821 |
// Cacheline-alignment is relevant for per-thread workspaces. We normally |
| 6822 |
// get that automatically by allocating from the bottom of the arena, but |
| 6823 |
// in this case it's more convenient to allocate them at the end, which is |
| 6824 |
// normally only vector-aligned. So we force the end to be |
| 6825 |
// cacheline-aligned here. |
| 6826 |
g_bigstack_end = R_CAST(unsigned char*, RoundDownPow2(R_CAST(uintptr_t, g_bigstack_end), kCacheline)); |
| 6827 |
|
| 6828 |
unsigned char* bigstack_mark2 = g_bigstack_base; |
| 6829 |
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs); |
| 6830 |
ctx.thread_read_mhc = nullptr; |
| 6831 |
uint32_t read_block_size; |
| 6832 |
if (unlikely(PgenMtLoadInit(variant_include, raw_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) { |
| 6833 |
goto SampleCounts_ret_NOMEM; |
| 6834 |
} |
| 6835 |
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) { |
| 6836 |
goto SampleCounts_ret_NOMEM; |
| 6837 |
} |
| 6838 |
ctx.variant_include = variant_include; |
| 6839 |
ctx.cip = cip; |
| 6840 |
ctx.allele_idx_offsets = allele_idx_offsets; |
| 6841 |
ctx.allele_storage = allele_storage; |
| 6842 |
ctx.sample_include = sample_include; |
| 6843 |
ctx.sample_ct = sample_ct; |
| 6844 |
ctx.male_ct = male_ct; |
| 6845 |
ctx.y_nonmale_needed = y_nonmale_needed; |
| 6846 |
ctx.err_info = (~0LLU) << 32; |
| 6847 |
unsigned char* bigstack_end_mark2 = nullptr; |
| 6848 |
assert(bigstack_left() >= thread_xalloc_cacheline_ct * kCacheline * calc_thread_ct); |
| 6849 |
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) { |
| 6850 |
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_end_alloc_raw(thread_xalloc_cacheline_ct * kCacheline)); |
| 6851 |
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc); |
| 6852 |
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]); |
| 6853 |
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 6854 |
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]); |
| 6855 |
if (mhc_needed) { |
| 6856 |
ctx.thread_alt_subst_codes[tidx] = R_CAST(uint16_t*, cur_alloc); |
| 6857 |
cur_alloc = &(cur_alloc[alt_subst_codes_vec_ct * kBytesPerVec]); |
| 6858 |
} |
| 6859 |
if (!tidx) { |
| 6860 |
bigstack_end_mark2 = cur_alloc; |
| 6861 |
} |
| 6862 |
ctx.thread_dense_counts[tidx] = R_CAST(VecW**, cur_alloc); |
| 6863 |
cur_alloc = &(cur_alloc[dense_counts_middle_vec_ct * kBytesPerVec]); |
| 6864 |
ZeroPtrArr(4 * kSubstCodeCt, ctx.thread_dense_counts[tidx]); |
| 6865 |
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) { |
| 6866 |
if (!((chr_types >> cur_chr_type) & 1)) { |
| 6867 |
continue; |
| 6868 |
} |
| 6869 |
const uintptr_t record_byte_ct = (dense_counts_vstride * (2 + (cur_chr_type < 2))) * kBytesPerVec; |
| 6870 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 6871 |
ctx.thread_dense_counts[tidx][cur_chr_type * kSubstCodeCt + subst_code] = R_CAST(VecW*, cur_alloc); |
| 6872 |
cur_alloc = &(cur_alloc[record_byte_ct]); |
| 6873 |
} |
| 6874 |
} |
| 6875 |
ctx.thread_sparse_counts[tidx] = R_CAST(uint32_t**, cur_alloc); |
| 6876 |
cur_alloc = &(cur_alloc[sparse_counts_middle_vec_ct * kBytesPerVec]); |
| 6877 |
ZeroPtrArr(8 * kSubstCodeCt, ctx.thread_sparse_counts[tidx]); |
| 6878 |
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) { |
| 6879 |
if (!((chr_types >> cur_chr_type) & 1)) { |
| 6880 |
continue; |
| 6881 |
} |
| 6882 |
const uintptr_t record_byte_ct = sample_ct_i32v * 3 * kBytesPerVec; |
| 6883 |
for (uint32_t common_geno_and_subst_code = 0; common_geno_and_subst_code != 2 * kSubstCodeCt; ++common_geno_and_subst_code) { |
| 6884 |
ctx.thread_sparse_counts[tidx][cur_chr_type * 2 * kSubstCodeCt + common_geno_and_subst_code] = R_CAST(uint32_t*, cur_alloc); |
| 6885 |
cur_alloc = &(cur_alloc[record_byte_ct]); |
| 6886 |
} |
| 6887 |
} |
| 6888 |
ctx.thread_sparse_common0_cts[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 6889 |
cur_alloc = &(cur_alloc[sparse_common0_vec_ct * kBytesPerVec]); |
| 6890 |
|
| 6891 |
if (ctx.thread_diploid_singleton_cts) { |
| 6892 |
ctx.thread_diploid_singleton_cts[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 6893 |
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]); |
| 6894 |
} |
| 6895 |
if (ctx.thread_singleton_cts) { |
| 6896 |
ctx.thread_singleton_cts[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 6897 |
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]); |
| 6898 |
} |
| 6899 |
if (mhc_needed) { |
| 6900 |
ctx.thread_het2alt_cts[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 6901 |
cur_alloc = &(cur_alloc[het2alt_vec_ct * kBytesPerVec]); |
| 6902 |
ctx.thread_het_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc); |
| 6903 |
cur_alloc = &(cur_alloc[het_rarealt_vec_ct * kBytesPerVec]); |
| 6904 |
ctx.thread_hom_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc); |
| 6905 |
cur_alloc = &(cur_alloc[hom_rarealt_vec_ct * kBytesPerVec]); |
| 6906 |
if (ctx.thread_hap_rarealt_cts) { |
| 6907 |
ctx.thread_hap_rarealt_cts[tidx] = R_CAST(int32_t*, cur_alloc); |
| 6908 |
cur_alloc = &(cur_alloc[hap_rarealt_vec_ct * kBytesPerVec]); |
| 6909 |
} |
| 6910 |
} |
| 6911 |
if (!tidx) { |
| 6912 |
assert(S_CAST(uintptr_t, cur_alloc - g_bigstack_end) == thread_xalloc_vec_ct * kBytesPerVec); |
| 6913 |
} |
| 6914 |
} |
| 6915 |
SetThreadFuncAndData(SampleCountsThread, &ctx, &tg); |
| 6916 |
|
| 6917 |
logputs("Calculating sample counts... "); |
| 6918 |
fputs("0%", stdout); |
| 6919 |
fflush(stdout); |
| 6920 |
uint32_t pct = 0; |
| 6921 |
|
| 6922 |
uint32_t parity = 0; |
| 6923 |
uint32_t read_block_idx = 0; |
| 6924 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 6925 |
for (uint32_t variant_idx = 0; ; ) { |
| 6926 |
const uint32_t cur_block_size = MultireadNonempty(variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr); |
| 6927 |
if (unlikely(reterr)) { |
| 6928 |
goto SampleCounts_ret_PGR_FAIL; |
| 6929 |
} |
| 6930 |
if (variant_idx) { |
| 6931 |
JoinThreads(&tg); |
| 6932 |
reterr = S_CAST(PglErr, ctx.err_info); |
| 6933 |
if (unlikely(reterr)) { |
| 6934 |
PgenErrPrintNV(reterr, ctx.err_info >> 32); |
| 6935 |
goto SampleCounts_ret_1; |
| 6936 |
} |
| 6937 |
} |
| 6938 |
if (!IsLastBlock(&tg)) { |
| 6939 |
ctx.cur_block_size = cur_block_size; |
| 6940 |
ComputeUidxStartPartition(variant_include, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts); |
| 6941 |
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs); |
| 6942 |
if (variant_idx + cur_block_size == variant_ct) { |
| 6943 |
DeclareLastThreadBlock(&tg); |
| 6944 |
} |
| 6945 |
if (unlikely(SpawnThreads(&tg))) { |
| 6946 |
goto SampleCounts_ret_THREAD_CREATE_FAIL; |
| 6947 |
} |
| 6948 |
} |
| 6949 |
|
| 6950 |
parity = 1 - parity; |
| 6951 |
if (variant_idx == variant_ct) { |
| 6952 |
break; |
| 6953 |
} |
| 6954 |
if (variant_idx >= next_print_variant_idx) { |
| 6955 |
if (pct > 10) { |
| 6956 |
putc_unlocked('\b', stdout); |
| 6957 |
} |
| 6958 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 6959 |
printf("\b\b%u%%", pct++); |
| 6960 |
fflush(stdout); |
| 6961 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 6962 |
} |
| 6963 |
|
| 6964 |
++read_block_idx; |
| 6965 |
variant_idx += cur_block_size; |
| 6966 |
// crucially, this is independent of the PgenReader block_base |
| 6967 |
// pointers |
| 6968 |
pgfip->block_base = main_loadbufs[parity]; |
| 6969 |
} |
| 6970 |
const uintptr_t acc32_voffset = acc2_vec_ct * 7; |
| 6971 |
const uintptr_t acc32_vec_ct = acc2_vec_ct * 16; |
| 6972 |
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) { |
| 6973 |
// any reasonable compiler should vectorize the inner loops |
| 6974 |
// could also multithread this (unscramble first, then split by sample |
| 6975 |
// ranges), but computation time here should be negligible |
| 6976 |
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) { |
| 6977 |
VecW* dst_acc2_0 = ctx.thread_dense_counts[0][dense_vtype]; |
| 6978 |
if (dst_acc2_0) { |
| 6979 |
const VecW* src_acc2_0 = ctx.thread_dense_counts[tidx][dense_vtype]; |
| 6980 |
const VecU32* src_acc32_0 = R_CAST(const VecU32*, &(src_acc2_0[acc32_voffset])); |
| 6981 |
VecU32* dst_acc32_0 = R_CAST(VecU32*, &(dst_acc2_0[acc32_voffset])); |
| 6982 |
U32VecAdd(src_acc32_0, acc32_vec_ct, dst_acc32_0); |
| 6983 |
const VecU32* src_acc32_2 = &(src_acc32_0[acc2_vec_ct * 23]); |
| 6984 |
VecU32* dst_acc32_2 = &(dst_acc32_0[acc2_vec_ct * 23]); |
| 6985 |
U32VecAdd(src_acc32_2, acc32_vec_ct, dst_acc32_2); |
| 6986 |
if (dense_vtype < 2 * kSubstCodeCt) { |
| 6987 |
const VecU32* src_acc32_1 = &(src_acc32_2[acc2_vec_ct * 23]); |
| 6988 |
VecU32* dst_acc32_1 = &(dst_acc32_2[acc2_vec_ct * 23]); |
| 6989 |
U32VecAdd(src_acc32_1, acc32_vec_ct, dst_acc32_1); |
| 6990 |
} |
| 6991 |
} |
| 6992 |
} |
| 6993 |
for (uint32_t sparse_vtype = 0; sparse_vtype != 8 * kSubstCodeCt; ++sparse_vtype) { |
| 6994 |
uint32_t* dst = ctx.thread_sparse_counts[0][sparse_vtype]; |
| 6995 |
if (dst) { |
| 6996 |
const uint32_t* src = ctx.thread_sparse_counts[tidx][sparse_vtype]; |
| 6997 |
U32CastVecAdd(src, sample_ct_i32v * 3, dst); |
| 6998 |
} |
| 6999 |
} |
| 7000 |
{ |
| 7001 |
const uint32_t* src = ctx.thread_sparse_common0_cts[tidx]; |
| 7002 |
uint32_t* dst = ctx.thread_sparse_common0_cts[0]; |
| 7003 |
for (uint32_t dense_vtype = 0; dense_vtype != 4 * kSubstCodeCt; ++dense_vtype) { |
| 7004 |
dst[dense_vtype] += src[dense_vtype]; |
| 7005 |
} |
| 7006 |
} |
| 7007 |
if (ctx.thread_diploid_singleton_cts) { |
| 7008 |
const uint32_t* src = ctx.thread_diploid_singleton_cts[tidx]; |
| 7009 |
uint32_t* dst = ctx.thread_diploid_singleton_cts[0]; |
| 7010 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7011 |
} |
| 7012 |
if (ctx.thread_singleton_cts) { |
| 7013 |
const uint32_t* src = ctx.thread_singleton_cts[tidx]; |
| 7014 |
uint32_t* dst = ctx.thread_singleton_cts[0]; |
| 7015 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7016 |
} |
| 7017 |
if (mhc_needed) { |
| 7018 |
{ |
| 7019 |
uint32_t* dst = ctx.thread_het2alt_cts[0]; |
| 7020 |
const uint32_t* src = ctx.thread_het2alt_cts[tidx]; |
| 7021 |
U32CastVecAdd(src, sample_ct_i32v * 2 * kSubstCodeCt, dst); |
| 7022 |
} |
| 7023 |
|
| 7024 |
int32_t* dst = ctx.thread_het_rarealt_cts[0]; |
| 7025 |
const int32_t* src = ctx.thread_het_rarealt_cts[tidx]; |
| 7026 |
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst); |
| 7027 |
dst = ctx.thread_hom_rarealt_cts[0]; |
| 7028 |
src = ctx.thread_hom_rarealt_cts[tidx]; |
| 7029 |
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst); |
| 7030 |
|
| 7031 |
if (ctx.thread_hap_rarealt_cts) { |
| 7032 |
dst = ctx.thread_hap_rarealt_cts[0]; |
| 7033 |
src = ctx.thread_hap_rarealt_cts[tidx]; |
| 7034 |
I32CastVecAdd(src, sample_ct_i32v * kSubstCodeCt, dst); |
| 7035 |
} |
| 7036 |
} |
| 7037 |
} |
| 7038 |
BigstackDoubleReset(bigstack_mark2, bigstack_end_mark2); |
| 7039 |
// Now we're ready to derive our final values from the raw count-matrices. |
| 7040 |
// 1. Unscramble the final dense raw counts. |
| 7041 |
uint32_t* unscramble_buf; |
| 7042 |
if (unlikely(bigstack_alloc_u32(acc32_vec_ct * kInt32PerVec, &unscramble_buf))) { |
| 7043 |
goto SampleCounts_ret_NOMEM; |
| 7044 |
} |
| 7045 |
uint32_t* male_u32_mask = nullptr; |
| 7046 |
uint32_t* haploid_counts[kSubstCodeCt][2]; |
| 7047 |
uint32_t* y_nonmale_counts[2]; |
| 7048 |
uint32_t* diploid_counts[kSubstCodeCt][3]; |
| 7049 |
{ |
| 7050 |
uint32_t* unscrambled_dense_counts[4 * kSubstCodeCt][3]; |
| 7051 |
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) { |
| 7052 |
const uint32_t vtype_stop = kSubstCodeCt * (cur_chr_type + 1); |
| 7053 |
if (!((chr_types >> cur_chr_type) & 1)) { |
| 7054 |
for (uint32_t vtype = kSubstCodeCt * cur_chr_type; vtype != vtype_stop; ++vtype) { |
| 7055 |
unscrambled_dense_counts[vtype][0] = nullptr; |
| 7056 |
unscrambled_dense_counts[vtype][1] = nullptr; |
| 7057 |
unscrambled_dense_counts[vtype][2] = nullptr; |
| 7058 |
} |
| 7059 |
continue; |
| 7060 |
} |
| 7061 |
for (uint32_t vtype = kSubstCodeCt * cur_chr_type; vtype != vtype_stop; ++vtype) { |
| 7062 |
VecW* dst_acc2_0 = ctx.thread_dense_counts[0][vtype]; |
| 7063 |
uint32_t* dst_0 = R_CAST(uint32_t*, &(dst_acc2_0[acc32_voffset])); |
| 7064 |
Unscramble2(sample_ct, dst_0, unscramble_buf); |
| 7065 |
unscrambled_dense_counts[vtype][0] = dst_0; |
| 7066 |
|
| 7067 |
uint32_t* dst_2 = &(dst_0[acc2_vec_ct * 23 * kInt32PerVec]); |
| 7068 |
Unscramble2(sample_ct, dst_2, unscramble_buf); |
| 7069 |
unscrambled_dense_counts[vtype][2] = dst_2; |
| 7070 |
|
| 7071 |
if (cur_chr_type < 2) { |
| 7072 |
uint32_t* dst_1 = &(dst_2[acc2_vec_ct * 23 * kInt32PerVec]); |
| 7073 |
Unscramble2(sample_ct, dst_1, unscramble_buf); |
| 7074 |
unscrambled_dense_counts[vtype][1] = dst_1; |
| 7075 |
} else { |
| 7076 |
unscrambled_dense_counts[vtype][1] = nullptr; |
| 7077 |
} |
| 7078 |
} |
| 7079 |
} |
| 7080 |
|
| 7081 |
BigstackReset(bigstack_mark2); |
| 7082 |
// 2. Patch in the sparse counts. |
| 7083 |
for (uint32_t cur_chr_type = 0; cur_chr_type != 4; ++cur_chr_type) { |
| 7084 |
if (!((chr_types >> cur_chr_type) & 1)) { |
| 7085 |
continue; |
| 7086 |
} |
| 7087 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7088 |
const uint32_t dense_vtype = kSubstCodeCt * cur_chr_type + subst_code; |
| 7089 |
uint32_t* dense0 = unscrambled_dense_counts[dense_vtype][0]; |
| 7090 |
uint32_t* dense1 = unscrambled_dense_counts[dense_vtype][1]; |
| 7091 |
uint32_t* dense2 = unscrambled_dense_counts[dense_vtype][2]; |
| 7092 |
|
| 7093 |
const uint32_t base0 = ctx.thread_sparse_common0_cts[0][dense_vtype]; |
| 7094 |
uint32_t sparse_vtype = dense_vtype + kSubstCodeCt * cur_chr_type; |
| 7095 |
// 0->1 |
| 7096 |
const uint32_t* src = ctx.thread_sparse_counts[0][sparse_vtype]; |
| 7097 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7098 |
dense0[sample_idx] += base0 - src[sample_idx]; |
| 7099 |
} |
| 7100 |
if (dense1) { |
| 7101 |
U32CastVecAdd(src, sample_ct_i32v, dense1); |
| 7102 |
} |
| 7103 |
// 0->2 |
| 7104 |
src = &(src[sample_ct_i32av]); |
| 7105 |
U32CastVecSub(src, sample_ct_i32v, dense0); |
| 7106 |
U32CastVecAdd(src, sample_ct_i32v, dense2); |
| 7107 |
// 0->3 |
| 7108 |
src = &(src[sample_ct_i32av]); |
| 7109 |
U32CastVecSub(src, sample_ct_i32v, dense0); |
| 7110 |
|
| 7111 |
sparse_vtype += kSubstCodeCt; |
| 7112 |
src = ctx.thread_sparse_counts[0][sparse_vtype]; |
| 7113 |
// 3->2 |
| 7114 |
U32CastVecAdd(src, sample_ct_i32v, dense2); |
| 7115 |
// 3->1 |
| 7116 |
src = &(src[sample_ct_i32av]); |
| 7117 |
if (dense1) { |
| 7118 |
U32CastVecAdd(src, sample_ct_i32v, dense1); |
| 7119 |
} |
| 7120 |
// 3->0 |
| 7121 |
src = &(src[sample_ct_i32av]); |
| 7122 |
U32CastVecAdd(src, sample_ct_i32v, dense0); |
| 7123 |
} |
| 7124 |
} |
| 7125 |
|
| 7126 |
// 3. Allocate the reported-counts arrays, and fill them in a sensible |
| 7127 |
// order. |
| 7128 |
|
| 7129 |
// We start with |
| 7130 |
// haploid_counts := chrX/chrY male + generic-haploid |
| 7131 |
// y_nonmale_counts := chrY nonmale 0+2 |
| 7132 |
// diploid_counts := autosomal-diploid + chrX nonmale |
| 7133 |
// It's safe to move and alter the unscrambled_dense_counts arrays in the |
| 7134 |
// process, since we only refer to haploid_counts/y_nonmale_counts/ |
| 7135 |
// diploid_counts afterward, but we have to be careful about timing when |
| 7136 |
// we do that. |
| 7137 |
for (uint32_t alt_ct = 0; alt_ct != 2; ++alt_ct) { |
| 7138 |
y_nonmale_counts[alt_ct] = nullptr; |
| 7139 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7140 |
haploid_counts[subst_code][alt_ct] = nullptr; |
| 7141 |
} |
| 7142 |
} |
| 7143 |
if (chr_types & 14) { |
| 7144 |
if (chr_types & 6) { |
| 7145 |
// possible todo: not important here, but should be interesting to |
| 7146 |
// benchmark vector-based ways of doing this (including a simple |
| 7147 |
// 16- or 256-element lookup table) |
| 7148 |
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &male_u32_mask))) { |
| 7149 |
goto SampleCounts_ret_NOMEM; |
| 7150 |
} |
| 7151 |
const uintptr_t* sex_male_collapsed = ctx.sex_male_collapsed; |
| 7152 |
uintptr_t sample_idx_base = 0; |
| 7153 |
uintptr_t cur_bits = sex_male_collapsed[0]; |
| 7154 |
for (uint32_t male_idx = 0; male_idx != male_ct; ++male_idx) { |
| 7155 |
const uint32_t sample_idx = BitIter1(sex_male_collapsed, &sample_idx_base, &cur_bits); |
| 7156 |
male_u32_mask[sample_idx] = UINT32_MAX; |
| 7157 |
} |
| 7158 |
} |
| 7159 |
uint32_t* female_y_dst = nullptr; |
| 7160 |
for (uint32_t alt_ct = 0; alt_ct != 2; ++alt_ct) { |
| 7161 |
if (y_nonmale_needed) { |
| 7162 |
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &female_y_dst))) { |
| 7163 |
goto SampleCounts_ret_NOMEM; |
| 7164 |
} |
| 7165 |
y_nonmale_counts[alt_ct] = female_y_dst; |
| 7166 |
} |
| 7167 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7168 |
uint32_t* dst; |
| 7169 |
if (chr_types & 8) { |
| 7170 |
dst = unscrambled_dense_counts[3 * kSubstCodeCt + subst_code][alt_ct * 2]; |
| 7171 |
} else { |
| 7172 |
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &dst))) { |
| 7173 |
goto SampleCounts_ret_NOMEM; |
| 7174 |
} |
| 7175 |
} |
| 7176 |
haploid_counts[subst_code][alt_ct] = dst; |
| 7177 |
if (chr_types & 6) { |
| 7178 |
if (chr_types & 4) { |
| 7179 |
const uint32_t* src2 = unscrambled_dense_counts[2 * kSubstCodeCt + subst_code][alt_ct * 2]; |
| 7180 |
if (female_y_dst) { |
| 7181 |
U32CastVecInvmaskedAdd(male_u32_mask, src2, sample_ct_i32v, female_y_dst); |
| 7182 |
} |
| 7183 |
if (chr_types & 2) { |
| 7184 |
const uint32_t* src1 = unscrambled_dense_counts[kSubstCodeCt + subst_code][alt_ct * 2]; |
| 7185 |
U32CastVecMaskedAdd2(male_u32_mask, src1, src2, sample_ct_i32v, dst); |
| 7186 |
} else { |
| 7187 |
U32CastVecMaskedAdd(male_u32_mask, src2, sample_ct_i32v, dst); |
| 7188 |
} |
| 7189 |
} else { |
| 7190 |
const uint32_t* src1 = unscrambled_dense_counts[kSubstCodeCt + subst_code][alt_ct * 2]; |
| 7191 |
U32CastVecMaskedAdd(male_u32_mask, src1, sample_ct_i32v, dst); |
| 7192 |
} |
| 7193 |
} |
| 7194 |
} |
| 7195 |
} |
| 7196 |
} |
| 7197 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7198 |
for (uint32_t alt_ct = 0; alt_ct != 3; ++alt_ct) { |
| 7199 |
uint32_t* dst; |
| 7200 |
if (chr_types & 1) { |
| 7201 |
dst = unscrambled_dense_counts[subst_code][alt_ct]; |
| 7202 |
} else { |
| 7203 |
if (unlikely(bigstack_end_calloc_u32(sample_ct_i32av, &dst))) { |
| 7204 |
goto SampleCounts_ret_NOMEM; |
| 7205 |
} |
| 7206 |
} |
| 7207 |
|
| 7208 |
diploid_counts[subst_code][alt_ct] = dst; |
| 7209 |
if (chr_types & 2) { |
| 7210 |
// chrX nonmales |
| 7211 |
const uint32_t* src = unscrambled_dense_counts[subst_code + kSubstCodeCt][alt_ct]; |
| 7212 |
U32CastVecInvmaskedAdd(male_u32_mask, src, sample_ct_i32v, dst); |
| 7213 |
} |
| 7214 |
} |
| 7215 |
} |
| 7216 |
if (mhc_needed) { |
| 7217 |
// het_rarealt: modifies diploid alt_ct=1 subst_code distribution |
| 7218 |
// hom_rarealt: modifies diploid alt_ct=2 subst_code distribution |
| 7219 |
// hap_rarealt: modifies haploid alt_ct=1 subst_code distribution |
| 7220 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7221 |
// let's make sure overflow behavior is defined, so if there's a bug |
| 7222 |
// earlier on it's less likely to be a nightmare |
| 7223 |
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_het_rarealt_cts[0][subst_code * sample_ct_i32av])); |
| 7224 |
uint32_t* dst = diploid_counts[subst_code][1]; |
| 7225 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7226 |
} |
| 7227 |
|
| 7228 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7229 |
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_hom_rarealt_cts[0][subst_code * sample_ct_i32av])); |
| 7230 |
uint32_t* dst = diploid_counts[subst_code][2]; |
| 7231 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7232 |
} |
| 7233 |
|
| 7234 |
if (ctx.thread_hap_rarealt_cts) { |
| 7235 |
for (uint32_t subst_code = 0; subst_code != kSubstCodeCt; ++subst_code) { |
| 7236 |
const uint32_t* src = R_CAST(uint32_t*, &(ctx.thread_hap_rarealt_cts[0][subst_code * sample_ct_i32av])); |
| 7237 |
uint32_t* dst = haploid_counts[subst_code][1]; |
| 7238 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7239 |
} |
| 7240 |
} |
| 7241 |
|
| 7242 |
// het2alt: handled separately |
| 7243 |
} |
| 7244 |
} |
| 7245 |
// Main dependency graph: |
| 7246 |
// het2alt ALT1= pieces |
| 7247 |
// | |
| 7248 |
// v |
| 7249 |
// het2alt reported sum + refalt -> het |
| 7250 |
// | | |
| 7251 |
// | ---> missing |
| 7252 |
// v | |
| 7253 |
// homalt + homref -> hom |
| 7254 |
uint32_t* het2alt_reported_vals = nullptr; |
| 7255 |
if (mhc_needed) { |
| 7256 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &het2alt_reported_vals))) { |
| 7257 |
goto SampleCounts_ret_NOMEM; |
| 7258 |
} |
| 7259 |
const uint32_t* src0 = ctx.thread_het2alt_cts[0]; |
| 7260 |
const uint32_t* src1 = &(src0[sample_ct_i32av]); |
| 7261 |
const uint32_t* src2 = &(src1[sample_ct_i32av]); |
| 7262 |
const uint32_t* src3 = &(src2[sample_ct_i32av]); |
| 7263 |
const uint32_t* src4 = &(src3[sample_ct_i32av]); |
| 7264 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, het2alt_reported_vals); |
| 7265 |
} |
| 7266 |
uint32_t* refalt_vals; |
| 7267 |
uint32_t* homalt_vals; |
| 7268 |
uint32_t* homref_vals; |
| 7269 |
uint32_t* hom_vals; |
| 7270 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &refalt_vals) || |
| 7271 |
bigstack_alloc_u32(sample_ct_i32av, &homalt_vals) || |
| 7272 |
bigstack_alloc_u32(sample_ct_i32av, &homref_vals) || |
| 7273 |
bigstack_alloc_u32(sample_ct_i32av, &hom_vals))) { |
| 7274 |
goto SampleCounts_ret_NOMEM; |
| 7275 |
} |
| 7276 |
{ |
| 7277 |
const uint32_t* src0 = diploid_counts[0][1]; |
| 7278 |
const uint32_t* src1 = diploid_counts[1][1]; |
| 7279 |
const uint32_t* src2 = diploid_counts[2][1]; |
| 7280 |
const uint32_t* src3 = diploid_counts[3][1]; |
| 7281 |
const uint32_t* src4 = diploid_counts[4][1]; |
| 7282 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, refalt_vals); |
| 7283 |
} |
| 7284 |
uint32_t* het_vals; |
| 7285 |
if (!mhc_needed) { |
| 7286 |
het_vals = refalt_vals; |
| 7287 |
} else { |
| 7288 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &het_vals))) { |
| 7289 |
goto SampleCounts_ret_NOMEM; |
| 7290 |
} |
| 7291 |
U32CastVecAssignAdd2(het2alt_reported_vals, refalt_vals, sample_ct_i32v, het_vals); |
| 7292 |
} |
| 7293 |
{ |
| 7294 |
const uint32_t* src0 = diploid_counts[0][2]; |
| 7295 |
const uint32_t* src1 = diploid_counts[1][2]; |
| 7296 |
const uint32_t* src2 = diploid_counts[2][2]; |
| 7297 |
const uint32_t* src3 = diploid_counts[3][2]; |
| 7298 |
const uint32_t* src4 = diploid_counts[4][2]; |
| 7299 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, homalt_vals); |
| 7300 |
if (het2alt_reported_vals) { |
| 7301 |
U32CastVecSub(het2alt_reported_vals, sample_ct_i32v, homalt_vals); |
| 7302 |
} |
| 7303 |
|
| 7304 |
src0 = diploid_counts[0][0]; |
| 7305 |
src1 = diploid_counts[1][0]; |
| 7306 |
src2 = diploid_counts[2][0]; |
| 7307 |
src3 = diploid_counts[3][0]; |
| 7308 |
src4 = diploid_counts[4][0]; |
| 7309 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, homref_vals); |
| 7310 |
U32CastVecAssignAdd2(homref_vals, homalt_vals, sample_ct_i32v, hom_vals); |
| 7311 |
} |
| 7312 |
uint32_t* hapref_vals; |
| 7313 |
uint32_t* hapalt_vals; |
| 7314 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &hapref_vals) || |
| 7315 |
bigstack_alloc_u32(sample_ct_i32av, &hapalt_vals))) { |
| 7316 |
goto SampleCounts_ret_NOMEM; |
| 7317 |
} |
| 7318 |
{ |
| 7319 |
if (chr_types & 14) { |
| 7320 |
const uint32_t* src0 = haploid_counts[0][0]; |
| 7321 |
const uint32_t* src1 = haploid_counts[1][0]; |
| 7322 |
const uint32_t* src2 = haploid_counts[2][0]; |
| 7323 |
const uint32_t* src3 = haploid_counts[3][0]; |
| 7324 |
const uint32_t* src4 = haploid_counts[4][0]; |
| 7325 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, hapref_vals); |
| 7326 |
src0 = haploid_counts[0][1]; |
| 7327 |
src1 = haploid_counts[1][1]; |
| 7328 |
src2 = haploid_counts[2][1]; |
| 7329 |
src3 = haploid_counts[3][1]; |
| 7330 |
src4 = haploid_counts[4][1]; |
| 7331 |
U32CastVecAssignAdd5(src0, src1, src2, src3, src4, sample_ct_i32v, hapalt_vals); |
| 7332 |
} else { |
| 7333 |
ZeroU32Arr(sample_ct, hapref_vals); |
| 7334 |
ZeroU32Arr(sample_ct, hapalt_vals); |
| 7335 |
} |
| 7336 |
} |
| 7337 |
|
| 7338 |
uint32_t* final_counts[kSampleCountTypeCt]; |
| 7339 |
ZeroPtrArr(kSampleCountTypeCt, final_counts); |
| 7340 |
if (flags & kfSampleCountsColHom) { |
| 7341 |
final_counts[kSampleCountHom] = hom_vals; |
| 7342 |
} |
| 7343 |
if (flags & kfSampleCountsColHomref) { |
| 7344 |
final_counts[kSampleCountHomref] = homref_vals; |
| 7345 |
} |
| 7346 |
if (flags & kfSampleCountsColHomalt) { |
| 7347 |
final_counts[kSampleCountHomalt] = homalt_vals; |
| 7348 |
} |
| 7349 |
if (flags & kfSampleCountsColHomaltSnp) { |
| 7350 |
uint32_t* dst; |
| 7351 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7352 |
goto SampleCounts_ret_NOMEM; |
| 7353 |
} |
| 7354 |
final_counts[kSampleCountHomaltSnp] = dst; |
| 7355 |
const uint32_t* src1 = diploid_counts[kSubstCodeTs][2]; |
| 7356 |
const uint32_t* src2 = diploid_counts[kSubstCodeTv][2]; |
| 7357 |
const uint32_t* src3 = diploid_counts[kSubstCodeWeirdSnp][2]; |
| 7358 |
U32CastVecAssignAdd3(src1, src2, src3, sample_ct_i32v, dst); |
| 7359 |
if (mhc_needed) { |
| 7360 |
const uint32_t* src_base = ctx.thread_het2alt_cts[0]; |
| 7361 |
src1 = &(src_base[sample_ct_i32av * kSubstCodeTs]); |
| 7362 |
src2 = &(src_base[sample_ct_i32av * kSubstCodeTv]); |
| 7363 |
src3 = &(src_base[sample_ct_i32av * kSubstCodeWeirdSnp]); |
| 7364 |
U32CastVecSub3(src1, src2, src3, sample_ct_i32v, dst); |
| 7365 |
} |
| 7366 |
} |
| 7367 |
if (flags & kfSampleCountsColHet) { |
| 7368 |
final_counts[kSampleCountHet] = het_vals; |
| 7369 |
} |
| 7370 |
if (flags & kfSampleCountsColRefalt) { |
| 7371 |
final_counts[kSampleCountRefalt] = refalt_vals; |
| 7372 |
} |
| 7373 |
if (flags & kfSampleCountsColHet2alt) { |
| 7374 |
if (het2alt_reported_vals) { |
| 7375 |
final_counts[kSampleCountHet2alt] = het2alt_reported_vals; |
| 7376 |
} else { |
| 7377 |
if (unlikely(bigstack_calloc_u32(sample_ct_i32av, &(final_counts[kSampleCountHet2alt])))) { |
| 7378 |
goto SampleCounts_ret_NOMEM; |
| 7379 |
} |
| 7380 |
} |
| 7381 |
} |
| 7382 |
|
| 7383 |
if (flags & kfSampleCountsColHetSnp) { |
| 7384 |
uint32_t* dst; |
| 7385 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7386 |
goto SampleCounts_ret_NOMEM; |
| 7387 |
} |
| 7388 |
final_counts[kSampleCountHetSnp] = dst; |
| 7389 |
const uint32_t* src1 = diploid_counts[kSubstCodeTs][1]; |
| 7390 |
const uint32_t* src2 = diploid_counts[kSubstCodeTv][1]; |
| 7391 |
const uint32_t* src3 = diploid_counts[kSubstCodeWeirdSnp][1]; |
| 7392 |
U32CastVecAssignAdd3(src1, src2, src3, sample_ct_i32v, dst); |
| 7393 |
if (mhc_needed) { |
| 7394 |
const uint32_t* src_base = &(ctx.thread_het2alt_cts[0][kSubstCodeCt * sample_ct_i32av]); |
| 7395 |
src1 = &(src_base[kSubstCodeTs * sample_ct_i32av]); |
| 7396 |
src2 = &(src_base[kSubstCodeTv * sample_ct_i32av]); |
| 7397 |
src3 = &(src_base[kSubstCodeWeirdSnp * sample_ct_i32av]); |
| 7398 |
U32CastVecAdd3(src1, src2, src3, sample_ct_i32v, dst); |
| 7399 |
} |
| 7400 |
} |
| 7401 |
if (flags & kfSampleCountsColDiploidTs) { |
| 7402 |
final_counts[kSampleCountDiploidTs] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTs]), nullptr, sample_ct_i32v, kSubstCodeTs); |
| 7403 |
if (unlikely(!final_counts[kSampleCountDiploidTs])) { |
| 7404 |
goto SampleCounts_ret_NOMEM; |
| 7405 |
} |
| 7406 |
} |
| 7407 |
if (flags & kfSampleCountsColTs) { |
| 7408 |
final_counts[kSampleCountTs] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTs]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeTs]), sample_ct_i32v, kSubstCodeTs); |
| 7409 |
if (unlikely(!final_counts[kSampleCountTs])) { |
| 7410 |
goto SampleCounts_ret_NOMEM; |
| 7411 |
} |
| 7412 |
} |
| 7413 |
if (flags & kfSampleCountsColDiploidTv) { |
| 7414 |
final_counts[kSampleCountDiploidTv] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTv]), nullptr, sample_ct_i32v, kSubstCodeTv); |
| 7415 |
if (unlikely(!final_counts[kSampleCountDiploidTv])) { |
| 7416 |
goto SampleCounts_ret_NOMEM; |
| 7417 |
} |
| 7418 |
} |
| 7419 |
if (flags & kfSampleCountsColTv) { |
| 7420 |
final_counts[kSampleCountTv] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeTv]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeTv]), sample_ct_i32v, kSubstCodeTv); |
| 7421 |
if (unlikely(!final_counts[kSampleCountTv])) { |
| 7422 |
goto SampleCounts_ret_NOMEM; |
| 7423 |
} |
| 7424 |
} |
| 7425 |
if (flags & kfSampleCountsColDiploidNonsnpsymb) { |
| 7426 |
final_counts[kSampleCountDiploidNonsnpsymb] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), nullptr, sample_ct_i32v, kSubstCodeNonsnpsymb); |
| 7427 |
if (unlikely(!final_counts[kSampleCountDiploidNonsnpsymb])) { |
| 7428 |
goto SampleCounts_ret_NOMEM; |
| 7429 |
} |
| 7430 |
} |
| 7431 |
if (flags & kfSampleCountsColNonsnpsymb) { |
| 7432 |
final_counts[kSampleCountNonsnpsymb] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeNonsnpsymb]), sample_ct_i32v, kSubstCodeNonsnpsymb); |
| 7433 |
if (unlikely(!final_counts[kSampleCountNonsnpsymb])) { |
| 7434 |
goto SampleCounts_ret_NOMEM; |
| 7435 |
} |
| 7436 |
} |
| 7437 |
if (flags & kfSampleCountsColSymbolic) { |
| 7438 |
final_counts[kSampleCountSymbolic] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeSymbolic]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeSymbolic]), sample_ct_i32v, kSubstCodeSymbolic); |
| 7439 |
if (unlikely(!final_counts[kSampleCountSymbolic])) { |
| 7440 |
goto SampleCounts_ret_NOMEM; |
| 7441 |
} |
| 7442 |
} |
| 7443 |
if (flags & kfSampleCountsColNonsnp) { |
| 7444 |
final_counts[kSampleCountNonsnp] = AllocAndCountSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeNonsnpsymb]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeNonsnpsymb]), sample_ct_i32v, kSubstCodeNonsnpsymb); |
| 7445 |
if (unlikely(!final_counts[kSampleCountNonsnp])) { |
| 7446 |
goto SampleCounts_ret_NOMEM; |
| 7447 |
} |
| 7448 |
IncrSubstType(&ctx, TO_CONSTU32PCONSTP(diploid_counts[kSubstCodeSymbolic]), TO_CONSTU32PCONSTP(haploid_counts[kSubstCodeSymbolic]), sample_ct_i32v, kSubstCodeSymbolic, final_counts[kSampleCountNonsnp]); |
| 7449 |
} |
| 7450 |
|
| 7451 |
if (flags & kfSampleCountsColDiploidSingle) { |
| 7452 |
final_counts[kSampleCountDiploidSingle] = ctx.thread_diploid_singleton_cts[0]; |
| 7453 |
} |
| 7454 |
if (flags & kfSampleCountsColSingle) { |
| 7455 |
final_counts[kSampleCountSingle] = ctx.thread_singleton_cts[0]; |
| 7456 |
} |
| 7457 |
if (flags & kfSampleCountsColHaprefWithFemaleY) { |
| 7458 |
uint32_t* dst; |
| 7459 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7460 |
goto SampleCounts_ret_NOMEM; |
| 7461 |
} |
| 7462 |
final_counts[kSampleCountHaprefWithFemaleY] = dst; |
| 7463 |
memcpy(dst, hapref_vals, sample_ct * sizeof(int32_t)); |
| 7464 |
if (chr_types & 4) { |
| 7465 |
const uint32_t* src = y_nonmale_counts[0]; |
| 7466 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7467 |
} |
| 7468 |
} |
| 7469 |
if (flags & kfSampleCountsColHapref) { |
| 7470 |
final_counts[kSampleCountHapref] = hapref_vals; |
| 7471 |
} |
| 7472 |
if (flags & kfSampleCountsColHapaltWithFemaleY) { |
| 7473 |
uint32_t* dst; |
| 7474 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7475 |
goto SampleCounts_ret_NOMEM; |
| 7476 |
} |
| 7477 |
final_counts[kSampleCountHapaltWithFemaleY] = dst; |
| 7478 |
memcpy(dst, hapalt_vals, sample_ct * sizeof(int32_t)); |
| 7479 |
if (chr_types & 4) { |
| 7480 |
const uint32_t* src = y_nonmale_counts[1]; |
| 7481 |
U32CastVecAdd(src, sample_ct_i32v, dst); |
| 7482 |
} |
| 7483 |
} |
| 7484 |
if (flags & kfSampleCountsColHapalt) { |
| 7485 |
final_counts[kSampleCountHapalt] = hapalt_vals; |
| 7486 |
} |
| 7487 |
if (flags & kfSampleCountsColMissingWithFemaleY) { |
| 7488 |
uint32_t* dst; |
| 7489 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7490 |
goto SampleCounts_ret_NOMEM; |
| 7491 |
} |
| 7492 |
final_counts[kSampleCountMissingWithFemaleY] = dst; |
| 7493 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7494 |
// todo: verify this vectorizes well |
| 7495 |
dst[sample_idx] = variant_ct - hom_vals[sample_idx] - het_vals[sample_idx] - hapref_vals[sample_idx] - hapalt_vals[sample_idx]; |
| 7496 |
} |
| 7497 |
if (chr_types & 4) { |
| 7498 |
const uint32_t* src0 = y_nonmale_counts[0]; |
| 7499 |
const uint32_t* src1 = y_nonmale_counts[1]; |
| 7500 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7501 |
dst[sample_idx] -= src0[sample_idx] + src1[sample_idx]; |
| 7502 |
} |
| 7503 |
} |
| 7504 |
} |
| 7505 |
if (flags & kfSampleCountsColMissing) { |
| 7506 |
uint32_t* dst; |
| 7507 |
if (unlikely(bigstack_alloc_u32(sample_ct_i32av, &dst))) { |
| 7508 |
goto SampleCounts_ret_NOMEM; |
| 7509 |
} |
| 7510 |
final_counts[kSampleCountMissing] = dst; |
| 7511 |
const uint32_t nony_variant_ct = variant_ct - y_variant_ct; |
| 7512 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7513 |
dst[sample_idx] = nony_variant_ct - hom_vals[sample_idx] - het_vals[sample_idx] - hapref_vals[sample_idx] - hapalt_vals[sample_idx]; |
| 7514 |
} |
| 7515 |
if (chr_types & 4) { |
| 7516 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7517 |
dst[sample_idx] += male_u32_mask[sample_idx] & y_variant_ct; |
| 7518 |
} |
| 7519 |
} |
| 7520 |
} |
| 7521 |
|
| 7522 |
// Ready to write to disk. |
| 7523 |
if (pct > 10) { |
| 7524 |
putc_unlocked('\b', stdout); |
| 7525 |
} |
| 7526 |
fputs("\b\b", stdout); |
| 7527 |
logputs("done.\n"); |
| 7528 |
BigstackEndReset(bigstack_end_mark2); |
| 7529 |
const uintptr_t overflow_buf_size = RoundUpPow2(kCompressStreamBlock + 3 * kMaxIdSlen + 512, kCacheline); |
| 7530 |
const uint32_t output_zst = flags & kfSampleCountsZs; |
| 7531 |
uintptr_t overflow_buf_alloc = overflow_buf_size; |
| 7532 |
if (output_zst) { |
| 7533 |
overflow_buf_alloc += CstreamWkspaceReq(overflow_buf_size); |
| 7534 |
} |
| 7535 |
char* overflow_buf; |
| 7536 |
if (unlikely(bigstack_alloc_c(overflow_buf_alloc, &overflow_buf))) { |
| 7537 |
goto SampleCounts_ret_NOMEM; |
| 7538 |
} |
| 7539 |
OutnameZstSet(".scount", output_zst, outname_end); |
| 7540 |
reterr = InitCstream(outname, 0, output_zst, max_thread_ct, overflow_buf_size, overflow_buf, R_CAST(unsigned char*, &(overflow_buf[overflow_buf_size])), &css); |
| 7541 |
if (unlikely(reterr)) { |
| 7542 |
goto SampleCounts_ret_1; |
| 7543 |
} |
| 7544 |
cswritep = overflow_buf; |
| 7545 |
*cswritep++ = '#'; |
| 7546 |
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSampleCountsColMaybefid); |
| 7547 |
if (col_fid) { |
| 7548 |
cswritep = strcpya_k(cswritep, "FID\t"); |
| 7549 |
} |
| 7550 |
cswritep = strcpya_k(cswritep, "IID"); |
| 7551 |
const char* sample_ids = siip->sample_ids; |
| 7552 |
const char* sids = siip->sids; |
| 7553 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 7554 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 7555 |
const uint32_t col_sid = SidColIsRequired(sids, flags / kfSampleCountsColMaybesid); |
| 7556 |
if (col_sid) { |
| 7557 |
cswritep = strcpya_k(cswritep, "\tSID"); |
| 7558 |
} |
| 7559 |
const uint32_t col_sex = (flags / kfSampleCountsColSex) & 1; |
| 7560 |
if (col_sex) { |
| 7561 |
cswritep = strcpya_k(cswritep, "\tSEX"); |
| 7562 |
} |
| 7563 |
uint32_t type_bitarr; |
| 7564 |
memcpy(&type_bitarr, &flags, 4); |
| 7565 |
type_bitarr = type_bitarr / kfSampleCountsColHom; |
| 7566 |
{ |
| 7567 |
uint32_t types_left = type_bitarr; |
| 7568 |
while (types_left) { |
| 7569 |
*cswritep++ = '\t'; |
| 7570 |
cswritep = strcpya(cswritep, sample_counts_headers[ctzu32(types_left)]); |
| 7571 |
types_left = types_left & (types_left - 1); |
| 7572 |
} |
| 7573 |
} |
| 7574 |
AppendBinaryEoln(&cswritep); |
| 7575 |
uintptr_t sample_uidx_base = 0; |
| 7576 |
uintptr_t cur_bits = sample_include[0]; |
| 7577 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7578 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 7579 |
cswritep = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep); |
| 7580 |
if (col_sex) { |
| 7581 |
*cswritep++ = '\t'; |
| 7582 |
if (IsSet(sex_nm, sample_uidx)) { |
| 7583 |
*cswritep++ = '2' - IsSet(sex_male, sample_uidx); |
| 7584 |
} else { |
| 7585 |
cswritep = strcpya_k(cswritep, "NA"); |
| 7586 |
} |
| 7587 |
} |
| 7588 |
uint32_t types_left = type_bitarr; |
| 7589 |
while (types_left) { |
| 7590 |
const uint32_t type_idx = ctzu32(types_left); |
| 7591 |
*cswritep++ = '\t'; |
| 7592 |
cswritep = u32toa(final_counts[type_idx][sample_idx], cswritep); |
| 7593 |
types_left = types_left & (types_left - 1); |
| 7594 |
} |
| 7595 |
AppendBinaryEoln(&cswritep); |
| 7596 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 7597 |
goto SampleCounts_ret_WRITE_FAIL; |
| 7598 |
} |
| 7599 |
} |
| 7600 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 7601 |
goto SampleCounts_ret_WRITE_FAIL; |
| 7602 |
} |
| 7603 |
logprintfww("--sample-counts: Results written to %s .\n", outname); |
| 7604 |
} |
| 7605 |
while (0) { |
| 7606 |
SampleCounts_ret_NOMEM: |
| 7607 |
reterr = kPglRetNomem; |
| 7608 |
break; |
| 7609 |
SampleCounts_ret_PGR_FAIL: |
| 7610 |
PgenErrPrintN(reterr); |
| 7611 |
break; |
| 7612 |
SampleCounts_ret_WRITE_FAIL: |
| 7613 |
reterr = kPglRetWriteFail; |
| 7614 |
break; |
| 7615 |
SampleCounts_ret_THREAD_CREATE_FAIL: |
| 7616 |
reterr = kPglRetThreadCreateFail; |
| 7617 |
break; |
| 7618 |
} |
| 7619 |
SampleCounts_ret_1: |
| 7620 |
CleanupThreads(&tg); |
| 7621 |
CswriteCloseCond(&css, cswritep); |
| 7622 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 7623 |
pgfip->block_base = nullptr; |
| 7624 |
return reterr; |
| 7625 |
} |
| 7626 |
|
| 7627 |
static const Dosage kGenoToDosage[4] = {0, kDosageMid, kDosageMax, kDosageMissing}; |
| 7628 |
|
| 7629 |
typedef struct SdiffCountsStruct { |
| 7630 |
uint32_t missing_ct; // never includes halfmiss |
| 7631 |
uint32_t ibsmiss_ct; // can determine ibs2_ct from this |
| 7632 |
uint32_t ibsx_cts[2]; |
| 7633 |
uint32_t halfmiss_ct; |
| 7634 |
uint32_t diff_ct; // never includes halfmiss |
| 7635 |
} SdiffCounts; |
| 7636 |
|
| 7637 |
// Simplest case. May multithread this, add biallelic hardcall and other |
| 7638 |
// optimizations, etc. later. |
| 7639 |
PglErr SdiffCountsOnly(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const uint32_t* __restrict id_pairs, const uintptr_t* __restrict pair_sex_male, const uintptr_t* __restrict variant_include, const ChrInfo* cip, const uintptr_t* __restrict allele_idx_offsets, const SdiffInfo* sdip, uint32_t sample_ct, uint32_t variant_ct, uintptr_t id_pair_ct, PgenReader* simple_pgrp, SdiffCounts* sdiff_counts) { |
| 7640 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 7641 |
PglErr reterr = kPglRetSuccess; |
| 7642 |
{ |
| 7643 |
const uint32_t dosage_hap_tol = sdip->dosage_hap_tol; |
| 7644 |
const uint32_t dosage_needed = (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) && (dosage_hap_tol != kDosageMissing); |
| 7645 |
|
| 7646 |
// values unimportant if dosage_hap_tol == kDosageMissing |
| 7647 |
const uint32_t dosage_dip_tol = dosage_hap_tol / 2; |
| 7648 |
uint32_t dosage_sex_tols[2]; // for chrX |
| 7649 |
dosage_sex_tols[0] = dosage_dip_tol; |
| 7650 |
dosage_sex_tols[1] = dosage_hap_tol; |
| 7651 |
|
| 7652 |
const uint32_t ibs_needed = ((sdip->flags & kfSdiffCountsIbsNeeded) != kfSdiff0); |
| 7653 |
PgenVariant pgv; |
| 7654 |
if (unlikely(BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv))) { |
| 7655 |
goto SdiffCountsOnly_ret_NOMEM; |
| 7656 |
} |
| 7657 |
Dosage* dosage_buf = nullptr; |
| 7658 |
if (dosage_needed) { |
| 7659 |
// todo: multidosage |
| 7660 |
if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_buf))) { |
| 7661 |
goto SdiffCountsOnly_ret_NOMEM; |
| 7662 |
} |
| 7663 |
} |
| 7664 |
AlleleCode* allele_code_buf = nullptr; |
| 7665 |
if (allele_idx_offsets != nullptr) { |
| 7666 |
if (unlikely(bigstack_alloc_ac(2 * sample_ct, &allele_code_buf))) { |
| 7667 |
goto SdiffCountsOnly_ret_NOMEM; |
| 7668 |
} |
| 7669 |
} |
| 7670 |
pgv.patch_01_ct = 0; |
| 7671 |
pgv.patch_10_ct = 0; |
| 7672 |
pgv.dosage_ct = 0; |
| 7673 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 7674 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 7675 |
uintptr_t variant_uidx_base = 0; |
| 7676 |
uintptr_t cur_bits = variant_include[0]; |
| 7677 |
uint32_t is_autosomal_diploid = 0; |
| 7678 |
uint32_t is_x = 0; |
| 7679 |
uint32_t is_y = 0; |
| 7680 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 7681 |
uint32_t chr_end = 0; |
| 7682 |
uint32_t pct = 0; |
| 7683 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 7684 |
uint32_t allele_ct = 2; |
| 7685 |
fputs("--sample-diff counts-only: 0%", stdout); |
| 7686 |
fflush(stdout); |
| 7687 |
PgrSampleSubsetIndex pssi; |
| 7688 |
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi); |
| 7689 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 7690 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 7691 |
if (variant_uidx >= chr_end) { |
| 7692 |
do { |
| 7693 |
++chr_fo_idx; |
| 7694 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 7695 |
} while (variant_uidx >= chr_end); |
| 7696 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 7697 |
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx); |
| 7698 |
is_x = (chr_idx == x_code); |
| 7699 |
is_y = (chr_idx == y_code); |
| 7700 |
} |
| 7701 |
if (allele_idx_offsets) { |
| 7702 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 7703 |
} |
| 7704 |
if (allele_ct == 2) { |
| 7705 |
if (!dosage_needed) { |
| 7706 |
reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec); |
| 7707 |
} else { |
| 7708 |
reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct); |
| 7709 |
} |
| 7710 |
} else { |
| 7711 |
if (!dosage_needed) { |
| 7712 |
reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv); |
| 7713 |
} else { |
| 7714 |
reterr = PgrGetMD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv); |
| 7715 |
} |
| 7716 |
if ((!pgv.patch_01_ct) && (!pgv.patch_10_ct)) { |
| 7717 |
// todo: also check for multidosage |
| 7718 |
allele_ct = 2; |
| 7719 |
} |
| 7720 |
} |
| 7721 |
if (unlikely(reterr)) { |
| 7722 |
PgenErrPrintNV(reterr, variant_uidx); |
| 7723 |
goto SdiffCountsOnly_ret_1; |
| 7724 |
} |
| 7725 |
if (variant_idx >= next_print_variant_idx) { |
| 7726 |
if (pct > 10) { |
| 7727 |
putc_unlocked('\b', stdout); |
| 7728 |
} |
| 7729 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 7730 |
printf("\b\b%u%%", pct++); |
| 7731 |
fflush(stdout); |
| 7732 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 7733 |
} |
| 7734 |
if (allele_ct == 2) { |
| 7735 |
if (!pgv.dosage_ct) { |
| 7736 |
if (AllGenoEqual(pgv.genovec, sample_ct)) { |
| 7737 |
// don't need to do anything! |
| 7738 |
continue; |
| 7739 |
} |
| 7740 |
const uint32_t* id_pair_iter = id_pairs; |
| 7741 |
if (is_autosomal_diploid) { |
| 7742 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7743 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7744 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7745 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 7746 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 7747 |
if (hc1 == hc2) { |
| 7748 |
if (hc1 == 3) { |
| 7749 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 7750 |
sdiff_counts[pair_idx].ibsmiss_ct += 1; |
| 7751 |
} |
| 7752 |
continue; |
| 7753 |
} |
| 7754 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7755 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 7756 |
cur_counts->halfmiss_ct += 1; |
| 7757 |
cur_counts->ibsmiss_ct += 1; |
| 7758 |
continue; |
| 7759 |
} |
| 7760 |
cur_counts->diff_ct += 1; |
| 7761 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 7762 |
} |
| 7763 |
} else if (is_x) { |
| 7764 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7765 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7766 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7767 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 7768 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 7769 |
if (hc1 == hc2) { |
| 7770 |
if (hc1 == 3) { |
| 7771 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 7772 |
if (!IsSet(pair_sex_male, pair_idx)) { |
| 7773 |
sdiff_counts[pair_idx].ibsmiss_ct += 1; |
| 7774 |
} |
| 7775 |
} |
| 7776 |
continue; |
| 7777 |
} |
| 7778 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7779 |
const uint32_t is_male = IsSet(pair_sex_male, pair_idx); |
| 7780 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 7781 |
cur_counts->halfmiss_ct += 1; |
| 7782 |
cur_counts->ibsmiss_ct += !is_male; |
| 7783 |
continue; |
| 7784 |
} |
| 7785 |
cur_counts->diff_ct += 1; |
| 7786 |
if (!is_male) { |
| 7787 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 7788 |
} |
| 7789 |
} |
| 7790 |
} else { |
| 7791 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7792 |
// don't need pair_sex_nonfemale here since we prohibit |
| 7793 |
// unknown-sex pairs when chrY is present |
| 7794 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 7795 |
continue; |
| 7796 |
} |
| 7797 |
const uint32_t sample_idx1 = id_pairs[2 * pair_idx]; |
| 7798 |
const uint32_t sample_idx2 = id_pairs[2 * pair_idx + 1]; |
| 7799 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 7800 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 7801 |
if (hc1 == hc2) { |
| 7802 |
if (hc1 == 3) { |
| 7803 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 7804 |
} |
| 7805 |
continue; |
| 7806 |
} |
| 7807 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7808 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 7809 |
cur_counts->halfmiss_ct += 1; |
| 7810 |
continue; |
| 7811 |
} |
| 7812 |
cur_counts->diff_ct += 1; |
| 7813 |
} |
| 7814 |
} |
| 7815 |
} else { |
| 7816 |
// dosages present |
| 7817 |
const Dosage* dosage_read_iter = pgv.dosage_main; |
| 7818 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 7819 |
if (!IsSet(pgv.dosage_present, sample_idx)) { |
| 7820 |
dosage_buf[sample_idx] = kGenoToDosage[GetNyparrEntry(pgv.genovec, sample_idx)]; |
| 7821 |
} else { |
| 7822 |
dosage_buf[sample_idx] = *dosage_read_iter++; |
| 7823 |
} |
| 7824 |
} |
| 7825 |
const uint32_t* id_pair_iter = id_pairs; |
| 7826 |
if (is_autosomal_diploid) { |
| 7827 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7828 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7829 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7830 |
const uint32_t dosage1 = dosage_buf[sample_idx1]; |
| 7831 |
const uint32_t dosage2 = dosage_buf[sample_idx2]; |
| 7832 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7833 |
if (dosage1 == kDosageMissing) { |
| 7834 |
cur_counts->ibsmiss_ct += 1; |
| 7835 |
if (dosage2 == kDosageMissing) { |
| 7836 |
cur_counts->missing_ct += 1; |
| 7837 |
} else { |
| 7838 |
cur_counts->halfmiss_ct += 1; |
| 7839 |
} |
| 7840 |
continue; |
| 7841 |
} |
| 7842 |
if (dosage2 == kDosageMissing) { |
| 7843 |
cur_counts->halfmiss_ct += 1; |
| 7844 |
cur_counts->ibsmiss_ct += 1; |
| 7845 |
continue; |
| 7846 |
} |
| 7847 |
if (abs_i32(dosage1 - dosage2) > dosage_dip_tol) { |
| 7848 |
cur_counts->diff_ct += 1; |
| 7849 |
} |
| 7850 |
if (!ibs_needed) { |
| 7851 |
continue; |
| 7852 |
} |
| 7853 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 7854 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 7855 |
if (hc1 == hc2) { |
| 7856 |
continue; |
| 7857 |
} |
| 7858 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 7859 |
cur_counts->ibsmiss_ct += 1; |
| 7860 |
} |
| 7861 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 7862 |
} |
| 7863 |
} else if (is_x) { |
| 7864 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7865 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7866 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7867 |
const uint32_t dosage1 = dosage_buf[sample_idx1]; |
| 7868 |
const uint32_t dosage2 = dosage_buf[sample_idx2]; |
| 7869 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7870 |
if (dosage1 == kDosageMissing) { |
| 7871 |
cur_counts->ibsmiss_ct += 1; |
| 7872 |
if (dosage2 == kDosageMissing) { |
| 7873 |
cur_counts->missing_ct += 1; |
| 7874 |
} else { |
| 7875 |
cur_counts->halfmiss_ct += 1; |
| 7876 |
} |
| 7877 |
continue; |
| 7878 |
} |
| 7879 |
if (dosage2 == kDosageMissing) { |
| 7880 |
cur_counts->halfmiss_ct += 1; |
| 7881 |
cur_counts->ibsmiss_ct += 1; |
| 7882 |
continue; |
| 7883 |
} |
| 7884 |
const uint32_t is_male = IsSet(pair_sex_male, pair_idx); |
| 7885 |
if (abs_i32(dosage1 - dosage2) > dosage_sex_tols[is_male]) { |
| 7886 |
cur_counts->diff_ct += 1; |
| 7887 |
} |
| 7888 |
if ((!ibs_needed) || is_male) { |
| 7889 |
continue; |
| 7890 |
} |
| 7891 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 7892 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 7893 |
if (hc1 == hc2) { |
| 7894 |
continue; |
| 7895 |
} |
| 7896 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 7897 |
cur_counts->ibsmiss_ct += 1; |
| 7898 |
} |
| 7899 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 7900 |
} |
| 7901 |
} else { |
| 7902 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7903 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 7904 |
continue; |
| 7905 |
} |
| 7906 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7907 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7908 |
const uint32_t dosage1 = dosage_buf[sample_idx1]; |
| 7909 |
const uint32_t dosage2 = dosage_buf[sample_idx2]; |
| 7910 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7911 |
if (dosage1 == kDosageMissing) { |
| 7912 |
cur_counts->ibsmiss_ct += 1; |
| 7913 |
if (dosage2 == kDosageMissing) { |
| 7914 |
cur_counts->missing_ct += 1; |
| 7915 |
} else { |
| 7916 |
cur_counts->halfmiss_ct += 1; |
| 7917 |
} |
| 7918 |
continue; |
| 7919 |
} |
| 7920 |
if (dosage2 == kDosageMissing) { |
| 7921 |
cur_counts->halfmiss_ct += 1; |
| 7922 |
cur_counts->ibsmiss_ct += 1; |
| 7923 |
continue; |
| 7924 |
} |
| 7925 |
if (abs_i32(dosage1 - dosage2) > dosage_hap_tol) { |
| 7926 |
cur_counts->diff_ct += 1; |
| 7927 |
} |
| 7928 |
} |
| 7929 |
} |
| 7930 |
} |
| 7931 |
} else { |
| 7932 |
// multiallelic |
| 7933 |
if (!pgv.dosage_ct) { |
| 7934 |
PglMultiallelicSparseToDenseMiss(&pgv, sample_ct, allele_code_buf); |
| 7935 |
const uint32_t* id_pair_iter = id_pairs; |
| 7936 |
if (is_autosomal_diploid) { |
| 7937 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7938 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7939 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7940 |
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1]; |
| 7941 |
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1]; |
| 7942 |
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2]; |
| 7943 |
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1]; |
| 7944 |
if ((ac11 == ac21) && (ac12 == ac22)) { |
| 7945 |
if (ac11 == kMissingAlleleCode) { |
| 7946 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 7947 |
sdiff_counts[pair_idx].ibsmiss_ct += 1; |
| 7948 |
} |
| 7949 |
continue; |
| 7950 |
} |
| 7951 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7952 |
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) { |
| 7953 |
cur_counts->halfmiss_ct += 1; |
| 7954 |
cur_counts->ibsmiss_ct += 1; |
| 7955 |
continue; |
| 7956 |
} |
| 7957 |
cur_counts->diff_ct += 1; |
| 7958 |
if (ibs_needed) { |
| 7959 |
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1; |
| 7960 |
} |
| 7961 |
} |
| 7962 |
} else if (is_x) { |
| 7963 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7964 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 7965 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 7966 |
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1]; |
| 7967 |
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1]; |
| 7968 |
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2]; |
| 7969 |
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1]; |
| 7970 |
if ((ac11 == ac21) && (ac12 == ac22)) { |
| 7971 |
if (ac11 == kMissingAlleleCode) { |
| 7972 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 7973 |
if (!IsSet(pair_sex_male, pair_idx)) { |
| 7974 |
sdiff_counts[pair_idx].ibsmiss_ct += 1; |
| 7975 |
} |
| 7976 |
} |
| 7977 |
continue; |
| 7978 |
} |
| 7979 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 7980 |
const uint32_t is_male = IsSet(pair_sex_male, pair_idx); |
| 7981 |
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) { |
| 7982 |
cur_counts->halfmiss_ct += 1; |
| 7983 |
cur_counts->ibsmiss_ct += !is_male; |
| 7984 |
continue; |
| 7985 |
} |
| 7986 |
cur_counts->diff_ct += 1; |
| 7987 |
if (ibs_needed && (!is_male)) { |
| 7988 |
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1; |
| 7989 |
} |
| 7990 |
} |
| 7991 |
} else { |
| 7992 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 7993 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 7994 |
continue; |
| 7995 |
} |
| 7996 |
const uint32_t sample_idx1 = id_pairs[2 * pair_idx]; |
| 7997 |
const uint32_t sample_idx2 = id_pairs[2 * pair_idx + 1]; |
| 7998 |
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1]; |
| 7999 |
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1]; |
| 8000 |
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2]; |
| 8001 |
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1]; |
| 8002 |
if ((ac11 == ac21) && (ac12 == ac22)) { |
| 8003 |
if (ac11 == kMissingAlleleCode) { |
| 8004 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 8005 |
} |
| 8006 |
continue; |
| 8007 |
} |
| 8008 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 8009 |
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) { |
| 8010 |
cur_counts->halfmiss_ct += 1; |
| 8011 |
} |
| 8012 |
cur_counts->diff_ct += 1; |
| 8013 |
} |
| 8014 |
} |
| 8015 |
} else { |
| 8016 |
// multiallelic-dosage; todo |
| 8017 |
exit(S_CAST(int32_t, kPglRetInternalError)); |
| 8018 |
} |
| 8019 |
} |
| 8020 |
} |
| 8021 |
if (pct > 10) { |
| 8022 |
putc_unlocked('\b', stdout); |
| 8023 |
} |
| 8024 |
fputs("\b\b", stdout); |
| 8025 |
logputs("done.\n"); |
| 8026 |
} |
| 8027 |
while (0) { |
| 8028 |
SdiffCountsOnly_ret_NOMEM: |
| 8029 |
reterr = kPglRetNomem; |
| 8030 |
break; |
| 8031 |
PgenErrPrintN(reterr); |
| 8032 |
break; |
| 8033 |
} |
| 8034 |
SdiffCountsOnly_ret_1: |
| 8035 |
BigstackReset(bigstack_mark); |
| 8036 |
return reterr; |
| 8037 |
} |
| 8038 |
|
| 8039 |
void AppendSdiffHeaderLine(SdiffFlags flags, uint32_t col_provref, uint32_t col_fid, uint32_t col_sid, uint32_t dosage_reported, char** cswritepp) { |
| 8040 |
char* cswritep = *cswritepp; |
| 8041 |
*cswritep++ = '#'; |
| 8042 |
if (flags & kfSdiffColChrom) { |
| 8043 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 8044 |
} |
| 8045 |
if (flags & kfSdiffColPos) { |
| 8046 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 8047 |
} |
| 8048 |
cswritep = strcpya_k(cswritep, "ID"); |
| 8049 |
if (flags & kfSdiffColRef) { |
| 8050 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 8051 |
} |
| 8052 |
if (flags & kfSdiffColAlt) { |
| 8053 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 8054 |
} |
| 8055 |
if (col_provref) { |
| 8056 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 8057 |
} |
| 8058 |
if (flags & kfSdiffColId) { |
| 8059 |
if (col_fid) { |
| 8060 |
cswritep = strcpya_k(cswritep, "\tFID1"); |
| 8061 |
} |
| 8062 |
cswritep = strcpya_k(cswritep, "\tIID1"); |
| 8063 |
if (col_sid) { |
| 8064 |
cswritep = strcpya_k(cswritep, "\tSID1"); |
| 8065 |
} |
| 8066 |
if (col_fid) { |
| 8067 |
cswritep = strcpya_k(cswritep, "\tFID2"); |
| 8068 |
} |
| 8069 |
cswritep = strcpya_k(cswritep, "\tIID2"); |
| 8070 |
if (col_sid) { |
| 8071 |
cswritep = strcpya_k(cswritep, "\tSID2"); |
| 8072 |
} |
| 8073 |
} |
| 8074 |
if (flags & kfSdiffColGeno) { |
| 8075 |
if (!dosage_reported) { |
| 8076 |
cswritep = strcpya_k(cswritep, "\tGT1\tGT2"); |
| 8077 |
} else { |
| 8078 |
cswritep = strcpya_k(cswritep, "\tDS1\tDS2"); |
| 8079 |
} |
| 8080 |
} |
| 8081 |
*cswritepp = cswritep; |
| 8082 |
AppendBinaryEoln(cswritepp); |
| 8083 |
} |
| 8084 |
|
| 8085 |
typedef struct SdiffWriteContextStruct { |
| 8086 |
char* collapsed_sample_fmtids; |
| 8087 |
char* chr_buf; |
| 8088 |
const uint32_t* variant_bps; |
| 8089 |
const char* const* variant_ids; |
| 8090 |
SdiffFlags flags; |
| 8091 |
uintptr_t max_sample_fmtid_blen; |
| 8092 |
uint32_t chr_buf_blen; |
| 8093 |
} SdiffWriteContext; |
| 8094 |
|
| 8095 |
BoolErr AppendSdiffPregenoFields(const SdiffWriteContext* swcp, const char* const* cur_alleles, uint32_t sample_idx1, uint32_t sample_idx2, uint32_t variant_uidx, uint32_t allele_ct, uint32_t col_provref, uint32_t provref, CompressStreamState* cssp, char** cswritepp) { |
| 8096 |
char* cswritep = *cswritepp; |
| 8097 |
if (swcp->chr_buf) { |
| 8098 |
cswritep = memcpya(cswritep, swcp->chr_buf, swcp->chr_buf_blen); |
| 8099 |
} |
| 8100 |
if (swcp->variant_bps) { |
| 8101 |
cswritep = u32toa_x(swcp->variant_bps[variant_uidx], '\t', cswritep); |
| 8102 |
} |
| 8103 |
cswritep = strcpya(cswritep, swcp->variant_ids[variant_uidx]); |
| 8104 |
if (swcp->flags & kfSdiffColRef) { |
| 8105 |
*cswritep++ = '\t'; |
| 8106 |
const char* cur_allele = cur_alleles[0]; |
| 8107 |
const uint32_t allele_slen = strlen(cur_allele); |
| 8108 |
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) { |
| 8109 |
// might not need this assignment, but play it safe for now |
| 8110 |
*cswritepp = cswritep; |
| 8111 |
return 1; |
| 8112 |
} |
| 8113 |
} |
| 8114 |
if (swcp->flags & kfSdiffColAlt) { |
| 8115 |
*cswritep++ = '\t'; |
| 8116 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 8117 |
const char* cur_allele = cur_alleles[allele_idx]; |
| 8118 |
const uint32_t allele_slen = strlen(cur_allele); |
| 8119 |
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) { |
| 8120 |
*cswritepp = cswritep; |
| 8121 |
return 1; |
| 8122 |
} |
| 8123 |
*cswritep++ = ','; |
| 8124 |
} |
| 8125 |
--cswritep; |
| 8126 |
} |
| 8127 |
if (col_provref) { |
| 8128 |
*cswritep++ = '\t'; |
| 8129 |
*cswritep++ = provref? 'Y' : 'N'; |
| 8130 |
} |
| 8131 |
if (swcp->collapsed_sample_fmtids) { |
| 8132 |
*cswritep++ = '\t'; |
| 8133 |
cswritep = strcpyax(cswritep, &(swcp->collapsed_sample_fmtids[sample_idx1 * swcp->max_sample_fmtid_blen]), '\t'); |
| 8134 |
cswritep = strcpya(cswritep, &(swcp->collapsed_sample_fmtids[sample_idx2 * swcp->max_sample_fmtid_blen])); |
| 8135 |
} |
| 8136 |
*cswritepp = cswritep; |
| 8137 |
return 0; |
| 8138 |
} |
| 8139 |
|
| 8140 |
PglErr SdiffMainBatch(const uintptr_t* __restrict sample_include, const uint32_t* __restrict sample_include_cumulative_popcounts, const SampleIdInfo* siip, const uint32_t* __restrict id_pairs, const uintptr_t* __restrict pair_sex_male, const uintptr_t* __restrict variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* __restrict allele_idx_offsets, const char* const* allele_storage, const SdiffInfo* sdip, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uintptr_t id_pair_ct, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end, SdiffCounts* sdiff_counts) { |
| 8141 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 8142 |
char** cswritep_arr = nullptr; |
| 8143 |
CompressStreamState* css_arr = nullptr; |
| 8144 |
const SdiffFlags flags = sdip->flags; |
| 8145 |
const uint32_t is_pairwise = (flags / kfSdiffPairwise) & 1; |
| 8146 |
const uintptr_t file_ct = is_pairwise? id_pair_ct : 1; |
| 8147 |
PglErr reterr = kPglRetSuccess; |
| 8148 |
{ |
| 8149 |
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSdiffColMaybefid); |
| 8150 |
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfSdiffColMaybesid); |
| 8151 |
SdiffWriteContext swc; |
| 8152 |
if (unlikely(CollapsedSampleFmtidInitAlloc(sample_include, siip, sample_ct, col_fid, col_sid, &swc.collapsed_sample_fmtids, &swc.max_sample_fmtid_blen))) { |
| 8153 |
goto SdiffMainBatch_ret_NOMEM; |
| 8154 |
} |
| 8155 |
swc.chr_buf = nullptr; |
| 8156 |
if (flags & kfSdiffColChrom) { |
| 8157 |
const uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 8158 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &swc.chr_buf))) { |
| 8159 |
goto SdiffMainBatch_ret_NOMEM; |
| 8160 |
} |
| 8161 |
} |
| 8162 |
if (!(flags & kfSdiffColPos)) { |
| 8163 |
swc.variant_bps = nullptr; |
| 8164 |
} else { |
| 8165 |
swc.variant_bps = variant_bps; |
| 8166 |
} |
| 8167 |
swc.variant_ids = variant_ids; |
| 8168 |
if (unlikely(bigstack_calloc_cp(file_ct, &cswritep_arr) || |
| 8169 |
BIGSTACK_ALLOC_X(CompressStreamState, file_ct, &css_arr))) { |
| 8170 |
goto SdiffMainBatch_ret_NOMEM; |
| 8171 |
} |
| 8172 |
swc.flags = flags; |
| 8173 |
swc.chr_buf_blen = 0; |
| 8174 |
for (uintptr_t fidx = 0; fidx != id_pair_ct; ++fidx) { |
| 8175 |
PreinitCstream(&(css_arr[fidx])); |
| 8176 |
} |
| 8177 |
const uintptr_t* nonref_flags = PgrGetNonrefFlags(simple_pgrp); |
| 8178 |
const uint32_t all_nonref = (PgrGetGflags(simple_pgrp) & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 8179 |
const uint32_t col_provref = (flags & kfSdiffColRef) && ProvrefCol(variant_include, nonref_flags, flags / kfSdiffColMaybeprovref, raw_variant_ct, all_nonref); |
| 8180 |
const uint32_t output_zst = (flags / kfSdiffZs) & 1; |
| 8181 |
// ".sdiff" + terminating null = 7 bytes |
| 8182 |
const uintptr_t fname_extrachar_limit = kPglFnamesize - 7 - (output_zst * 4) - S_CAST(uintptr_t, outname_end - outname); |
| 8183 |
const char fname_id_delim = sdip->fname_id_delim; |
| 8184 |
const uint32_t dosage_hap_tol = sdip->dosage_hap_tol; |
| 8185 |
const uint32_t dosage_reported = (dosage_hap_tol != kDosageMissing); |
| 8186 |
const uint32_t dosage_needed = (PgrGetGflags(simple_pgrp) & kfPgenGlobalDosagePresent) && dosage_reported; |
| 8187 |
if (is_pairwise) { |
| 8188 |
const uint32_t* id_pair_iter = id_pairs; |
| 8189 |
const uint32_t stream_thread_ct = (max_thread_ct > (2 * id_pair_ct))? ((max_thread_ct - 1) / id_pair_ct) : 1; |
| 8190 |
*outname_end = '.'; |
| 8191 |
for (uintptr_t fidx = 0; fidx != id_pair_ct; ++fidx) { |
| 8192 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 8193 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 8194 |
const char* sample_fmtid1 = &(swc.collapsed_sample_fmtids[sample_idx1 * swc.max_sample_fmtid_blen]); |
| 8195 |
const char* sample_fmtid2 = &(swc.collapsed_sample_fmtids[sample_idx2 * swc.max_sample_fmtid_blen]); |
| 8196 |
const uint32_t slen1 = strlen(sample_fmtid1); |
| 8197 |
const uint32_t slen2 = strlen(sample_fmtid2); |
| 8198 |
if (unlikely(slen1 + slen2 + 2 > fname_extrachar_limit)) { |
| 8199 |
logputs("\n"); |
| 8200 |
logerrputs("Error: Sample ID and/or --out argument too long for --sample-diff pairwise\nmode.\n"); |
| 8201 |
goto SdiffMainBatch_ret_INCONSISTENT_INPUT; |
| 8202 |
} |
| 8203 |
char* fname_iter = &(outname_end[1]); |
| 8204 |
// note that this copies tab(s); replace them with fname_id_delim |
| 8205 |
fname_iter = memcpya(fname_iter, sample_fmtid1, slen1); |
| 8206 |
char* tab_iter = &(outname_end[2]); |
| 8207 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8208 |
if (tab_iter) { |
| 8209 |
*tab_iter++ = fname_id_delim; |
| 8210 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8211 |
if (tab_iter) { |
| 8212 |
*tab_iter = fname_id_delim; |
| 8213 |
} |
| 8214 |
} |
| 8215 |
*fname_iter++ = '.'; |
| 8216 |
tab_iter = &(fname_iter[1]); |
| 8217 |
fname_iter = memcpya(fname_iter, sample_fmtid2, slen2); |
| 8218 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8219 |
if (tab_iter) { |
| 8220 |
*tab_iter++ = fname_id_delim; |
| 8221 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8222 |
if (tab_iter) { |
| 8223 |
*tab_iter = fname_id_delim; |
| 8224 |
} |
| 8225 |
} |
| 8226 |
fname_iter = strcpya_k(fname_iter, ".sdiff"); |
| 8227 |
if (output_zst) { |
| 8228 |
fname_iter = strcpya_k(fname_iter, ".zst"); |
| 8229 |
} |
| 8230 |
*fname_iter = '\0'; |
| 8231 |
reterr = InitCstreamAlloc(outname, 0, output_zst, stream_thread_ct, kCompressStreamBlock + kMaxMediumLine, &(css_arr[fidx]), &(cswritep_arr[fidx])); |
| 8232 |
if (unlikely(reterr)) { |
| 8233 |
goto SdiffMainBatch_ret_1; |
| 8234 |
} |
| 8235 |
AppendSdiffHeaderLine(flags, col_provref, col_fid, col_sid, dosage_reported, &(cswritep_arr[fidx])); |
| 8236 |
} |
| 8237 |
} else { |
| 8238 |
char* fname_iter = outname_end; |
| 8239 |
const uint32_t stream_thread_ct = (max_thread_ct > 1)? (max_thread_ct - 1) : 1; |
| 8240 |
if (flags & kfSdiffOneBase) { |
| 8241 |
const uint32_t base_sample_idx = id_pairs[0]; |
| 8242 |
const char* sample_fmtid = &(swc.collapsed_sample_fmtids[base_sample_idx * swc.max_sample_fmtid_blen]); |
| 8243 |
const uint32_t base_slen = strlen(sample_fmtid); |
| 8244 |
if (unlikely(base_slen >= fname_extrachar_limit)) { |
| 8245 |
logputs("\n"); |
| 8246 |
logerrputs("Error: Sample ID and/or --out argument too long for --sample-diff base= mode.\n"); |
| 8247 |
goto SdiffMainBatch_ret_INCONSISTENT_INPUT; |
| 8248 |
} |
| 8249 |
*fname_iter++ = '.'; |
| 8250 |
char* tab_iter = &(fname_iter[1]); |
| 8251 |
fname_iter = memcpya(fname_iter, sample_fmtid, base_slen); |
| 8252 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8253 |
if (tab_iter) { |
| 8254 |
*tab_iter++ = fname_id_delim; |
| 8255 |
tab_iter = S_CAST(char*, memchr(tab_iter, '\t', fname_iter - tab_iter)); |
| 8256 |
if (tab_iter) { |
| 8257 |
*tab_iter = fname_id_delim; |
| 8258 |
} |
| 8259 |
} |
| 8260 |
} |
| 8261 |
fname_iter = strcpya_k(fname_iter, ".sdiff"); |
| 8262 |
if (output_zst) { |
| 8263 |
fname_iter = strcpya_k(fname_iter, ".zst"); |
| 8264 |
} |
| 8265 |
*fname_iter = '\0'; |
| 8266 |
reterr = InitCstreamAlloc(outname, 0, output_zst, stream_thread_ct, kCompressStreamBlock + kMaxMediumLine, &(css_arr[0]), &(cswritep_arr[0])); |
| 8267 |
if (unlikely(reterr)) { |
| 8268 |
goto SdiffMainBatch_ret_1; |
| 8269 |
} |
| 8270 |
AppendSdiffHeaderLine(flags, col_provref, col_fid, col_sid, dosage_reported, &(cswritep_arr[0])); |
| 8271 |
} |
| 8272 |
if (!(flags & kfSdiffColId)) { |
| 8273 |
swc.collapsed_sample_fmtids = nullptr; |
| 8274 |
} |
| 8275 |
|
| 8276 |
// values unimportant if dosage_hap_tol == kDosageMissing |
| 8277 |
const uint32_t dosage_dip_tol = dosage_hap_tol / 2; |
| 8278 |
uint32_t dosage_sex_tols[2]; // for chrX |
| 8279 |
dosage_sex_tols[0] = dosage_dip_tol; |
| 8280 |
dosage_sex_tols[1] = dosage_hap_tol; |
| 8281 |
|
| 8282 |
const uint32_t ibs_needed = ((sdip->flags & kfSdiffCountsIbsNeeded) != kfSdiff0); |
| 8283 |
PgenVariant pgv; |
| 8284 |
if (unlikely(BigstackAllocPgv(sample_ct, allele_idx_offsets != nullptr, dosage_needed? kfPgenGlobalDosagePresent : kfPgenGlobal0, &pgv))) { |
| 8285 |
goto SdiffMainBatch_ret_NOMEM; |
| 8286 |
} |
| 8287 |
Dosage* dosage_buf = nullptr; |
| 8288 |
if (dosage_needed) { |
| 8289 |
// todo: multidosage |
| 8290 |
if (unlikely(bigstack_alloc_dosage(sample_ct, &dosage_buf))) { |
| 8291 |
goto SdiffMainBatch_ret_NOMEM; |
| 8292 |
} |
| 8293 |
} |
| 8294 |
AlleleCode* allele_code_buf = nullptr; |
| 8295 |
if (allele_idx_offsets != nullptr) { |
| 8296 |
if (unlikely(bigstack_alloc_ac(2 * sample_ct, &allele_code_buf))) { |
| 8297 |
goto SdiffMainBatch_ret_NOMEM; |
| 8298 |
} |
| 8299 |
} |
| 8300 |
pgv.patch_01_ct = 0; |
| 8301 |
pgv.patch_10_ct = 0; |
| 8302 |
pgv.dosage_ct = 0; |
| 8303 |
// assumes little-endian |
| 8304 |
// diploid GT: \t0/0 \t0/1 \t1/1 \t./. |
| 8305 |
// diploid DS: \t0 \t1 \t2 \t. |
| 8306 |
// haploid GT: \t0 \t0/1 \t1 \t. |
| 8307 |
// haploid DS: \t0 \t0.5 \t1 \t. |
| 8308 |
// '!' = ascii 33, should never appear in output |
| 8309 |
const uint32_t gt_text[8] = {0x302f3009, 0x312f3009, 0x312f3109, 0x2e2f2e09, 0x21213009, 0x312f3009, 0x21213109, 0x21212e09}; |
| 8310 |
const uint32_t ds_text[8] = {0x21213009, 0x21213109, 0x21213209, 0x21212e09, 0x21213009, 0x352e3009, 0x21213109, 0x21212e09}; |
| 8311 |
const uint32_t* hc_text = dosage_reported? ds_text : gt_text; |
| 8312 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 8313 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 8314 |
const uint32_t include_missing = (flags / kfSdiffIncludeMissing) & 1; |
| 8315 |
uintptr_t variant_uidx_base = 0; |
| 8316 |
uintptr_t cur_bits = variant_include[0]; |
| 8317 |
uint32_t is_autosomal_diploid = 0; |
| 8318 |
uint32_t is_x = 0; |
| 8319 |
uint32_t is_y = 0; |
| 8320 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 8321 |
uint32_t chr_end = 0; |
| 8322 |
uint32_t pct = 0; |
| 8323 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 8324 |
uint32_t allele_ct = 2; |
| 8325 |
PgrSampleSubsetIndex pssi; |
| 8326 |
PgrSetSampleSubsetIndex(sample_include_cumulative_popcounts, simple_pgrp, &pssi); |
| 8327 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 8328 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 8329 |
if (variant_uidx >= chr_end) { |
| 8330 |
do { |
| 8331 |
++chr_fo_idx; |
| 8332 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 8333 |
} while (variant_uidx >= chr_end); |
| 8334 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 8335 |
is_autosomal_diploid = !IsSet(cip->haploid_mask, chr_idx); |
| 8336 |
is_x = (chr_idx == x_code); |
| 8337 |
is_y = (chr_idx == y_code); |
| 8338 |
if (swc.chr_buf) { |
| 8339 |
char* chr_name_end = chrtoa(cip, chr_idx, swc.chr_buf); |
| 8340 |
*chr_name_end = '\t'; |
| 8341 |
swc.chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - swc.chr_buf); |
| 8342 |
} |
| 8343 |
} |
| 8344 |
uintptr_t allele_idx_offset_base = variant_uidx * 2; |
| 8345 |
if (allele_idx_offsets) { |
| 8346 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 8347 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 8348 |
} |
| 8349 |
if (allele_ct == 2) { |
| 8350 |
if (!dosage_needed) { |
| 8351 |
reterr = PgrGet(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec); |
| 8352 |
} else { |
| 8353 |
reterr = PgrGetD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, pgv.genovec, pgv.dosage_present, pgv.dosage_main, &pgv.dosage_ct); |
| 8354 |
} |
| 8355 |
} else { |
| 8356 |
if (!dosage_needed) { |
| 8357 |
reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv); |
| 8358 |
} else { |
| 8359 |
reterr = PgrGetMD(sample_include, pssi, sample_ct, variant_uidx, simple_pgrp, &pgv); |
| 8360 |
} |
| 8361 |
} |
| 8362 |
if (unlikely(reterr)) { |
| 8363 |
PgenErrPrintNV(reterr, variant_uidx); |
| 8364 |
goto SdiffMainBatch_ret_1; |
| 8365 |
} |
| 8366 |
if (variant_idx >= next_print_variant_idx) { |
| 8367 |
if (pct > 10) { |
| 8368 |
putc_unlocked('\b', stdout); |
| 8369 |
} |
| 8370 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 8371 |
printf("\b\b%u%%", pct++); |
| 8372 |
fflush(stdout); |
| 8373 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 8374 |
} |
| 8375 |
const uint32_t provref = (all_nonref || (nonref_flags && IsSet(nonref_flags, variant_uidx))); |
| 8376 |
if (allele_ct == 2) { |
| 8377 |
if (!pgv.dosage_ct) { |
| 8378 |
if (AllGenoEqual(pgv.genovec, sample_ct)) { |
| 8379 |
// don't need to do anything! |
| 8380 |
continue; |
| 8381 |
} |
| 8382 |
const uint32_t* id_pair_iter = id_pairs; |
| 8383 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 8384 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 8385 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 8386 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 8387 |
continue; |
| 8388 |
} |
| 8389 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 8390 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 8391 |
if (hc1 == hc2) { |
| 8392 |
if (hc1 == 3) { |
| 8393 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 8394 |
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8395 |
} |
| 8396 |
continue; |
| 8397 |
} |
| 8398 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 8399 |
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8400 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 8401 |
cur_counts->halfmiss_ct += 1; |
| 8402 |
cur_counts->ibsmiss_ct += is_diploid_pair; |
| 8403 |
if (!include_missing) { |
| 8404 |
continue; |
| 8405 |
} |
| 8406 |
} else { |
| 8407 |
cur_counts->diff_ct += 1; |
| 8408 |
if (is_diploid_pair) { |
| 8409 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 8410 |
} |
| 8411 |
} |
| 8412 |
const uintptr_t fidx = is_pairwise? pair_idx : 0; |
| 8413 |
char* cswritep = cswritep_arr[fidx]; |
| 8414 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 8415 |
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) { |
| 8416 |
// might not need this assignment, but play it safe for now |
| 8417 |
cswritep_arr[fidx] = cswritep; |
| 8418 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8419 |
} |
| 8420 |
if (flags & kfSdiffColGeno) { |
| 8421 |
if (is_diploid_pair) { |
| 8422 |
cswritep = memcpya(cswritep, &(hc_text[hc1]), 4); |
| 8423 |
cswritep -= 2 * dosage_reported; |
| 8424 |
cswritep = memcpya(cswritep, &(hc_text[hc2]), 4); |
| 8425 |
cswritep -= 2 * dosage_reported; |
| 8426 |
} else { |
| 8427 |
cswritep = memcpya(cswritep, &(hc_text[hc1 + 4]), 4); |
| 8428 |
cswritep -= 2 * (hc1 != 1); |
| 8429 |
cswritep = memcpya(cswritep, &(hc_text[hc2 + 4]), 4); |
| 8430 |
cswritep -= 2 * (hc2 != 1); |
| 8431 |
} |
| 8432 |
} |
| 8433 |
AppendBinaryEoln(&cswritep); |
| 8434 |
cswritep_arr[fidx] = cswritep; |
| 8435 |
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) { |
| 8436 |
cswritep_arr[fidx] = cswritep; |
| 8437 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8438 |
} |
| 8439 |
} |
| 8440 |
} else { |
| 8441 |
// dosages present |
| 8442 |
const Dosage* dosage_read_iter = pgv.dosage_main; |
| 8443 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 8444 |
if (!IsSet(pgv.dosage_present, sample_idx)) { |
| 8445 |
dosage_buf[sample_idx] = kGenoToDosage[GetNyparrEntry(pgv.genovec, sample_idx)]; |
| 8446 |
} else { |
| 8447 |
dosage_buf[sample_idx] = *dosage_read_iter++; |
| 8448 |
} |
| 8449 |
} |
| 8450 |
const uint32_t* id_pair_iter = id_pairs; |
| 8451 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 8452 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 8453 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 8454 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 8455 |
continue; |
| 8456 |
} |
| 8457 |
const uint32_t dosage1 = dosage_buf[sample_idx1]; |
| 8458 |
const uint32_t dosage2 = dosage_buf[sample_idx2]; |
| 8459 |
if (dosage1 == dosage2) { |
| 8460 |
if (dosage1 == kDosageMissing) { |
| 8461 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 8462 |
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8463 |
} |
| 8464 |
continue; |
| 8465 |
} |
| 8466 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 8467 |
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8468 |
if ((dosage1 == kDosageMissing) || (dosage2 == kDosageMissing)) { |
| 8469 |
cur_counts->halfmiss_ct += 1; |
| 8470 |
cur_counts->ibsmiss_ct += is_diploid_pair; |
| 8471 |
if (!include_missing) { |
| 8472 |
continue; |
| 8473 |
} |
| 8474 |
} else { |
| 8475 |
if (ibs_needed && is_diploid_pair) { |
| 8476 |
const uintptr_t hc1 = GetNyparrEntry(pgv.genovec, sample_idx1); |
| 8477 |
const uintptr_t hc2 = GetNyparrEntry(pgv.genovec, sample_idx2); |
| 8478 |
if (hc1 != hc2) { |
| 8479 |
if ((hc1 == 3) || (hc2 == 3)) { |
| 8480 |
cur_counts->ibsmiss_ct += 1; |
| 8481 |
} |
| 8482 |
cur_counts->ibsx_cts[(hc1 | hc2) & 1] += 1; |
| 8483 |
} |
| 8484 |
} |
| 8485 |
if (abs_i32(dosage1 - dosage2) <= dosage_sex_tols[!is_diploid_pair]) { |
| 8486 |
continue; |
| 8487 |
} |
| 8488 |
cur_counts->diff_ct += 1; |
| 8489 |
} |
| 8490 |
const uintptr_t fidx = is_pairwise? pair_idx : 0; |
| 8491 |
char* cswritep = cswritep_arr[fidx]; |
| 8492 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 8493 |
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) { |
| 8494 |
cswritep_arr[fidx] = cswritep; |
| 8495 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8496 |
} |
| 8497 |
if (flags & kfSdiffColGeno) { |
| 8498 |
*cswritep++ = '\t'; |
| 8499 |
if (dosage1 == kDosageMissing) { |
| 8500 |
*cswritep++ = '.'; |
| 8501 |
} else if (is_diploid_pair) { |
| 8502 |
cswritep = PrintSmallDosage(dosage1, cswritep); |
| 8503 |
} else { |
| 8504 |
cswritep = PrintHaploidDosage(dosage1, cswritep); |
| 8505 |
} |
| 8506 |
*cswritep++ = '\t'; |
| 8507 |
if (dosage2 == kDosageMissing) { |
| 8508 |
*cswritep++ = '.'; |
| 8509 |
} else if (is_diploid_pair) { |
| 8510 |
cswritep = PrintSmallDosage(dosage2, cswritep); |
| 8511 |
} else { |
| 8512 |
cswritep = PrintHaploidDosage(dosage2, cswritep); |
| 8513 |
} |
| 8514 |
} |
| 8515 |
AppendBinaryEoln(&cswritep); |
| 8516 |
cswritep_arr[fidx] = cswritep; |
| 8517 |
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) { |
| 8518 |
cswritep_arr[fidx] = cswritep; |
| 8519 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8520 |
} |
| 8521 |
} |
| 8522 |
} |
| 8523 |
} else { |
| 8524 |
// multiallelic |
| 8525 |
if (!pgv.dosage_ct) { |
| 8526 |
PglMultiallelicSparseToDenseMiss(&pgv, sample_ct, allele_code_buf); |
| 8527 |
const uint32_t* id_pair_iter = id_pairs; |
| 8528 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 8529 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 8530 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 8531 |
if (is_y && (!IsSet(pair_sex_male, pair_idx))) { |
| 8532 |
continue; |
| 8533 |
} |
| 8534 |
const AlleleCode ac11 = allele_code_buf[2 * sample_idx1]; |
| 8535 |
const AlleleCode ac12 = allele_code_buf[2 * sample_idx1 + 1]; |
| 8536 |
const AlleleCode ac21 = allele_code_buf[2 * sample_idx2]; |
| 8537 |
const AlleleCode ac22 = allele_code_buf[2 * sample_idx2 + 1]; |
| 8538 |
if ((ac11 == ac21) && (ac12 == ac22)) { |
| 8539 |
if (ac11 == kMissingAlleleCode) { |
| 8540 |
sdiff_counts[pair_idx].missing_ct += 1; |
| 8541 |
sdiff_counts[pair_idx].ibsmiss_ct += is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8542 |
} |
| 8543 |
continue; |
| 8544 |
} |
| 8545 |
SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 8546 |
const uint32_t is_diploid_pair = is_autosomal_diploid || (is_x && (!IsSet(pair_sex_male, pair_idx))); |
| 8547 |
if ((ac11 == kMissingAlleleCode) || (ac21 == kMissingAlleleCode)) { |
| 8548 |
cur_counts->halfmiss_ct += 1; |
| 8549 |
cur_counts->ibsmiss_ct += is_diploid_pair; |
| 8550 |
if (!include_missing) { |
| 8551 |
continue; |
| 8552 |
} |
| 8553 |
} else { |
| 8554 |
cur_counts->diff_ct += 1; |
| 8555 |
if (ibs_needed && is_diploid_pair) { |
| 8556 |
cur_counts->ibsx_cts[(ac11 == ac21) || (ac11 == ac22) || (ac12 == ac21) || (ac12 == ac22)] += 1; |
| 8557 |
} |
| 8558 |
} |
| 8559 |
const uintptr_t fidx = is_pairwise? pair_idx : 0; |
| 8560 |
char* cswritep = cswritep_arr[fidx]; |
| 8561 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 8562 |
if (unlikely(AppendSdiffPregenoFields(&swc, cur_alleles, sample_idx1, sample_idx2, variant_uidx, allele_ct, col_provref, provref, &(css_arr[fidx]), &cswritep))) { |
| 8563 |
// might not need this assignment, but play it safe for now |
| 8564 |
cswritep_arr[fidx] = cswritep; |
| 8565 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8566 |
} |
| 8567 |
if (flags & kfSdiffColGeno) { |
| 8568 |
*cswritep++ = '\t'; |
| 8569 |
if (is_diploid_pair) { |
| 8570 |
if (!dosage_reported) { |
| 8571 |
if (ac11 == kMissingAlleleCode) { |
| 8572 |
cswritep = strcpya_k(cswritep, "./."); |
| 8573 |
} else { |
| 8574 |
cswritep = u32toa_x(ac11, '/', cswritep); |
| 8575 |
cswritep = u32toa(ac12, cswritep); |
| 8576 |
} |
| 8577 |
*cswritep++ = '\t'; |
| 8578 |
if (ac21 == kMissingAlleleCode) { |
| 8579 |
cswritep = strcpya_k(cswritep, "./."); |
| 8580 |
} else { |
| 8581 |
cswritep = u32toa_x(ac21, '/', cswritep); |
| 8582 |
cswritep = u32toa(ac22, cswritep); |
| 8583 |
} |
| 8584 |
} else { |
| 8585 |
cswritep = PrintMultiallelicHcAsDs(ac11, ac12, allele_ct, cswritep); |
| 8586 |
*cswritep++ = '\t'; |
| 8587 |
cswritep = PrintMultiallelicHcAsDs(ac21, ac22, allele_ct, cswritep); |
| 8588 |
} |
| 8589 |
} else { |
| 8590 |
if (!dosage_reported) { |
| 8591 |
if (ac11 == kMissingAlleleCode) { |
| 8592 |
*cswritep++ = '.'; |
| 8593 |
} else { |
| 8594 |
cswritep = u32toa(ac11, cswritep); |
| 8595 |
if (ac11 != ac12) { |
| 8596 |
*cswritep++ = '/'; |
| 8597 |
cswritep = u32toa(ac12, cswritep); |
| 8598 |
} |
| 8599 |
} |
| 8600 |
*cswritep++ = '\t'; |
| 8601 |
if (ac21 == kMissingAlleleCode) { |
| 8602 |
*cswritep++ = '.'; |
| 8603 |
} else { |
| 8604 |
cswritep = u32toa(ac21, cswritep); |
| 8605 |
if (ac21 != ac22) { |
| 8606 |
*cswritep++ = '/'; |
| 8607 |
cswritep = u32toa(ac22, cswritep); |
| 8608 |
} |
| 8609 |
} |
| 8610 |
} else { |
| 8611 |
cswritep = PrintMultiallelicHcAsHaploidDs(ac11, ac12, allele_ct, cswritep); |
| 8612 |
*cswritep++ = '\t'; |
| 8613 |
cswritep = PrintMultiallelicHcAsHaploidDs(ac21, ac22, allele_ct, cswritep); |
| 8614 |
} |
| 8615 |
} |
| 8616 |
} |
| 8617 |
AppendBinaryEoln(&cswritep); |
| 8618 |
cswritep_arr[fidx] = cswritep; |
| 8619 |
if (unlikely(Cswrite(&(css_arr[fidx]), &(cswritep_arr[fidx])))) { |
| 8620 |
cswritep_arr[fidx] = cswritep; |
| 8621 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8622 |
} |
| 8623 |
} |
| 8624 |
} else { |
| 8625 |
// multiallelic-dosage; todo |
| 8626 |
exit(S_CAST(int32_t, kPglRetInternalError)); |
| 8627 |
} |
| 8628 |
} |
| 8629 |
} |
| 8630 |
for (uintptr_t fidx = 0; fidx != file_ct; ++fidx) { |
| 8631 |
if (unlikely(CswriteCloseNull(&(css_arr[fidx]), cswritep_arr[fidx]))) { |
| 8632 |
goto SdiffMainBatch_ret_WRITE_FAIL; |
| 8633 |
} |
| 8634 |
} |
| 8635 |
if (pct > 10) { |
| 8636 |
fputs("\b \b", stdout); |
| 8637 |
} |
| 8638 |
fputs("\b\b", stdout); |
| 8639 |
} |
| 8640 |
while (0) { |
| 8641 |
SdiffMainBatch_ret_NOMEM: |
| 8642 |
reterr = kPglRetNomem; |
| 8643 |
break; |
| 8644 |
SdiffMainBatch_ret_WRITE_FAIL: |
| 8645 |
reterr = kPglRetWriteFail; |
| 8646 |
break; |
| 8647 |
SdiffMainBatch_ret_INCONSISTENT_INPUT: |
| 8648 |
reterr = kPglRetInconsistentInput; |
| 8649 |
break; |
| 8650 |
} |
| 8651 |
SdiffMainBatch_ret_1: |
| 8652 |
if (css_arr) { |
| 8653 |
for (uintptr_t fidx = 0; fidx != file_ct; ++fidx) { |
| 8654 |
CswriteCloseCond(&(css_arr[fidx]), cswritep_arr[fidx]); |
| 8655 |
} |
| 8656 |
} |
| 8657 |
BigstackReset(bigstack_mark); |
| 8658 |
return reterr; |
| 8659 |
} |
| 8660 |
|
| 8661 |
CONSTI32(kSdiffBatchMax, (kMaxOpenFiles - 32) & (~(kBitsPerWord - 1))); |
| 8662 |
static_assert((kSdiffBatchMax % kBitsPerWord) == 0, "kSdiffBatchMax must be a multiple of kBitsPerWord."); |
| 8663 |
static_assert(kSdiffBatchMax > 0, "kSdiffBatchMax must be positive."); |
| 8664 |
|
| 8665 |
PglErr Sdiff(const uintptr_t* orig_sample_include, const SampleIdInfo* siip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const uintptr_t* variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const SdiffInfo* sdip, uint32_t raw_sample_ct, uint32_t orig_sample_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t iid_sid, uint32_t max_thread_ct, PgenReader* simple_pgrp, char* outname, char* outname_end) { |
| 8666 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 8667 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 8668 |
uintptr_t line_idx = 0; |
| 8669 |
TextStream txs; // file= |
| 8670 |
PreinitTextStream(&txs); |
| 8671 |
FILE* outfile = nullptr; |
| 8672 |
PglErr reterr = kPglRetSuccess; |
| 8673 |
{ |
| 8674 |
// Determine xid_mode. |
| 8675 |
const SdiffFlags flags = sdip->flags; |
| 8676 |
const uint32_t other_id_ct = sdip->other_id_ct; |
| 8677 |
char* line_start = nullptr; |
| 8678 |
char* line_iter = nullptr; |
| 8679 |
XidMode xid_mode; |
| 8680 |
if (other_id_ct) { |
| 8681 |
// todo: make this its own function if we use the same logic elsewhere |
| 8682 |
// For sanity's sake, require all sample IDs provided on command line |
| 8683 |
// to contain the same number of delimiters. |
| 8684 |
const char* first_delim_ptr = strchr(sdip->first_id_or_fname, '\t'); |
| 8685 |
if (!first_delim_ptr) { |
| 8686 |
xid_mode = kfXidModeIid; |
| 8687 |
} else { |
| 8688 |
const char* second_delim_ptr = strchr(&(first_delim_ptr[1]), '\t'); |
| 8689 |
if (!second_delim_ptr) { |
| 8690 |
if (iid_sid) { |
| 8691 |
xid_mode = kfXidModeIidSid; |
| 8692 |
} else { |
| 8693 |
xid_mode = kfXidModeFidIid; |
| 8694 |
} |
| 8695 |
} else { |
| 8696 |
if (unlikely(strchr(&(second_delim_ptr[1]), '\t'))) { |
| 8697 |
logerrputs("Error: Too many instances of id-delim= character in --sample-diff sample ID.\n"); |
| 8698 |
goto Sdiff_ret_INVALID_CMDLINE; |
| 8699 |
} |
| 8700 |
xid_mode = kfXidModeFidIidSid; |
| 8701 |
} |
| 8702 |
} |
| 8703 |
} else { |
| 8704 |
reterr = InitTextStream(sdip->first_id_or_fname, kTextStreamBlenFast, MAXV(max_thread_ct - 1, 1), &txs); |
| 8705 |
if (unlikely(reterr)) { |
| 8706 |
goto Sdiff_ret_TSTREAM_FAIL; |
| 8707 |
} |
| 8708 |
reterr = LoadXidHeaderPair("sample-diff", iid_sid, &line_idx, &txs, &xid_mode, &line_start, &line_iter); |
| 8709 |
if (unlikely(reterr)) { |
| 8710 |
if (reterr == kPglRetEof) { |
| 8711 |
logerrputs("Error: Empty --sample-diff file.\n"); |
| 8712 |
reterr = kPglRetInconsistentInput; |
| 8713 |
} |
| 8714 |
goto Sdiff_ret_TSTREAM_XID_FAIL; |
| 8715 |
} |
| 8716 |
} |
| 8717 |
unsigned char* bigstack_mark2 = g_bigstack_base; |
| 8718 |
// May as well have --strict-sid0 or lack of it apply to base=/ids= too. |
| 8719 |
if ((xid_mode & kfXidModeFlagSid) && (!siip->sids) && (!(siip->flags & kfSampleIdStrictSid0))) { |
| 8720 |
xid_mode ^= kfXidModeFlagSid | kfXidModeFlagSkipSid; |
| 8721 |
} |
| 8722 |
char* sorted_xidbox; |
| 8723 |
uint32_t* xid_map; |
| 8724 |
uintptr_t max_xid_blen; |
| 8725 |
reterr = SortedXidboxInitAlloc(orig_sample_include, siip, orig_sample_ct, xid_mode, 0, &sorted_xidbox, &xid_map, &max_xid_blen); |
| 8726 |
if (unlikely(reterr)) { |
| 8727 |
goto Sdiff_ret_1; |
| 8728 |
} |
| 8729 |
char* idbuf; |
| 8730 |
if (unlikely(bigstack_alloc_c(max_xid_blen, &idbuf))) { |
| 8731 |
goto Sdiff_ret_NOMEM; |
| 8732 |
} |
| 8733 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 8734 |
// Now we can parse the sample IDs from the file or command line properly. |
| 8735 |
uintptr_t* sample_include; |
| 8736 |
uint32_t* sample_include_cumulative_popcounts; |
| 8737 |
uint32_t* id_pairs; |
| 8738 |
uintptr_t id_pair_ct; |
| 8739 |
uint32_t sample_ct; |
| 8740 |
if (other_id_ct) { |
| 8741 |
sample_ct = other_id_ct + 1; |
| 8742 |
uint32_t* sample_idxs; |
| 8743 |
if (unlikely(bigstack_end_alloc_u32(sample_ct, &sample_idxs))) { |
| 8744 |
goto Sdiff_ret_NOMEM; |
| 8745 |
} |
| 8746 |
const char* first_id = sdip->first_id_or_fname; |
| 8747 |
const char* dummy_iter = first_id; |
| 8748 |
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &dummy_iter, &(sample_idxs[0]), idbuf))) { |
| 8749 |
logerrprintfww("Error: --sample-diff sample ID '%s' not found.\n", first_id); |
| 8750 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8751 |
} |
| 8752 |
const char* other_ids_iter = sdip->other_ids_flattened; |
| 8753 |
for (uint32_t id_idx = 1; id_idx != sample_ct; ++id_idx) { |
| 8754 |
const char* other_id = other_ids_iter; |
| 8755 |
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &other_ids_iter, &(sample_idxs[id_idx]), idbuf))) { |
| 8756 |
logerrprintfww("Error: --sample-diff sample ID '%s' not found.\n", other_id); |
| 8757 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8758 |
} |
| 8759 |
++other_ids_iter; |
| 8760 |
} |
| 8761 |
BigstackReset(bigstack_mark2); |
| 8762 |
if (flags & kfSdiffOneBase) { |
| 8763 |
id_pair_ct = other_id_ct; |
| 8764 |
} else { |
| 8765 |
id_pair_ct = (S_CAST(uintptr_t, other_id_ct) * sample_ct) / 2; |
| 8766 |
} |
| 8767 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &sample_include) || |
| 8768 |
bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 8769 |
bigstack_alloc_u32(id_pair_ct * 2, &id_pairs))) { |
| 8770 |
goto Sdiff_ret_NOMEM; |
| 8771 |
} |
| 8772 |
for (uint32_t id_idx = 0; id_idx != sample_ct; ++id_idx) { |
| 8773 |
const uint32_t sample_uidx = sample_idxs[id_idx]; |
| 8774 |
if (IsSet(sample_include, sample_uidx)) { |
| 8775 |
logerrputs("Error: Duplicate ID in --sample-diff list.\n"); |
| 8776 |
goto Sdiff_ret_INVALID_CMDLINE; |
| 8777 |
} |
| 8778 |
SetBit(sample_uidx, sample_include); |
| 8779 |
} |
| 8780 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 8781 |
UidxsToIdxs(sample_include, sample_include_cumulative_popcounts, sample_ct, sample_idxs); |
| 8782 |
if (flags & kfSdiffOneBase) { |
| 8783 |
const uint32_t sample_idx_base = sample_idxs[0]; |
| 8784 |
for (uint32_t id_idx = 1; id_idx != sample_ct; ++id_idx) { |
| 8785 |
id_pairs[2 * id_idx - 2] = sample_idx_base; |
| 8786 |
id_pairs[2 * id_idx - 1] = sample_idxs[id_idx]; |
| 8787 |
} |
| 8788 |
} else { |
| 8789 |
uint32_t* id_pairs_iter = id_pairs; |
| 8790 |
for (uint32_t id_idx2 = 1; id_idx2 != sample_ct; ++id_idx2) { |
| 8791 |
const uint32_t sample_idx2 = sample_idxs[id_idx2]; |
| 8792 |
for (uint32_t id_idx1 = 0; id_idx1 != id_idx2; ++id_idx1) { |
| 8793 |
*id_pairs_iter++ = sample_idxs[id_idx1]; |
| 8794 |
*id_pairs_iter++ = sample_idx2; |
| 8795 |
} |
| 8796 |
} |
| 8797 |
} |
| 8798 |
BigstackEndReset(bigstack_end_mark); |
| 8799 |
} else { |
| 8800 |
uint32_t* sample_pair_uidxs_end = R_CAST(uint32_t*, bigstack_end_mark); |
| 8801 |
uint32_t* sample_pair_uidxs_iter = sample_pair_uidxs_end; |
| 8802 |
uint32_t* sample_pair_uidxs_oom = R_CAST(uint32_t*, g_bigstack_base); |
| 8803 |
if (*line_start == '#') { |
| 8804 |
line_iter = AdvPastDelim(line_iter, '\n'); |
| 8805 |
++line_idx; |
| 8806 |
} else { |
| 8807 |
line_iter = line_start; |
| 8808 |
} |
| 8809 |
for (; TextGetUnsafe2(&txs, &line_iter); line_iter = AdvPastDelim(line_iter, '\n'), ++line_idx) { |
| 8810 |
const char* linebuf_iter = line_iter; |
| 8811 |
uint32_t sample_uidx1; |
| 8812 |
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx1, idbuf))) { |
| 8813 |
if (!idbuf[0]) { |
| 8814 |
logerrprintfww("Error: --sample-diff sample ID (on line %" PRIuPTR " of file) not found.\n", line_idx); |
| 8815 |
} else { |
| 8816 |
TabsToSpaces(idbuf); |
| 8817 |
logerrprintfww("Error: --sample-diff sample ID '%s' (on line %" PRIuPTR " of file) not found.\n", idbuf, line_idx); |
| 8818 |
} |
| 8819 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8820 |
} |
| 8821 |
linebuf_iter = FirstNonTspace(linebuf_iter); |
| 8822 |
if (unlikely(IsEolnKns(*linebuf_iter))) { |
| 8823 |
goto Sdiff_ret_MISSING_TOKENS; |
| 8824 |
} |
| 8825 |
uint32_t sample_uidx2; |
| 8826 |
if (unlikely(SortedXidboxReadFind(sorted_xidbox, xid_map, max_xid_blen, orig_sample_ct, 0, xid_mode, &linebuf_iter, &sample_uidx2, idbuf))) { |
| 8827 |
if (!idbuf[0]) { |
| 8828 |
logerrprintfww("Error: --sample-diff sample ID (on line %" PRIuPTR " of file) not found.\n", line_idx); |
| 8829 |
} else { |
| 8830 |
TabsToSpaces(idbuf); |
| 8831 |
logerrprintfww("Error: --sample-diff sample ID '%s' (on line %" PRIuPTR " of file) not found.\n", idbuf, line_idx); |
| 8832 |
} |
| 8833 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8834 |
} |
| 8835 |
if (unlikely(sample_uidx1 == sample_uidx2)) { |
| 8836 |
TabsToSpaces(idbuf); |
| 8837 |
logerrprintfww("Error: Duplicate sample ID \"%s\" on line %" PRIuPTR " of --sample-diff file.\n", idbuf, line_idx); |
| 8838 |
goto Sdiff_ret_MALFORMED_INPUT; |
| 8839 |
} |
| 8840 |
if (unlikely(sample_pair_uidxs_iter == sample_pair_uidxs_oom)) { |
| 8841 |
goto Sdiff_ret_NOMEM; |
| 8842 |
} |
| 8843 |
*(--sample_pair_uidxs_iter) = sample_uidx1; |
| 8844 |
*(--sample_pair_uidxs_iter) = sample_uidx2; |
| 8845 |
line_iter = K_CAST(char*, linebuf_iter); |
| 8846 |
} |
| 8847 |
if (unlikely(TextStreamErrcode2(&txs, &reterr))) { |
| 8848 |
goto Sdiff_ret_TSTREAM_FAIL; |
| 8849 |
} |
| 8850 |
const uintptr_t id_ct = sample_pair_uidxs_end - sample_pair_uidxs_iter; |
| 8851 |
if (unlikely(!id_ct)) { |
| 8852 |
logerrputs("Error: Empty --sample-diff file.\n"); |
| 8853 |
goto Sdiff_ret_MALFORMED_INPUT; |
| 8854 |
} |
| 8855 |
BigstackEndSet(sample_pair_uidxs_iter); |
| 8856 |
BigstackReset(bigstack_mark2); |
| 8857 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &sample_include) || |
| 8858 |
bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 8859 |
bigstack_alloc_u32(id_ct, &id_pairs))) { |
| 8860 |
goto Sdiff_ret_NOMEM; |
| 8861 |
} |
| 8862 |
sample_pair_uidxs_iter = sample_pair_uidxs_end; |
| 8863 |
for (uintptr_t ulii = 0; ulii != id_ct; ++ulii) { |
| 8864 |
const uint32_t sample_uidx = *(--sample_pair_uidxs_iter); |
| 8865 |
SetBit(sample_uidx, sample_include); |
| 8866 |
id_pairs[ulii] = sample_uidx; |
| 8867 |
} |
| 8868 |
BigstackEndReset(bigstack_end_mark); |
| 8869 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 8870 |
sample_ct = sample_include_cumulative_popcounts[raw_sample_ctl - 1] + PopcountWord(sample_include[raw_sample_ctl - 1]); |
| 8871 |
// Don't strictly enforce pair-uniqueness for now, but do perform a basic |
| 8872 |
// sanity check. |
| 8873 |
if (id_ct > S_CAST(uintptr_t, sample_ct) * (sample_ct - 1)) { |
| 8874 |
logerrputs("Error: Duplicate ID pairs in --sample-diff file.\n"); |
| 8875 |
goto Sdiff_ret_MALFORMED_INPUT; |
| 8876 |
} |
| 8877 |
UidxsToIdxs(sample_include, sample_include_cumulative_popcounts, id_ct, id_pairs); |
| 8878 |
id_pair_ct = id_ct / 2; |
| 8879 |
} |
| 8880 |
|
| 8881 |
SdiffCounts* sdiff_counts; |
| 8882 |
if (unlikely(BIGSTACK_ALLOC_X(SdiffCounts, id_pair_ct, &sdiff_counts))) { |
| 8883 |
goto Sdiff_ret_NOMEM; |
| 8884 |
} |
| 8885 |
memset(sdiff_counts, 0, id_pair_ct * sizeof(SdiffCounts)); |
| 8886 |
uintptr_t* pair_sex_male = nullptr; |
| 8887 |
uint32_t x_ct = 0; |
| 8888 |
uint32_t y_ct = 0; |
| 8889 |
{ |
| 8890 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 8891 |
if ((!IsI32Neg(x_code)) && IsSet(cip->chr_mask, x_code)) { |
| 8892 |
x_ct = CountChrVariantsUnsafe(variant_include, cip, x_code); |
| 8893 |
} |
| 8894 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 8895 |
if ((!IsI32Neg(y_code)) && IsSet(cip->chr_mask, y_code)) { |
| 8896 |
y_ct = CountChrVariantsUnsafe(variant_include, cip, y_code); |
| 8897 |
} |
| 8898 |
} |
| 8899 |
if (x_ct || y_ct) { |
| 8900 |
const uintptr_t id_pair_ctl = BitCtToWordCt(id_pair_ct); |
| 8901 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 8902 |
uintptr_t* sex_nm_collapsed; |
| 8903 |
uintptr_t* sex_male_collapsed; |
| 8904 |
if (unlikely(bigstack_alloc_w(id_pair_ctl, &pair_sex_male) || |
| 8905 |
bigstack_alloc_w(sample_ctl, &sex_nm_collapsed) || |
| 8906 |
bigstack_alloc_w(sample_ctl, &sex_male_collapsed))) { |
| 8907 |
goto Sdiff_ret_NOMEM; |
| 8908 |
} |
| 8909 |
CopyBitarrSubset(sex_nm, sample_include, sample_ct, sex_nm_collapsed); |
| 8910 |
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed); |
| 8911 |
const uint32_t* id_pairs_iter = id_pairs; |
| 8912 |
const uintptr_t word_ct_m1 = id_pair_ctl - 1; |
| 8913 |
uint32_t loop_len = kBitsPerWord; |
| 8914 |
for (uintptr_t widx = 0; ; ++widx) { |
| 8915 |
if (widx >= word_ct_m1) { |
| 8916 |
if (widx > word_ct_m1) { |
| 8917 |
break; |
| 8918 |
} |
| 8919 |
loop_len = ModNz(id_pair_ct, kBitsPerWord); |
| 8920 |
} |
| 8921 |
uintptr_t cur_word = 0; |
| 8922 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 8923 |
const uint32_t sample_idx1 = *id_pairs_iter++; |
| 8924 |
const uint32_t sample_idx2 = *id_pairs_iter++; |
| 8925 |
const uint32_t sex_nm1 = IsSet(sex_nm_collapsed, sample_idx1); |
| 8926 |
const uint32_t sex_nm_xor = sex_nm1 ^ IsSet(sex_nm_collapsed, sample_idx2); |
| 8927 |
const uintptr_t sex_male1 = IsSet(sex_male_collapsed, sample_idx1); |
| 8928 |
const uintptr_t sex_male_xor = sex_male1 ^ IsSet(sex_male_collapsed, sample_idx2); |
| 8929 |
if (sex_nm_xor) { |
| 8930 |
// Exactly one sex is missing. |
| 8931 |
cur_word |= sex_male_xor << uii; |
| 8932 |
} else if (unlikely(!sex_nm1)) { |
| 8933 |
logerrputs("Error: --sample-diff requires at least one sample in each pair to have known\nsex when chrX or chrY is present.\n"); |
| 8934 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8935 |
} else if (unlikely(sex_male_xor)) { |
| 8936 |
logerrputs("Error: --sample-diff cannot perform male-female comparisons when chrX or chrY\nis present. (Consider \"--not-chr X,Y\".)\n"); |
| 8937 |
goto Sdiff_ret_INCONSISTENT_INPUT; |
| 8938 |
} else { |
| 8939 |
cur_word |= sex_male1 << uii; |
| 8940 |
} |
| 8941 |
} |
| 8942 |
pair_sex_male[widx] = cur_word; |
| 8943 |
} |
| 8944 |
BigstackReset(sex_nm_collapsed); |
| 8945 |
} |
| 8946 |
// Main loops. |
| 8947 |
if (flags & kfSdiffCountsOnly) { |
| 8948 |
reterr = SdiffCountsOnly(sample_include, sample_include_cumulative_popcounts, id_pairs, pair_sex_male, variant_include, cip, allele_idx_offsets, sdip, sample_ct, variant_ct, id_pair_ct, simple_pgrp, sdiff_counts); |
| 8949 |
if (unlikely(reterr)) { |
| 8950 |
goto Sdiff_ret_1; |
| 8951 |
} |
| 8952 |
} else { |
| 8953 |
const uint32_t is_pairwise = (flags / kfSdiffPairwise) & 1; |
| 8954 |
uintptr_t batch_ct = 1; |
| 8955 |
if (is_pairwise && (id_pair_ct > kSdiffBatchMax)) { |
| 8956 |
batch_ct = 1 + ((id_pair_ct - 1) / kSdiffBatchMax); |
| 8957 |
} |
| 8958 |
for (uintptr_t batch_idx = 0; batch_idx != batch_ct; ++batch_idx) { |
| 8959 |
const uintptr_t id_pair_idx_start = batch_idx * kSdiffBatchMax; |
| 8960 |
uintptr_t id_pair_idx_end = id_pair_ct; |
| 8961 |
if (batch_ct == 1) { |
| 8962 |
printf("--sample-diff%s: 0%%", is_pairwise? " pairwise" : ""); |
| 8963 |
} else { |
| 8964 |
if (batch_idx != batch_ct - 1) { |
| 8965 |
id_pair_idx_end = id_pair_idx_start + kSdiffBatchMax; |
| 8966 |
} |
| 8967 |
printf("\r--sample-diff pairwise batch %" PRIuPTR "/%" PRIuPTR ": 0%%", batch_idx + 1, batch_ct); |
| 8968 |
} |
| 8969 |
fflush(stdout); |
| 8970 |
reterr = SdiffMainBatch(sample_include, sample_include_cumulative_popcounts, siip, &(id_pairs[2 * id_pair_idx_start]), &(pair_sex_male[id_pair_idx_start / kBitsPerWord]), variant_include, cip, variant_bps, variant_ids, allele_idx_offsets, allele_storage, sdip, sample_ct, raw_variant_ct, variant_ct, id_pair_idx_end - id_pair_idx_start, max_thread_ct, simple_pgrp, outname, outname_end, &(sdiff_counts[id_pair_idx_start])); |
| 8971 |
if (unlikely(reterr)) { |
| 8972 |
goto Sdiff_ret_1; |
| 8973 |
} |
| 8974 |
} |
| 8975 |
fputs("done.\n", stdout); |
| 8976 |
if (is_pairwise) { |
| 8977 |
*outname_end = '\0'; |
| 8978 |
logprintfww("--sample-diff pairwise: Discordances written to %s.[ID1].[ID2].sdiff%s (%" PRIuPTR " file%s).\n", outname, (flags & kfSdiffZs)? ".zst" : "", id_pair_ct, (id_pair_ct == 1)? "" : "s"); |
| 8979 |
} else { |
| 8980 |
logprintfww("--sample-diff: Discordances written to %s .\n", outname); |
| 8981 |
} |
| 8982 |
} |
| 8983 |
|
| 8984 |
// Final count-summary. |
| 8985 |
const uint32_t col_fid = FidColIsRequired(siip, flags / kfSdiffCountsColMaybefid); |
| 8986 |
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfSdiffCountsColMaybesid); |
| 8987 |
char* collapsed_sample_fmtids; |
| 8988 |
uintptr_t max_sample_fmtid_blen; |
| 8989 |
if (unlikely(CollapsedSampleFmtidInitAlloc(sample_include, siip, sample_ct, col_fid, col_sid, &collapsed_sample_fmtids, &max_sample_fmtid_blen))) { |
| 8990 |
goto Sdiff_ret_NOMEM; |
| 8991 |
} |
| 8992 |
uint32_t autosomal_diploid_ct; |
| 8993 |
uint32_t nonsex_haploid_ct; |
| 8994 |
if (!IsSet(cip->chr_mask, 0)) { |
| 8995 |
const uint32_t x_code = cip->xymt_codes[kChrOffsetX]; |
| 8996 |
const uint32_t y_code = cip->xymt_codes[kChrOffsetY]; |
| 8997 |
const uint32_t chr_idx_end = cip->max_code + 1 + cip->name_ct; |
| 8998 |
nonsex_haploid_ct = 0; |
| 8999 |
for (uint32_t chr_idx = 1; ; ++chr_idx) { |
| 9000 |
// usually just MT |
| 9001 |
chr_idx = AdvBoundedTo1Bit(cip->haploid_mask, chr_idx, chr_idx_end); |
| 9002 |
if (chr_idx == chr_idx_end) { |
| 9003 |
break; |
| 9004 |
} |
| 9005 |
if ((!IsSet(cip->chr_mask, chr_idx)) || (chr_idx == x_code) || (chr_idx == y_code)) { |
| 9006 |
continue; |
| 9007 |
} |
| 9008 |
nonsex_haploid_ct += CountChrVariantsUnsafe(variant_include, cip, chr_idx); |
| 9009 |
} |
| 9010 |
autosomal_diploid_ct = variant_ct - x_ct - y_ct - nonsex_haploid_ct; |
| 9011 |
} else { |
| 9012 |
autosomal_diploid_ct = 0; |
| 9013 |
nonsex_haploid_ct = variant_ct - x_ct - y_ct; |
| 9014 |
} |
| 9015 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".sdiff.summary"); |
| 9016 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) { |
| 9017 |
goto Sdiff_ret_OPEN_FAIL; |
| 9018 |
} |
| 9019 |
char* textbuf = g_textbuf; |
| 9020 |
char* textbuf_flush = &(textbuf[kMaxMediumLine]); |
| 9021 |
char* write_iter = textbuf; |
| 9022 |
*write_iter++ = '#'; |
| 9023 |
if (col_fid) { |
| 9024 |
write_iter = strcpya_k(write_iter, "FID1\t"); |
| 9025 |
} |
| 9026 |
write_iter = strcpya_k(write_iter, "IID1"); |
| 9027 |
if (col_sid) { |
| 9028 |
write_iter = strcpya_k(write_iter, "\tSID1"); |
| 9029 |
} |
| 9030 |
if (col_fid) { |
| 9031 |
write_iter = strcpya_k(write_iter, "\tFID2"); |
| 9032 |
} |
| 9033 |
write_iter = strcpya_k(write_iter, "\tIID2"); |
| 9034 |
if (col_sid) { |
| 9035 |
write_iter = strcpya_k(write_iter, "\tSID2"); |
| 9036 |
} |
| 9037 |
if (flags & kfSdiffCountsColNobs) { |
| 9038 |
write_iter = strcpya_k(write_iter, "\tOBS_CT"); |
| 9039 |
} |
| 9040 |
if (flags & kfSdiffCountsColNobsIbs) { |
| 9041 |
write_iter = strcpya_k(write_iter, "\tIBS_OBS_CT"); |
| 9042 |
} |
| 9043 |
if (flags & kfSdiffCountsColIbs0) { |
| 9044 |
write_iter = strcpya_k(write_iter, "\tIBS0_CT"); |
| 9045 |
} |
| 9046 |
if (flags & kfSdiffCountsColIbs1) { |
| 9047 |
write_iter = strcpya_k(write_iter, "\tIBS1_CT"); |
| 9048 |
} |
| 9049 |
if (flags & kfSdiffCountsColIbs2) { |
| 9050 |
write_iter = strcpya_k(write_iter, "\tIBS2_CT"); |
| 9051 |
} |
| 9052 |
if (flags & kfSdiffCountsColHalfmiss) { |
| 9053 |
write_iter = strcpya_k(write_iter, "\tHALFMISS_CT"); |
| 9054 |
} |
| 9055 |
if (flags & kfSdiffCountsColDiff) { |
| 9056 |
write_iter = strcpya_k(write_iter, "\tDIFF_CT"); |
| 9057 |
} |
| 9058 |
AppendBinaryEoln(&write_iter); |
| 9059 |
const uint32_t obs_ct_base = autosomal_diploid_ct + x_ct + nonsex_haploid_ct; |
| 9060 |
const uint32_t* id_pair_iter = id_pairs; |
| 9061 |
for (uintptr_t pair_idx = 0; pair_idx != id_pair_ct; ++pair_idx) { |
| 9062 |
const uint32_t sample_idx1 = *id_pair_iter++; |
| 9063 |
const uint32_t sample_idx2 = *id_pair_iter++; |
| 9064 |
write_iter = strcpyax(write_iter, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx1]), '\t'); |
| 9065 |
write_iter = strcpya(write_iter, &(collapsed_sample_fmtids[max_sample_fmtid_blen * sample_idx2])); |
| 9066 |
const SdiffCounts* cur_counts = &(sdiff_counts[pair_idx]); |
| 9067 |
if (flags & kfSdiffCountsColNobs) { |
| 9068 |
uint32_t obs_ct = obs_ct_base; |
| 9069 |
if (y_ct && IsSet(pair_sex_male, pair_idx)) { |
| 9070 |
obs_ct += y_ct; |
| 9071 |
} |
| 9072 |
if (!(flags & kfSdiffIncludeMissing)) { |
| 9073 |
obs_ct -= cur_counts->missing_ct + cur_counts->halfmiss_ct; |
| 9074 |
} |
| 9075 |
*write_iter++ = '\t'; |
| 9076 |
write_iter = u32toa(obs_ct, write_iter); |
| 9077 |
} |
| 9078 |
if (flags & kfSdiffCountsIbsNeeded) { |
| 9079 |
uint32_t ibs_obs_ct = autosomal_diploid_ct - cur_counts->ibsmiss_ct; |
| 9080 |
if (x_ct && (!IsSet(pair_sex_male, pair_idx))) { |
| 9081 |
ibs_obs_ct += x_ct; |
| 9082 |
} |
| 9083 |
if (flags & kfSdiffCountsColNobsIbs) { |
| 9084 |
*write_iter++ = '\t'; |
| 9085 |
write_iter = u32toa(ibs_obs_ct, write_iter); |
| 9086 |
} |
| 9087 |
if (flags & kfSdiffCountsColIbs0) { |
| 9088 |
*write_iter++ = '\t'; |
| 9089 |
write_iter = u32toa(cur_counts->ibsx_cts[0], write_iter); |
| 9090 |
} |
| 9091 |
if (flags & kfSdiffCountsColIbs1) { |
| 9092 |
*write_iter++ = '\t'; |
| 9093 |
write_iter = u32toa(cur_counts->ibsx_cts[1], write_iter); |
| 9094 |
} |
| 9095 |
if (flags & kfSdiffCountsColIbs2) { |
| 9096 |
*write_iter++ = '\t'; |
| 9097 |
write_iter = u32toa(ibs_obs_ct - cur_counts->ibsx_cts[0] - cur_counts->ibsx_cts[1], write_iter); |
| 9098 |
} |
| 9099 |
} |
| 9100 |
if (flags & kfSdiffCountsColHalfmiss) { |
| 9101 |
*write_iter++ = '\t'; |
| 9102 |
write_iter = u32toa(cur_counts->halfmiss_ct, write_iter); |
| 9103 |
} |
| 9104 |
if (flags & kfSdiffCountsColDiff) { |
| 9105 |
uint32_t diff_ct = cur_counts->diff_ct; |
| 9106 |
if (flags & kfSdiffIncludeMissing) { |
| 9107 |
diff_ct += cur_counts->halfmiss_ct; |
| 9108 |
} |
| 9109 |
*write_iter++ = '\t'; |
| 9110 |
write_iter = u32toa(diff_ct, write_iter); |
| 9111 |
} |
| 9112 |
AppendBinaryEoln(&write_iter); |
| 9113 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9114 |
goto Sdiff_ret_WRITE_FAIL; |
| 9115 |
} |
| 9116 |
} |
| 9117 |
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) { |
| 9118 |
goto Sdiff_ret_WRITE_FAIL; |
| 9119 |
} |
| 9120 |
logprintfww("--sample-diff: Discordance count summary written to %s .\n", outname); |
| 9121 |
} |
| 9122 |
while (0) { |
| 9123 |
Sdiff_ret_NOMEM: |
| 9124 |
reterr = kPglRetNomem; |
| 9125 |
break; |
| 9126 |
Sdiff_ret_OPEN_FAIL: |
| 9127 |
reterr = kPglRetOpenFail; |
| 9128 |
break; |
| 9129 |
Sdiff_ret_TSTREAM_XID_FAIL: |
| 9130 |
if (!TextStreamErrcode(&txs)) { |
| 9131 |
break; |
| 9132 |
} |
| 9133 |
Sdiff_ret_TSTREAM_FAIL: |
| 9134 |
TextStreamErrPrint("--sample-diff file", &txs); |
| 9135 |
break; |
| 9136 |
Sdiff_ret_WRITE_FAIL: |
| 9137 |
reterr = kPglRetWriteFail; |
| 9138 |
break; |
| 9139 |
Sdiff_ret_INVALID_CMDLINE: |
| 9140 |
reterr = kPglRetInvalidCmdline; |
| 9141 |
break; |
| 9142 |
Sdiff_ret_MISSING_TOKENS: |
| 9143 |
logerrprintf("Error: Line %" PRIuPTR " of --sample-diff file has fewer tokens than expected.\n", line_idx); |
| 9144 |
Sdiff_ret_MALFORMED_INPUT: |
| 9145 |
reterr = kPglRetMalformedInput; |
| 9146 |
break; |
| 9147 |
Sdiff_ret_INCONSISTENT_INPUT: |
| 9148 |
reterr = kPglRetInconsistentInput; |
| 9149 |
break; |
| 9150 |
} |
| 9151 |
Sdiff_ret_1: |
| 9152 |
fclose_cond(outfile); |
| 9153 |
CleanupTextStream2("--sample-diff file", &txs, &reterr); |
| 9154 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 9155 |
return reterr; |
| 9156 |
} |
| 9157 |
|
| 9158 |
PglErr WriteSnplist(const uintptr_t* variant_include, const char* const* variant_ids, uint32_t variant_ct, uint32_t output_zst, uint32_t allow_dups, uint32_t max_thread_ct, char* outname, char* outname_end) { |
| 9159 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 9160 |
char* cswritep = nullptr; |
| 9161 |
CompressStreamState css; |
| 9162 |
PglErr reterr = kPglRetSuccess; |
| 9163 |
PreinitCstream(&css); |
| 9164 |
{ |
| 9165 |
if (!allow_dups) { |
| 9166 |
uint32_t dup_found; |
| 9167 |
reterr = CheckIdUniqueness(g_bigstack_base, g_bigstack_end, variant_include, variant_ids, variant_ct, max_thread_ct, &dup_found); |
| 9168 |
if (unlikely(reterr)) { |
| 9169 |
goto WriteSnplist_ret_1; |
| 9170 |
} |
| 9171 |
if (dup_found) { |
| 9172 |
// I estimate that this corresponds to a pipeline bug (or, at minimum, |
| 9173 |
// inefficiency) >90% of the time. |
| 9174 |
// --extract[-intersect] could be modified in a similar manner, but my |
| 9175 |
// working hypothesis is that interception of suspect --write-snplist |
| 9176 |
// operations is enough to stop most duplicate-related --extract |
| 9177 |
// misuses. |
| 9178 |
logerrputs("Error: --write-snplist normally shouldn't be used with duplicate variant IDs.\n(--set-all-var-ids helps with ID deduplication, and --rm-dup addresses actual\nduplicate data.) However, if you've already accounted for them, you can\nsuppress this error with the 'allow-dups' modifier.\n"); |
| 9179 |
goto WriteSnplist_ret_INCONSISTENT_INPUT; |
| 9180 |
} |
| 9181 |
} |
| 9182 |
OutnameZstSet(".snplist", output_zst, outname_end); |
| 9183 |
reterr = InitCstreamAlloc(outname, 0, output_zst, max_thread_ct, kCompressStreamBlock + kMaxIdSlen + 2, &css, &cswritep); |
| 9184 |
if (unlikely(reterr)) { |
| 9185 |
goto WriteSnplist_ret_1; |
| 9186 |
} |
| 9187 |
uintptr_t variant_uidx_base = 0; |
| 9188 |
uintptr_t cur_bits = variant_include[0]; |
| 9189 |
for (uint32_t variant_idx = 0; variant_idx != variant_ct; ++variant_idx) { |
| 9190 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 9191 |
cswritep = strcpya(cswritep, variant_ids[variant_uidx]); |
| 9192 |
AppendBinaryEoln(&cswritep); |
| 9193 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 9194 |
goto WriteSnplist_ret_WRITE_FAIL; |
| 9195 |
} |
| 9196 |
} |
| 9197 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 9198 |
goto WriteSnplist_ret_WRITE_FAIL; |
| 9199 |
} |
| 9200 |
logprintfww("--write-snplist%s%s: Variant IDs written to %s .\n", output_zst? " zs" : "", allow_dups? " allow-dups" : "", outname); |
| 9201 |
} |
| 9202 |
while (0) { |
| 9203 |
WriteSnplist_ret_WRITE_FAIL: |
| 9204 |
reterr = kPglRetWriteFail; |
| 9205 |
break; |
| 9206 |
WriteSnplist_ret_INCONSISTENT_INPUT: |
| 9207 |
reterr = kPglRetInconsistentInput; |
| 9208 |
break; |
| 9209 |
} |
| 9210 |
WriteSnplist_ret_1: |
| 9211 |
CswriteCloseCond(&css, cswritep); |
| 9212 |
BigstackReset(bigstack_mark); |
| 9213 |
return reterr; |
| 9214 |
} |
| 9215 |
|
| 9216 |
// similar to write_psam(). |
| 9217 |
PglErr WriteCovar(const uintptr_t* sample_include, const PedigreeIdInfo* piip, const uintptr_t* sex_nm, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const PhenoCol* covar_cols, const char* covar_names, const uint32_t* new_sample_idx_to_old, const char* output_missing_pheno, uint32_t sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t covar_ct, uintptr_t max_covar_name_blen, WriteCovarFlags write_covar_flags, char* outname, char* outname_end) { |
| 9218 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 9219 |
FILE* outfile = nullptr; |
| 9220 |
PglErr reterr = kPglRetSuccess; |
| 9221 |
{ |
| 9222 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".cov"); |
| 9223 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) { |
| 9224 |
goto WriteCovar_ret_OPEN_FAIL; |
| 9225 |
} |
| 9226 |
const uint32_t omp_slen = strlen(output_missing_pheno); |
| 9227 |
|
| 9228 |
char* textbuf = g_textbuf; |
| 9229 |
char* textbuf_flush = &(textbuf[kMaxMediumLine]); |
| 9230 |
|
| 9231 |
const uint32_t write_fid = FidColIsRequired(&piip->sii, write_covar_flags / kfWriteCovarColMaybefid); |
| 9232 |
const char* sample_ids = piip->sii.sample_ids; |
| 9233 |
const char* sids = piip->sii.sids; |
| 9234 |
const char* paternal_ids = piip->parental_id_info.paternal_ids; |
| 9235 |
const char* maternal_ids = piip->parental_id_info.maternal_ids; |
| 9236 |
const uintptr_t max_sample_id_blen = piip->sii.max_sample_id_blen; |
| 9237 |
const uintptr_t max_sid_blen = piip->sii.max_sid_blen; |
| 9238 |
const uintptr_t max_paternal_id_blen = piip->parental_id_info.max_paternal_id_blen; |
| 9239 |
const uintptr_t max_maternal_id_blen = piip->parental_id_info.max_maternal_id_blen; |
| 9240 |
const uint32_t write_sid = SidColIsRequired(sids, write_covar_flags / kfWriteCovarColMaybesid); |
| 9241 |
const uint32_t write_parents = ParentalColsAreRequired(piip, write_covar_flags / kfWriteCovarColMaybeparents); |
| 9242 |
const uint32_t write_sex = (write_covar_flags / kfWriteCovarColSex) & 1; |
| 9243 |
const uint32_t write_empty_pheno = (write_covar_flags & kfWriteCovarColPheno1) && (!pheno_ct); |
| 9244 |
const uint32_t write_phenos = (write_covar_flags & (kfWriteCovarColPheno1 | kfWriteCovarColPhenos)) && pheno_ct; |
| 9245 |
if (write_phenos && (!(write_covar_flags & kfWriteCovarColPhenos))) { |
| 9246 |
pheno_ct = 1; |
| 9247 |
} |
| 9248 |
char* write_iter = textbuf; |
| 9249 |
*write_iter++ = '#'; |
| 9250 |
if (write_fid) { |
| 9251 |
write_iter = strcpya_k(write_iter, "FID\t"); |
| 9252 |
} |
| 9253 |
write_iter = strcpya_k(write_iter, "IID"); |
| 9254 |
if (write_sid) { |
| 9255 |
write_iter = strcpya_k(write_iter, "\tSID"); |
| 9256 |
} |
| 9257 |
if (write_parents) { |
| 9258 |
write_iter = strcpya_k(write_iter, "\tPAT\tMAT"); |
| 9259 |
} |
| 9260 |
if (write_sex) { |
| 9261 |
write_iter = strcpya_k(write_iter, "\tSEX"); |
| 9262 |
} |
| 9263 |
if (write_phenos || write_empty_pheno || write_sex) { |
| 9264 |
// verify that no names are duplicated |
| 9265 |
uint32_t* covar_name_htable; |
| 9266 |
uint32_t covar_name_htable_size; |
| 9267 |
if (unlikely(HtableGoodSizeAlloc(covar_ct + write_sex, bigstack_left(), &covar_name_htable, &covar_name_htable_size))) { |
| 9268 |
goto WriteCovar_ret_NOMEM; |
| 9269 |
} |
| 9270 |
// shouldn't be possible for this to fail |
| 9271 |
PopulateStrboxHtable(covar_names, covar_ct, max_covar_name_blen, covar_name_htable_size, covar_name_htable); |
| 9272 |
uint32_t max_xcovar_name_blen = max_covar_name_blen; |
| 9273 |
if (write_sex) { |
| 9274 |
// add "SEX" |
| 9275 |
if (unlikely(StrboxHtableAdd("SEX", covar_names, max_covar_name_blen, strlen("SEX"), covar_name_htable_size, covar_ct, covar_name_htable) != UINT32_MAX)) { |
| 9276 |
logerrputs("Error: .cov file cannot have both a regular SEX column and a covariate named\n'SEX'. Exclude or rename one of these columns.\n"); |
| 9277 |
goto WriteCovar_ret_INCONSISTENT_INPUT; |
| 9278 |
} |
| 9279 |
if (max_xcovar_name_blen < 4) { |
| 9280 |
max_xcovar_name_blen = 4; |
| 9281 |
} |
| 9282 |
} |
| 9283 |
if (write_phenos) { |
| 9284 |
const char* pheno_name_iter = pheno_names; |
| 9285 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 9286 |
*write_iter++ = '\t'; |
| 9287 |
const uint32_t cur_pheno_name_slen = strlen(pheno_name_iter); |
| 9288 |
if (cur_pheno_name_slen < max_xcovar_name_blen) { |
| 9289 |
// can't just use StrboxHtableFind() since "SEX" may not be stored |
| 9290 |
// in covar_names[] |
| 9291 |
const uint32_t cur_pheno_name_blen = cur_pheno_name_slen + 1; |
| 9292 |
for (uint32_t hashval = Hashceil(pheno_name_iter, cur_pheno_name_slen, covar_name_htable_size); ; ) { |
| 9293 |
const uint32_t cur_htable_idval = covar_name_htable[hashval]; |
| 9294 |
if (cur_htable_idval >= covar_ct) { |
| 9295 |
if (cur_htable_idval == UINT32_MAX) { |
| 9296 |
break; |
| 9297 |
} |
| 9298 |
if (unlikely(strequal_k_unsafe(pheno_name_iter, "SEX"))) { |
| 9299 |
logerrputs(write_sex? "Error: .cov file cannot have both a regular SEX column and a phenotype named\n'SEX'. Exclude or rename one of these columns.\n" : "Error: .cov file cannot have a phenotype and a covariate with the same name.\n"); |
| 9300 |
goto WriteCovar_ret_INCONSISTENT_INPUT; |
| 9301 |
} |
| 9302 |
} else { |
| 9303 |
if (unlikely(memequal(pheno_name_iter, &(covar_names[cur_htable_idval * max_covar_name_blen]), cur_pheno_name_blen))) { |
| 9304 |
logerrputs("Error: .cov file cannot have a phenotype and a covariate with the same name.\n"); |
| 9305 |
goto WriteCovar_ret_INCONSISTENT_INPUT; |
| 9306 |
} |
| 9307 |
} |
| 9308 |
if (++hashval == covar_name_htable_size) { |
| 9309 |
hashval = 0; |
| 9310 |
} |
| 9311 |
} |
| 9312 |
} |
| 9313 |
write_iter = memcpya(write_iter, pheno_name_iter, cur_pheno_name_slen); |
| 9314 |
pheno_name_iter = &(pheno_name_iter[max_pheno_name_blen]); |
| 9315 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9316 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9317 |
} |
| 9318 |
} |
| 9319 |
} else if (write_empty_pheno) { |
| 9320 |
if (max_covar_name_blen > 6) { |
| 9321 |
for (uint32_t hashval = Hashceil("PHENO1", 6, covar_name_htable_size); ; ) { |
| 9322 |
const uint32_t cur_htable_idval = covar_name_htable[hashval]; |
| 9323 |
if (cur_htable_idval >= covar_ct) { |
| 9324 |
if (cur_htable_idval == UINT32_MAX) { |
| 9325 |
break; |
| 9326 |
} |
| 9327 |
} else { |
| 9328 |
if (unlikely(strequal_k_unsafe(&(covar_names[cur_htable_idval * max_covar_name_blen]), "PHENO1"))) { |
| 9329 |
logerrputs("Error: .cov file cannot have a phenotype and a covariate with the same name.\n"); |
| 9330 |
goto WriteCovar_ret_INCONSISTENT_INPUT; |
| 9331 |
} |
| 9332 |
} |
| 9333 |
if (++hashval == covar_name_htable_size) { |
| 9334 |
hashval = 0; |
| 9335 |
} |
| 9336 |
} |
| 9337 |
} |
| 9338 |
write_iter = strcpya_k(write_iter, "\tPHENO1"); |
| 9339 |
} |
| 9340 |
} |
| 9341 |
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) { |
| 9342 |
*write_iter++ = '\t'; |
| 9343 |
const char* cur_covar_name = &(covar_names[covar_idx * max_covar_name_blen]); |
| 9344 |
const uint32_t cur_covar_name_slen = strlen(cur_covar_name); |
| 9345 |
write_iter = memcpya(write_iter, cur_covar_name, cur_covar_name_slen); |
| 9346 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9347 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9348 |
} |
| 9349 |
} |
| 9350 |
AppendBinaryEoln(&write_iter); |
| 9351 |
|
| 9352 |
uintptr_t sample_uidx_base = 0; |
| 9353 |
uintptr_t cur_bits = sample_include[0]; |
| 9354 |
uint32_t sample_uidx2 = 0; |
| 9355 |
// not really necessary to make sample_uidx increment dependent on |
| 9356 |
// new_sample_idx_to_old == nullptr |
| 9357 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 9358 |
uintptr_t sample_uidx; |
| 9359 |
if (!new_sample_idx_to_old) { |
| 9360 |
sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 9361 |
} else { |
| 9362 |
do { |
| 9363 |
sample_uidx = new_sample_idx_to_old[sample_uidx2++]; |
| 9364 |
} while (!IsSet(sample_include, sample_uidx)); |
| 9365 |
} |
| 9366 |
write_iter = AppendXid(sample_ids, sids, write_fid, write_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter); |
| 9367 |
if (write_parents) { |
| 9368 |
*write_iter++ = '\t'; |
| 9369 |
write_iter = strcpyax(write_iter, &(paternal_ids[max_paternal_id_blen * sample_uidx]), '\t'); |
| 9370 |
write_iter = strcpya(write_iter, &(maternal_ids[max_maternal_id_blen * sample_uidx])); |
| 9371 |
} |
| 9372 |
if (write_sex) { |
| 9373 |
*write_iter++ = '\t'; |
| 9374 |
if (IsSet(sex_nm, sample_uidx)) { |
| 9375 |
*write_iter++ = '2' - IsSet(sex_male, sample_uidx); |
| 9376 |
} else { |
| 9377 |
// this is better than '0' since it allows the raw column to be used |
| 9378 |
// as --covar input |
| 9379 |
// (can't do this for .fam export, though: not worth the |
| 9380 |
// compatibility issues) |
| 9381 |
write_iter = strcpya_k(write_iter, "NA"); |
| 9382 |
} |
| 9383 |
} |
| 9384 |
if (write_phenos) { |
| 9385 |
for (uint32_t pheno_idx = 0; pheno_idx != pheno_ct; ++pheno_idx) { |
| 9386 |
*write_iter++ = '\t'; |
| 9387 |
write_iter = AppendPhenoStr(&(pheno_cols[pheno_idx]), output_missing_pheno, omp_slen, sample_uidx, write_iter); |
| 9388 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9389 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9390 |
} |
| 9391 |
} |
| 9392 |
} else { |
| 9393 |
if (write_empty_pheno) { |
| 9394 |
*write_iter++ = '\t'; |
| 9395 |
write_iter = memcpya(write_iter, output_missing_pheno, omp_slen); |
| 9396 |
} |
| 9397 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9398 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9399 |
} |
| 9400 |
} |
| 9401 |
for (uint32_t covar_idx = 0; covar_idx != covar_ct; ++covar_idx) { |
| 9402 |
*write_iter++ = '\t'; |
| 9403 |
write_iter = AppendPhenoStr(&(covar_cols[covar_idx]), output_missing_pheno, omp_slen, sample_uidx, write_iter); |
| 9404 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 9405 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9406 |
} |
| 9407 |
} |
| 9408 |
AppendBinaryEoln(&write_iter); |
| 9409 |
} |
| 9410 |
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) { |
| 9411 |
goto WriteCovar_ret_WRITE_FAIL; |
| 9412 |
} |
| 9413 |
logprintfww("Covariates written to %s .\n", outname); |
| 9414 |
} |
| 9415 |
while (0) { |
| 9416 |
WriteCovar_ret_NOMEM: |
| 9417 |
reterr = kPglRetNomem; |
| 9418 |
break; |
| 9419 |
WriteCovar_ret_OPEN_FAIL: |
| 9420 |
reterr = kPglRetOpenFail; |
| 9421 |
break; |
| 9422 |
WriteCovar_ret_WRITE_FAIL: |
| 9423 |
reterr = kPglRetWriteFail; |
| 9424 |
break; |
| 9425 |
WriteCovar_ret_INCONSISTENT_INPUT: |
| 9426 |
reterr = kPglRetInconsistentInput; |
| 9427 |
break; |
| 9428 |
} |
| 9429 |
fclose_cond(outfile); |
| 9430 |
BigstackReset(bigstack_mark); |
| 9431 |
return reterr; |
| 9432 |
} |
| 9433 |
|
| 9434 |
// This is almost a subset of SampleCounts(). |
| 9435 |
typedef struct HetCtxStruct { |
| 9436 |
const uintptr_t* variant_subset; |
| 9437 |
|
| 9438 |
const uintptr_t* allele_idx_offsets; |
| 9439 |
const uintptr_t* sample_include; |
| 9440 |
const uint32_t* sample_include_cumulative_popcounts; |
| 9441 |
const uintptr_t* founder_info_collapsed; // only non-null if small-sample |
| 9442 |
const uintptr_t* founder_info_interleaved_vec; |
| 9443 |
const double* allele_freqs; // nullptr if small-sample |
| 9444 |
uint32_t sample_ct; |
| 9445 |
uint32_t founder_ct; |
| 9446 |
|
| 9447 |
PgenReader** pgr_ptrs; |
| 9448 |
uintptr_t** genovecs; |
| 9449 |
uintptr_t** thread_read_mhc; |
| 9450 |
uintptr_t** raregenos; |
| 9451 |
uint32_t** difflist_sample_id_bufs; |
| 9452 |
uint32_t** allele_nobs_bufs; |
| 9453 |
VecW** scrambled_ohet_bufs; |
| 9454 |
uint32_t* read_variant_uidx_starts; |
| 9455 |
uint32_t cur_block_size; |
| 9456 |
|
| 9457 |
uint64_t err_info; |
| 9458 |
|
| 9459 |
double* thread_ehet_base; |
| 9460 |
uint32_t* thread_nobs_base; |
| 9461 |
uint32_t* thread_monomorphic_ct; |
| 9462 |
uint32_t** thread_ohets; |
| 9463 |
double** thread_ehet_incrs; |
| 9464 |
int32_t** thread_nobs_incrs; |
| 9465 |
} HetCtx; |
| 9466 |
|
| 9467 |
THREAD_FUNC_DECL HetThread(void* raw_arg) { |
| 9468 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 9469 |
const uintptr_t tidx = arg->tidx; |
| 9470 |
HetCtx* ctx = S_CAST(HetCtx*, arg->sharedp->context); |
| 9471 |
|
| 9472 |
const uintptr_t* variant_subset = ctx->variant_subset; |
| 9473 |
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets; |
| 9474 |
const double* allele_freqs = ctx->allele_freqs; |
| 9475 |
const uintptr_t* sample_include = ctx->sample_include; |
| 9476 |
PgenReader* pgrp = ctx->pgr_ptrs[tidx]; |
| 9477 |
PgrSampleSubsetIndex pssi; |
| 9478 |
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi); |
| 9479 |
const uintptr_t* founder_info_collapsed = ctx->founder_info_collapsed; |
| 9480 |
const uintptr_t* founder_info_interleaved_vec = ctx->founder_info_interleaved_vec; |
| 9481 |
const uint32_t sample_ct = ctx->sample_ct; |
| 9482 |
const uint32_t founder_ct = ctx->founder_ct; |
| 9483 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 9484 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 9485 |
uintptr_t* genovec = ctx->genovecs[tidx]; |
| 9486 |
PgenVariant pgv; |
| 9487 |
pgv.genovec = genovec; |
| 9488 |
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv); |
| 9489 |
uintptr_t* raregeno = ctx->raregenos[tidx]; |
| 9490 |
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx]; |
| 9491 |
uint32_t* allele_nobs = nullptr; |
| 9492 |
if (ctx->thread_read_mhc) { |
| 9493 |
allele_nobs = ctx->allele_nobs_bufs[tidx]; |
| 9494 |
} |
| 9495 |
|
| 9496 |
// todo: tune this threshold |
| 9497 |
const uint32_t max_simple_difflist_len = sample_ct / 32; |
| 9498 |
|
| 9499 |
double ehet_base = 0.0; |
| 9500 |
uint32_t nobs_base = 0; |
| 9501 |
uint32_t monomorphic_ct = 0; |
| 9502 |
uint32_t* ohets = ctx->thread_ohets[tidx]; |
| 9503 |
double* ehet_incrs = ctx->thread_ehet_incrs[tidx]; |
| 9504 |
int32_t* nobs_incrs = ctx->thread_nobs_incrs[tidx]; |
| 9505 |
ZeroU32Arr(RoundUpPow2(sample_ct, kInt32PerVec), ohets); |
| 9506 |
ZeroDArr(sample_ct, ehet_incrs); |
| 9507 |
ZeroI32Arr(RoundUpPow2(sample_ct, kInt32PerVec), nobs_incrs); |
| 9508 |
const uint32_t acc2_vec_ct = NypCtToVecCt(sample_ct); |
| 9509 |
const uintptr_t dense_counts_vstride = acc2_vec_ct * 23; |
| 9510 |
VecW* scrambled_ohets = ctx->scrambled_ohet_bufs[tidx]; |
| 9511 |
uint32_t dense_ct_rem3 = 3; |
| 9512 |
uint32_t dense_ct_rem15d3 = 5; |
| 9513 |
uint32_t dense_ct_rem255d15 = 17; |
| 9514 |
ZeroVecArr(dense_counts_vstride, scrambled_ohets); |
| 9515 |
|
| 9516 |
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp); |
| 9517 |
|
| 9518 |
double ehet = 0.0; |
| 9519 |
uint32_t cur_allele_ct = 2; |
| 9520 |
uint64_t new_err_info = 0; |
| 9521 |
do { |
| 9522 |
const uint32_t cur_block_size = ctx->cur_block_size; |
| 9523 |
const uint32_t cur_idx_ct = (((tidx + 1) * cur_block_size) / calc_thread_ct) - ((tidx * cur_block_size) / calc_thread_ct); |
| 9524 |
uintptr_t variant_uidx_base; |
| 9525 |
uintptr_t cur_bits; |
| 9526 |
BitIter1Start(variant_subset, ctx->read_variant_uidx_starts[tidx], &variant_uidx_base, &cur_bits); |
| 9527 |
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) { |
| 9528 |
const uint32_t variant_uidx = BitIter1(variant_subset, &variant_uidx_base, &cur_bits); |
| 9529 |
uintptr_t allele_idx_offset_base; |
| 9530 |
if (!allele_idx_offsets) { |
| 9531 |
allele_idx_offset_base = variant_uidx * 2; |
| 9532 |
} else { |
| 9533 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 9534 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 9535 |
} |
| 9536 |
if (cur_allele_ct == 2) { |
| 9537 |
if (allele_freqs) { |
| 9538 |
const double ref_freq = allele_freqs[allele_idx_offset_base - variant_uidx]; |
| 9539 |
ehet = 2 * ref_freq * (1 - ref_freq); |
| 9540 |
if (ehet < kSmallishEpsilon) { |
| 9541 |
++monomorphic_ct; |
| 9542 |
continue; |
| 9543 |
} |
| 9544 |
} |
| 9545 |
uint32_t difflist_common_geno; |
| 9546 |
uint32_t difflist_len; |
| 9547 |
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len); |
| 9548 |
if (unlikely(reterr)) { |
| 9549 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 9550 |
goto HetThread_err; |
| 9551 |
} |
| 9552 |
if (difflist_common_geno != UINT32_MAX) { |
| 9553 |
ZeroTrailingNyps(difflist_len, raregeno); |
| 9554 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 9555 |
if (!allele_freqs) { |
| 9556 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 9557 |
genocounts[0] = 0; |
| 9558 |
genocounts[1] = 0; |
| 9559 |
genocounts[2] = 0; |
| 9560 |
genocounts[3] = 0; |
| 9561 |
if (word_ct) { |
| 9562 |
const uint32_t word_ct_m1 = word_ct - 1; |
| 9563 |
uint32_t loop_len = kBitsPerWordD2; |
| 9564 |
for (uint32_t widx = 0; ; ++widx) { |
| 9565 |
if (widx >= word_ct_m1) { |
| 9566 |
if (widx > word_ct_m1) { |
| 9567 |
break; |
| 9568 |
} |
| 9569 |
loop_len = ModNz(difflist_len, kBitsPerWordD2); |
| 9570 |
} |
| 9571 |
const uint32_t difflist_idx_base = widx * kBitsPerWordD2; |
| 9572 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]); |
| 9573 |
uintptr_t raregeno_word = raregeno[widx]; |
| 9574 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 9575 |
const uint32_t sample_idx = cur_difflist_sample_ids[uii]; |
| 9576 |
genocounts[raregeno_word & 3] += IsSet(founder_info_collapsed, sample_idx); |
| 9577 |
raregeno_word >>= 2; |
| 9578 |
} |
| 9579 |
} |
| 9580 |
} |
| 9581 |
genocounts[difflist_common_geno] += founder_ct - difflist_len; |
| 9582 |
const uint32_t numer1 = 2 * genocounts[0] + genocounts[1]; |
| 9583 |
const uint32_t numer2 = genocounts[1] + 2 * genocounts[2]; |
| 9584 |
if ((!numer1) || (!numer2)) { |
| 9585 |
++monomorphic_ct; |
| 9586 |
continue; |
| 9587 |
} |
| 9588 |
const uint32_t denom = numer1 + numer2; |
| 9589 |
ehet = 2 * S_CAST(double, numer1) * S_CAST(double, numer2) / ((S_CAST(double, denom)) * S_CAST(double, denom - 1)); |
| 9590 |
} |
| 9591 |
if (difflist_common_geno != 3) { |
| 9592 |
ehet_base += ehet; |
| 9593 |
++nobs_base; |
| 9594 |
for (uint32_t widx = 0; widx != word_ct; ++widx) { |
| 9595 |
const uintptr_t raregeno_word = raregeno[widx]; |
| 9596 |
const uint32_t difflist_idx_base = widx * kBitsPerWordD2; |
| 9597 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]); |
| 9598 |
uintptr_t het_word = (raregeno_word & kMask5555) & (~(raregeno_word >> 1)); |
| 9599 |
while (het_word) { |
| 9600 |
const uint32_t difflist_idx_lowbits = ctzw(het_word) / 2; |
| 9601 |
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits]; |
| 9602 |
ohets[sample_idx] += 1; |
| 9603 |
het_word &= het_word - 1; |
| 9604 |
} |
| 9605 |
uintptr_t missing_word = (raregeno_word & kMask5555) & (raregeno_word >> 1); |
| 9606 |
while (missing_word) { |
| 9607 |
const uint32_t difflist_idx_lowbits = ctzw(missing_word) / 2; |
| 9608 |
const uint32_t sample_idx = cur_difflist_sample_ids[difflist_idx_lowbits]; |
| 9609 |
ehet_incrs[sample_idx] -= ehet; |
| 9610 |
nobs_incrs[sample_idx] -= 1; |
| 9611 |
missing_word &= missing_word - 1; |
| 9612 |
} |
| 9613 |
} |
| 9614 |
} else { |
| 9615 |
if (!word_ct) { |
| 9616 |
++monomorphic_ct; |
| 9617 |
continue; |
| 9618 |
} |
| 9619 |
const uint32_t word_ct_m1 = word_ct - 1; |
| 9620 |
uint32_t loop_len = kBitsPerWordD2; |
| 9621 |
for (uint32_t widx = 0; ; ++widx) { |
| 9622 |
if (widx >= word_ct_m1) { |
| 9623 |
if (widx > word_ct_m1) { |
| 9624 |
break; |
| 9625 |
} |
| 9626 |
loop_len = ModNz(difflist_len, kBitsPerWordD2); |
| 9627 |
} |
| 9628 |
uintptr_t raregeno_word = raregeno[widx]; |
| 9629 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[widx * kBitsPerWordD2]); |
| 9630 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 9631 |
const uint32_t sample_idx = cur_difflist_sample_ids[uii]; |
| 9632 |
ohets[sample_idx] += raregeno_word & 1; |
| 9633 |
ehet_incrs[sample_idx] += ehet; |
| 9634 |
nobs_incrs[sample_idx] += 1; |
| 9635 |
raregeno_word >>= 2; |
| 9636 |
} |
| 9637 |
} |
| 9638 |
} |
| 9639 |
continue; |
| 9640 |
} |
| 9641 |
ZeroTrailingNyps(sample_ct, genovec); |
| 9642 |
if (!allele_freqs) { |
| 9643 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 9644 |
GenoarrCountSubsetFreqs(genovec, founder_info_interleaved_vec, sample_ct, founder_ct, genocounts); |
| 9645 |
const uint32_t numer1 = 2 * genocounts[0] + genocounts[1]; |
| 9646 |
const uint32_t numer2 = genocounts[1] + 2 * genocounts[2]; |
| 9647 |
if ((!numer1) || (!numer2)) { |
| 9648 |
++monomorphic_ct; |
| 9649 |
continue; |
| 9650 |
} |
| 9651 |
const uint32_t denom = numer1 + numer2; |
| 9652 |
ehet = 2 * S_CAST(double, numer1) * S_CAST(double, numer2) / ((S_CAST(double, denom)) * S_CAST(double, denom - 1)); |
| 9653 |
} |
| 9654 |
} else { |
| 9655 |
// multiallelic |
| 9656 |
if (allele_freqs) { |
| 9657 |
const double* cur_allele_freqs = &(allele_freqs[allele_idx_offset_base - variant_uidx]); |
| 9658 |
const uint32_t cur_allele_ct_m1 = cur_allele_ct - 1; |
| 9659 |
double freq_sum = 0.0; |
| 9660 |
double freq_ssq = 0.0; |
| 9661 |
for (uint32_t aidx = 0; aidx != cur_allele_ct_m1; ++aidx) { |
| 9662 |
const double cur_freq = cur_allele_freqs[aidx]; |
| 9663 |
freq_sum += cur_freq; |
| 9664 |
freq_ssq += cur_freq * cur_freq; |
| 9665 |
} |
| 9666 |
const double last_allele_freq = 1.0 - freq_sum; |
| 9667 |
ehet = 1.0 - freq_ssq - last_allele_freq * last_allele_freq; |
| 9668 |
if (ehet < kSmallishEpsilon) { |
| 9669 |
++monomorphic_ct; |
| 9670 |
continue; |
| 9671 |
} |
| 9672 |
} |
| 9673 |
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv); |
| 9674 |
if (unlikely(reterr)) { |
| 9675 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 9676 |
goto HetThread_err; |
| 9677 |
} |
| 9678 |
const uint32_t patch_10_ct = pgv.patch_10_ct; |
| 9679 |
const AlleleCode* patch_10_vals = pgv.patch_10_vals; |
| 9680 |
if (!allele_freqs) { |
| 9681 |
STD_ARRAY_DECL(uint32_t, 4, genocounts); |
| 9682 |
GenoarrCountSubsetFreqs(genovec, founder_info_interleaved_vec, sample_ct, founder_ct, genocounts); |
| 9683 |
allele_nobs[0] = 2 * genocounts[0] + genocounts[1]; |
| 9684 |
allele_nobs[1] = genocounts[1] + 2 * genocounts[2]; |
| 9685 |
const uint32_t denom = allele_nobs[0] + allele_nobs[1]; |
| 9686 |
if (!denom) { |
| 9687 |
++monomorphic_ct; |
| 9688 |
continue; |
| 9689 |
} |
| 9690 |
ZeroU32Arr(cur_allele_ct - 2, &(allele_nobs[2])); |
| 9691 |
const uint32_t patch_01_ct = pgv.patch_01_ct; |
| 9692 |
if (patch_01_ct) { |
| 9693 |
const uintptr_t* patch_01_set = pgv.patch_01_set; |
| 9694 |
const AlleleCode* patch_01_vals = pgv.patch_01_vals; |
| 9695 |
uintptr_t sample_idx_base = 0; |
| 9696 |
uintptr_t sample_idx_bits = patch_01_set[0]; |
| 9697 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 9698 |
const uintptr_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits); |
| 9699 |
allele_nobs[patch_01_vals[uii]] += IsSet(founder_info_collapsed, sample_idx); |
| 9700 |
} |
| 9701 |
allele_nobs[1] -= PopcountWordsIntersect(founder_info_collapsed, patch_01_set, sample_ctl); |
| 9702 |
} |
| 9703 |
if (patch_10_ct) { |
| 9704 |
const uintptr_t* patch_10_set = pgv.patch_10_set; |
| 9705 |
uintptr_t sample_idx_base = 0; |
| 9706 |
uintptr_t sample_idx_bits = patch_10_set[0]; |
| 9707 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 9708 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 9709 |
if (IsSet(founder_info_collapsed, sample_idx)) { |
| 9710 |
allele_nobs[patch_10_vals[2 * uii]] += 1; |
| 9711 |
allele_nobs[patch_10_vals[2 * uii + 1]] += 1; |
| 9712 |
} |
| 9713 |
} |
| 9714 |
allele_nobs[1] -= 2 * PopcountWordsIntersect(founder_info_collapsed, patch_10_set, sample_ctl); |
| 9715 |
} |
| 9716 |
|
| 9717 |
uint64_t allele_nobs_ssq = 0; |
| 9718 |
for (uint32_t uii = 0; uii != cur_allele_ct; ++uii) { |
| 9719 |
const uintptr_t cur_allele_nobs = allele_nobs[uii]; |
| 9720 |
allele_nobs_ssq += S_CAST(uint64_t, cur_allele_nobs) * cur_allele_nobs; |
| 9721 |
} |
| 9722 |
const double denom_d = S_CAST(double, denom); |
| 9723 |
ehet = (1.0 - (S_CAST(double, allele_nobs_ssq) / (denom_d * denom_d))) * (denom_d / S_CAST(double, denom - 1)); |
| 9724 |
} |
| 9725 |
if (patch_10_ct) { |
| 9726 |
// For every altx/alty genotype where x and y are different, change |
| 9727 |
// the genovec entry from 2 to 1. |
| 9728 |
const uintptr_t* patch_10_set = pgv.patch_10_set; |
| 9729 |
uintptr_t sample_idx_base = 0; |
| 9730 |
uintptr_t sample_idx_bits = patch_10_set[0]; |
| 9731 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 9732 |
const uintptr_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 9733 |
const AlleleCode a0 = patch_10_vals[uii * 2]; |
| 9734 |
const AlleleCode a1 = patch_10_vals[uii * 2 + 1]; |
| 9735 |
if (a0 != a1) { |
| 9736 |
const uintptr_t widx = sample_idx / kBitsPerWordD2; |
| 9737 |
const uint32_t bit_shift_ct = 2 * (sample_idx % kBitsPerWordD2); |
| 9738 |
genovec[widx] ^= (3 * k1LU) << bit_shift_ct; |
| 9739 |
} |
| 9740 |
} |
| 9741 |
} |
| 9742 |
} |
| 9743 |
ehet_base += ehet; |
| 9744 |
++nobs_base; |
| 9745 |
|
| 9746 |
// See e.g. UpdateDenseSampleCounts2(). |
| 9747 |
const VecW m1 = VCONST_W(kMask5555); |
| 9748 |
const VecW* genovvec = R_CAST(const VecW*, genovec); |
| 9749 |
for (uint32_t vidx = 0; vidx != acc2_vec_ct; ++vidx) { |
| 9750 |
const VecW vv = genovvec[vidx]; |
| 9751 |
const VecW vv_shifted = vecw_srli(vv, 1); |
| 9752 |
const VecW vv_lo_only = vv & m1; |
| 9753 |
scrambled_ohets[vidx] += vecw_and_notfirst(vv_shifted, vv_lo_only); |
| 9754 |
} |
| 9755 |
--dense_ct_rem3; |
| 9756 |
if (!dense_ct_rem3) { |
| 9757 |
VecW* acc4 = &(scrambled_ohets[acc2_vec_ct]); |
| 9758 |
Vcount0Incr2To4(acc2_vec_ct, scrambled_ohets, acc4); |
| 9759 |
--dense_ct_rem15d3; |
| 9760 |
if (!dense_ct_rem15d3) { |
| 9761 |
const uint32_t acc4_vec_ct = acc2_vec_ct * 2; |
| 9762 |
VecW* acc8 = &(acc4[acc4_vec_ct]); |
| 9763 |
Vcount0Incr4To8(acc4_vec_ct, acc4, acc8); |
| 9764 |
--dense_ct_rem255d15; |
| 9765 |
if (!dense_ct_rem255d15) { |
| 9766 |
const uint32_t acc8_vec_ct = acc4_vec_ct * 2; |
| 9767 |
VecW* acc32 = &(acc8[acc8_vec_ct]); |
| 9768 |
Vcount0Incr8To32(acc8_vec_ct, acc8, acc32); |
| 9769 |
dense_ct_rem255d15 = 17; |
| 9770 |
} |
| 9771 |
dense_ct_rem15d3 = 5; |
| 9772 |
} |
| 9773 |
dense_ct_rem3 = 3; |
| 9774 |
} |
| 9775 |
|
| 9776 |
for (uint32_t widx = 0; widx != sample_ctl2; ++widx) { |
| 9777 |
const uintptr_t geno_word = genovec[widx]; |
| 9778 |
uintptr_t missing_word = geno_word & (geno_word >> 1) & kMask5555; |
| 9779 |
if (!missing_word) { |
| 9780 |
continue; |
| 9781 |
} |
| 9782 |
uint32_t sample_idx_base = widx * kBitsPerWordD2; |
| 9783 |
double* cur_ehet_incrs = &(ehet_incrs[sample_idx_base]); |
| 9784 |
int32_t* cur_nobs_incrs = &(nobs_incrs[sample_idx_base]); |
| 9785 |
do { |
| 9786 |
const uint32_t sample_idx_lowbits = ctzw(missing_word) / 2; |
| 9787 |
cur_ehet_incrs[sample_idx_lowbits] -= ehet; |
| 9788 |
cur_nobs_incrs[sample_idx_lowbits] -= 1; |
| 9789 |
missing_word &= missing_word - 1; |
| 9790 |
} while (missing_word); |
| 9791 |
} |
| 9792 |
} |
| 9793 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 9794 |
{ |
| 9795 |
ctx->thread_ehet_base[tidx] = ehet_base; |
| 9796 |
ctx->thread_nobs_base[tidx] = nobs_base; |
| 9797 |
ctx->thread_monomorphic_ct[tidx] = monomorphic_ct; |
| 9798 |
|
| 9799 |
VecW* acc4 = &(scrambled_ohets[acc2_vec_ct]); |
| 9800 |
VcountIncr2To4(scrambled_ohets, acc2_vec_ct, acc4); |
| 9801 |
const uint32_t acc4_vec_ct = acc2_vec_ct * 2; |
| 9802 |
VecW* acc8 = &(acc4[acc4_vec_ct]); |
| 9803 |
VcountIncr4To8(acc4, acc4_vec_ct, acc8); |
| 9804 |
const uint32_t acc8_vec_ct = acc4_vec_ct * 2; |
| 9805 |
VecW* acc32 = &(acc8[acc8_vec_ct]); |
| 9806 |
VcountIncr8To32(acc8, acc8_vec_ct, acc32); |
| 9807 |
uint32_t* acc32_alias = R_CAST(uint32_t*, acc32); |
| 9808 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 9809 |
const uint32_t scrambled_idx = VcountScramble2(sample_idx); |
| 9810 |
ohets[sample_idx] += acc32_alias[scrambled_idx]; |
| 9811 |
} |
| 9812 |
} |
| 9813 |
while (0) { |
| 9814 |
HetThread_err: |
| 9815 |
UpdateU64IfSmaller(new_err_info, &ctx->err_info); |
| 9816 |
THREAD_BLOCK_FINISH(arg); |
| 9817 |
break; |
| 9818 |
} |
| 9819 |
THREAD_RETURN; |
| 9820 |
} |
| 9821 |
|
| 9822 |
PglErr HetCalcMain(const uintptr_t* sample_include, const uintptr_t* variant_subset, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const uintptr_t* founder_info, const char* calcstr, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t founder_ct, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t small_sample, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, uint32_t** ohets_ptr, double** ehet_incrs_ptr, int32_t** nobs_incrs_ptr, double* ehet_base_ptr, int32_t* nobs_base_ptr) { |
| 9823 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 9824 |
PglErr reterr = kPglRetSuccess; |
| 9825 |
ThreadGroup tg; |
| 9826 |
PreinitThreads(&tg); |
| 9827 |
HetCtx ctx; |
| 9828 |
{ |
| 9829 |
// return values |
| 9830 |
if (unlikely(bigstack_alloc_u32(sample_ct, ohets_ptr) || |
| 9831 |
bigstack_alloc_d(sample_ct, ehet_incrs_ptr) || |
| 9832 |
bigstack_alloc_i32(sample_ct, nobs_incrs_ptr))) { |
| 9833 |
goto HetCalcMain_ret_NOMEM; |
| 9834 |
} |
| 9835 |
bigstack_mark = g_bigstack_base; |
| 9836 |
|
| 9837 |
ctx.variant_subset = variant_subset; |
| 9838 |
ctx.allele_idx_offsets = allele_idx_offsets; |
| 9839 |
ctx.sample_include = sample_include; |
| 9840 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 9841 |
uint32_t* sample_include_cumulative_popcounts; |
| 9842 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts))) { |
| 9843 |
goto HetCalcMain_ret_NOMEM; |
| 9844 |
} |
| 9845 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 9846 |
ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts; |
| 9847 |
ctx.founder_info_collapsed = nullptr; |
| 9848 |
ctx.founder_info_interleaved_vec = nullptr; |
| 9849 |
ctx.allele_freqs = allele_freqs; |
| 9850 |
if (small_sample) { |
| 9851 |
const uint32_t sample_ctaw = BitCtToAlignedWordCt(sample_ct); |
| 9852 |
uintptr_t* founder_info_collapsed; |
| 9853 |
uintptr_t* founder_info_interleaved_vec; |
| 9854 |
if (unlikely(bigstack_alloc_w(sample_ctaw, &founder_info_collapsed) || |
| 9855 |
bigstack_alloc_w(sample_ctaw, &founder_info_interleaved_vec))) { |
| 9856 |
goto HetCalcMain_ret_NOMEM; |
| 9857 |
} |
| 9858 |
CopyBitarrSubset(founder_info, sample_include, sample_ct, founder_info_collapsed); |
| 9859 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 9860 |
ZeroWArr(sample_ctaw - sample_ctl, &(founder_info_collapsed[sample_ctl])); |
| 9861 |
FillInterleavedMaskVec(founder_info_collapsed, sample_ctaw / kWordsPerVec, founder_info_interleaved_vec); |
| 9862 |
ctx.founder_info_collapsed = founder_info_collapsed; |
| 9863 |
ctx.founder_info_interleaved_vec = founder_info_interleaved_vec; |
| 9864 |
ctx.allele_freqs = nullptr; |
| 9865 |
} |
| 9866 |
ctx.sample_ct = sample_ct; |
| 9867 |
ctx.founder_ct = founder_ct; |
| 9868 |
|
| 9869 |
uint32_t calc_thread_ct = max_thread_ct; |
| 9870 |
if (unlikely(bigstack_alloc_wp(calc_thread_ct, &ctx.raregenos) || |
| 9871 |
bigstack_alloc_u32p(calc_thread_ct, &ctx.difflist_sample_id_bufs) || |
| 9872 |
bigstack_alloc_vp(calc_thread_ct, &ctx.scrambled_ohet_bufs) || |
| 9873 |
bigstack_alloc_d(calc_thread_ct, &ctx.thread_ehet_base) || |
| 9874 |
bigstack_alloc_u32(calc_thread_ct, &ctx.thread_nobs_base) || |
| 9875 |
bigstack_alloc_u32(calc_thread_ct, &ctx.thread_monomorphic_ct) || |
| 9876 |
bigstack_alloc_u32p(calc_thread_ct, &ctx.thread_ohets) || |
| 9877 |
bigstack_alloc_dp(calc_thread_ct, &ctx.thread_ehet_incrs) || |
| 9878 |
bigstack_alloc_i32p(calc_thread_ct, &ctx.thread_nobs_incrs))) { |
| 9879 |
goto HetCalcMain_ret_NOMEM; |
| 9880 |
} |
| 9881 |
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor); |
| 9882 |
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec); |
| 9883 |
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec); |
| 9884 |
const uint32_t mhc_needed = (max_allele_ct > 2); |
| 9885 |
uintptr_t allele_nobs_vec_ct = 0; |
| 9886 |
ctx.allele_nobs_bufs = nullptr; |
| 9887 |
if (mhc_needed) { |
| 9888 |
if (unlikely(bigstack_alloc_u32p(calc_thread_ct, &ctx.allele_nobs_bufs))) { |
| 9889 |
goto HetCalcMain_ret_NOMEM; |
| 9890 |
} |
| 9891 |
allele_nobs_vec_ct = DivUp(max_allele_ct, kInt32PerVec); |
| 9892 |
} |
| 9893 |
|
| 9894 |
const uintptr_t acc2_vec_ct = NypCtToVecCt(sample_ct); |
| 9895 |
const uintptr_t scrambled_ohet_vec_ct = acc2_vec_ct * 23; |
| 9896 |
const uintptr_t sample_ct_i32v = DivUp(sample_ct, kInt32PerVec); |
| 9897 |
const uintptr_t sample_ct_dv = DivUp(sample_ct * sizeof(double), kBytesPerVec); |
| 9898 |
|
| 9899 |
const uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + allele_nobs_vec_ct + scrambled_ohet_vec_ct + 2 * sample_ct_i32v + sample_ct_dv; |
| 9900 |
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline); |
| 9901 |
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs); |
| 9902 |
ctx.thread_read_mhc = nullptr; |
| 9903 |
uint32_t read_block_size; |
| 9904 |
if (unlikely(PgenMtLoadInit(ctx.variant_subset, raw_sample_ct, variant_ct, bigstack_left(), pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, 0, 0, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, nullptr, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) { |
| 9905 |
goto HetCalcMain_ret_NOMEM; |
| 9906 |
} |
| 9907 |
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) { |
| 9908 |
goto HetCalcMain_ret_NOMEM; |
| 9909 |
} |
| 9910 |
ctx.err_info = (~0LLU) << 32; |
| 9911 |
assert(bigstack_left() >= thread_xalloc_cacheline_ct * kCacheline * calc_thread_ct); |
| 9912 |
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) { |
| 9913 |
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_alloc_raw(thread_xalloc_cacheline_ct * kCacheline)); |
| 9914 |
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc); |
| 9915 |
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]); |
| 9916 |
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 9917 |
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]); |
| 9918 |
if (mhc_needed) { |
| 9919 |
ctx.allele_nobs_bufs[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 9920 |
cur_alloc = &(cur_alloc[allele_nobs_vec_ct * kBytesPerVec]); |
| 9921 |
} |
| 9922 |
ctx.scrambled_ohet_bufs[tidx] = R_CAST(VecW*, cur_alloc); |
| 9923 |
cur_alloc = &(cur_alloc[scrambled_ohet_vec_ct * kBytesPerVec]); |
| 9924 |
if (!tidx) { |
| 9925 |
ctx.thread_ohets[0] = *ohets_ptr; |
| 9926 |
ctx.thread_ehet_incrs[0] = *ehet_incrs_ptr; |
| 9927 |
ctx.thread_nobs_incrs[0] = *nobs_incrs_ptr; |
| 9928 |
} else { |
| 9929 |
ctx.thread_ohets[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 9930 |
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]); |
| 9931 |
ctx.thread_ehet_incrs[tidx] = R_CAST(double*, cur_alloc); |
| 9932 |
cur_alloc = &(cur_alloc[sample_ct_dv * kBytesPerVec]); |
| 9933 |
ctx.thread_nobs_incrs[tidx] = R_CAST(int32_t*, cur_alloc); |
| 9934 |
cur_alloc = &(cur_alloc[sample_ct_i32v * kBytesPerVec]); |
| 9935 |
assert(cur_alloc <= g_bigstack_base); |
| 9936 |
} |
| 9937 |
} |
| 9938 |
SetThreadFuncAndData(HetThread, &ctx, &tg); |
| 9939 |
|
| 9940 |
logprintf("%s: ", calcstr); |
| 9941 |
fputs("0%", stdout); |
| 9942 |
fflush(stdout); |
| 9943 |
uint32_t pct = 0; |
| 9944 |
|
| 9945 |
uint32_t parity = 0; |
| 9946 |
uint32_t read_block_idx = 0; |
| 9947 |
uint32_t next_print_variant_idx = variant_ct / 100; |
| 9948 |
for (uint32_t variant_idx = 0; ; ) { |
| 9949 |
const uint32_t cur_block_size = MultireadNonempty(ctx.variant_subset, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr); |
| 9950 |
if (unlikely(reterr)) { |
| 9951 |
goto HetCalcMain_ret_PGR_FAIL; |
| 9952 |
} |
| 9953 |
if (variant_idx) { |
| 9954 |
JoinThreads(&tg); |
| 9955 |
reterr = S_CAST(PglErr, ctx.err_info); |
| 9956 |
if (unlikely(reterr)) { |
| 9957 |
PgenErrPrintNV(reterr, ctx.err_info >> 32); |
| 9958 |
goto HetCalcMain_ret_1; |
| 9959 |
} |
| 9960 |
} |
| 9961 |
if (!IsLastBlock(&tg)) { |
| 9962 |
ctx.cur_block_size = cur_block_size; |
| 9963 |
ComputeUidxStartPartition(ctx.variant_subset, cur_block_size, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts); |
| 9964 |
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs); |
| 9965 |
if (variant_idx + cur_block_size == variant_ct) { |
| 9966 |
DeclareLastThreadBlock(&tg); |
| 9967 |
} |
| 9968 |
if (unlikely(SpawnThreads(&tg))) { |
| 9969 |
goto HetCalcMain_ret_THREAD_CREATE_FAIL; |
| 9970 |
} |
| 9971 |
} |
| 9972 |
|
| 9973 |
parity = 1 - parity; |
| 9974 |
if (variant_idx == variant_ct) { |
| 9975 |
break; |
| 9976 |
} |
| 9977 |
if (variant_idx >= next_print_variant_idx) { |
| 9978 |
if (pct > 10) { |
| 9979 |
putc_unlocked('\b', stdout); |
| 9980 |
} |
| 9981 |
pct = (variant_idx * 100LLU) / variant_ct; |
| 9982 |
printf("\b\b%u%%", pct++); |
| 9983 |
fflush(stdout); |
| 9984 |
next_print_variant_idx = (pct * S_CAST(uint64_t, variant_ct)) / 100; |
| 9985 |
} |
| 9986 |
|
| 9987 |
++read_block_idx; |
| 9988 |
variant_idx += cur_block_size; |
| 9989 |
pgfip->block_base = main_loadbufs[parity]; |
| 9990 |
} |
| 9991 |
double ehet_base = ctx.thread_ehet_base[0]; |
| 9992 |
uint32_t nobs_base = ctx.thread_nobs_base[0]; |
| 9993 |
uint32_t monomorphic_ct = ctx.thread_monomorphic_ct[0]; |
| 9994 |
uint32_t* ohets = *ohets_ptr; |
| 9995 |
double* ehet_incrs = *ehet_incrs_ptr; |
| 9996 |
int32_t* nobs_incrs = *nobs_incrs_ptr; |
| 9997 |
for (uint32_t tidx = 1; tidx != calc_thread_ct; ++tidx) { |
| 9998 |
ehet_base += ctx.thread_ehet_base[tidx]; |
| 9999 |
nobs_base += ctx.thread_nobs_base[tidx]; |
| 10000 |
monomorphic_ct += ctx.thread_monomorphic_ct[tidx]; |
| 10001 |
U32CastVecAdd(ctx.thread_ohets[tidx], sample_ct_i32v, ohets); |
| 10002 |
const double* src = ctx.thread_ehet_incrs[tidx]; |
| 10003 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 10004 |
ehet_incrs[sample_idx] += src[sample_idx]; |
| 10005 |
} |
| 10006 |
I32CastVecAdd(ctx.thread_nobs_incrs[tidx], sample_ct_i32v, nobs_incrs); |
| 10007 |
} |
| 10008 |
if (pct > 10) { |
| 10009 |
putc_unlocked('\b', stdout); |
| 10010 |
} |
| 10011 |
fputs("\b\b", stdout); |
| 10012 |
logputs("done.\n"); |
| 10013 |
if (monomorphic_ct) { |
| 10014 |
logerrprintfww("Warning: %u variant%s skipped because %s monomorphic.%s\n", monomorphic_ct, (monomorphic_ct == 1)? "" : "s", (monomorphic_ct == 1)? "it was" : "they were", small_sample? "" : " You may want to use --read-freq to provide more accurate allele frequency estimates."); |
| 10015 |
} |
| 10016 |
*ehet_base_ptr = ehet_base; |
| 10017 |
*nobs_base_ptr = nobs_base; |
| 10018 |
} |
| 10019 |
while (0) { |
| 10020 |
HetCalcMain_ret_NOMEM: |
| 10021 |
reterr = kPglRetNomem; |
| 10022 |
break; |
| 10023 |
HetCalcMain_ret_PGR_FAIL: |
| 10024 |
PgenErrPrintN(reterr); |
| 10025 |
break; |
| 10026 |
HetCalcMain_ret_THREAD_CREATE_FAIL: |
| 10027 |
reterr = kPglRetThreadCreateFail; |
| 10028 |
break; |
| 10029 |
} |
| 10030 |
HetCalcMain_ret_1: |
| 10031 |
CleanupThreads(&tg); |
| 10032 |
BigstackReset(bigstack_mark); |
| 10033 |
pgfip->block_base = nullptr; |
| 10034 |
return reterr; |
| 10035 |
} |
| 10036 |
|
| 10037 |
PglErr HetReport(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const uintptr_t* founder_info, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t founder_ct, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t max_allele_ct, HetFlags flags, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) { |
| 10038 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 10039 |
char* cswritep = nullptr; |
| 10040 |
CompressStreamState css; |
| 10041 |
PglErr reterr = kPglRetSuccess; |
| 10042 |
PreinitCstream(&css); |
| 10043 |
{ |
| 10044 |
if (IsSet(cip->haploid_mask, 0)) { |
| 10045 |
logerrputs("Error: --het cannot be used on haploid genomes.\n"); |
| 10046 |
goto HetReport_ret_INCONSISTENT_INPUT; |
| 10047 |
} |
| 10048 |
const uint32_t small_sample = (flags / kfHetSmallSample) & 1; |
| 10049 |
if (small_sample && (!founder_ct)) { |
| 10050 |
logerrputs("Error: '--het small-sample' requires founders. (--make-founders may come in\nhandy here.\n)"); |
| 10051 |
goto HetReport_ret_INCONSISTENT_INPUT; |
| 10052 |
} |
| 10053 |
|
| 10054 |
const uintptr_t* autosomal_variant_include = orig_variant_include; |
| 10055 |
uint32_t autosomal_variant_ct = orig_variant_ct; |
| 10056 |
reterr = ConditionalAllocateNonAutosomalVariants(cip, "--het", raw_variant_ct, &autosomal_variant_include, &autosomal_variant_ct); |
| 10057 |
if (!autosomal_variant_ct) { |
| 10058 |
goto HetReport_ret_NO_VARIATION; |
| 10059 |
} |
| 10060 |
|
| 10061 |
const uint32_t output_zst = flags & kfHetZs; |
| 10062 |
OutnameZstSet(".het", output_zst, outname_end); |
| 10063 |
reterr = InitCstreamAlloc(outname, 0, output_zst, 1, 2 * kCompressStreamBlock, &css, &cswritep); |
| 10064 |
if (unlikely(reterr)) { |
| 10065 |
goto HetReport_ret_1; |
| 10066 |
} |
| 10067 |
*cswritep++ = '#'; |
| 10068 |
const uint32_t col_fid = FidColIsRequired(siip, flags / kfHetColMaybefid); |
| 10069 |
if (col_fid) { |
| 10070 |
cswritep = strcpya_k(cswritep, "FID\t"); |
| 10071 |
} |
| 10072 |
cswritep = strcpya_k(cswritep, "IID"); |
| 10073 |
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfHetColMaybesid); |
| 10074 |
if (col_sid) { |
| 10075 |
cswritep = strcpya_k(cswritep, "\tSID"); |
| 10076 |
} |
| 10077 |
const uint32_t col_hom = (flags / kfHetColHom) & 1; |
| 10078 |
if (col_hom) { |
| 10079 |
cswritep = strcpya_k(cswritep, "\tO(HOM)\tE(HOM)"); |
| 10080 |
} |
| 10081 |
const uint32_t col_het = (flags / kfHetColHet) & 1; |
| 10082 |
if (col_het) { |
| 10083 |
cswritep = strcpya_k(cswritep, "\tO(HET)\tE(HET)"); |
| 10084 |
} |
| 10085 |
const uint32_t col_nobs = (flags / kfHetColNobs) & 1; |
| 10086 |
if (col_nobs) { |
| 10087 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 10088 |
} |
| 10089 |
const uint32_t col_f = (flags / kfHetColF) & 1; |
| 10090 |
if (col_f) { |
| 10091 |
cswritep = strcpya_k(cswritep, "\tF"); |
| 10092 |
} |
| 10093 |
AppendBinaryEoln(&cswritep); |
| 10094 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 10095 |
goto HetReport_ret_WRITE_FAIL; |
| 10096 |
} |
| 10097 |
|
| 10098 |
uint32_t* ohets; |
| 10099 |
double* ehet_incrs; |
| 10100 |
int32_t* nobs_incrs; |
| 10101 |
double ehet_base; |
| 10102 |
int32_t nobs_base; |
| 10103 |
reterr = HetCalcMain(sample_include, autosomal_variant_include, allele_idx_offsets, allele_freqs, founder_info, "--het", raw_sample_ct, sample_ct, founder_ct, raw_variant_ct, autosomal_variant_ct, max_allele_ct, small_sample, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, &ohets, &ehet_incrs, &nobs_incrs, &ehet_base, &nobs_base); |
| 10104 |
if (unlikely(reterr)) { |
| 10105 |
goto HetReport_ret_1; |
| 10106 |
} |
| 10107 |
const char* sample_ids = siip->sample_ids; |
| 10108 |
const char* sids = siip->sids; |
| 10109 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 10110 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 10111 |
uintptr_t sample_uidx_base = 0; |
| 10112 |
uintptr_t cur_bits = sample_include[0]; |
| 10113 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 10114 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 10115 |
cswritep = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, cswritep); |
| 10116 |
const uint32_t ohet = ohets[sample_idx]; |
| 10117 |
const double ehet = ehet_base + ehet_incrs[sample_idx]; |
| 10118 |
const uint32_t nobs = nobs_base + nobs_incrs[sample_idx]; |
| 10119 |
if (col_hom) { |
| 10120 |
*cswritep++ = '\t'; |
| 10121 |
cswritep = u32toa_x(nobs - ohet, '\t', cswritep); |
| 10122 |
cswritep = dtoa_g(u31tod(nobs) - ehet, cswritep); |
| 10123 |
} |
| 10124 |
if (col_het) { |
| 10125 |
*cswritep++ = '\t'; |
| 10126 |
cswritep = u32toa_x(ohet, '\t', cswritep); |
| 10127 |
cswritep = dtoa_g(ehet, cswritep); |
| 10128 |
} |
| 10129 |
if (col_nobs) { |
| 10130 |
*cswritep++ = '\t'; |
| 10131 |
cswritep = u32toa(nobs, cswritep); |
| 10132 |
} |
| 10133 |
if (col_f) { |
| 10134 |
*cswritep++ = '\t'; |
| 10135 |
cswritep = dtoa_g(1.0 - u31tod(ohet) / ehet, cswritep); |
| 10136 |
} |
| 10137 |
AppendBinaryEoln(&cswritep); |
| 10138 |
if (unlikely(Cswrite(&css, &cswritep))) { |
| 10139 |
goto HetReport_ret_WRITE_FAIL; |
| 10140 |
} |
| 10141 |
} |
| 10142 |
if (unlikely(CswriteCloseNull(&css, cswritep))) { |
| 10143 |
goto HetReport_ret_WRITE_FAIL; |
| 10144 |
} |
| 10145 |
logprintfww("--het: Results written to %s .\n", outname); |
| 10146 |
} |
| 10147 |
while (0) { |
| 10148 |
HetReport_ret_WRITE_FAIL: |
| 10149 |
reterr = kPglRetWriteFail; |
| 10150 |
break; |
| 10151 |
HetReport_ret_NO_VARIATION: |
| 10152 |
logerrputs("Error: --het requires at least one polymorphic autosomal variant.\n"); |
| 10153 |
HetReport_ret_INCONSISTENT_INPUT: |
| 10154 |
reterr = kPglRetInconsistentInput; |
| 10155 |
break; |
| 10156 |
} |
| 10157 |
HetReport_ret_1: |
| 10158 |
CswriteCloseCond(&css, cswritep); |
| 10159 |
BigstackReset(bigstack_mark); |
| 10160 |
return reterr; |
| 10161 |
} |
| 10162 |
|
| 10163 |
PglErr CheckOrImputeSex(const uintptr_t* sample_include, const SampleIdInfo* siip, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uintptr_t* allele_idx_offsets, const double* allele_freqs, const CheckSexInfo* csip, uint32_t raw_sample_ct, uint32_t sample_ct, uint32_t raw_variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, uintptr_t* sex_nm, uintptr_t* sex_male, PgenFileInfo* pgfip, char* outname, char* outname_end) { |
| 10164 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 10165 |
FILE* outfile = nullptr; |
| 10166 |
PglErr reterr = kPglRetSuccess; |
| 10167 |
{ |
| 10168 |
const CheckSexFlags flags = csip->flags; |
| 10169 |
const char* flagstr = (flags & kfCheckSexImpute)? "--impute-sex" : "--check-sex"; |
| 10170 |
if (IsSet(cip->haploid_mask, 0)) { |
| 10171 |
snprintf(g_logbuf, kLogbufSize, "Error: %s cannot be used on haploid genomes.\n", flagstr); |
| 10172 |
goto CheckOrImputeSex_ret_INCONSISTENT_INPUT_2; |
| 10173 |
} |
| 10174 |
|
| 10175 |
double* xfs = nullptr; |
| 10176 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 10177 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 10178 |
double max_female_xf = csip->max_female_xf; |
| 10179 |
double min_male_xf = csip->min_male_xf; |
| 10180 |
uint32_t used_variant_ct_x = 0; |
| 10181 |
uint32_t x_code; |
| 10182 |
if ((flags & kfCheckSexUseX) && XymtExists(cip, kChrOffsetX, &x_code)) { |
| 10183 |
used_variant_ct_x = CountChrVariantsUnsafe(orig_variant_include, cip, x_code); |
| 10184 |
if (used_variant_ct_x) { |
| 10185 |
if (max_female_xf == -1.0) { |
| 10186 |
max_female_xf = PrevFloat64(min_male_xf); |
| 10187 |
} else if (min_male_xf == -1.0) { |
| 10188 |
min_male_xf = NextFloat64(max_female_xf); |
| 10189 |
} |
| 10190 |
uintptr_t* variant_include_x; |
| 10191 |
if (unlikely(bigstack_alloc_d(sample_ct, &xfs) || |
| 10192 |
bigstack_alloc_w(raw_variant_ctl, &variant_include_x))) { |
| 10193 |
goto CheckOrImputeSex_ret_NOMEM; |
| 10194 |
} |
| 10195 |
const uint32_t x_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 10196 |
const uint32_t x_start = cip->chr_fo_vidx_start[x_fo_idx]; |
| 10197 |
const uint32_t x_end = cip->chr_fo_vidx_start[x_fo_idx + 1]; |
| 10198 |
const uint32_t x_start_widx = x_start / kBitsPerWord; |
| 10199 |
const uint32_t x_end_widx = (x_end + kBitsPerWord - 1) / kBitsPerWord; |
| 10200 |
memcpy(&(variant_include_x[x_start_widx]), &(orig_variant_include[x_start_widx]), (x_end_widx - x_start_widx) * sizeof(intptr_t)); |
| 10201 |
if (x_start) { |
| 10202 |
ClearBitsNz(0, x_start, variant_include_x); |
| 10203 |
} |
| 10204 |
// bugfix (17 Dec 2024): trailing bits must also be zeroed out |
| 10205 |
const uint32_t raw_variant_ct_rounded_up = RoundUpPow2(raw_variant_ct, kBitsPerWord); |
| 10206 |
if (x_end < raw_variant_ct_rounded_up) { |
| 10207 |
ClearBitsNz(x_end, raw_variant_ct_rounded_up, variant_include_x); |
| 10208 |
} |
| 10209 |
// Don't actually need nobs. |
| 10210 |
uint32_t* ohets; |
| 10211 |
double* ehet_incrs; |
| 10212 |
int32_t* nobs_incrs; |
| 10213 |
double ehet_base; |
| 10214 |
int32_t nobs_base; |
| 10215 |
reterr = HetCalcMain(sample_include, variant_include_x, allele_idx_offsets, allele_freqs, nullptr, (flags & kfCheckSexImpute)? "--impute-sex chrX" : "--check-sex chrX", raw_sample_ct, sample_ct, sample_ct, raw_variant_ct, used_variant_ct_x, max_allele_ct, 0, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, &ohets, &ehet_incrs, &nobs_incrs, &ehet_base, &nobs_base); |
| 10216 |
if (unlikely(reterr)) { |
| 10217 |
goto CheckOrImputeSex_ret_1; |
| 10218 |
} |
| 10219 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 10220 |
const uint32_t ohet = ohets[sample_idx]; |
| 10221 |
const double ehet = ehet_base + ehet_incrs[sample_idx]; |
| 10222 |
xfs[sample_idx] = 1.0 - u31tod(ohet) / ehet; |
| 10223 |
} |
| 10224 |
BigstackReset(variant_include_x); |
| 10225 |
} |
| 10226 |
} |
| 10227 |
uint32_t* y_valid_geno_cts = nullptr; |
| 10228 |
uint32_t max_female_ycount = csip->max_female_ycount; |
| 10229 |
uint32_t min_male_ycount = csip->min_male_ycount; |
| 10230 |
uint32_t used_variant_ct_y = 0; |
| 10231 |
uint32_t y_code = 0; |
| 10232 |
if ((flags & kfCheckSexUseY) && XymtExists(cip, kChrOffsetY, &y_code)) { |
| 10233 |
used_variant_ct_y = CountChrVariantsUnsafe(orig_variant_include, cip, y_code); |
| 10234 |
if (used_variant_ct_y) { |
| 10235 |
if (max_female_ycount == UINT32_MAX) { |
| 10236 |
if (min_male_ycount != UINT32_MAX) { |
| 10237 |
max_female_ycount = min_male_ycount - 1; |
| 10238 |
} else { |
| 10239 |
// No ycount condition specified. yrate condition will be merged |
| 10240 |
// correctly if we initialize max_female_ycount=UINT32_MAX, |
| 10241 |
// min_male_ycount=0. |
| 10242 |
min_male_ycount = 0; |
| 10243 |
} |
| 10244 |
} else if (min_male_ycount == UINT32_MAX) { |
| 10245 |
min_male_ycount = max_female_ycount + 1; |
| 10246 |
} |
| 10247 |
{ |
| 10248 |
const double max_female_yrate = csip->max_female_yrate; |
| 10249 |
const double min_male_yrate = csip->min_male_yrate; |
| 10250 |
if (max_female_yrate != -1.0) { |
| 10251 |
const uint32_t uii = S_CAST(int32_t, max_female_yrate * used_variant_ct_y); |
| 10252 |
if (uii < max_female_ycount) { |
| 10253 |
max_female_ycount = uii; |
| 10254 |
} |
| 10255 |
} |
| 10256 |
if (min_male_yrate != -1.0) { |
| 10257 |
const uint32_t uii = used_variant_ct_y - S_CAST(int32_t, (1.0 - min_male_yrate) * used_variant_ct_y); |
| 10258 |
if (uii > min_male_ycount) { |
| 10259 |
min_male_ycount = uii; |
| 10260 |
} |
| 10261 |
} |
| 10262 |
} |
| 10263 |
uintptr_t* variant_include_y; |
| 10264 |
uint32_t* sample_missing_hc_cts; |
| 10265 |
uint32_t* sample_hethap_cts; |
| 10266 |
if (unlikely(bigstack_alloc_u32(sample_ct, &y_valid_geno_cts) || |
| 10267 |
bigstack_alloc_w(raw_variant_ctl, &variant_include_y) || |
| 10268 |
bigstack_alloc_u32(raw_sample_ct, &sample_missing_hc_cts) || |
| 10269 |
bigstack_alloc_u32(raw_sample_ct, &sample_hethap_cts))) { |
| 10270 |
goto CheckOrImputeSex_ret_NOMEM; |
| 10271 |
} |
| 10272 |
const uint32_t y_fo_idx = cip->chr_idx_to_foidx[y_code]; |
| 10273 |
const uint32_t y_start = cip->chr_fo_vidx_start[y_fo_idx]; |
| 10274 |
const uint32_t y_end = cip->chr_fo_vidx_start[y_fo_idx + 1]; |
| 10275 |
const uint32_t y_start_widx = y_start / kBitsPerWord; |
| 10276 |
const uint32_t y_end_widx = (y_end + kBitsPerWord - 1) / kBitsPerWord; |
| 10277 |
memcpy(&(variant_include_y[y_start_widx]), &(orig_variant_include[y_start_widx]), (y_end_widx - y_start_widx) * sizeof(intptr_t)); |
| 10278 |
if (y_start) { |
| 10279 |
ClearBitsNz(0, y_start, variant_include_y); |
| 10280 |
} |
| 10281 |
const uint32_t raw_variant_ct_rounded_up = RoundUpPow2(raw_variant_ct, kBitsPerWord); |
| 10282 |
if (y_end < raw_variant_ct_rounded_up) { |
| 10283 |
ClearBitsNz(y_end, raw_variant_ct_rounded_up, variant_include_y); |
| 10284 |
} |
| 10285 |
logprintf("%s: ", flagstr); |
| 10286 |
reterr = LoadSampleMissingCts(sample_include, sample_include, variant_include_y, cip, "chrY valid genotype call", raw_variant_ct, used_variant_ct_y, raw_sample_ct, 0, max_thread_ct, pgr_alloc_cacheline_ct, pgfip, sample_missing_hc_cts, nullptr, sample_hethap_cts); |
| 10287 |
if (unlikely(reterr)) { |
| 10288 |
goto CheckOrImputeSex_ret_1; |
| 10289 |
} |
| 10290 |
uintptr_t sample_uidx_base = 0; |
| 10291 |
uintptr_t cur_bits = sample_include[0]; |
| 10292 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 10293 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 10294 |
y_valid_geno_cts[sample_idx] = used_variant_ct_y - sample_missing_hc_cts[sample_uidx] - sample_hethap_cts[sample_uidx]; |
| 10295 |
} |
| 10296 |
BigstackReset(variant_include_y); |
| 10297 |
} |
| 10298 |
} |
| 10299 |
if (unlikely((!used_variant_ct_x) && (!used_variant_ct_y))) { |
| 10300 |
snprintf(g_logbuf, kLogbufSize, "Error: %s: No usable variants.\n", flagstr); |
| 10301 |
goto CheckOrImputeSex_ret_INCONSISTENT_INPUT_2; |
| 10302 |
} |
| 10303 |
uintptr_t* imputed_sex_nm; |
| 10304 |
uintptr_t* imputed_sex_male; |
| 10305 |
if (unlikely(bigstack_calloc_w(raw_sample_ctl, &imputed_sex_nm) || |
| 10306 |
bigstack_calloc_w(raw_sample_ctl, &imputed_sex_male))) { |
| 10307 |
goto CheckOrImputeSex_ret_NOMEM; |
| 10308 |
} |
| 10309 |
snprintf(outname_end, kMaxOutfnameExtBlen, ".sexcheck"); |
| 10310 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &outfile))) { |
| 10311 |
goto CheckOrImputeSex_ret_OPEN_FAIL; |
| 10312 |
} |
| 10313 |
char* textbuf_flush = &(g_textbuf[kMaxMediumLine]); |
| 10314 |
char* write_iter = g_textbuf; |
| 10315 |
*write_iter++ = '#'; |
| 10316 |
const uint32_t col_fid = FidColIsRequired(siip, flags / kfCheckSexColMaybefid); |
| 10317 |
if (col_fid) { |
| 10318 |
write_iter = strcpya_k(write_iter, "FID\t"); |
| 10319 |
} |
| 10320 |
write_iter = strcpya_k(write_iter, "IID"); |
| 10321 |
const uint32_t col_sid = SidColIsRequired(siip->sids, flags / kfCheckSexColMaybesid); |
| 10322 |
if (col_sid) { |
| 10323 |
write_iter = strcpya_k(write_iter, "\tSID"); |
| 10324 |
} |
| 10325 |
const uint32_t col_pedsex = (flags / kfCheckSexColPedsex) & 1; |
| 10326 |
if (col_pedsex) { |
| 10327 |
write_iter = strcpya_k(write_iter, "\tPEDSEX"); |
| 10328 |
} |
| 10329 |
write_iter = strcpya_k(write_iter, "\tSNPSEX"); |
| 10330 |
const uint32_t col_status = (flags / kfCheckSexColStatus) & 1; |
| 10331 |
if (col_status) { |
| 10332 |
write_iter = strcpya_k(write_iter, "\tSTATUS"); |
| 10333 |
} |
| 10334 |
const uint32_t col_xf = used_variant_ct_x && (flags & kfCheckSexColXF); |
| 10335 |
if (col_xf) { |
| 10336 |
write_iter = strcpya_k(write_iter, "\tF"); |
| 10337 |
} |
| 10338 |
const uint32_t col_ycount = used_variant_ct_y && (flags & kfCheckSexColYcount); |
| 10339 |
if (col_ycount) { |
| 10340 |
write_iter = strcpya_k(write_iter, "\tYCOUNT"); |
| 10341 |
} |
| 10342 |
const uint32_t col_yrate = used_variant_ct_y && (flags & kfCheckSexColYrate); |
| 10343 |
if (col_yrate) { |
| 10344 |
write_iter = strcpya_k(write_iter, "\tYRATE"); |
| 10345 |
} |
| 10346 |
const uint32_t col_yobs = used_variant_ct_y && (flags & kfCheckSexColYobs); |
| 10347 |
if (col_yobs) { |
| 10348 |
write_iter = strcpya_k(write_iter, "\tYOBS"); |
| 10349 |
} |
| 10350 |
AppendBinaryEoln(&write_iter); |
| 10351 |
|
| 10352 |
const double y_denom = used_variant_ct_y? (1.0 / u31tod(used_variant_ct_y)) : 0.0; |
| 10353 |
const char* sample_ids = siip->sample_ids; |
| 10354 |
const char* sids = siip->sids; |
| 10355 |
const uintptr_t max_sample_id_blen = siip->max_sample_id_blen; |
| 10356 |
const uintptr_t max_sid_blen = siip->max_sid_blen; |
| 10357 |
uintptr_t sample_uidx_base = 0; |
| 10358 |
uintptr_t cur_bits = sample_include[0]; |
| 10359 |
double cur_xf = 0.0; |
| 10360 |
uint32_t cur_ycount = 0; |
| 10361 |
uint32_t problem_ct = 0; |
| 10362 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 10363 |
const uint32_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &cur_bits); |
| 10364 |
write_iter = AppendXid(sample_ids, sids, col_fid, col_sid, max_sample_id_blen, max_sid_blen, sample_uidx, write_iter); |
| 10365 |
const uint32_t ped_nm = IsSet(sex_nm, sample_uidx); |
| 10366 |
const uint32_t ped_male = IsSet(sex_male, sample_uidx); |
| 10367 |
if (col_pedsex) { |
| 10368 |
*write_iter++ = '\t'; |
| 10369 |
if (ped_nm) { |
| 10370 |
*write_iter++ = '2' - ped_male; |
| 10371 |
} else { |
| 10372 |
write_iter = strcpya_k(write_iter, "NA"); |
| 10373 |
} |
| 10374 |
} |
| 10375 |
uint32_t not_male = 0; |
| 10376 |
uint32_t not_female = 0; |
| 10377 |
if (xfs) { |
| 10378 |
cur_xf = xfs[sample_idx]; |
| 10379 |
if (cur_xf <= max_female_xf) { |
| 10380 |
not_male = 1; |
| 10381 |
} else if (cur_xf >= min_male_xf) { |
| 10382 |
not_female = 1; |
| 10383 |
} else { |
| 10384 |
not_male = 1; |
| 10385 |
not_female = 1; |
| 10386 |
} |
| 10387 |
} |
| 10388 |
if (y_valid_geno_cts) { |
| 10389 |
cur_ycount = y_valid_geno_cts[sample_idx]; |
| 10390 |
if (cur_ycount <= max_female_ycount) { |
| 10391 |
not_male = 1; |
| 10392 |
} else if (cur_ycount >= min_male_ycount) { |
| 10393 |
not_female = 1; |
| 10394 |
} else { |
| 10395 |
not_male = 1; |
| 10396 |
not_female = 1; |
| 10397 |
} |
| 10398 |
} |
| 10399 |
*write_iter++ = '\t'; |
| 10400 |
uint32_t is_problem; |
| 10401 |
if (not_male) { |
| 10402 |
if (not_female) { |
| 10403 |
write_iter = strcpya_k(write_iter, "NA"); |
| 10404 |
is_problem = 1; |
| 10405 |
} else { |
| 10406 |
*write_iter++ = '2'; |
| 10407 |
SetBit(sample_uidx, imputed_sex_nm); |
| 10408 |
is_problem = (!ped_nm) || ped_male; |
| 10409 |
} |
| 10410 |
} else { |
| 10411 |
*write_iter++ = '1'; |
| 10412 |
SetBit(sample_uidx, imputed_sex_nm); |
| 10413 |
SetBit(sample_uidx, imputed_sex_male); |
| 10414 |
is_problem = (!ped_nm) || (!ped_male); |
| 10415 |
} |
| 10416 |
problem_ct += is_problem; |
| 10417 |
if (col_status) { |
| 10418 |
if (is_problem) { |
| 10419 |
write_iter = strcpya_k(write_iter, "\tPROBLEM"); |
| 10420 |
} else { |
| 10421 |
write_iter = strcpya_k(write_iter, "\tOK"); |
| 10422 |
} |
| 10423 |
} |
| 10424 |
if (col_xf) { |
| 10425 |
*write_iter++ = '\t'; |
| 10426 |
write_iter = dtoa_g(cur_xf, write_iter); |
| 10427 |
} |
| 10428 |
if (col_ycount) { |
| 10429 |
*write_iter++ = '\t'; |
| 10430 |
write_iter = u32toa(cur_ycount, write_iter); |
| 10431 |
} |
| 10432 |
if (col_yrate) { |
| 10433 |
*write_iter++ = '\t'; |
| 10434 |
write_iter = dtoa_g(u31tod(cur_ycount) * y_denom, write_iter); |
| 10435 |
} |
| 10436 |
if (col_yobs) { |
| 10437 |
*write_iter++ = '\t'; |
| 10438 |
write_iter = u32toa(used_variant_ct_y, write_iter); |
| 10439 |
} |
| 10440 |
AppendBinaryEoln(&write_iter); |
| 10441 |
if (unlikely(fwrite_ck(textbuf_flush, outfile, &write_iter))) { |
| 10442 |
goto CheckOrImputeSex_ret_WRITE_FAIL; |
| 10443 |
} |
| 10444 |
} |
| 10445 |
if (unlikely(fclose_flush_null(textbuf_flush, write_iter, &outfile))) { |
| 10446 |
goto CheckOrImputeSex_ret_WRITE_FAIL; |
| 10447 |
} |
| 10448 |
write_iter = strcpya(g_logbuf, flagstr); |
| 10449 |
write_iter = strcpya_k(write_iter, ": "); |
| 10450 |
if (used_variant_ct_x) { |
| 10451 |
write_iter = u32toa(used_variant_ct_x, write_iter); |
| 10452 |
write_iter = strcpya_k(write_iter, " chrX variant"); |
| 10453 |
if (used_variant_ct_x != 1) { |
| 10454 |
*write_iter++ = 's'; |
| 10455 |
} |
| 10456 |
if (used_variant_ct_y) { |
| 10457 |
write_iter = strcpya_k(write_iter, " and "); |
| 10458 |
write_iter = u32toa(used_variant_ct_y, write_iter); |
| 10459 |
write_iter = strcpya_k(write_iter, " variant"); |
| 10460 |
if (used_variant_ct_y != 1) { |
| 10461 |
*write_iter++ = 's'; |
| 10462 |
} |
| 10463 |
} |
| 10464 |
} else { |
| 10465 |
write_iter = u32toa(used_variant_ct_y, write_iter); |
| 10466 |
write_iter = strcpya_k(write_iter, " variant"); |
| 10467 |
if (used_variant_ct_y != 1) { |
| 10468 |
*write_iter++ = 's'; |
| 10469 |
} |
| 10470 |
} |
| 10471 |
write_iter = strcpya_k(write_iter, " scanned, "); |
| 10472 |
if (flags & kfCheckSexImpute) { |
| 10473 |
memcpy(sex_nm, imputed_sex_nm, raw_sample_ctl * sizeof(intptr_t)); |
| 10474 |
memcpy(sex_male, imputed_sex_male, raw_sample_ctl * sizeof(intptr_t)); |
| 10475 |
const uint32_t imputed_nm_ct = PopcountWords(imputed_sex_nm, raw_sample_ctl); |
| 10476 |
const uint32_t imputed_male_ct = PopcountWords(imputed_sex_male, raw_sample_ctl); |
| 10477 |
write_iter = u32toa_x(imputed_nm_ct, '/', write_iter); |
| 10478 |
write_iter = u32toa(sample_ct, write_iter); |
| 10479 |
write_iter = strcpya_k(write_iter, " sex"); |
| 10480 |
if (sample_ct != 1) { |
| 10481 |
write_iter = strcpya_k(write_iter, "es"); |
| 10482 |
} |
| 10483 |
write_iter = strcpya_k(write_iter, " imputed ("); |
| 10484 |
write_iter = u32toa(imputed_nm_ct - imputed_male_ct, write_iter); |
| 10485 |
write_iter = strcpya_k(write_iter, " female, "); |
| 10486 |
write_iter = u32toa(imputed_male_ct, write_iter); |
| 10487 |
write_iter = strcpya_k(write_iter, " male)"); |
| 10488 |
} else { |
| 10489 |
write_iter = u32toa(problem_ct, write_iter); |
| 10490 |
write_iter = strcpya_k(write_iter, " problem"); |
| 10491 |
if (problem_ct != 1) { |
| 10492 |
*write_iter++ = 's'; |
| 10493 |
} |
| 10494 |
write_iter = strcpya_k(write_iter, " detected"); |
| 10495 |
} |
| 10496 |
write_iter = strcpya_k(write_iter, ". Report written to "); |
| 10497 |
write_iter = memcpya(write_iter, outname, &(outname_end[strlen(".sexcheck")]) - outname); |
| 10498 |
strcpy_k(write_iter, " .\n"); |
| 10499 |
WordWrapB(0); |
| 10500 |
logputsb(); |
| 10501 |
} |
| 10502 |
while (0) { |
| 10503 |
CheckOrImputeSex_ret_NOMEM: |
| 10504 |
reterr = kPglRetNomem; |
| 10505 |
break; |
| 10506 |
CheckOrImputeSex_ret_OPEN_FAIL: |
| 10507 |
reterr = kPglRetOpenFail; |
| 10508 |
break; |
| 10509 |
CheckOrImputeSex_ret_WRITE_FAIL: |
| 10510 |
reterr = kPglRetWriteFail; |
| 10511 |
break; |
| 10512 |
CheckOrImputeSex_ret_INCONSISTENT_INPUT_2: |
| 10513 |
logerrputsb(); |
| 10514 |
reterr = kPglRetInconsistentInput; |
| 10515 |
break; |
| 10516 |
} |
| 10517 |
CheckOrImputeSex_ret_1: |
| 10518 |
fclose_cond(outfile); |
| 10519 |
BigstackReset(bigstack_mark); |
| 10520 |
return reterr; |
| 10521 |
} |
| 10522 |
|
| 10523 |
typedef struct FstCtxStruct { |
| 10524 |
const uintptr_t* cur_variant_include; |
| 10525 |
const uintptr_t* allele_idx_offsets; |
| 10526 |
const uintptr_t* sample_include; |
| 10527 |
const uint32_t* sample_include_cumulative_popcounts; |
| 10528 |
// sex_male_collapsed == nullptr unless chrX /w males |
| 10529 |
const uintptr_t* sex_male_collapsed; |
| 10530 |
const uint32_t* sample_to_pop_idx; |
| 10531 |
uint32_t* diploid_pop_sizes; |
| 10532 |
const uint32_t* haploid_pop_sizes; |
| 10533 |
uint32_t sample_ct; |
| 10534 |
uint32_t pop_ct; |
| 10535 |
|
| 10536 |
PgenReader** pgr_ptrs; |
| 10537 |
uintptr_t** genovecs; |
| 10538 |
uintptr_t** thread_read_mhc; |
| 10539 |
uintptr_t** raregenos; |
| 10540 |
uint32_t** difflist_sample_id_bufs; |
| 10541 |
uint32_t** pop_geno_bufs; |
| 10542 |
uint32_t* read_variant_uidx_starts; |
| 10543 |
uint32_t cur_block_variant_ct; // .pgen iteration, not jackknife |
| 10544 |
|
| 10545 |
uint64_t err_info; |
| 10546 |
|
| 10547 |
// worker threads compute intermediate stats; parent thread computes final |
| 10548 |
// Fst estimates (to avoid O(pop_ct^2) space problem) and executes |
| 10549 |
// block-jackknife. |
| 10550 |
uint32_t* pop_nm_sample_cts[2]; |
| 10551 |
uint32_t* pop_allele_obs_cts[2]; // major dimension = pop, minor = allele |
| 10552 |
|
| 10553 |
// Hudson only |
| 10554 |
double* half_within[2]; |
| 10555 |
|
| 10556 |
// W-C only |
| 10557 |
uint32_t* pop_allele_het_cts[2]; |
| 10558 |
} FstCtx; |
| 10559 |
|
| 10560 |
THREAD_FUNC_DECL FstThread(void* raw_arg) { |
| 10561 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 10562 |
const uintptr_t tidx = arg->tidx; |
| 10563 |
FstCtx* ctx = S_CAST(FstCtx*, arg->sharedp->context); |
| 10564 |
|
| 10565 |
const uintptr_t* variant_include = ctx->cur_variant_include; |
| 10566 |
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets; |
| 10567 |
const uintptr_t* sample_include = ctx->sample_include; |
| 10568 |
PgenReader* pgrp = ctx->pgr_ptrs[tidx]; |
| 10569 |
PgrSampleSubsetIndex pssi; |
| 10570 |
PgrSetSampleSubsetIndex(ctx->sample_include_cumulative_popcounts, pgrp, &pssi); |
| 10571 |
// sex_male nullptr iff not chrX /w males |
| 10572 |
const uintptr_t* sex_male = ctx->sex_male_collapsed; |
| 10573 |
const uint32_t* sample_to_pop_idx = ctx->sample_to_pop_idx; |
| 10574 |
const uint32_t* diploid_pop_sizes = ctx->diploid_pop_sizes; |
| 10575 |
const uint32_t* haploid_pop_sizes = ctx->haploid_pop_sizes; |
| 10576 |
const uint32_t sample_ct = ctx->sample_ct; |
| 10577 |
const uint32_t sample_ctl2 = NypCtToWordCt(sample_ct); |
| 10578 |
const uint32_t sample_ctl2_m1 = sample_ctl2 - 1; |
| 10579 |
const uint32_t haploid_present = (sex_male != nullptr); |
| 10580 |
const uintptr_t pop_ct = ctx->pop_ct; |
| 10581 |
const uintptr_t pop_ct_x4 = pop_ct * 4; |
| 10582 |
uintptr_t* genovec = ctx->genovecs[tidx]; |
| 10583 |
PgenVariant pgv; |
| 10584 |
pgv.genovec = genovec; |
| 10585 |
SetPgvThreadMhcNull(sample_ct, tidx, ctx->thread_read_mhc, &pgv); |
| 10586 |
uintptr_t* raregeno = ctx->raregenos[tidx]; |
| 10587 |
uint32_t* difflist_sample_ids = ctx->difflist_sample_id_bufs[tidx]; |
| 10588 |
uint32_t* pop_geno_buf = ctx->pop_geno_bufs[tidx]; |
| 10589 |
const uintptr_t pop_geno_buf_size = pop_ct_x4 << haploid_present; |
| 10590 |
|
| 10591 |
// todo: tune this threshold |
| 10592 |
const uint32_t max_simple_difflist_len = sample_ct / 32; |
| 10593 |
|
| 10594 |
const uint32_t calc_thread_ct = GetThreadCt(arg->sharedp); |
| 10595 |
|
| 10596 |
uint32_t allele_ct = 2; |
| 10597 |
uint32_t parity = 0; |
| 10598 |
uint64_t new_err_info = 0; |
| 10599 |
do { |
| 10600 |
uint32_t cur_idx_ct; |
| 10601 |
uintptr_t variant_uidx_base; |
| 10602 |
uintptr_t variant_include_bits; |
| 10603 |
uint32_t* pop_nm_sample_cts_iter; |
| 10604 |
uint32_t* pop_allele_obs_cts_iter; |
| 10605 |
double* half_within_iter; |
| 10606 |
uint32_t* pop_allele_het_cts_iter; |
| 10607 |
{ |
| 10608 |
const uint32_t cur_block_variant_ct = ctx->cur_block_variant_ct; |
| 10609 |
const uint32_t first_variant_bidx = (tidx * cur_block_variant_ct) / calc_thread_ct; |
| 10610 |
cur_idx_ct = (((tidx + 1) * cur_block_variant_ct) / calc_thread_ct) - first_variant_bidx; |
| 10611 |
const uint32_t variant_uidx_start = ctx->read_variant_uidx_starts[tidx]; |
| 10612 |
BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &variant_include_bits); |
| 10613 |
const uintptr_t allele_bidx = first_variant_bidx * 2 + CountExtraAlleles(variant_include, allele_idx_offsets, ctx->read_variant_uidx_starts[0], variant_uidx_start, 0); |
| 10614 |
// non-null iff Weir-Cockerham method, or OBS_CT .fst.var col requested |
| 10615 |
pop_nm_sample_cts_iter = ctx->pop_nm_sample_cts[parity]; |
| 10616 |
if (pop_nm_sample_cts_iter) { |
| 10617 |
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct * first_variant_bidx]); |
| 10618 |
} |
| 10619 |
pop_allele_obs_cts_iter = ctx->pop_allele_obs_cts[parity]; |
| 10620 |
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_bidx]); |
| 10621 |
// non-null iff Hudson |
| 10622 |
half_within_iter = ctx->half_within[parity]; |
| 10623 |
if (half_within_iter) { |
| 10624 |
half_within_iter = &(half_within_iter[pop_ct * first_variant_bidx]); |
| 10625 |
} |
| 10626 |
|
| 10627 |
// non-null iff W-C |
| 10628 |
pop_allele_het_cts_iter = ctx->pop_allele_het_cts[parity]; |
| 10629 |
if (pop_allele_het_cts_iter) { |
| 10630 |
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_bidx]); |
| 10631 |
} |
| 10632 |
} |
| 10633 |
for (uint32_t cur_idx = 0; cur_idx != cur_idx_ct; ++cur_idx) { |
| 10634 |
const uint32_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &variant_include_bits); |
| 10635 |
if (allele_idx_offsets) { |
| 10636 |
allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx]; |
| 10637 |
} |
| 10638 |
ZeroU32Arr(pop_geno_buf_size, pop_geno_buf); |
| 10639 |
uint32_t difflist_common_geno = UINT32_MAX; |
| 10640 |
if (allele_ct == 2) { |
| 10641 |
uint32_t difflist_len; |
| 10642 |
const PglErr reterr = PgrGetDifflistOrGenovec(sample_include, pssi, sample_ct, max_simple_difflist_len, variant_uidx, pgrp, genovec, &difflist_common_geno, raregeno, difflist_sample_ids, &difflist_len); |
| 10643 |
if (unlikely(reterr)) { |
| 10644 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 10645 |
goto FstThread_err; |
| 10646 |
} |
| 10647 |
if (difflist_common_geno != UINT32_MAX) { |
| 10648 |
const uint32_t word_ct = NypCtToWordCt(difflist_len); |
| 10649 |
if (word_ct) { |
| 10650 |
const uint32_t word_ct_m1 = word_ct - 1; |
| 10651 |
uint32_t loop_len = kBitsPerWordD2; |
| 10652 |
for (uint32_t widx = 0; ; ++widx) { |
| 10653 |
if (widx >= word_ct_m1) { |
| 10654 |
if (widx > word_ct_m1) { |
| 10655 |
break; |
| 10656 |
} |
| 10657 |
loop_len = ModNz(difflist_len, kBitsPerWordD2); |
| 10658 |
} |
| 10659 |
const uint32_t difflist_idx_base = widx * kBitsPerWordD2; |
| 10660 |
const uint32_t* cur_difflist_sample_ids = &(difflist_sample_ids[difflist_idx_base]); |
| 10661 |
uintptr_t raregeno_word = raregeno[widx]; |
| 10662 |
if (!haploid_present) { |
| 10663 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 10664 |
const uint32_t sample_idx = cur_difflist_sample_ids[uii]; |
| 10665 |
const uintptr_t cur_geno = raregeno_word & 3; |
| 10666 |
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 10667 |
pop_geno_buf[pop_idx * 4 + cur_geno] += 1; |
| 10668 |
raregeno_word >>= 2; |
| 10669 |
} |
| 10670 |
} else { |
| 10671 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 10672 |
const uint32_t sample_idx = cur_difflist_sample_ids[uii]; |
| 10673 |
uintptr_t cur_geno = raregeno_word & 3; |
| 10674 |
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 10675 |
const uintptr_t male_mask = -IsSet(sex_male, sample_idx); |
| 10676 |
pop_geno_buf[pop_idx * 4 + cur_geno + (male_mask & pop_ct_x4)] += 1; |
| 10677 |
raregeno_word >>= 2; |
| 10678 |
} |
| 10679 |
} |
| 10680 |
} |
| 10681 |
} |
| 10682 |
if (difflist_common_geno != 3) { |
| 10683 |
const uint32_t other_hom_geno = 2 - difflist_common_geno; |
| 10684 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10685 |
const uint32_t diploid_pop_size = diploid_pop_sizes[pop_idx]; |
| 10686 |
uint32_t* cur_pop_geno_buf = &(pop_geno_buf[pop_idx * 4]); |
| 10687 |
cur_pop_geno_buf[difflist_common_geno] = diploid_pop_size - cur_pop_geno_buf[1] - cur_pop_geno_buf[other_hom_geno] - cur_pop_geno_buf[3]; |
| 10688 |
} |
| 10689 |
if (haploid_present) { |
| 10690 |
uint32_t* haploid_pop_geno_buf = &(pop_geno_buf[pop_ct_x4]); |
| 10691 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10692 |
const uint32_t haploid_pop_size = haploid_pop_sizes[pop_idx]; |
| 10693 |
uint32_t* cur_pop_geno_buf = &(haploid_pop_geno_buf[pop_idx * 4]); |
| 10694 |
cur_pop_geno_buf[difflist_common_geno] = haploid_pop_size - cur_pop_geno_buf[1] - cur_pop_geno_buf[other_hom_geno] - cur_pop_geno_buf[3]; |
| 10695 |
} |
| 10696 |
} |
| 10697 |
} |
| 10698 |
} |
| 10699 |
} else { |
| 10700 |
const PglErr reterr = PgrGetM(sample_include, pssi, sample_ct, variant_uidx, pgrp, &pgv); |
| 10701 |
if (unlikely(reterr)) { |
| 10702 |
new_err_info = (S_CAST(uint64_t, variant_uidx) << 32) | S_CAST(uint32_t, reterr); |
| 10703 |
goto FstThread_err; |
| 10704 |
} |
| 10705 |
} |
| 10706 |
if (difflist_common_geno == UINT32_MAX) { |
| 10707 |
uint32_t loop_len = kBitsPerWordD2; |
| 10708 |
for (uint32_t widx = 0; ; ++widx) { |
| 10709 |
if (widx >= sample_ctl2_m1) { |
| 10710 |
if (widx > sample_ctl2_m1) { |
| 10711 |
break; |
| 10712 |
} |
| 10713 |
loop_len = ModNz(sample_ct, kBitsPerWordD2); |
| 10714 |
} |
| 10715 |
const uint32_t* cur_pop_idxs = &(sample_to_pop_idx[widx * kBitsPerWordD2]); |
| 10716 |
uintptr_t geno_word = genovec[widx]; |
| 10717 |
if (!haploid_present) { |
| 10718 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 10719 |
const uintptr_t cur_geno = geno_word & 3; |
| 10720 |
const uintptr_t pop_idx = cur_pop_idxs[uii]; |
| 10721 |
pop_geno_buf[pop_idx * 4 + cur_geno] += 1; |
| 10722 |
geno_word >>= 2; |
| 10723 |
} |
| 10724 |
} else { |
| 10725 |
uintptr_t male_hw = R_CAST(const Halfword*, sex_male)[widx]; |
| 10726 |
for (uint32_t uii = 0; uii != loop_len; ++uii) { |
| 10727 |
const uintptr_t cur_geno = geno_word & 3; |
| 10728 |
const uintptr_t pop_idx = cur_pop_idxs[uii]; |
| 10729 |
const uintptr_t male_mask = -(male_hw & k1LU); |
| 10730 |
pop_geno_buf[pop_idx * 4 + cur_geno + (male_mask & pop_ct_x4)] += 1; |
| 10731 |
geno_word >>= 2; |
| 10732 |
male_hw >>= 1; |
| 10733 |
} |
| 10734 |
} |
| 10735 |
} |
| 10736 |
} |
| 10737 |
if (pop_nm_sample_cts_iter) { |
| 10738 |
const uint32_t* pop_geno_buf_iter = pop_geno_buf; |
| 10739 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10740 |
pop_nm_sample_cts_iter[pop_idx] = pop_geno_buf_iter[0] + pop_geno_buf_iter[1] + pop_geno_buf_iter[2]; |
| 10741 |
pop_geno_buf_iter = &(pop_geno_buf_iter[4]); |
| 10742 |
} |
| 10743 |
if (haploid_present) { |
| 10744 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10745 |
pop_nm_sample_cts_iter[pop_idx] += pop_geno_buf_iter[0] + pop_geno_buf_iter[2]; |
| 10746 |
pop_geno_buf_iter = &(pop_geno_buf_iter[4]); |
| 10747 |
} |
| 10748 |
} |
| 10749 |
} |
| 10750 |
ZeroU32Arr(pop_ct * allele_ct, pop_allele_obs_cts_iter); |
| 10751 |
if (pop_allele_het_cts_iter) { |
| 10752 |
ZeroU32Arr(pop_ct * allele_ct, pop_allele_het_cts_iter); |
| 10753 |
} |
| 10754 |
if (allele_ct != 2) { |
| 10755 |
if (pgv.patch_01_ct) { |
| 10756 |
const uint32_t patch_01_ct = pgv.patch_01_ct; |
| 10757 |
const uintptr_t* patch_01_set = pgv.patch_01_set; |
| 10758 |
const AlleleCode* patch_01_vals = pgv.patch_01_vals; |
| 10759 |
uintptr_t sample_idx_base = 0; |
| 10760 |
uintptr_t sample_idx_bits = patch_01_set[0]; |
| 10761 |
for (uint32_t uii = 0; uii != patch_01_ct; ++uii) { |
| 10762 |
const uint32_t sample_idx = BitIter1(patch_01_set, &sample_idx_base, &sample_idx_bits); |
| 10763 |
if (sex_male && IsSet(sex_male, sample_idx)) { |
| 10764 |
// already counted as missing |
| 10765 |
continue; |
| 10766 |
} |
| 10767 |
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 10768 |
pop_geno_buf[pop_idx * 4 + 1] -= 1; |
| 10769 |
pop_allele_obs_cts_iter[pop_idx] += 1; |
| 10770 |
const AlleleCode ac = patch_01_vals[uii]; |
| 10771 |
pop_allele_obs_cts_iter[ac * pop_ct + pop_idx] += 1; |
| 10772 |
if (pop_allele_het_cts_iter) { |
| 10773 |
pop_allele_het_cts_iter[pop_idx] += 1; |
| 10774 |
pop_allele_het_cts_iter[ac * pop_ct + pop_idx] += 1; |
| 10775 |
} |
| 10776 |
} |
| 10777 |
} |
| 10778 |
if (pgv.patch_10_ct) { |
| 10779 |
const uint32_t patch_10_ct = pgv.patch_10_ct; |
| 10780 |
const uintptr_t* patch_10_set = pgv.patch_10_set; |
| 10781 |
const AlleleCode* patch_10_vals = pgv.patch_10_vals; |
| 10782 |
uintptr_t sample_idx_base = 0; |
| 10783 |
uintptr_t sample_idx_bits = patch_10_set[0]; |
| 10784 |
if (!haploid_present) { |
| 10785 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 10786 |
const uint32_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 10787 |
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 10788 |
pop_geno_buf[pop_idx * 4 + 2] -= 1; |
| 10789 |
const AlleleCode ac0 = patch_10_vals[uii * 2]; |
| 10790 |
const AlleleCode ac1 = patch_10_vals[uii * 2 + 1]; |
| 10791 |
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 1; |
| 10792 |
pop_allele_obs_cts_iter[pop_idx + ac1 * pop_ct] += 1; |
| 10793 |
if (pop_allele_het_cts_iter && (ac0 != ac1)) { |
| 10794 |
pop_allele_het_cts_iter[pop_idx + ac0 * pop_ct] += 1; |
| 10795 |
pop_allele_het_cts_iter[pop_idx + ac1 * pop_ct] += 1; |
| 10796 |
} |
| 10797 |
} |
| 10798 |
} else { |
| 10799 |
for (uint32_t uii = 0; uii != patch_10_ct; ++uii) { |
| 10800 |
const uint32_t sample_idx = BitIter1(patch_10_set, &sample_idx_base, &sample_idx_bits); |
| 10801 |
const uintptr_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 10802 |
const uintptr_t is_male = IsSet(sex_male, sample_idx); |
| 10803 |
pop_geno_buf[pop_idx * 4 + 2 + ((-is_male) & pop_ct_x4)] -= 1; |
| 10804 |
const AlleleCode ac0 = patch_10_vals[uii * 2]; |
| 10805 |
const AlleleCode ac1 = patch_10_vals[uii * 2 + 1]; |
| 10806 |
if (ac0 == ac1) { |
| 10807 |
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 2 - is_male; |
| 10808 |
} else { |
| 10809 |
if (is_male) { |
| 10810 |
if (pop_nm_sample_cts_iter) { |
| 10811 |
pop_nm_sample_cts_iter[pop_idx] -= 1; |
| 10812 |
} |
| 10813 |
continue; |
| 10814 |
} |
| 10815 |
pop_allele_obs_cts_iter[pop_idx + ac0 * pop_ct] += 1; |
| 10816 |
pop_allele_obs_cts_iter[pop_idx + ac1 * pop_ct] += 1; |
| 10817 |
// guaranteed to be performing Hudson computation if we're |
| 10818 |
// here, so no need to check pop_allele_het_cts_iter |
| 10819 |
} |
| 10820 |
} |
| 10821 |
} |
| 10822 |
} |
| 10823 |
} |
| 10824 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10825 |
const uint32_t hom_ref_ct = pop_geno_buf[pop_idx * 4]; |
| 10826 |
const uint32_t het_ref_alt1_ct = pop_geno_buf[pop_idx * 4 + 1]; |
| 10827 |
const uint32_t hom_alt1_ct = pop_geno_buf[pop_idx * 4 + 2]; |
| 10828 |
pop_allele_obs_cts_iter[pop_idx] += hom_ref_ct * 2 + het_ref_alt1_ct; |
| 10829 |
pop_allele_obs_cts_iter[pop_idx + pop_ct] += hom_alt1_ct * 2 + het_ref_alt1_ct; |
| 10830 |
if (pop_allele_het_cts_iter) { |
| 10831 |
pop_allele_het_cts_iter[pop_idx] += het_ref_alt1_ct; |
| 10832 |
pop_allele_het_cts_iter[pop_idx + pop_ct] += het_ref_alt1_ct; |
| 10833 |
} |
| 10834 |
} |
| 10835 |
if (haploid_present) { |
| 10836 |
const uint32_t* haploid_pop_geno_buf_iter = &(pop_geno_buf[pop_ct_x4]); |
| 10837 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10838 |
const uint32_t hap_ref_ct = haploid_pop_geno_buf_iter[0]; |
| 10839 |
const uint32_t hap_alt1_ct = haploid_pop_geno_buf_iter[2]; |
| 10840 |
pop_allele_obs_cts_iter[pop_idx] += hap_ref_ct; |
| 10841 |
pop_allele_obs_cts_iter[pop_idx + pop_ct] += hap_alt1_ct; |
| 10842 |
haploid_pop_geno_buf_iter = &(haploid_pop_geno_buf_iter[4]); |
| 10843 |
} |
| 10844 |
} |
| 10845 |
if (half_within_iter) { |
| 10846 |
// Hudson |
| 10847 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 10848 |
uintptr_t n_hap = 0; |
| 10849 |
uint64_t ssq = 0; |
| 10850 |
for (uintptr_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) { |
| 10851 |
const uintptr_t allele_obs_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx]; |
| 10852 |
n_hap += allele_obs_ct; |
| 10853 |
ssq += S_CAST(uint64_t, allele_obs_ct) * allele_obs_ct; |
| 10854 |
} |
| 10855 |
const uint64_t n_pairs_x2 = S_CAST(uint64_t, n_hap) * (n_hap - 1); |
| 10856 |
const uint64_t n_same = (ssq - n_hap) / 2; |
| 10857 |
const uint64_t n_diff = n_pairs_x2 / 2 - n_same; |
| 10858 |
*half_within_iter++ = u63tod(n_diff) / u63tod(n_pairs_x2); |
| 10859 |
} |
| 10860 |
} else { |
| 10861 |
// Weir-Cockerham |
| 10862 |
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_ct]); |
| 10863 |
} |
| 10864 |
if (pop_nm_sample_cts_iter) { |
| 10865 |
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct]); |
| 10866 |
} |
| 10867 |
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_ct]); |
| 10868 |
} |
| 10869 |
parity = 1 - parity; |
| 10870 |
while (0) { |
| 10871 |
FstThread_err: |
| 10872 |
UpdateU64IfSmaller(new_err_info, &ctx->err_info); |
| 10873 |
} |
| 10874 |
} while (!THREAD_BLOCK_FINISH(arg)); |
| 10875 |
THREAD_RETURN; |
| 10876 |
} |
| 10877 |
|
| 10878 |
const char g_cc_cat_names[2][8] = {"CONTROL", "CASE"}; |
| 10879 |
|
| 10880 |
CONSTI32(kFstReportVariantsBatchMax, kMaxOpenFiles - 12); |
| 10881 |
|
| 10882 |
PglErr FstReport(const uintptr_t* orig_sample_include, const uintptr_t* sex_male, const PhenoCol* pheno_cols, const char* pheno_names, const uintptr_t* orig_variant_include, const ChrInfo* cip, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, const FstInfo* fst_infop, uint32_t raw_sample_ct, uint32_t pheno_ct, uintptr_t max_pheno_name_blen, uint32_t raw_variant_ct, uint32_t orig_variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct, uintptr_t pgr_alloc_cacheline_ct, PgenFileInfo* pgfip, char* outname, char* outname_end) { |
| 10883 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 10884 |
unsigned char* bigstack_end_mark = g_bigstack_end; |
| 10885 |
uint32_t max_variant_file_ct = 0; |
| 10886 |
FILE* s_outfile = nullptr; |
| 10887 |
char** v_cswritep_arr = nullptr; |
| 10888 |
CompressStreamState* v_css_arr = nullptr; |
| 10889 |
PglErr reterr = kPglRetSuccess; |
| 10890 |
TextStream txs; // file= |
| 10891 |
PreinitTextStream(&txs); |
| 10892 |
ThreadGroup tg; |
| 10893 |
PreinitThreads(&tg); |
| 10894 |
FstCtx ctx; |
| 10895 |
{ |
| 10896 |
if (IsSet(cip->haploid_mask, 0)) { |
| 10897 |
logerrputs("Error: --fst cannot be used on haploid genomes.\n"); |
| 10898 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 10899 |
} |
| 10900 |
const char* pheno_name = fst_infop->pheno_name; |
| 10901 |
const PhenoCol* pheno_col; |
| 10902 |
{ |
| 10903 |
const uint32_t pheno_blen = strlen(pheno_name) + 1; |
| 10904 |
if (pheno_blen > max_pheno_name_blen) { |
| 10905 |
goto FstReport_ret_PHENO_NOT_FOUND; |
| 10906 |
} |
| 10907 |
for (uintptr_t pheno_idx = 0; ; ++pheno_idx) { |
| 10908 |
if (pheno_idx == pheno_ct) { |
| 10909 |
goto FstReport_ret_PHENO_NOT_FOUND; |
| 10910 |
} |
| 10911 |
if (memequal(pheno_name, &(pheno_names[pheno_idx * max_pheno_name_blen]), pheno_blen)) { |
| 10912 |
pheno_col = &(pheno_cols[pheno_idx]); |
| 10913 |
break; |
| 10914 |
} |
| 10915 |
} |
| 10916 |
} |
| 10917 |
if (pheno_col->type_code == kPhenoDtypeQt) { |
| 10918 |
logerrprintfww("Error: --fst phenotype '%s' is quantitative (binary or categorical required).\n", pheno_name); |
| 10919 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 10920 |
} |
| 10921 |
const uint32_t raw_sample_ctl = BitCtToWordCt(raw_sample_ct); |
| 10922 |
if (pheno_col->type_code != kPhenoDtypeCat) { |
| 10923 |
assert(pheno_col->type_code == kPhenoDtypeCc); |
| 10924 |
// this may belong in plink2_cmdline |
| 10925 |
PhenoCol* synthetic_pheno_col; |
| 10926 |
uint32_t* cat_tmp; |
| 10927 |
const char** category_names; |
| 10928 |
if (unlikely(BIGSTACK_ALLOC_X(PhenoCol, 1, &synthetic_pheno_col) || |
| 10929 |
bigstack_end_calloc_u32(raw_sample_ct, &cat_tmp) || |
| 10930 |
bigstack_end_alloc_kcp(3, &category_names))) { |
| 10931 |
goto FstReport_ret_NOMEM; |
| 10932 |
} |
| 10933 |
const uintptr_t* raw_pheno_nm = pheno_col->nonmiss; |
| 10934 |
const uintptr_t* pheno_cc = pheno_col->data.cc; |
| 10935 |
for (uint32_t sample_uidx = 0; sample_uidx != raw_sample_ct; ++sample_uidx) { |
| 10936 |
if (!IsSet(raw_pheno_nm, sample_uidx)) { |
| 10937 |
continue; |
| 10938 |
} |
| 10939 |
// 'CASE' is lexicographically before 'CONTROL' |
| 10940 |
cat_tmp[sample_uidx] = 2 - IsSet(pheno_cc, sample_uidx); |
| 10941 |
} |
| 10942 |
category_names[0] = nullptr; |
| 10943 |
category_names[1] = g_cc_cat_names[1]; |
| 10944 |
category_names[2] = g_cc_cat_names[0]; |
| 10945 |
synthetic_pheno_col->category_names = category_names; |
| 10946 |
synthetic_pheno_col->nonmiss = pheno_col->nonmiss; |
| 10947 |
synthetic_pheno_col->data.cat = cat_tmp; |
| 10948 |
synthetic_pheno_col->type_code = kPhenoDtypeCat; |
| 10949 |
synthetic_pheno_col->nonnull_category_ct = 2; |
| 10950 |
pheno_col = synthetic_pheno_col; |
| 10951 |
} |
| 10952 |
ctx.allele_idx_offsets = allele_idx_offsets; |
| 10953 |
uintptr_t* sample_include; |
| 10954 |
if (unlikely(bigstack_alloc_w(raw_sample_ctl, &sample_include))) { |
| 10955 |
goto FstReport_ret_NOMEM; |
| 10956 |
} |
| 10957 |
BitvecAndCopy(orig_sample_include, pheno_col->nonmiss, raw_sample_ctl, sample_include); |
| 10958 |
uint32_t sample_ct = PopcountWords(sample_include, raw_sample_ctl); |
| 10959 |
const FstFlags flags = fst_infop->flags; |
| 10960 |
const uint32_t is_wc = (flags / kfFstMethodWc) & 1; |
| 10961 |
uintptr_t pop_pair_ct = 0; |
| 10962 |
uint32_t* pop_pairs = nullptr; |
| 10963 |
const char** pop_names; |
| 10964 |
uintptr_t pop_ct; |
| 10965 |
{ |
| 10966 |
const uint32_t nonnull_category_ct = pheno_col->nonnull_category_ct; |
| 10967 |
const uint32_t raw_cat_ctl = 1 + (nonnull_category_ct / kBitsPerWord); |
| 10968 |
uintptr_t* cats_seen; |
| 10969 |
if (unlikely(bigstack_end_alloc_w(raw_cat_ctl, &cats_seen))) { |
| 10970 |
goto FstReport_ret_NOMEM; |
| 10971 |
} |
| 10972 |
pop_ct = IdentifyRemainingCats(sample_include, pheno_col, sample_ct, cats_seen); |
| 10973 |
assert(!(cats_seen[0] & 1)); |
| 10974 |
if (pop_ct < 2) { |
| 10975 |
logerrputs("Error: --fst requires two or more populations.\n"); |
| 10976 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 10977 |
} |
| 10978 |
const uint32_t* old_cats = pheno_col->data.cat; |
| 10979 |
if (flags & (kfFstOneBasePop | kfFstExplicitPopIds)) { |
| 10980 |
const char** nonnull_category_names = &(pheno_col->category_names[1]); |
| 10981 |
const char* first_id = fst_infop->first_id_or_fname; |
| 10982 |
const uint32_t first_cat_idx = 1 + bsearch_strptr_natural(first_id, nonnull_category_names, nonnull_category_ct); |
| 10983 |
if (unlikely(!IsSet(cats_seen, first_cat_idx))) { |
| 10984 |
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, first_id); |
| 10985 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 10986 |
} |
| 10987 |
const char* other_ids = fst_infop->other_ids_flattened; |
| 10988 |
if (!other_ids) { |
| 10989 |
// base= with single argument |
| 10990 |
const uintptr_t other_pop_ct = pop_ct - 1; |
| 10991 |
if (unlikely(bigstack_alloc_u32(2 * other_pop_ct, &pop_pairs))) { |
| 10992 |
goto FstReport_ret_NOMEM; |
| 10993 |
} |
| 10994 |
pop_pair_ct = other_pop_ct; |
| 10995 |
uint32_t* pop_pairs_iter = pop_pairs; |
| 10996 |
uintptr_t cats_seen_base = 0; |
| 10997 |
uintptr_t cats_seen_bits = cats_seen[0]; |
| 10998 |
uintptr_t ulii = 0; |
| 10999 |
for (; ulii != other_pop_ct; ++ulii) { |
| 11000 |
const uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits); |
| 11001 |
if (other_cat_idx == first_cat_idx) { |
| 11002 |
break; |
| 11003 |
} |
| 11004 |
*pop_pairs_iter++ = other_cat_idx; |
| 11005 |
*pop_pairs_iter++ = first_cat_idx; |
| 11006 |
} |
| 11007 |
for (; ulii != other_pop_ct; ++ulii) { |
| 11008 |
const uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits); |
| 11009 |
*pop_pairs_iter++ = first_cat_idx; |
| 11010 |
*pop_pairs_iter++ = other_cat_idx; |
| 11011 |
} |
| 11012 |
} else { |
| 11013 |
// either base= or id= with multiple arguments |
| 11014 |
uintptr_t* pop_include; |
| 11015 |
if (unlikely(bigstack_end_calloc_w(raw_cat_ctl, &pop_include))) { |
| 11016 |
goto FstReport_ret_NOMEM; |
| 11017 |
} |
| 11018 |
SetBit(first_cat_idx, pop_include); |
| 11019 |
const char* other_ids_iter = other_ids; |
| 11020 |
do { |
| 11021 |
const uint32_t cat_idx = 1 + bsearch_strptr_natural(other_ids_iter, nonnull_category_names, nonnull_category_ct); |
| 11022 |
if (unlikely(!IsSet(cats_seen, cat_idx))) { |
| 11023 |
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, other_ids_iter); |
| 11024 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 11025 |
} |
| 11026 |
if (unlikely(IsSet(pop_include, cat_idx))) { |
| 11027 |
logerrprintfww("Error: Duplicate --fst population ID '%s'.\n", other_ids_iter); |
| 11028 |
goto FstReport_ret_INVALID_CMDLINE; |
| 11029 |
} |
| 11030 |
SetBit(cat_idx, pop_include); |
| 11031 |
other_ids_iter = strnul(other_ids_iter); |
| 11032 |
++other_ids_iter; |
| 11033 |
} while (*other_ids_iter); |
| 11034 |
const uintptr_t named_pop_ct = PopcountWords(pop_include, raw_cat_ctl); |
| 11035 |
if (named_pop_ct != pop_ct) { |
| 11036 |
// Safe to ignore unnamed populations. |
| 11037 |
pop_ct = named_pop_ct; |
| 11038 |
memcpy(cats_seen, pop_include, raw_cat_ctl * sizeof(intptr_t)); |
| 11039 |
sample_ct = RemoveExcludedCats(old_cats, cats_seen, raw_sample_ct, sample_ct, sample_include); |
| 11040 |
} |
| 11041 |
if (flags & kfFstOneBasePop) { |
| 11042 |
pop_pair_ct = named_pop_ct - 1; |
| 11043 |
if (unlikely(bigstack_alloc_u32(2 * pop_pair_ct, &pop_pairs))) { |
| 11044 |
goto FstReport_ret_NOMEM; |
| 11045 |
} |
| 11046 |
uint32_t* pop_pairs_iter = pop_pairs; |
| 11047 |
uint32_t uii = 0; |
| 11048 |
uintptr_t cats_seen_base = 0; |
| 11049 |
uintptr_t cats_seen_bits = cats_seen[0]; |
| 11050 |
for (; uii != named_pop_ct; ++uii) { |
| 11051 |
uint32_t other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits); |
| 11052 |
if (first_cat_idx == other_cat_idx) { |
| 11053 |
while (1) { |
| 11054 |
++uii; |
| 11055 |
if (uii == named_pop_ct) { |
| 11056 |
break; |
| 11057 |
} |
| 11058 |
other_cat_idx = BitIter1(cats_seen, &cats_seen_base, &cats_seen_bits); |
| 11059 |
*pop_pairs_iter++ = first_cat_idx; |
| 11060 |
*pop_pairs_iter++ = other_cat_idx; |
| 11061 |
} |
| 11062 |
break; |
| 11063 |
} |
| 11064 |
*pop_pairs_iter++ = other_cat_idx; |
| 11065 |
*pop_pairs_iter++ = first_cat_idx; |
| 11066 |
} |
| 11067 |
} else { |
| 11068 |
// ids= |
| 11069 |
SetBit(first_cat_idx, cats_seen); |
| 11070 |
const uint64_t named_pop_ct_m1 = named_pop_ct - k1LU; |
| 11071 |
const uint64_t pop_pair_ct_u64 = (named_pop_ct * named_pop_ct_m1) / 2; |
| 11072 |
if (unlikely(bigstack_alloc64_u32(2 * pop_pair_ct_u64, &pop_pairs))) { |
| 11073 |
goto FstReport_ret_NOMEM; |
| 11074 |
} |
| 11075 |
pop_pair_ct = pop_pair_ct_u64; |
| 11076 |
uint32_t* pop_pairs_iter = pop_pairs; |
| 11077 |
uintptr_t cats_seen_base1 = 0; |
| 11078 |
uintptr_t cats_seen_bits1 = cats_seen[0]; |
| 11079 |
for (uintptr_t ulii = 0; ulii != named_pop_ct_m1; ++ulii) { |
| 11080 |
const uint32_t cat_idx1 = BitIter1(cats_seen, &cats_seen_base1, &cats_seen_bits1); |
| 11081 |
uintptr_t cats_seen_base2 = cats_seen_base1; |
| 11082 |
uintptr_t cats_seen_bits2 = cats_seen_bits1; |
| 11083 |
for (uintptr_t uljj = ulii; uljj != named_pop_ct_m1; ++uljj) { |
| 11084 |
const uint32_t cat_idx2 = BitIter1(cats_seen, &cats_seen_base2, &cats_seen_bits2); |
| 11085 |
*pop_pairs_iter++ = cat_idx1; |
| 11086 |
*pop_pairs_iter++ = cat_idx2; |
| 11087 |
} |
| 11088 |
} |
| 11089 |
} |
| 11090 |
} |
| 11091 |
} else if (flags & kfFstPopPairFile) { |
| 11092 |
const uint64_t possible_pair_ct_u64 = S_CAST(uint64_t, nonnull_category_ct) * (nonnull_category_ct + 1LLU) / 2; |
| 11093 |
const uint64_t possible_pair_ctl_u64 = DivUpU64(possible_pair_ct_u64, kBitsPerWord); |
| 11094 |
uintptr_t* selected_pairs; |
| 11095 |
uintptr_t* pop_include; |
| 11096 |
if (unlikely(bigstack_end_calloc64_w(possible_pair_ctl_u64, &selected_pairs) || |
| 11097 |
bigstack_end_calloc_w(raw_cat_ctl, &pop_include))) { |
| 11098 |
goto FstReport_ret_NOMEM; |
| 11099 |
} |
| 11100 |
unsigned char* bigstack_end_mark2 = g_bigstack_end; |
| 11101 |
const char* in_fname = fst_infop->first_id_or_fname; |
| 11102 |
reterr = InitTextStreamEx(in_fname, 1, kMaxLongLine, kTextStreamBlenFast, 1, &txs); |
| 11103 |
if (unlikely(reterr)) { |
| 11104 |
goto FstReport_ret_TSTREAM_FAIL; |
| 11105 |
} |
| 11106 |
const char** nonnull_category_names = &(pheno_col->category_names[1]); |
| 11107 |
uintptr_t duplicate_ct = 0; |
| 11108 |
uintptr_t line_idx = 0; |
| 11109 |
while (1) { |
| 11110 |
++line_idx; |
| 11111 |
char* first_token_start = TextGet(&txs); |
| 11112 |
if (!first_token_start) { |
| 11113 |
if (likely(!TextStreamErrcode2(&txs, &reterr))) { |
| 11114 |
break; |
| 11115 |
} |
| 11116 |
goto FstReport_ret_TSTREAM_FAIL; |
| 11117 |
} |
| 11118 |
char* first_token_end = CurTokenEnd(first_token_start); |
| 11119 |
char* second_token_start = FirstNonTspace(first_token_end); |
| 11120 |
if (unlikely(IsEolnKns(*second_token_start))) { |
| 11121 |
logerrprintfww("Error: Line %" PRIuPTR " of %s has fewer tokens than expected.\n", line_idx, in_fname); |
| 11122 |
goto FstReport_ret_MALFORMED_INPUT; |
| 11123 |
} |
| 11124 |
char* second_token_end = CurTokenEnd(second_token_start); |
| 11125 |
*first_token_end = '\0'; |
| 11126 |
const uintptr_t cat_idx1 = 1 + bsearch_strptr_natural(first_token_start, nonnull_category_names, nonnull_category_ct); |
| 11127 |
if (unlikely(!IsSet(cats_seen, cat_idx1))) { |
| 11128 |
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, first_token_start); |
| 11129 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 11130 |
} |
| 11131 |
*second_token_end = '\0'; |
| 11132 |
const uintptr_t cat_idx2 = 1 + bsearch_strptr_natural(second_token_start, nonnull_category_names, nonnull_category_ct); |
| 11133 |
if (unlikely(!IsSet(cats_seen, cat_idx2))) { |
| 11134 |
logerrprintfww("Error: --fst phenotype '%s' does not have a nonempty population with ID '%s'.\n", pheno_name, second_token_start); |
| 11135 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 11136 |
} |
| 11137 |
uintptr_t bit_idx; |
| 11138 |
if (cat_idx1 < cat_idx2) { |
| 11139 |
bit_idx = ((cat_idx2 * (cat_idx2 - 1)) / 2) + cat_idx1; |
| 11140 |
} else if (likely(cat_idx2 < cat_idx1)) { |
| 11141 |
bit_idx = ((cat_idx1 * (cat_idx1 - 1)) / 2) + cat_idx2; |
| 11142 |
} else { |
| 11143 |
logerrprintfww("Error: Both populations on line %" PRIuPTR " of %s are the same.\n", line_idx, in_fname); |
| 11144 |
goto FstReport_ret_MALFORMED_INPUT; |
| 11145 |
} |
| 11146 |
SetBit(cat_idx1, pop_include); |
| 11147 |
SetBit(cat_idx2, pop_include); |
| 11148 |
duplicate_ct += IsSet(selected_pairs, bit_idx); |
| 11149 |
SetBit(bit_idx, selected_pairs); |
| 11150 |
} |
| 11151 |
if (unlikely(CleanupTextStream2("--fst file", &txs, &reterr))) { |
| 11152 |
goto FstReport_ret_1; |
| 11153 |
} |
| 11154 |
const uintptr_t named_pop_ct = PopcountWords(pop_include, raw_cat_ctl); |
| 11155 |
if (named_pop_ct != pop_ct) { |
| 11156 |
pop_ct = named_pop_ct; |
| 11157 |
memcpy(cats_seen, pop_include, raw_cat_ctl * sizeof(intptr_t)); |
| 11158 |
sample_ct = RemoveExcludedCats(old_cats, cats_seen, raw_sample_ct, sample_ct, sample_include); |
| 11159 |
} |
| 11160 |
BigstackEndReset(bigstack_end_mark2); |
| 11161 |
pop_pair_ct = PopcountWords(selected_pairs, possible_pair_ctl_u64); |
| 11162 |
if (unlikely(!pop_pair_ct)) { |
| 11163 |
logerrprintfww("Error: %s is empty.\n", in_fname); |
| 11164 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 11165 |
} |
| 11166 |
logprintfww("--fst: %" PRIuPTR "%s population pair%s loaded from %s.\n", pop_pair_ct, duplicate_ct? " distinct" : "", (pop_pair_ct == 1)? "" : "s", in_fname); |
| 11167 |
if (duplicate_ct) { |
| 11168 |
logerrprintf("Warning: %" PRIuPTR " duplicate pair%s in --fst file.\n", duplicate_ct, (duplicate_ct == 1)? "" : "s"); |
| 11169 |
} |
| 11170 |
if (unlikely(bigstack_alloc_u32(2 * pop_pair_ct, &pop_pairs))) { |
| 11171 |
goto FstReport_ret_NOMEM; |
| 11172 |
} |
| 11173 |
uint32_t* pop_pairs_iter = pop_pairs; |
| 11174 |
uintptr_t selected_pairs_base = 0; |
| 11175 |
uintptr_t selected_pairs_bits = selected_pairs[0]; |
| 11176 |
uintptr_t cur_tri = 0; |
| 11177 |
uintptr_t idx_hi = 1; |
| 11178 |
for (uintptr_t ulii = 0; ulii != pop_pair_ct; ++ulii) { |
| 11179 |
const uintptr_t selected_pairs_uidx = BitIter1(selected_pairs, &selected_pairs_base, &selected_pairs_bits); |
| 11180 |
uintptr_t idx_lo = selected_pairs_uidx - cur_tri; |
| 11181 |
while (idx_lo >= idx_hi) { |
| 11182 |
idx_lo -= idx_hi; |
| 11183 |
cur_tri += idx_hi; |
| 11184 |
++idx_hi; |
| 11185 |
} |
| 11186 |
*pop_pairs_iter++ = idx_lo; |
| 11187 |
*pop_pairs_iter++ = idx_hi; |
| 11188 |
} |
| 11189 |
} |
| 11190 |
uint32_t* sample_include_cumulative_popcounts; |
| 11191 |
uint32_t* sample_to_pop_idx; |
| 11192 |
uint32_t* diploid_pop_sizes; |
| 11193 |
uint32_t* old_cat_idx_to_new; |
| 11194 |
if (unlikely(bigstack_alloc_u32(raw_sample_ctl, &sample_include_cumulative_popcounts) || |
| 11195 |
bigstack_alloc_u32(sample_ct, &sample_to_pop_idx) || |
| 11196 |
bigstack_calloc_u32(pop_ct, &diploid_pop_sizes) || |
| 11197 |
bigstack_alloc_kcp(pop_ct, &pop_names) || |
| 11198 |
bigstack_end_alloc_u32(1 + nonnull_category_ct, &old_cat_idx_to_new))) { |
| 11199 |
goto FstReport_ret_NOMEM; |
| 11200 |
} |
| 11201 |
ctx.sample_include = sample_include; |
| 11202 |
FillCumulativePopcounts(sample_include, raw_sample_ctl, sample_include_cumulative_popcounts); |
| 11203 |
ctx.sample_include_cumulative_popcounts = sample_include_cumulative_popcounts; |
| 11204 |
uintptr_t cat_uidx_base = 0; |
| 11205 |
uintptr_t cats_seen_bits = cats_seen[0]; |
| 11206 |
for (uintptr_t cat_idx = 0; cat_idx != pop_ct; ++cat_idx) { |
| 11207 |
const uintptr_t cat_uidx = BitIter1(cats_seen, &cat_uidx_base, &cats_seen_bits); |
| 11208 |
old_cat_idx_to_new[cat_uidx] = cat_idx; |
| 11209 |
pop_names[cat_idx] = pheno_col->category_names[cat_uidx]; |
| 11210 |
} |
| 11211 |
uintptr_t sample_uidx_base = 0; |
| 11212 |
uintptr_t sample_include_bits = sample_include[0]; |
| 11213 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 11214 |
const uintptr_t sample_uidx = BitIter1(sample_include, &sample_uidx_base, &sample_include_bits); |
| 11215 |
const uint32_t pop_idx = old_cat_idx_to_new[old_cats[sample_uidx]]; |
| 11216 |
sample_to_pop_idx[sample_idx] = pop_idx; |
| 11217 |
diploid_pop_sizes[pop_idx] += 1; |
| 11218 |
} |
| 11219 |
ctx.sample_to_pop_idx = sample_to_pop_idx; |
| 11220 |
ctx.diploid_pop_sizes = diploid_pop_sizes; |
| 11221 |
ctx.sample_ct = sample_ct; |
| 11222 |
ctx.pop_ct = pop_ct; |
| 11223 |
if (!(flags & (kfFstOneBasePop | kfFstExplicitPopIds | kfFstPopPairFile))) { |
| 11224 |
const uint64_t pop_pair_ct_u64 = (S_CAST(uint64_t, pop_ct) * (pop_ct - k1LU)) / 2; |
| 11225 |
if (unlikely(bigstack_alloc64_u32(2 * pop_pair_ct_u64, &pop_pairs))) { |
| 11226 |
goto FstReport_ret_NOMEM; |
| 11227 |
} |
| 11228 |
pop_pair_ct = pop_pair_ct_u64; |
| 11229 |
uint32_t* pop_pairs_iter = pop_pairs; |
| 11230 |
const uint32_t pop_ct_m1 = pop_ct - 1; |
| 11231 |
for (uint32_t first_pop_idx = 0; first_pop_idx != pop_ct_m1; ++first_pop_idx) { |
| 11232 |
for (uint32_t second_pop_idx = first_pop_idx + 1; second_pop_idx != pop_ct; ++second_pop_idx) { |
| 11233 |
*pop_pairs_iter++ = first_pop_idx; |
| 11234 |
*pop_pairs_iter++ = second_pop_idx; |
| 11235 |
} |
| 11236 |
} |
| 11237 |
} else { |
| 11238 |
const uintptr_t pop_pair_ct_x2 = pop_pair_ct * 2; |
| 11239 |
for (uintptr_t ulii = 0; ulii != pop_pair_ct_x2; ++ulii) { |
| 11240 |
pop_pairs[ulii] = old_cat_idx_to_new[pop_pairs[ulii]]; |
| 11241 |
} |
| 11242 |
} |
| 11243 |
BigstackEndReset(bigstack_end_mark); |
| 11244 |
} |
| 11245 |
logprintf("--fst: Analyzing %u samples across %" PRIuPTR " populations.\n", sample_ct, pop_ct); |
| 11246 |
if (unlikely(bigstack_alloc_wp(max_thread_ct, &ctx.raregenos) || |
| 11247 |
bigstack_alloc_u32p(max_thread_ct, &ctx.difflist_sample_id_bufs) || |
| 11248 |
bigstack_alloc_u32p(max_thread_ct, &ctx.pop_geno_bufs))) { |
| 11249 |
goto FstReport_ret_NOMEM; |
| 11250 |
} |
| 11251 |
const uint32_t report_variants = (flags / kfFstReportVariants) & 1; |
| 11252 |
if (report_variants) { |
| 11253 |
max_variant_file_ct = MINV(pop_pair_ct, kFstReportVariantsBatchMax); |
| 11254 |
if (unlikely(bigstack_calloc_cp(max_variant_file_ct, &v_cswritep_arr) || |
| 11255 |
BIGSTACK_ALLOC_X(CompressStreamState, max_variant_file_ct, &v_css_arr))) { |
| 11256 |
goto FstReport_ret_NOMEM; |
| 11257 |
} |
| 11258 |
for (uintptr_t fidx = 0; fidx != max_variant_file_ct; ++fidx) { |
| 11259 |
PreinitCstream(&(v_css_arr[fidx])); |
| 11260 |
} |
| 11261 |
} |
| 11262 |
const uint32_t v_output_zst = (flags / kfFstZs) & 1; |
| 11263 |
const uint32_t chrom_vcol = (flags / kfFstVcolChrom) & 1; |
| 11264 |
char* chr_buf = nullptr; |
| 11265 |
if (chrom_vcol) { |
| 11266 |
uint32_t max_chr_blen = GetMaxChrSlen(cip) + 1; |
| 11267 |
if (unlikely(bigstack_alloc_c(max_chr_blen, &chr_buf))) { |
| 11268 |
goto FstReport_ret_NOMEM; |
| 11269 |
} |
| 11270 |
} |
| 11271 |
const uint32_t pos_vcol = (flags / kfFstVcolPos) & 1; |
| 11272 |
const uint32_t ref_vcol = (flags / kfFstVcolRef) & 1; |
| 11273 |
const uint32_t alt_vcol = (flags / kfFstVcolAlt) & 1; |
| 11274 |
const uint32_t alleles_needed = ref_vcol || alt_vcol; |
| 11275 |
const uintptr_t* nonref_flags = pgfip->nonref_flags; |
| 11276 |
const uint32_t all_nonref = (pgfip->gflags & kfPgenGlobalAllNonref) && (!nonref_flags); |
| 11277 |
const uint32_t nobs_vcol = (flags / kfFstVcolNobs) & 1; |
| 11278 |
const uint32_t nallele_vcol = (flags / kfFstVcolNallele) & 1; |
| 11279 |
const uint32_t fstfrac_vcol = (flags / kfFstVcolFstfrac) & 1; |
| 11280 |
const uint32_t fst_vcol = (flags / kfFstVcolFst) & 1; |
| 11281 |
const uint32_t jackknife_blocksize = fst_infop->blocksize; |
| 11282 |
const uint32_t max_returned_difflist_len = 2 * (raw_sample_ct / kPglMaxDifflistLenDivisor); |
| 11283 |
const uintptr_t raregeno_vec_ct = DivUp(max_returned_difflist_len, kNypsPerVec); |
| 11284 |
const uintptr_t difflist_sample_id_vec_ct = DivUp(max_returned_difflist_len, kInt32PerVec); |
| 11285 |
const uint32_t mhc_needed = (max_allele_ct > 2); |
| 11286 |
|
| 11287 |
const uint32_t raw_variant_ctl = BitCtToWordCt(raw_variant_ct); |
| 11288 |
unsigned char* bigstack_mark2 = g_bigstack_base; |
| 11289 |
uint32_t allele_ct = 2; |
| 11290 |
for (uint32_t is_x = 0; is_x != 2; ++is_x) { |
| 11291 |
const uintptr_t* cur_variant_include = orig_variant_include; |
| 11292 |
char* outname_end2 = outname_end; |
| 11293 |
uint32_t cur_variant_ct; |
| 11294 |
if (!is_x) { |
| 11295 |
cur_variant_ct = orig_variant_ct; |
| 11296 |
reterr = ConditionalAllocateNonAutosomalVariants(cip, nullptr, raw_variant_ct, &cur_variant_include, &cur_variant_ct); |
| 11297 |
if (unlikely(reterr)) { |
| 11298 |
goto FstReport_ret_1; |
| 11299 |
} |
| 11300 |
ctx.sex_male_collapsed = nullptr; |
| 11301 |
ctx.haploid_pop_sizes = nullptr; |
| 11302 |
} else { |
| 11303 |
if (is_wc) { |
| 11304 |
break; |
| 11305 |
} |
| 11306 |
outname_end2 = strcpya_k(outname_end2, ".x"); |
| 11307 |
cur_variant_ct = 0; |
| 11308 |
uint32_t x_code; |
| 11309 |
if (XymtExists(cip, kChrOffsetX, &x_code)) { |
| 11310 |
const uint32_t chr_fo_idx = cip->chr_idx_to_foidx[x_code]; |
| 11311 |
const uint32_t start_idx = cip->chr_fo_vidx_start[chr_fo_idx]; |
| 11312 |
const uint32_t end_idx = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 11313 |
cur_variant_ct = PopcountBitRange(orig_variant_include, start_idx, end_idx); |
| 11314 |
if (cur_variant_ct && (cur_variant_ct != orig_variant_ct)) { |
| 11315 |
// may want this in a plink2_common function |
| 11316 |
uintptr_t* tmp_variant_include; |
| 11317 |
if (unlikely(bigstack_alloc_w(raw_variant_ctl, &tmp_variant_include))) { |
| 11318 |
goto FstReport_ret_NOMEM; |
| 11319 |
} |
| 11320 |
const uint32_t start_widx = start_idx / kBitsPerWord; |
| 11321 |
const uint32_t end_widx = DivUp(end_idx, kBitsPerWord); |
| 11322 |
ZeroWArr(start_widx, tmp_variant_include); |
| 11323 |
memcpy(&(tmp_variant_include[start_widx]), &(orig_variant_include[start_widx]), (end_widx - start_widx) * sizeof(intptr_t)); |
| 11324 |
ZeroWArr(raw_variant_ctl - end_widx, &(tmp_variant_include[end_widx])); |
| 11325 |
const uint32_t start_remainder = start_idx % kBitsPerWord; |
| 11326 |
tmp_variant_include[start_widx] &= (~k0LU) << start_remainder; |
| 11327 |
const uint32_t end_remainder = end_idx % kBitsPerWord; |
| 11328 |
if (end_remainder) { |
| 11329 |
tmp_variant_include[end_widx - 1] &= (k1LU << end_remainder) - 1; |
| 11330 |
} |
| 11331 |
cur_variant_include = tmp_variant_include; |
| 11332 |
} |
| 11333 |
const uint32_t haploid_present = !IntersectionIsEmpty(sample_include, sex_male, raw_sample_ctl); |
| 11334 |
if (haploid_present) { |
| 11335 |
const uint32_t sample_ctl = BitCtToWordCt(sample_ct); |
| 11336 |
uintptr_t* sex_male_collapsed; |
| 11337 |
uint32_t* haploid_pop_sizes; |
| 11338 |
if (unlikely(bigstack_alloc_w(sample_ctl, &sex_male_collapsed) || |
| 11339 |
bigstack_calloc_u32(pop_ct, &haploid_pop_sizes))) { |
| 11340 |
goto FstReport_ret_NOMEM; |
| 11341 |
} |
| 11342 |
CopyBitarrSubset(sex_male, sample_include, sample_ct, sex_male_collapsed); |
| 11343 |
const uint32_t* sample_to_pop_idx = ctx.sample_to_pop_idx; |
| 11344 |
for (uint32_t sample_idx = 0; sample_idx != sample_ct; ++sample_idx) { |
| 11345 |
const uint32_t pop_idx = sample_to_pop_idx[sample_idx]; |
| 11346 |
haploid_pop_sizes[pop_idx] += IsSet(sex_male_collapsed, sample_idx); |
| 11347 |
} |
| 11348 |
// This assumes is_x happens after !is_x. |
| 11349 |
for (uintptr_t pop_idx = 0; pop_idx != pop_ct; ++pop_idx) { |
| 11350 |
ctx.diploid_pop_sizes[pop_idx] -= haploid_pop_sizes[pop_idx]; |
| 11351 |
} |
| 11352 |
ctx.sex_male_collapsed = sex_male_collapsed; |
| 11353 |
ctx.haploid_pop_sizes = haploid_pop_sizes; |
| 11354 |
} |
| 11355 |
} |
| 11356 |
} |
| 11357 |
if (!cur_variant_ct) { |
| 11358 |
continue; |
| 11359 |
} |
| 11360 |
const uint32_t provref_vcol = ref_vcol && ProvrefCol(cur_variant_include, nonref_flags, flags / kfFstVcolMaybeprovref, raw_variant_ct, all_nonref); |
| 11361 |
ctx.cur_variant_include = cur_variant_include; |
| 11362 |
const uintptr_t pop_geno_vec_ct = DivUp(pop_ct * (4 << (ctx.sex_male_collapsed != nullptr)), kInt32PerVec); |
| 11363 |
const uintptr_t thread_xalloc_vec_ct = raregeno_vec_ct + difflist_sample_id_vec_ct + pop_geno_vec_ct; |
| 11364 |
const uintptr_t thread_xalloc_cacheline_ct = DivUp(thread_xalloc_vec_ct, kVecsPerCacheline); |
| 11365 |
const uintptr_t per_allele_xalloc_byte_ct = pop_ct * sizeof(int32_t) * 2 * (1 + is_wc); |
| 11366 |
uintptr_t per_variant_xalloc_byte_ct = per_allele_xalloc_byte_ct; |
| 11367 |
if (nobs_vcol || is_wc) { |
| 11368 |
per_variant_xalloc_byte_ct += pop_ct * sizeof(int32_t) * 2; |
| 11369 |
} else { |
| 11370 |
ctx.pop_nm_sample_cts[0] = nullptr; |
| 11371 |
ctx.pop_nm_sample_cts[1] = nullptr; |
| 11372 |
} |
| 11373 |
if (!is_wc) { |
| 11374 |
// half_within |
| 11375 |
per_variant_xalloc_byte_ct += pop_ct * sizeof(double) * 2; |
| 11376 |
|
| 11377 |
ctx.pop_allele_het_cts[0] = nullptr; |
| 11378 |
ctx.pop_allele_het_cts[1] = nullptr; |
| 11379 |
} else { |
| 11380 |
// pop_allele_het_cts already included in (1 + is_wc) term above |
| 11381 |
ctx.half_within[0] = nullptr; |
| 11382 |
ctx.half_within[1] = nullptr; |
| 11383 |
} |
| 11384 |
uint32_t calc_thread_ct = max_thread_ct; |
| 11385 |
|
| 11386 |
strcpy_k(outname_end2, ".fst.summary"); |
| 11387 |
if (unlikely(fopen_checked(outname, FOPEN_WB, &s_outfile))) { |
| 11388 |
goto FstReport_ret_OPEN_FAIL; |
| 11389 |
} |
| 11390 |
char* s_write_iter = g_textbuf; |
| 11391 |
char* s_textbuf_flush = &(s_write_iter[kMaxMediumLine]); |
| 11392 |
s_write_iter = strcpya_k(s_write_iter, "#POP1\tPOP2\t"); |
| 11393 |
const uint32_t nobs_scol = (flags / kfFstColNobs) & 1; |
| 11394 |
if (nobs_scol) { |
| 11395 |
s_write_iter = strcpya_k(s_write_iter, "OBS_CT\t"); |
| 11396 |
} |
| 11397 |
if (!is_wc) { |
| 11398 |
s_write_iter = strcpya_k(s_write_iter, "HUDSON_FST"); |
| 11399 |
} else { |
| 11400 |
s_write_iter = strcpya_k(s_write_iter, "WC_FST"); |
| 11401 |
} |
| 11402 |
if (jackknife_blocksize) { |
| 11403 |
s_write_iter = strcpya_k(s_write_iter, "\tSE"); |
| 11404 |
} |
| 11405 |
AppendBinaryEoln(&s_write_iter); |
| 11406 |
|
| 11407 |
uintptr_t pop_pair_batch_size = pop_pair_ct; |
| 11408 |
uintptr_t pass_ct = 1; |
| 11409 |
if (report_variants && (pop_pair_ct > kFstReportVariantsBatchMax)) { |
| 11410 |
pop_pair_batch_size = kFstReportVariantsBatchMax; |
| 11411 |
pass_ct = DivUp(pop_pair_ct, kFstReportVariantsBatchMax); |
| 11412 |
} |
| 11413 |
double* fst_numer_sums; |
| 11414 |
double* fst_denom_sums; |
| 11415 |
uint32_t* fst_nobs; |
| 11416 |
if (unlikely(bigstack_alloc_d(pop_pair_batch_size, &fst_numer_sums) || |
| 11417 |
bigstack_alloc_d(pop_pair_batch_size, &fst_denom_sums) || |
| 11418 |
bigstack_alloc_u32(pop_pair_batch_size, &fst_nobs))) { |
| 11419 |
goto FstReport_ret_NOMEM; |
| 11420 |
} |
| 11421 |
uint32_t jackknife_block_max = 0; |
| 11422 |
if (jackknife_blocksize) { |
| 11423 |
if (cur_variant_ct <= jackknife_blocksize) { |
| 11424 |
logerrprintf("Warning: Too few %s variants for --fst blocksize=%u to be useful.\n", is_x? "chrX" : "autosomal", jackknife_blocksize); |
| 11425 |
} |
| 11426 |
jackknife_block_max = DivUp(cur_variant_ct, jackknife_blocksize); |
| 11427 |
} |
| 11428 |
// <output prefix, including .x>.<popID1>.<popID2>.fst.var[.zst] |
| 11429 |
const uint32_t pop_name_capacity = kPglFnamesize - 11 - (4 * v_output_zst) - S_CAST(uintptr_t, outname_end2 - outname); |
| 11430 |
unsigned char* bigstack_mark3 = g_bigstack_base; |
| 11431 |
for (uintptr_t pass_idx = 0; pass_idx != pass_ct; ++pass_idx) { |
| 11432 |
const uintptr_t pop_pair_start_idx = pass_idx * pop_pair_batch_size; |
| 11433 |
if (pass_idx == pass_ct - 1) { |
| 11434 |
pop_pair_batch_size = pop_pair_ct - pop_pair_start_idx; |
| 11435 |
} |
| 11436 |
const uint32_t* cur_pop_pairs = &(pop_pairs[2 * pop_pair_start_idx]); |
| 11437 |
if (report_variants) { |
| 11438 |
if (pop_pair_batch_size > pop_pair_ct - pop_pair_start_idx) { |
| 11439 |
pop_pair_batch_size = pop_pair_ct - pop_pair_start_idx; |
| 11440 |
} |
| 11441 |
for (uintptr_t fidx = 0; fidx != pop_pair_batch_size; ++fidx) { |
| 11442 |
{ |
| 11443 |
const uint32_t pop_idx1 = cur_pop_pairs[2 * fidx]; |
| 11444 |
const uint32_t pop_idx2 = cur_pop_pairs[2 * fidx + 1]; |
| 11445 |
char* fname_iter = outname_end2; |
| 11446 |
const uint32_t slen1 = strlen(pop_names[pop_idx1]); |
| 11447 |
const uint32_t slen2 = strlen(pop_names[pop_idx2]); |
| 11448 |
if (unlikely(slen1 + slen2 > pop_name_capacity)) { |
| 11449 |
logerrputs("Error: Population name and/or --out argument too long.\n"); |
| 11450 |
goto FstReport_ret_INCONSISTENT_INPUT; |
| 11451 |
} |
| 11452 |
*fname_iter++ = '.'; |
| 11453 |
fname_iter = memcpyax(fname_iter, pop_names[pop_idx1], slen1, '.'); |
| 11454 |
fname_iter = memcpya(fname_iter, pop_names[pop_idx2], slen2); |
| 11455 |
OutnameZstSet(".fst.var", v_output_zst, fname_iter); |
| 11456 |
} |
| 11457 |
reterr = InitCstreamAlloc(outname, 0, v_output_zst, 1, 2 * kCompressStreamBlock, &(v_css_arr[fidx]), &(v_cswritep_arr[fidx])); |
| 11458 |
if (unlikely(reterr)) { |
| 11459 |
goto FstReport_ret_1; |
| 11460 |
} |
| 11461 |
char* cswritep = v_cswritep_arr[fidx]; |
| 11462 |
*cswritep++ = '#'; |
| 11463 |
if (chrom_vcol) { |
| 11464 |
cswritep = strcpya_k(cswritep, "CHROM\t"); |
| 11465 |
} |
| 11466 |
if (pos_vcol) { |
| 11467 |
cswritep = strcpya_k(cswritep, "POS\t"); |
| 11468 |
} |
| 11469 |
cswritep = strcpya_k(cswritep, "ID"); |
| 11470 |
if (ref_vcol) { |
| 11471 |
cswritep = strcpya_k(cswritep, "\tREF"); |
| 11472 |
} |
| 11473 |
if (alt_vcol) { |
| 11474 |
cswritep = strcpya_k(cswritep, "\tALT"); |
| 11475 |
} |
| 11476 |
if (provref_vcol) { |
| 11477 |
cswritep = strcpya_k(cswritep, "\tPROVISIONAL_REF?"); |
| 11478 |
} |
| 11479 |
if (nobs_vcol) { |
| 11480 |
cswritep = strcpya_k(cswritep, "\tOBS_CT"); |
| 11481 |
} |
| 11482 |
if (nallele_vcol) { |
| 11483 |
cswritep = strcpya_k(cswritep, "\tPOP1_ALLELE_CT\tPOP2_ALLELE_CT"); |
| 11484 |
} |
| 11485 |
if (fstfrac_vcol) { |
| 11486 |
cswritep = strcpya_k(cswritep, "\tFST_NUMER\tFST_DENOM"); |
| 11487 |
} |
| 11488 |
if (fst_vcol) { |
| 11489 |
if (!is_wc) { |
| 11490 |
cswritep = strcpya_k(cswritep, "\tHUDSON_FST"); |
| 11491 |
} else { |
| 11492 |
cswritep = strcpya_k(cswritep, "\tWC_FST"); |
| 11493 |
} |
| 11494 |
} |
| 11495 |
AppendBinaryEoln(&cswritep); |
| 11496 |
v_cswritep_arr[fidx] = cswritep; |
| 11497 |
} |
| 11498 |
} |
| 11499 |
ZeroDArr(pop_pair_batch_size, fst_numer_sums); |
| 11500 |
ZeroDArr(pop_pair_batch_size, fst_denom_sums); |
| 11501 |
ZeroU32Arr(pop_pair_batch_size, fst_nobs); |
| 11502 |
double* jackknife_fst_numers = nullptr; |
| 11503 |
double* jackknife_fst_denoms = nullptr; |
| 11504 |
uint32_t* jackknife_next_block_starts = nullptr; |
| 11505 |
// In the jackknife case, fst_{numer,denom}_sums are only for the |
| 11506 |
// current block while the calculation is in progress; we save them off |
| 11507 |
// to jackknife_fst_{numers,denoms} when each block is complete. |
| 11508 |
if (jackknife_blocksize) { |
| 11509 |
// leading dimension = pop-pair index |
| 11510 |
// strictly speaking, pop_pair_batch_size should be reduced if this |
| 11511 |
// would be too large, but that should never come up with any sane |
| 11512 |
// blocksize= choice |
| 11513 |
if (unlikely(bigstack_alloc_d(jackknife_block_max * pop_pair_batch_size, &jackknife_fst_numers) || |
| 11514 |
bigstack_alloc_d(jackknife_block_max * pop_pair_batch_size, &jackknife_fst_denoms) || |
| 11515 |
bigstack_alloc_u32(pop_pair_batch_size, &jackknife_next_block_starts))) { |
| 11516 |
goto FstReport_ret_NOMEM; |
| 11517 |
} |
| 11518 |
for (uintptr_t ulii = 0; ulii != pop_pair_batch_size; ++ulii) { |
| 11519 |
jackknife_next_block_starts[ulii] = jackknife_blocksize; |
| 11520 |
} |
| 11521 |
} |
| 11522 |
|
| 11523 |
uintptr_t bytes_avail = bigstack_left(); |
| 11524 |
// defend against adverse rounding |
| 11525 |
if (unlikely(bytes_avail < 6 * kCacheline)) { |
| 11526 |
goto FstReport_ret_NOMEM; |
| 11527 |
} |
| 11528 |
bytes_avail -= 6 * kCacheline; |
| 11529 |
|
| 11530 |
STD_ARRAY_DECL(unsigned char*, 2, main_loadbufs); |
| 11531 |
ctx.thread_read_mhc = nullptr; |
| 11532 |
uint32_t read_block_size; |
| 11533 |
uintptr_t max_alt_allele_block_size; |
| 11534 |
if (unlikely(PgenMtLoadInit(cur_variant_include, sample_ct, cur_variant_ct, bytes_avail, pgr_alloc_cacheline_ct, thread_xalloc_cacheline_ct, per_variant_xalloc_byte_ct, per_allele_xalloc_byte_ct, pgfip, &calc_thread_ct, &ctx.genovecs, mhc_needed? (&ctx.thread_read_mhc) : nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &read_block_size, &max_alt_allele_block_size, main_loadbufs, &ctx.pgr_ptrs, &ctx.read_variant_uidx_starts))) { |
| 11535 |
goto FstReport_ret_NOMEM; |
| 11536 |
} |
| 11537 |
if (unlikely(SetThreadCt(calc_thread_ct, &tg))) { |
| 11538 |
goto FstReport_ret_NOMEM; |
| 11539 |
} |
| 11540 |
ctx.err_info = (~0LLU) << 32; |
| 11541 |
for (uint32_t tidx = 0; tidx != calc_thread_ct; ++tidx) { |
| 11542 |
unsigned char* cur_alloc = S_CAST(unsigned char*, bigstack_alloc_raw(thread_xalloc_cacheline_ct * kCacheline)); |
| 11543 |
ctx.raregenos[tidx] = R_CAST(uintptr_t*, cur_alloc); |
| 11544 |
cur_alloc = &(cur_alloc[raregeno_vec_ct * kBytesPerVec]); |
| 11545 |
ctx.difflist_sample_id_bufs[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 11546 |
cur_alloc = &(cur_alloc[difflist_sample_id_vec_ct * kBytesPerVec]); |
| 11547 |
ctx.pop_geno_bufs[tidx] = R_CAST(uint32_t*, cur_alloc); |
| 11548 |
cur_alloc = &(cur_alloc[pop_geno_vec_ct * kBytesPerVec]); |
| 11549 |
} |
| 11550 |
if (nobs_vcol || is_wc) { |
| 11551 |
const uintptr_t geno_obs_alloc = RoundUpPow2(pop_ct * sizeof(int32_t) * read_block_size, kCacheline); |
| 11552 |
ctx.pop_nm_sample_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(geno_obs_alloc)); |
| 11553 |
ctx.pop_nm_sample_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(geno_obs_alloc)); |
| 11554 |
} |
| 11555 |
const uintptr_t max_allele_block_size = read_block_size + max_alt_allele_block_size; |
| 11556 |
const uintptr_t allele_pop_alloc = RoundUpPow2(pop_ct * max_allele_block_size * sizeof(int32_t), kCacheline); |
| 11557 |
ctx.pop_allele_obs_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc)); |
| 11558 |
ctx.pop_allele_obs_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc)); |
| 11559 |
if (!is_wc) { |
| 11560 |
const uintptr_t half_within_alloc = RoundUpPow2(pop_ct * sizeof(double) * read_block_size, kCacheline); |
| 11561 |
ctx.half_within[0] = S_CAST(double*, bigstack_alloc_raw(half_within_alloc)); |
| 11562 |
ctx.half_within[1] = S_CAST(double*, bigstack_alloc_raw(half_within_alloc)); |
| 11563 |
} else { |
| 11564 |
ctx.pop_allele_het_cts[0] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc)); |
| 11565 |
ctx.pop_allele_het_cts[1] = S_CAST(uint32_t*, bigstack_alloc_raw(allele_pop_alloc)); |
| 11566 |
} |
| 11567 |
SetThreadFuncAndData(FstThread, &ctx, &tg); |
| 11568 |
|
| 11569 |
if (pop_pair_ct == pop_pair_batch_size) { |
| 11570 |
logprintf("%s --fst: ", is_x? "chrX" : "Autosomal"); |
| 11571 |
} else { |
| 11572 |
logprintf("%s --fst pass %u/%u: ", is_x? "chrX" : "Autosomal", pass_idx + 1, pass_ct); |
| 11573 |
} |
| 11574 |
fputs("0%", stdout); |
| 11575 |
fflush(stdout); |
| 11576 |
uint32_t pct = 0; |
| 11577 |
|
| 11578 |
uintptr_t write_variant_uidx_base = 0; |
| 11579 |
uintptr_t write_variant_bits = cur_variant_include[0]; |
| 11580 |
uint32_t parity = 0; |
| 11581 |
uint32_t read_block_idx = 0; |
| 11582 |
uint32_t chr_fo_idx = UINT32_MAX; |
| 11583 |
uint32_t chr_end = 0; |
| 11584 |
uint32_t chr_buf_blen = 0; |
| 11585 |
uint32_t prev_block_variant_ct = 0; |
| 11586 |
uint32_t next_print_variant_idx = cur_variant_ct / 100; |
| 11587 |
for (uint32_t variant_idx = 0; ; ) { |
| 11588 |
const uint32_t cur_block_variant_ct = MultireadNonempty(cur_variant_include, &tg, raw_variant_ct, read_block_size, pgfip, &read_block_idx, &reterr); |
| 11589 |
if (unlikely(reterr)) { |
| 11590 |
goto FstReport_ret_PGR_FAIL; |
| 11591 |
} |
| 11592 |
if (variant_idx) { |
| 11593 |
JoinThreads(&tg); |
| 11594 |
reterr = S_CAST(PglErr, ctx.err_info); |
| 11595 |
if (unlikely(reterr)) { |
| 11596 |
PgenErrPrintNV(reterr, ctx.err_info >> 32); |
| 11597 |
goto FstReport_ret_1; |
| 11598 |
} |
| 11599 |
} |
| 11600 |
if (!IsLastBlock(&tg)) { |
| 11601 |
ctx.cur_block_variant_ct = cur_block_variant_ct; |
| 11602 |
ComputeUidxStartPartition(cur_variant_include, cur_block_variant_ct, calc_thread_ct, read_block_idx * read_block_size, ctx.read_variant_uidx_starts); |
| 11603 |
PgrCopyBaseAndOffset(pgfip, calc_thread_ct, ctx.pgr_ptrs); |
| 11604 |
if (variant_idx + cur_block_variant_ct == cur_variant_ct) { |
| 11605 |
DeclareLastThreadBlock(&tg); |
| 11606 |
} |
| 11607 |
if (unlikely(SpawnThreads(&tg))) { |
| 11608 |
goto FstReport_ret_THREAD_CREATE_FAIL; |
| 11609 |
} |
| 11610 |
} |
| 11611 |
|
| 11612 |
parity = 1 - parity; |
| 11613 |
if (variant_idx) { |
| 11614 |
// process *previous* block results |
| 11615 |
const uint32_t* pop_nm_sample_cts_iter = ctx.pop_nm_sample_cts[parity]; |
| 11616 |
const uint32_t* pop_allele_obs_cts_iter = ctx.pop_allele_obs_cts[parity]; |
| 11617 |
const double* half_within_iter = ctx.half_within[parity]; |
| 11618 |
const uint32_t* pop_allele_het_cts_iter = ctx.pop_allele_het_cts[parity]; |
| 11619 |
for (uint32_t variant_bidx = 0; variant_bidx != prev_block_variant_ct; ++variant_bidx) { |
| 11620 |
const uint32_t write_variant_uidx = BitIter1(cur_variant_include, &write_variant_uidx_base, &write_variant_bits); |
| 11621 |
if (chr_buf && (write_variant_uidx >= chr_end)) { |
| 11622 |
do { |
| 11623 |
++chr_fo_idx; |
| 11624 |
chr_end = cip->chr_fo_vidx_start[chr_fo_idx + 1]; |
| 11625 |
} while (write_variant_uidx >= chr_end); |
| 11626 |
const uint32_t chr_idx = cip->chr_file_order[chr_fo_idx]; |
| 11627 |
char* chr_name_end = chrtoa(cip, chr_idx, chr_buf); |
| 11628 |
*chr_name_end = '\t'; |
| 11629 |
chr_buf_blen = 1 + S_CAST(uintptr_t, chr_name_end - chr_buf); |
| 11630 |
} |
| 11631 |
uintptr_t allele_idx_offset_base = write_variant_uidx * 2; |
| 11632 |
if (allele_idx_offsets) { |
| 11633 |
allele_idx_offset_base = allele_idx_offsets[write_variant_uidx]; |
| 11634 |
allele_ct = allele_idx_offsets[write_variant_uidx + 1] - allele_idx_offset_base; |
| 11635 |
} |
| 11636 |
for (uintptr_t pop_pair_bidx = 0; pop_pair_bidx != pop_pair_batch_size; ++pop_pair_bidx) { |
| 11637 |
const uint32_t pop_idx1 = cur_pop_pairs[2 * pop_pair_bidx]; |
| 11638 |
const uint32_t pop_idx2 = cur_pop_pairs[2 * pop_pair_bidx + 1]; |
| 11639 |
// See allel/stats/fst.py under |
| 11640 |
// https://github.com/cggh/scikit-allel for a more readable |
| 11641 |
// form of these computations. |
| 11642 |
double fst_numer = 0.0; |
| 11643 |
double fst_denom = 0.0; |
| 11644 |
uintptr_t pop1_n_hap = 0; |
| 11645 |
uintptr_t pop2_n_hap = 0; |
| 11646 |
if (!is_wc) { |
| 11647 |
// Hudson |
| 11648 |
uint64_t n_same = 0; |
| 11649 |
for (uintptr_t allele_idx = 0; allele_idx != allele_ct; ++allele_idx) { |
| 11650 |
const uintptr_t ct1 = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx1]; |
| 11651 |
const uintptr_t ct2 = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx2]; |
| 11652 |
pop1_n_hap += ct1; |
| 11653 |
pop2_n_hap += ct2; |
| 11654 |
n_same += S_CAST(uint64_t, ct1) * ct2; |
| 11655 |
} |
| 11656 |
const uint64_t n_pairs = S_CAST(uint64_t, pop1_n_hap) * pop2_n_hap; |
| 11657 |
const uint64_t n_diff = n_pairs - n_same; |
| 11658 |
if (n_diff) { |
| 11659 |
const double within = half_within_iter[pop_idx1] + half_within_iter[pop_idx2]; |
| 11660 |
fst_denom = u63tod(n_diff) / u63tod(n_pairs); |
| 11661 |
fst_numer = fst_denom - within; |
| 11662 |
} |
| 11663 |
} else { |
| 11664 |
// Weir-Cockerham |
| 11665 |
const uintptr_t pop1_size = pop_nm_sample_cts_iter[pop_idx1]; |
| 11666 |
const uintptr_t pop2_size = pop_nm_sample_cts_iter[pop_idx2]; |
| 11667 |
pop1_n_hap = pop1_size * 2; |
| 11668 |
pop2_n_hap = pop2_size * 2; |
| 11669 |
const uintptr_t n_total = pop1_size + pop2_size; |
| 11670 |
const double n_total_d = u31tod(n_total); |
| 11671 |
const double n_total_recip = 1.0 / n_total_d; |
| 11672 |
const double n_bar = n_total_d * 0.5; |
| 11673 |
const double n_bar_m1_recip = 1.0 / (n_bar - 1); |
| 11674 |
const double n_bar_div_n_c = n_bar / (n_total_d - u63tod(pop1_size * pop1_size + pop2_size * pop2_size) * n_total_recip); |
| 11675 |
const double pop1_size_d = u31tod(pop1_size); |
| 11676 |
const double pop2_size_d = u31tod(pop2_size); |
| 11677 |
const double pop1_size_recip = 1.0 / pop1_size_d; |
| 11678 |
const double pop2_size_recip = 1.0 / pop2_size_d; |
| 11679 |
double a_sum = 0.0; |
| 11680 |
double b_sum = 0.0; |
| 11681 |
double c_sum = 0.0; |
| 11682 |
const uintptr_t wc_allele_ct = (allele_ct == 2)? 1 : allele_ct; |
| 11683 |
for (uintptr_t allele_idx = 0; allele_idx != wc_allele_ct; ++allele_idx) { |
| 11684 |
const uint32_t pop1_cur_allele_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx1]; |
| 11685 |
const uint32_t pop2_cur_allele_ct = pop_allele_obs_cts_iter[allele_idx * pop_ct + pop_idx2]; |
| 11686 |
const uint32_t total_allele_ct = pop1_cur_allele_ct + pop2_cur_allele_ct; |
| 11687 |
if (!total_allele_ct) { |
| 11688 |
continue; |
| 11689 |
} |
| 11690 |
if (total_allele_ct == 2 * n_total) { |
| 11691 |
// guaranteed to have no variation; don't want to deal |
| 11692 |
// with rounding errors, etc. |
| 11693 |
break; |
| 11694 |
} |
| 11695 |
const double pop1_cur_allele_ct_d = u31tod(pop1_cur_allele_ct); |
| 11696 |
const double pop2_cur_allele_ct_d = u31tod(pop2_cur_allele_ct); |
| 11697 |
const double pop1_afreq = pop1_cur_allele_ct_d * pop1_size_recip * 0.5; |
| 11698 |
const double pop2_afreq = pop2_cur_allele_ct_d * pop2_size_recip * 0.5; |
| 11699 |
const double p_bar = (pop1_cur_allele_ct_d + pop2_cur_allele_ct_d) * 0.5 * n_total_recip; |
| 11700 |
const double s_squared_pop1_term = pop1_afreq - p_bar; |
| 11701 |
const double s_squared_pop2_term = pop2_afreq - p_bar; |
| 11702 |
const double s_squared = (pop1_size_d * s_squared_pop1_term * s_squared_pop1_term + pop2_size_d * s_squared_pop2_term * s_squared_pop2_term) * n_total_recip * 2; |
| 11703 |
const double h_bar = u31tod(pop_allele_het_cts_iter[allele_idx * pop_ct + pop_idx1] + pop_allele_het_cts_iter[allele_idx * pop_ct + pop_idx2]) * n_total_recip; |
| 11704 |
const double p_bar_times_1_minus_p_bar = p_bar * (1 - p_bar); |
| 11705 |
a_sum += n_bar_div_n_c * (s_squared - (p_bar_times_1_minus_p_bar - 0.5 * s_squared - 0.25 * h_bar) * n_bar_m1_recip); |
| 11706 |
b_sum += n_bar * n_bar_m1_recip * (p_bar_times_1_minus_p_bar - 0.5 * s_squared - (0.5 - 0.5 * n_total_recip) * h_bar); |
| 11707 |
c_sum += h_bar * 0.5; |
| 11708 |
} |
| 11709 |
fst_numer = a_sum; |
| 11710 |
fst_denom = a_sum + b_sum + c_sum; |
| 11711 |
} |
| 11712 |
if ((fst_denom != 0.0) && (fst_numer == fst_numer)) { |
| 11713 |
fst_numer_sums[pop_pair_bidx] += fst_numer; |
| 11714 |
fst_denom_sums[pop_pair_bidx] += fst_denom; |
| 11715 |
const uint32_t new_nobs = fst_nobs[pop_pair_bidx] + 1; |
| 11716 |
fst_nobs[pop_pair_bidx] = new_nobs; |
| 11717 |
if (jackknife_next_block_starts && (new_nobs == jackknife_next_block_starts[pop_pair_bidx])) { |
| 11718 |
const uintptr_t idx_2d = pop_pair_bidx * jackknife_block_max + (new_nobs / jackknife_blocksize) - 1; |
| 11719 |
const double cur_block_fst_numer_sum = fst_numer_sums[pop_pair_bidx]; |
| 11720 |
const double cur_block_fst_denom_sum = fst_denom_sums[pop_pair_bidx]; |
| 11721 |
jackknife_fst_numers[idx_2d] = cur_block_fst_numer_sum; |
| 11722 |
jackknife_fst_denoms[idx_2d] = cur_block_fst_denom_sum; |
| 11723 |
fst_numer_sums[pop_pair_bidx] = 0.0; |
| 11724 |
fst_denom_sums[pop_pair_bidx] = 0.0; |
| 11725 |
jackknife_next_block_starts[pop_pair_bidx] = new_nobs + jackknife_blocksize; |
| 11726 |
} |
| 11727 |
} |
| 11728 |
if (!report_variants) { |
| 11729 |
continue; |
| 11730 |
} |
| 11731 |
CompressStreamState* cssp = &(v_css_arr[pop_pair_bidx]); |
| 11732 |
char* cswritep = v_cswritep_arr[pop_pair_bidx]; |
| 11733 |
// first several columns are practically identical to e.g. |
| 11734 |
// AppendSdiffPregenoFields(); probably want a library |
| 11735 |
// function for this |
| 11736 |
if (chrom_vcol) { |
| 11737 |
cswritep = memcpya(cswritep, chr_buf, chr_buf_blen); |
| 11738 |
} |
| 11739 |
if (pos_vcol) { |
| 11740 |
cswritep = u32toa_x(variant_bps[write_variant_uidx], '\t', cswritep); |
| 11741 |
} |
| 11742 |
cswritep = strcpya(cswritep, variant_ids[write_variant_uidx]); |
| 11743 |
if (alleles_needed) { |
| 11744 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 11745 |
if (ref_vcol) { |
| 11746 |
*cswritep++ = '\t'; |
| 11747 |
const char* cur_allele = cur_alleles[0]; |
| 11748 |
const uint32_t allele_slen = strlen(cur_allele); |
| 11749 |
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) { |
| 11750 |
v_cswritep_arr[pop_pair_bidx] = cswritep; |
| 11751 |
goto FstReport_ret_WRITE_FAIL; |
| 11752 |
} |
| 11753 |
} |
| 11754 |
if (alt_vcol) { |
| 11755 |
*cswritep++ = '\t'; |
| 11756 |
for (uint32_t allele_idx = 1; allele_idx != allele_ct; ++allele_idx) { |
| 11757 |
const char* cur_allele = cur_alleles[allele_idx]; |
| 11758 |
const uint32_t allele_slen = strlen(cur_allele); |
| 11759 |
if (unlikely(CsputsStd(cur_allele, allele_slen, cssp, &cswritep))) { |
| 11760 |
v_cswritep_arr[pop_pair_bidx] = cswritep; |
| 11761 |
goto FstReport_ret_WRITE_FAIL; |
| 11762 |
} |
| 11763 |
*cswritep++ = ','; |
| 11764 |
} |
| 11765 |
--cswritep; |
| 11766 |
} |
| 11767 |
if (provref_vcol) { |
| 11768 |
*cswritep++ = '\t'; |
| 11769 |
*cswritep++ = (all_nonref || (nonref_flags && IsSet(nonref_flags, write_variant_uidx)))? 'Y' : 'N'; |
| 11770 |
} |
| 11771 |
} |
| 11772 |
if (nobs_vcol) { |
| 11773 |
*cswritep++ = '\t'; |
| 11774 |
cswritep = u32toa(pop_nm_sample_cts_iter[pop_idx1] + pop_nm_sample_cts_iter[pop_idx2], cswritep); |
| 11775 |
} |
| 11776 |
if (nallele_vcol) { |
| 11777 |
*cswritep++ = '\t'; |
| 11778 |
cswritep = u32toa_x(pop1_n_hap, '\t', cswritep); |
| 11779 |
cswritep = u32toa(pop2_n_hap, cswritep); |
| 11780 |
} |
| 11781 |
if (fstfrac_vcol) { |
| 11782 |
*cswritep++ = '\t'; |
| 11783 |
cswritep = dtoa_g(fst_numer, cswritep); |
| 11784 |
*cswritep++ = '\t'; |
| 11785 |
cswritep = dtoa_g(fst_denom, cswritep); |
| 11786 |
} |
| 11787 |
if (fst_vcol) { |
| 11788 |
*cswritep++ = '\t'; |
| 11789 |
cswritep = dtoa_g(fst_numer / fst_denom, cswritep); |
| 11790 |
} |
| 11791 |
AppendBinaryEoln(&cswritep); |
| 11792 |
if (unlikely(Cswrite(cssp, &cswritep))) { |
| 11793 |
goto FstReport_ret_WRITE_FAIL; |
| 11794 |
} |
| 11795 |
v_cswritep_arr[pop_pair_bidx] = cswritep; |
| 11796 |
} |
| 11797 |
if (pop_nm_sample_cts_iter) { |
| 11798 |
pop_nm_sample_cts_iter = &(pop_nm_sample_cts_iter[pop_ct]); |
| 11799 |
} |
| 11800 |
pop_allele_obs_cts_iter = &(pop_allele_obs_cts_iter[pop_ct * allele_ct]); |
| 11801 |
if (half_within_iter) { |
| 11802 |
half_within_iter = &(half_within_iter[pop_ct]); |
| 11803 |
} else { |
| 11804 |
pop_allele_het_cts_iter = &(pop_allele_het_cts_iter[pop_ct * allele_ct]); |
| 11805 |
} |
| 11806 |
} |
| 11807 |
} |
| 11808 |
if (variant_idx == cur_variant_ct) { |
| 11809 |
break; |
| 11810 |
} |
| 11811 |
if (variant_idx >= next_print_variant_idx) { |
| 11812 |
if (pct > 10) { |
| 11813 |
putc_unlocked('\b', stdout); |
| 11814 |
} |
| 11815 |
pct = (variant_idx * 100LLU) / cur_variant_ct; |
| 11816 |
printf("\b\b%u%%", pct++); |
| 11817 |
fflush(stdout); |
| 11818 |
next_print_variant_idx = (pct * S_CAST(uint64_t, cur_variant_ct)) / 100; |
| 11819 |
} |
| 11820 |
++read_block_idx; |
| 11821 |
prev_block_variant_ct = cur_block_variant_ct; |
| 11822 |
variant_idx += cur_block_variant_ct; |
| 11823 |
pgfip->block_base = main_loadbufs[parity]; |
| 11824 |
} |
| 11825 |
for (uintptr_t pop_pair_bidx = 0; pop_pair_bidx != pop_pair_batch_size; ++pop_pair_bidx) { |
| 11826 |
const uint32_t pop_idx1 = cur_pop_pairs[2 * pop_pair_bidx]; |
| 11827 |
const uint32_t pop_idx2 = cur_pop_pairs[2 * pop_pair_bidx + 1]; |
| 11828 |
const uint32_t nobs = fst_nobs[pop_pair_bidx]; |
| 11829 |
double fst_numer_sum = fst_numer_sums[pop_pair_bidx]; |
| 11830 |
double fst_denom_sum = fst_denom_sums[pop_pair_bidx]; |
| 11831 |
double fst_se = 0.0; |
| 11832 |
if (jackknife_fst_numers) { |
| 11833 |
double* block_fst_numers = &(jackknife_fst_numers[pop_pair_bidx * jackknife_block_max]); |
| 11834 |
double* block_fst_denoms = &(jackknife_fst_denoms[pop_pair_bidx * jackknife_block_max]); |
| 11835 |
if (nobs > jackknife_blocksize) { |
| 11836 |
const uint32_t n_block = DivUp(nobs, jackknife_blocksize); |
| 11837 |
uint32_t prev_block_ct = n_block; |
| 11838 |
uint32_t last_block_size = jackknife_blocksize; |
| 11839 |
if (nobs != n_block * jackknife_blocksize) { |
| 11840 |
--prev_block_ct; |
| 11841 |
block_fst_numers[prev_block_ct] = fst_numer_sum; |
| 11842 |
block_fst_denoms[prev_block_ct] = fst_denom_sum; |
| 11843 |
last_block_size = nobs - (prev_block_ct * jackknife_blocksize); |
| 11844 |
} |
| 11845 |
for (uint32_t block_idx = 0; block_idx != prev_block_ct; ++block_idx) { |
| 11846 |
fst_numer_sum += block_fst_numers[block_idx]; |
| 11847 |
fst_denom_sum += block_fst_denoms[block_idx]; |
| 11848 |
} |
| 11849 |
const double nobs_d = u31tod(nobs); |
| 11850 |
const double nobs_recip = 1.0 / nobs_d; |
| 11851 |
// https://reich.hms.harvard.edu/sites/reich.hms.harvard.edu/files/inline-files/wjack.pdf |
| 11852 |
const double theta_hat = fst_numer_sum / fst_denom_sum; |
| 11853 |
// first pass: compute theta_jack |
| 11854 |
double theta_jack = 0.0; |
| 11855 |
double cur_block_size_d = u31tod(jackknife_blocksize); |
| 11856 |
for (uint32_t block_idx = 0; ; ++block_idx) { |
| 11857 |
if (block_idx >= prev_block_ct) { |
| 11858 |
if (block_idx > prev_block_ct) { |
| 11859 |
break; |
| 11860 |
} |
| 11861 |
cur_block_size_d = u31tod(last_block_size); |
| 11862 |
} |
| 11863 |
// we can avoid computing some of these values twice, but this |
| 11864 |
// isn't a bottleneck |
| 11865 |
const double theta_with_j_removed = (fst_numer_sum - block_fst_numers[block_idx]) / (fst_denom_sum - block_fst_denoms[block_idx]); |
| 11866 |
theta_jack += (theta_hat - theta_with_j_removed) + cur_block_size_d * theta_with_j_removed * nobs_recip; |
| 11867 |
} |
| 11868 |
// second pass: compute variance estimate |
| 11869 |
double main_sum = 0.0; |
| 11870 |
double hh = nobs_d / u31tod(jackknife_blocksize); |
| 11871 |
for (uint32_t block_idx = 0; ; ++block_idx) { |
| 11872 |
if (block_idx >= prev_block_ct) { |
| 11873 |
if (block_idx > prev_block_ct) { |
| 11874 |
break; |
| 11875 |
} |
| 11876 |
hh = nobs_d / u31tod(last_block_size); |
| 11877 |
} |
| 11878 |
const double h_minus_1 = hh - 1.0; |
| 11879 |
const double theta_with_j_removed = (fst_numer_sum - block_fst_numers[block_idx]) / (fst_denom_sum - block_fst_denoms[block_idx]); |
| 11880 |
const double tau_j = hh * theta_hat - h_minus_1 * theta_with_j_removed; |
| 11881 |
const double tau_j_minus_theta_jack = tau_j - theta_jack; |
| 11882 |
main_sum += tau_j_minus_theta_jack * tau_j_minus_theta_jack / h_minus_1; |
| 11883 |
} |
| 11884 |
const double variance_estimate = main_sum / u31tod(n_block); |
| 11885 |
fst_se = sqrt(variance_estimate); |
| 11886 |
} else { |
| 11887 |
if (nobs == jackknife_blocksize) { |
| 11888 |
fst_numer_sum += block_fst_numers[0]; |
| 11889 |
fst_denom_sum += block_fst_denoms[0]; |
| 11890 |
} |
| 11891 |
fst_se = 0.0 / 0.0; |
| 11892 |
} |
| 11893 |
} |
| 11894 |
s_write_iter = strcpyax(s_write_iter, pop_names[pop_idx1], '\t'); |
| 11895 |
s_write_iter = strcpyax(s_write_iter, pop_names[pop_idx2], '\t'); |
| 11896 |
if (nobs_scol) { |
| 11897 |
s_write_iter = u32toa_x(nobs, '\t', s_write_iter); |
| 11898 |
} |
| 11899 |
s_write_iter = dtoa_g(fst_numer_sum / fst_denom_sum, s_write_iter); |
| 11900 |
if (jackknife_blocksize) { |
| 11901 |
*s_write_iter++ = '\t'; |
| 11902 |
s_write_iter = dtoa_g(fst_se, s_write_iter); |
| 11903 |
} |
| 11904 |
AppendBinaryEoln(&s_write_iter); |
| 11905 |
if (unlikely(fwrite_ck(s_textbuf_flush, s_outfile, &s_write_iter))) { |
| 11906 |
goto FstReport_ret_WRITE_FAIL; |
| 11907 |
} |
| 11908 |
} |
| 11909 |
if (report_variants) { |
| 11910 |
for (uintptr_t fidx = 0; fidx != pop_pair_batch_size; ++fidx) { |
| 11911 |
if (unlikely(CswriteCloseNull(&(v_css_arr[fidx]), v_cswritep_arr[fidx]))) { |
| 11912 |
goto FstReport_ret_WRITE_FAIL; |
| 11913 |
} |
| 11914 |
} |
| 11915 |
} |
| 11916 |
if (pct > 10) { |
| 11917 |
putc_unlocked('\b', stdout); |
| 11918 |
} |
| 11919 |
fputs("\b\b", stdout); |
| 11920 |
logputs("done.\n"); |
| 11921 |
BigstackReset(bigstack_mark3); |
| 11922 |
} |
| 11923 |
if (report_variants) { |
| 11924 |
logprintf("%s --fst: %u .fst.var%s file%s written.\n", is_x? "chrX" : "Autosomal", pop_pair_ct, v_output_zst? ".zst" : "", (pop_pair_ct == 1)? "" : "s"); |
| 11925 |
strcpy_k(outname_end2, ".fst.summary"); |
| 11926 |
} |
| 11927 |
if (unlikely(fclose_flush_null(s_textbuf_flush, s_write_iter, &s_outfile))) { |
| 11928 |
goto FstReport_ret_WRITE_FAIL; |
| 11929 |
} |
| 11930 |
logprintfww("%s --fst: Summary written to %s .\n", is_x? "chrX" : "Autosomal", outname); |
| 11931 |
BigstackReset(bigstack_mark2); |
| 11932 |
} |
| 11933 |
} |
| 11934 |
while (0) { |
| 11935 |
FstReport_ret_NOMEM: |
| 11936 |
reterr = kPglRetNomem; |
| 11937 |
break; |
| 11938 |
FstReport_ret_PGR_FAIL: |
| 11939 |
PgenErrPrintN(reterr); |
| 11940 |
break; |
| 11941 |
FstReport_ret_OPEN_FAIL: |
| 11942 |
reterr = kPglRetOpenFail; |
| 11943 |
break; |
| 11944 |
FstReport_ret_WRITE_FAIL: |
| 11945 |
reterr = kPglRetWriteFail; |
| 11946 |
break; |
| 11947 |
FstReport_ret_INVALID_CMDLINE: |
| 11948 |
reterr = kPglRetInvalidCmdline; |
| 11949 |
break; |
| 11950 |
FstReport_ret_TSTREAM_FAIL: |
| 11951 |
TextStreamErrPrint("--fst file", &txs); |
| 11952 |
break; |
| 11953 |
FstReport_ret_MALFORMED_INPUT: |
| 11954 |
reterr = kPglRetMalformedInput; |
| 11955 |
break; |
| 11956 |
FstReport_ret_PHENO_NOT_FOUND: |
| 11957 |
logerrprintfww("Error: --fst phenotype '%s' not loaded.\n", fst_infop->pheno_name); |
| 11958 |
FstReport_ret_INCONSISTENT_INPUT: |
| 11959 |
reterr = kPglRetInconsistentInput; |
| 11960 |
break; |
| 11961 |
FstReport_ret_THREAD_CREATE_FAIL: |
| 11962 |
reterr = kPglRetThreadCreateFail; |
| 11963 |
break; |
| 11964 |
} |
| 11965 |
FstReport_ret_1: |
| 11966 |
if (v_css_arr) { |
| 11967 |
for (uintptr_t fidx = 0; fidx != max_variant_file_ct; ++fidx) { |
| 11968 |
CswriteCloseCond(&(v_css_arr[fidx]), v_cswritep_arr[fidx]); |
| 11969 |
} |
| 11970 |
} |
| 11971 |
CleanupThreads(&tg); |
| 11972 |
fclose_cond(s_outfile); |
| 11973 |
CleanupTextStream2("--fst file", &txs, &reterr); |
| 11974 |
BigstackDoubleReset(bigstack_mark, bigstack_end_mark); |
| 11975 |
pgfip->block_base = nullptr; |
| 11976 |
return reterr; |
| 11977 |
} |
| 11978 |
|
| 11979 |
typedef struct AlleleUniquenessCheckerStruct { |
| 11980 |
const uintptr_t* variant_include; |
| 11981 |
const uintptr_t* allele_idx_offsets; |
| 11982 |
const char* const* allele_storage; |
| 11983 |
|
| 11984 |
uint32_t* variant_uidx_starts; |
| 11985 |
const char*** allele_sortbufs; |
| 11986 |
|
| 11987 |
uint32_t variant_ct; |
| 11988 |
|
| 11989 |
uint32_t dup_vidx; // UINT32_MAX if no variant found with duplicate alleles |
| 11990 |
} AlleleUniquenessChecker; |
| 11991 |
|
| 11992 |
void CheckAlleleUniquenessMain(uint32_t tidx, uint32_t thread_ct, AlleleUniquenessChecker* ctx) { |
| 11993 |
const uintptr_t* variant_include = ctx->variant_include; |
| 11994 |
const uintptr_t* allele_idx_offsets = ctx->allele_idx_offsets; |
| 11995 |
const char* const* allele_storage = ctx->allele_storage; |
| 11996 |
const char** allele_sortbuf = ctx->allele_sortbufs? ctx->allele_sortbufs[tidx] : nullptr; |
| 11997 |
const uint32_t variant_ct = ctx->variant_ct; |
| 11998 |
const uint32_t variant_uidx_start = ctx->variant_uidx_starts[tidx]; |
| 11999 |
const uint32_t variant_idx_start = (variant_ct * S_CAST(uint64_t, tidx)) / thread_ct; |
| 12000 |
const uint32_t variant_idx_end = (variant_ct * (S_CAST(uint64_t, tidx) + 1)) / thread_ct; |
| 12001 |
uint32_t cur_allele_ct = 2; |
| 12002 |
uintptr_t variant_uidx_base; |
| 12003 |
uintptr_t cur_bits; |
| 12004 |
BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits); |
| 12005 |
for (uint32_t variant_idx = variant_idx_start; variant_idx != variant_idx_end; ++variant_idx) { |
| 12006 |
const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits); |
| 12007 |
uintptr_t allele_idx_offset_base = 2 * variant_uidx; |
| 12008 |
if (allele_idx_offsets) { |
| 12009 |
allele_idx_offset_base = allele_idx_offsets[variant_uidx]; |
| 12010 |
cur_allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offset_base; |
| 12011 |
} |
| 12012 |
const char* const* cur_alleles = &(allele_storage[allele_idx_offset_base]); |
| 12013 |
if (cur_allele_ct == 2) { |
| 12014 |
if (unlikely(strequal_overread(cur_alleles[0], cur_alleles[1]))) { |
| 12015 |
UpdateU32IfSmaller(variant_uidx, &(ctx->dup_vidx)); |
| 12016 |
return; |
| 12017 |
} |
| 12018 |
} else { |
| 12019 |
memcpy(allele_sortbuf, cur_alleles, cur_allele_ct * sizeof(intptr_t)); |
| 12020 |
StrptrArrSortOverread(cur_allele_ct, allele_sortbuf); |
| 12021 |
const char* prev_allele = allele_sortbuf[0]; |
| 12022 |
for (uint32_t aidx = 1; aidx != cur_allele_ct; ++aidx) { |
| 12023 |
const char* cur_allele = allele_sortbuf[aidx]; |
| 12024 |
if (unlikely(strequal_overread(prev_allele, cur_allele))) { |
| 12025 |
UpdateU32IfSmaller(variant_uidx, &(ctx->dup_vidx)); |
| 12026 |
return; |
| 12027 |
} |
| 12028 |
cur_allele = prev_allele; |
| 12029 |
} |
| 12030 |
} |
| 12031 |
} |
| 12032 |
} |
| 12033 |
|
| 12034 |
THREAD_FUNC_DECL CheckAlleleUniquenessThread(void* raw_arg) { |
| 12035 |
ThreadGroupFuncArg* arg = S_CAST(ThreadGroupFuncArg*, raw_arg); |
| 12036 |
const uint32_t tidx = arg->tidx; |
| 12037 |
const uint32_t thread_ct = GetThreadCt(arg->sharedp) + 1; |
| 12038 |
AlleleUniquenessChecker* ctx = S_CAST(AlleleUniquenessChecker*, arg->sharedp->context); |
| 12039 |
CheckAlleleUniquenessMain(tidx, thread_ct, ctx); |
| 12040 |
THREAD_RETURN; |
| 12041 |
} |
| 12042 |
|
| 12043 |
PglErr CheckAlleleUniqueness(const uintptr_t* variant_include, const ChrInfo* cip, const ChrIdx* chr_idxs, const uint32_t* variant_bps, const char* const* variant_ids, const uintptr_t* allele_idx_offsets, const char* const* allele_storage, uint32_t variant_ct, uint32_t max_allele_ct, uint32_t max_thread_ct) { |
| 12044 |
unsigned char* bigstack_mark = g_bigstack_base; |
| 12045 |
PglErr reterr = kPglRetSuccess; |
| 12046 |
ThreadGroup tg; |
| 12047 |
PreinitThreads(&tg); |
| 12048 |
AlleleUniquenessChecker ctx; |
| 12049 |
{ |
| 12050 |
const uint32_t thread_ct = ClipU32(variant_ct / 65536, 1, max_thread_ct); |
| 12051 |
if (unlikely(SetThreadCt0(thread_ct - 1, &tg) || |
| 12052 |
bigstack_alloc_u32(thread_ct, &ctx.variant_uidx_starts))) { |
| 12053 |
goto CheckAlleleUniqueness_ret_NOMEM; |
| 12054 |
} |
| 12055 |
if (max_allele_ct == 2) { |
| 12056 |
ctx.allele_sortbufs = nullptr; |
| 12057 |
} else { |
| 12058 |
if (unlikely(bigstack_alloc_kcpp(thread_ct, &ctx.allele_sortbufs))) { |
| 12059 |
goto CheckAlleleUniqueness_ret_NOMEM; |
| 12060 |
} |
| 12061 |
for (uint32_t tidx = 0; tidx != thread_ct; ++tidx) { |
| 12062 |
if (unlikely(bigstack_alloc_kcp(max_allele_ct, &(ctx.allele_sortbufs[tidx])))) { |
| 12063 |
goto CheckAlleleUniqueness_ret_NOMEM; |
| 12064 |
} |
| 12065 |
} |
| 12066 |
} |
| 12067 |
ctx.variant_include = variant_include; |
| 12068 |
ctx.allele_idx_offsets = allele_idx_offsets; |
| 12069 |
ctx.allele_storage = allele_storage; |
| 12070 |
ctx.variant_ct = variant_ct; |
| 12071 |
ctx.dup_vidx = UINT32_MAX; |
| 12072 |
FillU32SubsetStarts(variant_include, thread_ct, 0, variant_ct, ctx.variant_uidx_starts); |
| 12073 |
|
| 12074 |
if (thread_ct > 1) { |
| 12075 |
SetThreadFuncAndData(CheckAlleleUniquenessThread, &ctx, &tg); |
| 12076 |
DeclareLastThreadBlock(&tg); |
| 12077 |
if (unlikely(SpawnThreads(&tg))) { |
| 12078 |
goto CheckAlleleUniqueness_ret_THREAD_CREATE_FAIL; |
| 12079 |
} |
| 12080 |
} |
| 12081 |
CheckAlleleUniquenessMain(thread_ct - 1, thread_ct, &ctx); |
| 12082 |
JoinThreads0(&tg); |
| 12083 |
const uint32_t dup_vidx = ctx.dup_vidx; |
| 12084 |
if (unlikely(dup_vidx != UINT32_MAX)) { |
| 12085 |
// Not a big deal, but best to make this still work when split |
| 12086 |
// chromosomes are present. |
| 12087 |
const uint32_t chr_idx = chr_idxs? chr_idxs[dup_vidx] : GetVariantChr(cip, dup_vidx); |
| 12088 |
char* write_iter = strcpya_k(g_logbuf, "Error: Duplicate allele code in variant '"); |
| 12089 |
write_iter = strcpya(write_iter, variant_ids[dup_vidx]); |
| 12090 |
write_iter = strcpya_k(write_iter, "' at position "); |
| 12091 |
write_iter = chrtoa(cip, chr_idx, write_iter); |
| 12092 |
*write_iter++ = ':'; |
| 12093 |
write_iter = u32toa(variant_bps[dup_vidx], write_iter); |
| 12094 |
strcpy_k(write_iter, ".\n"); |
| 12095 |
WordWrapB(0); |
| 12096 |
logerrputsb(); |
| 12097 |
reterr = kPglRetInconsistentInput; |
| 12098 |
} |
| 12099 |
} |
| 12100 |
while (0) { |
| 12101 |
CheckAlleleUniqueness_ret_NOMEM: |
| 12102 |
reterr = kPglRetNomem; |
| 12103 |
break; |
| 12104 |
CheckAlleleUniqueness_ret_THREAD_CREATE_FAIL: |
| 12105 |
reterr = kPglRetThreadCreateFail; |
| 12106 |
break; |
| 12107 |
} |
| 12108 |
CleanupThreads(&tg); |
| 12109 |
BigstackReset(bigstack_mark); |
| 12110 |
return reterr; |
| 12111 |
} |
| 12112 |
|
| 12113 |
#ifdef __cplusplus |
| 12114 |
} // namespace plink2 |
| 12115 |
#endif |